var e,t,n={"?2ce3": /*!**********************************!*\ !*** onnxruntime-node (ignored) ***! \**********************************/()=>{},"?7a2c": /*!********************!*\ !*** fs (ignored) ***! \********************/()=>{},"?a42a": /*!**********************!*\ !*** path (ignored) ***! \**********************/()=>{},"?2b25": /*!***********************!*\ !*** sharp (ignored) ***! \***********************/()=>{},"?569f": /*!********************!*\ !*** fs (ignored) ***! \********************/()=>{},"?3f59": /*!**********************!*\ !*** path (ignored) ***! \**********************/()=>{},"?154a": /*!*********************!*\ !*** url (ignored) ***! \*********************/()=>{},"./node_modules/@huggingface/jinja/dist/index.js": /*!*******************************************************!*\ !*** ./node_modules/@huggingface/jinja/dist/index.js ***! \*******************************************************/(e,t,n)=>{n.r(t),n.d(t,{Environment:()=>H,Interpreter:()=>K,Template:()=>X,parse:()=>O,tokenize:()=>d});var r=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),a=Object.freeze({set:r.Set,for:r.For,in:r.In,is:r.Is,if:r.If,else:r.Else,endif:r.EndIf,elif:r.ElseIf,endfor:r.EndFor,and:r.And,or:r.Or,not:r.Not,"not in":r.NotIn,true:r.BooleanLiteral,false:r.BooleanLiteral}),i=class{constructor(e,t){this.value=e,this.type=t}};function s(e){return/\w/.test(e)}function o(e){return/[0-9]/.test(e)}var l=[["{%",r.OpenStatement],["%}",r.CloseStatement],["{{",r.OpenExpression],["}}",r.CloseExpression],["(",r.OpenParen],[")",r.CloseParen],["{",r.OpenCurlyBracket],["}",r.CloseCurlyBracket],["[",r.OpenSquareBracket],["]",r.CloseSquareBracket],[",",r.Comma],[".",r.Dot],[":",r.Colon],["|",r.Pipe],["<=",r.ComparisonBinaryOperator],[">=",r.ComparisonBinaryOperator],["==",r.ComparisonBinaryOperator],["!=",r.ComparisonBinaryOperator],["<",r.ComparisonBinaryOperator],[">",r.ComparisonBinaryOperator],["+",r.AdditiveBinaryOperator],["-",r.AdditiveBinaryOperator],["*",r.MultiplicativeBinaryOperator],["/",r.MultiplicativeBinaryOperator],["%",r.MultiplicativeBinaryOperator],["=",r.Equals]],u=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function d(e,t={}){const n=[],d=function(e,t={}){return e.endsWith("\n")&&(e=e.slice(0,-1)),e=e.replace(/{#.*?#}/gs,"{##}"),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%]})\n/g,"$1")),e.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(e,t);let c=0;const p=e=>{let t="";for(;e(d[c]);)if("\\"!==d[c]){if(t+=d[c++],c>=d.length)throw new SyntaxError("Unexpected end of input")}else{if(++c,c>=d.length)throw new SyntaxError("Unexpected end of input");const e=d[c++],n=u.get(e);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${e}`);t+=n}return t};e:for(;c0){n.push(new i(e,r.Text));continue}}p((e=>/\s/.test(e)));const t=d[c];if("-"===t||"+"===t){const e=n.at(-1)?.type;if(e===r.Text||void 0===e)throw new SyntaxError(`Unexpected character: ${t}`);switch(e){case r.Identifier:case r.NumericLiteral:case r.BooleanLiteral:case r.StringLiteral:case r.CloseParen:case r.CloseSquareBracket:break;default:{++c;const e=p(o);n.push(new i(`${t}${e}`,e.length>0?r.NumericLiteral:r.UnaryOperator));continue}}}for(const[e,t]of l){if(d.slice(c,c+e.length)===e){n.push(new i(e,t)),c+=e.length;continue e}}if("'"!==t&&'"'!==t)if(o(t)){const e=p(o);n.push(new i(e,r.NumericLiteral))}else{if(!s(t))throw new SyntaxError(`Unexpected character: ${t}`);{const e=p(s),t=Object.hasOwn(a,e)?a[e]:r.Identifier;t===r.In&&n.at(-1)?.type===r.Not?(n.pop(),n.push(new i("not in",r.NotIn))):n.push(new i(e,t))}}else{++c;const e=p((e=>e!==t));n.push(new i(e,r.StringLiteral)),++c}}return n}var c=class{type="Statement"},p=class extends c{constructor(e){super(),this.body=e}type="Program"},h=class extends c{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type="If"},f=class extends c{constructor(e,t,n){super(),this.loopvar=e,this.iterable=t,this.body=n}type="For"},m=class extends c{constructor(e,t){super(),this.assignee=e,this.value=t}type="Set"},g=class extends c{type="Expression"},_=class extends g{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type="MemberExpression"},w=class extends g{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},y=class extends g{constructor(e){super(),this.value=e}type="Identifier"},b=class extends g{constructor(e){super(),this.value=e}type="Literal"},v=class extends b{type="NumericLiteral"},$=class extends b{type="StringLiteral"},x=class extends b{type="BooleanLiteral"},T=class extends b{type="ArrayLiteral"},S=class extends b{type="TupleLiteral"},M=class extends b{type="ObjectLiteral"},k=class extends g{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type="BinaryExpression"},C=class extends g{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},E=class extends g{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type="TestExpression"},A=class extends g{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},I=class extends g{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type="SliceExpression"},P=class extends g{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"};function O(e){const t=new p([]);let n=0;function a(t,r){const a=e[n++];if(!a||a.type!==t)throw new Error(`Parser Error: ${r}. ${a.type} !== ${t}.`);return a}function i(){switch(e[n].type){case r.Text:return new $(a(r.Text,"Expected text token").value);case r.OpenStatement:return function(){let t;switch(a(r.OpenStatement,"Expected opening statement token"),e[n].type){case r.Set:++n,t=l(),a(r.CloseStatement,"Expected closing statement token");break;case r.If:++n,t=u(),a(r.OpenStatement,"Expected {% token"),a(r.EndIf,"Expected endif token"),a(r.CloseStatement,"Expected %} token");break;case r.For:++n,t=function(){const e=d(!0);if(!(e instanceof y||e instanceof S))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);a(r.In,"Expected `in` keyword following loop variable");const t=c();a(r.CloseStatement,"Expected closing statement token");const n=[];for(;s(r.OpenStatement,r.EndFor);)n.push(i());return new f(e,t,n)}(),a(r.OpenStatement,"Expected {% token"),a(r.EndFor,"Expected endfor token"),a(r.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[n].type}`)}return t}();case r.OpenExpression:return function(){a(r.OpenExpression,"Expected opening expression token");const e=c();return a(r.CloseExpression,"Expected closing expression token"),e}();default:throw new SyntaxError(`Unexpected token type: ${e[n].type}`)}}function s(...t){return n+t.length<=e.length&&t.some(((t,r)=>t!==e[n+r].type))}function o(...t){return n+t.length<=e.length&&t.every(((t,r)=>t===e[n+r].type))}function l(){const e=c();if(o(r.Equals)){++n;const t=l();return new m(e,t)}return e}function u(){const t=c();a(r.CloseStatement,"Expected closing statement token");const s=[],l=[];for(;e[n]?.type!==r.OpenStatement||e[n+1]?.type!==r.ElseIf&&e[n+1]?.type!==r.Else&&e[n+1]?.type!==r.EndIf;)s.push(i());if(e[n]?.type===r.OpenStatement&&e[n+1]?.type!==r.EndIf)if(++n,o(r.ElseIf))a(r.ElseIf,"Expected elseif token"),l.push(u());else for(a(r.Else,"Expected else token"),a(r.CloseStatement,"Expected closing statement token");e[n]?.type!==r.OpenStatement||e[n+1]?.type!==r.EndIf;)l.push(i());return new h(t,s,l)}function d(e=!1){const t=e?N:c,a=[t()],i=o(r.Comma);for(;i&&(++n,a.push(t()),o(r.Comma)););return i?new S(a):a[0]}function c(){return function(){const e=g();if(o(r.If)){++n;const t=g();a(r.Else,"Expected else token");const i=g();return new h(t,[e],[i])}return e}()}function g(){let t=b();for(;o(r.Or);){const r=e[n];++n;const a=b();t=new k(r,t,a)}return t}function b(){let t=O();for(;o(r.And);){const r=e[n];++n;const a=O();t=new k(r,t,a)}return t}function O(){let t;for(;o(r.Not);){const r=e[n];++n;const a=O();t=new A(r,a)}return t??function(){let t=z();for(;o(r.ComparisonBinaryOperator)||o(r.In)||o(r.NotIn);){const r=e[n];++n;const a=z();t=new k(r,t,a)}return t}()}function z(){let t=D();for(;o(r.AdditiveBinaryOperator);){const r=e[n];++n;const a=D();t=new k(r,t,a)}return t}function B(){const t=function(){let t=N();for(;o(r.Dot)||o(r.OpenSquareBracket);){const i=e[n];let s;++n;const o=i.type!==r.Dot;if(o)s=R(),a(r.CloseSquareBracket,"Expected closing square bracket");else if(s=N(),"Identifier"!==s.type)throw new SyntaxError("Expected identifier following dot operator");t=new _(t,s,o)}return t}();return o(r.OpenParen)?F(t):t}function F(e){let t=new w(e,function(){a(r.OpenParen,"Expected opening parenthesis for arguments list");const e=function(){const e=[];for(;!o(r.CloseParen);){let t=c();if(o(r.Equals)){if(++n,!(t instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const e=c();t=new P(t,e)}e.push(t),o(r.Comma)&&++n}return e}();return a(r.CloseParen,"Expected closing parenthesis for arguments list"),e}());return o(r.OpenParen)&&(t=F(t)),t}function R(){const e=[];let t=!1;for(;!o(r.CloseSquareBracket);)o(r.Colon)?(e.push(void 0),++n,t=!0):(e.push(c()),o(r.Colon)&&(++n,t=!0));if(0===e.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(t){if(e.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new I(...e)}return e[0]}function D(){let t=L();for(;o(r.MultiplicativeBinaryOperator);){const r=e[n];++n;const a=L();t=new k(r,t,a)}return t}function L(){let e=function(){let e=B();for(;o(r.Pipe);){++n;let t=N();if(!(t instanceof y))throw new SyntaxError("Expected identifier for the filter");o(r.OpenParen)&&(t=F(t)),e=new C(e,t)}return e}();for(;o(r.Is);){++n;const t=o(r.Not);t&&++n;let a=N();if(a instanceof x&&(a=new y(a.value.toString())),!(a instanceof y))throw new SyntaxError("Expected identifier for the test");e=new E(e,t,a)}return e}function N(){const t=e[n];switch(t.type){case r.NumericLiteral:return++n,new v(Number(t.value));case r.StringLiteral:return++n,new $(t.value);case r.BooleanLiteral:return++n,new x("true"===t.value);case r.Identifier:return++n,new y(t.value);case r.OpenParen:{++n;const t=d();if(e[n].type!==r.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[n].type} instead`);return++n,t}case r.OpenSquareBracket:{++n;const e=[];for(;!o(r.CloseSquareBracket);)e.push(c()),o(r.Comma)&&++n;return++n,new T(e)}case r.OpenCurlyBracket:{++n;const e=new Map;for(;!o(r.CloseCurlyBracket);){const t=c();a(r.Colon,"Expected colon between key and value in object literal");const i=c();e.set(t,i),o(r.Comma)&&++n}return++n,new M(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}for(;n=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));const i=[];for(let s=t;a*se.toUpperCase()))}var R=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new N(!!this.value)}},D=class extends R{type="NumericValue"},L=class extends R{type="StringValue";builtins=new Map([["upper",new G((()=>new L(this.value.toUpperCase())))],["lower",new G((()=>new L(this.value.toLowerCase())))],["strip",new G((()=>new L(this.value.trim())))],["title",new G((()=>new L(F(this.value))))],["length",new D(this.value.length)]])},N=class extends R{type="BooleanValue"},U=class extends R{type="ObjectValue";__bool__(){return new N(this.value.size>0)}builtins=new Map([["get",new G((([e,t])=>{if(!(e instanceof L))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new j}))],["items",new G((()=>new W(Array.from(this.value.entries()).map((([e,t])=>new W([new L(e),t]))))))]])},W=class extends R{type="ArrayValue";builtins=new Map([["length",new D(this.value.length)]]);__bool__(){return new N(this.value.length>0)}},V=class extends W{type="TupleValue"},G=class extends R{type="FunctionValue"},j=class extends R{type="NullValue"},q=class extends R{type="UndefinedValue"},H=class{constructor(e){this.parent=e}variables=new Map([["namespace",new G((e=>{if(0===e.length)return new U(new Map);if(1!==e.length||!(e[0]instanceof U))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]}))]]);tests=new Map([["boolean",e=>"BooleanValue"===e.type],["callable",e=>e instanceof G],["odd",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "odd" to type: ${e.type}`);return e.value%2!=0}],["even",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "even" to type: ${e.type}`);return e.value%2==0}],["false",e=>"BooleanValue"===e.type&&!e.value],["true",e=>"BooleanValue"===e.type&&e.value],["number",e=>"NumericValue"===e.type],["integer",e=>"NumericValue"===e.type&&Number.isInteger(e.value)],["iterable",e=>e instanceof W||e instanceof L],["lower",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toUpperCase()}],["none",e=>"NullValue"===e.type],["defined",e=>"UndefinedValue"!==e.type],["undefined",e=>"UndefinedValue"===e.type],["equalto",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Y(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new q}catch{return new q}}},K=class{global;constructor(e){this.global=e??new H}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const n=this.evaluate(e.left,t);switch(e.operator.value){case"and":return n.__bool__().value?this.evaluate(e.right,t):n;case"or":return n.__bool__().value?n:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new N(n.value==r.value);case"!=":return new N(n.value!=r.value)}if(n instanceof q||r instanceof q)throw new Error("Cannot perform operation on undefined values");if(n instanceof j||r instanceof j)throw new Error("Cannot perform operation on null values");if(n instanceof D&&r instanceof D)switch(e.operator.value){case"+":return new D(n.value+r.value);case"-":return new D(n.value-r.value);case"*":return new D(n.value*r.value);case"/":return new D(n.value/r.value);case"%":return new D(n.value%r.value);case"<":return new N(n.value":return new N(n.value>r.value);case">=":return new N(n.value>=r.value);case"<=":return new N(n.value<=r.value)}else if(n instanceof W&&r instanceof W){if("+"===e.operator.value)return new W(n.value.concat(r.value))}else if(r instanceof W){const t=void 0!==r.value.find((e=>e.value===n.value));switch(e.operator.value){case"in":return new N(t);case"not in":return new N(!t)}}if((n instanceof L||r instanceof L)&&"+"===e.operator.value)return new L(n.value.toString()+r.value.toString());if(n instanceof L&&r instanceof L)switch(e.operator.value){case"in":return new N(r.value.includes(n.value));case"not in":return new N(!r.value.includes(n.value))}if(n instanceof L&&r instanceof U)switch(e.operator.value){case"in":return new N(r.value.has(n.value));case"not in":return new N(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateFilterExpression(e,t){const n=this.evaluate(e.operand,t);if("Identifier"===e.filter.type){const t=e.filter;if(n instanceof W)switch(t.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new D(n.value.length);case"reverse":return new W(n.value.reverse());case"sort":return new W(n.value.sort(((e,t)=>{if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"NumericValue":return e.value-t.value;case"StringValue":return e.value.localeCompare(t.value);default:throw new Error(`Cannot compare type: ${e.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${t.value}`)}else if(n instanceof L)switch(t.value){case"length":return new D(n.value.length);case"upper":return new L(n.value.toUpperCase());case"lower":return new L(n.value.toLowerCase());case"title":return new L(F(n.value));case"capitalize":return new L(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new L(n.value.trim());default:throw new Error(`Unknown StringValue filter: ${t.value}`)}else{if(n instanceof D){if("abs"===t.value)return new D(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${t.value}`)}if(n instanceof U)switch(t.value){case"items":return new W(Array.from(n.value.entries()).map((([e,t])=>new W([new L(e),t]))));case"length":return new D(n.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${n.type}`)}if("CallExpression"===e.filter.type){const r=e.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const a=r.callee.value;if(n instanceof W){if("selectattr"===a){if(n.value.some((e=>!(e instanceof U))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((e=>"StringLiteral"!==e.type)))throw new Error("arguments of `selectattr` must be strings");const[e,a,i]=r.args.map((e=>this.evaluate(e,t)));let s;if(a){const e=t.tests.get(a.value);if(!e)throw new Error(`Unknown test: ${a.value}`);s=e}else s=(...e)=>e[0].__bool__().value;const o=n.value.filter((t=>{const n=t.value.get(e.value);return!!n&&s(n,i)}));return new W(o)}throw new Error(`Unknown ArrayValue filter: ${a}`)}throw new Error(`Cannot apply filter "${a}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw new Error(`Unknown test: ${e.test.value}`);const a=r(n);return new N(e.negate?!a:a)}evaluateUnaryExpression(e,t){const n=this.evaluate(e.argument,t);if("not"===e.operator.value)return new N(!n.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n="";for(const r of e){const e=this.evaluate(r,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(n+=e.value)}return new L(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const n=[],r=new Map;for(const a of e.args)if("KeywordArgumentExpression"===a.type){const e=a;r.set(e.key.value,this.evaluate(e.value,t))}else n.push(this.evaluate(a,t));r.size>0&&n.push(new U(r));const a=this.evaluate(e.callee,t);if("FunctionValue"!==a.type)throw new Error(`Cannot call something that is not a function: got ${a.type}`);return a.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof W||e instanceof L))throw new Error("Slice object must be an array or string");const r=this.evaluate(t.start,n),a=this.evaluate(t.stop,n),i=this.evaluate(t.step,n);if(!(r instanceof D||r instanceof q))throw new Error("Slice start must be numeric or undefined");if(!(a instanceof D||a instanceof q))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof D||i instanceof q))throw new Error("Slice step must be numeric or undefined");return e instanceof W?new W(B(e.value,r.value,a.value,i.value)):new L(B(Array.from(e.value),r.value,a.value,i.value).join(""))}evaluateMemberExpression(e,t){const n=this.evaluate(e.object,t);let r,a;if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new L(e.property.value);if(n instanceof U){if(!(r instanceof L))throw new Error(`Cannot access property with non-string: got ${r.type}`);a=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof W||n instanceof L)if(r instanceof D)a=n.value.at(r.value),n instanceof L&&(a=new L(n.value.at(r.value)));else{if(!(r instanceof L))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);a=n.builtins.get(r.value)}else{if(!(r instanceof L))throw new Error(`Cannot access property with non-string: got ${r.type}`);a=n.builtins.get(r.value)}return a instanceof R?a:new q}evaluateSet(e,t){const n=this.evaluate(e.value,t);if("Identifier"===e.assignee.type){const r=e.assignee.value;t.setVariable(r,n)}else{if("MemberExpression"!==e.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);{const r=e.assignee,a=this.evaluate(r.object,t);if(!(a instanceof U))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");a.value.set(r.property.value,n)}}return new j}evaluateIf(e,t){const n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const n=new H(t),r=this.evaluate(e.iterable,n);if(!(r instanceof W))throw new Error(`Expected iterable type in for loop: got ${r.type}`);let a="";for(let t=0;t0?r.value[t-1]:new q],["nextitem",tr.value.length?"few":"many"} items to unpack`);for(let e=0;ethis.evaluate(e,t))));case"TupleLiteral":return new V(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const n=new Map;for(const[r,a]of e.value){const e=this.evaluate(r,t);if(!(e instanceof L))throw new Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(a,t))}return new U(n)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Y(e){switch(typeof e){case"number":return new D(e);case"string":return new L(e);case"boolean":return new N(e);case"object":return null===e?new j:Array.isArray(e)?new W(e.map(Y)):new U(new Map(Object.entries(e).map((([e,t])=>[e,Y(t)]))));case"function":return new G(((t,n)=>Y(e(...t.map((e=>e.value)))??null)));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var X=class{parsed;constructor(e){const t=d(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=O(t)}render(e){const t=new H;t.set("false",!1),t.set("true",!0),t.set("raise_exception",(e=>{throw new Error(e)})),t.set("range",z);for(const[n,r]of Object.entries(e))t.set(n,r);return new K(t).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js": /*!******************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/backend-impl.js ***! \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>i,resolveBackend:()=>s});const r=new Map,a=[],i=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{const i=r.get(e);if(void 0===i)r.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){const t=a.indexOf(e);-1!==t&&a.splice(t,1);for(let t=0;t{const t=0===e.length?a:e,n=[];for(const e of t){const t=r.get(e);if(t){if(t.initialized)return t.backend;if(t.aborted)continue;const r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(a){r||n.push({name:e,err:a}),t.aborted=!0}finally{delete t.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`)}},"./node_modules/onnxruntime-common/dist/esm/backend.js": /*!*************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/backend.js ***! \*************************************************************/(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>r.registerBackend});var r=n(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js": /*!**************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/env-impl.js ***! \**************************************************************/(e,t,n)=>{n.r(t),n.d(t,{env:()=>i});var r=n(/*! ./version.js */"./node_modules/onnxruntime-common/dist/esm/version.js");let a="warning";const i={wasm:{},webgl:{},webgpu:{},versions:{common:r.version},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);a=e}},get logLevel(){return a}};Object.defineProperty(i,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js": /*!*********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/env.js ***! \*********************************************************/(e,t,n)=>{n.r(t),n.d(t,{env:()=>r});const r=n(/*! ./env-impl.js */"./node_modules/onnxruntime-common/dist/esm/env-impl.js").env},"./node_modules/onnxruntime-common/dist/esm/index.js": /*!***********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/index.js ***! \***********************************************************/(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>i.InferenceSession,TRACE:()=>o.TRACE,TRACE_FUNC_BEGIN:()=>o.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>o.TRACE_FUNC_END,Tensor:()=>s.Tensor,TrainingSession:()=>l.TrainingSession,env:()=>a.env,registerBackend:()=>r.registerBackend});var r=n(/*! ./backend.js */"./node_modules/onnxruntime-common/dist/esm/backend.js"),a=n(/*! ./env.js */"./node_modules/onnxruntime-common/dist/esm/env.js"),i=n(/*! ./inference-session.js */"./node_modules/onnxruntime-common/dist/esm/inference-session.js"),s=n(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js"),o=n(/*! ./trace.js */"./node_modules/onnxruntime-common/dist/esm/trace.js"),l=(n(/*! ./onnx-value.js */"./node_modules/onnxruntime-common/dist/esm/onnx-value.js"),n(/*! ./training-session.js */"./node_modules/onnxruntime-common/dist/esm/training-session.js"))},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js": /*!****************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js ***! \****************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>s});var r=n(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=n(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js"),i=n(/*! ./trace.js */"./node_modules/onnxruntime-common/dist/esm/trace.js");class s{constructor(e){this.handler=e}async run(e,t,n){(0,i.TRACE_FUNC_BEGIN)();const r={};let s={};if("object"!=typeof e||null===e||e instanceof a.Tensor||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if("object"==typeof t){if(null===t)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(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(const e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)s=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else{let e=!1;const i=Object.getOwnPropertyNames(t);for(const n of this.outputNames)if(-1!==i.indexOf(n)){const i=t[n];(null===i||i instanceof a.Tensor)&&(e=!0,o=!1,r[n]=i)}if(e){if("object"==typeof n&&null!==n)s=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else s=t}}else if(void 0!==t)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of this.inputNames)if(void 0===e[t])throw new Error(`input '${t}' is missing in 'feeds'.`);if(o)for(const e of this.outputNames)r[e]=null;const l=await this.handler.run(e,r,s),u={};for(const e in l)if(Object.hasOwnProperty.call(l,e)){const t=l[e];t instanceof a.Tensor?u[e]=t:u[e]=new a.Tensor(t.type,t.data,t.dims)}return(0,i.TRACE_FUNC_END)(),u}async release(){return this.handler.dispose()}static async create(e,t,n,a){let o;(0,i.TRACE_FUNC_BEGIN)();let l={};if("string"==typeof e){if(o=e,"object"==typeof t&&null!==t)l=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,"object"==typeof t&&null!==t)l=t;else if(void 0!==t)throw new TypeError("'options' must be an object.")}else{if(!(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{const r=e;let i=0,s=e.byteLength;if("object"==typeof t&&null!==t)l=t;else if("number"==typeof t){if(i=t,!Number.isSafeInteger(i))throw new RangeError("'byteOffset' must be an integer.");if(i<0||i>=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(s=e.byteLength-i,"number"==typeof n){if(s=n,!Number.isSafeInteger(s))throw new RangeError("'byteLength' must be an integer.");if(s<=0||i+s>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-i}].`);if("object"==typeof a&&null!==a)l=a;else if(void 0!==a)throw new TypeError("'options' must be an object.")}else if(void 0!==n)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==t)throw new TypeError("'options' must be an object.");o=new Uint8Array(r,i,s)}}const u=(l.executionProviders||[]).map((e=>"string"==typeof e?e:e.name)),d=await(0,r.resolveBackend)(u),c=await d.createInferenceSessionHandler(o,l);return(0,i.TRACE_FUNC_END)(),new s(c)}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": /*!***********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/inference-session.js ***! \***********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>r});const r=n(/*! ./inference-session-impl.js */"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js").InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js": /*!****************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/onnx-value.js ***! \****************************************************************/(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js": /*!****************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js ***! \****************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{tensorToDataURL:()=>r,tensorToImageData:()=>a});const r=(e,t)=>{const n="undefined"!=typeof document?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];const r=n.getContext("2d");if(null!=r){let a,i;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],i=e.dims[3]):(a=e.dims[3],i=e.dims[2]);const s=void 0!==t?.format?t.format:"RGB",o=t?.norm;let l,u;void 0===o||void 0===o.mean?l=[255,255,255,255]:"number"==typeof o.mean?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],void 0!==o.mean[3]&&(l[3]=o.mean[3])),void 0===o||void 0===o.bias?u=[0,0,0,0]:"number"==typeof o.bias?u=[o.bias,o.bias,o.bias,o.bias]:(u=[o.bias[0],o.bias[1],o.bias[2],0],void 0!==o.bias[3]&&(u[3]=o.bias[3]));const d=i*a;let c=0,p=d,h=2*d,f=-1;"RGBA"===s?(c=0,p=d,h=2*d,f=3*d):"RGB"===s?(c=0,p=d,h=2*d):"RBG"===s&&(c=0,h=d,p=2*d);for(let t=0;t{const n="undefined"!=typeof document?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(null==n)throw new Error("Can not access image data");{let a,i,s;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],i=e.dims[1],s=e.dims[3]):(a=e.dims[3],i=e.dims[2],s=e.dims[1]);const o=void 0!==t&&void 0!==t.format?t.format:"RGB",l=t?.norm;let u,d;void 0===l||void 0===l.mean?u=[255,255,255,255]:"number"==typeof l.mean?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],void 0!==l.mean[3]&&(u[3]=l.mean[3])),void 0===l||void 0===l.bias?d=[0,0,0,0]:"number"==typeof l.bias?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],void 0!==l.bias[3]&&(d[3]=l.bias[3]));const c=i*a;if(void 0!==t&&(void 0!==t.format&&4===s&&"RGBA"!==t.format||3===s&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");const p=4;let h=0,f=1,m=2,g=3,_=0,w=c,y=2*c,b=-1;"RGBA"===o?(_=0,w=c,y=2*c,b=3*c):"RGB"===o?(_=0,w=c,y=2*c):"RBG"===o&&(_=0,y=c,w=2*c),r=n.createImageData(a,i);for(let t=0;t{n.r(t),n.d(t,{bufferToTensor:()=>a,tensorFromGpuBuffer:()=>o,tensorFromImage:()=>i,tensorFromPinnedBuffer:()=>l,tensorFromTexture:()=>s});var r=n(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");const{height:n,width:a}=t,i=t.norm??{mean:255,bias:0};let s,o;s="number"==typeof i.mean?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o="number"==typeof i.bias?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const l=void 0!==t.format?t.format:"RGBA",u=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",d=n*a,c="RGBA"===u?new Float32Array(4*d):new Float32Array(3*d);let p=4,h=0,f=1,m=2,g=3,_=0,w=d,y=2*d,b=-1;"RGB"===l&&(p=3,h=0,f=1,m=2,g=-1),"RGBA"===u?b=3*d:"RBG"===u?(_=0,y=d,w=2*d):"BGR"===u&&(y=0,w=d,_=2*d);for(let t=0;t{const n="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,r="undefined"!=typeof ImageData&&e instanceof ImageData,i="undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap,s="string"==typeof e;let o,l=t??{};const u=()=>{if("undefined"!=typeof document)return document.createElement("canvas");if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=e=>e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(n){const n=u();n.width=e.width,n.height=e.height;const r=d(n);if(null==r)throw new Error("Can not access image data");{let n=e.height,a=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(n=t.resizedHeight,a=t.resizedWidth),void 0!==t){if(l=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");l.tensorFormat="RGBA",l.height=n,l.width=a}else l.tensorFormat="RGBA",l.height=n,l.width=a;r.drawImage(e,0,0),o=r.getImageData(0,0,a,n).data}}else{if(!r){if(i){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");const n=u();n.width=e.width,n.height=e.height;const r=d(n);if(null!=r){const t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,l.height=t,l.width=n,a(o,l)}throw new Error("Can not access image data")}if(s)return new Promise(((t,n)=>{const r=u(),i=d(r);if(!e||!i)return n();const s=new Image;s.crossOrigin="Anonymous",s.src=e,s.onload=()=>{r.width=s.width,r.height=s.height,i.drawImage(s,0,0,r.width,r.height);const e=i.getImageData(0,0,r.width,r.height);l.height=r.height,l.width=r.width,t(a(e.data,l))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let n,r;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),void 0!==t&&(l=t),l.format="RGBA",l.height=n,l.width=r,void 0!==t){const t=u();t.width=r,t.height=n;const a=d(t);if(null==a)throw new Error("Can not access image data");a.putImageData(e,0,0),o=a.getImageData(0,0,r,n).data}else o=e.data}}if(void 0!==o)return a(o,l);throw new Error("Input data provided is not supported - aborted tensor creation")},s=(e,t)=>{const{width:n,height:a,download:i,dispose:s}=t,o=[1,a,n,4];return new r.Tensor({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:s})},o=(e,t)=>{const{dataType:n,dims:a,download:i,dispose:s}=t;return new r.Tensor({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:a,download:i,dispose:s})},l=(e,t,n)=>new r.Tensor({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js": /*!******************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js ***! \******************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>a,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>r,checkBigInt:()=>s});const r=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),a=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let i=!1;const s=()=>{if(!i){i=!0;const e="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,t="undefined"!=typeof BigUint64Array&&"function"==typeof BigUint64Array.from;e&&(r.set("int64",BigInt64Array),a.set(BigInt64Array,"int64")),t&&(r.set("uint64",BigUint64Array),a.set(BigUint64Array,"uint64"))}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js": /*!*****************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl.js ***! \*****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>o});var r=n(/*! ./tensor-conversion-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),a=n(/*! ./tensor-factory-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),i=n(/*! ./tensor-impl-type-mapping.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),s=n(/*! ./tensor-utils-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class o{constructor(e,t,n){let r,a;if((0,i.checkBigInt)(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,r=e.type,a=e.dims,e.location){case"cpu-pinned":{const t=i.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(r);if(!t)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"bool"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,o;if("string"==typeof e)if(r=e,o=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");s=t}else{const n=i.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");s="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else{if(!(t instanceof n))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);s=t}}else if(o=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");const t=typeof e[0];if("string"===t)r="string",s=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",s=Uint8Array.from(e)}}else{const t=i.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,s=e}if(void 0===o)o=[s.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");a=o,this.cpuData=s,this.dataLocation="cpu"}const o=(0,s.calculateSize)(a);if(this.cpuData&&o!==this.cpuData.length)throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=a,this.size=o}static async fromImage(e,t){return(0,a.tensorFromImage)(e,t)}static fromTexture(e,t){return(0,a.tensorFromTexture)(e,t)}static fromGpuBuffer(e,t){return(0,a.tensorFromGpuBuffer)(e,t)}static fromPinnedBuffer(e,t,n){return(0,a.tensorFromPinnedBuffer)(e,t,n)}toDataURL(e){return(0,r.tensorToDataURL)(this,e)}toImageData(e){return(0,r.tensorToImageData)(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if("none"===this.dataLocation)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(0,s.tensorReshape)(this,e)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js": /*!***********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js ***! \***********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{calculateSize:()=>a,tensorReshape:()=>i});var r=n(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new r.Tensor(e.type,e.data,t);case"cpu-pinned":return new r.Tensor({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new r.Tensor({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new r.Tensor({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js": /*!************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor.js ***! \************************************************************/(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>r});const r=n(/*! ./tensor-impl.js */"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js").Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js": /*!***********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/trace.js ***! \***********************************************************/(e,t,n)=>{n.r(t),n.d(t,{TRACE:()=>a,TRACE_FUNC_BEGIN:()=>s,TRACE_FUNC_END:()=>o});var r=n(/*! ./env-impl.js */"./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=(e,t)=>{r.env.wasm.trace&&console.timeStamp(`${e}::ORT::${t}`)},i=(e,t)=>{const n=(new Error).stack?.split(/\r\n|\r|\n/g)||[];let r=!1;for(let i=0;i{r.env.wasm.trace&&i("BEGIN",e)},o=e=>{r.env.wasm.trace&&i("END",e)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js": /*!***************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/training-session-impl.js ***! \***************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>i});var r=n(/*! ./backend-impl.js */"./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=n(/*! ./tensor.js */"./node_modules/onnxruntime-common/dist/esm/tensor.js");class i{constructor(e,t,n){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,t){const n=e.evalModel||"",a=e.optimizerModel||"",s=t||{},o=(s.executionProviders||[]).map((e=>"string"==typeof e?e:e.name)),l=await(0,r.resolveBackend)(o);if(l.createTrainingSessionHandler){const t=await l.createTrainingSessionHandler(e.checkpointState,e.trainModel,n,a,s);return new i(t,!!e.optimizerModel,!!e.evalModel)}throw new Error("Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.")}typeNarrowingForRunStep(e,t,n,r,i){const s={};let o={};if("object"!=typeof n||null===n||n instanceof a.Tensor||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if("object"==typeof r){if(null===r)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(0===r.length)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(const e of r){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===t.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);s[e]=null}if("object"==typeof i&&null!==i)o=i;else if(void 0!==i)throw new TypeError("'options' must be an object.")}else{let e=!1;const n=Object.getOwnPropertyNames(r);for(const i of t)if(-1!==n.indexOf(i)){const t=r[i];(null===t||t instanceof a.Tensor)&&(e=!0,l=!1,s[i]=t)}if(e){if("object"==typeof i&&null!==i)o=i;else if(void 0!==i)throw new TypeError("'options' must be an object.")}else o=r}}else if(void 0!==r)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const t of e)if(void 0===n[t])throw new Error(`input '${t}' is missing in 'feeds'.`);if(l)for(const e of t)s[e]=null;return[s,o]}convertHandlerReturnTypeToMapOfTensors(e){const t={};for(const n in e)if(Object.hasOwnProperty.call(e,n)){const r=e[n];r instanceof a.Tensor?t[n]=r:t[n]=new a.Tensor(r.type,r.data,r.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,n){const[r,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,n),i=await this.handler.runTrainStep(e,r,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}async runOptimizerStep(e){if(!this.hasOptimizerModel)throw new Error("This TrainingSession has no OptimizerModel loaded.");await this.handler.runOptimizerStep(e||{})}async runEvalStep(e,t,n){if(this.hasEvalModel){const[r,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,n),i=await this.handler.runEvalStep(e,r,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,t=!0){const n=await this.getParametersSize(t);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,t)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js": /*!**********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/training-session.js ***! \**********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>r});const r=n(/*! ./training-session-impl.js */"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js").TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js": /*!*************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/version.js ***! \*************************************************************/(e,t,n)=>{n.r(t),n.d(t,{version:()=>r});const r="1.17.0"},"./node_modules/onnxruntime-web/dist/esm/ort.webgpu.min.js": /*!*****************************************************************!*\ !*** ./node_modules/onnxruntime-web/dist/esm/ort.webgpu.min.js ***! \*****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>P,TRACE:()=>k,TRACE_FUNC_BEGIN:()=>E,TRACE_FUNC_END:()=>A,Tensor:()=>M,TrainingSession:()=>z,default:()=>Ou,env:()=>c,registerBackend:()=>i}); /*! * ONNX Runtime Web v1.17.3 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ var r,a,i,s,o,l,u,d,c,p,h,f,m,g,_,w,y,b,v,$,x,T,S,M,k,C,E,A,I,P,O,z,B=Object.defineProperty,F=Object.getOwnPropertyDescriptor,R=Object.getOwnPropertyNames,D=Object.prototype.hasOwnProperty,L=(e,t)=>()=>(e&&(t=e(e=0)),t),N=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),U=(e,t)=>{for(var n in t)B(e,n,{get:t[n],enumerable:!0})},W=e=>((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of R(t))!D.call(e,a)&&a!==n&&B(e,a,{get:()=>t[a],enumerable:!(r=F(t,a))||r.enumerable});return e})(B({},"__esModule",{value:!0}),e),V=L((()=>{r=new Map,a=[],i=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{let i=r.get(e);if(void 0===i)r.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=a.indexOf(e);-1!==t&&a.splice(t,1);for(let t=0;t{let t=r.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},o=async e=>{let t,n=e.executionProviders||[],r=n.map((e=>"string"==typeof e?e:e.name)),i=0===r.length?a:r,o=[],l=new Set;for(let e of i){let n=await s(e);"string"==typeof n?o.push({name:e,err:n}):(t||(t=n),t===n&&l.add(e))}if(!t)throw new Error(`no available backend found. ERR: ${o.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`);for(let{name:e,err:t}of o)r.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let u=n.filter((e=>l.has("string"==typeof e?e:e.name)));return[t,new Proxy(e,{get:(e,t)=>"executionProviders"===t?u:Reflect.get(e,t)})]}})),G=L((()=>{V()})),j=L((()=>{l="1.17.3"})),q=L((()=>{j(),u="warning",d={wasm:{},webgl:{},webgpu:{},versions:{common:l},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);u=e}},get logLevel(){return u}},Object.defineProperty(d,"logLevel",{enumerable:!0})})),H=L((()=>{q(),c=d})),K=L((()=>{p=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext("2d");if(null!=r){let a,i;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],i=e.dims[3]):(a=e.dims[3],i=e.dims[2]);let s,o,l=void 0!==t?.format?t.format:"RGB",u=t?.norm;void 0===u||void 0===u.mean?s=[255,255,255,255]:"number"==typeof u.mean?s=[u.mean,u.mean,u.mean,u.mean]:(s=[u.mean[0],u.mean[1],u.mean[2],0],void 0!==u.mean[3]&&(s[3]=u.mean[3])),void 0===u||void 0===u.bias?o=[0,0,0,0]:"number"==typeof u.bias?o=[u.bias,u.bias,u.bias,u.bias]:(o=[u.bias[0],u.bias[1],u.bias[2],0],void 0!==u.bias[3]&&(o[3]=u.bias[3]));let d=i*a,c=0,p=d,h=2*d,f=-1;"RGBA"===l?(c=0,p=d,h=2*d,f=3*d):"RGB"===l?(c=0,p=d,h=2*d):"RBG"===l&&(c=0,h=d,p=2*d);for(let t=0;t{let n,r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(null==r)throw new Error("Can not access image data");{let a,i,s;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],i=e.dims[1],s=e.dims[3]):(a=e.dims[3],i=e.dims[2],s=e.dims[1]);let o,l,u=void 0!==t&&void 0!==t.format?t.format:"RGB",d=t?.norm;void 0===d||void 0===d.mean?o=[255,255,255,255]:"number"==typeof d.mean?o=[d.mean,d.mean,d.mean,d.mean]:(o=[d.mean[0],d.mean[1],d.mean[2],255],void 0!==d.mean[3]&&(o[3]=d.mean[3])),void 0===d||void 0===d.bias?l=[0,0,0,0]:"number"==typeof d.bias?l=[d.bias,d.bias,d.bias,d.bias]:(l=[d.bias[0],d.bias[1],d.bias[2],0],void 0!==d.bias[3]&&(l[3]=d.bias[3]));let c=i*a;if(void 0!==t&&(void 0!==t.format&&4===s&&"RGBA"!==t.format||3===s&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,f=1,m=2,g=3,_=0,w=c,y=2*c,b=-1;"RGBA"===u?(_=0,w=c,y=2*c,b=3*c):"RGB"===u?(_=0,w=c,y=2*c):"RBG"===u&&(_=0,y=c,w=2*c),n=r.createImageData(a,i);for(let t=0;t{Z(),f=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");let n,r,{height:a,width:i}=t,s=t.norm??{mean:255,bias:0};n="number"==typeof s.mean?[s.mean,s.mean,s.mean,s.mean]:[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],r="number"==typeof s.bias?[s.bias,s.bias,s.bias,s.bias]:[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let o=void 0!==t.format?t.format:"RGBA",l=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",u=a*i,d="RGBA"===l?new Float32Array(4*u):new Float32Array(3*u),c=4,p=0,h=1,f=2,m=3,g=0,_=u,w=2*u,y=-1;"RGB"===o&&(c=3,p=0,h=1,f=2,m=-1),"RGBA"===l?y=3*u:"RBG"===l?(g=0,w=u,_=2*u):"BGR"===l&&(w=0,_=u,g=2*u);for(let t=0;t{let n,r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,s="string"==typeof e,o=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=e=>e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(r){let r=l();r.width=e.width,r.height=e.height;let a=u(r);if(null==a)throw new Error("Can not access image data");{let r=e.height,i=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(r=t.resizedHeight,i=t.resizedWidth),void 0!==t){if(o=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=r,o.width=i}else o.tensorFormat="RGBA",o.height=r,o.width=i;a.drawImage(e,0,0),n=a.getImageData(0,0,i,r).data}}else{if(!a){if(i){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");let r=l();r.width=e.width,r.height=e.height;let a=u(r);if(null!=a){let t=e.height,r=e.width;return a.drawImage(e,0,0,r,t),n=a.getImageData(0,0,r,t).data,o.height=t,o.width=r,f(n,o)}throw new Error("Can not access image data")}if(s)return new Promise(((t,n)=>{let r=l(),a=u(r);if(!e||!a)return n();let i=new Image;i.crossOrigin="Anonymous",i.src=e,i.onload=()=>{r.width=i.width,r.height=i.height,a.drawImage(i,0,0,r.width,r.height);let e=a.getImageData(0,0,r.width,r.height);o.height=r.height,o.width=r.width,t(f(e.data,o))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let r,a;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(r=t.resizedHeight,a=t.resizedWidth):(r=e.height,a=e.width),void 0!==t&&(o=t),o.format="RGBA",o.height=r,o.width=a,void 0!==t){let t=l();t.width=a,t.height=r;let i=u(t);if(null==i)throw new Error("Can not access image data");i.putImageData(e,0,0),n=i.getImageData(0,0,a,r).data}else n=e.data}}if(void 0!==n)return f(n,o);throw new Error("Input data provided is not supported - aborted tensor creation")},g=(e,t)=>{let{width:n,height:r,download:a,dispose:i}=t;return new S({location:"texture",type:"float32",texture:e,dims:[1,r,n,4],download:a,dispose:i})},_=(e,t)=>{let{dataType:n,dims:r,download:a,dispose:i}=t;return new S({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:r,download:a,dispose:i})},w=(e,t,n)=>new S({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})})),X=L((()=>{y=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),b=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),v=!1,$=()=>{if(!v){v=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=typeof Float16Array<"u"&&Float16Array.from;e&&(y.set("int64",BigInt64Array),b.set(BigInt64Array,"int64")),t&&(y.set("uint64",BigUint64Array),b.set(BigUint64Array,"uint64")),n?(y.set("float16",Float16Array),b.set(Float16Array,"float16")):y.set("float16",Uint16Array)}}})),Q=L((()=>{Z(),x=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new S(e.type,e.data,t);case"cpu-pinned":return new S({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new S({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new S({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}})),Z=L((()=>{K(),Y(),X(),Q(),S=class{constructor(e,t,n){let r,a;if($(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,r=e.type,a=e.dims,e.location){case"cpu-pinned":{let t=y.get(r);if(!t)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint8"!==r&&"bool"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,s;if("string"==typeof e)if(r=e,s=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let n=y.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&n===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");i="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else{if(!(t instanceof n))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);i=t}}else if(s=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");let t=typeof e[0];if("string"===t)r="string",i=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",i=Uint8Array.from(e)}}else{let t=b.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,i=e}if(void 0===s)s=[i.length];else if(!Array.isArray(s))throw new TypeError("A tensor's dims must be a number array");a=s,this.cpuData=i,this.dataLocation="cpu"}let i=x(a);if(this.cpuData&&i!==this.cpuData.length)throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=a,this.size=i}static async fromImage(e,t){return m(e,t)}static fromTexture(e,t){return g(e,t)}static fromGpuBuffer(e,t){return _(e,t)}static fromPinnedBuffer(e,t,n){return w(e,t,n)}toDataURL(e){return p(this,e)}toImageData(e){return h(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if("none"===this.dataLocation)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 T(this,e)}}})),J=L((()=>{Z(),M=S})),ee=L((()=>{q(),k=(e,t)=>{(typeof d.trace>"u"?!d.wasm.trace:!d.trace)||console.timeStamp(`${e}::ORT::${t}`)},C=(e,t)=>{let n=(new Error).stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let a=0;a{(typeof d.trace>"u"?!d.wasm.trace:!d.trace)||C("BEGIN",e)},A=e=>{(typeof d.trace>"u"?!d.wasm.trace:!d.trace)||C("END",e)}})),te=L((()=>{V(),J(),ee(),I=class e{constructor(e){this.handler=e}async run(e,t,n){E();let r={},a={};if("object"!=typeof e||null===e||e instanceof M||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof M)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,s=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(-1!==s.indexOf(n)){let a=t[n];(null===a||a instanceof M)&&(e=!0,i=!1,r[n]=a)}if(e){if("object"==typeof n&&null!==n)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of this.inputNames)if(typeof e[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(i)for(let e of this.outputNames)r[e]=null;let s=await this.handler.run(e,r,a),o={};for(let e in s)if(Object.hasOwnProperty.call(s,e)){let t=s[e];o[e]=t instanceof M?t:new M(t.type,t.data,t.dims)}return A(),o}async release(){return this.handler.dispose()}static async create(t,n,r,a){E();let i,s={};if("string"==typeof t){if(i=t,"object"==typeof n&&null!==n)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,"object"==typeof n&&null!==n)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let e=t,o=0,l=t.byteLength;if("object"==typeof n&&null!==n)s=n;else if("number"==typeof n){if(o=n,!Number.isSafeInteger(o))throw new RangeError("'byteOffset' must be an integer.");if(o<0||o>=e.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(l=t.byteLength-o,"number"==typeof r){if(l=r,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||o+l>e.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${e.byteLength-o}].`);if("object"==typeof a&&null!==a)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(e,o,l)}}let[l,u]=await o(s),d=await l.createInferenceSessionHandler(i,u);return A(),new e(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}})),ne=L((()=>{te(),P=I})),re=L((()=>{})),ae=L((()=>{})),ie=L((()=>{})),se=L((()=>{})),oe=L((()=>{V(),J(),"Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",O=class e{constructor(e,t,n){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,n){let r=t.evalModel||"",a=t.optimizerModel||"",i=n||{},[s,l]=await o(i);if(s.createTrainingSessionHandler){let n=await s.createTrainingSessionHandler(t.checkpointState,t.trainModel,r,a,l);return new e(n,!!t.optimizerModel,!!t.evalModel)}throw new Error("Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.")}typeNarrowingForRunStep(e,t,n,r,a){let i={},s={};if("object"!=typeof n||null===n||n instanceof M||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if("object"==typeof r){if(null===r)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof M)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(0===r.length)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let e of r){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===t.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);i[e]=null}if("object"==typeof a&&null!==a)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,n=Object.getOwnPropertyNames(r);for(let a of t)if(-1!==n.indexOf(a)){let t=r[a];(null===t||t instanceof M)&&(e=!0,o=!1,i[a]=t)}if(e){if("object"==typeof a&&null!==a)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of e)if(typeof n[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(o)for(let e of t)i[e]=null;return[i,s]}convertHandlerReturnTypeToMapOfTensors(e){let t={};for(let n in e)if(Object.hasOwnProperty.call(e,n)){let r=e[n];t[n]=r instanceof M?r:new M(r.type,r.data,r.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,n){let[r,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,n),i=await this.handler.runTrainStep(e,r,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}async runOptimizerStep(e){if(!this.hasOptimizerModel)throw new Error("This TrainingSession has no OptimizerModel loaded.");await this.handler.runOptimizerStep(e||{})}async runEvalStep(e,t,n){if(this.hasEvalModel){let[r,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,n),i=await this.handler.runEvalStep(e,r,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,t=!0){let n=await this.getParametersSize(t);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,t)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}})),le=L((()=>{oe(),z=O})),ue={};U(ue,{InferenceSession:()=>P,TRACE:()=>k,TRACE_FUNC_BEGIN:()=>E,TRACE_FUNC_END:()=>A,Tensor:()=>M,TrainingSession:()=>z,env:()=>c,registerBackend:()=>i});var de=L((()=>{G(),H(),ne(),J(),re(),ae(),ee(),ie(),se(),le()})),ce={};U(ce,{createReadStream:()=>fe,readFile:()=>pe,readFileSync:()=>he});var pe,he,fe,me=L((()=>{pe=void 0,he=void 0,fe=void 0})),ge={};U(ge,{join:()=>_e});var _e,we=L((()=>{_e=void 0})),ye=N(((e,t)=>{var n,r=(n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0,typeof __filename<"u"&&(n=n||__filename),function(e={}){var t,r,a=e;a.ready=new Promise(((e,n)=>{t=e,r=n})),a.mountExternalData=(e,t)=>{(a.Fa||(a.Fa=new Map)).set(e,t)},a.unmountExternalData=()=>{delete a.Fa};let i=()=>{let e=(e,t,n)=>(...r)=>{let a=_e,i=t?.();r=e(...r);let s=t?.();return i!==s&&(e=s,n(i),t=n=null),_e!=a?new Promise(((e,t)=>{Te={resolve:e,reject:t}})):r},t=e=>async(...t)=>{try{if(a.Ea)throw Error("Session already started");let n=a.Ea={Za:t[0],errors:[]},r=await e(...t);if(a.Ea!==n)throw Error("Session mismatch");a.La?.flush();let i=n.errors;if(0e)),0a._OrtCreateSession),(e=>a._OrtCreateSession=e)),a._OrtRun=t(e(a._OrtRun,(()=>a._OrtRun),(e=>a._OrtRun=e))),a._OrtRunWithBinding=t(e(a._OrtRunWithBinding,(()=>a._OrtRunWithBinding),(e=>a._OrtRunWithBinding=e))),a._OrtBindInput=e(a._OrtBindInput,(()=>a._OrtBindInput),(e=>a._OrtBindInput=e)),i=void 0};a.jsepInit=(e,t)=>{if(i?.(),"webgpu"===e){[a.La,a.Ra,a.Va,a.Ma,a.Ua,a.sa,a.Wa,a.Ya,a.Sa,a.Ta,a.Xa]=t;let e=a.La;a.jsepRegisterBuffer=(t,n,r,a)=>e.registerBuffer(t,n,r,a),a.jsepGetBuffer=t=>e.getBuffer(t),a.jsepCreateDownloader=(t,n,r)=>e.createDownloader(t,n,r),a.jsepOnReleaseSession=t=>{e.onReleaseSession(t)},a.jsepOnRunStart=t=>e.onRunStart(t)}};var s,o,l,u=Object.assign({},a),d="./this.program",c=(e,t)=>{throw t},p="object"==typeof window,h="function"==typeof importScripts,f="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";if(f){var g=(me(),W(ce)),_=(we(),W(ge));m=h?_.dirname(m)+"/":__dirname+"/",s=(e,t)=>(e=L(e)?new URL(e):_.normalize(e),g.readFileSync(e,t?void 0:"utf8")),l=e=>((e=s(e,!0)).buffer||(e=new Uint8Array(e)),e),o=(e,t,n,r=!0)=>{e=L(e)?new URL(e):_.normalize(e),g.readFile(e,r?void 0:"utf8",((e,a)=>{e?n(e):t(r?a.buffer:a)}))},!a.thisProgram&&1{throw process.exitCode=e,t},a.inspect=()=>"[Emscripten Module object]"}else(p||h)&&(h?m=self.location.href:typeof document<"u"&&document.currentScript&&(m=document.currentScript.src),n&&(m=n),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},h&&(l=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),o=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var w=console.log.bind(console),y=console.error.bind(console);Object.assign(a,u),u=null,"object"!=typeof WebAssembly&&F("no native wasm support detected");var b,v,$,x,T,S,M,k,C=!1;function E(){var e=b.buffer;a.HEAP8=$=new Int8Array(e),a.HEAP16=new Int16Array(e),a.HEAPU8=x=new Uint8Array(e),a.HEAPU16=new Uint16Array(e),a.HEAP32=T=new Int32Array(e),a.HEAPU32=S=new Uint32Array(e),a.HEAPF32=M=new Float32Array(e),a.HEAPF64=k=new Float64Array(e)}var A=[],I=[],P=[],O=0,z=null,B=null;function F(e){throw y(e="Aborted("+e+")"),C=!0,v=1,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),r(e),e}var R,D=e=>e.startsWith("data:application/octet-stream;base64,"),L=e=>e.startsWith("file://");if(!D(R="ort-wasm-simd.wasm")){var N=R;R=a.locateFile?a.locateFile(N,m):m+N}function U(e){if(l)return l(e);throw"both async and sync fetching of the wasm failed"}function V(e,t,n){return function(e){if(p||h){if("function"==typeof fetch&&!L(e))return fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((()=>U(e)));if(o)return new Promise(((t,n)=>{o(e,(e=>t(new Uint8Array(e))),n)}))}return Promise.resolve().then((()=>U(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(n,(e=>{y(`failed to asynchronously prepare wasm: ${e}`),F(e)}))}var G,j={931760:(e,t,n,r)=>{if(typeof a>"u"||!a.Fa)return 1;if((e=Q(e>>>0)).startsWith("./")&&(e=e.substring(2)),!(e=a.Fa.get(e)))return 2;if((t>>>=0)+(n>>>=0)>e.byteLength)return 3;try{return x.set(e.subarray(t,t+n),r>>>0>>>0),0}catch{return 4}},932261:()=>{a.Sa()},932292:()=>{a.Ta()},932321:()=>{a.Xa()},932346:e=>a.Ra(e),932379:e=>a.Va(e),932411:(e,t,n)=>{a.Ma(e,t,n,!0)},932450:(e,t,n)=>{a.Ma(e,t,n)},932483:e=>{a.sa("Abs",e,void 0)},932534:e=>{a.sa("Neg",e,void 0)},932585:e=>{a.sa("Floor",e,void 0)},932638:e=>{a.sa("Ceil",e,void 0)},932690:e=>{a.sa("Reciprocal",e,void 0)},932748:e=>{a.sa("Sqrt",e,void 0)},932800:e=>{a.sa("Exp",e,void 0)},932851:e=>{a.sa("Erf",e,void 0)},932902:e=>{a.sa("Sigmoid",e,void 0)},932957:(e,t,n)=>{a.sa("HardSigmoid",e,{alpha:t,beta:n})},933036:e=>{a.sa("Log",e,void 0)},933087:e=>{a.sa("Sin",e,void 0)},933138:e=>{a.sa("Cos",e,void 0)},933189:e=>{a.sa("Tan",e,void 0)},933240:e=>{a.sa("Asin",e,void 0)},933292:e=>{a.sa("Acos",e,void 0)},933344:e=>{a.sa("Atan",e,void 0)},933396:e=>{a.sa("Sinh",e,void 0)},933448:e=>{a.sa("Cosh",e,void 0)},933500:e=>{a.sa("Asinh",e,void 0)},933553:e=>{a.sa("Acosh",e,void 0)},933606:e=>{a.sa("Atanh",e,void 0)},933659:e=>{a.sa("Tanh",e,void 0)},933711:e=>{a.sa("Not",e,void 0)},933762:(e,t,n)=>{a.sa("Clip",e,{min:t,max:n})},933831:e=>{a.sa("Clip",e,void 0)},933883:(e,t)=>{a.sa("Elu",e,{alpha:t})},933941:e=>{a.sa("Relu",e,void 0)},933993:(e,t)=>{a.sa("LeakyRelu",e,{alpha:t})},934057:(e,t)=>{a.sa("ThresholdedRelu",e,{alpha:t})},934127:(e,t)=>{a.sa("Cast",e,{to:t})},934185:e=>{a.sa("Add",e,void 0)},934236:e=>{a.sa("Sub",e,void 0)},934287:e=>{a.sa("Mul",e,void 0)},934338:e=>{a.sa("Div",e,void 0)},934389:e=>{a.sa("Pow",e,void 0)},934440:e=>{a.sa("Equal",e,void 0)},934493:e=>{a.sa("Greater",e,void 0)},934548:e=>{a.sa("GreaterOrEqual",e,void 0)},934610:e=>{a.sa("Less",e,void 0)},934662:e=>{a.sa("LessOrEqual",e,void 0)},934721:(e,t,n,r,i)=>{a.sa("ReduceMean",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},934880:(e,t,n,r,i)=>{a.sa("ReduceMax",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},935038:(e,t,n,r,i)=>{a.sa("ReduceMin",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},935196:(e,t,n,r,i)=>{a.sa("ReduceProd",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},935355:(e,t,n,r,i)=>{a.sa("ReduceSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},935513:(e,t,n,r,i)=>{a.sa("ReduceL1",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},935670:(e,t,n,r,i)=>{a.sa("ReduceL2",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},935827:(e,t,n,r,i)=>{a.sa("ReduceLogSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},935988:(e,t,n,r,i)=>{a.sa("ReduceSumSquare",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},936152:(e,t,n,r,i)=>{a.sa("ReduceLogSumExp",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},936316:e=>{a.sa("Where",e,void 0)},936369:(e,t,n)=>{a.sa("Transpose",e,{perm:t?Array.from(T.subarray(t>>>0,n>>>0)):[]})},936477:(e,t,n,r,i,s,o,l,u,d,c,p,h,f,m)=>{a.sa("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:t,dilations:[n],group:r,kernel_shape:[i],pads:[s,o],strides:[l],wIsConst:()=>!!$[d>>>0],outputPadding:c?Array.from(T.subarray(c>>>0,p>>>0)):[],outputShape:h?Array.from(T.subarray(h>>>0,f>>>0)):[],activation:Q(m)})},936879:(e,t,n,r,i,s,o,l,u,d,c,p,h,f)=>{a.sa("ConvTranspose",e,{format:l?"NHWC":"NCHW",autoPad:t,dilations:Array.from(T.subarray(n>>>0,2+(n>>>0)>>>0)),group:r,kernelShape:Array.from(T.subarray(i>>>0,2+(i>>>0)>>>0)),pads:Array.from(T.subarray(s>>>0,4+(s>>>0)>>>0)),strides:Array.from(T.subarray(o>>>0,2+(o>>>0)>>>0)),wIsConst:()=>!!$[u>>>0],outputPadding:d?Array.from(T.subarray(d>>>0,c>>>0)):[],outputShape:p?Array.from(T.subarray(p>>>0,h>>>0)):[],activation:Q(f)})},937444:(e,t,n,r,i,s,o,l,u,d,c,p,h,f,m)=>{a.sa("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:t,dilations:[n],group:r,kernel_shape:[i],pads:[s,o],strides:[l],wIsConst:()=>!!$[d>>>0],outputPadding:c?Array.from(T.subarray(c>>>0,p>>>0)):[],outputShape:h?Array.from(T.subarray(h>>>0,f>>>0)):[],activation:Q(m)})},937846:(e,t,n,r,i,s,o,l,u,d,c,p,h,f)=>{a.sa("ConvTranspose",e,{format:l?"NHWC":"NCHW",autoPad:t,dilations:Array.from(T.subarray(n>>>0,2+(n>>>0)>>>0)),group:r,kernelShape:Array.from(T.subarray(i>>>0,2+(i>>>0)>>>0)),pads:Array.from(T.subarray(s>>>0,4+(s>>>0)>>>0)),strides:Array.from(T.subarray(o>>>0,2+(o>>>0)>>>0)),wIsConst:()=>!!$[u>>>0],outputPadding:d?Array.from(T.subarray(d>>>0,c>>>0)):[],outputShape:p?Array.from(T.subarray(p>>>0,h>>>0)):[],activation:Q(f)})},938411:(e,t)=>{a.sa("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},938502:(e,t,n,r,i,s,o,l,u,d,c,p,h,f,m,g)=>{a.sa("AveragePool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:[s,o],kernel_shape:[l,u],pads:[d,c,p,h],strides:[f,m]})},938786:(e,t)=>{a.sa("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},938877:(e,t,n,r,i,s,o,l,u,d,c,p,h,f,m,g)=>{a.sa("AveragePool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:[s,o],kernel_shape:[l,u],pads:[d,c,p,h],strides:[f,m]})},939161:(e,t)=>{a.sa("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},939248:(e,t,n,r,i,s,o,l,u,d,c,p,h,f,m,g)=>{a.sa("MaxPool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:[s,o],kernel_shape:[l,u],pads:[d,c,p,h],strides:[f,m]})},939528:(e,t)=>{a.sa("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},939615:(e,t,n,r,i,s,o,l,u,d,c,p,h,f,m,g)=>{a.sa("MaxPool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:[s,o],kernel_shape:[l,u],pads:[d,c,p,h],strides:[f,m]})},939895:(e,t,n,r,i)=>{a.sa("Gemm",e,{alpha:t,beta:n,transA:r,transB:i})},939999:e=>{a.sa("MatMul",e,void 0)},940053:(e,t,n,r)=>{a.sa("ArgMax",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},940161:(e,t,n,r)=>{a.sa("ArgMin",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},940269:(e,t)=>{a.sa("Softmax",e,{axis:t})},940332:(e,t)=>{a.sa("Concat",e,{axis:t})},940392:(e,t,n,r,i)=>{a.sa("Split",e,{axis:t,numOutputs:n,splitSizes:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},940532:e=>{a.sa("Expand",e,void 0)},940586:(e,t)=>{a.sa("Gather",e,{axis:Number(t)})},940657:(e,t)=>{a.sa("GatherElements",e,{axis:Number(t)})},940736:(e,t,n,r,i,s,o,l,u,d,c)=>{a.sa("Resize",e,{antialias:t,axes:n?Array.from(T.subarray(n>>>0,r>>>0)):[],coordinateTransformMode:Q(i),cubicCoeffA:s,excludeOutside:o,extrapolationValue:l,keepAspectRatioPolicy:Q(u),mode:Q(d),nearestMode:Q(c)})},941082:(e,t,n,r,i,s,o)=>{a.sa("Slice",e,{starts:t?Array.from(T.subarray(t>>>0,n>>>0)):[],ends:r?Array.from(T.subarray(r>>>0,i>>>0)):[],axes:s?Array.from(T.subarray(s>>>0,o>>>0)):[]})},941298:e=>{a.sa("Tile",e,void 0)},941350:(e,t,n)=>{a.sa("LayerNormalization",e,{axis:Number(t),epsilon:Number(n)})},941457:(e,t,n)=>{a.sa("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},941571:(e,t,n)=>{a.sa("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},941685:e=>{a.sa("Range",e,void 0)},941738:(e,t)=>{a.sa("Einsum",e,{equation:Q(t)})},941819:(e,t,n,r,i)=>{a.sa("Pad",e,{mode:t,value:n,pads:r?Array.from(T.subarray(r>>>0,i>>>0)):[]})},941946:(e,t,n,r,i,s)=>{a.sa("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!i,trainingMode:!!r,format:s?"NHWC":"NCHW"})},942115:(e,t,n,r,i,s)=>{a.sa("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!i,trainingMode:!!r,format:s?"NHWC":"NCHW"})},942284:(e,t,n)=>{a.sa("CumSum",e,{exclusive:Number(t),reverse:Number(n)})},942381:(e,t,n,r,i,s,o,l,u)=>{a.sa("Attention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:i,doRotary:s,qkvHiddenSizes:o?Array.from(T.subarray(Number(l)>>>0,Number(l)+o>>>0)):[],pastPresentShareBuffer:!!u})},942653:e=>{a.sa("BiasAdd",e,void 0)},942708:e=>{a.sa("BiasSplitGelu",e,void 0)},942769:e=>{a.sa("FastGelu",e,void 0)},942825:(e,t,n,r,i,s,o,l,u,d,c,p,h)=>{a.sa("Conv",e,{format:u?"NHWC":"NCHW",auto_pad:t,dilations:[n],group:r,kernel_shape:[i],pads:s?Array.from(T.subarray(s>>>0,o>>>0)):[],strides:[l],w_is_const:()=>!!$[d>>>0],activation:Q(c),activation_params:p?Array.from(M.subarray(p>>>0,h>>>0)):[]})},943195:(e,t,n,r,i,s,o,l,u,d,c,p,h,f,m,g)=>{a.sa("Conv",e,{format:p?"NHWC":"NCHW",auto_pad:t,dilations:[n,r],group:i,kernel_shape:[s,o],pads:l?Array.from(T.subarray(l>>>0,u>>>0)):[],strides:[d,c],w_is_const:()=>!!$[h>>>0],activation:Q(f),activation_params:m?Array.from(M.subarray(m>>>0,g>>>0)):[]})},943586:e=>{a.sa("Gelu",e,void 0)},943638:(e,t,n,r,i,s)=>{a.sa("MatMulNBits",e,{k:t,n,accuracyLevel:r,bits:i,blockSize:s})},943765:(e,t,n,r,i,s)=>{a.sa("MultiHeadAttention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:i,doRotary:s})},943924:(e,t)=>{a.sa("SkipLayerNormalization",e,{epsilon:t})},944005:e=>{a.Wa(e)},944039:(e,t)=>a.Ya(e,t,a.Ea.Za,a.Ea.errors)};function q(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}function H(e){this.Ja=e-24,this.Pa=function(e){S[this.Ja+4>>>2>>>0]=e},this.Oa=function(e){S[this.Ja+8>>>2>>>0]=e},this.eb=function(e,t){this.Na(),this.Pa(e),this.Oa(t)},this.Na=function(){S[this.Ja+16>>>2>>>0]=0}}var K,Y=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,X=(e,t,n)=>{var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|s:(7&a)<<18|i<<12|s<<6|63&e[t++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r},Q=(e,t)=>(e>>>=0)?X(x,e,t):"",Z=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t},J=(e,t,n,r)=>{if(!(0>>=0;r=n+r-1;for(var i=0;i=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-a},ee=e=>e%4==0&&(e%100!=0||e%400==0),te=[0,31,60,91,121,152,182,213,244,274,305,335],ne=[0,31,59,90,120,151,181,212,243,273,304,334],re=e=>{var t=Z(e)+1,n=Ie(t);return n&&J(e,x,n,t),n},ae=[],ie=(e,t)=>{ae.length=0;for(var n;n=x[e++>>>0];){var r=105!=n;t+=(r&=112!=n)&&t%8?4:0,ae.push(112==n?S[t>>>2>>>0]:105==n?T[t>>>2>>>0]:k[t>>>3>>>0]),t+=r?8:4}return ae},se={},oe=()=>{if(!K){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(e in se)void 0===se[e]?delete t[e]:t[e]=se[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);K=n}return K},le=[null,[],[]],ue=[31,29,31,30,31,30,31,31,30,31,30,31],de=[31,28,31,30,31,30,31,31,30,31,30,31];function pe(e,t,n,r){function a(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.lengthe?-1:0r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=o(new Date(e.getFullYear(),0,4)),n=o(n),0>=s(t,e)?0>=s(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}e>>>=0,t>>>=0,n>>>=0;var u=S[40+(r>>>=0)>>>2>>>0];for(var d in r={bb:T[r>>>2>>>0],ab:T[r+4>>>2>>>0],Ga:T[r+8>>>2>>>0],Ka:T[r+12>>>2>>>0],Ha:T[r+16>>>2>>>0],Da:T[r+20>>>2>>>0],xa:T[r+24>>>2>>>0],Ca:T[r+28>>>2>>>0],fb:T[r+32>>>2>>>0],$a:T[r+36>>>2>>>0],cb:u?Q(u):""},n=Q(n),u={"%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"})n=n.replace(new RegExp(d,"g"),u[d]);var c="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(d in u={"%a":e=>c[e.xa].substring(0,3),"%A":e=>c[e.xa],"%b":e=>p[e.Ha].substring(0,3),"%B":e=>p[e.Ha],"%C":e=>i((e.Da+1900)/100|0,2),"%d":e=>i(e.Ka,2),"%e":e=>a(e.Ka,2," "),"%g":e=>l(e).toString().substring(2),"%G":e=>l(e),"%H":e=>i(e.Ga,2),"%I":e=>(0==(e=e.Ga)?e=12:12{for(var t=0,n=0;n<=e.Ha-1;t+=(ee(e.Da+1900)?ue:de)[n++]);return i(e.Ka+t,3)},"%m":e=>i(e.Ha+1,2),"%M":e=>i(e.ab,2),"%n":()=>"\n","%p":e=>0<=e.Ga&&12>e.Ga?"AM":"PM","%S":e=>i(e.bb,2),"%t":()=>"\t","%u":e=>e.xa||7,"%U":e=>i(Math.floor((e.Ca+7-e.xa)/7),2),"%V":e=>{var t=Math.floor((e.Ca+7-(e.xa+6)%7)/7);if(2>=(e.xa+371-e.Ca-2)%7&&t++,t)53==t&&(4==(n=(e.xa+371-e.Ca)%7)||3==n&&ee(e.Da)||(t=1));else{t=52;var n=(e.xa+7-e.Ca-1)%7;(4==n||5==n&&ee(e.Da%400-1))&&t++}return i(t,2)},"%w":e=>e.xa,"%W":e=>i(Math.floor((e.Ca+7-(e.xa+6)%7)/7),2),"%y":e=>(e.Da+1900).toString().substring(2),"%Y":e=>e.Da+1900,"%z":e=>(0<=(e=e.$a)?"+":"-")+("0000"+((e=Math.abs(e)/60)/60*100+e%60)).slice(-4),"%Z":e=>e.cb,"%%":()=>"%"},n=n.replace(/%%/g,"\0\0"),u)n.includes(d)&&(n=n.replace(new RegExp(d,"g"),u[d](r)));return d=function(e){var t=Array(Z(e)+1);return J(e,t,0,t.length),t}(n=n.replace(/\0\0/g,"%")),d.length>t?0:($.set(d,e>>>0),d.length-1)}var he=e=>{try{e()}catch(e){F(e)}},fe=0,_e=null,ye=0,be=[],ve={},$e={},xe=0,Te=null,Se=[];function Me(e){if(!C){if(0===fe){var t=!1,n=!1;e(((e=0)=>{if(!C&&(ye=e,t=!0,n)){fe=2,he((()=>Le(_e))),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.resume(),e=!1;try{var r=(0,Ce[$e[T[_e+8>>>2>>>0]]])()}catch(t){r=t,e=!0}var a=!1;if(!_e){var i=Te;i&&(Te=null,(e?i.reject:i.resolve)(r),a=!0)}if(e&&!a)throw r}})),n=!0,t||(fe=1,_e=function(){var e=Ie(65548),t=e+12;S[e>>>2>>>0]=t,S[e+4>>>2>>>0]=t+65536,t=be[0];var n=ve[t];return void 0===n&&(n=xe++,ve[t]=n,$e[n]=t),T[e+8>>>2>>>0]=n,e}(),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.pause(),he((()=>Re(_e))))}else 2===fe?(fe=0,he(Ne),Pe(_e),_e=null,Se.forEach((e=>{if(!C)try{e();try{v=v=e=v,a.onExit?.(e),C=!0,c(e,new q(e))}catch(e){e instanceof q||"unwind"==e||c(1,e)}}catch(e){e instanceof q||"unwind"==e||c(1,e)}}))):F(`invalid state: ${fe}`);return ye}}var ke={n:function(e,t,n){return function(e){return Me((t=>{e().then(t)}))}((async()=>{await a.Ua(e,t,n)}))},a:function(e,t,n){throw new H(e>>>=0).eb(t>>>0,n>>>0),e},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),T[n>>>2>>>0]=e.getUTCSeconds(),T[n+4>>>2>>>0]=e.getUTCMinutes(),T[n+8>>>2>>>0]=e.getUTCHours(),T[n+12>>>2>>>0]=e.getUTCDate(),T[n+16>>>2>>>0]=e.getUTCMonth(),T[n+20>>>2>>>0]=e.getUTCFullYear()-1900,T[n+24>>>2>>>0]=e.getUTCDay(),T[n+28>>>2>>>0]=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),T[n>>>2>>>0]=e.getSeconds(),T[n+4>>>2>>>0]=e.getMinutes(),T[n+8>>>2>>>0]=e.getHours(),T[n+12>>>2>>>0]=e.getDate(),T[n+16>>>2>>>0]=e.getMonth(),T[n+20>>>2>>>0]=e.getFullYear()-1900,T[n+24>>>2>>>0]=e.getDay(),T[n+28>>>2>>>0]=(ee(e.getFullYear())?te:ne)[e.getMonth()]+e.getDate()-1|0,T[n+36>>>2>>>0]=-60*e.getTimezoneOffset(),t=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();T[n+32>>>2>>>0]=0|(t!=r&&e.getTimezoneOffset()==Math.min(r,t))},s:function(e){e>>>=0;var t=new Date(T[e+20>>>2>>>0]+1900,T[e+16>>>2>>>0],T[e+12>>>2>>>0],T[e+8>>>2>>>0],T[e+4>>>2>>>0],T[e>>>2>>>0],0),n=T[e+32>>>2>>>0],r=t.getTimezoneOffset(),a=new Date(t.getFullYear(),6,1).getTimezoneOffset(),i=new Date(t.getFullYear(),0,1).getTimezoneOffset(),s=Math.min(i,a);return 0>n?T[e+32>>>2>>>0]=+(a!=i&&s==r):0>>2>>>0]=t.getDay(),T[e+28>>>2>>>0]=(ee(t.getFullYear())?te:ne)[t.getMonth()]+t.getDate()-1|0,T[e>>>2>>>0]=t.getSeconds(),T[e+4>>>2>>>0]=t.getMinutes(),T[e+8>>>2>>>0]=t.getHours(),T[e+12>>>2>>>0]=t.getDate(),T[e+16>>>2>>>0]=t.getMonth(),T[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),isNaN(e)?(T[Ae()>>>2>>>0]=61,e=-1):e/=1e3,Oe((G=e,1<=+Math.abs(G)?0>>0:~~+Math.ceil((G-+(~~G>>>0))/4294967296)>>>0:0)),e>>>0},o:function(){return-52},p:function(){},w:function(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}n>>>=0;var a=(new Date).getFullYear(),i=new Date(a,0,1),s=new Date(a,6,1);a=i.getTimezoneOffset();var o=s.getTimezoneOffset();S[e>>>0>>>2>>>0]=60*Math.max(a,o),T[t>>>0>>>2>>>0]=+(a!=o),e=r(i),t=r(s),e=re(e),t=re(t),o>>2>>>0]=e,S[n+4>>>2>>>0]=t):(S[n>>>2>>>0]=t,S[n+4>>>2>>>0]=e)},e:()=>{F("")},b:function(e,t,n){return e>>>=0,t=ie(t>>>0,n>>>0),j[e].apply(null,t)},i:function(e,t,n){return e>>>=0,t=ie(t>>>0,n>>>0),j[e].apply(null,t)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(e,t,n){return t>>>=0,x.copyWithin(e>>>0>>>0,t>>>0,t+(n>>>0)>>>0)},u:function(e){e>>>=0;var t=x.length;if(4294901760=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var a=Math;r=Math.max(e,r);e:{a=(a.min.call(a,4294901760,r+(65536-r%65536)%65536)-b.buffer.byteLength+65535)/65536;try{b.grow(a),E();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1},E:function(e,t){e>>>=0,t>>>=0;var n=0;return oe().forEach(((r,a)=>{var i=t+n;for(a=S[e+4*a>>>2>>>0]=i,i=0;i>>0>>>0]=r.charCodeAt(i);$[a>>>0>>>0]=0,n+=r.length+1})),0},F:function(e,t){e>>>=0,t>>>=0;var n=oe();S[e>>>2>>>0]=n.length;var r=0;return n.forEach((e=>r+=e.length+1)),S[t>>>2>>>0]=r,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(e,t,n,r){t>>>=0,n>>>=0,r>>>=0;for(var a=0,i=0;i>>2>>>0],o=S[t+4>>>2>>>0];t+=8;for(var l=0;l>>0],d=le[e];0===u||10===u?((1===e?w:y)(X(d,0)),d.length=0):d.push(u)}a+=o}return S[r>>>2>>>0]=a,0},v:pe,d:function(e,t,n,r){return pe(e>>>0,t>>>0,n>>>0,r>>>0)}},Ce=function(){function e(e){return Ce=e.exports,Ce=function(){var e=Ce,t={};for(let[n,r]of Object.entries(e))t[n]="function"==typeof r?function(){be.push(n);try{return r.apply(null,arguments)}finally{C||(be.pop(),_e&&1===fe&&0===be.length&&(fe=0,he(De),typeof Fibers<"u"&&Fibers.gb()))}}:r;return t}(),Ce=function(){var e=Ce;e=Object.assign({},e);var t=e=>()=>e()>>>0,n=e=>t=>e(t)>>>0;return e.pa=t(e.pa),e.qa=n(e.qa),e.ua=t(e.ua),e.wa=n(e.wa),e}(),b=Ce.M,E(),I.unshift(Ce.N),0==--O&&(null!==z&&(clearInterval(z),z=null),B&&(e=B,B=null,e())),Ce}var t={a:ke};if(O++,a.instantiateWasm)try{return a.instantiateWasm(t,e)}catch(e){y(`Module.instantiateWasm callback failed with error: ${e}`),r(e)}return function(e,t){var n=R;return"function"!=typeof WebAssembly.instantiateStreaming||D(n)||L(n)||f||"function"!=typeof fetch?V(n,e,t):fetch(n,{credentials:"same-origin"}).then((r=>WebAssembly.instantiateStreaming(r,e).then(t,(function(r){return y(`wasm streaming compile failed: ${r}`),y("falling back to ArrayBuffer instantiation"),V(n,e,t)}))))}(t,(function(t){e(t.instance)})).catch(r),{}}();a._OrtInit=(e,t)=>(a._OrtInit=Ce.O)(e,t),a._OrtGetLastError=(e,t)=>(a._OrtGetLastError=Ce.P)(e,t),a._OrtCreateSessionOptions=(e,t,n,r,i,s,o,l,u,d)=>(a._OrtCreateSessionOptions=Ce.Q)(e,t,n,r,i,s,o,l,u,d),a._OrtAppendExecutionProvider=(e,t)=>(a._OrtAppendExecutionProvider=Ce.R)(e,t),a._OrtAddFreeDimensionOverride=(e,t,n)=>(a._OrtAddFreeDimensionOverride=Ce.S)(e,t,n),a._OrtAddSessionConfigEntry=(e,t,n)=>(a._OrtAddSessionConfigEntry=Ce.T)(e,t,n),a._OrtReleaseSessionOptions=e=>(a._OrtReleaseSessionOptions=Ce.U)(e),a._OrtCreateSession=(e,t,n)=>(a._OrtCreateSession=Ce.V)(e,t,n),a._OrtReleaseSession=e=>(a._OrtReleaseSession=Ce.W)(e),a._OrtGetInputOutputCount=(e,t,n)=>(a._OrtGetInputOutputCount=Ce.X)(e,t,n),a._OrtGetInputName=(e,t)=>(a._OrtGetInputName=Ce.Y)(e,t),a._OrtGetOutputName=(e,t)=>(a._OrtGetOutputName=Ce.Z)(e,t),a._OrtFree=e=>(a._OrtFree=Ce._)(e),a._OrtCreateTensor=(e,t,n,r,i,s)=>(a._OrtCreateTensor=Ce.$)(e,t,n,r,i,s),a._OrtGetTensorData=(e,t,n,r,i)=>(a._OrtGetTensorData=Ce.aa)(e,t,n,r,i),a._OrtReleaseTensor=e=>(a._OrtReleaseTensor=Ce.ba)(e),a._OrtCreateRunOptions=(e,t,n,r)=>(a._OrtCreateRunOptions=Ce.ca)(e,t,n,r),a._OrtAddRunConfigEntry=(e,t,n)=>(a._OrtAddRunConfigEntry=Ce.da)(e,t,n),a._OrtReleaseRunOptions=e=>(a._OrtReleaseRunOptions=Ce.ea)(e),a._OrtCreateBinding=e=>(a._OrtCreateBinding=Ce.fa)(e),a._OrtBindInput=(e,t,n)=>(a._OrtBindInput=Ce.ga)(e,t,n),a._OrtBindOutput=(e,t,n,r)=>(a._OrtBindOutput=Ce.ha)(e,t,n,r),a._OrtClearBoundOutputs=e=>(a._OrtClearBoundOutputs=Ce.ia)(e),a._OrtReleaseBinding=e=>(a._OrtReleaseBinding=Ce.ja)(e),a._OrtRunWithBinding=(e,t,n,r,i)=>(a._OrtRunWithBinding=Ce.ka)(e,t,n,r,i),a._OrtRun=(e,t,n,r,i,s,o,l)=>(a._OrtRun=Ce.la)(e,t,n,r,i,s,o,l),a._OrtEndProfiling=e=>(a._OrtEndProfiling=Ce.ma)(e),a._JsepOutput=(e,t,n)=>(a._JsepOutput=Ce.na)(e,t,n),a._JsepGetNodeName=e=>(a._JsepGetNodeName=Ce.oa)(e);var Ee,Ae=()=>(Ae=Ce.pa)(),Ie=a._malloc=e=>(Ie=a._malloc=Ce.qa)(e),Pe=a._free=e=>(Pe=a._free=Ce.ra)(e),Oe=e=>(Oe=Ce.ta)(e),ze=()=>(ze=Ce.ua)(),Be=e=>(Be=Ce.va)(e),Fe=e=>(Fe=Ce.wa)(e),Re=e=>(Re=Ce.ya)(e),De=()=>(De=Ce.za)(),Le=e=>(Le=Ce.Aa)(e),Ne=()=>(Ne=Ce.Ba)();function Ue(){if(!(0J(e,x,t,n),a.lengthBytesUTF8=Z,B=function e(){Ee||Ue(),Ee||(B=e)},Ue(),e.ready});"object"==typeof e&&"object"==typeof t?t.exports=r:"function"==typeof define&&define.amd&&define([],(()=>r))})),be=N((()=>{})),ve=N((()=>{})),$e={};U($e,{cpus:()=>xe});var xe,Te,Se,Me,ke,Ce,Ee,Ae,Ie,Pe,Oe,ze,Be,Fe,Re,De,Le,Ne,Ue,We,Ve,Ge,je,qe,He,Ke,Ye,Xe,Qe,Ze,Je,et,tt,nt,rt,at,it,st,ot,lt,ut,dt,ct,pt,ht,ft,mt,gt,_t,wt,yt,bt,vt,$t,xt,Tt,St,Mt,kt,Ct,Et,At,It,Pt,Ot,zt,Bt,Ft,Rt,Dt,Lt,Nt,Ut,Wt,Vt,Gt,jt,qt,Ht,Kt,Yt,Xt,Qt,Zt,Jt,en,tn,nn,rn,an,sn,on,ln,un,dn,cn,pn,hn,fn,mn,gn,_n,wn,yn,bn,vn,$n,xn,Tn,Sn,Mn,kn,Cn,En,An,In,Pn,On,zn,Bn,Fn,Rn,Dn,Ln,Nn,Un,Wn,Vn,Gn,jn,qn,Hn,Kn,Yn,Xn,Qn,Zn,Jn,er,tr,nr,rr,ar,ir,sr,or,lr,ur,dr,cr,pr,hr,fr,mr,gr,_r,wr,yr,br,vr,$r,xr,Tr,Sr,Mr,kr,Cr,Er,Ar,Ir,Pr,Or,zr,Br,Fr,Rr,Dr,Lr,Nr,Ur,Wr,Vr,Gr,jr,qr,Hr,Kr,Yr,Xr,Qr,Zr,Jr,ea,ta,na,ra,aa,ia,sa,oa,la,ua,da,ca,pa,ha,fa,ma,ga,_a,wa,ya,ba,va,$a,xa,Ta,Sa,Ma,ka,Ca,Ea,Aa,Ia,Pa,Oa,za,Ba,Fa,Ra,Da,La,Na,Ua,Wa,Va,Ga,ja,qa,Ha,Ka,Ya,Xa,Qa,Za,Ja,ei,ti,ni,ri,ai,ii,si,oi,li,ui,di,ci,pi,hi,fi,mi,gi,_i,wi,yi,bi,vi,$i,xi,Ti,Si,Mi,ki,Ci,Ei,Ai,Ii,Pi,Oi,zi,Bi,Fi,Ri,Di,Li,Ni,Ui,Wi,Vi,Gi,ji,qi,Hi,Ki,Yi,Xi,Qi,Zi,Ji,es,ts,ns,rs,as,is,ss,os,ls,us,ds,cs,ps,hs,fs,ms,gs,_s,ws,ys,bs,vs,$s,xs,Ts,Ss,Ms,ks,Cs,Es,As,Is,Ps,Os,zs,Bs,Fs,Rs,Ds,Ls,Ns,Us,Ws,Vs,Gs,js,qs,Hs,Ks,Ys,Xs,Qs,Zs,Js,eo,to,no,ro,ao,io,so,oo,lo,uo,co,po,ho,fo,mo,go,_o,wo,yo,bo,vo,$o,xo,To,So,Mo,ko,Co,Eo,Ao,Io=L((()=>{xe=void 0})),Po=N(((e,t)=>{var n,r=(n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0,typeof __filename<"u"&&(n=n||__filename),function(e={}){function t(){return A.buffer!=O.buffer&&N(),O}function r(){return A.buffer!=O.buffer&&N(),z}function a(){return A.buffer!=O.buffer&&N(),B}function i(){return A.buffer!=O.buffer&&N(),F}function s(){return A.buffer!=O.buffer&&N(),R}function o(){return A.buffer!=O.buffer&&N(),D}var l,u,d=e;d.ready=new Promise(((e,t)=>{l=e,u=t})),d.mountExternalData=(e,t)=>{(d.cb||(d.cb=new Map)).set(e,t)},d.unmountExternalData=()=>{delete d.cb};let c=()=>{let e=(e,t,n)=>(...r)=>{let a=bt,i=t?.();r=e(...r);let s=t?.();return i!==s&&(e=s,n(i),t=n=null),bt!=a?new Promise(((e,t)=>{Mt={resolve:e,reject:t}})):r},t=e=>async(...t)=>{try{if(d.bb)throw Error("Session already started");let n=d.bb={Gb:t[0],errors:[]},r=await e(...t);if(d.bb!==n)throw Error("Session mismatch");d.kb?.flush();let a=n.errors;if(0e)),0d._OrtCreateSession),(e=>d._OrtCreateSession=e)),d._OrtRun=t(e(d._OrtRun,(()=>d._OrtRun),(e=>d._OrtRun=e))),d._OrtRunWithBinding=t(e(d._OrtRunWithBinding,(()=>d._OrtRunWithBinding),(e=>d._OrtRunWithBinding=e))),d._OrtBindInput=e(d._OrtBindInput,(()=>d._OrtBindInput),(e=>d._OrtBindInput=e)),c=void 0};d.jsepInit=(e,t)=>{if(c?.(),"webgpu"===e){[d.kb,d.xb,d.Bb,d.lb,d.Ab,d.Ea,d.Cb,d.Eb,d.yb,d.zb,d.Db]=t;let e=d.kb;d.jsepRegisterBuffer=(t,n,r,a)=>e.registerBuffer(t,n,r,a),d.jsepGetBuffer=t=>e.getBuffer(t),d.jsepCreateDownloader=(t,n,r)=>e.createDownloader(t,n,r),d.jsepOnReleaseSession=t=>{e.onReleaseSession(t)},d.jsepOnRunStart=t=>e.onRunStart(t)}};var p,h,f,m=Object.assign({},d),g="./this.program",_=(e,t)=>{throw t},w="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,v=d.ENVIRONMENT_IS_PTHREAD||!1,$="";function x(e){return d.locateFile?d.locateFile(e,$):$+e}if(b){var T=(me(),W(ce)),S=(we(),W(ge));let e;$=y?S.dirname($)+"/":__dirname+"/",p=(e,t)=>(e=J(e)?new URL(e):S.normalize(e),T.readFileSync(e,t?void 0:"utf8")),f=e=>((e=p(e,!0)).buffer||(e=new Uint8Array(e)),e),h=(e,t,n,r=!0)=>{e=J(e)?new URL(e):S.normalize(e),T.readFile(e,r?void 0:"utf8",((e,a)=>{e?n(e):t(r?a.buffer:a)}))},!d.thisProgram&&1{throw process.exitCode=e,t},d.inspect=()=>"[Emscripten Module object]";try{e=be()}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}global.Worker=e.Worker}else(w||y)&&(y?$=self.location.href:typeof document<"u"&&document.currentScript&&($=document.currentScript.src),typeof n<"u"&&n&&($=n),$=0!==$.indexOf("blob:")?$.substr(0,$.replace(/[?#].*/,"").lastIndexOf("/")+1):"",b||(p=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},y&&(f=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),h=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));b&&typeof performance>"u"&&(global.performance=ve().performance);var M=console.log.bind(console),k=console.error.bind(console);b&&(M=(...e)=>T.writeSync(1,e.join(" ")+"\n"),k=(...e)=>T.writeSync(2,e.join(" ")+"\n"));var C=M,E=k;Object.assign(d,m),m=null,"object"!=typeof WebAssembly&&X("no native wasm support detected");var A,I,P,O,z,B,F,R,D,L=!1;function N(){var e=A.buffer;d.HEAP8=O=new Int8Array(e),d.HEAP16=new Int16Array(e),d.HEAPU8=z=new Uint8Array(e),d.HEAPU16=new Uint16Array(e),d.HEAP32=B=new Int32Array(e),d.HEAPU32=F=new Uint32Array(e),d.HEAPF32=R=new Float32Array(e),d.HEAPF64=D=new Float64Array(e)}var U=16777216;if(v)A=d.wasmMemory;else if(d.wasmMemory)A=d.wasmMemory;else if(!((A=new WebAssembly.Memory({initial:U/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw E("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"),b&&E("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");N(),U=A.buffer.byteLength;var V=[],G=[],j=[],q=0,H=null,K=null;function Y(){if(0==--q&&(null!==H&&(clearInterval(H),H=null),K)){var e=K;K=null,e()}}function X(e){throw E(e="Aborted("+e+")"),L=!0,P=1,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),u(e),e}var Q,Z=e=>e.startsWith("data:application/octet-stream;base64,"),J=e=>e.startsWith("file://");function ee(e){if(f)return f(e);throw"both async and sync fetching of the wasm failed"}function te(e,t,n){return function(e){if(w||y){if("function"==typeof fetch&&!J(e))return fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((()=>ee(e)));if(h)return new Promise(((t,n)=>{h(e,(e=>t(new Uint8Array(e))),n)}))}return Promise.resolve().then((()=>ee(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(n,(e=>{E(`failed to asynchronously prepare wasm: ${e}`),X(e)}))}Z(Q="ort-wasm-simd-threaded.wasm")||(Q=x(Q));var ne,re={933148:(e,t,n,a)=>{if(typeof d>"u"||!d.cb)return 1;if((e=de(e>>>0)).startsWith("./")&&(e=e.substring(2)),!(e=d.cb.get(e)))return 2;if(a>>>=0,(t>>>=0)+(n>>>=0)>e.byteLength)return 3;try{return r().set(e.subarray(t,t+n),a>>>0),0}catch{return 4}},933649:()=>{d.yb()},933680:()=>{d.zb()},933709:()=>{d.Db()},933734:e=>d.xb(e),933767:e=>d.Bb(e),933799:(e,t,n)=>{d.lb(e,t,n,!0)},933838:(e,t,n)=>{d.lb(e,t,n)},933871:e=>{d.Ea("Abs",e,void 0)},933922:e=>{d.Ea("Neg",e,void 0)},933973:e=>{d.Ea("Floor",e,void 0)},934026:e=>{d.Ea("Ceil",e,void 0)},934078:e=>{d.Ea("Reciprocal",e,void 0)},934136:e=>{d.Ea("Sqrt",e,void 0)},934188:e=>{d.Ea("Exp",e,void 0)},934239:e=>{d.Ea("Erf",e,void 0)},934290:e=>{d.Ea("Sigmoid",e,void 0)},934345:(e,t,n)=>{d.Ea("HardSigmoid",e,{alpha:t,beta:n})},934424:e=>{d.Ea("Log",e,void 0)},934475:e=>{d.Ea("Sin",e,void 0)},934526:e=>{d.Ea("Cos",e,void 0)},934577:e=>{d.Ea("Tan",e,void 0)},934628:e=>{d.Ea("Asin",e,void 0)},934680:e=>{d.Ea("Acos",e,void 0)},934732:e=>{d.Ea("Atan",e,void 0)},934784:e=>{d.Ea("Sinh",e,void 0)},934836:e=>{d.Ea("Cosh",e,void 0)},934888:e=>{d.Ea("Asinh",e,void 0)},934941:e=>{d.Ea("Acosh",e,void 0)},934994:e=>{d.Ea("Atanh",e,void 0)},935047:e=>{d.Ea("Tanh",e,void 0)},935099:e=>{d.Ea("Not",e,void 0)},935150:(e,t,n)=>{d.Ea("Clip",e,{min:t,max:n})},935219:e=>{d.Ea("Clip",e,void 0)},935271:(e,t)=>{d.Ea("Elu",e,{alpha:t})},935329:e=>{d.Ea("Relu",e,void 0)},935381:(e,t)=>{d.Ea("LeakyRelu",e,{alpha:t})},935445:(e,t)=>{d.Ea("ThresholdedRelu",e,{alpha:t})},935515:(e,t)=>{d.Ea("Cast",e,{to:t})},935573:e=>{d.Ea("Add",e,void 0)},935624:e=>{d.Ea("Sub",e,void 0)},935675:e=>{d.Ea("Mul",e,void 0)},935726:e=>{d.Ea("Div",e,void 0)},935777:e=>{d.Ea("Pow",e,void 0)},935828:e=>{d.Ea("Equal",e,void 0)},935881:e=>{d.Ea("Greater",e,void 0)},935936:e=>{d.Ea("GreaterOrEqual",e,void 0)},935998:e=>{d.Ea("Less",e,void 0)},936050:e=>{d.Ea("LessOrEqual",e,void 0)},936109:(e,t,n,r,i)=>{d.Ea("ReduceMean",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},936268:(e,t,n,r,i)=>{d.Ea("ReduceMax",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},936426:(e,t,n,r,i)=>{d.Ea("ReduceMin",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},936584:(e,t,n,r,i)=>{d.Ea("ReduceProd",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},936743:(e,t,n,r,i)=>{d.Ea("ReduceSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},936901:(e,t,n,r,i)=>{d.Ea("ReduceL1",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},937058:(e,t,n,r,i)=>{d.Ea("ReduceL2",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},937215:(e,t,n,r,i)=>{d.Ea("ReduceLogSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},937376:(e,t,n,r,i)=>{d.Ea("ReduceSumSquare",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},937540:(e,t,n,r,i)=>{d.Ea("ReduceLogSumExp",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},937704:e=>{d.Ea("Where",e,void 0)},937757:(e,t,n)=>{d.Ea("Transpose",e,{perm:t?Array.from(a().subarray(t>>>0,n>>>0)):[]})},937865:(e,n,r,i,s,o,l,u,c,p,h,f,m,g,_)=>{d.Ea("ConvTranspose",e,{format:c?"NHWC":"NCHW",autoPad:n,dilations:[r],group:i,kernel_shape:[s],pads:[o,l],strides:[u],wIsConst:()=>!!t()[p>>>0],outputPadding:h?Array.from(a().subarray(h>>>0,f>>>0)):[],outputShape:m?Array.from(a().subarray(m>>>0,g>>>0)):[],activation:de(_)})},938267:(e,n,r,i,s,o,l,u,c,p,h,f,m,g)=>{d.Ea("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:n,dilations:Array.from(a().subarray(r>>>0,2+(r>>>0)>>>0)),group:i,kernelShape:Array.from(a().subarray(s>>>0,2+(s>>>0)>>>0)),pads:Array.from(a().subarray(o>>>0,4+(o>>>0)>>>0)),strides:Array.from(a().subarray(l>>>0,2+(l>>>0)>>>0)),wIsConst:()=>!!t()[c>>>0],outputPadding:p?Array.from(a().subarray(p>>>0,h>>>0)):[],outputShape:f?Array.from(a().subarray(f>>>0,m>>>0)):[],activation:de(g)})},938832:(e,n,r,i,s,o,l,u,c,p,h,f,m,g,_)=>{d.Ea("ConvTranspose",e,{format:c?"NHWC":"NCHW",autoPad:n,dilations:[r],group:i,kernel_shape:[s],pads:[o,l],strides:[u],wIsConst:()=>!!t()[p>>>0],outputPadding:h?Array.from(a().subarray(h>>>0,f>>>0)):[],outputShape:m?Array.from(a().subarray(m>>>0,g>>>0)):[],activation:de(_)})},939234:(e,n,r,i,s,o,l,u,c,p,h,f,m,g)=>{d.Ea("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:n,dilations:Array.from(a().subarray(r>>>0,2+(r>>>0)>>>0)),group:i,kernelShape:Array.from(a().subarray(s>>>0,2+(s>>>0)>>>0)),pads:Array.from(a().subarray(o>>>0,4+(o>>>0)>>>0)),strides:Array.from(a().subarray(l>>>0,2+(l>>>0)>>>0)),wIsConst:()=>!!t()[c>>>0],outputPadding:p?Array.from(a().subarray(p>>>0,h>>>0)):[],outputShape:f?Array.from(a().subarray(f>>>0,m>>>0)):[],activation:de(g)})},939799:(e,t)=>{d.Ea("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},939890:(e,t,n,r,a,i,s,o,l,u,c,p,h,f,m,g)=>{d.Ea("AveragePool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:a,dilations:[i,s],kernel_shape:[o,l],pads:[u,c,p,h],strides:[f,m]})},940174:(e,t)=>{d.Ea("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},940265:(e,t,n,r,a,i,s,o,l,u,c,p,h,f,m,g)=>{d.Ea("AveragePool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:a,dilations:[i,s],kernel_shape:[o,l],pads:[u,c,p,h],strides:[f,m]})},940549:(e,t)=>{d.Ea("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},940636:(e,t,n,r,a,i,s,o,l,u,c,p,h,f,m,g)=>{d.Ea("MaxPool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:a,dilations:[i,s],kernel_shape:[o,l],pads:[u,c,p,h],strides:[f,m]})},940916:(e,t)=>{d.Ea("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},941003:(e,t,n,r,a,i,s,o,l,u,c,p,h,f,m,g)=>{d.Ea("MaxPool",e,{format:g?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:a,dilations:[i,s],kernel_shape:[o,l],pads:[u,c,p,h],strides:[f,m]})},941283:(e,t,n,r,a)=>{d.Ea("Gemm",e,{alpha:t,beta:n,transA:r,transB:a})},941387:e=>{d.Ea("MatMul",e,void 0)},941441:(e,t,n,r)=>{d.Ea("ArgMax",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},941549:(e,t,n,r)=>{d.Ea("ArgMin",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},941657:(e,t)=>{d.Ea("Softmax",e,{axis:t})},941720:(e,t)=>{d.Ea("Concat",e,{axis:t})},941780:(e,t,n,r,i)=>{d.Ea("Split",e,{axis:t,numOutputs:n,splitSizes:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},941920:e=>{d.Ea("Expand",e,void 0)},941974:(e,t)=>{d.Ea("Gather",e,{axis:Number(t)})},942045:(e,t)=>{d.Ea("GatherElements",e,{axis:Number(t)})},942124:(e,t,n,r,i,s,o,l,u,c,p)=>{d.Ea("Resize",e,{antialias:t,axes:n?Array.from(a().subarray(n>>>0,r>>>0)):[],coordinateTransformMode:de(i),cubicCoeffA:s,excludeOutside:o,extrapolationValue:l,keepAspectRatioPolicy:de(u),mode:de(c),nearestMode:de(p)})},942470:(e,t,n,r,i,s,o)=>{d.Ea("Slice",e,{starts:t?Array.from(a().subarray(t>>>0,n>>>0)):[],ends:r?Array.from(a().subarray(r>>>0,i>>>0)):[],axes:s?Array.from(a().subarray(s>>>0,o>>>0)):[]})},942686:e=>{d.Ea("Tile",e,void 0)},942738:(e,t,n)=>{d.Ea("LayerNormalization",e,{axis:Number(t),epsilon:Number(n)})},942845:(e,t,n)=>{d.Ea("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},942959:(e,t,n)=>{d.Ea("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},943073:e=>{d.Ea("Range",e,void 0)},943126:(e,t)=>{d.Ea("Einsum",e,{equation:de(t)})},943207:(e,t,n,r,i)=>{d.Ea("Pad",e,{mode:t,value:n,pads:r?Array.from(a().subarray(r>>>0,i>>>0)):[]})},943334:(e,t,n,r,a,i)=>{d.Ea("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!a,trainingMode:!!r,format:i?"NHWC":"NCHW"})},943503:(e,t,n,r,a,i)=>{d.Ea("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!a,trainingMode:!!r,format:i?"NHWC":"NCHW"})},943672:(e,t,n)=>{d.Ea("CumSum",e,{exclusive:Number(t),reverse:Number(n)})},943769:(e,t,n,r,i,s,o,l,u)=>{d.Ea("Attention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:i,doRotary:s,qkvHiddenSizes:o?Array.from(a().subarray(Number(l)>>>0,Number(l)+o>>>0)):[],pastPresentShareBuffer:!!u})},944041:e=>{d.Ea("BiasAdd",e,void 0)},944096:e=>{d.Ea("BiasSplitGelu",e,void 0)},944157:e=>{d.Ea("FastGelu",e,void 0)},944213:(e,n,r,i,o,l,u,c,p,h,f,m,g)=>{d.Ea("Conv",e,{format:p?"NHWC":"NCHW",auto_pad:n,dilations:[r],group:i,kernel_shape:[o],pads:l?Array.from(a().subarray(l>>>0,u>>>0)):[],strides:[c],w_is_const:()=>!!t()[h>>>0],activation:de(f),activation_params:m?Array.from(s().subarray(m>>>0,g>>>0)):[]})},944583:(e,n,r,i,o,l,u,c,p,h,f,m,g,_,w,y)=>{d.Ea("Conv",e,{format:m?"NHWC":"NCHW",auto_pad:n,dilations:[r,i],group:o,kernel_shape:[l,u],pads:c?Array.from(a().subarray(c>>>0,p>>>0)):[],strides:[h,f],w_is_const:()=>!!t()[g>>>0],activation:de(_),activation_params:w?Array.from(s().subarray(w>>>0,y>>>0)):[]})},944974:e=>{d.Ea("Gelu",e,void 0)},945026:(e,t,n,r,a,i)=>{d.Ea("MatMulNBits",e,{k:t,n,accuracyLevel:r,bits:a,blockSize:i})},945153:(e,t,n,r,a,i)=>{d.Ea("MultiHeadAttention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:a,doRotary:i})},945312:(e,t)=>{d.Ea("SkipLayerNormalization",e,{epsilon:t})},945393:e=>{d.Cb(e)},945427:(e,t)=>d.Eb(e,t,d.bb.Gb,d.bb.errors)};function ae(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var ie=e=>{e.terminate(),e.onmessage=()=>{}},se=e=>{0==Se.Ya.length&&(Te(),Se.mb(Se.Ya[0]));var t=Se.Ya.pop();if(!t)return 6;Se.Za.push(t),Se.Qa[e.Xa]=t,t.Xa=e.Xa;var n={cmd:"run",start_routine:e.Hb,arg:e.ub,pthread_ptr:e.Xa};return b&&t.unref(),t.postMessage(n,e.Nb),0},oe=0,le=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ue=(e,t,n)=>{var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|s:(7&a)<<18|i<<12|s<<6|63&e[t++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r},de=(e,t)=>(e>>>=0)?ue(r(),e,t):"",pe=e=>{var t=Gt();return e=e(),jt(t),e};function he(e,t){var n=arguments.length-2,r=arguments;return pe((()=>{for(var a=qt(8*n),i=a>>>3,s=0;s>>0]=l}return Dt(e,n,a,t)}))}function fe(e){if(v)return he(0,1,e);P=e,0{if(P=e,v)throw ke(e),"unwind";fe(e)},ye=e=>{e instanceof ae||"unwind"==e||_(1,e)};function xe(){for(var e=d.numThreads;e--;)Te();V.unshift((()=>{q++,function(e){v?e():Promise.all(Se.Ya.map(Se.mb)).then(e)}((()=>Y()))}))}function Te(){var e=x("ort-wasm-simd-threaded.worker.js");e=new Worker(e),Se.Ya.push(e)}var Se={Ya:[],Za:[],qb:[],Qa:{},hb(){v?(Se.receiveObjectTransfer=Se.Fb,Se.threadInitTLS=Se.pb,Se.setExitStatus=Se.ob):xe()},ob:e=>P=e,Qb:["$terminateWorker"],Ib:()=>{for(var e of Se.Za)ie(e);for(e of Se.Ya)ie(e);Se.Ya=[],Se.Za=[],Se.Qa=[]},nb:e=>{var t=e.Xa;delete Se.Qa[t],Se.Ya.push(e),Se.Za.splice(Se.Za.indexOf(e),1),e.Xa=0,Lt(t)},Fb(){},pb(){Se.qb.forEach((e=>e()))},mb:e=>new Promise((t=>{e.onmessage=n=>{var r=(n=n.data).cmd;if(n.targetThread&&n.targetThread!=Ot()){var a=Se.Qa[n.targetThread];a?a.postMessage(n,n.transferList):E(`Internal error! Worker sent a message "${r}" to target pthread ${n.targetThread}, but that thread no longer exists!`)}else"checkMailbox"===r?Ye():"spawnThread"===r?se(n):"cleanupThread"===r?Se.nb(Se.Qa[n.thread]):"killThread"===r?(n=n.thread,r=Se.Qa[n],delete Se.Qa[n],ie(r),Lt(n),Se.Za.splice(Se.Za.indexOf(r),1),r.Xa=0):"cancelThread"===r?Se.Qa[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=!0,b&&!e.Xa&&e.unref(),t(e)):"alert"===r?alert(`Thread ${n.threadId}: ${n.text}`):"setimmediate"===n.target?e.postMessage(n):"callHandler"===r?d[n.handler](...n.args):r&&E(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw E(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e},b&&(e.on("message",(t=>e.onmessage({data:t}))),e.on("error",(t=>e.onerror(t))));var r,a=[];for(r of["onExit"])d.hasOwnProperty(r)&&a.push(r);e.postMessage({cmd:"load",handlers:a,urlOrBlob:d.mainScriptUrlOrBlob||n,wasmMemory:A,wasmModule:I})}))};d.PThread=Se;var Me=e=>{for(;0>>2>>>0]=e},this.sb=function(e){i()[this.gb+8>>>2>>>0]=e},this.hb=function(e,t){this.rb(),this.tb(e),this.sb(t)},this.rb=function(){i()[this.gb+16>>>2>>>0]=0}}function Ee(e,t,n,r){return v?he(2,1,e,t,n,r):Ae(e,t,n,r)}function Ae(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,typeof SharedArrayBuffer>"u")return E("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return v&&0===a.length?Ee(e,t,n,r):(e={Hb:n,Xa:e,ub:r,Nb:a},v?(e.Pb="spawnThread",postMessage(e,a),0):se(e))}function Ie(e,t,n){return v?he(3,1,e,t,n):0}function Pe(e,t){if(v)return he(4,1,e,t)}d.establishStackSpace=()=>{var e=Ot(),t=i()[e+52>>>2>>>0];e=i()[e+56>>>2>>>0],Vt(t,t-e),jt(t)},d.invokeEntryPoint=(e,t)=>{e=Ht.apply(null,[e,t]),0{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t},ze=(e,t,n,r)=>{if(!(0>>=0;r=n+r-1;for(var i=0;i=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-a},Be=(e,t,n)=>ze(e,r(),t,n);function Fe(e,t){if(v)return he(5,1,e,t)}function Re(e,t,n){if(v)return he(6,1,e,t,n)}function De(e,t,n){return v?he(7,1,e,t,n):0}function Le(e,t){if(v)return he(8,1,e,t)}function Ne(e,t,n){if(v)return he(9,1,e,t,n)}function Ue(e,t,n,r){if(v)return he(10,1,e,t,n,r)}function We(e,t,n,r){if(v)return he(11,1,e,t,n,r)}function Ve(e,t,n,r){if(v)return he(12,1,e,t,n,r)}function Ge(e){if(v)return he(13,1,e)}function je(e,t){if(v)return he(14,1,e,t)}function qe(e,t,n){if(v)return he(15,1,e,t,n)}var He=()=>{if(!(0>>=0,"function"==typeof Atomics.Ob&&(Atomics.Ob(a(),e>>>2,e).value.then(Ye),e+=128,Atomics.store(a(),e>>>2,1))}d.__emscripten_thread_mailbox_await=Ke;var Ye=()=>{var e=Ot();if(e&&(Ke(e),!L))try{Ut(),He()}catch(e){ye(e)}};d.checkMailbox=Ye;var Xe=[],Qe=e=>e%4==0&&(e%100!=0||e%400==0),Ze=[0,31,60,91,121,152,182,213,244,274,305,335],Je=[0,31,59,90,120,151,181,212,243,273,304,334];function et(e,t,n,r,a,i,s,o){return v?he(16,1,e,t,n,r,a,i,s,o):-52}function tt(e,t,n,r,a,i,s){if(v)return he(17,1,e,t,n,r,a,i,s)}var nt,rt=e=>{var t=Oe(e)+1,n=zt(t);return n&&Be(e,n,t),n},at=[],it=(e,t)=>{at.length=0;for(var n;n=r()[e++>>>0];){var s=105!=n;t+=(s&=112!=n)&&t%8?4:0,at.push(112==n?i()[t>>>2>>>0]:105==n?a()[t>>>2>>>0]:o()[t>>>3>>>0]),t+=s?8:4}return at},st={},ot=()=>{if(!nt){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:g||"./this.program"};for(e in st)void 0===st[e]?delete t[e]:t[e]=st[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);nt=n}return nt};function lt(e,n){if(v)return he(18,1,e,n);e>>>=0,n>>>=0;var r=0;return ot().forEach(((a,s)=>{var o=n+r;for(s=i()[e+4*s>>>2>>>0]=o,o=0;o>>0>>>0]=a.charCodeAt(o);t()[s>>>0>>>0]=0,r+=a.length+1})),0}function ut(e,t){if(v)return he(19,1,e,t);e>>>=0,t>>>=0;var n=ot();i()[e>>>2>>>0]=n.length;var r=0;return n.forEach((e=>r+=e.length+1)),i()[t>>>2>>>0]=r,0}function dt(e){return v?he(20,1,e):52}function ct(e,t,n,r){return v?he(21,1,e,t,n,r):52}function pt(e,t,n,r,a){return v?he(22,1,e,t,n,r,a):70}var ht=[null,[],[]];function ft(e,t,n,a){if(v)return he(23,1,e,t,n,a);t>>>=0,n>>>=0,a>>>=0;for(var s=0,o=0;o>>2>>>0],u=i()[t+4>>>2>>>0];t+=8;for(var d=0;d>>0],p=ht[e];0===c||10===c?((1===e?C:E)(ue(p,0)),p.length=0):p.push(c)}s+=u}return i()[a>>>2>>>0]=s,0}var mt=[31,29,31,30,31,30,31,31,30,31,30,31],gt=[31,28,31,30,31,30,31,31,30,31,30,31];function _t(e,n,r,s){function o(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.lengthe?-1:0r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=d(new Date(e.getFullYear(),0,4)),n=d(n),0>=u(t,e)?0>=u(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}e>>>=0,n>>>=0,r>>>=0,s>>>=0;var p=i()[s+40>>>2>>>0];for(var h in s={Lb:a()[s>>>2>>>0],Kb:a()[s+4>>>2>>>0],eb:a()[s+8>>>2>>>0],jb:a()[s+12>>>2>>>0],fb:a()[s+16>>>2>>>0],ab:a()[s+20>>>2>>>0],Wa:a()[s+24>>>2>>>0],$a:a()[s+28>>>2>>>0],Rb:a()[s+32>>>2>>>0],Jb:a()[s+36>>>2>>>0],Mb:p?de(p):""},r=de(r),p={"%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"})r=r.replace(new RegExp(h,"g"),p[h]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),m="January February March April May June July August September October November December".split(" ");for(h in p={"%a":e=>f[e.Wa].substring(0,3),"%A":e=>f[e.Wa],"%b":e=>m[e.fb].substring(0,3),"%B":e=>m[e.fb],"%C":e=>l((e.ab+1900)/100|0,2),"%d":e=>l(e.jb,2),"%e":e=>o(e.jb,2," "),"%g":e=>c(e).toString().substring(2),"%G":e=>c(e),"%H":e=>l(e.eb,2),"%I":e=>(0==(e=e.eb)?e=12:12{for(var t=0,n=0;n<=e.fb-1;t+=(Qe(e.ab+1900)?mt:gt)[n++]);return l(e.jb+t,3)},"%m":e=>l(e.fb+1,2),"%M":e=>l(e.Kb,2),"%n":()=>"\n","%p":e=>0<=e.eb&&12>e.eb?"AM":"PM","%S":e=>l(e.Lb,2),"%t":()=>"\t","%u":e=>e.Wa||7,"%U":e=>l(Math.floor((e.$a+7-e.Wa)/7),2),"%V":e=>{var t=Math.floor((e.$a+7-(e.Wa+6)%7)/7);if(2>=(e.Wa+371-e.$a-2)%7&&t++,t)53==t&&(4==(n=(e.Wa+371-e.$a)%7)||3==n&&Qe(e.ab)||(t=1));else{t=52;var n=(e.Wa+7-e.$a-1)%7;(4==n||5==n&&Qe(e.ab%400-1))&&t++}return l(t,2)},"%w":e=>e.Wa,"%W":e=>l(Math.floor((e.$a+7-(e.Wa+6)%7)/7),2),"%y":e=>(e.ab+1900).toString().substring(2),"%Y":e=>e.ab+1900,"%z":e=>(0<=(e=e.Jb)?"+":"-")+("0000"+((e=Math.abs(e)/60)/60*100+e%60)).slice(-4),"%Z":e=>e.Mb,"%%":()=>"%"},r=r.replace(/%%/g,"\0\0"),p)r.includes(h)&&(r=r.replace(new RegExp(h,"g"),p[h](s)));return h=function(e){var t=Array(Oe(e)+1);return ze(e,t,0,t.length),t}(r=r.replace(/\0\0/g,"%")),h.length>n?0:(((e,n)=>{t().set(e,n>>>0)})(h,e),h.length-1)}var wt=e=>{try{e()}catch(e){X(e)}},yt=0,bt=null,vt=0,$t=[],xt={},Tt={},St=0,Mt=null,kt=[];function Ct(e){if(!L){if(0===yt){var t=!1,n=!1;e(((e=0)=>{if(!L&&(vt=e,t=!0,n)){yt=2,wt((()=>Xt(bt))),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.resume(),e=!1;try{var r=function(){var e=a()[bt+8>>>2>>>0];return e=It[Tt[e]],--oe,e()}()}catch(t){r=t,e=!0}var i=!1;if(!bt){var s=Mt;s&&(Mt=null,(e?s.reject:s.resolve)(r),i=!0)}if(e&&!i)throw r}})),n=!0,t||(yt=1,bt=function(){var e=zt(65548),t=e+12;i()[e>>>2>>>0]=t,i()[e+4>>>2>>>0]=t+65536,t=$t[0];var n=xt[t];return void 0===n&&(n=St++,xt[t]=n,Tt[n]=t),t=n,a()[e+8>>>2>>>0]=t,e}(),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.pause(),wt((()=>Kt(bt))))}else 2===yt?(yt=0,wt(Qt),Bt(bt),bt=null,kt.forEach((e=>{if(!L)try{e(),He()}catch(e){ye(e)}}))):X(`invalid state: ${yt}`);return vt}}Se.hb();var Et=[fe,ke,Ee,Ie,Pe,Fe,Re,De,Le,Ne,Ue,We,Ve,Ge,je,qe,et,tt,lt,ut,dt,ct,pt,ft],At={r:function(e,t,n){return function(e){return Ct((t=>{e().then(t)}))}((async()=>{await d.Ab(e,t,n)}))},b:function(e,t,n){throw new Ce(e>>>=0).hb(t>>>0,n>>>0),e},N:function(e){Ft(e>>>0,!y,1,!w,131072,!1),Se.pb()},l:function(e){e>>>=0,v?postMessage({cmd:"cleanupThread",thread:e}):Se.nb(Se.Qa[e])},J:Ae,i:Ie,T:Pe,F:Fe,H:Re,U:De,R:Le,L:Ne,Q:Ue,p:We,G:Ve,D:Ge,S:je,E:qe,q:()=>1,B:function(e,t){(e>>>=0)==t>>>0?setTimeout((()=>Ye())):v?postMessage({targetThread:e,cmd:"checkMailbox"}):(e=Se.Qa[e])&&e.postMessage({cmd:"checkMailbox"})},K:function(e,t,n,r){t>>>=0,Xe.length=n,r=r>>>0>>>3;for(var a=0;a>>0];return e=0>e?re[-e-1]:Et[e],Se.vb=t,t=e.apply(null,Xe),Se.vb=0,t},M:Ke,W:function(e){b&&Se.Qa[e>>>0].ref()},u:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),a()[n>>>2>>>0]=e.getUTCSeconds(),a()[n+4>>>2>>>0]=e.getUTCMinutes(),a()[n+8>>>2>>>0]=e.getUTCHours(),a()[n+12>>>2>>>0]=e.getUTCDate(),a()[n+16>>>2>>>0]=e.getUTCMonth(),a()[n+20>>>2>>>0]=e.getUTCFullYear()-1900,a()[n+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[n+28>>>2>>>0]=e},v:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),a()[n>>>2>>>0]=e.getSeconds(),a()[n+4>>>2>>>0]=e.getMinutes(),a()[n+8>>>2>>>0]=e.getHours(),a()[n+12>>>2>>>0]=e.getDate(),a()[n+16>>>2>>>0]=e.getMonth(),a()[n+20>>>2>>>0]=e.getFullYear()-1900,a()[n+24>>>2>>>0]=e.getDay(),t=(Qe(e.getFullYear())?Ze:Je)[e.getMonth()]+e.getDate()-1|0,a()[n+28>>>2>>>0]=t,a()[n+36>>>2>>>0]=-60*e.getTimezoneOffset(),t=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(t!=r&&e.getTimezoneOffset()==Math.min(r,t)),a()[n+32>>>2>>>0]=e},w:function(e){e>>>=0;var t=new Date(a()[e+20>>>2>>>0]+1900,a()[e+16>>>2>>>0],a()[e+12>>>2>>>0],a()[e+8>>>2>>>0],a()[e+4>>>2>>>0],a()[e>>>2>>>0],0),n=a()[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(s,i);return 0>n?a()[e+32>>>2>>>0]=+(i!=s&&o==r):0>>2>>>0]=t.getDay(),n=(Qe(t.getFullYear())?Ze:Je)[t.getMonth()]+t.getDate()-1|0,a()[e+28>>>2>>>0]=n,a()[e>>>2>>>0]=t.getSeconds(),a()[e+4>>>2>>>0]=t.getMinutes(),a()[e+8>>>2>>>0]=t.getHours(),a()[e+12>>>2>>>0]=t.getDate(),a()[e+16>>>2>>>0]=t.getMonth(),a()[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),isNaN(e)?(a()[Pt()>>>2>>>0]=61,e=-1):e/=1e3,Wt((ne=e,1<=+Math.abs(ne)?0>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)),e>>>0},s:et,t:tt,A:function(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}e>>>=0,t>>>=0,n>>>=0;var s=(new Date).getFullYear(),o=new Date(s,0,1),l=new Date(s,6,1);s=o.getTimezoneOffset();var u=l.getTimezoneOffset(),d=Math.max(s,u);i()[e>>>2>>>0]=60*d,a()[t>>>2>>>0]=+(s!=u),e=r(o),t=r(l),e=rt(e),t=rt(t),u>>2>>>0]=e,i()[n+4>>>2>>>0]=t):(i()[n>>>2>>>0]=t,i()[n+4>>>2>>>0]=e)},d:()=>{X("")},c:function(e,t,n){return e>>>=0,t=it(t>>>0,n>>>0),re[e].apply(null,t)},k:function(e,t,n){return e>>>=0,t=it(t>>>0,n>>>0),re[e].apply(null,t)},m:()=>{},j:()=>Date.now(),V:()=>{throw oe+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>b?(Io(),W($e)).cpus().length:navigator.hardwareConcurrency,y:function(e){e>>>=0;var t=r().length;if(e<=t||4294901760=n;n*=2){var a=t*(1+.2/n);a=Math.min(a,e+100663296);var i=Math;a=Math.max(e,a);e:{i=(i.min.call(i,4294901760,a+(65536-a%65536)%65536)-A.buffer.byteLength+65535)/65536;try{A.grow(i),N();var s=1;break e}catch{}s=void 0}if(s)return!0}return!1},O:lt,P:ut,I:_e,h:dt,o:ct,x:pt,n:ft,a:A||d.wasmMemory,z:_t,e:function(e,t,n,r){return _t(e>>>0,t>>>0,n>>>0,r>>>0)}},It=function(){function e(e,t){return It=e.exports,It=function(){var e=It,t={};for(let[n,r]of Object.entries(e))t[n]="function"==typeof r?function(){$t.push(n);try{return r.apply(null,arguments)}finally{L||($t.pop(),bt&&1===yt&&0===$t.length&&(yt=0,oe+=1,wt(Yt),typeof Fibers<"u"&&Fibers.Sb()))}}:r;return t}(),It=function(){var e=It;e=Object.assign({},e);var t=e=>()=>e()>>>0,n=e=>t=>e(t)>>>0;return e.za=t(e.za),e.Aa=t(e.Aa),e.Ba=n(e.Ba),e.emscripten_main_runtime_thread_id=t(e.emscripten_main_runtime_thread_id),e.Na=t(e.Na),e.Pa=n(e.Pa),e}(),Se.qb.push(It.Da),G.unshift(It.X),I=t,Y(),It}var t={a:At};if(q++,d.instantiateWasm)try{return d.instantiateWasm(t,e)}catch(e){E(`Module.instantiateWasm callback failed with error: ${e}`),u(e)}return function(e,t){var n=Q;return"function"!=typeof WebAssembly.instantiateStreaming||Z(n)||J(n)||b||"function"!=typeof fetch?te(n,e,t):fetch(n,{credentials:"same-origin"}).then((r=>WebAssembly.instantiateStreaming(r,e).then(t,(function(r){return E(`wasm streaming compile failed: ${r}`),E("falling back to ArrayBuffer instantiation"),te(n,e,t)}))))}(t,(function(t){e(t.instance,t.module)})).catch(u),{}}();d._OrtInit=(e,t)=>(d._OrtInit=It.Y)(e,t),d._OrtGetLastError=(e,t)=>(d._OrtGetLastError=It.Z)(e,t),d._OrtCreateSessionOptions=(e,t,n,r,a,i,s,o,l,u)=>(d._OrtCreateSessionOptions=It._)(e,t,n,r,a,i,s,o,l,u),d._OrtAppendExecutionProvider=(e,t)=>(d._OrtAppendExecutionProvider=It.$)(e,t),d._OrtAddFreeDimensionOverride=(e,t,n)=>(d._OrtAddFreeDimensionOverride=It.aa)(e,t,n),d._OrtAddSessionConfigEntry=(e,t,n)=>(d._OrtAddSessionConfigEntry=It.ba)(e,t,n),d._OrtReleaseSessionOptions=e=>(d._OrtReleaseSessionOptions=It.ca)(e),d._OrtCreateSession=(e,t,n)=>(d._OrtCreateSession=It.da)(e,t,n),d._OrtReleaseSession=e=>(d._OrtReleaseSession=It.ea)(e),d._OrtGetInputOutputCount=(e,t,n)=>(d._OrtGetInputOutputCount=It.fa)(e,t,n),d._OrtGetInputName=(e,t)=>(d._OrtGetInputName=It.ga)(e,t),d._OrtGetOutputName=(e,t)=>(d._OrtGetOutputName=It.ha)(e,t),d._OrtFree=e=>(d._OrtFree=It.ia)(e),d._OrtCreateTensor=(e,t,n,r,a,i)=>(d._OrtCreateTensor=It.ja)(e,t,n,r,a,i),d._OrtGetTensorData=(e,t,n,r,a)=>(d._OrtGetTensorData=It.ka)(e,t,n,r,a),d._OrtReleaseTensor=e=>(d._OrtReleaseTensor=It.la)(e),d._OrtCreateRunOptions=(e,t,n,r)=>(d._OrtCreateRunOptions=It.ma)(e,t,n,r),d._OrtAddRunConfigEntry=(e,t,n)=>(d._OrtAddRunConfigEntry=It.na)(e,t,n),d._OrtReleaseRunOptions=e=>(d._OrtReleaseRunOptions=It.oa)(e),d._OrtCreateBinding=e=>(d._OrtCreateBinding=It.pa)(e),d._OrtBindInput=(e,t,n)=>(d._OrtBindInput=It.qa)(e,t,n),d._OrtBindOutput=(e,t,n,r)=>(d._OrtBindOutput=It.ra)(e,t,n,r),d._OrtClearBoundOutputs=e=>(d._OrtClearBoundOutputs=It.sa)(e),d._OrtReleaseBinding=e=>(d._OrtReleaseBinding=It.ta)(e),d._OrtRunWithBinding=(e,t,n,r,a)=>(d._OrtRunWithBinding=It.ua)(e,t,n,r,a),d._OrtRun=(e,t,n,r,a,i,s,o)=>(d._OrtRun=It.va)(e,t,n,r,a,i,s,o),d._OrtEndProfiling=e=>(d._OrtEndProfiling=It.wa)(e),d._JsepOutput=(e,t,n)=>(d._JsepOutput=It.xa)(e,t,n),d._JsepGetNodeName=e=>(d._JsepGetNodeName=It.ya)(e);var Pt=()=>(Pt=It.za)(),Ot=d._pthread_self=()=>(Ot=d._pthread_self=It.Aa)(),zt=d._malloc=e=>(zt=d._malloc=It.Ba)(e),Bt=d._free=e=>(Bt=d._free=It.Ca)(e);d.__emscripten_tls_init=()=>(d.__emscripten_tls_init=It.Da)();var Ft=d.__emscripten_thread_init=(e,t,n,r,a,i)=>(Ft=d.__emscripten_thread_init=It.Fa)(e,t,n,r,a,i);d.__emscripten_thread_crashed=()=>(d.__emscripten_thread_crashed=It.Ga)();var Rt,Dt=(e,t,n,r)=>(Dt=It.Ha)(e,t,n,r),Lt=e=>(Lt=It.Ia)(e),Nt=d.__emscripten_thread_exit=e=>(Nt=d.__emscripten_thread_exit=It.Ja)(e),Ut=()=>(Ut=It.Ka)(),Wt=e=>(Wt=It.La)(e),Vt=(e,t)=>(Vt=It.Ma)(e,t),Gt=()=>(Gt=It.Na)(),jt=e=>(jt=It.Oa)(e),qt=e=>(qt=It.Pa)(e),Ht=d.dynCall_ii=(e,t)=>(Ht=d.dynCall_ii=It.Ra)(e,t),Kt=e=>(Kt=It.Sa)(e),Yt=()=>(Yt=It.Ta)(),Xt=e=>(Xt=It.Ua)(e),Qt=()=>(Qt=It.Va)();function Zt(){if(!(00r))})),Oo=N(((e,t)=>{t.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\n'})),zo=L((()=>{Te=ye(),Se=Po(),ke=!1,Ce=!1,Ee=!1,Ae=e=>{if(1===e)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");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}},Ie=()=>{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}},Pe=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Oe=async e=>{if(ke)return Promise.resolve();if(Ce)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ee)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ce=!0;let t=e.initTimeout,n=e.numThreads,r=e.simd,a=Ae(n),i=r&&Ie(),s=e.wasmPaths,o="string"==typeof s?s:void 0,l=Pe(i,a),u="object"==typeof s?s[l]:void 0,d=!1,c=[];if(t>0&&c.push(new Promise((e=>{setTimeout((()=>{d=!0,e()}),t)}))),c.push(new Promise(((e,t)=>{let r=a?Se:Te,i={locateFile:(e,t)=>{if(a&&e.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Oo()],{type:"text/javascript"}));if(e.endsWith(".wasm")){if(u)return u;let e=o??t;return"ort-wasm-simd.wasm"===l?e+"ort-wasm-simd.jsep.wasm":"ort-wasm-simd-threaded.wasm"===l?e+"ort-wasm-simd-threaded.jsep.wasm":e+l}return t+e}};if(a)if(i.numThreads=n,typeof Blob>"u")i.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let e=`var ortWasmThreaded=${r.toString()};`;i.mainScriptUrlOrBlob=new Blob([e],{type:"text/javascript"})}r(i).then((t=>{Ce=!1,ke=!0,Me=t,e()}),(e=>{Ce=!1,Ee=!0,t(e)}))}))),await Promise.race(c),d)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if(ke&&Me)return Me;throw new Error("WebAssembly is not initialized yet.")}})),Bo=L((()=>{zo(),Be=(e,t)=>{let n=ze(),r=n.lengthBytesUTF8(e)+1,a=n._malloc(r);return n.stringToUTF8(e,a,r),t.push(a),a},Fe=(e,t,n,r)=>{if("object"==typeof e&&null!==e){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach((([e,a])=>{let i=t?t+e:e;if("object"==typeof a)Fe(a,i+".",n,r);else if("string"==typeof a||"number"==typeof a)r(i,a.toString());else{if("boolean"!=typeof a)throw new Error("Can't handle extra config type: "+typeof a);r(i,a?"1":"0")}}))},Re=e=>{let t=ze(),n=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let r=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],i=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${r}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(n)}}})),Fo=L((()=>{zo(),Bo(),De=e=>{let t=ze(),n=0,r=[],a=e||{};try{if(void 0===e?.logSeverityLevel)a.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===e?.logVerbosityLevel)a.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===e?.terminate&&(a.terminate=!1);let i=0;return void 0!==e?.tag&&(i=Be(e.tag,r)),n=t._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,i),0===n&&Re("Can't create run options."),void 0!==e?.extra&&Fe(e.extra,"",new WeakSet,((e,a)=>{let i=Be(e,r),s=Be(a,r);0!==t._OrtAddRunConfigEntry(n,i,s)&&Re(`Can't set a run config entry: ${e} - ${a}.`)})),[n,r]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),r.forEach((e=>t._free(e))),e}}})),Ro=L((()=>{zo(),Bo(),Le=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}`)}},Ne=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ue=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((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)},We=(e,t,n)=>{for(let r of t){let t="string"==typeof r?r:r.name;switch(t){case"webnn":if(t="WEBNN","string"!=typeof r){let t=r;if(t?.deviceType){let r=Be("deviceType",n),a=Be(t.deviceType,n);0!==ze()._OrtAddSessionConfigEntry(e,r,a)&&Re(`Can't set a session config entry: 'deviceType' - ${t.deviceType}.`)}if(t?.numThreads){let r=t.numThreads;("number"!=typeof r||!Number.isInteger(r)||r<0)&&(r=0);let a=Be("numThreads",n),i=Be(r.toString(),n);0!==ze()._OrtAddSessionConfigEntry(e,a,i)&&Re(`Can't set a session config entry: 'numThreads' - ${t.numThreads}.`)}if(t?.powerPreference){let r=Be("powerPreference",n),a=Be(t.powerPreference,n);0!==ze()._OrtAddSessionConfigEntry(e,r,a)&&Re(`Can't set a session config entry: 'powerPreference' - ${t.powerPreference}.`)}}break;case"webgpu":if(t="JS","string"!=typeof r){let t=r;if(t?.preferredLayout){if("NCHW"!==t.preferredLayout&&"NHWC"!==t.preferredLayout)throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${t.preferredLayout}`);let r=Be("preferredLayout",n),a=Be(t.preferredLayout,n);0!==ze()._OrtAddSessionConfigEntry(e,r,a)&&Re(`Can't set a session config entry: 'preferredLayout' - ${t.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${t}`)}let a=Be(t,n);0!==ze()._OrtAppendExecutionProvider(e,a)&&Re(`Can't append execution provider: ${t}.`)}},Ve=e=>{let t=ze(),n=0,r=[],a=e||{};Ue(a);try{let e=Le(a.graphOptimizationLevel??"all"),i=Ne(a.executionMode??"sequential"),s="string"==typeof a.logId?Be(a.logId,r):0,o=a.logSeverityLevel??2;if(!Number.isInteger(o)||o<0||o>4)throw new Error(`log serverity level is not valid: ${o}`);let l=a.logVerbosityLevel??0;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log verbosity level is not valid: ${l}`);let u="string"==typeof a.optimizedModelFilePath?Be(a.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!a.enableCpuMemArena,!!a.enableMemPattern,i,!!a.enableProfiling,0,s,o,l,u),0===n&&Re("Can't create session options."),a.executionProviders&&We(n,a.executionProviders,r),void 0!==a.enableGraphCapture){if("boolean"!=typeof a.enableGraphCapture)throw new Error(`enableGraphCapture must be a boolean value: ${a.enableGraphCapture}`);let e=Be("enableGraphCapture",r),i=Be(a.enableGraphCapture.toString(),r);0!==t._OrtAddSessionConfigEntry(n,e,i)&&Re(`Can't set a session config entry: 'enableGraphCapture' - ${a.enableGraphCapture}.`)}if(a.freeDimensionOverrides)for(let[e,i]of Object.entries(a.freeDimensionOverrides)){if("string"!=typeof e)throw new Error(`free dimension override name must be a string: ${e}`);if("number"!=typeof i||!Number.isInteger(i)||i<0)throw new Error(`free dimension override value must be a non-negative integer: ${i}`);let a=Be(e,r);0!==t._OrtAddFreeDimensionOverride(n,a,i)&&Re(`Can't set a free dimension override: ${e} - ${i}.`)}return void 0!==a.extra&&Fe(a.extra,"",new WeakSet,((e,a)=>{let i=Be(e,r),s=Be(a,r);0!==t._OrtAddSessionConfigEntry(n,i,s)&&Re(`Can't set a session config entry: ${e} - ${a}.`)})),[n,r]}catch(e){throw 0!==n&&t._OrtReleaseSessionOptions(n),r.forEach((e=>t._free(e))),e}}})),Do=L((()=>{Ge=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;default:throw new Error(`unsupported data type: ${e}`)}},je=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";default:throw new Error(`unsupported data type: ${e}`)}},qe=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],He=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ke=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}`)}},Ye=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint8"===e||"bool"===e,Xe=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}})),Lo=L((()=>{Qe=async e=>{if("string"!=typeof e)return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e);if(!(typeof process<"u"&&process.versions&&process.versions.node)){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n,a=t.body.getReader();try{n=new ArrayBuffer(r)}catch(e){if(!(e instanceof RangeError))throw e;{let e=Math.ceil(r/65536);n=new WebAssembly.Memory({initial:e,maximum:e}).buffer}}let i=0;for(;;){let{done:e,value:t}=await a.read();if(e)break;let r=t.byteLength;new Uint8Array(n,i,r).set(t),i+=r}return new Uint8Array(n,0,r)}}try{return new Uint8Array(await(void 0)(e))}catch(t){if("ERR_FS_FILE_TOO_LARGE"===t.code){let t=(void 0)(e),n=[];for await(let e of t)n.push(e);return new Uint8Array(Buffer.concat(n))}throw t}}})),No=L((()=>{Do(),Ze=["V","I","W","E","F"],Je=(e,t)=>{console.log(`[${Ze[e]},${(new Date).toISOString()}]${t}`)},nt=(e,t)=>{et=e,tt=t},rt=(e,t)=>{let n=Ke(e);n>=Ke(et)&&Je(n,"function"==typeof t?t():t)},at=(...e)=>{tt&&rt(...e)}})),Uo=L((()=>{Do(),it=(e,t)=>new(He(t))(e)})),Wo=L((()=>{})),Vo=L((()=>{No(),Wo(),st=e=>16*Math.ceil(e/16),ot=1,lt=()=>ot++,ut=async(e,t,n,r)=>{let a=st(n),i=e.device.createBuffer({size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=e.getCommandEncoder();e.endComputePass(),s.copyBufferToBuffer(t,0,i,0,a),e.flush(),await i.mapAsync(GPUMapMode.READ);let o=i.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(o,0,n)),e}return new Uint8Array(o.slice(0,n))}finally{i.destroy()}},dt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map}upload(e,t){let n=t.buffer,r=t.byteOffset,a=t.byteLength,i=st(a),s=this.storageCache.get(e);if(!s)throw new Error("gpu data for uploading does not exist");if(s.originalSize!==a)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${a}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=o.getMappedRange();new Uint8Array(l).set(new Uint8Array(n,r,a)),o.unmap();let u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o,0,s.gpuData.buffer,0,i),at("verbose",(()=>`[WebGPU] GpuDataManager.upload(id=${e})`)),this.buffersForUploadingPending.push(o)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let r=this.storageCache.get(t);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");let a=st(n.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,a)}registerExternalBuffer(e,t,n){let r;if(n){if(r=this.externalBuffers.get(n),void 0===r)throw new Error("previous buffer is not registered");if(e===n)return at("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`)),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error("Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!");this.externalBuffers.delete(n)}else r=lt();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,r),at("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`)),r}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);void 0!==t&&(this.storageCache.delete(t),this.externalBuffers.delete(e),at("verbose",(()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`)))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n,r=st(e),a=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(a||i){let e=a?this.freeBuffers:this.freeUniformBuffers,i=e.get(r);i||(i=[],e.set(r,i)),n=i.length>0?i.pop():this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let s={id:lt(),type:0,buffer:n};return this.storageCache.set(s.id,{gpuData:s,originalSize:e}),at("verbose",(()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${s.id}`)),s}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return at("verbose",(()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`)),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("data does not exist");await ut(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],0!==this.buffersPending.length)if("default"===this.backend.sessionStatus){for(let e of this.buffersPending)(e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(e.size).push(e):(e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(e.size).push(e):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((e=>{e.destroy()}))})),this.freeUniformBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache.forEach((e=>{e.gpuData.buffer.destroy()})),this.capturedPendingBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach((e=>{e.destroy()})),this.capturedPendingBuffers.delete(e))}},ct=(...e)=>new dt(...e)})),Go=L((()=>{pt=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}},ht=e=>new pt(e)})),jo=L((()=>{ft=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},mt=class{static calcShape(e,t,n=!1){let r=e.length,a=t.length;if(0===r)return t;if(0===a)return e;let i=Math.max(e.length,t.length),s=new Array(i);if(n){if(r<2||a<2)return;let n=ft.calcMatMulShape([e[r-2],e[r-1]],[t[a-2],t[a-1]]);if(void 0===n)return;[s[i-2],s[i-1]]=n}for(let o=n?3:1;o<=i;o++){let n=r-o<0?1:e[r-o],l=a-o<0?1:t[a-o];if(n!==l&&n>1&&l>1)return;let u=Math.max(n,l);if(n&&l)s[i-o]=Math.max(n,l);else{if(u>1)return;s[i-o]=0}}return s}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let a=1;a<=n;a++)if(1!==e[n-a]&&e[n-a]!==t[r-a])return!1;return!0}},gt=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(0===n)return[];let r=new Array(n),a=n-1;for(;a>=0;){if(e[a]%t==0){r[a]=e[a]/t;break}if(t%e[a]!=0)throw new Error("cannot convert shape");r[a]=1,t/=e[a],a--}for(a--;a>=0;a--)r[a]=e[a];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let a=t;a=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((n=>this.normalizeAxis(n,t??e.length)))}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}},_t=class e{static adjustPoolAttributes(e,t,n,r,a,i){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e=n[e]||i[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,r,a,i,s,o){if(o){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(a.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{Do(),jo(),vt=64,$t=(e,t)=>{if(3===t)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(4!==t)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},xt=(e,t=1)=>{let n=$t(e,t);return"string"==typeof n?n:n[0]},Tt=(e,t=1)=>{let n=$t(e,t);return"string"==typeof n?n:n[1]},St=(...e)=>{let t=[];return e.forEach((e=>{0!==e.length&&t.push({type:12,data:e},{type:12,data:gt.computeStrides(e)})})),t},Mt=e=>e%4==0?4:e%2==0?2:1,kt=(e="f32",t,n="0")=>t&&1!==t?`vec${t}<${e}>(${n})`:`${e}(${n})`,Ct=(e,t,n)=>"f32"===e?n:1===t?`f32(${n})`:`vec${t}f(${n})`,Et=(e,t)=>4===t?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:2===t?`(${e}.x + ${e}.y)`:3===t?`(${e}.x + ${e}.y + ${e}.z)`:e,At=(e,t,n,r)=>e.startsWith("uniforms.")&&n>4?"string"==typeof t?"f16"===r?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:"f16"===r?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,It=(e,t,n,r,a)=>{let i="number"==typeof n,s=i?n:n.length,o=[...new Array(s).keys()],l=s<2?"u32":s<=4?`vec${s}`:`array`,u=$t(t,a),d="string"==typeof u?u:u[1],c="string"==typeof u?u:u[0],p={indices:l,value:d,storage:c,tensor:t},h=e=>"string"==typeof e?e:`${e}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},m=i?"uniforms.":"",g=`${m}${e}_shape`,_=`${m}${e}_strides`,w="";for(let e=0;e ${p.indices} {\n var indices: ${p.indices};\n var current = offset;\n ${w}\n return indices;\n }`,b=[];if(s>=2)for(let e=s-1;e>=0;e--)b.push(`${At(_,e,s)} * (indices[${e}])`);let v=s<2?"":`\n fn i2o_${e}(indices: ${p.indices}) -> u32 {\n return ${b.join("+")};\n }`,$=(...e)=>0===s?"0u":`${p.indices}(${e.map(h).join(",")})`,x=(e,t)=>s<2?`${e}`:`${At(e,t,s)}`,T={},S=(t,n)=>(()=>{if(p.storage===p.value)return`${e}[${t}]=${n};`;if("vec2"===p.storage&&"i32"===p.value)return`${e}[${t}]=vec2(u32(${n}), select(0u, 0xFFFFFFFFu, ${n} < 0));`;if("vec2"===p.storage&&"u32"===p.value)return`${e}[${t}]=vec2(u32(${n}), 0u);`;if("u32"===p.storage&&"vec4"===p.value)return`${e}[${t}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${n}));`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),M=t=>(()=>{if(p.storage===p.value)return`${e}[${t}]`;if("vec2"===p.storage&&"i32"===p.value)return`i32(${e}[${t}].x)`;if("vec2"===p.storage&&"u32"===p.value)return`u32(${e}[${t}].x)`;if("u32"===p.storage&&"vec4"===p.value)return`vec4(bool(${e}[${t}] & 0xFFu), bool(${e}[${t}] & 0xFF00u), bool(${e}[${t}] & 0xFF0000u), bool(${e}[${t}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),k=s<2?"":`\n fn get_${e}ByIndices(indices: ${p.indices}) -> ${d} {\n return ${M(`i2o_${e}(indices)`)};\n }`,C=s<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n fn get_${e}(${t}) -> ${d} {\n return get_${e}ByIndices(${$(n)});\n }`})(),E=s<2?"":`\n fn set_${e}ByIndices(indices: ${p.indices}, value: ${d}) {\n ${S(`i2o_${e}(indices)`,"value")}\n }`,A=s<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n fn set_${e}(${t}, value: ${d}) {\n set_${e}ByIndices(${$(n)}, value);\n }`})();return{impl:()=>{let e=[],t=!1;return f.offsetToIndices&&(e.push(y),t=!0),f.indicesToOffset&&(e.push(v),t=!0),f.broadcastedIndicesToOffset&&(Object.values(T).forEach((t=>e.push(t))),t=!0),f.set&&(e.push(A),t=!0),f.setByIndices&&(e.push(E),t=!0),f.get&&(e.push(C),t=!0),f.getByIndices&&(e.push(k),t=!0),!i&&t&&e.unshift(`const ${g} = ${p.indices}(${n.join(",")});`,`const ${_} = ${p.indices}(${gt.computeStrides(n).join(",")});`),e.join("\n")},type:p,offsetToIndices:t=>(f.offsetToIndices=!0,s<2?t:`o2i_${e}(${t})`),indicesToOffset:t=>(f.indicesToOffset=!0,s<2?t:`i2o_${e}(${t})`),broadcastedIndicesToOffset:(t,n)=>{f.broadcastedIndicesToOffset=!0;let r=`${n.name}broadcastedIndicesTo${e}Offset`;if(r in T)return`${r}(${t})`;let a=[];for(let e=s-1;e>=0;e--){let t=n.indicesGet("outputIndices",e+n.rank-s);a.push(`${x(_,e)} * (${t} % ${x(g,e)})`)}return T[r]=`fn ${r}(outputIndices: ${n.type.indices}) -> u32 {\n return ${a.length>0?a.join("+"):"0u"};\n }`,`${r}(${t})`},indices:$,indicesGet:x,indicesSet:(e,t,n)=>s<2?`${e}=${n};`:`${At(e,t,s)}=${n};`,set:(...t)=>{if(t.length!==s+1)throw new Error(`indices length must be ${s}`);let n=t[s];if("string"!=typeof n)throw new Error("value must be string");let r=t.slice(0,s).map(h).join(",");return 0===s?S("0u",n):1===s?S(r[0],n):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${r}, ${n})`)},setByOffset:S,setByIndices:(t,n)=>s<2?S(t,n):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:(...t)=>{if(t.length!==s)throw new Error(`indices length must be ${s}`);let n=t.map(h).join(",");return 0===s?M("0u"):1===s?M(n[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${n})`)},getByOffset:M,getByIndices:t=>s<2?M(t):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${t})`),usage:r,name:e,strides:_,shape:g,rank:s}},Pt=(e,t,n,r=1)=>It(e,t,n,"input",r),Ot=(e,t,n,r=1)=>It(e,t,n,"output",r),zt=(e,t,n,r=1)=>It(e,t,n,"internal",r),Bt=class{constructor(e){this.normalizedDispatchGroup=e,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${"number"==typeof e?`${e}u`:e}) { return; }`}mainStart(e=vt){let t="number"==typeof e?e:e[0],n="number"==typeof e?1:e[1],r="number"==typeof e?1:e[2],a=1===this.normalizedDispatchGroup[1]&&1===this.normalizedDispatchGroup[2];return`@compute @workgroup_size(${t}, ${n}, ${r})\n fn main(${a?"@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3":"@builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3"}) {\n ${a?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${t*n*r}u + local_idx;`}\n `}appendVariableUniforms(e){0!==e.rank&&(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("internal"===e.usage)throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let n="input"===e.usage?"read":"read_write",r=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${r}>;`}declareVariables(...e){return e.map((e=>this.declareVariable(e,this.variableIndex++))).join("\n")}registerInternalVariable(e){if("internal"!==e.usage)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((e=>this.registerInternalVariable(e))),this}registerUniform(e,t,n=1){return this.uniforms.push({name:e,type:t,length:n}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(0===this.uniforms.length)return"";let e=[];for(let{name:t,type:n,length:r}of this.uniforms)if(r&&r>4)"f16"===n?e.push(`@align(16) ${t}:array, ${Math.ceil(r/8)}>`):e.push(`${t}:array, ${Math.ceil(r/4)}>`);else{let a=null==r||1===r?n:`vec${r}<${n}>`;e.push(`${t}:${a}`)}return`\n struct Uniforms { ${e.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map((e=>e.impl())).join("\n")+this.internalVariables.map((e=>e.impl())).join("\n")}},Ft=e=>new Bt(e),Rt=(e,t)=>{let n=e.length,r=[];for(let a=0;a1&&1===s&&r.unshift(i)}return r}})),Ho=L((()=>{Do(),jo(),Go(),qo(),Dt=e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.")},Lt=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Nt=(e,t)=>gt.sortBasedOnPerm(e,Lt(e.length,t)),Ut=(e,t,n,r)=>{let a=[];a.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {\n var a: ${n.type.indices};`);for(let r=0;r{let n=e.dataType,r=e.dims.length,a=Lt(r,t),i=Nt(e.dims,a),s=Ot("output",n,i.length),o=Pt("a",n,r);return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:e=>{let t=gt.size(i);return{outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:[{type:12,data:t},...St(e[0].dims,i)]}},getShaderSource:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(o,s)}\n\n ${Ut(a,r,o,s)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${s.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${s.setByOffset("global_idx",o.getByIndices("aIndices"))}\n }`}},Vt=(e,t)=>{Dt(e.inputs),e.compute(Wt(e.inputs[0],t.perm))},Gt=e=>ht({perm:e.perm})})),Ko=L((()=>{Do(),jo(),qo(),Yo(),Ho(),jt={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"},qt={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"},Ht={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Kt={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Yt=(e,t)=>{let n=[];for(let r=t-e;r{let n=[],r=e.length;for(let a=0;ae[t]))]},Qt=(e,t)=>{let n=e.length+t.length,r=[],a=0;for(let i=0;i{for(let n=0;n{let n=[];if(!Zt(e,t)){for(let r=0;rn.push(e)))}return n},en=(e,t,n,r,a,i,s)=>{let o=n[0].dims,l=gt.size(i),u=gt.size(s),d=Pt("_A",n[0].dataType,o),c=Ot("output",a,i);return{name:e,shaderCache:t,getShaderSource:e=>`\n ${e.registerUniform("reduceSize","u32").declareVariables(d,c)}\n \n var aBestValues : array;\n \n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${e.mainStart(32)}\n\n let outputIndex = global_idx / 32;\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${Ht[r]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + 32) {\n let candidate = f32(${d.getByOffset("offset + k")});\n bestValue = ${jt[r]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, 32u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${qt[r]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${c.setByOffset("outputIndex",""+("mean"===r?`${c.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${c.type.storage}(${Kt[r]})`))};\n }\n }`,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},tn=(e,t,n,r)=>{let a=1===e.inputs.length?n:gn(e.inputs,n),i=a.axes;0===i.length&&!a.noopWithEmptyAxes&&(i=e.inputs[0].dims.map(((e,t)=>t)));let s=gt.normalizeAxes(i,e.inputs[0].dims.length),o=s,l=e.inputs[0],u=Jt(o,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Wt(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],o=Yt(o.length,l.dims.length));let[d,c]=Xt(l.dims,o),p=d;a.keepDims&&(p=Qt(d,s)),e.compute(en(t,{hint:a.cacheKey,inputDependencies:["type"]},[l],r,e.inputs[0].dataType,p,c),{inputs:[l]})},nn=(e,t)=>{tn(e,"ReduceMeanShared",t,"mean")},rn=(e,t)=>{tn(e,"ReduceL1Shared",t,"l1")},an=(e,t)=>{tn(e,"ReduceL2Shared",t,"l2")},sn=(e,t)=>{tn(e,"ReduceLogSumExpShared",t,"logSumExp")},on=(e,t)=>{tn(e,"ReduceMaxShared",t,"max")},ln=(e,t)=>{tn(e,"ReduceMinShared",t,"min")},un=(e,t)=>{tn(e,"ReduceProdShared",t,"prod")},dn=(e,t)=>{tn(e,"ReduceSumShared",t,"sum")},cn=(e,t)=>{tn(e,"ReduceSumSquareShared",t,"sumSquare")},pn=(e,t)=>{tn(e,"ReduceLogSumShared",t,"logSum")}})),Yo=L((()=>{Do(),jo(),Go(),qo(),Ko(),hn=e=>{if(!e||0===e.length||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(2===e.length&&1!==e[1].dims.length)throw new Error("Invalid axes input dims.")},fn=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],mn=(e,t,n,r,a,i,s=!1,o=!1)=>{let l=[],u=n[0].dims,d=u.length,c=gt.normalizeAxes(a,d),p=!o&&0===c.length;u.forEach(((e,t)=>{p||c.indexOf(t)>=0?s&&l.push(1):l.push(e)}));let h=l.length,f=gt.size(l);return{name:e,shaderCache:t,getShaderSource:e=>{let t=[],a=Pt("_A",n[0].dataType,d),o=Ot("output",i,h),l=r(a,o,c),f=l[2];for(let e=0,n=0;e=0?(s&&n++,f=`for(var j${e}: u32 = 0; j${e} < ${u[e]}; j${e}++) {\n ${l[2].includes("last_index")?`let last_index = j${e};`:""}\n ${a.indicesSet("input_indices",e,`j${e}`)}\n ${f}\n }`):(t.push(`${a.indicesSet("input_indices",e,o.indicesGet("output_indices",n))};`),n++);return`\n\n ${e.registerUniform("output_size","u32").declareVariables(a,o)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${a.type.indices};\n let output_indices = ${o.offsetToIndices("global_idx")};\n\n ${t.join("\n")}\n ${l[0]} // init ops for reduce max/min\n ${l[1]}\n ${f}\n ${l[3]}\n ${4===l.length?o.setByOffset("global_idx","value"):l.slice(4).join("\n")}\n }`},getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...St(u,l)]})}},gn=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),ht({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},_n=(e,t,n,r)=>{let a=e.inputs,i=1===a.length?n:gn(a,n);e.compute(mn(t,{hint:i.cacheKey,inputDependencies:["rank"]},[a[0]],i.noopWithEmptyAxes&&0===i.axes.length?fn:r,i.axes,a[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},wn=(e,t)=>{hn(e.inputs),_n(e,"ReduceLogSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,"value = log(value);"]))},yn=(e,t)=>{hn(e.inputs),_n(e,"ReduceL1",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += abs(${e.getByIndices("input_indices")});`,""]))},bn=(e,t)=>{hn(e.inputs),_n(e,"ReduceL2",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"]))},vn=(e,t)=>{hn(e.inputs),_n(e,"ReduceLogSumExp",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += exp(${e.getByIndices("input_indices")});`,"value = log(value);"]))},$n=(e,t)=>{hn(e.inputs),_n(e,"ReduceMax",t,((e,t,n)=>{let r=[];for(let t=0;t=0||0===n.length)&&r.push(e.indicesSet("input_indices",t,0));return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = max(value, ${e.getByIndices("input_indices")});`,""]}))},xn=(e,t)=>{hn(e.inputs),_n(e,"ReduceMean",t,((t,n,r)=>{let a=1;for(let n=0;n=0||0===r.length)&&(a*=e.inputs[0].dims[n]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]}))},Tn=(e,t)=>{hn(e.inputs),_n(e,"ReduceMin",t,((e,t,n)=>{let r=[];for(let t=0;t=0||0===n.length)&&r.push(`input_indices[${t}] = 0;`);return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = min(value, ${e.getByIndices("input_indices")});`,""]}))},Sn=(e,t)=>{hn(e.inputs),_n(e,"ReduceProd",t,((e,t)=>[`var value = ${t.type.storage}(1);`,"",`value *= ${e.getByIndices("input_indices")};`,""]))},Mn=(e,t)=>{hn(e.inputs),_n(e,"ReduceSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,""]))},kn=(e,t)=>{hn(e.inputs),_n(e,"ReduceSumSquare",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += t * t;`,""]))},Cn=(e,t,n)=>{if(0===t.length)return n;let r=1,a=1;for(let n=0;n1024},En=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xn(e,t):nn(e,t)},An=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?yn(e,t):rn(e,t)},In=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bn(e,t):an(e,t)},Pn=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vn(e,t):sn(e,t)},On=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$n(e,t):on(e,t)},zn=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tn(e,t):ln(e,t)},Bn=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sn(e,t):un(e,t)},Fn=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Mn(e,t):dn(e,t)},Rn=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?kn(e,t):cn(e,t)},Dn=(e,t)=>{Cn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wn(e,t):pn(e,t)}})),Xo=L((()=>{Do(),Go(),Yo(),Ln=e=>{if(!e||0===e.length||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(1!==e[0].dataType)throw new Error("Invalid input type.")},Nn=(e,t)=>{Ln(e.inputs);e.compute(mn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let a=[];for(let t=0;t=0||0===r.length)&&a.push(`input_indices[${t}] = 0;`);return[`${a.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Un=(e,t)=>{Ln(e.inputs);e.compute(mn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let a=[];for(let t=0;t=0||0===r.length)&&a.push(`input_indices[${t}] = 0;`);return[`${a.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Wn=e=>ht(e)})),Qo=L((()=>{Do(),Wo(),qo(),Vn=(e,t)=>{let n=e[0],r=e[1],a=e[2],i=e[3],s=e[4],o=e[5];if(s&&o)throw new Error("Attention cannot have both past and relative_position_bias");if(3!==n.dims.length)throw new Error('Input "input" must have 3 dimensions');let l=n.dims[0],u=n.dims[1],d=n.dims[2];if(1!==a.dims.length)throw new Error('Input "bias" is expected to have 1 dimensions');if(2!==r.dims.length)throw new Error('Input "weights" is expected to have 2 dimensions');if(r.dims[0]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(a.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let c=a.dims[0]/3,p=c,h=p;if(t.qkvHiddenSizes.length>0){if(3!==t.qkvHiddenSizes.length)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let e of t.qkvHiddenSizes)if(e%t.numHeads!=0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");c=t.qkvHiddenSizes[0],p=t.qkvHiddenSizes[1],h=t.qkvHiddenSizes[2]}let f=u;if(c!==p)throw new Error("qkv_hidden_sizes first element should be same as the second");if(a.dims[0]!==c+p+h)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let m=0;if(s){if(p!==h)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(5!==s.dims.length)throw new Error('Input "past" must have 5 dimensions');if(2!==s.dims[0])throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==p/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(m=s.dims[3])}let g=f+m;if(i)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");if(o)throw new Error("relativePositionBias is not supported");return{batchSize:l,sequenceLength:u,pastSequenceLength:m,kvSequenceLength:f,totalSequenceLength:g,maxSequenceLength:-1,inputHiddenSize:d,hiddenSize:c,vHiddenSize:h,headSize:Math.floor(c/t.numHeads),vHeadSize:Math.floor(h/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Gn=(e,t,n,r)=>{let a=Mt(r),i=64,s=r/a;s{let n=Ot("x",t.dataType,t.dims,a),r="thread_max_vector";2===a?r="max(thread_max_vector.x, thread_max_vector.y)":4===a&&(r="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let s=Tt(t.dataType),o=[{name:"d_inv",type:s},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return`\n var wgMax: array;\n var wgSum: array;\n ${e.registerUniforms(o).declareVariables(n)}\n ${e.mainStart([i,1,1])}\n let localOffset = local_idx * uniforms.elements_per_wg;\n let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset;\n\n var thread_max_vector = ${kt("f32",a,"-3.402823e+38f")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n thread_max_vector = max(${Ct(s,a,"x[offset + i]")}, thread_max_vector);\n }\n wgMax[local_idx] = ${r};\n workgroupBarrier();\n\n var maxValue = -3.402823e+38f;\n for (var i = 0u; i < ${i}; i++) {\n maxValue = max(wgMax[i], maxValue);\n }\n\n var sumVector = ${kt("f32",a,"0")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n sumVector += exp(${Ct(s,a,"x[offset + i]")} - maxValue);\n }\n wgSum[local_idx] = ${Et("sumVector",a)};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${i}; i++) {\n sum += wgSum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n x[offset + i] = ${kt(s,a,"uniforms.d_inv")};\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n let f32input = ${Ct(s,a,"x[offset + i]")};\n x[offset + i] = ${n.type.value}(exp(f32input - maxValue) / sum);\n }\n }\n }`},getRunData:()=>({outputs:[],dispatchGroup:{x:n},programUniforms:l})},{inputs:[t],outputs:[]})},jn=(e,t,n,r,a,i)=>{let s=[a.batchSize,a.numHeads,a.sequenceLength,a.kvSequenceLength+a.pastSequenceLength],o=0===i.scale?1/Math.sqrt(a.headSize):i.scale,l=Mt(a.headSize),u=a.headSize/l,d=12,c={x:Math.ceil(a.totalSequenceLength/d),y:Math.ceil(a.sequenceLength/d),z:a.batchSize*a.numHeads},p=[{type:12,data:a.sequenceLength},{type:12,data:u},{type:12,data:a.totalSequenceLength},{type:12,data:a.kvSequenceLength},{type:t.dataType,data:o}],h=[t,n],f=e.compute({name:"AttentionProbs",shaderCache:{hint:`${l}`,inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:p}),getShaderSource:e=>{let r=Pt("q",t.dataType,t.dims,l),a=Pt("key",n.dataType,n.dims,l),i=Ot("output",t.dataType,s),o=xt(t.dataType),u=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:o}];return`\n const beta: ${o} = 1.0;\n const TILE_SIZE = 12u;\n\n var tileQ: array<${r.type.storage}, 144>;\n var tileK: array<${r.type.storage}, 144>;\n ${e.registerUniforms(u).declareVariables(r,a,i)}\n ${e.mainStart([d,d,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let lm = m + local_id.y;\n let ln = n + local_id.x;\n\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${kt(o,l)};\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m + local_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k{let a=[r.batchSize,r.sequenceLength,r.vHiddenSize],i=12,s={x:Math.ceil(r.vHeadSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},o=[{type:12,data:r.sequenceLength},{type:12,data:r.totalSequenceLength},{type:12,data:r.vHeadSize},{type:12,data:r.numHeads},{type:12,data:r.vHiddenSize}];return e.compute({name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType,gpuDataType:0}],dispatchGroup:s,programUniforms:o}),getShaderSource:e=>{let r=Pt("probs",t.dataType,t.dims),s=Pt("v",n.dataType,n.dims),o=Ot("output",t.dataType,a);return`\n const TILE_SIZE = 12u;\n var tileQ: array<${r.type.value}, 144>;\n var tileK: array<${r.type.value}, 144>;\n ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}]).declareVariables(r,s,o)}\n ${e.mainStart([i,i,1])}\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${r.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k{let c=jn(e,t,n,0,u,d);qn(e,c,r,u)},Kn=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],r=t.sequenceLength,a=t.inputHiddenSize,i=t.headSize,s=12,o={x:Math.ceil(t.headSize/s),y:Math.ceil(t.sequenceLength/s),z:t.batchSize*t.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:r},{type:12,data:a},{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}];return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:u}),getShaderSource:e=>{let t=Ot("output_q",l[0].dataType,n),r=Ot("output_k",l[0].dataType,n),a=Ot("output_v",l[0].dataType,n),i=Pt("input",l[0].dataType,l[0].dims),o=Pt("weight",l[1].dataType,l[1].dims),u=Pt("bias",l[2].dataType,l[2].dims),d=i.type.storage;return`\n const TILE_SIZE = 12u;\n var tileInput: array<${d}, 144>;\n var tileWeightQ: array<${d}, 144>;\n var tileWeightK: array<${d}, 144>;\n var tileWeightV: array<${d}, 144>;\n ${e.registerUniforms([{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"}]).declareVariables(i,o,u,t,r,a)}\n ${e.mainStart([s,s,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${d}(0);\n var valueK = ${d}(0);\n var valueV = ${d}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k{let n=Vn(e.inputs,t),[r,a,i]=Kn(e,n);return Hn(e,r,a,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n,t)}})),Zo=L((()=>{de(),Do(),jo(),Go(),qo(),Xn=(e,t)=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs");let n=(e,t,n)=>{let r=t.length;if(r!==e.length)throw new Error(`${n}: num dimensions != ${r}`);t.forEach(((t,r)=>{if(t!==e[r])throw new Error(`${n}: dim[${r}] do not match`)}))};if(e[0].dims.length>1){let r="NHWC"===t.format?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);n(e[1].dims,r,"Invalid input scale"),n(e[2].dims,r,"Invalid input B"),n(e[3].dims,r,"Invalid input mean"),n(e[4].dims,r,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},Qn=(e,t)=>{let{epsilon:n,spatial:r,format:a}=t,i=e[0].dims,s=r?Mt(i[i.length-1]):1,o="NHWC"===a&&i.length>1?s:1,l=gt.size(i)/s,u=r,d=u?i.length:i,c=Pt("x",e[0].dataType,e[0].dims,s),p=Pt("scale",e[1].dataType,e[1].dims,o),h=Pt("bias",e[2].dataType,e[2].dims,o),f=Pt("inputMean",e[3].dataType,e[3].dims,o),m=Pt("inputVar",e[4].dataType,e[4].dims,o),g=Ot("y",e[0].dataType,d,s);return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${r}_${s}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:e=>`\n const epsilon = ${n};\n ${e.registerUniform("outputSize","u32").declareVariables(c,p,h,f,m,g)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${g.offsetToIndices(`global_idx * ${s}`)};\n ${(()=>{let e="";if(r)e=`let cOffset = ${1===i.length?"0u":"NHWC"===a?`outputIndices[${i.length-1}] / ${s}`:"outputIndices[1]"};`;else if("NCHW"===a)e=`\n ${g.indicesSet("outputIndices","0","0")}\n let cOffset = ${g.indicesToOffset("outputIndices")};`;else{e=`var cIndices = ${p.type.indices}(0);\n cIndices[0] = outputIndices[${i.length-1}];`;for(let t=1;t({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...St(i)]:[{type:12,data:l}]})}},Zn=e=>ht(e),Jn=(e,t)=>{let{inputs:n,outputCount:r}=e,a=Zn({...t,outputCount:r});if(c.webgpu.validateInputContent&&Xn(n,a),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Qn(n,a))}})),Jo=L((()=>{jo(),qo(),er=e=>{if(3!==e[0].dims.length)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(1!==e[1].dims.length)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")},tr=e=>{let t=e[0].dims,n=e[0].dims[2],r=gt.size(t)/4,a=e[0].dataType,i=Pt("input",a,t,4),s=Pt("bias",a,[n],4),o=Pt("residual",a,t,4),l=Ot("output",a,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:e=>`\n const channels = ${n}u / 4;\n ${e.declareVariables(i,s,o,l)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(r)}\n let value = ${i.getByOffset("global_idx")}\n + ${s.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")};\n ${l.setByOffset("global_idx","value")}\n }`}},nr=e=>{er(e.inputs),e.compute(tr(e.inputs))}})),el=L((()=>{Do(),jo(),Go(),qo(),rr=(e,t,n,r,a,i)=>{let s=Math.ceil(t/4),o="";o="string"==typeof a?`${a}(a)`:a("a");let l=Pt("inputData",n,[s],4),u=Ot("outputData",r,[s],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(l,u)}\n\n ${i??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${l.getByOffset("global_idx")};\n ${u.setByOffset("global_idx",o)}\n }`},ar=(e,t,n,r,a,i=e.dataType)=>({name:t,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:t=>rr(t,gt.size(e.dims),e.dataType,i,n,r),getRunData:t=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(gt.size(t[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(gt.size(e.dims)/4)}]})}),ir=e=>{e.compute(ar(e.inputs[0],"Abs","abs"))},sr=e=>{e.compute(ar(e.inputs[0],"Acos","acos"))},or=e=>{e.compute(ar(e.inputs[0],"Acosh","acosh"))},lr=e=>{e.compute(ar(e.inputs[0],"Asin","asin"))},ur=e=>{e.compute(ar(e.inputs[0],"Asinh","asinh"))},dr=e=>{e.compute(ar(e.inputs[0],"Atan","atan"))},cr=e=>{e.compute(ar(e.inputs[0],"Atanh","atanh"))},pr=e=>ht(e),hr=(e,t)=>{let n;switch(t.to){case 10:n="vec4";break;case 1:n="vec4";break;case 12:n="vec4";break;case 6:n="vec4";break;case 9:n="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ar(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},fr=e=>{let t=e.length>=2&&0!==e[1].data?e[1].getFloat32Array()[0]:yt,n=e.length>=3&&0!==e[2].data?e[2].getFloat32Array()[0]:bt;return ht({min:t,max:n})},mr=(e,t)=>{let n=1===e.inputs.length?t:fr(e.inputs),r=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Clip",(e=>`clamp(${e}, clip_min_, clip_max_)`),`\n const clip_min_: vec4<${r}> = vec4(${r}(${n.min}));\n const clip_max_: vec4<${r}> = vec4(${r}(${n.max}));\n`,n.cacheKey),{inputs:[0]})},gr=e=>{e.compute(ar(e.inputs[0],"Ceil","ceil"))},_r=e=>{e.compute(ar(e.inputs[0],"Cos","cos"))},wr=e=>{e.compute(ar(e.inputs[0],"Cosh","cosh"))},yr=e=>ht(e),br=(e,t)=>{let n=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Elu",(e=>`elu_vf32(${e})`),`\n const elu_alpha_ = ${n}(${t.alpha});\n\n fn elu_f32(a: ${n}) -> ${n} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},vr=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,$r=e=>{let t=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Erf",(e=>`erf_vf32(${e})`),vr(t)))},xr=e=>{e.compute(ar(e.inputs[0],"Exp","exp"))},Tr=e=>{e.compute(ar(e.inputs[0],"Floor","floor"))},Sr=e=>{let t=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Gelu",(e=>`0.5 * ${e} * (1.0 + erf_vf32(${e} * 0.7071067811865475))`),vr(t)))},Mr=(e,t)=>{let n=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"LeakyRelu",(e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<${n}>(0.0))`),`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},kr=e=>{e.compute(ar(e.inputs[0],"Not",(e=>`!${e}`)))},Cr=e=>{e.compute(ar(e.inputs[0],"Neg",(e=>`-${e}`)))},Er=e=>{e.compute(ar(e.inputs[0],"Reciprocal",(e=>`1.0/${e}`)))},Ar=e=>{let t=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Relu",(e=>`select(vec4<${t}>(0.0), ${e}, ${e} > vec4<${t}>(0.0))`)))},Ir=e=>{e.compute(ar(e.inputs[0],"Sigmoid",(e=>`(1.0 / (1.0 + exp(-${e})))`)))},Pr=e=>ht(e),Or=(e,t)=>{let n=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"HardSigmoid",(e=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${e} + vec4<${n}>(${t.beta})))`),void 0,t.cacheKey))},zr=e=>{e.compute(ar(e.inputs[0],"Sin","sin"))},Br=e=>{e.compute(ar(e.inputs[0],"Sinh","sinh"))},Fr=e=>{e.compute(ar(e.inputs[0],"Sqrt","sqrt"))},Rr=e=>{e.compute(ar(e.inputs[0],"Tan","tan"))},Dr=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Lr=e=>{e.compute(ar(e.inputs[0],"Tanh",Dr))},Nr=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Dr("v")};\n}\n`,Ur=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Wr=e=>{let t=Tt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"FastGelu",Ur,Nr(t),void 0,e.inputs[0].dataType))},Vr=(e,t)=>{let n=Tt(e.inputs[0].dataType);return e.compute(ar(e.inputs[0],"ThresholdedRelu",(e=>`select(vec4<${n}>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`),`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},Gr=e=>{e.compute(ar(e.inputs[0],"Log","log"))}})),tl=L((()=>{jo(),qo(),el(),jr=e=>{if(3!==e[0].dims.length)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(1!==e[1].dims.length)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")},qr=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=Pt("input",e[0].dataType,e[0].dims,4),r=Pt("bias",e[0].dataType,[e[0].dims[2]],4),a=Ot("output",e[0].dataType,t,4),i=gt.size(t)/4,s=xt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:t=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${t.declareVariables(n,r,a)}\n\n ${vr(s)}\n\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${a.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},Hr=e=>{jr(e.inputs),e.compute(qr(e.inputs))}})),nl=L((()=>{Do(),jo(),qo(),Kr=(e,t,n,r,a,i,s,o,l,u,d,c)=>{let p,h;"string"==typeof o?p=h=(e,t)=>`${o}((${e}),(${t}))`:"function"==typeof o?p=h=o:(p=o.scalar,h=o.vector);let f,m=Ot("outputData",d,r.length,4),g=Pt("aData",l,t.length,4),_=Pt("bData",u,n.length,4);if(a)if(i){let e=1===gt.size(t),r=1===gt.size(n),a=t.length>0&&t[t.length-1]%4==0,i=n.length>0&&n[n.length-1]%4==0;f=e||r?m.setByOffset("global_idx",h(e?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),r?`${_.type.value}(${_.getByOffset("0")}.x)`:_.getByOffset("global_idx"))):`\n let outputIndices = ${m.offsetToIndices("global_idx * 4u")};\n let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",m)};\n let offsetB = ${_.broadcastedIndicesToOffset("outputIndices",m)};\n ${m.setByOffset("global_idx",h(s||a?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||i?_.getByOffset("offsetB / 4u"):`${_.type.value}(${_.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else f=m.setByOffset("global_idx",h(g.getByOffset("global_idx"),_.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let e=(e,t,n="")=>{let r=`aData[indexA${t}][componentA${t}]`,a=`bData[indexB${t}][componentB${t}]`;return`\n let outputIndices${t} = ${m.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offsetA${t} = ${g.broadcastedIndicesToOffset(`outputIndices${t}`,m)};\n let offsetB${t} = ${_.broadcastedIndicesToOffset(`outputIndices${t}`,m)};\n let indexA${t} = offsetA${t} / 4u;\n let indexB${t} = offsetB${t} / 4u;\n let componentA${t} = offsetA${t} % 4u;\n let componentB${t} = offsetB${t} % 4u;\n ${e}[${t}] = ${n}(${p(r,a)});\n `};f=9===d?`\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:`\n ${e("outputData[global_idx]",0)}\n ${e("outputData[global_idx]",1)}\n ${e("outputData[global_idx]",2)}\n ${e("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(g,_,m)}\n\n ${c??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${f}\n }`},Yr=(e,t,n,r,a,i,s=n.dataType)=>{let o=!gt.areEqual(n.dims,r.dims),l=n.dims,u=gt.size(n.dims),d=!1,c=!1,p=[o];if(o){let e=mt.calcShape(n.dims,r.dims,!1);if(!e)throw new Error("Can't perform binary op on the given tensors");l=e,u=gt.size(l);let t=1===gt.size(n.dims),a=1===gt.size(r.dims),i=n.dims.length>0&&n.dims[n.dims.length-1]%4==0,s=r.dims.length>0&&r.dims[r.dims.length-1]%4==0;p.push(t),p.push(a),p.push(i),p.push(s);let o=1;for(let e=1;ee.toString())).join("_"),inputDependencies:["rank","rank"]},getShaderSource:e=>Kr(e,n.dims,r.dims,l,d,o,c,a,n.dataType,r.dataType,s,i),getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(gt.size(l)/4)},...St(n.dims,r.dims,l)]})}},Xr=(e,t,n,r,a,i)=>{e.compute(Yr(t,a??"",e.inputs[0],e.inputs[1],n,r,i))},Qr=e=>{Xr(e,"Add",((e,t)=>`${e}+${t}`))},Zr=e=>{Xr(e,"Div",((e,t)=>`${e}/${t}`))},Jr=e=>{Xr(e,"Equal",{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4(${e}==${t})`},void 0,void 0,9)},ea=e=>{Xr(e,"Mul",((e,t)=>`${e}*${t}`))},ta=e=>{let t=Pt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Xr(e,"Pow",{scalar:(e,t)=>`pow_custom(${e},${t})`,vector:(e,t)=>`pow_vector_custom(${e},${t})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${"i32"===t?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n 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));\n }\n `)},na=e=>{Xr(e,"Sub",((e,t)=>`${e}-${t}`))},ra=e=>{Xr(e,"Greater",{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4(${e}>${t})`},void 0,void 0,9)},aa=e=>{Xr(e,"Less",{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4(${e}<${t})`},void 0,void 0,9)},ia=e=>{Xr(e,"GreaterOrEqual",{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4(${e}>=${t})`},void 0,void 0,9)},sa=e=>{Xr(e,"LessOrEqual",{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4(${e}<=${t})`},void 0,void 0,9)}})),rl=L((()=>{Do(),jo(),Go(),qo(),oa=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=e[0],r=n.dataType,a=n.dims.length;e.forEach(((e,i)=>{if(0!==i){if(e.dataType!==r)throw new Error("input tensors should be one type");if(e.dims.length!==a)throw new Error("input tensors should have the same shape");e.dims.forEach(((e,r)=>{if(r!==t&&e!==n.dims[r])throw new Error("non concat dimensions must match")}))}}))},la=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,ua=(e,t)=>{let n=e.length,r=[];for(let a=0;a{let a=gt.size(n),i=new Array(e.length),s=new Array(e.length),o=0,l=[],u=[],d=[{type:12,data:a}];for(let n=0;n`uniforms.sizeInConcatAxis${e}`)).join(",");return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:t=>`\n\n ${(()=>{t.registerUniform("outputSize","u32");for(let n=0;n(${h});\n ${p} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${ua(s,c)}\n }`}},ca=(e,t)=>{let n=e.inputs,r=n[0].dims,a=gt.normalizeAxis(t.axis,r.length);oa(n,a);let i=r.slice();i[a]=n.reduce(((e,t)=>e+(t.dims.length>a?t.dims[a]:0)),0);let s=n.filter((e=>gt.size(e.dims)>0));e.compute(da(s,a,i,n[0].dataType),{inputs:s})},pa=e=>ht({axis:e.axis})})),al=L((()=>{Do(),jo(),ha=(e,t,n="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}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},fa=(e,t)=>{"Clip"===e.activation?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):"HardSigmoid"===e.activation?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):"LeakyRelu"===e.activation&&t.push({type:1,data:e.alpha})},ma=(e,t)=>{"Clip"===e.activation?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):"HardSigmoid"===e.activation?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):"LeakyRelu"===e.activation&&t.push({name:"alpha",type:"f32"})},ga=e=>{let t=e?.activation||"";if("HardSigmoid"===t){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}if("Clip"===t){let[n,r]=e?.activation_params||[yt,bt];return{activation:t,clipMax:r,clipMin:n}}if("LeakyRelu"===t){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}})),il=L((()=>{_a=(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.`)}},wa=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `})),sl=L((()=>{ya=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`})),ol=L((()=>{Do(),jo(),qo(),al(),il(),ba=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,va=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${3===t?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,$a=(e,t,n="f32",r,a=!1,i=32,s=!1,o=32)=>{let l=t[1]*e[1],u=t[0]*e[0],d=a?l:i,c=a?i:l,p=d/t[0],h=i/t[1];if((!a||4!==p||4!==e[1])&&(a||3!==p&&4!==p)||d%t[0]!=0||i%t[1]!=0||4!==e[0])throw new Error(`If transposeA ${a} is true, innerElementSize ${p} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${p} must be 3 or 4.\n tileAWidth ${d} 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`\nvar mm_Asub: array, ${d/p}>, ${c}>;\nvar mm_Bsub: array, ${u/e[0]}>, ${i}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${p};\nconst tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${s?"0":"i32(globalId.z)"};\n ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${l};\n\n let num_tiles = ${s?`${Math.ceil(o/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${s?`i32(globalId.z) * ${o}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${h};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${ba(a,r)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${r?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${3===p?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${va(a,p)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},xa=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,Ta=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Sa=(e,t,n="f32",r,a=!1,i=32,s=!1,o=32,l=!1)=>{let u=e[1]*t[1],d=e[0]*t[0],c=a?u:i,p=a?i:u;if(p%t[1]!=0||c%t[0]!=0||i%t[1]!=0)throw new Error(`tileAHight ${p} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let h=p/t[1],f=c/t[0],m=i/t[1],g=l?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${u};\n let globalColStart = i32(workgroupId.x) * ${d};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${t[0]}) {\n ${xa(a,r)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${r?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${a?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${u};\n\nlet tileRowA = i32(localId.y) * ${h};\nlet tileColA = i32(localId.x) * ${f};\nlet tileRowB = i32(localId.y) * ${m};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${xa(a,r)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${m}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${r?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Ta(a)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${p}>;\n var mm_Bsub : array, ${i}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${s?"0":"i32(globalId.z)"};\n ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${s?`${Math.ceil(o/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${s?`i32(globalId.z) * ${o}`:"0"};\n\n var acc : array, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${g}\n }\n`},Ma=(e,t,n,r,a,i=!1)=>{let[s,o,l]=a,[u,d,c,p]=r,h=Rt(s,l),f=Rt(o,l),m=xt(r[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${_a(e,m)} {\n var value = ${_a(e,m)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n ${(()=>{let e=d.rank,t=u.rank,n=`var aIndices: ${d.type.indices};`;for(let r=e-2-1,a=t-1;r>=0;r--,a--)n+=`\naIndices[${r}] = ${t>1?`batchIndices[${a}]`:"batchIndices"};`;return h.forEach((e=>{n+=`\naIndices[${e}] = 0;`})),n+=`\naIndices[${e-2}] = u32(row);\n aIndices[${e-1}] = u32(colIn);`,n})()}\n value = ${d.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${_a(e,m)} {\n var value = ${_a(e,m)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n ${(()=>{let e=c.rank,t=u.rank,n=`var bIndices: ${c.type.indices};`;for(let r=e-2-1,a=t-1;r>=0;r--,a--)n+=`\nbIndices[${r}] = ${t>1?`batchIndices[${a}]`:"batchIndices"};`;return f.forEach((e=>{n+=`\nbIndices[${e}] = 0;`})),n+=`\nbIndices[${e-2}] = u32(row);\n bIndices[${e-1}] = u32(colIn);`,n})()}\n value = ${c.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${_a(e,m)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${i?"bias[colIn]":`${_a(e,m)}(bias[row])`};`:""}\n ${n}\n ${p.setByIndices("vec3(coords)","value")}\n }\n }\n `},ka=(e,t,n,r,a=!1)=>{let i=e[0].dims,s=e[1].dims,o=i.slice(0,-2),l=s.slice(0,-2),u=r?r.slice(0,-2):n.slice(0,-2),d=gt.size(u),c=i[i.length-2],p=i[i.length-1],h=s[s.length-1],f=p%4==0&&h%4==0,m=c<=8?[4,1,1]:[4,4,1],g=[8,8,1],_=[Math.ceil(h/g[0]/m[0]),Math.ceil(c/g[1]/m[1]),Math.ceil(d/g[2]/m[2])],w=f?4:1,y=[...o,c,p/w],b=y.length,v=[...l,p,h/w],$=v.length,x=[d,c,h/w],T=[{type:6,data:c},{type:6,data:h},{type:6,data:p}];fa(t,T),T.push(...St(u,y,v));let S=["rank","rank"],M=e.length>2;M&&(T.push(...St(e[2].dims)),S.push("rank")),T.push(...St(x));return{name:"MatMul",shaderCache:{hint:`${m};${t.activation};${f};${a}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:_[0],y:_[1],z:_[2]},programUniforms:T}),getShaderSource:n=>{let r=u.length,i=zt("batchDims",e[0].dataType,r,1),s=xt(e[0].dataType),d=Pt("a",e[0].dataType,b,w),c=Pt("b",e[1].dataType,$,w),p=Ot("result",e[0].dataType,x.length,w),h=[d,c];if(M){let t=a?w:1;h.push(Pt("bias",e[2].dataType,e[2].dims.length,t))}let _=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ma(t,_);let y=xt(p.type.tensor),v=ha(t,p.type.value,y),T=Ma(w,M,v,[i,d,c,p],[o,l,u],a);return`\n ${n.registerUniforms(_).registerInternalVariables(i).declareVariables(...h,p)}\n ${T}\n ${f?$a(m,g,s,i):Sa(m,g,s,i)}\n `}}}})),ll=L((()=>{Do(),No(),qo(),al(),il(),sl(),ol(),Ca=(e,t,n,r,a=!1,i,s=4,o=4,l=4,u="f32")=>{let d=e?"\n let coord = vec4(batch, xRow, xCol, xCh);\n ":"\n let coord = vec4(batch, xCh, xRow, xCol);\n ",c=e?"\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",f=e?"row":"col",m=e?"col":"row",g=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${f} / outWidth;\n let outCol = ${f} % outWidth;\n\n let WRow = ${m} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${m} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${m} % inChannels;\n var resData = ${_a(s,u)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${p} && xCol >= 0 && xCol < ${h}) {\n ${d}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${(e=>{switch(e){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(s)}\n }\n return resData;`,_=e?t&&r?`\n let col = colIn * ${s};\n ${g}`:`\n let col = colIn * ${s};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${g}\n }\n return ${_a(s,u)}(0.0);`:r&&n?`\n let col = colIn * ${s};\n ${g}`:`\n let col = colIn * ${s};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${g}\n }\n return ${_a(s,u)}(0.0);`,w=`${(e=>{switch(e){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 ${e} is not supported.`)}})(o)}`,y=_a(l,u),b=_a(e?s:o,u),v=_a(e?o:s,u),$=ha(i,y,u);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${b} {\n ${e?_:w}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${v} {\n ${e?w:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${y}) {\n let col = colIn * ${l};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${c}\n ${wa(a)}\n ${$}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Ea=(e,t,n,r,a,i,s,o)=>{let l="NHWC"===t.format,u=l?e[0].dims[3]:e[0].dims[1],d=n[0],c=l?n[2]:n[3],p=l?n[1]:n[2],h=l?n[3]:n[1],f=l&&(u%4==0||u%3==0)&&h%4==0,m=l?h:c*p,g=l?c*p:h,_=[8,8,1],w=r<=8?[4,1,1]:[4,4,1],y=[Math.ceil(m/_[0]/w[0]),Math.ceil(g/_[1]/w[1]),Math.ceil(d/_[2]/w[2])];at("verbose",(()=>`[conv2d_mm_webgpu] dispatch = ${y}`));let b=f?l&&u%4!=0?3:4:1,v=_[1]*w[1],$=_[0]*w[0],x=Math.max(_[0]*b,_[1]),T=r%v==0,S=a%$==0,M=i%x==0,k=f?[b,4,4]:[1,1,1],C=[{type:6,data:r},{type:6,data:a},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];fa(t,C),C.push(...St(e[0].dims,e[1].dims));let E=["rank","rank"];s&&(C.push(...St(e[2].dims)),E.push("rank")),C.push(...St(n));return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${b};${f};${T};${S};${M};${v};${$};${x}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:C}),getShaderSource:r=>{let a=[{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}];ma(t,a);let i=f?4:1,u=xt(e[0].dataType),d=`\n fn setOutputAtIndex(flatIndex : i32, value : ${f?`vec4<${u}>`:u}) {\n result[flatIndex] = ${f?`vec4<${u}>`:u}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${f?`vec4<${u}>`:u}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${f?"/ 4":""}, value);\n }`,c=[Pt("x",e[0].dataType,e[0].dims.length,3===b?1:b),Pt("w",e[1].dataType,e[1].dims.length,i)],p=Ot("result",e[0].dataType,n.length,i);if(s){let t=Pt("bias",e[2].dataType,e[2].dims.length,i);c.push(t),d+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${f?`vec4<${u}>`:u} {\n return bias[coords.${l?"w":"y"}${f?"/ 4":""}];\n }`}return`\n ${ya("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${r.registerUniforms(a).declareVariables(...c,p)}\n ${d}\n ${Ca(l,T,S,M,s,t,k[0],k[1],k[2],u)}\n ${f?$a(w,_,u,void 0,!l,x):Sa(w,_,u,void 0,!l,x,!1,void 0,o)}`}}}})),ul=L((()=>{Do(),jo(),qo(),cl(),al(),Aa=(e,t,n)=>{let r=e.length>2,a=r?"value += b[output_channel];":"",i=e[0].dims,s=e[1].dims,o=s[0]/t.group,l="NHWC"===t.format,u=Ba(i,s,t.dilations,t.pads,t.strides,l),d=gt.size(u),c=[{type:12,data:d},{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:o}];fa(t,c),c.push(...St(i,s,u));let p=["rank","rank"];r&&(c.push(...St(e[2].dims)),p.push("rank")),c.push(...St(u));return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:p},getRunData:()=>({outputs:[{dims:n?n(u):u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:n=>{let o=Ot("output",e[0].dataType,u.length),d=xt(o.type.tensor),c=ha(t,o.type.value,d),p=Pt("x",e[0].dataType,i.length),h=Pt("w",e[1].dataType,s.length),f=[p,h];r&&f.push(Pt("b",e[2].dataType,e[2].dims));let m=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return ma(t,m),`\n ${n.registerUniforms(m).declareVariables(...f,o)}\n\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${o.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${l?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel / uniforms.output_channels_per_group;\n\n var value: ${o.type.value} = ${o.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = group_id * uniforms.w_shape[1] + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[${l?1:2}]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[${l?2:3}]) {\n continue;\n }\n\n let xVal = ${l?p.get("batch","xHeight","xWidth","input_channel"):p.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${h.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${a}\n ${c}\n ${o.setByOffset("global_idx","value")}\n }`}}},Ia=(e,t,n)=>{let r=e.length>2,a=Mt(n[3]),i=Mt(n[2]),s=gt.size(n)/a/i,o=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],l=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],u=[n[0],n[1],n[2],n[3]/a],d=[{type:12,data:s},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];fa(t,d),d.push(...St(o,l,u));let c=(i-1)*t.strides[1]+l[1];return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${c};${l[0]};${l[1]}`,inputDependencies:r?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d}),getShaderSource:n=>{let s=Ot("output",e[0].dataType,u.length,a),d=xt(s.type.tensor),p=ha(t,s.type.value,d),h=Pt("x",e[0].dataType,o.length,a),f=Pt("w",e[1].dataType,l.length,a),m=[h,f];r&&m.push(Pt("b",e[2].dataType,e[2].dims,a));let g=r?"value += b[output_channel];":"",_=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ma(t,_),`\n ${n.registerUniforms(_).declareVariables(...m,s)}\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${i}u;\n let col = (index1 % width1) * ${i}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${h.type.value}, ${c}>;\n var values: array<${s.type.value}, ${i}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${l[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${c}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${h.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${h.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) {\n let w_val = ${f.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${i}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${i}u; i++) {\n var value = values[i];\n ${g}\n ${p}\n ${s.set("batch","row","col + i","output_channel","value")};\n }\n }`}}}})),dl=L((()=>{Do(),jo(),ol(),qo(),al(),Pa=(e,t,n,r,a=!1)=>{let i=e[0].dims,s=e[1].dims,o=i[i.length-2],l=s[s.length-1],u=i[i.length-1],d=Mt(l),c=Mt(u),p=Mt(o),h=gt.size(n)/d/p,f=e.length>2,m=r?r.slice(0,-2):n.slice(0,-2),g=[gt.size(m),o,l],_=[{type:12,data:h},{type:12,data:o},{type:12,data:l},{type:12,data:u}];fa(t,_),_.push(...St(m,i,s)),f&&_.push(...St(e[2].dims)),_.push(...St(g));return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${d};${c};${p};${a}`,inputDependencies:f?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:_}),getShaderSource:r=>{let o=zt("batch_dims",e[0].dataType,m.length),l=Pt("a",e[0].dataType,i.length,c),u=Pt("b",e[1].dataType,s.length,d),h=Ot("output",e[0].dataType,g.length,d),_=xt(h.type.tensor),w=ha(t,h.type.value,_),y=[l,u],b="";if(f){let t=a?d:1;y.push(Pt("bias",e[2].dataType,e[2].dims.length,t)),b=""+(a?`value += bias[col / ${t}];`:`value += ${h.type.value}(bias[row + i]);`)}let v=i.slice(0,-2),$=s.slice(0,-2),x=Rt(v,m),T=Rt($,m),S=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ma(t,S);let M=(e,t)=>{let n=e.rank,r=e.name;if(2===n)return`var ${r}_indices = ${e.type.indices}(0u, 0u);`;let a=o.rank,i=`var ${r}_indices: ${e.type.indices};`;for(let e=n-2-1,t=a-1;e>=0;e--,t--)i+=`\n${r}_indices[${e}] = ${a>1?`batch_indices[${t}]`:"batch_indices"};`;return t.forEach((e=>{i+=`\n${r}_indices[${e}] = 0;`})),i+=`${r}_indices[${n-2}] = 0u;\n ${r}_indices[${n-1}] = 0u;`,i};return`\n ${r.registerUniforms(S).registerInternalVariables(o).declareVariables(...y,h)}\n ${r.mainStart()}\n ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let col = (global_idx % (uniforms.N / ${d})) * ${d};\n var index1 = global_idx / (uniforms.N / ${d});\n let stride1 = uniforms.M / ${p};\n let row = (index1 % stride1) * ${p};\n let batch = index1 / stride1;\n\n ${2===n.length?"":`let batch_indices = ${o.offsetToIndices("batch")};`}\n ${M(l,x)}\n let a_offset = ${l.indicesToOffset("a_indices")};\n ${M(u,T)}\n let b_offset = ${u.indicesToOffset("b_indices")};\n var values: array<${h.type.value}, ${p}>;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${c}) {\n ${(()=>{let e=`var a_data: ${l.type.value};`;for(let t=0;t{if(!e||2!==e.length)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.")},za=e=>{Oa(e.inputs);let t=mt.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],r=e.inputs[0].dims[e.inputs[0].dims.length-1];n<8&&r<8?e.compute(Pa(e.inputs,{activation:""},t)):e.compute(ka(e.inputs,{activation:""},t))}})),cl=L((()=>{jo(),ll(),ol(),ul(),al(),dl(),Ho(),Ba=(e,t,n,r,a,i)=>{let s=e[0],o=e.slice(i?1:2,i?3:4),l=o.length,u=t[0],d=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),c=o.map(((e,t)=>e+r[t]+r[t+l])).map(((e,t)=>Math.floor((e-d[t]+a[t])/a[t])));return c.splice(0,0,s),c.splice(i?3:1,0,u),c},Fa=[2,3,1,0],Ra=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Da=(e,t)=>{let n=e.kernelShape.slice();for(let e=2;e{let t=ga(e),n=e.format;return{autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],format:n,dilations:e.dilations,group:e.group,kernelShape:e.kernel_shape,pads:e.pads,strides:e.strides,wIsConst:e.w_is_const(),...t,cacheKey:`${e.format};${t.activation};`}},Na=(e,t,n)=>{let r=Da(n,t),a="NHWC"===n.format;if(1!==n.group){if(!e.adapterInfo.isArchitecture("ampere")&&a&&t[1].dims[0]===n.group&&1===t[1].dims[1]&&1===n.dilations[0]&&1===n.dilations[1]){let i=Ba(t[0].dims,t[1].dims,n.dilations,r.pads,n.strides,a),s=e.kernelCustomData.wT??e.compute(Wt(t[1],Fa),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=s);let o=[t[0],s];3===t.length&&o.push(t[2]),e.compute(Ia(o,r,i),{inputs:o})}else e.compute(Aa(t,r));return}let i=3===t.length,s=t[0].dims[a?1:2],o=t[0].dims[a?2:3],l=t[0].dims[a?3:1],u=t[1].dims[2],d=t[1].dims[3],c=Ba(t[0].dims,t[1].dims,n.dilations,r.pads,n.strides,a),p=c[a?1:2],h=c[a?2:3],f=c[a?3:1],m=a&&u===s&&d===o&&0===n.pads[0]&&0===n.pads[1];if(m||1===u&&1===d&&1===n.dilations[0]&&1===n.dilations[1]&&1===n.strides[0]&&1===n.strides[1]&&0===n.pads[0]&&0===n.pads[1]){let u,d,g,_=c[0],w=[];if(a){let r=e.kernelCustomData.wT??e.compute(Wt(t[1],Fa),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),m){let e=s*o*l;u=t[0].reshape([1,_,e]),d=r.reshape([1,e,f]),g=[1,_,f]}else u=t[0].reshape([_,s*o,l]),d=r.reshape([1,l,f]),g=[_,p*h,f];w.push(u),w.push(d)}else u=t[0].reshape([_,l,s*o]),d=t[1].reshape([1,f,l]),g=[_,f,p*h],w.push(d),w.push(u);i&&w.push(t[2]);let y=g[2],b=w[0].dims[w[0].dims.length-1];return void(y<8&&b<8?e.compute(Pa(w,r,c,g,a),{inputs:w}):e.compute(ka(w,r,c,g,a),{inputs:w}))}let g=e.kernelCustomData.wT??e.compute(Wt(t[1],Fa),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let _=[t[0],g];i&&_.push(t[2]);let w=a?p*h:f,y=a?f:p*h,b=u*d*l;e.compute(Ea(_,r,c,w,y,b,i,!0),{inputs:_})},Ua=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[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]])];3===e.inputs.length&&r.push(e.inputs[2]);let a=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),s=[1].concat(t.dilations),o=[1].concat(t.kernelShape),l=Da({...t,pads:a,strides:i,dilations:s,kernelShape:o},r);e.compute(Aa(r,l,(e=>n?[e[0],e[2],e[3]]:[])))},Wa=(e,t)=>{Ra(e.inputs,t),3===e.inputs[0].dims.length?Ua(e,t):Na(e,e.inputs,t)}})),pl=L((()=>{Do(),No(),qo(),al(),il(),sl(),ol(),Va=(e,t=!1,n,r,a=4)=>{let i=e?"\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",s=e?"row":"col",o=e?"col":"row",l=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${s} / outWidth;\n let outCol = ${s} % outWidth;\n\n let WRow = ${o} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${o} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])"}) || fract(xR) > 0.0) {\n return ${r}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])"}) || fract(xC) > 0.0) {\n return ${r}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${o} % inChannels;\n ${e?"\n let coord = vec4(batch, iXR, iXC, xCh);\n ":"\n let coord = vec4(batch, xCh, iXR, iXC);\n "}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${a}];`,u=e?`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${l}\n }\n return ${r}(0.0);`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${l}\n }\n return ${r}(0.0);`,d=`\n let col = colIn * ${a};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${(e=>{switch(e){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${r}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${e} is not supported.`)}})(a)}\n }\n return ${r}(0.0);\n `,c=ha(n,r);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${r} {\n ${e?u:d}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${r} {\n ${e?d:u}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${r}) {\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${i}\n ${wa(t)}\n ${c}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${a}] = value;\n }\n }`},Ga=(e,t,n,r,a,i,s,o)=>{let l="NHWC"===t.format,u=l?e[0].dims[3]:e[0].dims[1],d=n[0],c=l?n[2]:n[3],p=l?n[1]:n[2],h=l?n[3]:n[1],f=l?u%4==0&&h%4==0:c%4==0&&h%4==0,m=l?h:c*p,g=l?c*p:h,_=f?[8,8,1]:[m<=4||g<=4?4:16,m>4&&g<=4?4:16,1],w=f?[4,4,1]:[m<=4?1:4,m>4&&g<=4?1:4,1],y=[Math.ceil(m/_[0]/w[0]),Math.ceil(g/_[1]/w[1]),Math.ceil(d/_[2]/w[2])];at("verbose",(()=>`[conv_backprop_mm_webgpu] dispatch = ${y}`));let b=f?4:1,v=Math.max(_[0]*b,_[1]),$=f?4:1,x=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],T=[x[0]+(t.dilations[0]<=1?0:(x[0]-1)*(t.dilations[0]-1)),x[1]+(t.dilations[1]<=1?0:(x[1]-1)*(t.dilations[1]-1))],S=[T[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),T[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],M=[{type:6,data:r},{type:6,data:a},{type:6,data:i},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:x},{type:6,data:S}];fa(t,M),M.push(...St(e[0].dims,e[1].dims));let k=["rank","rank"];s&&(M.push(...St(e[2].dims)),k.push("rank")),M.push(...St(n));return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${w};${_};${f}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:M}),getShaderSource:r=>{let a=Pt("x",e[0].dataType,e[0].dims.length,$),i=Pt("w",e[1].dataType,e[1].dims.length,1),u=Ot("result",e[0].dataType,n.length,$),d=[a,i],c="";if(s){let t=Pt("bias",e[2].dataType,e[2].dims.length,$);d.push(t),c+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${t.type.value} {\n return bias[coords.${l?"w":"y"}${f?"/ 4":""}];\n }`}let p=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:x.length},{name:"pads",type:"i32",length:S.length}];ma(t,p);let h=xt(e[0].dataType,1);if("f16"!==h&&"f32"!==h)throw new Error(`elemType ${h} is not supported.`);return`\n ${ya("uniforms.result_strides")}\n ${r.registerUniforms(p).declareVariables(...d,u)};\n ${c}\n ${Va(l,s,t,a.type.value,b)}\n ${f?$a(w,_,h,void 0,!l,v):Sa(w,_,h,void 0,!l,v,!1,void 0,o)}`}}}})),hl=L((()=>{Do(),No(),jo(),qo(),ja=(e,t,n,r,a,i=!1,s,o,l=!1)=>{let u=l?1:2,d=l?2:3,c=l?3:1,p=i?2:1,h=`\n fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${s}>`:s}) {\n result[flatIndex] = ${i?`vec4<${s}>`:s}(value);\n }`;r&&(h+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${s}>`:s} {\n return bias[coords.${l?"w":"y"}${i?"/ 4":""}];\n }`);let f=i?4:1,m=Pt("W",t[1].dataType,t[1].dims.length,f),g=Pt("Dy",t[0].dataType,t[0].dims.length,f),_=[g,m];r&&_.push(Pt("bias",t[2].dataType,[n[c]].length,f));let w=Ot("result",t[0].dataType,n.length,f),y=`{\n let batch: u32 = ${a?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${a?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${a?"global_id.y":"workgroup_id.y"} * ${p};\n let d1: u32 = ${a?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${p}>;\n for (var i = 0; i < ${p}; i++) {\n dotProd[i] = vec4<${s}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${s}(dyCorner.x) + ${s}(wR)) / ${s}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${s}(dyCorner.y) + ${s}(wC)) / ${s}(uniforms.strides.y);\n let dyC2 = (${s}(dyCorner.y) + 1.0 + ${s}(wC)) / ${s}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${s}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${g.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${g.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${c}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${g.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${m.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${g.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${p}; i = i + 1) {\n let value = dotProd[i] + ${r?"bias[c+i]":`vec4<${s}>(0.0)`};\n ${w.set("batch","r","c + i","d1","value")};\n }\n }`,b=`\n let outputIndices = ${w.offsetToIndices("global_idx")};\n let batch = ${w.indicesGet("outputIndices",0)};\n let d1 = ${w.indicesGet("outputIndices",c)};\n let r = ${w.indicesGet("outputIndices",u)};\n let c = ${w.indicesGet("outputIndices",d)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${s}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${u}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${d}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${l?g.get("batch","idyR","idyC","inputChannel"):g.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${m.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${r?"bias[d1]":`${s}(0.0)`};\n ${w.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(o).declareVariables(..._,w)}\n ${h}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${i?y:b}}`},qa=(e,t,n)=>{let r=e.length>2,a=t.outputShape,i=gt.size(a),s=[Math.ceil(i/64),1,1];at("verbose",(()=>`[conv2d_backprop_webgpu] dispatch = ${s}`));let o="NHWC"===t.format,l=["rank","rank"],u=[t.strides[0],t.strides[1]],d=[t.kernelShape[o?1:2],t.kernelShape[o?2:3]],c=[t.dilations[0],t.dilations[1]],p=[d[0]+(t.dilations[0]<=1?0:(t.kernelShape[o?1:2]-1)*(t.dilations[0]-1)),d[1]+(t.dilations[1]<=1?0:(t.kernelShape[o?2:3]-1)*(t.dilations[1]-1))],h=[p[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),p[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],f=t.group,m=e[1].dims,g=m[0]/f,_=m[1],w=[{type:6,data:i},{type:12,data:u},{type:12,data:d},{type:12,data:c},{type:12,data:p},{type:6,data:h},{type:12,data:g},{type:12,data:_},...St(e[0].dims,e[1].dims)];r&&(w.push(...St(e[2].dims)),l.push("rank")),w.push(...St(a));let y=1===s[1]&&1===s[2];return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:n?n(a):a,dataType:e[0].dataType}],programUniforms:w}),getShaderSource:t=>{let n=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:u.length},{name:"filter_dims",type:"u32",length:d.length},{name:"dilations",type:"u32",length:d.length},{name:"effective_filter_dims",type:"u32",length:p.length},{name:"pads",type:"i32",length:h.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],i=xt(e[0].dataType);return`${ja(t,e,a,r,y,false,i,n,o)}`}}}})),fl=L((()=>{pl(),hl(),al(),Ho(),Ha=(e,t,n,r,a,i)=>(e-1)*t+n+(r-1)*a+1-i,Ka=(e,t,n,r,a)=>{let i=Math.floor(e/2);"SAME_UPPER"===t?(n[r]=i,n[a]=e-i):"SAME_LOWER"===t&&(n[r]=e-i,n[a]=i)},Ya=(e,t,n,r,a,i,s,o,l,u)=>{let d=e.length-2,c=0===u.length;if(0===l.length)for(let e=0;e{let n=e.kernelShape.slice();if(0===e.kernelShape.length||0===e.kernelShape.reduce(((e,t)=>e*t),1)){n.length=0;for(let e=2;ee+t),0)){let e=t[0].dims.length-2;l=new Array(e).fill(1)}let u=e.strides.slice();if(0===u.reduce(((e,t)=>e+t),0)){let e=t[0].dims.length-2;u=new Array(e).fill(1)}Ya(o,n,l,e.autoPad,e.group,a,u,r,s,i);let d=Object.assign({},e);return Object.assign(d,{kernelShape:n,pads:a,outputPadding:s,outputShape:i,dilations:l,strides:u}),d},Qa=e=>{let t=ga(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],a=e.dilations,i=e.group,s=e.kernelShape,o=e.pads,l=e.strides,u=e.wIsConst();return{autoPad:r,format:n,dilations:a,group:i,kernelShape:s,outputPadding:e.outputPadding,outputShape:e.outputShape,pads:o,strides:l,wIsConst:u,...t,cacheKey:`${e.format};${t.activation};`}},Za=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)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");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");let r=e[0].dims.length-2;if(t.dilations.reduce(((e,t)=>e+t),0)>0&&t.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(t.strides.reduce(((e,t)=>e+t),0)>0&&t.strides.length!==r)throw new Error(`strides should be ${r}D`);if(t.pads.reduce(((e,t)=>e+t),0)>0&&t.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(t.outputPadding.length!==r&&0!==t.outputPadding.length)throw new Error(`output_padding should be ${r}D`);if(t.kernelShape.reduce(((e,t)=>e+t),0)>0&&0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Ja=[2,3,1,0],ei=(e,t,n)=>{let r=Xa(n,t),a="NHWC"===n.format,i=r.outputShape,s=i[a?3:1],o=t[0].dims[a?3:1];if(1!==r.group||1===s&&1===o)return void e.compute(qa(t,r));let l=i[a?1:2],u=i[a?2:3],d=a?l*u:s,c=a?s:l*u,p=t[1].dims[2]*t[1].dims[3]*o,h=e.kernelCustomData.wT??e.compute(Wt(t[1],Ja),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=h);let f=[t[0],h],m=3===t.length;m&&(a||1!==t[2].dims.length?f.push(t[2]):f.push(t[2].reshape([t[2].dims[0],1,1]))),e.compute(Ga(f,r,i,d,c,p,m,!0),{inputs:f})},ti=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[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]])];3===r.length&&r.push(e.inputs[2]);let a=t.kernelShape;(0===a.length||0===a[0])&&(a=[e.inputs[1].dims[2]]);let i=t.dilations;(0===i.length||0===i[0])&&(i=[1]);let s=t.strides;(0===s.length||0===s[0])&&(s=[1]);let o=t.pads;0===o.length&&(o=[0,0]),o=[0,o[0],0,o[1]],s=[1].concat(s),i=[1].concat(i),a=[1].concat(a);let l=Xa({...t,pads:o,strides:s,dilations:i,kernelShape:a},r);e.compute(qa(r,l,(e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])))},ni=(e,t)=>{Za(e.inputs,t),3===e.inputs[0].dims.length?ti(e,t):ei(e,e.inputs,t)}})),ml=L((()=>{Do(),jo(),Go(),qo(),ri=(e,t,n,r)=>{let a=gt.size(t),i=t.length,s=Pt("input",e,i),o=Ot("output",e,i),l=6===n.dataType?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),u=gt.normalizeAxis(l,i);return{name:"CumSum",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},{type:6,data:u},...St(t,t)]}),getShaderSource:e=>{let t=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,n=At("uniforms.input_shape","uniforms.axis",i),a=r.reverse?t+(r.exclusive?" + 1":""):"0",l=r.reverse?n:t+(r.exclusive?"":" + 1");return`\n ${e.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,o)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${o.offsetToIndices("global_idx")};\n var sum = ${o.type.value}(0);\n let first : i32 = ${a};\n let last : i32 = ${l};\n for (var i : i32 = first; i < last; i++) {\n ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${s.getByIndices("inputIndices")};\n }\n ${o.setByOffset("global_idx","sum")};\n }`}}},ai=(e,t)=>{let n=e.inputs[0].dims,r=e.inputs[0].dataType,a=e.inputs[1];e.compute(ri(r,n,a,t),{inputs:[0]})},ii=e=>{let t=1===e.exclusive,n=1===e.reverse;return ht({exclusive:t,reverse:n})}})),gl=L((()=>{Do(),jo(),Go(),qo(),li="^"+(oi="("+(si="[a-zA-Z]|\\.\\.\\.")+")+")+"$",ui="^"+("("+oi+",)*"+oi)+"$",di=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);void 0===n?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},ci=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,r]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(ui)))throw new Error("Invalid LHS term");if(n.split(",").forEach(((t,n)=>{let r=e[n].dims.slice();if(!t.match(RegExp(li)))throw new Error("Invalid LHS term");let a=this.processTerm(t,!0,r,n);this.lhs.push(a)})),""===r)r+=[...this.symbolToInfo.entries()].filter((([e,t])=>1===t.count||"..."===e)).map((([e])=>e)).join("");else if(!r.match(RegExp(oi)))throw new Error("Invalid RHS");r.match(RegExp(si,"g"))?.forEach((e=>{if("..."===e)this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let t=this.symbolToInfo.get(e);if(void 0===t)throw new Error("Invalid RHS symbol");this.outputDims.push(t.dimValue)}})),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(e,t,n){let r=this.symbolToInfo.get(e);if(void 0!==r){if(r.dimValue!==t&&1!==r.count)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,r)}processTerm(e,t,n,r=-1){let a=n.length,i=!1,s=[],o=0;if(!e.match(RegExp(li))&&!t&&""!==e)throw new Error("Invalid LHS term");let l=e.match(RegExp(si,"g")),u=new di(r);return l?.forEach(((e,d)=>{if("..."===e){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let e=a-l.length+1;if(e<0)throw new Error("Ellipsis out of bounds");if(s=n.slice(o,o+e),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else{if(!t)throw new Error("Ellipsis must be specified in the LHS");this.hasEllipsis=!0,this.ellipsisDims=s}for(let e=0;ee+"_max",hi=(e,t,n,r)=>{let a=e.map((e=>e.length)).map(((e,n)=>Pt(`input${n}`,t,e))),i=gt.size(r),s=Ot("output",t,r.length),o=[...n.symbolToInfo.keys()].filter((e=>!n.rhs.symbolToIndices.has(e)));return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map((()=>"rank"))},getRunData:()=>{let a=o.filter((e=>n.symbolToInfo.has(e))).map((e=>({type:12,data:n.symbolToInfo.get(e)?.dimValue||0})));a.push({type:12,data:i});let s=e.map(((e,t)=>[...St(e)])).reduce(((e,t)=>e.concat(t)),a);return s.push(...St(r)),{outputs:[{dims:r,dataType:t}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:s}},getShaderSource:e=>{let t=[],r=[],i=[],l=[],u=[],d=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach(((e,o)=>{if(n.rhs.symbolToIndices.has(o)){let r=n.rhs.symbolToIndices.get(o)?.[0];void 0!==r&&n.lhs.forEach(((n,i)=>{if(e.inputIndices.includes(i)){let e=n.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{t.push(`${a[i].indicesSet(`input${i}Indices`,e,s.indicesGet("outputIndices",r))}`)}))}}))}else n.lhs.forEach(((t,n)=>{if(e.inputIndices.includes(n)){let e=t.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{r.push(`${a[n].indicesSet(`input${n}Indices`,e,`${o}`)}`)})),u.push(`prod *= ${a[n].getByIndices(`input${n}Indices`)};`)}})),i.push(`for(var ${o}: u32 = 0; ${o} < uniforms.${pi(o)}; ${o}++) {`),l.push("}")}));let c=d?[...t,`let sum = ${a.map(((e,t)=>e.getByIndices(`input${t}Indices`))).join(" * ")};`]:[...t,"var sum = 0.0;",...i,...r,"var prod = 1.0;",...u,"sum += prod;",...l];return`\n ${e.registerUniforms(o.map((e=>({name:`${pi(e)}`,type:"u32"})))).registerUniform("outputSize","u32").declareVariables(...a,s)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${s.offsetToIndices("global_idx")};\n ${a.map(((e,t)=>`var input${t}Indices: ${a[t].type.indices};`)).join("\n")}\n ${c.join("\n")};\n ${s.setByOffset("global_idx","sum")};\n }`}}},fi=(e,t)=>{let n=new ci(e.inputs,t.equation),r=n.outputDims,a=e.inputs.map(((e,t)=>e.dims));e.compute(hi(a,e.inputs[0].dataType,n,r))},mi=e=>{let t=e.equation.replace(/\s+/g,"");return ht({equation:t})}})),_l=L((()=>{Do(),jo(),qo(),gi=e=>{if(!e||2!==e.length)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=n.length{let n=e.length-t.length,r=[];for(let t=0;te.length>t.length?_i(e,t):_i(t,e),yi=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=wi(t,n),a=e[0].dataType,i=9===a?4:1,s=Math.ceil(gt.size(r)/i),o=[{type:12,data:s},...St(t,r)];return{name:"Expand",shaderCache:{hint:`${r.length}`,inputDependencies:["rank"]},getShaderSource:e=>{let n,s=Pt("input",a,t.length,i),o=Ot("output",a,r.length,i);if(9===a){let e=(e,t,n="")=>`\n let outputIndices${t} = ${o.offsetToIndices(`outputOffset + ${t}u`)};\n let offset${t} = ${s.broadcastedIndicesToOffset(`outputIndices${t}`,o)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${s.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${i};\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n ${o.setByOffset("global_idx","data")}\n }`}else n=`\n let outputIndices = ${o.offsetToIndices("global_idx")};\n let inputOffset = ${s.broadcastedIndicesToOffset("outputIndices",o)};\n ${o.setByOffset("global_idx",s.getByOffset("inputOffset"))}\n }`;return`\n ${e.registerUniform("vec_size","u32").declareVariables(s,o)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${n}`},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},bi=e=>{gi(e.inputs),e.compute(yi(e.inputs),{inputs:[0]})}})),wl=L((()=>{Do(),jo(),qo(),el(),vi=e=>{let t=e[0].dataType,n=gt.size(e[0].dims),r=gt.size(e[1].dims),a=r%4==0;return{name:"FastGeluWithBias",shaderCache:{hint:`${a}`,inputDependencies:["type","type"]},getShaderSource:e=>{let n=Pt("x",t,[1],4),r=Pt("bias",t,[1],4),i=Ot("y",t,[1],4),s=e=>`\n let bias${e}_offset: u32 = (global_idx * 4 + ${e}) % uniforms.bias_size;\n let bias${e} = ${r.getByOffset(`bias${e}_offset / 4`)}[bias${e}_offset % 4];`,o=a?`\n let bias = ${r.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${s(0)}${s(1)}${s(2)}${s(3)}\n let bias = ${n.type.value}(bias0, bias1, bias2, bias3);`;return`${e.registerUniforms([{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}]).declareVariables(n,r,i)}\n\n ${Nr(Tt(t))}\n\n ${e.mainStart(vt)}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${n.getByOffset("global_idx")};\n ${o}\n let x_in = x + bias;\n ${i.setByOffset("global_idx",Ur("x_in"))}\n }`},getRunData:e=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/vt/4)}})}},$i=e=>{e.inputs.length<2||0===gt.size(e.inputs[1].dims)?Wr(e):e.compute(vi(e.inputs))}})),yl=L((()=>{Do(),jo(),Go(),qo(),xi=e=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.")},Ti=(e,t)=>{let n=e[0].dims,r=e[1].dims,a=n.length,i=gt.normalizeAxis(t.axis,a),s=n.slice(0);s.splice(i,1,...r);let o=n[i],l=9===e[0].dataType?4:1,u=Math.ceil(gt.size(s)/l),d=[{type:12,data:u},{type:6,data:o},{type:12,data:i},...St(e[0].dims,e[1].dims,s)];return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:t=>{let n,o=Pt("data",e[0].dataType,e[0].dims.length,l),u=Pt("inputIndices",e[1].dataType,e[1].dims.length),d=Ot("output",e[0].dataType,s.length,l),c=e=>{let t=r.length,n=`var indicesIndices${e} = ${u.type.indices}(0);`;for(let r=0;r1?`indicesIndices${e}[${r}]`:`indicesIndices${e}`} = ${s.length>1?`outputIndices${e}[uniforms.axis + ${r}]`:`outputIndices${e}`};`;n+=`\n var idx${e} = ${u.getByIndices(`indicesIndices${e}`)};\n if (idx${e} < 0) {\n idx${e} = idx${e} + uniforms.axisDimLimit;\n }\n var dataIndices${e} : ${o.type.indices};\n `;for(let r=0,o=0;r1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = u32(idx${e});`,o+=t):(n+=`${a>1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = ${s.length>1?`outputIndices${e}[${o}]`:`outputIndices${e}`};`,o++);return n};if(9===e[0].dataType){let e=(e,t,n="")=>`\n let outputIndices${t} = ${d.offsetToIndices(`outputOffset + ${t}u`)};\n ${c(t)};\n let offset${t} = ${o.indicesToOffset(`dataIndices${t}`)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${o.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${l};\n var value = vec4(0);\n ${e("value",0,"u32")}\n ${e("value",1,"u32")}\n ${e("value",2,"u32")}\n ${e("value",3,"u32")}\n ${d.setByOffset("global_idx","value")}\n `}else n=`\n let outputIndices = ${d.offsetToIndices("global_idx")};\n ${c("")};\n let value = ${o.getByIndices("dataIndices")};\n ${d.setByOffset("global_idx","value")};\n `;return`\n ${t.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(o,u,d)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${n}\n }`}}},Si=e=>ht({axis:e.axis}),Mi=(e,t)=>{let n=e.inputs;xi(n),e.compute(Ti(e.inputs,t))}})),bl=L((()=>{Do(),jo(),Go(),qo(),ki=e=>{if(!e||2!==e.length)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\n indices input tensors be of same rank.")},Ci=(e,t)=>{let n=e[0].dims,r=e[0].dataType,a=n.length,i=e[1].dims,s=e[1].dataType,o=gt.normalizeAxis(t.axis,a),l=n[o],u=i.slice(0),d=gt.size(u),c=Pt("input",r,a),p=Pt("indicesInput",s,i.length),h=Ot("output",r,u.length),f=[{type:12,data:d},{type:6,data:l},{type:12,data:o}];return f.push(...St(n,i,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f}),getShaderSource:e=>`\n ${e.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(c,p,h)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${h.offsetToIndices("global_idx")};\n\n var idx = ${p.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${c.type.indices}(outputIndices);\n ${c.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${c.getByIndices("inputIndices")};\n\n ${h.setByOffset("global_idx","value")};\n }`}},Ei=e=>ht({axis:e.axis}),Ai=(e,t)=>{let n=e.inputs;ki(n),e.compute(Ci(e.inputs,t))}})),vl=L((()=>{Do(),jo(),qo(),Ii=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(3===e.length&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Pi=(e,t)=>{let n=e[0].dims.slice(),r=e[1].dims.slice(),[a,i,s]=wt.getShapeOfGemmResult(n,t.transA,r,t.transB,3===e.length?e[2].dims:void 0),o=[a,i];if(!o)throw new Error("Can't use gemm on the given tensors");let l=gt.size(o),u=[{type:12,data:l},{type:12,data:a},{type:12,data:i},{type:12,data:s},{type:1,data:t.alpha},{type:1,data:t.beta}],d=["type","type"];3===e.length&&(u.push(...St(e[2].dims)),d.push("rank")),u.push(...St(o));return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:n=>{let r="";t.transA&&t.transB?r="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?r="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?r="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(r="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let a=1===t.alpha?"":"value *= uniforms.alpha;",i=Pt("a",e[0].dataType,e[0].dims),s=Pt("b",e[1].dataType,e[1].dims),l=i.type.value,u=null,d=[i,s];3===e.length&&(u=Pt("c",e[2].dataType,e[2].dims.length),d.push(u));let c=Ot("output",e[0].dataType,o.length);d.push(c);return`\n ${n.registerUniforms([{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"}]).declareVariables(...d)}\n\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${l}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${r}\n }\n\n ${a}\n ${null!=u?`let cOffset = ${u.broadcastedIndicesToOffset("vec2(m, n)",c)}; value += ${l}(uniforms.beta) * ${u.getByOffset("cOffset")};`:""}\n output[global_idx] = value;\n }`}}},Oi=e=>({transA:e.transA,transB:e.transB,alpha:e.alpha,beta:e.beta,cacheKey:`${e.transA};${e.transB};${1===e.alpha}`}),zi=(e,t)=>{Ii(e.inputs),e.compute(Pi(e.inputs,t))}})),$l=L((()=>{Do(),jo(),qo(),Bi=(e,t)=>{let n=e[0].dims,r=n,a=gt.sizeToDimension(n,2),i=gt.sizeFromDimension(n,2),s=Mt(i),o=i/s,l=[n[0],n[1],o],u=[{type:12,data:i},{type:12,data:o}];u.push(...St(l,l));return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${s}`,inputDependencies:["rank","type","type"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:a},programUniforms:u}),getShaderSource:n=>{let r=Pt("x",e[0].dataType,l.length,s),a=Pt("scale",e[1].dataType,e[1].dims),i=Pt("bias",e[2].dataType,e[2].dims),o=Ot("output",e[0].dataType,l.length,s),u=[r,a,i,o],d=r.type.value,c=1===s?"f32":`vec${s}`;return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${c}, 64>;\n const workgroupSize = 64u;\n ${n.registerUniforms([{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}]).declareVariables(...u)}\n ${n.mainStart(64)}\n let norm = global_idx / workgroupSize;\n let batch = norm / uniforms.x_shape[1];\n let channel = norm % uniforms.x_shape[1];\n let localIndex = local_id.x;\n\n // initialize workgroup memory\n var initial = ${c}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${c}(${r.get("batch","channel","h")});\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the mean of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n meanShared = ${Et("workgroupShared[0]",s)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${c}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${c}(${r.get("batch","channel","h")}) - ${c}(meanShared);\n initial = initial + deviation * deviation;\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the sum of square of deviation of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n squaredNormShared = ${Et("workgroupShared[0]",s)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${a.getByOffset("channel")});\n let channelShift = f32(${i.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${r.get("batch","channel","h")} * ${d}(${c}(channelScale)) + ${d}(${c}(channelShift));\n ${o.set("batch","channel","h","value")};\n }\n }`}}},Fi=(e,t,n,r,a,i,s,o)=>{let l=Mt(s),u=64,d=1===l?"vec2f":`mat2x${l}f`,c=1===l?"f32":`vec${l}f`,p=(e,t)=>`${d}(${e}, ${t})`,h=a*s/l,f=[{type:12,data:Math.ceil(i/u)},{type:12,data:i},{type:12,data:Math.floor(s/l)},{type:12,data:Math.floor(i*s/l)}],m=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:[a,s,u,2],dataType:1}],dispatchGroup:{x:a*s/l},programUniforms:f}),getShaderSource:e=>{let n=Pt("input",t.dataType,t.dims,l);return`\n ${e.declareVariables(n)}\n @group(0) @binding(1) var output : array<${d}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${e.mainStart(u)}\n let currentImageNumber = global_idx / 64 / uniforms.C;\n let currentChannelNumber = (global_idx / 64) % uniforms.C;\n let wgId = global_idx % 64;\n let wgOffset = wgId * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${kt("f32",l)};\n var squaredSum = ${kt("f32",l)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${c}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${p("sum","squaredSum")};\n }`}},{inputs:[t],outputs:[-1]})[0],g=[{type:12,data:h},{type:12,data:i},{type:12,data:Math.floor(s/l)},{type:12,data:Math.floor(u*s/l)}];return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o}`,inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:[a,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g}),getShaderSource:e=>{let t=Pt("scale",n.dataType,n.dims,l),a=Pt("bias",r.dataType,r.dims,l);return`\n @group(0) @binding(0) var input : array<${d}>;\n @group(0) @binding(1) var scale : array<${t.type.storage}>;\n @group(0) @binding(2) var bias : array<${a.type.storage}>;\n @group(0) @binding(3) var output : array<${d}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")}\n let currentImageNumber = global_idx / uniforms.C;\n let currentChannelNumber = global_idx % uniforms.C;\n\n let offset = currentImageNumber * uniforms.image_size;\n var sum = ${kt("f32",l)};\n var squaredSum = ${kt("f32",l)};\n for (var i: u32 = 0; i < min(64, uniforms.H); i++) {\n let value = input[offset + i + currentChannelNumber * 64];\n sum += value[0];\n squaredSum += value[1];\n }\n sum = sum / f32(uniforms.H);\n squaredSum = squaredSum / f32(uniforms.H);\n let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${o}));\n let channelScale = invStdDev * ${c}(scale[currentChannelNumber]);\n let channelShift = ${c}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${p("channelScale","channelShift")};\n }`}},{inputs:[m,n,r],outputs:[-1]})[0]},Ri=(e,t,n)=>{let r=t[0].dims,a=r,i=r[0],s=r[r.length-1],o=gt.sizeFromDimension(r,1)/s,l=Mt(s),u=gt.size(a)/l,d=[{type:12,data:o},{type:12,data:Math.floor(s/l)}],c=Fi(e,t[0],t[1],t[2],i,o,s,n.epsilon);e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:e=>{let n=xt(t[0].dataType),r=1===l?"vec2f":`mat2x${l}f`,i=1===l?n:`vec${l}<${n}>`,s=Pt("input",t[0].dataType,t[0].dims,l),o=Ot("output",t[0].dataType,a,l);return`\n @group(0) @binding(0) var input : array<${s.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${r}>;\n @group(0) @binding(2) var output : array<${o.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${e.mainStart()}\n let currentImageNumber = global_idx / (uniforms.C * uniforms.H);\n let currentChannelNumber = global_idx % uniforms.C;\n\n let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber;\n let scale = scaleInput[scaleOffset];\n output[global_idx] = fma(input[global_idx], ${i}(scale[0]), ${i}(scale[1]));\n }`}},{inputs:[t[0],c]})},Di=(e,t)=>{"NHWC"===t.format?Ri(e,e.inputs,t):e.compute(Bi(e.inputs,t))}})),xl=L((()=>{Do(),jo(),qo(),Li=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Ni=(e,t,n)=>{let r=e[0].dims,a=e[1],i=e[2],s=r,o=gt.normalizeAxis(t.axis,r.length),l=gt.sizeToDimension(r,o),u=gt.sizeFromDimension(r,o),d=gt.size(a.dims),c=i?gt.size(i.dims):0;if(d!==u||i&&c!==u)throw new Error(`Size of X.shape()[axis:] == ${u}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${d} and bias size of ${c}`);let p=[];for(let e=0;e1,_=n>2,w=[{dims:s,dataType:e[0].dataType}];return g&&w.push({dims:p,dataType:1}),_&&w.push({dims:p,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${h};${n}`,inputDependencies:f},getRunData:()=>({outputs:w,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:m}),getShaderSource:t=>{let n=xt(e[0].dataType),r=[Pt("x",e[0].dataType,e[0].dims,h),Pt("scale",a.dataType,a.dims,h)];i&&r.push(Pt("bias",i.dataType,i.dims,h)),r.push(Ot("output",e[0].dataType,s,h)),g&&r.push(Ot("mean_data_output",1,p)),_&&r.push(Ot("inv_std_output",1,p));return`\n ${t.registerUniforms([{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...r)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${kt("f32",h)};\n var mean_square_vector = ${kt("f32",h)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${Ct(n,h,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${Et("mean_vector",h)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${Et("mean_square_vector",h)} / uniforms.norm_size - mean * mean + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${Ct(n,h,"x[j + offset]")};\n let f32scale = ${Ct(n,h,"scale[j]")};\n output[j + offset] = ${r[0].type.value}((f32input - mean) * inv_std_dev * f32scale\n ${i?`+ ${Ct(n,h,"bias[j]")}`:""}\n );\n }\n\n ${g?"mean_data_output[global_idx] = mean":""};\n ${_?"inv_std_output[global_idx] = inv_std_dev":""};\n }`}}},Ui=(e,t)=>{Li(e.inputs),e.compute(Ni(e.inputs,t,e.outputCount))}})),Tl=L((()=>{Do(),jo(),Go(),qo(),Wi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],r=n.dims.length;if(n.dims[r-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let a=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,s=e[1];if(!gt.areEqual(s.dims,[t.n,a,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=e[2].dims;if(gt.size(o)!==t.n*a)throw new Error("scales input size error.");if(4===e.length){let n=e[3].dims,r=t.bits>4?t.n*a:t.n*Math.floor((a+1)/2);if(gt.size(n)!==r)throw new Error("zeroPoints input size error.")}},Vi=(e,t)=>{let n=e[0].dims,r=n.length,a=n.slice(0,r-1).concat(t.n),i=n[r-2],s=t.blockSize/8*t.bits/4,o=Mt(i),l=Mt(t.n),u=Mt(t.k),d=Mt(s),c=gt.size(a)/l/o,p=[{type:12,data:c},{type:12,data:t.k},{type:12,data:t.n},{type:12,data:t.accuracyLevel},{type:12,data:t.bits},{type:12,data:t.blockSize}],h=n.slice();h.splice(-1,1,t.k/u);let f=gt.convertShape(e[1].dims).slice();f.splice(-1,1,s/d),p.push(...St(h)),p.push(...St(f)),p.push(...St(e[2].dims)),4===e.length&&p.push(...St(gt.convertShape(e[3].dims)));let m=a.slice();m.splice(-1,1,t.n/l),p.push(...St(m));return{name:"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:n=>{let i=Pt("a",e[0].dataType,h.length,u),c=Pt("b",12,f.length,d),p=Pt("scales",e[2].dataType,e[2].dims.length),m=[i,c,p],g=4===e.length?Pt("zero_points",12,e[3].dims.length):void 0;g&&m.push(g);let _=Ot("output",e[0].dataType,a.length,l),w=Math.floor((t.k+t.blockSize-1)/t.blockSize),y=xt(e[0].dataType),b=(()=>{switch(u){case 1:return`array<${y}, 8>`;case 2:return`mat4x2<${y}>`;case 4:return`mat2x4<${y}>`;default:throw new Error(`${u}-component is not supported.`)}})(),v=`\n fn dequantize(quantized: ${b}, zero_point: ${y}, scale: ${y}) -> ${b} {\n ${1===u?`var dequantized = ${b}(${Array.from({length:8},((e,t)=>`(quantized[${t}] - zero_point) * scale`)).join(", ")});\n return dequantized;`:`var zero_points: ${b} = ${b}(${Array(8).fill("zero_point").join(",")});\n return (quantized - zero_points) * scale;`}\n }`,$=`\n fn ortUnpack8x4snorm(value: u32) -> ${b} {\n var quantized: ${b};\n var offset: u32 = 0;\n let count: u32 = 4;\n for (var i: u32 = 0; i < 8u; i++) {\n var result = ${y}(extractBits(value, offset, count));\n ${(()=>{switch(u){case 1:return"quantized[i] = result;";case 2:return"quantized[i / 2][i % 2] = result;";case 4:return"quantized[i / 4][i % 4] = result;";default:throw new Error(`${u}-component is not supported.`)}})()}\n offset += count;\n }\n return quantized;\n }`,x=g?`\n zero_point_offset += 4;\n if (zero_point_offset == 32) {\n zero_point_offset = 0;\n zero_point_index++;\n zero_point_word = ${g.getByOffset("zero_point_index")};\n }`:"";return`\n ${v};\n ${$};\n ${n.registerUniforms([{name:"output_size",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"accuracy_level",type:"u32"},{name:"bits",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...m,_)}\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var output_values: array<${_.type.value}, ${o}>;\n var output_indices = ${_.offsetToIndices("global_idx")};\n var n = ${_.indicesGet("output_indices",r-1)};\n var m = ${_.indicesGet("output_indices",r-2)};\n var a_indices: ${i.type.indices} = output_indices;\n // Two zero points are packed into one byte because uniforms.bits <= 4.\n // zero_point_offset is either 0 or 4. It is bit offset within one byte.\n // TODO support zero_point_offset for bits > 4\n ${g?`\n var zero_point_index: u32 = n * ${l} * ((${w} + 1) / 2) / 4;\n var zero_point_word: u32 = ${g.getByOffset("zero_point_index")};\n var zero_point_offset: u32 = 0;`:""}\n var scale_index = n * ${w*l};\n var b_indices: ${c.type.indices};\n for (var c: u32 = 0; c < ${l}; c++) {\n ${c.indicesSet("b_indices","0",`n * ${l} + c`)};\n var block_offset: u32 = 0;\n for (var block: u32 = 0; block < ${w}; block++) {\n // The scale and zero points are computed per block.\n let scale = ${p.getByOffset("scale_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${y}(${g?"extractBits(zero_point_word, zero_point_offset, 4)":8});\n ${c.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block_offset;\n for (var word: u32 = 0; word < ${s}; word += ${d}) {\n ${c.indicesSet("b_indices","2","word")};\n let b_data = ${c.getByIndices("b_indices")};\n for (var i: u32 = 0; i < ${d}; i++) {\n let b_value = ${1===d?"b_data":"b_data[word + i]"};\n let b_quantized_values: ${b} = ortUnpack8x4snorm(b_value);\n let b_dequantized_values = dequantize(b_quantized_values, zero_point, scale);\n // Number of B elements per 32-bit word is 32/bits = 32/4 = 8\n var offset: u32 = word_offset;\n for (var j: u32 = 0; j < 8/${u}; j++) {\n ${i.indicesSet("a_indices",r-1,`offset/${u}`)};\n for (var k: u32 = 0; k < ${o}u; k++) {\n ${i.indicesSet("a_indices",r-2,`m * ${o} + k`)};\n let a_data = ${i.getByIndices("a_indices")};\n output_values[k]${l>1?"[c]":""} += ${1===u?"a_data * b_dequantized_values[j]":"dot(a_data, b_dequantized_values[j])"};\n }\n offset += ${u};\n }\n word_offset += 8;\n }\n }\n scale_index++;\n ${x}\n block_offset += uniforms.block_size;\n }\n // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte.\n ${g?`if (zero_point_offset % 8 > 0) {\n ${x}\n }`:""}\n }\n for (var k: u32 = 0u; k < ${o}u; k++) {\n ${_.indicesSet("output_indices",r-2,""+(o+" * m + k"))};\n ${_.setByIndices("output_indices","output_values[k]")}\n }\n }`}}},Gi=(e,t)=>{Wi(e.inputs,t),e.compute(Vi(e.inputs,t))},ji=e=>ht(e)})),Sl=L((()=>{Do(),jo(),Go(),Wo(),Qo(),qo(),Ho(),qi=(e,t)=>{let n=e[0],r=e[1],a=e[2],i=e[3],s=e[4],o=e[5],l=e[6],u=e[7];if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let d,c=n.dims[0],p=n.dims[1],h=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],f=p,m=0,g=0,_=Math.floor(h/t.numHeads);if(l&&u){if(4!==l.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(4!==u.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');m=l.dims[2],g=l.dims[2]}else if(l||u)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');if(r){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===r.dims.length){if(r.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');d=2,f=r.dims[1]}else if(5===r.dims.length){if(r.dims[2]!==t.numHeads||2!==r.dims[3]||r.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');d=5,f=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=0,f=r.dims[2]}}else{if(3!==n.dims.length&&5!==n.dims.length)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(5===n.dims.length&&(n.dims[2]!==t.numHeads||3!==n.dims[3]))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');d=3}if(i){if(1!==i.dims.length)throw new Error('Input "bias" is expected to have 1 dimension');if(a&&5===n.dims.length&&2===n.dims[3])throw new Error("bias is not allowed for packed kv.")}let w=0;if(s){w=8;let e=s.dims;throw 1===e.length?e[0]===c?w=1:e[0]===3*c+2&&(w=3):2===e.length&&e[0]===c&&e[1]===f&&(w=5),8===w?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let y=!1,b=h;if(a){if(3!==a.dims.length&&4!==a.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===a.dims.length){if(f!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');b=a.dims[2]}else{if(f!==a.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');b=a.dims[1]*a.dims[3],y=!0}}let v=m+f;if(s)throw new Error("Key padding mask is not supported");if(o)throw new Error("extraAddQk is not supported");if(l)throw new Error("pastKey is not supported");if(u)throw new Error("pastValue is not supported");return{batchSize:c,sequenceLength:p,pastSequenceLength:m,kvSequenceLength:f,totalSequenceLength:v,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:b,headSize:_,vHeadSize:Math.floor(b/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:w,scale:t.scale,broadcastResPosBias:!1,passPastInKv:y,qkvFormat:d}},Hi=e=>ht({...e}),Ki=ht({perm:[0,2,1,3]}),Yi=(e,t,n,r,a,i,s)=>{let o=[r,a,i],l=gt.size(o),u=[{type:12,data:l},{type:12,data:s},{type:12,data:i}];return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:e=>{let r=Ot("qkv_with_bias",t.dataType,o),a=Pt("qkv",t.dataType,o),i=Pt("bias",n.dataType,o);return`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}]).declareVariables(a,i,r)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`}},{inputs:[t,n],outputs:[-1]})[0]},Xi=(e,t,n,r,a,i,s,o)=>{let l=i;if(s){if(1===r)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Yi(e,i,s,t,r,n*a,o),l=l.reshape([t,r,n,a]),e.compute(Wt(l,Ki.perm),{inputs:[l],outputs:[-1]})[0]}return 3===i.dims.length&&(l=i.reshape([t,r,n,a])),e.compute(Wt(l,Ki.perm),{inputs:[l],outputs:[-1]})[0]},Qi=(e,t)=>{let n=qi(e.inputs,t);if(5===e.inputs[0].dims.length)throw new Error("Packed QKV is not implemented");if(5===e.inputs[1]?.dims.length)throw new Error("Packed KV is not implemented");let r=e.inputs[1]&&e.inputs[2]&&4===e.inputs[1].dims.length&&4===e.inputs[2].dims.length,a=Xi(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,e.inputs[0],e.inputs[3],0);if(r)return Hn(e,a,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],n,t);let i=Xi(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,e.inputs[1],e.inputs[3],n.hiddenSize),s=Xi(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,e.inputs[2],e.inputs[3],2*n.hiddenSize);Hn(e,a,i,s,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],n,t)}})),Ml=L((()=>{Do(),jo(),qo(),Zi=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(1!==e[0].dataType&&10!==e[0].dataType)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=2*e[0].dims.length===e[1].dims[0];if(4===e.length&&(t=2*e[3].dims[0]===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Ji=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n k = i32(${e.indicesGet("indices",a)}) - ${At("uniforms.pads",a,n)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${At("uniforms.x_shape",a,t)})) {\n break;\n }\n offset += k * i32(${At("uniforms.x_strides",a,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n }\n `},es=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n k = i32(${e.indicesGet("indices",a)}) - ${At("uniforms.pads",a,n)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${At("uniforms.x_shape",a,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${At("uniforms.x_shape",a,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${At("uniforms.x_strides",a,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},ts=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n k = i32(${e.indicesGet("indices",a)}) - ${At("uniforms.pads",a,n)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${At("uniforms.x_shape",a,t)})) {\n k = i32(${At("uniforms.x_shape",a,t)}) - 1;\n }\n offset += k * i32(${At("uniforms.x_strides",a,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},ns=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n k = i32(${e.indicesGet("indices",a)}) - ${At("uniforms.pads",a,n)};\n if (k < 0) {\n k += i32(${At("uniforms.x_shape",a,t)}]);\n }\n if (k >= i32(${At("uniforms.x_shape",a,t)})) {\n k -= i32(${At("uniforms.x_shape",a,t)});\n }\n offset += k * i32(${At("uniforms.x_strides",a,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},rs=(e,t,n)=>{switch(n.mode){case 0:return Ji(e,t,n.pads.length);case 1:return es(e,t,n.pads.length);case 2:return ts(e,t,n.pads.length);case 3:return ns(e,t,n.pads.length);default:throw new Error("Invalid mode")}},as=(e,t)=>{let n=gt.padShape(e[0].dims.slice(),t.pads),r=e[0].dims,a=[{type:12,data:gt.size(n)},{type:12,data:t.pads}];0===t.mode&&a.push({type:e[0].dataType,data:t.value}),a.push(...St(e[0].dims,n));return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(gt.size(n)/64)},programUniforms:a}),getShaderSource:a=>{let i=Ot("output",e[0].dataType,n.length),s=Pt("x",e[0].dataType,r.length),o=s.type.value,l=rs(i,r.length,t),u=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return 0===t.mode&&u.push({name:"constant_value",type:o}),`\n ${a.registerUniforms(u).declareVariables(s,i)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${i.offsetToIndices("global_idx")};\n\n var value = ${o}(0);\n ${l}\n output[global_idx] = value;\n }`}}},is=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,a=e[0].dims.length,i=new Int32Array(2*a).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;ei[Number(t)]=Number(e)));let s=[];return i.forEach((e=>s.push(e))),{mode:t.mode,value:r,pads:s}}return t},ss=(e,t)=>{Zi(e.inputs);let n=is(e.inputs,t);e.compute(as(e.inputs,n),{inputs:[0]})}})),kl=L((()=>{de(),Do(),jo(),qo(),os=e=>{if(c.webgpu.validateInputContent&&(!e||1!==e.length))throw new Error("Pool ops requires 1 input.")},ls=(e,t,n)=>{let r="NHWC"===t.format,a=e.dims.slice();r&&a.splice(1,0,a.pop());let i=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),o=t.strides.slice(),l=i?t.dilations.slice():[],u=t.pads.slice();_t.adjustPoolAttributes(n,a,s,o,l,u);let d=_t.computePoolOutputShape(n,a,o,l,s,u,t.autoPad),c=Object.assign({},t);i?Object.assign(c,{kernelShape:s,strides:o,pads:u,dilations:l,cacheKey:t.cacheKey}):Object.assign(c,{kernelShape:s,strides:o,pads:u,cacheKey:t.cacheKey});let p=d.slice();return p.push(p.splice(1,1)[0]),[c,r?p:d]},us=(e,t)=>{let n="NHWC"===t.format,r=[{type:12,data:gt.size(e)},{type:12,data:gt.size(t.kernelShape)}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],i=t.pads[t.pads.length/2-1],s=t.pads[t.pads.length-1],o=!!(i+s);r.push({type:12,data:e},{type:12,data:n},{type:12,data:i},{type:12,data:s}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(2===t.kernelShape.length){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],i=t.pads[t.pads.length/2-2],s=t.pads[t.pads.length-2];l=!!(i+s),r.push({type:12,data:e},{type:12,data:n},{type:12,data:i},{type:12,data:s}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[r,a,!0,o,l]}{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let e=gt.computeStrides(t.kernelShape);return r.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:e.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length}),[r,a,!!t.pads.reduce(((e,t)=>e+t)),!1,!1]}},ds=(e,t,n,r,a,i,s,o,l,u,d,c)=>{let p="NHWC"===a.format,h=t.type.value,f=Ot("output",t.type.tensor,r);if(a.kernelShape.length<=2){let r="",u="",m="",g=n-(p?2:1);if(r=d?`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${g}] < 0 || xIndices[${g}]\n >= uniforms.x_shape[${g}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${i}\n }`:`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${i}\n }`,2===a.kernelShape.length){let e=n-(p?3:2);u=c?`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${e}] < 0 || xIndices[${e}] >= uniforms.x_shape[${e}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n `,m="\n }\n "}return`\n ${e.registerUniforms(l).declareVariables(t,f)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${f.offsetToIndices("global_idx")};\n var xIndices = ${f.offsetToIndices("global_idx")};\n\n var value = ${h}(${o});\n var pad = 0;\n ${u}\n ${r}\n ${m}\n ${s}\n\n output[global_idx] = value;\n }`}{if(p)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let r=a.kernelShape.length,d=a.pads.length,c="";return c=u?`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${i}\n }`:`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${i}\n `,`\n ${e.registerUniforms(l).declareVariables(t,f)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${f.offsetToIndices("global_idx")};\n var xIndices = ${f.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${h}(${o});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${r-1}u; j++) {\n offsets[j] = offset / ${At("uniforms.kernelStrides","j",r)};\n offset -= offsets[j] * ${At("uniforms.kernelStrides","j",r)};\n }\n offsets[${r-1}] = offset;\n\n isPad = false;\n for (var j = ${n-r}u; j < ${n}u; j++) {\n xIndices[j] = indices[j] * ${At("uniforms.strides",`j - ${n-r}u`,r)}\n + offsets[j - ${n-r}u] - ${At("uniforms.pads","j - 2u",d)};\n ${c}\n }\n ${s}\n\n output[global_idx] = value;\n }`}},cs=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,ps=e=>`${cs(e)};${e.countIncludePad}`,hs=e=>`${cs(e)};${e.storageOrder};${e.dilations}`,fs=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}),ms=(e,t,n,r)=>{let[a,i]=ls(t,r,n),s=Pt("x",t.dataType,t.dims.length),o=s.type.value,l="";a.countIncludePad?l+=`value /= ${o}(uniforms.kernelSize);`:l+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[u,d,c,p,h]=us(i,a);u.push(...St(t.dims,i));return{name:e,shaderCache:{hint:`${r.cacheKey};${c};${p};${h}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(gt.size(i)/64)},programUniforms:u}),getShaderSource:e=>ds(e,s,t.dims.length,i.length,a,"value += x_val;",l,0,d,c,p,h)}},gs=e=>{let t=0!==e.count_include_pad,n=fs(e);if(0!==n.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let r={countIncludePad:t,...n,cacheKey:""};return{...r,cacheKey:ps(r)}},_s=(e,t)=>{os(e.inputs),e.compute(ms("AveragePool",e.inputs[0],!1,t))},ws={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ys=e=>{let t=e.format;return{format:t,...ws,cacheKey:t}},bs=(e,t)=>{os(e.inputs),e.compute(ms("GlobalAveragePool",e.inputs[0],!0,t))},vs=(e,t,n,r)=>{let[a,i]=ls(t,r,n),s=Pt("x",t.dataType,t.dims.length),[o,l,u,d,c]=us(i,a);return o.push(...St(t.dims,i)),{name:e,shaderCache:{hint:`${r.cacheKey};${u};${d};${c}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(gt.size(i)/64)},programUniforms:o}),getShaderSource:e=>ds(e,s,t.dims.length,i.length,a,"\n value = max(x_val, value);\n ","",10===t.dataType?-65504:-1e5,l,u,d,c)}},$s=(e,t)=>{os(e.inputs),e.compute(vs("MaxPool",e.inputs[0],!1,t))},xs=e=>{let t=e.storage_order,n=e.dilations,r=fs(e);if(0!==t)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==r.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let a={storageOrder:t,dilations:n,...r,cacheKey:""};return{...a,cacheKey:hs(a)}},Ts=e=>{let t=e.format;return{format:t,...ws,cacheKey:t}},Ss=(e,t)=>{os(e.inputs),e.compute(vs("GlobalMaxPool",e.inputs[0],!0,t))}})),Cl=L((()=>{de(),Do(),qo(),Ms=(e,t,n)=>{if(e===t||et&&n>0)throw new Error("Range these inputs' contents are invalid.")},ks=(e,t,n,r)=>{let a=Math.abs(Math.ceil((t-e)/n)),i=[a],s=a,o=[{type:12,data:s},{type:r,data:e},{type:r,data:n},...St(i)];return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:e=>{let t=Ot("output",r,i.length),n=t.type.value,a=[{name:"outputSize",type:"u32"},{name:"start",type:n},{name:"delta",type:n}];return`\n ${e.registerUniforms(a).declareVariables(t)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${n}(global_idx) * uniforms.delta;\n }`},getRunData:()=>({outputs:[{dims:i,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},Cs=e=>{let t=0,n=0,r=0;6===e.inputs[0].dataType?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],r=e.inputs[2].getInt32Array()[0]):1===e.inputs[0].dataType&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],r=e.inputs[2].getFloat32Array()[0]),c.webgpu.validateInputContent&&Ms(t,n,r),e.compute(ks(t,n,r,e.inputs[0].dataType),{inputs:[]})}})),El=L((()=>{Do(),jo(),Go(),qo(),Es=(e,t)=>{if(e.every((e=>e>0||(()=>{throw new Error("Resize requires scales input values to be positive")}))),e.length>0)if("linear"===t.mode){if(!(2===e.length||3===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]||5===e.length&&1===e[0]&&1===e[1]))throw new Error("For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1")}else if("cubic"===t.mode&&!(2===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")},As=(e,t,n)=>{t.every((e=>e>=0&&e{throw new Error("Resize requires axes input values to be positive and less than rank")})));let r=new Array(n).fill(1);return t.forEach(((t,n)=>r[t]=e[n])),r},Is=(e,t,n,r,a,i)=>{let[s,o,l]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(s>0&&e.length>s&&e[s].dims.length>0)e[s].getFloat32Array().forEach((e=>i.push(e)));else if("tf_crop_and_resize"===t.coordinateTransformMode)throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&e.length>o&&e[o].dims.length>0){if(e[o].getFloat32Array().forEach((e=>r.push(e))),0!==r.length&&r.length!==u&&n>=18&&r.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");Es(r,t),t.axes.length>0&&As(r,t.axes,u).forEach(((e,t)=>r[t]=e))}if(l>0&&e.length>l&&(e[l].getBigInt64Array().forEach((e=>a.push(Number(e)))),a.length!==u||n>=18&&a.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(r.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(a.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 r<"u"&&typeof a<"u"&&r.length>0&&a.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},Ps=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n 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) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n 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`)}})()+"}",Os=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{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); }";default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",zs=(e,t,n)=>{let r=new Array(n).fill(0).concat(new Array(n).fill(1)),a=0===e.length?r:e.slice();return t.length>0?(t.forEach(((e,i)=>{r[e]=a[i],r[i+n]=a[t.length+i]})),r):a},Bs=(e,t,n,r)=>{let a=[];if(n.length>0)if(r.length>0){if(e.forEach((e=>a.push(e))),Math.max(...r)>e.length)throw new Error("axes is out of bound");r.forEach(((e,t)=>a[e]=n[t]))}else n.forEach((e=>a.push(e)));else{if(0===t.length)throw new Error("Resize requires either scales or sizes.");a=e.map(((e,n)=>Math.round(e*t[n])))}return a},Fs=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map((e=>t[e])),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map((e=>t[e])),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let a=e.slice();return n.axes.length>0?(n.axes.forEach((e=>t[e]=r)),n.axes.forEach((n=>a[n]=Math.round(e[n]*t[n])))):(t.fill(r,0,t.length),a.forEach(((e,n)=>a[n]=Math.round(e*t[n])))),a},Rs=(e,t,n,r,a)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {\n var original_indices: array<${e.type.value}, ${n.length}>;\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${At("uniforms.scales","i",r)};\n var roi_low = ${At("uniforms.roi","i",a)};\n var roi_hi = ${At("uniforms.roi",`i + ${t.length}`,a)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${At("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${At("uniforms.output_shape","i",n.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Ds=(e,t,n,r,a,i,s)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${At("uniforms.scales","i",a)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${At("uniforms.roi","i",i)};\n var roi_hi = ${At("uniforms.roi",`i + ${n.length}`,i)};\n var input_shape_i = ${At("uniforms.input_shape","i",n.length)};\n var output_shape_i = ${At("uniforms.output_shape","i",r.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${s} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,Ls=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${At("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Ns=(e,t,n,r)=>e.rank>r?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",n,"batch")};\n`:"",Us=(e,t,n,r,a)=>{let[i,s,o,l]=2===n.length?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",s,`max(0, min(row, ${n[s]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)};\n ${Ns(e,l,i,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${u} = originalIndices[${s}];\n var col:${u} = originalIndices[${o}];\n ${r?`if (row < 0 || row > (${n[s]} - 1) || col < 0 || col > (${n[o]} - 1)) {\n return ${a};\n }`:""};\n row = max(0, min(row, ${n[s]} - 1));\n col = max(0, min(col, ${n[o]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${n.length>2?`u32(originalIndices[${l}])`:"0"};\n var batch: u32 = ${n.length>2?`u32(originalIndices[${i}])`:"0"};\n var x11: ${u} = getInputValue(batch, channel, row1, col1);\n var x12: ${u} = getInputValue(batch, channel, row1, col2);\n var x21: ${u} = getInputValue(batch, channel, row2, col1);\n var x22: ${u} = getInputValue(batch, channel, row2, col2);\n var dx1: ${u} = abs(row - ${u}(row1));\n var dx2: ${u} = abs(${u}(row2) - row);\n var dy1: ${u} = abs(col - ${u}(col1));\n var dy2: ${u} = abs(${u}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Ws=(e,t,n,r,a,i,s,o,l,u)=>{let d=2===n.length,[c,p]=d?[0,1]:[2,3],h=e.type.value,f=s=>{let d=s===c?"row":"col";return`\n fn ${d}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${h} {\n var output_index = ${t.indicesGet("output_indices",s)};\n var originalIdx: ${h} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[s]},\n ${r[s]}, ${n[s]}, ${i[s]}, ${i[s]} + ${n.length});\n var fractOriginalIdx: ${h} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${o} && (originalIdx < 0 || originalIdx > (${n[s]} - 1))) {\n return ${l};\n }\n var data: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${d}: ${h} = originalIdx + ${h}(i);\n if (${d} < 0 || ${d} >= ${n[s]}) {\n ${u?"coefs[i + 1] = 0.0;\n continue;":o?`return ${l};`:`${d} = max(0, min(${d}, ${n[s]} - 1));`};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",s,`u32(${d})`)};\n data[i + 1] = ${s===c?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${f(c)};\n ${f(p)};\n fn getCubicInterpolationCoefs(s: ${h}) -> array<${h}, 4> {\n var absS = abs(s);\n var coeffs: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${h} = 1.0 - absS;\n var twoMinusAbsS: ${h} = 2.0 - absS;\n var onePlusAbsS: ${h} = 1.0 + absS;\n coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s};\n coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1;\n coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${h}, 4>, coefs: array<${h}, 4>) -> ${h} {\n var coefsSum: ${h} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${h} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Vs=(e,t,n,r,a)=>{let[i,s,o,l,u]=3===n.length?[-1,0,1,2,-1]:[0,2,3,4,1],d=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${d} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",s,`max(0, min(depth, ${n[s]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(height, ${n[o]} - 1))`)};\n ${e.indicesSet("input_indices",l,`max(0, min(width, ${n[l]} - 1))`)};\n ${Ns(e,u,i,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${d} = originalIndices[${s}];\n var height:${d} = originalIndices[${o}];\n var width:${d} = originalIndices[${l}];\n ${r?`if (depth < 0 || depth > (${n[s]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[l]} - 1)) {\n return ${a};\n }`:""};\n\n depth = max(0, min(depth, ${n[s]} - 1));\n height = max(0, min(height, ${n[o]} - 1));\n width = max(0, min(width, ${n[l]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${n.length>3?`u32(originalIndices[${u}])`:"0"};\n var batch: u32 = ${n.length>3?`u32(originalIndices[${i}])`:"0"};\n\n var x111: ${d} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${d} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${d} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${d} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${d} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${d} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${d} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${d} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${d} = abs(depth - ${d}(depth1));\n var dx2: ${d} = abs(${d}(depth2) - depth);\n var dy1: ${d} = abs(height - ${d}(height1));\n var dy2: ${d} = abs(${d}(height2) - height);\n var dz1: ${d} = abs(width - ${d}(width1));\n var dz2: ${d} = abs(${d}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Gs=(e,t,n,r,a,i)=>{let s=e.dims,o=zs(i,t.axes,s.length),l=Bs(s,r,a,t.axes),u=r.slice();0===r.length&&(u=s.map(((e,t)=>0===e?1:l[t]/e)),"stretch"!==t.keepAspectRatioPolicy&&(l=Fs(s,u,t)));let d=Ot("output",e.dataType,l.length),c=Pt("input",e.dataType,s.length),p=gt.size(l),h=s.length===l.length&&s.every(((e,t)=>e===l[t])),f="tf_crop_and_resize"===t.coordinateTransformMode,m=t.extrapolationValue,g=c.type.value;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${u.length>0?u:""}|${a.length>0?a:""}|${o.length>0?o:""}|${h}|${s}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${h?"":`\n ${Ps(t.coordinateTransformMode,g)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Ls(c,s)};\n ${Os(t.nearestMode,n,g)};\n ${Ds(c,d,s,l,u.length,o.length,f)};\n `;case"linear":return`\n ${Rs(d,s,l,u.length,o.length)};\n ${(()=>{if(2===s.length||4===s.length)return`${Us(c,d,s,f,m)}`;if(3===s.length||5===s.length)return`${Vs(c,d,s,f,m)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(2===s.length||4===s.length)return`${Ws(c,d,s,l,u,o,t.cubicCoeffA,f,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${e.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",o.length).declareVariables(c,d)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${h?"output[global_idx] = input[global_idx];":`\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${c.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${c.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${2===s.length||4===s.length?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:1,data:u},{type:1,data:o},...St(s,l)]})}},js=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},qs=(e,t)=>{let n=[],r=[],a=[],i=js(e);if(0!==t.antialias)throw Error("Only default value (0) for Antialias attribute is supported");Is(e.inputs,t,i,n,r,a),e.compute(Gs(e.inputs[0],t,i,n,r,a),{inputs:[0]})},Hs=e=>{let t=e.antialias,n=e.axes,r=e.coordinateTransformMode,a=e.cubicCoeffA,i=0!==e.excludeOutside,s=e.extrapolationValue,o=e.keepAspectRatioPolicy,l=e.mode,u=""===e.nearestMode?"simple":e.nearestMode;return ht({antialias:t,axes:n,coordinateTransformMode:r,cubicCoeffA:a,excludeOutside:i,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:u})}})),Al=L((()=>{Do(),jo(),qo(),Ks=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],r=e[2];if(t.dataType!==n.dataType||t.dataType!==r.dataType)throw new Error("All inputs must have the same data type");if(3!==t.dims.length&&2!==t.dims.length)throw new Error("Input must be 2D or 3D");if(3!==n.dims.length&&2!==n.dims.length)throw new Error("Skip must be 2D or 3D");let a=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==a)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(1!==r.dims.length)throw new Error("Gamma must be 1D");if(r.dims[r.dims.length-1]!==a)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let t=e[3];if(1!==t.dims.length)throw new Error("Beta must be 1D");if(t.dims[t.dims.length-1]!==a)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let t=e[4];if(1!==t.dims.length)throw new Error("Bias must be 1D");if(t.dims[t.dims.length-1]!==a)throw new Error("Bias must have the same hidden size as input")}},Ys=(e,t,n,r)=>{let a=e[0].dims,i=gt.size(a),s=a,o=i,l=a.slice(-1)[0],u=r?a.slice(0,-1).concat(1):[],d=e.length>3,c=e.length>4,p=r&&n>1,h=r&&n>2,f=n>3,m=Mt(l),g=[{type:12,data:o},{type:12,data:m},{type:12,data:l},{type:1,data:t.epsilon}],_=[{dims:s,dataType:e[0].dataType}];return n>1&&_.push({dims:u,dataType:1}),n>2&&_.push({dims:u,dataType:1}),n>3&&_.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${m};${p};${h};${f}`,inputDependencies:e.map(((e,t)=>"type"))},getShaderSource:t=>{let n=[Pt("x",e[0].dataType,e[0].dims,m),Pt("skip",e[1].dataType,e[1].dims,m),Pt("gamma",e[2].dataType,e[2].dims,m)];d&&n.push(Pt("beta",e[3].dataType,e[3].dims,m)),c&&n.push(Pt("bias",e[4].dataType,e[4].dims,m)),n.push(Ot("output",e[0].dataType,s,m)),p&&n.push(Ot("mean_output",1,u)),h&&n.push(Ot("inv_std_output",1,u)),f&&n.push(Ot("input_skip_bias_sum",e[0].dataType,s,m));let r=xt(e[0].dataType);return`\n\n ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...n)}\n\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")}\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n let offset = global_idx * hidden_size_vectorized;\n var sum = ${kt("f32",m)};\n var squareSum = ${kt("f32",m)};\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${c?"bias[i]":"0.0"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${f?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${Ct(r,m,"value")};\n sum += f32_value;\n squareSum += f32_value * f32_value;\n }\n let mean = ${Et("sum",m)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${Et("squareSum",m)} / f32(uniforms.hidden_size) - mean * mean + uniforms.epsilon);\n ${p?"mean_output[global_idx] = mean;":""}\n ${h?"inv_std_output[global_idx] = inv_std_dev;":""}\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n output[offset + i] = (output[offset + i] - ${r}(mean)) * ${r}(inv_std_dev) * gamma[i] + ${d?"beta[i]":"0.0"};\n }\n }`},getRunData:()=>({outputs:_,dispatchGroup:{x:Math.ceil(o/l/64)},programUniforms:g})}},Xs=(e,t)=>{Ks(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Ys(e.inputs,t,e.outputCount,!1),{outputs:n})}})),Il=L((()=>{Do(),jo(),Go(),qo(),Qs=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(0!==t.axes.length){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(((t,n)=>{if(6!==e[n+1].dataType&&7!==e[n+1].dataType)throw new Error(`Input ${n} must be an array of int32 or int64`)}))},Zs=(e,t)=>{let n=[];if(e.length>t)if(7===e[t].dataType)e[t].getBigInt64Array().forEach((e=>n.push(Number(e))));else{if(6!==e[t].dataType)throw new Error(`Input ${t} must be an array of int32 or int64`);e[t].getInt32Array().forEach((e=>n.push(Number(e))))}return n},Js=(e,t)=>{if(e.length>1){let t=Zs(e,1),n=Zs(e,2),r=Zs(e,3);return 0===r.length&&(r=[...Array(e[0].dims.length).keys()]),ht({starts:t,ends:n,axes:r})}return t},eo=(e,t,n,r,a)=>{let i=e;return e<0&&(i+=n[r[t]]),a[t]<0?Math.max(0,Math.min(i,n[r[t]]-1)):Math.max(0,Math.min(i,n[r[t]]))},to=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${n.length}; i >= 0; i--) {\n let input_shape_i = ${At("uniforms.input_shape","i",n.length)};\n let steps_i = ${At("uniforms.steps","i",n.length)};\n let signs_i = ${At("uniforms.signs","i",n.length)};\n let starts_i = ${At("uniforms.starts","i",n.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,no=(e,t)=>{let n=e[0].dims,r=gt.size(n),a=t.axes.length>0?gt.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],i=Zs(e,4);i.forEach((e=>0!==e||(()=>{throw new Error("step cannot be 0")}))),0===i.length&&(i=Array(a.length).fill(1));let s=t.starts.map(((e,t)=>eo(e,t,n,a,i))),o=t.ends.map(((e,t)=>eo(e,t,n,a,i)));if(a.length!==s.length||a.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(a.length!==n.length)for(let e=0;eMath.sign(e)));i.forEach(((e,t,n)=>{if(e<0){let r=(o[t]-s[t])/e,a=s[t],l=a+r*i[t];s[t]=l,o[t]=a,n[t]=-e}}));let u=n.slice(0);a.forEach(((e,t)=>{u[e]=Math.ceil((o[e]-s[e])/i[e])}));let d={dims:u,dataType:e[0].dataType},c=Ot("output",e[0].dataType,u.length),p=Pt("input",e[0].dataType,e[0].dims.length),h=gt.size(u),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:i.length}],m=[{type:12,data:h},{type:12,data:s},{type:6,data:l},{type:12,data:i},...St(e[0].dims,u)];return{name:"Slice",shaderCache:{hint:`${l.length}_${s.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${e.registerUniforms(f).declareVariables(p,c)}\n ${to(p,c,n)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${c.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${c.setByOffset("global_idx",p.getByIndices("input_indices"))}\n }`,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:m})}},ro=(e,t)=>{Qs(e.inputs,t);let n=Js(e.inputs,t);e.compute(no(e.inputs,n),{inputs:[0]})},ao=e=>{let t=e.starts,n=e.ends,r=e.axes;return ht({starts:t,ends:n,axes:r})}})),Pl=L((()=>{Do(),jo(),Go(),qo(),io=e=>{if(!e||1!==e.length)throw new Error("Softmax op requires 1 input.")},so=(e,t)=>{let n=e.dims,r=gt.size(n),a=t.axis;if(a<0&&(a=n.length+a),a({outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:s},programUniforms:[{type:12,data:l}]}),getShaderSource:e=>`\n var rowMaxShared : ${c};\n var rowSumShared : ${c};\n var threadShared : array<${c}, 64>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${c} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${c}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${e.registerUniform("packedCols","i32").declareVariables(u,d)}\n ${e.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = 64;\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${p}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${c}(${((e,t)=>4===t?`max(max(${e}.x, ${e}.y), max(${e}.z, ${e}.w))`:2===t?`max(${e}.x, ${e}.y)`:3===t?`max(max(${e}.x, ${e}.y), ${e}.z)`:e)("threadShared[0]",o)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${c}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${c}(${Et("threadShared[0]",o)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`}},oo=(e,t)=>{io(e.inputs),e.compute(so(e.inputs[0],t))},lo=e=>ht({axis:e.axis})})),Ol=L((()=>{Do(),jo(),Go(),qo(),uo=e=>{if(!e||e.length<1)throw new Error("too few inputs")},co=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),r=n.length),ht({numOutputs:r,axis:t.axis,splitSizes:n})},po=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${At("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,ho=e=>{let t=e.length,n=[];for(let r=0;r{let n=e[0].dims,r=gt.size(n),a=e[0].dataType,i=gt.normalizeAxis(t.axis,n.length),s=new Array(t.numOutputs),o=Pt("input",a,n.length),l=new Array(t.numOutputs),u=[],d=[],c=0,p=[{type:12,data:r}];for(let r=0;r`\n ${e.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)}\n ${po(l.length)}\n ${ho(s)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${o.offsetToIndices("global_idx")};\n var index = ${o.indicesGet("indices",i)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${At("uniforms.size_in_split_axis","output_number - 1u",l.length)};\n ${o.indicesSet("indices",i,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:p})}},mo=(e,t)=>{uo(e.inputs);let n=1===e.inputs.length?t:co(e.inputs,t);e.compute(fo(e.inputs,n),{inputs:[0]})},go=e=>{let t=e.axis,n=e.splitSizes,r=e.numOutputs<0?n.length:e.numOutputs;if(r!==n.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ht({axis:t,numOutputs:r,splitSizes:n})}})),zl=L((()=>{Do(),jo(),qo(),_o=e=>Array.from(e.getBigInt64Array(),Number),wo=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 inputs.");if(1!==e[0].dataType&&6!==e[0].dataType&&12!==e[0].dataType)throw new Error("Tile only support float, int32, and uint32 data types");if(7!==e[1].dataType)throw new Error("Tile `repeats` input should be of int64 data type");if(1!==e[1].dims.length)throw new Error("Tile `repeats` input should be 1-D");if(_o(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")},yo=(e,t)=>{let n=[];for(let r=0;r{let t=e[0].dims,n=_o(e[1]),r=yo(t,n),a=gt.size(r),i=e[0].dataType,s=Pt("input",i,t.length),o=Ot("output",i,r.length);return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...St(e[0].dims,r)]}),getShaderSource:e=>`\n const inputShape = ${s.indices(...t)};\n ${e.registerUniform("output_size","u32").declareVariables(s,o)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${o.offsetToIndices("global_idx")};\n var input_indices: ${s.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${s.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${o.indicesGet("output_indices","i")} % input_dim_i;\n\n ${s.indicesSet("input_indices","i","input_dim_value")}\n }\n ${o.setByOffset("global_idx",s.getByIndices("input_indices"))}\n }`}},vo=e=>{wo(e.inputs),e.compute(bo(e.inputs),{inputs:[0]})}})),Bl=L((()=>{Do(),jo(),qo(),$o=(e,t,n,r,a)=>{let i,s=Ot("output_data",a,n.length,4),o=Pt("a_data",t[1].dataType,t[1].dims.length,4),l=Pt("b_data",t[2].dataType,t[2].dims.length,4),u=Pt("c_data",t[0].dataType,t[0].dims.length,4),d=(e,t,n)=>`select(${t}, ${e}, ${n})`;if(r){let e=(e,t,n="")=>{let r=`a_data[index_a${t}][component_a${t}]`,a=`b_data[index_b${t}][component_b${t}]`,i=`bool(c_data[index_c${t}] & (0xffu << (component_c${t} * 8)))`;return`\n let output_indices${t} = ${s.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offset_a${t} = ${o.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let offset_b${t} = ${l.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let offset_c${t} = ${u.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let index_a${t} = offset_a${t} / 4u;\n let index_b${t} = offset_b${t} / 4u;\n let index_c${t} = offset_c${t} / 4u;\n let component_a${t} = offset_a${t} % 4u;\n let component_b${t} = offset_b${t} % 4u;\n let component_c${t} = offset_c${t} % 4u;\n ${e}[${t}] = ${n}(${d(r,a,i)});\n `};i=9===a?`\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:`\n ${e("output_data[global_idx]",0)}\n ${e("output_data[global_idx]",1)}\n ${e("output_data[global_idx]",2)}\n ${e("output_data[global_idx]",3)}\n `}else i=s.setByOffset("global_idx",d(o.getByOffset("global_idx"),l.getByOffset("global_idx"),u.getByOffset("global_idx")));return`\n ${e.registerUniform("vec_size","u32").declareVariables(u,o,l,s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${i}\n }`},xo=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,a=e[1].dataType,i=!(gt.areEqual(t,n)&>.areEqual(n,r)),s=t,o=gt.size(t);if(i){let e=mt.calcShape(mt.calcShape(t,n,!1),r,!1);if(!e)throw new Error("Can't perform where op on the given tensors");s=e,o=gt.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:t=>$o(t,e,s,i,a),getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...St(r,t,n,s)]})}},To=e=>{e.compute(xo(e.inputs))}})),Fl=L((()=>{Xo(),Qo(),Zo(),Jo(),tl(),nl(),rl(),cl(),fl(),ml(),gl(),_l(),wl(),yl(),bl(),vl(),$l(),xl(),dl(),Tl(),Sl(),Ml(),kl(),Cl(),Yo(),El(),Al(),Il(),Pl(),Ol(),zl(),Ho(),el(),Bl(),So=new Map([["Abs",[ir]],["Acos",[sr]],["Acosh",[or]],["Add",[Qr]],["ArgMax",[Un,Wn]],["ArgMin",[Nn,Wn]],["Asin",[lr]],["Asinh",[ur]],["Atan",[dr]],["Atanh",[cr]],["Attention",[Yn]],["AveragePool",[_s,gs]],["BatchNormalization",[Jn]],["BiasAdd",[nr]],["BiasSplitGelu",[Hr]],["Cast",[hr,pr]],["Ceil",[gr]],["Clip",[mr]],["Concat",[ca,pa]],["Conv",[Wa,La]],["ConvTranspose",[ni,Qa]],["Cos",[_r]],["Cosh",[wr]],["CumSum",[ai,ii]],["Div",[Zr]],["Einsum",[fi,mi]],["Elu",[br,yr]],["Equal",[Jr]],["Erf",[$r]],["Exp",[xr]],["Expand",[bi]],["FastGelu",[$i]],["Floor",[Tr]],["FusedConv",[Wa,La]],["Gather",[Mi,Si]],["GatherElements",[Ai,Ei]],["Gelu",[Sr]],["Gemm",[zi,Oi]],["GlobalAveragePool",[bs,ys]],["GlobalMaxPool",[Ss,Ts]],["Greater",[ra]],["GreaterOrEqual",[ia]],["HardSigmoid",[Or,Pr]],["InstanceNormalization",[Di]],["LayerNormalization",[Ui]],["LeakyRelu",[Mr,yr]],["Less",[aa]],["LessOrEqual",[sa]],["Log",[Gr]],["MatMul",[za]],["MatMulNBits",[Gi,ji]],["MaxPool",[$s,xs]],["Mul",[ea]],["MultiHeadAttention",[Qi,Hi]],["Neg",[Cr]],["Not",[kr]],["Pad",[ss]],["Pow",[ta]],["Range",[Cs]],["Reciprocal",[Er]],["ReduceMin",[zn]],["ReduceMean",[En]],["ReduceMax",[On]],["ReduceSum",[Fn]],["ReduceProd",[Bn]],["ReduceL1",[An]],["ReduceL2",[In]],["ReduceLogSum",[Dn]],["ReduceLogSumExp",[Pn]],["ReduceSumSquare",[Rn]],["Relu",[Ar]],["Resize",[qs,Hs]],["Sigmoid",[Ir]],["Sin",[zr]],["Sinh",[Br]],["Slice",[ro,ao]],["SkipLayerNormalization",[Xs]],["Split",[mo,go]],["Sqrt",[Fr]],["Softmax",[oo,lo]],["Sub",[na]],["Tan",[Rr]],["Tanh",[Lr]],["ThresholdedRelu",[Vr,yr]],["Tile",[vo]],["Transpose",[Vt,Gt]],["Where",[To]]])})),Rl=L((()=>{de(),No(),qo(),Mo=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,n,r,a){E(e.programInfo.name);let i=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber);let o=[];for(let e of t)o.push({binding:o.length,resource:{buffer:e.buffer}});for(let e of n)o.push({binding:o.length,resource:{buffer:e.buffer}});a&&o.push({binding:o.length,resource:a});let l=i.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:o,label:e.programInfo.name});if("capturing"===this.backend.sessionStatus){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}s.setPipeline(e.computePipeline),s.setBindGroup(0,l),s.dispatchWorkgroups(...r),this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||"at-passes"===this.backend.queryType)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),A(e.programInfo.name)}dispose(){}build(e,t){E(e.name);let n=this.backend.device,r=[];n.features.has("shader-f16")&&r.push("enable f16;");let a=Ft(t),i=e.getShaderSource(a),s=`${r.join("\n")}\n${a.additionalImplementations}\n${i}`,o=n.createShaderModule({code:s,label:e.name});at("verbose",(()=>`[WebGPU] ${e.name} shader code: ${s}`));let l=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:e.name});return A(e.name),{programInfo:e,computePipeline:l}}normalizeDispatchGroupSize(e){let t="number"==typeof e?e:e.x,n="number"==typeof e?1:e.y||1,r="number"==typeof e?1:e.z||1,a=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=a&&n<=a&&r<=a)return[t,n,r];let i=t*n*r,s=Math.ceil(Math.sqrt(i));if(s>a){if(s=Math.ceil(Math.cbrt(i)),s>a)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}return[s,s,1]}}})),Dl=L((()=>{de(),Do(),No(),Uo(),Vo(),Fl(),Rl(),ko=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r{let r=e.name;return e.shaderCache?.hint&&(r+="["+e.shaderCache.hint+"]"),r+=":"+n+`:${ko(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,r},Eo=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Ao=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(null===this.currentKernelId)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 n=[],r={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:n};t.features.has("chromium-experimental-timestamp-query-inside-passes")?n.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&n.push("timestamp-query"),t.features.has("shader-f16")&&n.push("shader-f16"),this.device=await t.requestDevice(r),this.adapterInfo=new Eo(await t.requestAdapterInfo()),this.gpuDataManager=ct(this),this.programManager=new Mo(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,nt(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.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={};"at-passes"===this.queryType&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:2*this.pendingDispatchNumber,endOfPassWriteIndex:2*this.pendingDispatchNumber+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;let e;E(),this.endComputePass(),"none"!==this.queryType&&(this.commandEncoder.resolveQuerySet(this.querySet,0,2*this.pendingDispatchNumber,this.queryResolveBuffer,0),e=this.device.createBuffer({size:2*this.pendingDispatchNumber*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,2*this.pendingDispatchNumber*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,"none"!==this.queryType&&e.mapAsync(GPUMapMode.READ).then((()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e"u"&&(this.queryTimeBase=c);let h=Number(c-this.queryTimeBase),f=Number(p-this.queryTimeBase);if(!Number.isSafeInteger(h)||!Number.isSafeInteger(f))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map((e=>({dims:e.dims,dataType:je(e.dataType)}))),outputsMetadata:d.map((e=>({dims:e.dims,dataType:je(e.dataType)}))),kernelId:a,kernelType:s,kernelName:o,programName:l,startTime:h,endTime:f});else{let e="";u.forEach(((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${je(t.dataType)}, `}));let t="";d.forEach(((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${je(e.dataType)}, `})),console.log(`[profiling] kernel "${a}|${s}|${o}|${l}" ${e}${t}execution time: ${f-h} ns`)}k("GPU",`${l}::${c}::${p}`)}e.unmap(),this.pendingQueries.delete(e)})),A()}run(e,t,n,r,a){E(e.name);let i=[];for(let e=0;et)):n;if(u.length!==s.length)throw new Error(`Output size ${u.length} must be equal to ${s.length}.`);let d,c=[],p=[];for(let e=0;e=s.length)throw new Error(`Invalid output index: ${u[e]}`);if(-3===u[e])continue;let t=-1===u[e],n=-2===u[e],i=t||n?a(s[e].dataType,s[e].dims):r(u[e],s[e].dataType,s[e].dims);if(c.push(i),0===i.data)continue;let o=this.gpuDataManager.get(i.data);if(!o)throw new Error(`no GPU data for output: ${i.data}`);if(t&&this.temporaryData.push(o),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(o)}p.push(o)}if(i.length!==t.length||p.length!==c.length){if(0===p.length)return A(e.name),c;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}if(l){let e=0,t=[];l.forEach((n=>{let r="number"==typeof n.data?[n.data]:n.data;if(0===r.length)return;let a,i,s=10===n.type?2:4;10===n.type?(i=r.length>4?16:r.length>2?8:r.length*s,a=r.length>4?16:s*r.length):(i=r.length<=2?r.length*s:16,a=16),e=Math.ceil(e/i)*i,t.push(e);let o=10===n.type?8:4;e+=r.length>4?Math.ceil(r.length/o)*a:r.length*s}));let n=16;e=Math.ceil(e/n)*n;let r=new ArrayBuffer(e);l.forEach(((e,n)=>{let a=t[n],i="number"==typeof e.data?[e.data]:e.data;if(6===e.type)new Int32Array(r,a,i.length).set(i);else if(12===e.type)new Uint32Array(r,a,i.length).set(i);else if(10===e.type)new Uint16Array(r,a,i.length).set(i);else{if(1!==e.type)throw new Error(`Unsupported uniform type: ${je(e.type)}`);new Float32Array(r,a,i.length).set(i)}}));let a=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(a.buffer,0,r,0,e),this.gpuDataManager.release(a.id),d={offset:0,size:e,buffer:a.buffer}}let h=this.programManager.normalizeDispatchGroupSize(o),f=1===h[1]&&1===h[2],m=Co(e,t,f),g=this.programManager.getArtifact(m);if(g||(g=this.programManager.build(e,h),this.programManager.setArtifact(m,g),at("info",(()=>`[artifact] key: ${m}, programName: ${e.name}`))),at("info",(()=>`[ProgramManager] run "${e.name}" (key=${m}) with ${h[0]}x${h[1]}x${h[2]}`)),"none"!==this.queryType||"capturing"===this.sessionStatus){let e={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:t,outputTensorViews:c};this.pendingKernels.push(e),"capturing"===this.sessionStatus&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(g,i,p,h,d),A(e.name),c}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,n,r){let a=So.get(e);if(!a)throw new Error(`kernel not implemented: ${e}`);let i={kernelType:e,kernelName:r,kernelEntry:a[0],attributes:[a[1],n]};this.kernels.set(t,i)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw new Error(`kernel not created: ${e}`);let a=r.kernelType,i=r.kernelName,s=r.kernelEntry,o=r.attributes;if(null!==this.currentKernelId)throw new Error(`kernel "[${a}] ${i}" is not allowed to be called recursively`);this.currentKernelId=e,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),at("info",(()=>`[WebGPU] Start to run kernel "[${a}] ${i}"...`));let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),s(t,o[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${a}] ${i}" failed. ${e}`)),1}finally{l&&n.push(this.device.popErrorScope().then((e=>e?`GPU validation error for kernel "[${a}] ${i}": ${e.message}`:null)));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let a=this.sessionExternalDataMapping.get(e);a||(a=new Map,this.sessionExternalDataMapping.set(e,a));let i=a.get(t),s=this.gpuDataManager.registerExternalBuffer(n,r,i?.[1]);return a.set(t,[s,n]),s}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach((e=>this.gpuDataManager.unregisterExternalBuffer(e[1]))),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await ut(this,e,t);return it(r.buffer,n)}}writeTimestamp(e){"inside-passes"===this.queryType&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",("default"===this.env.webgpu.profiling?.mode||(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"),"none"!==this.queryType&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2*this.maxDispatchNumber}),this.queryResolveBuffer=this.device.createBuffer({size:2*this.maxDispatchNumber*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){at("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(){at("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){at("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r=this.maxDispatchNumber||"at-passes"===this.queryType)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}})),Ll={};U(Ll,{init:()=>Wl});var Nl,Ul,Wl,Vl,Gl,jl,ql,Hl,Kl,Yl,Xl,Ql,Zl,Jl,eu,tu,nu,ru,au,iu,su,ou,lu,uu,du,cu,pu,hu,fu,mu,gu,_u,wu,yu,bu,vu,$u,xu,Tu=L((()=>{Do(),Dl(),No(),jo(),Nl=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(1!==this.dataType)throw new Error("Invalid data type");let e=gt.size(this.dims);return 0===e?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(7!==this.dataType)throw new Error("Invalid data type");let e=gt.size(this.dims);return 0===e?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(6!==this.dataType)throw new Error("Invalid data type");let e=gt.size(this.dims);return 0===e?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(gt.size(t)!==gt.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Ul=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let r=e.HEAPU32,a=n>>>2;this.opKernelContext=r[a++];let i=r[a++];this.outputCount=r[a++],this.customDataOffset=r[a++],this.customDataSize=r[a++];let s=[];for(let t=0;t"number"==typeof e?this.inputs[e]:e))??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,((e,t,n)=>new Nl(this.module,t,this.output(e,n),n)),((e,t)=>{let n=qe(e);if(!n)throw new Error(`Unsupported data type: ${e}`);let r=n*gt.size(t),a=r>0?this.backend.gpuDataManager.create(r).id:0;return new Nl(this.module,e,a,t)}))}output(e,t){let n=this.module.stackSave();try{let n=this.module.stackAlloc(4*(1+t.length)),r=n>>2;this.module.HEAPU32[r++]=t.length;for(let e=0;e{let a=t.jsepInit;if(!a)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if("webgpu"===e){let e=new Ao;await e.initialize(n,r),a("webgpu",[e,t=>e.alloc(t),t=>e.free(t),(n,r,a,i=!1)=>{if(i)at("verbose",(()=>`[WebGPU] jsepCopyGpuToGpu: src=${n}, dst=${r}, size=${a}`)),e.memcpy(n,r);else{at("verbose",(()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${n}, gpuDataId=${r}, size=${a}`));let i=t.HEAPU8.subarray(n>>>0,(n>>>0)+a);e.upload(r,i)}},async(n,r,a)=>{at("verbose",(()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${n}, dataOffset=${r}, size=${a}`)),await e.download(n,(()=>t.HEAPU8.subarray(r>>>0,(r>>>0)+a)))},(n,r,a)=>e.createKernel(n,r,a,t.UTF8ToString(t._JsepGetNodeName(r))),t=>e.releaseKernel(t),(n,r,a,i)=>{at("verbose",(()=>`[WebGPU] jsepRun: sessionHandle=${a}, kernel=${n}, contextDataOffset=${r}`));let s=new Ul(t,e,r);return e.computeKernel(n,s,i)},()=>e.captureBegin(),()=>e.captureEnd(),()=>e.replay()])}else a("webnn")}})),Su=L((()=>{Fo(),Ro(),Do(),zo(),Bo(),Lo(),Vl=(e,t)=>{0!==ze()._OrtInit(e,t)&&Re("Can't initialize onnxruntime.")},Gl=async e=>{Vl(e.wasm.numThreads,Ke(e.logLevel))},jl=async(e,t)=>{{let n=(Tu(),W(Ll)).init;if("webgpu"===t){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let t=e.webgpu.adapter;if(t){if("object"!=typeof t.limits||"object"!=typeof t.features||"function"!=typeof t.requestDevice)throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(void 0!==n&&"low-power"!==n&&"high-performance"!==n)throw new Error(`Invalid powerPreference setting: "${n}"`);let r=e.webgpu.forceFallbackAdapter;if(void 0!==r&&"boolean"!=typeof r)throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:r}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await n("webgpu",ze(),e,t)}if("webnn"===t){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await n("webnn",ze(),e)}}},ql=new Map,Hl=e=>{let t=ze(),n=t.stackSave();try{let n=t.stackAlloc(8);return 0!==t._OrtGetInputOutputCount(e,n,n+4)&&Re("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(n)}},Kl=e=>{let t=ze(),n=t._malloc(e.byteLength);if(0===n)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Yl=async(e,t)=>{let n,r,a=ze();Array.isArray(e)?[n,r]=e:e.buffer===a.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Kl(e);let i=0,s=0,o=0,l=[],u=[],d=[];try{if([s,l]=Ve(t),t?.externalData&&a.mountExternalData){let e=[];for(let n of t.externalData){let t="string"==typeof n?n:n.path;e.push(Qe("string"==typeof n?n:n.data).then((e=>{a.mountExternalData(t,e)})))}await Promise.all(e)}i=await a._OrtCreateSession(n,r,s),0===i&&Re("Can't create a session.");let[e,c]=Hl(i),p=!!t?.enableGraphCapture,h=[],f=[],m=[];for(let t=0;t"gpu-buffer"===e))&&(o=a._OrtCreateBinding(i),0===o&&Re("Can't create IO binding."),g={handle:o,outputPreferredLocations:m,outputPreferredLocationsEncoded:m.map((e=>Xe(e)))}),ql.set(i,[i,u,d,g,p,!1]),[i,h,f]}catch(e){throw u.forEach((e=>a._OrtFree(e))),d.forEach((e=>a._OrtFree(e))),0!==o&&a._OrtReleaseBinding(o),0!==i&&a._OrtReleaseSession(i),e}finally{a._free(n),0!==s&&a._OrtReleaseSessionOptions(s),l.forEach((e=>a._free(e))),a.unmountExternalData?.()}},Xl=e=>{let t=ze(),n=ql.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[r,a,i,s,o]=n;s&&(o&&t._OrtClearBoundOutputs(s.handle),t._OrtReleaseBinding(s.handle)),t.jsepOnReleaseSession?.(e),a.forEach((e=>t._OrtFree(e))),i.forEach((e=>t._OrtFree(e))),t._OrtReleaseSession(r),ql.delete(e)},Ql=(e,t,n,r,a,i=!1)=>{if(!e)return void t.push(0);let s,o,l=ze(),u=e[0],d=e[1],c=e[3];if("string"===u&&"gpu-buffer"===c)throw new Error("String tensor is not supported on GPU.");if(i&&"gpu-buffer"!==c)throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if("gpu-buffer"===c){let t=e[2].gpuBuffer,n=qe(Ge(u));o=d.reduce(((e,t)=>e*t),1)*n;let i=l.jsepRegisterBuffer;if(!i)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');s=i(r,a,t,o)}else{let t=e[2];if(Array.isArray(t)){o=4*t.length,s=l._malloc(o),n.push(s);let e=s/4;for(let r=0;rl.HEAP32[e++]=t));let n=l._OrtCreateTensor(Ge(u),s,o,h,d.length,Xe(c));0===n&&Re(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(n)}finally{l.stackRestore(p)}},Zl=async(e,t,n,r,a,i)=>{let s=ze(),o=ql.get(e);if(!o)throw new Error(`cannot run inference. invalid session id: ${e}`);let l=o[0],u=o[1],d=o[2],c=o[3],p=o[4],h=o[5],f=t.length,m=r.length,g=0,_=[],w=[],y=[],b=[],v=s.stackSave(),$=s.stackAlloc(4*f),x=s.stackAlloc(4*f),T=s.stackAlloc(4*m),S=s.stackAlloc(4*m);try{[g,_]=De(i);for(let r=0;re*t),1);n=je(i);let m=c?.outputPreferredLocations[r[e]];if("string"===n){if("gpu-buffer"===m)throw new Error("String tensor is not supported on GPU.");let e=[],t=u/4;for(let n=0;n0){let e=s.jsepGetBuffer;if(!e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let r=e(u),a=qe(i);if(void 0===a||!Ye(n))throw new Error(`Unsupported data type: ${n}`);l=!0,E.push([n,h,{gpuBuffer:r,download:s.jsepCreateDownloader(r,f*a,n),dispose:()=>{s._OrtReleaseTensor(t)}},"gpu-buffer"])}else{let e=new(He(n))(f);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s.HEAPU8.subarray(u,u+e.byteLength)),E.push([n,h,e,"cpu"])}}finally{s.stackRestore(i),"string"===n&&u&&s._free(u),l||s._OrtReleaseTensor(t)}}return c&&!p&&(s._OrtClearBoundOutputs(c.handle),ql.set(e,[l,u,d,c,p,!1])),E}finally{s.stackRestore(v),w.forEach((e=>s._OrtReleaseTensor(e))),y.forEach((e=>s._OrtReleaseTensor(e))),b.forEach((e=>s._free(e))),0!==g&&s._OrtReleaseRunOptions(g),_.forEach((e=>s._free(e)))}},Jl=e=>{let t=ze(),n=ql.get(e);if(!n)throw new Error("invalid session id");let r=n[0],a=t._OrtEndProfiling(r);0===a&&Re("Can't get an profile file name."),t._OrtFree(a)},eu=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&"buffer"in e&&t.push(e.buffer)}return t}})),Mu=N(((e,t)=>{t.exports='/*!\n * ONNX Runtime Web v1.17.3\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var vn=Object.defineProperty;var dd=Object.getOwnPropertyDescriptor;var ld=Object.getOwnPropertyNames;var cd=Object.prototype.hasOwnProperty;var q=(e,t)=>()=>(e&&(t=e(e=0)),t);var pr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Mr=(e,t)=>{for(var r in t)vn(e,r,{get:t[r],enumerable:!0})},pd=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ld(t))!cd.call(e,n)&&n!==r&&vn(e,n,{get:()=>t[n],enumerable:!(o=dd(t,n))||o.enumerable});return e};var Ft=e=>pd(vn({},"__esModule",{value:!0}),e);var $n={};Mr($n,{createReadStream:()=>Po,readFile:()=>md,readFileSync:()=>fd});var md,fd,Po,_n=q(()=>{md=void 0,fd=void 0,Po=void 0});var xn={};Mr(xn,{join:()=>hd});var hd,Sn=q(()=>{hd=void 0});var Ro=pr((ko,Cn)=>{"use strict";var Oo=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){var r=t,o,n;r.ready=new Promise((d,h)=>{o=d,n=h}),r.mountExternalData=(d,h)=>{(r.Fa||(r.Fa=new Map)).set(d,h)},r.unmountExternalData=()=>{delete r.Fa};let s=()=>{let d=(w,S,P)=>(...N)=>{let K=nt,X=S?.();N=w(...N);let ae=S?.();return X!==ae&&(w=ae,P(X),S=P=null),nt!=K?Cr():N},h=w=>async(...S)=>{try{if(r.Ea)throw Error("Session already started");let P=r.Ea={Za:S[0],errors:[]},N=await w(...S);if(r.Ea!==P)throw Error("Session mismatch");r.La?.flush();let K=P.errors;if(0ae),0r._OrtCreateSession,w=>r._OrtCreateSession=w),r._OrtRun=h(d(r._OrtRun,()=>r._OrtRun,w=>r._OrtRun=w)),r._OrtRunWithBinding=h(d(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,w=>r._OrtRunWithBinding=w)),r._OrtBindInput=d(r._OrtBindInput,()=>r._OrtBindInput,w=>r._OrtBindInput=w),s=void 0};r.jsepInit=(d,h)=>{if(s?.(),d==="webgpu"){[r.La,r.Ra,r.Va,r.Ma,r.Ua,r.sa,r.Wa,r.Ya,r.Sa,r.Ta,r.Xa]=h;let w=r.La;r.jsepRegisterBuffer=(S,P,N,K)=>w.registerBuffer(S,P,N,K),r.jsepGetBuffer=S=>w.getBuffer(S),r.jsepCreateDownloader=(S,P,N)=>w.createDownloader(S,P,N),r.jsepOnReleaseSession=S=>{w.onReleaseSession(S)},r.jsepOnRunStart=S=>w.onRunStart(S)}};var u=Object.assign({},r),l="./this.program",a=(d,h)=>{throw h},p=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",b="",_,y,$;if(f){var I=(_n(),Ft($n)),C=(Sn(),Ft(xn));b=m?C.dirname(b)+"/":__dirname+"/",_=(d,h)=>(d=Ae(d)?new URL(d):C.normalize(d),I.readFileSync(d,h?void 0:"utf8")),$=d=>(d=_(d,!0),d.buffer||(d=new Uint8Array(d)),d),y=(d,h,w,S=!0)=>{d=Ae(d)?new URL(d):C.normalize(d),I.readFile(d,S?void 0:"utf8",(P,N)=>{P?w(P):h(S?N.buffer:N)})},!r.thisProgram&&1{throw process.exitCode=d,h},r.inspect=()=>"[Emscripten Module object]"}else(p||m)&&(m?b=self.location.href:typeof document<"u"&&document.currentScript&&(b=document.currentScript.src),e&&(b=e),b.indexOf("blob:")!==0?b=b.substr(0,b.replace(/[?#].*/,"").lastIndexOf("/")+1):b="",_=d=>{var h=new XMLHttpRequest;return h.open("GET",d,!1),h.send(null),h.responseText},m&&($=d=>{var h=new XMLHttpRequest;return h.open("GET",d,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),y=(d,h,w)=>{var S=new XMLHttpRequest;S.open("GET",d,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?h(S.response):w()},S.onerror=w,S.send(null)});var v=console.log.bind(console),A=console.error.bind(console);Object.assign(r,u),u=null,typeof WebAssembly!="object"&&se("no native wasm support detected");var T,D=!1,U,V,H,R,L,pe,Ie;function we(){var d=T.buffer;r.HEAP8=V=new Int8Array(d),r.HEAP16=new Int16Array(d),r.HEAPU8=H=new Uint8Array(d),r.HEAPU16=new Uint16Array(d),r.HEAP32=R=new Int32Array(d),r.HEAPU32=L=new Uint32Array(d),r.HEAPF32=pe=new Float32Array(d),r.HEAPF64=Ie=new Float64Array(d)}var ne=[],ze=[],Q=[],xe=0,me=null,ue=null;function se(d){throw d="Aborted("+d+")",A(d),D=!0,U=1,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),n(d),d}var he=d=>d.startsWith("data:application/octet-stream;base64,"),Ae=d=>d.startsWith("file://"),He;if(He="ort-wasm-simd.wasm",!he(He)){var G=He;He=r.locateFile?r.locateFile(G,b):b+G}function J(d){if($)return $(d);throw"both async and sync fetching of the wasm failed"}function Se(d){if(p||m){if(typeof fetch=="function"&&!Ae(d))return fetch(d,{credentials:"same-origin"}).then(h=>{if(!h.ok)throw"failed to load wasm binary file at \'"+d+"\'";return h.arrayBuffer()}).catch(()=>J(d));if(y)return new Promise((h,w)=>{y(d,S=>h(new Uint8Array(S)),w)})}return Promise.resolve().then(()=>J(d))}function Qe(d,h,w){return Se(d).then(S=>WebAssembly.instantiate(S,h)).then(S=>S).then(w,S=>{A(`failed to asynchronously prepare wasm: ${S}`),se(S)})}function Xe(d,h){var w=He;return typeof WebAssembly.instantiateStreaming!="function"||he(w)||Ae(w)||f||typeof fetch!="function"?Qe(w,d,h):fetch(w,{credentials:"same-origin"}).then(S=>WebAssembly.instantiateStreaming(S,d).then(h,function(P){return A(`wasm streaming compile failed: ${P}`),A("falling back to ArrayBuffer instantiation"),Qe(w,d,h)}))}var Le,wt={931760:(d,h,w,S)=>{if(typeof r>"u"||!r.Fa)return 1;if(d=qe(d>>>0),d.startsWith("./")&&(d=d.substring(2)),d=r.Fa.get(d),!d)return 2;if(h>>>=0,w>>>=0,h+w>d.byteLength)return 3;try{return H.set(d.subarray(h,h+w),S>>>0>>>0),0}catch{return 4}},932261:()=>{r.Sa()},932292:()=>{r.Ta()},932321:()=>{r.Xa()},932346:d=>r.Ra(d),932379:d=>r.Va(d),932411:(d,h,w)=>{r.Ma(d,h,w,!0)},932450:(d,h,w)=>{r.Ma(d,h,w)},932483:d=>{r.sa("Abs",d,void 0)},932534:d=>{r.sa("Neg",d,void 0)},932585:d=>{r.sa("Floor",d,void 0)},932638:d=>{r.sa("Ceil",d,void 0)},932690:d=>{r.sa("Reciprocal",d,void 0)},932748:d=>{r.sa("Sqrt",d,void 0)},932800:d=>{r.sa("Exp",d,void 0)},932851:d=>{r.sa("Erf",d,void 0)},932902:d=>{r.sa("Sigmoid",d,void 0)},932957:(d,h,w)=>{r.sa("HardSigmoid",d,{alpha:h,beta:w})},933036:d=>{r.sa("Log",d,void 0)},933087:d=>{r.sa("Sin",d,void 0)},933138:d=>{r.sa("Cos",d,void 0)},933189:d=>{r.sa("Tan",d,void 0)},933240:d=>{r.sa("Asin",d,void 0)},933292:d=>{r.sa("Acos",d,void 0)},933344:d=>{r.sa("Atan",d,void 0)},933396:d=>{r.sa("Sinh",d,void 0)},933448:d=>{r.sa("Cosh",d,void 0)},933500:d=>{r.sa("Asinh",d,void 0)},933553:d=>{r.sa("Acosh",d,void 0)},933606:d=>{r.sa("Atanh",d,void 0)},933659:d=>{r.sa("Tanh",d,void 0)},933711:d=>{r.sa("Not",d,void 0)},933762:(d,h,w)=>{r.sa("Clip",d,{min:h,max:w})},933831:d=>{r.sa("Clip",d,void 0)},933883:(d,h)=>{r.sa("Elu",d,{alpha:h})},933941:d=>{r.sa("Relu",d,void 0)},933993:(d,h)=>{r.sa("LeakyRelu",d,{alpha:h})},934057:(d,h)=>{r.sa("ThresholdedRelu",d,{alpha:h})},934127:(d,h)=>{r.sa("Cast",d,{to:h})},934185:d=>{r.sa("Add",d,void 0)},934236:d=>{r.sa("Sub",d,void 0)},934287:d=>{r.sa("Mul",d,void 0)},934338:d=>{r.sa("Div",d,void 0)},934389:d=>{r.sa("Pow",d,void 0)},934440:d=>{r.sa("Equal",d,void 0)},934493:d=>{r.sa("Greater",d,void 0)},934548:d=>{r.sa("GreaterOrEqual",d,void 0)},934610:d=>{r.sa("Less",d,void 0)},934662:d=>{r.sa("LessOrEqual",d,void 0)},934721:(d,h,w,S,P)=>{r.sa("ReduceMean",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},934880:(d,h,w,S,P)=>{r.sa("ReduceMax",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935038:(d,h,w,S,P)=>{r.sa("ReduceMin",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935196:(d,h,w,S,P)=>{r.sa("ReduceProd",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935355:(d,h,w,S,P)=>{r.sa("ReduceSum",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935513:(d,h,w,S,P)=>{r.sa("ReduceL1",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935670:(d,h,w,S,P)=>{r.sa("ReduceL2",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935827:(d,h,w,S,P)=>{r.sa("ReduceLogSum",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935988:(d,h,w,S,P)=>{r.sa("ReduceSumSquare",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},936152:(d,h,w,S,P)=>{r.sa("ReduceLogSumExp",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},936316:d=>{r.sa("Where",d,void 0)},936369:(d,h,w)=>{r.sa("Transpose",d,{perm:h?Array.from(R.subarray(h>>>0,w>>>0)):[]})},936477:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe)=>{r.sa("ConvTranspose",d,{format:ae?"NHWC":"NCHW",autoPad:h,dilations:[w],group:S,kernel_shape:[P],pads:[N,K],strides:[X],wIsConst:()=>!!V[de>>>0],outputPadding:fe?Array.from(R.subarray(fe>>>0,Oe>>>0)):[],outputShape:Re?Array.from(R.subarray(Re>>>0,O>>>0)):[],activation:qe(oe)})},936879:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O)=>{r.sa("ConvTranspose",d,{format:X?"NHWC":"NCHW",autoPad:h,dilations:Array.from(R.subarray(w>>>0,(w>>>0)+2>>>0)),group:S,kernelShape:Array.from(R.subarray(P>>>0,(P>>>0)+2>>>0)),pads:Array.from(R.subarray(N>>>0,(N>>>0)+4>>>0)),strides:Array.from(R.subarray(K>>>0,(K>>>0)+2>>>0)),wIsConst:()=>!!V[ae>>>0],outputPadding:de?Array.from(R.subarray(de>>>0,fe>>>0)):[],outputShape:Oe?Array.from(R.subarray(Oe>>>0,Re>>>0)):[],activation:qe(O)})},937444:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe)=>{r.sa("ConvTranspose",d,{format:ae?"NHWC":"NCHW",autoPad:h,dilations:[w],group:S,kernel_shape:[P],pads:[N,K],strides:[X],wIsConst:()=>!!V[de>>>0],outputPadding:fe?Array.from(R.subarray(fe>>>0,Oe>>>0)):[],outputShape:Re?Array.from(R.subarray(Re>>>0,O>>>0)):[],activation:qe(oe)})},937846:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O)=>{r.sa("ConvTranspose",d,{format:X?"NHWC":"NCHW",autoPad:h,dilations:Array.from(R.subarray(w>>>0,(w>>>0)+2>>>0)),group:S,kernelShape:Array.from(R.subarray(P>>>0,(P>>>0)+2>>>0)),pads:Array.from(R.subarray(N>>>0,(N>>>0)+4>>>0)),strides:Array.from(R.subarray(K>>>0,(K>>>0)+2>>>0)),wIsConst:()=>!!V[ae>>>0],outputPadding:de?Array.from(R.subarray(de>>>0,fe>>>0)):[],outputShape:Oe?Array.from(R.subarray(Oe>>>0,Re>>>0)):[],activation:qe(O)})},938411:(d,h)=>{r.sa("GlobalAveragePool",d,{format:h?"NHWC":"NCHW"})},938502:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("AveragePool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},938786:(d,h)=>{r.sa("GlobalAveragePool",d,{format:h?"NHWC":"NCHW"})},938877:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("AveragePool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},939161:(d,h)=>{r.sa("GlobalMaxPool",d,{format:h?"NHWC":"NCHW"})},939248:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("MaxPool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},939528:(d,h)=>{r.sa("GlobalMaxPool",d,{format:h?"NHWC":"NCHW"})},939615:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("MaxPool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},939895:(d,h,w,S,P)=>{r.sa("Gemm",d,{alpha:h,beta:w,transA:S,transB:P})},939999:d=>{r.sa("MatMul",d,void 0)},940053:(d,h,w,S)=>{r.sa("ArgMax",d,{keepDims:!!h,selectLastIndex:!!w,axis:S})},940161:(d,h,w,S)=>{r.sa("ArgMin",d,{keepDims:!!h,selectLastIndex:!!w,axis:S})},940269:(d,h)=>{r.sa("Softmax",d,{axis:h})},940332:(d,h)=>{r.sa("Concat",d,{axis:h})},940392:(d,h,w,S,P)=>{r.sa("Split",d,{axis:h,numOutputs:w,splitSizes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},940532:d=>{r.sa("Expand",d,void 0)},940586:(d,h)=>{r.sa("Gather",d,{axis:Number(h)})},940657:(d,h)=>{r.sa("GatherElements",d,{axis:Number(h)})},940736:(d,h,w,S,P,N,K,X,ae,de,fe)=>{r.sa("Resize",d,{antialias:h,axes:w?Array.from(R.subarray(w>>>0,S>>>0)):[],coordinateTransformMode:qe(P),cubicCoeffA:N,excludeOutside:K,extrapolationValue:X,keepAspectRatioPolicy:qe(ae),mode:qe(de),nearestMode:qe(fe)})},941082:(d,h,w,S,P,N,K)=>{r.sa("Slice",d,{starts:h?Array.from(R.subarray(h>>>0,w>>>0)):[],ends:S?Array.from(R.subarray(S>>>0,P>>>0)):[],axes:N?Array.from(R.subarray(N>>>0,K>>>0)):[]})},941298:d=>{r.sa("Tile",d,void 0)},941350:(d,h,w)=>{r.sa("LayerNormalization",d,{axis:Number(h),epsilon:Number(w)})},941457:(d,h,w)=>{r.sa("InstanceNormalization",d,{epsilon:h,format:w?"NHWC":"NCHW"})},941571:(d,h,w)=>{r.sa("InstanceNormalization",d,{epsilon:h,format:w?"NHWC":"NCHW"})},941685:d=>{r.sa("Range",d,void 0)},941738:(d,h)=>{r.sa("Einsum",d,{equation:qe(h)})},941819:(d,h,w,S,P)=>{r.sa("Pad",d,{mode:h,value:w,pads:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},941946:(d,h,w,S,P,N)=>{r.sa("BatchNormalization",d,{epsilon:h,momentum:w,spatial:!!P,trainingMode:!!S,format:N?"NHWC":"NCHW"})},942115:(d,h,w,S,P,N)=>{r.sa("BatchNormalization",d,{epsilon:h,momentum:w,spatial:!!P,trainingMode:!!S,format:N?"NHWC":"NCHW"})},942284:(d,h,w)=>{r.sa("CumSum",d,{exclusive:Number(h),reverse:Number(w)})},942381:(d,h,w,S,P,N,K,X,ae)=>{r.sa("Attention",d,{numHeads:h,isUnidirectional:w,maskFilterValue:S,scale:P,doRotary:N,qkvHiddenSizes:K?Array.from(R.subarray(Number(X)>>>0,Number(X)+K>>>0)):[],pastPresentShareBuffer:!!ae})},942653:d=>{r.sa("BiasAdd",d,void 0)},942708:d=>{r.sa("BiasSplitGelu",d,void 0)},942769:d=>{r.sa("FastGelu",d,void 0)},942825:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re)=>{r.sa("Conv",d,{format:ae?"NHWC":"NCHW",auto_pad:h,dilations:[w],group:S,kernel_shape:[P],pads:N?Array.from(R.subarray(N>>>0,K>>>0)):[],strides:[X],w_is_const:()=>!!V[de>>>0],activation:qe(fe),activation_params:Oe?Array.from(pe.subarray(Oe>>>0,Re>>>0)):[]})},943195:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("Conv",d,{format:Oe?"NHWC":"NCHW",auto_pad:h,dilations:[w,S],group:P,kernel_shape:[N,K],pads:X?Array.from(R.subarray(X>>>0,ae>>>0)):[],strides:[de,fe],w_is_const:()=>!!V[Re>>>0],activation:qe(O),activation_params:oe?Array.from(pe.subarray(oe>>>0,Ce>>>0)):[]})},943586:d=>{r.sa("Gelu",d,void 0)},943638:(d,h,w,S,P,N)=>{r.sa("MatMulNBits",d,{k:h,n:w,accuracyLevel:S,bits:P,blockSize:N})},943765:(d,h,w,S,P,N)=>{r.sa("MultiHeadAttention",d,{numHeads:h,isUnidirectional:w,maskFilterValue:S,scale:P,doRotary:N})},943924:(d,h)=>{r.sa("SkipLayerNormalization",d,{epsilon:h})},944005:d=>{r.Wa(d)},944039:(d,h)=>r.Ya(d,h,r.Ea.Za,r.Ea.errors)};function Ne(d){this.name="ExitStatus",this.message=`Program terminated with exit(${d})`,this.status=d}function Fe(d){this.Ja=d-24,this.Pa=function(h){L[this.Ja+4>>>2>>>0]=h},this.Oa=function(h){L[this.Ja+8>>>2>>>0]=h},this.eb=function(h,w){this.Na(),this.Pa(h),this.Oa(w)},this.Na=function(){L[this.Ja+16>>>2>>>0]=0}}var Je=0,kt=0,vt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,xt=(d,h,w)=>{h>>>=0;var S=h+w;for(w=h;d[w]&&!(w>=S);)++w;if(16P?S+=String.fromCharCode(P):(P-=65536,S+=String.fromCharCode(55296|P>>10,56320|P&1023))}}else S+=String.fromCharCode(P)}return S},qe=(d,h)=>(d>>>=0)?xt(H,d,h):"",Zt=d=>{for(var h=0,w=0;w=S?h++:2047>=S?h+=2:55296<=S&&57343>=S?(h+=4,++w):h+=3}return h},Vt=(d,h,w,S)=>{if(w>>>=0,!(0=K){var X=d.charCodeAt(++N);K=65536+((K&1023)<<10)|X&1023}if(127>=K){if(w>=S)break;h[w++>>>0]=K}else{if(2047>=K){if(w+1>=S)break;h[w++>>>0]=192|K>>6}else{if(65535>=K){if(w+2>=S)break;h[w++>>>0]=224|K>>12}else{if(w+3>=S)break;h[w++>>>0]=240|K>>18,h[w++>>>0]=128|K>>12&63}h[w++>>>0]=128|K>>6&63}h[w++>>>0]=128|K&63}}return h[w>>>0]=0,w-P},St=d=>d%4===0&&(d%100!==0||d%400===0),$t=[0,31,60,91,121,152,182,213,244,274,305,335],Nt=[0,31,59,90,120,151,181,212,243,273,304,334],Wt=d=>{var h=Zt(d)+1,w=Lt(h);return w&&Vt(d,H,w,h),w},Rt=[],Qt=(d,h)=>{Rt.length=0;for(var w;w=H[d++>>>0];){var S=w!=105;S&=w!=112,h+=S&&h%8?4:0,Rt.push(w==112?L[h>>>2>>>0]:w==105?R[h>>>2>>>0]:Ie[h>>>3>>>0]),h+=S?8:4}return Rt},at={},Xt=()=>{if(!Gt){var d={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",_:l||"./this.program"},h;for(h in at)at[h]===void 0?delete d[h]:d[h]=at[h];var w=[];for(h in d)w.push(`${h}=${d[h]}`);Gt=w}return Gt},Gt,Ke=[null,[],[]],vr=[31,29,31,30,31,30,31,31,30,31,30,31],ke=[31,28,31,30,31,30,31,31,30,31,30,31];function $r(d){var h=Array(Zt(d)+1);return Vt(d,h,0,h.length),h}function Ht(d,h,w,S){function P(O,oe,Ce){for(O=typeof O=="number"?O.toString():O||"";O.lengthPr?-1:0ct-O.getDate())oe-=ct-O.getDate()+1,O.setDate(1),11>Ce?O.setMonth(Ce+1):(O.setMonth(0),O.setFullYear(O.getFullYear()+1));else{O.setDate(O.getDate()+oe);break}}return Ce=new Date(O.getFullYear()+1,0,4),oe=X(new Date(O.getFullYear(),0,4)),Ce=X(Ce),0>=K(oe,O)?0>=K(Ce,O)?O.getFullYear()+1:O.getFullYear():O.getFullYear()-1}d>>>=0,h>>>=0,w>>>=0,S>>>=0;var de=L[S+40>>>2>>>0];S={bb:R[S>>>2>>>0],ab:R[S+4>>>2>>>0],Ga:R[S+8>>>2>>>0],Ka:R[S+12>>>2>>>0],Ha:R[S+16>>>2>>>0],Da:R[S+20>>>2>>>0],xa:R[S+24>>>2>>>0],Ca:R[S+28>>>2>>>0],fb:R[S+32>>>2>>>0],$a:R[S+36>>>2>>>0],cb:de?qe(de):""},w=qe(w),de={"%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"};for(var fe in de)w=w.replace(new RegExp(fe,"g"),de[fe]);var Oe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Re="January February March April May June July August September October November December".split(" ");de={"%a":O=>Oe[O.xa].substring(0,3),"%A":O=>Oe[O.xa],"%b":O=>Re[O.Ha].substring(0,3),"%B":O=>Re[O.Ha],"%C":O=>N((O.Da+1900)/100|0,2),"%d":O=>N(O.Ka,2),"%e":O=>P(O.Ka,2," "),"%g":O=>ae(O).toString().substring(2),"%G":O=>ae(O),"%H":O=>N(O.Ga,2),"%I":O=>(O=O.Ga,O==0?O=12:12{for(var oe=0,Ce=0;Ce<=O.Ha-1;oe+=(St(O.Da+1900)?vr:ke)[Ce++]);return N(O.Ka+oe,3)},"%m":O=>N(O.Ha+1,2),"%M":O=>N(O.ab,2),"%n":()=>`\n`,"%p":O=>0<=O.Ga&&12>O.Ga?"AM":"PM","%S":O=>N(O.bb,2),"%t":()=>"\t","%u":O=>O.xa||7,"%U":O=>N(Math.floor((O.Ca+7-O.xa)/7),2),"%V":O=>{var oe=Math.floor((O.Ca+7-(O.xa+6)%7)/7);if(2>=(O.xa+371-O.Ca-2)%7&&oe++,oe)oe==53&&(Ce=(O.xa+371-O.Ca)%7,Ce==4||Ce==3&&St(O.Da)||(oe=1));else{oe=52;var Ce=(O.xa+7-O.Ca-1)%7;(Ce==4||Ce==5&&St(O.Da%400-1))&&oe++}return N(oe,2)},"%w":O=>O.xa,"%W":O=>N(Math.floor((O.Ca+7-(O.xa+6)%7)/7),2),"%y":O=>(O.Da+1900).toString().substring(2),"%Y":O=>O.Da+1900,"%z":O=>{O=O.$a;var oe=0<=O;return O=Math.abs(O)/60,(oe?"+":"-")+("0000"+(O/60*100+O%60)).slice(-4)},"%Z":O=>O.cb,"%%":()=>"%"},w=w.replace(/%%/g,"\\0\\0");for(fe in de)w.includes(fe)&&(w=w.replace(new RegExp(fe,"g"),de[fe](S)));return w=w.replace(/\\0\\0/g,"%"),fe=$r(w),fe.length>h?0:(V.set(fe,d>>>0),fe.length-1)}var Ct=d=>{try{d()}catch(h){se(h)}};function mn(){var d=ee,h={};for(let[w,S]of Object.entries(d))h[w]=typeof S=="function"?function(){_t.push(w);try{return S.apply(null,arguments)}finally{D||(_t.pop(),nt&&it===1&&_t.length===0&&(it=0,Ct(dr),typeof Fibers<"u"&&Fibers.gb()))}}:S;return h}var it=0,nt=null,te=0,_t=[],Jt={},_r={},xr=0,er=null,Sr=[];function Cr(){return new Promise((d,h)=>{er={resolve:d,reject:h}})}function Ir(){var d=Lt(65548),h=d+12;L[d>>>2>>>0]=h,L[d+4>>>2>>>0]=h+65536,h=_t[0];var w=Jt[h];return w===void 0&&(w=xr++,Jt[h]=w,_r[w]=h),R[d+8>>>2>>>0]=w,d}function Ar(d){if(!D){if(it===0){var h=!1,w=!1;d((S=0)=>{if(!D&&(te=S,h=!0,w)){it=2,Ct(()=>lr(nt)),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.resume(),S=!1;try{var P=(0,ee[_r[R[nt+8>>>2>>>0]]])()}catch(X){P=X,S=!0}var N=!1;if(!nt){var K=er;K&&(er=null,(S?K.reject:K.resolve)(P),N=!0)}if(S&&!N)throw P}}),w=!0,h||(it=1,nt=Ir(),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.pause(),Ct(()=>ur(nt)))}else it===2?(it=0,Ct(cr),nr(nt),nt=null,Sr.forEach(S=>{if(!D)try{S();try{U=U=S=U,r.onExit?.(S),D=!0,a(S,new Ne(S))}catch(P){P instanceof Ne||P=="unwind"||a(1,P)}}catch(P){P instanceof Ne||P=="unwind"||a(1,P)}})):se(`invalid state: ${it}`);return te}}function tr(d){return Ar(h=>{d().then(h)})}var Tr={n:function(d,h,w){return tr(async()=>{await r.Ua(d,h,w)})},a:function(d,h,w){throw d>>>=0,new Fe(d).eb(h>>>0,w>>>0),Je=d,kt++,Je},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(d,h,w){d=h+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*h:NaN,w>>>=0,d=new Date(1e3*d),R[w>>>2>>>0]=d.getUTCSeconds(),R[w+4>>>2>>>0]=d.getUTCMinutes(),R[w+8>>>2>>>0]=d.getUTCHours(),R[w+12>>>2>>>0]=d.getUTCDate(),R[w+16>>>2>>>0]=d.getUTCMonth(),R[w+20>>>2>>>0]=d.getUTCFullYear()-1900,R[w+24>>>2>>>0]=d.getUTCDay(),R[w+28>>>2>>>0]=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(d,h,w){d=h+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*h:NaN,w>>>=0,d=new Date(1e3*d),R[w>>>2>>>0]=d.getSeconds(),R[w+4>>>2>>>0]=d.getMinutes(),R[w+8>>>2>>>0]=d.getHours(),R[w+12>>>2>>>0]=d.getDate(),R[w+16>>>2>>>0]=d.getMonth(),R[w+20>>>2>>>0]=d.getFullYear()-1900,R[w+24>>>2>>>0]=d.getDay(),R[w+28>>>2>>>0]=(St(d.getFullYear())?$t:Nt)[d.getMonth()]+d.getDate()-1|0,R[w+36>>>2>>>0]=-(60*d.getTimezoneOffset()),h=new Date(d.getFullYear(),6,1).getTimezoneOffset();var S=new Date(d.getFullYear(),0,1).getTimezoneOffset();R[w+32>>>2>>>0]=(h!=S&&d.getTimezoneOffset()==Math.min(S,h))|0},s:function(d){d>>>=0;var h=new Date(R[d+20>>>2>>>0]+1900,R[d+16>>>2>>>0],R[d+12>>>2>>>0],R[d+8>>>2>>>0],R[d+4>>>2>>>0],R[d>>>2>>>0],0),w=R[d+32>>>2>>>0],S=h.getTimezoneOffset(),P=new Date(h.getFullYear(),6,1).getTimezoneOffset(),N=new Date(h.getFullYear(),0,1).getTimezoneOffset(),K=Math.min(N,P);return 0>w?R[d+32>>>2>>>0]=+(P!=N&&K==S):0>>2>>>0]=h.getDay(),R[d+28>>>2>>>0]=(St(h.getFullYear())?$t:Nt)[h.getMonth()]+h.getDate()-1|0,R[d>>>2>>>0]=h.getSeconds(),R[d+4>>>2>>>0]=h.getMinutes(),R[d+8>>>2>>>0]=h.getHours(),R[d+12>>>2>>>0]=h.getDate(),R[d+16>>>2>>>0]=h.getMonth(),R[d+20>>>2>>>0]=h.getYear(),d=h.getTime(),isNaN(d)?(R[rr()>>>2>>>0]=61,d=-1):d/=1e3,or((Le=d,1<=+Math.abs(Le)?0>>0:~~+Math.ceil((Le-+(~~Le>>>0))/4294967296)>>>0:0)),d>>>0},o:function(){return-52},p:function(){},w:function(d,h,w){function S(ae){return(ae=ae.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?ae[1]:"GMT"}w>>>=0;var P=new Date().getFullYear(),N=new Date(P,0,1),K=new Date(P,6,1);P=N.getTimezoneOffset();var X=K.getTimezoneOffset();L[d>>>0>>>2>>>0]=60*Math.max(P,X),R[h>>>0>>>2>>>0]=+(P!=X),d=S(N),h=S(K),d=Wt(d),h=Wt(h),X>>2>>>0]=d,L[w+4>>>2>>>0]=h):(L[w>>>2>>>0]=h,L[w+4>>>2>>>0]=d)},e:()=>{se("")},b:function(d,h,w){return d>>>=0,h=Qt(h>>>0,w>>>0),wt[d].apply(null,h)},i:function(d,h,w){return d>>>=0,h=Qt(h>>>0,w>>>0),wt[d].apply(null,h)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(d,h,w){return h>>>=0,H.copyWithin(d>>>0>>>0,h>>>0,h+(w>>>0)>>>0)},u:function(d){d>>>=0;var h=H.length;if(4294901760=w;w*=2){var S=h*(1+.2/w);S=Math.min(S,d+100663296);var P=Math;S=Math.max(d,S);e:{P=(P.min.call(P,4294901760,S+(65536-S%65536)%65536)-T.buffer.byteLength+65535)/65536;try{T.grow(P),we();var N=1;break e}catch{}N=void 0}if(N)return!0}return!1},E:function(d,h){d>>>=0,h>>>=0;var w=0;return Xt().forEach((S,P)=>{var N=h+w;for(P=L[d+4*P>>>2>>>0]=N,N=0;N>>0>>>0]=S.charCodeAt(N);V[P>>>0>>>0]=0,w+=S.length+1}),0},F:function(d,h){d>>>=0,h>>>=0;var w=Xt();L[d>>>2>>>0]=w.length;var S=0;return w.forEach(P=>S+=P.length+1),L[h>>>2>>>0]=S,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(d,h,w,S){h>>>=0,w>>>=0,S>>>=0;for(var P=0,N=0;N>>2>>>0],X=L[h+4>>>2>>>0];h+=8;for(var ae=0;ae>>0],fe=Ke[d];de===0||de===10?((d===1?v:A)(xt(fe,0)),fe.length=0):fe.push(de)}P+=X}return L[S>>>2>>>0]=P,0},v:Ht,d:function(d,h,w,S){return Ht(d>>>0,h>>>0,w>>>0,S>>>0)}},ee=function(){function d(w){return ee=w.exports,ee=mn(),ee=Er(),T=ee.M,we(),ze.unshift(ee.N),xe--,xe==0&&(me!==null&&(clearInterval(me),me=null),ue&&(w=ue,ue=null,w())),ee}var h={a:Tr};if(xe++,r.instantiateWasm)try{return r.instantiateWasm(h,d)}catch(w){A(`Module.instantiateWasm callback failed with error: ${w}`),n(w)}return Xe(h,function(w){d(w.instance)}).catch(n),{}}();r._OrtInit=(d,h)=>(r._OrtInit=ee.O)(d,h),r._OrtGetLastError=(d,h)=>(r._OrtGetLastError=ee.P)(d,h),r._OrtCreateSessionOptions=(d,h,w,S,P,N,K,X,ae,de)=>(r._OrtCreateSessionOptions=ee.Q)(d,h,w,S,P,N,K,X,ae,de),r._OrtAppendExecutionProvider=(d,h)=>(r._OrtAppendExecutionProvider=ee.R)(d,h),r._OrtAddFreeDimensionOverride=(d,h,w)=>(r._OrtAddFreeDimensionOverride=ee.S)(d,h,w),r._OrtAddSessionConfigEntry=(d,h,w)=>(r._OrtAddSessionConfigEntry=ee.T)(d,h,w),r._OrtReleaseSessionOptions=d=>(r._OrtReleaseSessionOptions=ee.U)(d),r._OrtCreateSession=(d,h,w)=>(r._OrtCreateSession=ee.V)(d,h,w),r._OrtReleaseSession=d=>(r._OrtReleaseSession=ee.W)(d),r._OrtGetInputOutputCount=(d,h,w)=>(r._OrtGetInputOutputCount=ee.X)(d,h,w),r._OrtGetInputName=(d,h)=>(r._OrtGetInputName=ee.Y)(d,h),r._OrtGetOutputName=(d,h)=>(r._OrtGetOutputName=ee.Z)(d,h),r._OrtFree=d=>(r._OrtFree=ee._)(d),r._OrtCreateTensor=(d,h,w,S,P,N)=>(r._OrtCreateTensor=ee.$)(d,h,w,S,P,N),r._OrtGetTensorData=(d,h,w,S,P)=>(r._OrtGetTensorData=ee.aa)(d,h,w,S,P),r._OrtReleaseTensor=d=>(r._OrtReleaseTensor=ee.ba)(d),r._OrtCreateRunOptions=(d,h,w,S)=>(r._OrtCreateRunOptions=ee.ca)(d,h,w,S),r._OrtAddRunConfigEntry=(d,h,w)=>(r._OrtAddRunConfigEntry=ee.da)(d,h,w),r._OrtReleaseRunOptions=d=>(r._OrtReleaseRunOptions=ee.ea)(d),r._OrtCreateBinding=d=>(r._OrtCreateBinding=ee.fa)(d),r._OrtBindInput=(d,h,w)=>(r._OrtBindInput=ee.ga)(d,h,w),r._OrtBindOutput=(d,h,w,S)=>(r._OrtBindOutput=ee.ha)(d,h,w,S),r._OrtClearBoundOutputs=d=>(r._OrtClearBoundOutputs=ee.ia)(d),r._OrtReleaseBinding=d=>(r._OrtReleaseBinding=ee.ja)(d),r._OrtRunWithBinding=(d,h,w,S,P)=>(r._OrtRunWithBinding=ee.ka)(d,h,w,S,P),r._OrtRun=(d,h,w,S,P,N,K,X)=>(r._OrtRun=ee.la)(d,h,w,S,P,N,K,X),r._OrtEndProfiling=d=>(r._OrtEndProfiling=ee.ma)(d),r._JsepOutput=(d,h,w)=>(r._JsepOutput=ee.na)(d,h,w),r._JsepGetNodeName=d=>(r._JsepGetNodeName=ee.oa)(d);var rr=()=>(rr=ee.pa)(),Lt=r._malloc=d=>(Lt=r._malloc=ee.qa)(d),nr=r._free=d=>(nr=r._free=ee.ra)(d),or=d=>(or=ee.ta)(d),ar=()=>(ar=ee.ua)(),ir=d=>(ir=ee.va)(d),sr=d=>(sr=ee.wa)(d),ur=d=>(ur=ee.ya)(d),dr=()=>(dr=ee.za)(),lr=d=>(lr=ee.Aa)(d),cr=()=>(cr=ee.Ba)();r.___start_em_js=944151,r.___stop_em_js=944312;function Er(){var d=ee;d=Object.assign({},d);var h=S=>()=>S()>>>0,w=S=>P=>S(P)>>>0;return d.pa=h(d.pa),d.qa=w(d.qa),d.ua=h(d.ua),d.wa=w(d.wa),d}r.stackAlloc=sr,r.stackSave=ar,r.stackRestore=ir,r.UTF8ToString=qe,r.stringToUTF8=(d,h,w)=>Vt(d,H,h,w),r.lengthBytesUTF8=Zt;var It;ue=function d(){It||Bt(),It||(ue=d)};function Bt(){if(!(0Oo)});var Bo=pr(()=>{});var Do=pr(()=>{});var Mo={};Mr(Mo,{cpus:()=>gd});var gd,zo=q(()=>{gd=void 0});var No=pr((Vo,In)=>{"use strict";var Uo=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){function r(){return ne.buffer!=me.buffer&&G(),me}function o(){return ne.buffer!=me.buffer&&G(),ue}function n(){return ne.buffer!=me.buffer&&G(),se}function s(){return ne.buffer!=me.buffer&&G(),he}function u(){return ne.buffer!=me.buffer&&G(),Ae}function l(){return ne.buffer!=me.buffer&&G(),He}var a=t,p,m;a.ready=new Promise((i,c)=>{p=i,m=c}),a.mountExternalData=(i,c)=>{(a.cb||(a.cb=new Map)).set(i,c)},a.unmountExternalData=()=>{delete a.cb};let f=()=>{let i=(g,x,E)=>(...k)=>{let W=pt,Z=x?.();k=g(...k);let ge=x?.();return Z!==ge&&(g=ge,E(Z),x=E=null),pt!=W?td():k},c=g=>async(...x)=>{try{if(a.bb)throw Error("Session already started");let E=a.bb={Gb:x[0],errors:[]},k=await g(...x);if(a.bb!==E)throw Error("Session mismatch");a.kb?.flush();let W=E.errors;if(0ge),0a._OrtCreateSession,g=>a._OrtCreateSession=g),a._OrtRun=c(i(a._OrtRun,()=>a._OrtRun,g=>a._OrtRun=g)),a._OrtRunWithBinding=c(i(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,g=>a._OrtRunWithBinding=g)),a._OrtBindInput=i(a._OrtBindInput,()=>a._OrtBindInput,g=>a._OrtBindInput=g),f=void 0};a.jsepInit=(i,c)=>{if(f?.(),i==="webgpu"){[a.kb,a.xb,a.Bb,a.lb,a.Ab,a.Ea,a.Cb,a.Eb,a.yb,a.zb,a.Db]=c;let g=a.kb;a.jsepRegisterBuffer=(x,E,k,W)=>g.registerBuffer(x,E,k,W),a.jsepGetBuffer=x=>g.getBuffer(x),a.jsepCreateDownloader=(x,E,k)=>g.createDownloader(x,E,k),a.jsepOnReleaseSession=x=>{g.onReleaseSession(x)},a.jsepOnRunStart=x=>g.onRunStart(x)}};var b=Object.assign({},a),_="./this.program",y=(i,c)=>{throw c},$=typeof window=="object",I=typeof importScripts=="function",C=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",v=a.ENVIRONMENT_IS_PTHREAD||!1,A="";function T(i){return a.locateFile?a.locateFile(i,A):A+i}var D,U,V;if(C){var H=(_n(),Ft($n)),R=(Sn(),Ft(xn));A=I?R.dirname(A)+"/":__dirname+"/",D=(c,g)=>(c=vt(c)?new URL(c):R.normalize(c),H.readFileSync(c,g?void 0:"utf8")),V=c=>(c=D(c,!0),c.buffer||(c=new Uint8Array(c)),c),U=(c,g,x,E=!0)=>{c=vt(c)?new URL(c):R.normalize(c),H.readFile(c,E?void 0:"utf8",(k,W)=>{k?x(k):g(E?W.buffer:W)})},!a.thisProgram&&1{throw process.exitCode=c,g},a.inspect=()=>"[Emscripten Module object]";let i;try{i=Bo()}catch(c){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),c}global.Worker=i.Worker}else($||I)&&(I?A=self.location.href:typeof document<"u"&&document.currentScript&&(A=document.currentScript.src),typeof e<"u"&&e&&(A=e),A.indexOf("blob:")!==0?A=A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):A="",C||(D=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.send(null),c.responseText},I&&(V=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),U=(i,c,g)=>{var x=new XMLHttpRequest;x.open("GET",i,!0),x.responseType="arraybuffer",x.onload=()=>{x.status==200||x.status==0&&x.response?c(x.response):g()},x.onerror=g,x.send(null)}));C&&typeof performance>"u"&&(global.performance=Do().performance);var L=console.log.bind(console),pe=console.error.bind(console);C&&(L=(...i)=>H.writeSync(1,i.join(" ")+`\n`),pe=(...i)=>H.writeSync(2,i.join(" ")+`\n`));var Ie=L,we=pe;Object.assign(a,b),b=null,typeof WebAssembly!="object"&&Je("no native wasm support detected");var ne,ze,Q=!1,xe,me,ue,se,he,Ae,He;function G(){var i=ne.buffer;a.HEAP8=me=new Int8Array(i),a.HEAP16=new Int16Array(i),a.HEAPU8=ue=new Uint8Array(i),a.HEAPU16=new Uint16Array(i),a.HEAP32=se=new Int32Array(i),a.HEAPU32=he=new Uint32Array(i),a.HEAPF32=Ae=new Float32Array(i),a.HEAPF64=He=new Float64Array(i)}var J=16777216;if(v)ne=a.wasmMemory;else if(a.wasmMemory)ne=a.wasmMemory;else if(ne=new WebAssembly.Memory({initial:J/65536,maximum:65536,shared:!0}),!(ne.buffer instanceof SharedArrayBuffer))throw we("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"),C&&we("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");G(),J=ne.buffer.byteLength;var Se=[],Qe=[],Xe=[],Le=0,wt=null,Ne=null;function Fe(){if(Le--,Le==0&&(wt!==null&&(clearInterval(wt),wt=null),Ne)){var i=Ne;Ne=null,i()}}function Je(i){throw i="Aborted("+i+")",we(i),Q=!0,xe=1,i=new WebAssembly.RuntimeError(i+". Build with -sASSERTIONS for more info."),m(i),i}var kt=i=>i.startsWith("data:application/octet-stream;base64,"),vt=i=>i.startsWith("file://"),xt;xt="ort-wasm-simd-threaded.wasm",kt(xt)||(xt=T(xt));function qe(i){if(V)return V(i);throw"both async and sync fetching of the wasm failed"}function Zt(i){if($||I){if(typeof fetch=="function"&&!vt(i))return fetch(i,{credentials:"same-origin"}).then(c=>{if(!c.ok)throw"failed to load wasm binary file at \'"+i+"\'";return c.arrayBuffer()}).catch(()=>qe(i));if(U)return new Promise((c,g)=>{U(i,x=>c(new Uint8Array(x)),g)})}return Promise.resolve().then(()=>qe(i))}function Vt(i,c,g){return Zt(i).then(x=>WebAssembly.instantiate(x,c)).then(x=>x).then(g,x=>{we(`failed to asynchronously prepare wasm: ${x}`),Je(x)})}function St(i,c){var g=xt;return typeof WebAssembly.instantiateStreaming!="function"||kt(g)||vt(g)||C||typeof fetch!="function"?Vt(g,i,c):fetch(g,{credentials:"same-origin"}).then(x=>WebAssembly.instantiateStreaming(x,i).then(c,function(E){return we(`wasm streaming compile failed: ${E}`),we("falling back to ArrayBuffer instantiation"),Vt(g,i,c)}))}var $t,Nt={933148:(i,c,g,x)=>{if(typeof a>"u"||!a.cb)return 1;if(i=Ke(i>>>0),i.startsWith("./")&&(i=i.substring(2)),i=a.cb.get(i),!i)return 2;if(c>>>=0,g>>>=0,x>>>=0,c+g>i.byteLength)return 3;try{return o().set(i.subarray(c,c+g),x>>>0),0}catch{return 4}},933649:()=>{a.yb()},933680:()=>{a.zb()},933709:()=>{a.Db()},933734:i=>a.xb(i),933767:i=>a.Bb(i),933799:(i,c,g)=>{a.lb(i,c,g,!0)},933838:(i,c,g)=>{a.lb(i,c,g)},933871:i=>{a.Ea("Abs",i,void 0)},933922:i=>{a.Ea("Neg",i,void 0)},933973:i=>{a.Ea("Floor",i,void 0)},934026:i=>{a.Ea("Ceil",i,void 0)},934078:i=>{a.Ea("Reciprocal",i,void 0)},934136:i=>{a.Ea("Sqrt",i,void 0)},934188:i=>{a.Ea("Exp",i,void 0)},934239:i=>{a.Ea("Erf",i,void 0)},934290:i=>{a.Ea("Sigmoid",i,void 0)},934345:(i,c,g)=>{a.Ea("HardSigmoid",i,{alpha:c,beta:g})},934424:i=>{a.Ea("Log",i,void 0)},934475:i=>{a.Ea("Sin",i,void 0)},934526:i=>{a.Ea("Cos",i,void 0)},934577:i=>{a.Ea("Tan",i,void 0)},934628:i=>{a.Ea("Asin",i,void 0)},934680:i=>{a.Ea("Acos",i,void 0)},934732:i=>{a.Ea("Atan",i,void 0)},934784:i=>{a.Ea("Sinh",i,void 0)},934836:i=>{a.Ea("Cosh",i,void 0)},934888:i=>{a.Ea("Asinh",i,void 0)},934941:i=>{a.Ea("Acosh",i,void 0)},934994:i=>{a.Ea("Atanh",i,void 0)},935047:i=>{a.Ea("Tanh",i,void 0)},935099:i=>{a.Ea("Not",i,void 0)},935150:(i,c,g)=>{a.Ea("Clip",i,{min:c,max:g})},935219:i=>{a.Ea("Clip",i,void 0)},935271:(i,c)=>{a.Ea("Elu",i,{alpha:c})},935329:i=>{a.Ea("Relu",i,void 0)},935381:(i,c)=>{a.Ea("LeakyRelu",i,{alpha:c})},935445:(i,c)=>{a.Ea("ThresholdedRelu",i,{alpha:c})},935515:(i,c)=>{a.Ea("Cast",i,{to:c})},935573:i=>{a.Ea("Add",i,void 0)},935624:i=>{a.Ea("Sub",i,void 0)},935675:i=>{a.Ea("Mul",i,void 0)},935726:i=>{a.Ea("Div",i,void 0)},935777:i=>{a.Ea("Pow",i,void 0)},935828:i=>{a.Ea("Equal",i,void 0)},935881:i=>{a.Ea("Greater",i,void 0)},935936:i=>{a.Ea("GreaterOrEqual",i,void 0)},935998:i=>{a.Ea("Less",i,void 0)},936050:i=>{a.Ea("LessOrEqual",i,void 0)},936109:(i,c,g,x,E)=>{a.Ea("ReduceMean",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936268:(i,c,g,x,E)=>{a.Ea("ReduceMax",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936426:(i,c,g,x,E)=>{a.Ea("ReduceMin",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936584:(i,c,g,x,E)=>{a.Ea("ReduceProd",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936743:(i,c,g,x,E)=>{a.Ea("ReduceSum",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936901:(i,c,g,x,E)=>{a.Ea("ReduceL1",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937058:(i,c,g,x,E)=>{a.Ea("ReduceL2",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937215:(i,c,g,x,E)=>{a.Ea("ReduceLogSum",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937376:(i,c,g,x,E)=>{a.Ea("ReduceSumSquare",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937540:(i,c,g,x,E)=>{a.Ea("ReduceLogSumExp",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937704:i=>{a.Ea("Where",i,void 0)},937757:(i,c,g)=>{a.Ea("Transpose",i,{perm:c?Array.from(n().subarray(c>>>0,g>>>0)):[]})},937865:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce)=>{a.Ea("ConvTranspose",i,{format:ge?"NHWC":"NCHW",autoPad:c,dilations:[g],group:x,kernel_shape:[E],pads:[k,W],strides:[Z],wIsConst:()=>!!r()[le>>>0],outputPadding:ve?Array.from(n().subarray(ve>>>0,Ue>>>0)):[],outputShape:Ve?Array.from(n().subarray(Ve>>>0,B>>>0)):[],activation:Ke(ce)})},938267:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B)=>{a.Ea("ConvTranspose",i,{format:Z?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(g>>>0,(g>>>0)+2>>>0)),group:x,kernelShape:Array.from(n().subarray(E>>>0,(E>>>0)+2>>>0)),pads:Array.from(n().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ge>>>0],outputPadding:le?Array.from(n().subarray(le>>>0,ve>>>0)):[],outputShape:Ue?Array.from(n().subarray(Ue>>>0,Ve>>>0)):[],activation:Ke(B)})},938832:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce)=>{a.Ea("ConvTranspose",i,{format:ge?"NHWC":"NCHW",autoPad:c,dilations:[g],group:x,kernel_shape:[E],pads:[k,W],strides:[Z],wIsConst:()=>!!r()[le>>>0],outputPadding:ve?Array.from(n().subarray(ve>>>0,Ue>>>0)):[],outputShape:Ve?Array.from(n().subarray(Ve>>>0,B>>>0)):[],activation:Ke(ce)})},939234:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B)=>{a.Ea("ConvTranspose",i,{format:Z?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(g>>>0,(g>>>0)+2>>>0)),group:x,kernelShape:Array.from(n().subarray(E>>>0,(E>>>0)+2>>>0)),pads:Array.from(n().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ge>>>0],outputPadding:le?Array.from(n().subarray(le>>>0,ve>>>0)):[],outputShape:Ue?Array.from(n().subarray(Ue>>>0,Ve>>>0)):[],activation:Ke(B)})},939799:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939890:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("AveragePool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},940174:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},940265:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("AveragePool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},940549:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},940636:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("MaxPool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},940916:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},941003:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("MaxPool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},941283:(i,c,g,x,E)=>{a.Ea("Gemm",i,{alpha:c,beta:g,transA:x,transB:E})},941387:i=>{a.Ea("MatMul",i,void 0)},941441:(i,c,g,x)=>{a.Ea("ArgMax",i,{keepDims:!!c,selectLastIndex:!!g,axis:x})},941549:(i,c,g,x)=>{a.Ea("ArgMin",i,{keepDims:!!c,selectLastIndex:!!g,axis:x})},941657:(i,c)=>{a.Ea("Softmax",i,{axis:c})},941720:(i,c)=>{a.Ea("Concat",i,{axis:c})},941780:(i,c,g,x,E)=>{a.Ea("Split",i,{axis:c,numOutputs:g,splitSizes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},941920:i=>{a.Ea("Expand",i,void 0)},941974:(i,c)=>{a.Ea("Gather",i,{axis:Number(c)})},942045:(i,c)=>{a.Ea("GatherElements",i,{axis:Number(c)})},942124:(i,c,g,x,E,k,W,Z,ge,le,ve)=>{a.Ea("Resize",i,{antialias:c,axes:g?Array.from(n().subarray(g>>>0,x>>>0)):[],coordinateTransformMode:Ke(E),cubicCoeffA:k,excludeOutside:W,extrapolationValue:Z,keepAspectRatioPolicy:Ke(ge),mode:Ke(le),nearestMode:Ke(ve)})},942470:(i,c,g,x,E,k,W)=>{a.Ea("Slice",i,{starts:c?Array.from(n().subarray(c>>>0,g>>>0)):[],ends:x?Array.from(n().subarray(x>>>0,E>>>0)):[],axes:k?Array.from(n().subarray(k>>>0,W>>>0)):[]})},942686:i=>{a.Ea("Tile",i,void 0)},942738:(i,c,g)=>{a.Ea("LayerNormalization",i,{axis:Number(c),epsilon:Number(g)})},942845:(i,c,g)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:g?"NHWC":"NCHW"})},942959:(i,c,g)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:g?"NHWC":"NCHW"})},943073:i=>{a.Ea("Range",i,void 0)},943126:(i,c)=>{a.Ea("Einsum",i,{equation:Ke(c)})},943207:(i,c,g,x,E)=>{a.Ea("Pad",i,{mode:c,value:g,pads:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},943334:(i,c,g,x,E,k)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:g,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},943503:(i,c,g,x,E,k)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:g,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},943672:(i,c,g)=>{a.Ea("CumSum",i,{exclusive:Number(c),reverse:Number(g)})},943769:(i,c,g,x,E,k,W,Z,ge)=>{a.Ea("Attention",i,{numHeads:c,isUnidirectional:g,maskFilterValue:x,scale:E,doRotary:k,qkvHiddenSizes:W?Array.from(n().subarray(Number(Z)>>>0,Number(Z)+W>>>0)):[],pastPresentShareBuffer:!!ge})},944041:i=>{a.Ea("BiasAdd",i,void 0)},944096:i=>{a.Ea("BiasSplitGelu",i,void 0)},944157:i=>{a.Ea("FastGelu",i,void 0)},944213:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve)=>{a.Ea("Conv",i,{format:ge?"NHWC":"NCHW",auto_pad:c,dilations:[g],group:x,kernel_shape:[E],pads:k?Array.from(n().subarray(k>>>0,W>>>0)):[],strides:[Z],w_is_const:()=>!!r()[le>>>0],activation:Ke(ve),activation_params:Ue?Array.from(u().subarray(Ue>>>0,Ve>>>0)):[]})},944583:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("Conv",i,{format:Ue?"NHWC":"NCHW",auto_pad:c,dilations:[g,x],group:E,kernel_shape:[k,W],pads:Z?Array.from(n().subarray(Z>>>0,ge>>>0)):[],strides:[le,ve],w_is_const:()=>!!r()[Ve>>>0],activation:Ke(B),activation_params:ce?Array.from(u().subarray(ce>>>0,Te>>>0)):[]})},944974:i=>{a.Ea("Gelu",i,void 0)},945026:(i,c,g,x,E,k)=>{a.Ea("MatMulNBits",i,{k:c,n:g,accuracyLevel:x,bits:E,blockSize:k})},945153:(i,c,g,x,E,k)=>{a.Ea("MultiHeadAttention",i,{numHeads:c,isUnidirectional:g,maskFilterValue:x,scale:E,doRotary:k})},945312:(i,c)=>{a.Ea("SkipLayerNormalization",i,{epsilon:c})},945393:i=>{a.Cb(i)},945427:(i,c)=>a.Eb(i,c,a.bb.Gb,a.bb.errors)};function Wt(i){this.name="ExitStatus",this.message=`Program terminated with exit(${i})`,this.status=i}var Rt=i=>{i.terminate(),i.onmessage=()=>{}},Qt=i=>{te.Ya.length==0&&(it(),te.mb(te.Ya[0]));var c=te.Ya.pop();if(!c)return 6;te.Za.push(c),te.Qa[i.Xa]=c,c.Xa=i.Xa;var g={cmd:"run",start_routine:i.Hb,arg:i.ub,pthread_ptr:i.Xa};return C&&c.unref(),c.postMessage(g,i.Nb),0},at=0,Xt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Gt=(i,c,g)=>{c>>>=0;var x=c+g;for(g=c;i[g]&&!(g>=x);)++g;if(16E?x+=String.fromCharCode(E):(E-=65536,x+=String.fromCharCode(55296|E>>10,56320|E&1023))}}else x+=String.fromCharCode(E)}return x},Ke=(i,c)=>(i>>>=0)?Gt(o(),i,c):"",vr=i=>{var c=bn();return i=i(),Br(c),i};function ke(i,c){var g=arguments.length-2,x=arguments;return vr(()=>{for(var E=wn(8*g),k=E>>>3,W=0;W>>0]=Z}return wo(i,g,E,c)})}function $r(i){if(v)return ke(0,1,i);xe=i,0{if(xe=i,v)throw Jt(i),"unwind";$r(i)},Ct=i=>{i instanceof Wt||i=="unwind"||y(1,i)};function mn(){for(var i=a.numThreads;i--;)it();Se.unshift(()=>{Le++,nt(()=>Fe())})}function it(){var i=T("ort-wasm-simd-threaded.worker.js");i=new Worker(i),te.Ya.push(i)}function nt(i){v?i():Promise.all(te.Ya.map(te.mb)).then(i)}var te={Ya:[],Za:[],qb:[],Qa:{},hb(){v?(te.receiveObjectTransfer=te.Fb,te.threadInitTLS=te.pb,te.setExitStatus=te.ob):mn()},ob:i=>xe=i,Qb:["$terminateWorker"],Ib:()=>{for(var i of te.Za)Rt(i);for(i of te.Ya)Rt(i);te.Ya=[],te.Za=[],te.Qa=[]},nb:i=>{var c=i.Xa;delete te.Qa[c],te.Ya.push(i),te.Za.splice(te.Za.indexOf(i),1),i.Xa=0,gn(c)},Fb(){},pb(){te.qb.forEach(i=>i())},mb:i=>new Promise(c=>{i.onmessage=k=>{k=k.data;var W=k.cmd;if(k.targetThread&&k.targetThread!=Rr()){var Z=te.Qa[k.targetThread];Z?Z.postMessage(k,k.transferList):we(`Internal error! Worker sent a message "${W}" to target pthread ${k.targetThread}, but that thread no longer exists!`)}else W==="checkMailbox"?Bt():W==="spawnThread"?Qt(k):W==="cleanupThread"?te.nb(te.Qa[k.thread]):W==="killThread"?(k=k.thread,W=te.Qa[k],delete te.Qa[k],Rt(W),gn(k),te.Za.splice(te.Za.indexOf(W),1),W.Xa=0):W==="cancelThread"?te.Qa[k.thread].postMessage({cmd:"cancel"}):W==="loaded"?(i.loaded=!0,C&&!i.Xa&&i.unref(),c(i)):W==="alert"?alert(`Thread ${k.threadId}: ${k.text}`):k.target==="setimmediate"?i.postMessage(k):W==="callHandler"?a[k.handler](...k.args):W&&we(`worker sent an unknown command ${W}`)},i.onerror=k=>{throw we(`worker sent an error! ${k.filename}:${k.lineno}: ${k.message}`),k},C&&(i.on("message",k=>i.onmessage({data:k})),i.on("error",k=>i.onerror(k)));var g=[],x=["onExit"],E;for(E of x)a.hasOwnProperty(E)&&g.push(E);i.postMessage({cmd:"load",handlers:g,urlOrBlob:a.mainScriptUrlOrBlob||e,wasmMemory:ne,wasmModule:ze})})};a.PThread=te;var _t=i=>{for(;0{var i=Rr(),c=s()[i+52>>>2>>>0];i=s()[i+56>>>2>>>0],_o(c,c-i),Br(c)};function Jt(i){if(v)return ke(1,0,i);Ht(i)}a.invokeEntryPoint=(i,c)=>{i=xo.apply(null,[i,c]),0>>2>>>0]=c},this.sb=function(c){s()[this.gb+8>>>2>>>0]=c},this.hb=function(c,g){this.rb(),this.tb(c),this.sb(g)},this.rb=function(){s()[this.gb+16>>>2>>>0]=0}}var xr=0,er=0;function Sr(i,c,g,x){return v?ke(2,1,i,c,g,x):Cr(i,c,g,x)}function Cr(i,c,g,x){if(i>>>=0,c>>>=0,g>>>=0,x>>>=0,typeof SharedArrayBuffer>"u")return we("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var E=[];return v&&E.length===0?Sr(i,c,g,x):(i={Hb:g,Xa:i,ub:x,Nb:E},v?(i.Pb="spawnThread",postMessage(i,E),0):Qt(i))}function Ir(i,c,g){return v?ke(3,1,i,c,g):0}function Ar(i,c){if(v)return ke(4,1,i,c)}var tr=i=>{for(var c=0,g=0;g=x?c++:2047>=x?c+=2:55296<=x&&57343>=x?(c+=4,++g):c+=3}return c},Tr=(i,c,g,x)=>{if(g>>>=0,!(0=W){var Z=i.charCodeAt(++k);W=65536+((W&1023)<<10)|Z&1023}if(127>=W){if(g>=x)break;c[g++>>>0]=W}else{if(2047>=W){if(g+1>=x)break;c[g++>>>0]=192|W>>6}else{if(65535>=W){if(g+2>=x)break;c[g++>>>0]=224|W>>12}else{if(g+3>=x)break;c[g++>>>0]=240|W>>18,c[g++>>>0]=128|W>>12&63}c[g++>>>0]=128|W>>6&63}c[g++>>>0]=128|W&63}}return c[g>>>0]=0,g-E},ee=(i,c,g)=>Tr(i,o(),c,g);function rr(i,c){if(v)return ke(5,1,i,c)}function Lt(i,c,g){if(v)return ke(6,1,i,c,g)}function nr(i,c,g){return v?ke(7,1,i,c,g):0}function or(i,c){if(v)return ke(8,1,i,c)}function ar(i,c,g){if(v)return ke(9,1,i,c,g)}function ir(i,c,g,x){if(v)return ke(10,1,i,c,g,x)}function sr(i,c,g,x){if(v)return ke(11,1,i,c,g,x)}function ur(i,c,g,x){if(v)return ke(12,1,i,c,g,x)}function dr(i){if(v)return ke(13,1,i)}function lr(i,c){if(v)return ke(14,1,i,c)}function cr(i,c,g){if(v)return ke(15,1,i,c,g)}var Er=()=>{if(!(0>>=0,typeof Atomics.Ob=="function"&&(Atomics.Ob(n(),i>>>2,i).value.then(Bt),i+=128,Atomics.store(n(),i>>>2,1))}a.__emscripten_thread_mailbox_await=It;var Bt=()=>{var i=Rr();if(i&&(It(i),!Q))try{vo(),Er()}catch(c){Ct(c)}};a.checkMailbox=Bt;var d=[],h=i=>i%4===0&&(i%100!==0||i%400===0),w=[0,31,60,91,121,152,182,213,244,274,305,335],S=[0,31,59,90,120,151,181,212,243,273,304,334];function P(i,c,g,x,E,k,W,Z){return v?ke(16,1,i,c,g,x,E,k,W,Z):-52}function N(i,c,g,x,E,k,W){if(v)return ke(17,1,i,c,g,x,E,k,W)}var K=i=>{var c=tr(i)+1,g=hn(c);return g&&ee(i,g,c),g},X=[],ae=(i,c)=>{X.length=0;for(var g;g=o()[i++>>>0];){var x=g!=105;x&=g!=112,c+=x&&c%8?4:0,X.push(g==112?s()[c>>>2>>>0]:g==105?n()[c>>>2>>>0]:l()[c>>>3>>>0]),c+=x?8:4}return X},de={},fe=()=>{if(!Oe){var i={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",_:_||"./this.program"},c;for(c in de)de[c]===void 0?delete i[c]:i[c]=de[c];var g=[];for(c in i)g.push(`${c}=${i[c]}`);Oe=g}return Oe},Oe;function Re(i,c){if(v)return ke(18,1,i,c);i>>>=0,c>>>=0;var g=0;return fe().forEach((x,E)=>{var k=c+g;for(E=s()[i+4*E>>>2>>>0]=k,k=0;k>>0>>>0]=x.charCodeAt(k);r()[E>>>0>>>0]=0,g+=x.length+1}),0}function O(i,c){if(v)return ke(19,1,i,c);i>>>=0,c>>>=0;var g=fe();s()[i>>>2>>>0]=g.length;var x=0;return g.forEach(E=>x+=E.length+1),s()[c>>>2>>>0]=x,0}function oe(i){return v?ke(20,1,i):52}function Ce(i,c,g,x){return v?ke(21,1,i,c,g,x):52}function ct(i,c,g,x,E){return v?ke(22,1,i,c,g,x,E):70}var Pr=[null,[],[]];function uo(i,c,g,x){if(v)return ke(23,1,i,c,g,x);c>>>=0,g>>>=0,x>>>=0;for(var E=0,k=0;k>>2>>>0],Z=s()[c+4>>>2>>>0];c+=8;for(var ge=0;ge>>0],ve=Pr[i];le===0||le===10?((i===1?Ie:we)(Gt(ve,0)),ve.length=0):ve.push(le)}E+=Z}return s()[x>>>2>>>0]=E,0}var lo=[31,29,31,30,31,30,31,31,30,31,30,31],co=[31,28,31,30,31,30,31,31,30,31,30,31];function Zu(i){var c=Array(tr(i)+1);return Tr(i,c,0,c.length),c}var Qu=(i,c)=>{r().set(i,c>>>0)};function po(i,c,g,x){function E(B,ce,Te){for(B=typeof B=="number"?B.toString():B||"";B.lengthEo?-1:0Dt-B.getDate())ce-=Dt-B.getDate()+1,B.setDate(1),11>Te?B.setMonth(Te+1):(B.setMonth(0),B.setFullYear(B.getFullYear()+1));else{B.setDate(B.getDate()+ce);break}}return Te=new Date(B.getFullYear()+1,0,4),ce=Z(new Date(B.getFullYear(),0,4)),Te=Z(Te),0>=W(ce,B)?0>=W(Te,B)?B.getFullYear()+1:B.getFullYear():B.getFullYear()-1}i>>>=0,c>>>=0,g>>>=0,x>>>=0;var le=s()[x+40>>>2>>>0];x={Lb:n()[x>>>2>>>0],Kb:n()[x+4>>>2>>>0],eb:n()[x+8>>>2>>>0],jb:n()[x+12>>>2>>>0],fb:n()[x+16>>>2>>>0],ab:n()[x+20>>>2>>>0],Wa:n()[x+24>>>2>>>0],$a:n()[x+28>>>2>>>0],Rb:n()[x+32>>>2>>>0],Jb:n()[x+36>>>2>>>0],Mb:le?Ke(le):""},g=Ke(g),le={"%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"};for(var ve in le)g=g.replace(new RegExp(ve,"g"),le[ve]);var Ue="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ve="January February March April May June July August September October November December".split(" ");le={"%a":B=>Ue[B.Wa].substring(0,3),"%A":B=>Ue[B.Wa],"%b":B=>Ve[B.fb].substring(0,3),"%B":B=>Ve[B.fb],"%C":B=>k((B.ab+1900)/100|0,2),"%d":B=>k(B.jb,2),"%e":B=>E(B.jb,2," "),"%g":B=>ge(B).toString().substring(2),"%G":B=>ge(B),"%H":B=>k(B.eb,2),"%I":B=>(B=B.eb,B==0?B=12:12{for(var ce=0,Te=0;Te<=B.fb-1;ce+=(h(B.ab+1900)?lo:co)[Te++]);return k(B.jb+ce,3)},"%m":B=>k(B.fb+1,2),"%M":B=>k(B.Kb,2),"%n":()=>`\n`,"%p":B=>0<=B.eb&&12>B.eb?"AM":"PM","%S":B=>k(B.Lb,2),"%t":()=>"\t","%u":B=>B.Wa||7,"%U":B=>k(Math.floor((B.$a+7-B.Wa)/7),2),"%V":B=>{var ce=Math.floor((B.$a+7-(B.Wa+6)%7)/7);if(2>=(B.Wa+371-B.$a-2)%7&&ce++,ce)ce==53&&(Te=(B.Wa+371-B.$a)%7,Te==4||Te==3&&h(B.ab)||(ce=1));else{ce=52;var Te=(B.Wa+7-B.$a-1)%7;(Te==4||Te==5&&h(B.ab%400-1))&&ce++}return k(ce,2)},"%w":B=>B.Wa,"%W":B=>k(Math.floor((B.$a+7-(B.Wa+6)%7)/7),2),"%y":B=>(B.ab+1900).toString().substring(2),"%Y":B=>B.ab+1900,"%z":B=>{B=B.Jb;var ce=0<=B;return B=Math.abs(B)/60,(ce?"+":"-")+("0000"+(B/60*100+B%60)).slice(-4)},"%Z":B=>B.Mb,"%%":()=>"%"},g=g.replace(/%%/g,"\\0\\0");for(ve in le)g.includes(ve)&&(g=g.replace(new RegExp(ve,"g"),le[ve](x)));return g=g.replace(/\\0\\0/g,"%"),ve=Zu(g),ve.length>c?0:(Qu(ve,i),ve.length-1)}var Or=i=>{try{i()}catch(c){Je(c)}};function Xu(){var i=Y,c={};for(let[g,x]of Object.entries(i))c[g]=typeof x=="function"?function(){kr.push(g);try{return x.apply(null,arguments)}finally{Q||(kr.pop(),pt&&At===1&&kr.length===0&&(At=0,at+=1,Or(Co),typeof Fibers<"u"&&Fibers.Sb()))}}:x;return c}var At=0,pt=null,mo=0,kr=[],fo={},ho={},Ju=0,fn=null,ed=[];function td(){return new Promise((i,c)=>{fn={resolve:i,reject:c}})}function rd(){var i=hn(65548),c=i+12;s()[i>>>2>>>0]=c,s()[i+4>>>2>>>0]=c+65536,c=kr[0];var g=fo[c];return g===void 0&&(g=Ju++,fo[c]=g,ho[g]=c),c=g,n()[i+8>>>2>>>0]=c,i}function nd(){var i=n()[pt+8>>>2>>>0];return i=Y[ho[i]],--at,i()}function od(i){if(!Q){if(At===0){var c=!1,g=!1;i((x=0)=>{if(!Q&&(mo=x,c=!0,g)){At=2,Or(()=>Io(pt)),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.resume(),x=!1;try{var E=nd()}catch(Z){E=Z,x=!0}var k=!1;if(!pt){var W=fn;W&&(fn=null,(x?W.reject:W.resolve)(E),k=!0)}if(x&&!k)throw E}}),g=!0,c||(At=1,pt=rd(),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.pause(),Or(()=>So(pt)))}else At===2?(At=0,Or(Ao),yo(pt),pt=null,ed.forEach(x=>{if(!Q)try{x(),Er()}catch(E){Ct(E)}})):Je(`invalid state: ${At}`);return mo}}function ad(i){return od(c=>{i().then(c)})}te.hb();var id=[$r,Jt,Sr,Ir,Ar,rr,Lt,nr,or,ar,ir,sr,ur,dr,lr,cr,P,N,Re,O,oe,Ce,ct,uo],sd={r:function(i,c,g){return ad(async()=>{await a.Ab(i,c,g)})},b:function(i,c,g){throw i>>>=0,new _r(i).hb(c>>>0,g>>>0),xr=i,er++,xr},N:function(i){bo(i>>>0,!I,1,!$,131072,!1),te.pb()},l:function(i){i>>>=0,v?postMessage({cmd:"cleanupThread",thread:i}):te.nb(te.Qa[i])},J:Cr,i:Ir,T:Ar,F:rr,H:Lt,U:nr,R:or,L:ar,Q:ir,p:sr,G:ur,D:dr,S:lr,E:cr,q:()=>1,B:function(i,c){i>>>=0,i==c>>>0?setTimeout(()=>Bt()):v?postMessage({targetThread:i,cmd:"checkMailbox"}):(i=te.Qa[i])&&i.postMessage({cmd:"checkMailbox"})},K:function(i,c,g,x){c>>>=0,d.length=g,x=x>>>0>>>3;for(var E=0;E>>0];return i=0>i?Nt[-i-1]:id[i],te.vb=c,c=i.apply(null,d),te.vb=0,c},M:It,W:function(i){C&&te.Qa[i>>>0].ref()},u:function(i,c,g){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,g>>>=0,i=new Date(1e3*i),n()[g>>>2>>>0]=i.getUTCSeconds(),n()[g+4>>>2>>>0]=i.getUTCMinutes(),n()[g+8>>>2>>>0]=i.getUTCHours(),n()[g+12>>>2>>>0]=i.getUTCDate(),n()[g+16>>>2>>>0]=i.getUTCMonth(),n()[g+20>>>2>>>0]=i.getUTCFullYear()-1900,n()[g+24>>>2>>>0]=i.getUTCDay(),i=(i.getTime()-Date.UTC(i.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,n()[g+28>>>2>>>0]=i},v:function(i,c,g){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,g>>>=0,i=new Date(1e3*i),n()[g>>>2>>>0]=i.getSeconds(),n()[g+4>>>2>>>0]=i.getMinutes(),n()[g+8>>>2>>>0]=i.getHours(),n()[g+12>>>2>>>0]=i.getDate(),n()[g+16>>>2>>>0]=i.getMonth(),n()[g+20>>>2>>>0]=i.getFullYear()-1900,n()[g+24>>>2>>>0]=i.getDay(),c=(h(i.getFullYear())?w:S)[i.getMonth()]+i.getDate()-1|0,n()[g+28>>>2>>>0]=c,n()[g+36>>>2>>>0]=-(60*i.getTimezoneOffset()),c=new Date(i.getFullYear(),6,1).getTimezoneOffset();var x=new Date(i.getFullYear(),0,1).getTimezoneOffset();i=(c!=x&&i.getTimezoneOffset()==Math.min(x,c))|0,n()[g+32>>>2>>>0]=i},w:function(i){i>>>=0;var c=new Date(n()[i+20>>>2>>>0]+1900,n()[i+16>>>2>>>0],n()[i+12>>>2>>>0],n()[i+8>>>2>>>0],n()[i+4>>>2>>>0],n()[i>>>2>>>0],0),g=n()[i+32>>>2>>>0],x=c.getTimezoneOffset(),E=new Date(c.getFullYear(),6,1).getTimezoneOffset(),k=new Date(c.getFullYear(),0,1).getTimezoneOffset(),W=Math.min(k,E);return 0>g?n()[i+32>>>2>>>0]=+(E!=k&&W==x):0>>2>>>0]=c.getDay(),g=(h(c.getFullYear())?w:S)[c.getMonth()]+c.getDate()-1|0,n()[i+28>>>2>>>0]=g,n()[i>>>2>>>0]=c.getSeconds(),n()[i+4>>>2>>>0]=c.getMinutes(),n()[i+8>>>2>>>0]=c.getHours(),n()[i+12>>>2>>>0]=c.getDate(),n()[i+16>>>2>>>0]=c.getMonth(),n()[i+20>>>2>>>0]=c.getYear(),i=c.getTime(),isNaN(i)?(n()[go()>>>2>>>0]=61,i=-1):i/=1e3,$o(($t=i,1<=+Math.abs($t)?0<$t?+Math.floor($t/4294967296)>>>0:~~+Math.ceil(($t-+(~~$t>>>0))/4294967296)>>>0:0)),i>>>0},s:P,t:N,A:function(i,c,g){function x(le){return(le=le.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?le[1]:"GMT"}i>>>=0,c>>>=0,g>>>=0;var E=new Date().getFullYear(),k=new Date(E,0,1),W=new Date(E,6,1);E=k.getTimezoneOffset();var Z=W.getTimezoneOffset(),ge=Math.max(E,Z);s()[i>>>2>>>0]=60*ge,n()[c>>>2>>>0]=+(E!=Z),i=x(k),c=x(W),i=K(i),c=K(c),Z>>2>>>0]=i,s()[g+4>>>2>>>0]=c):(s()[g>>>2>>>0]=c,s()[g+4>>>2>>>0]=i)},d:()=>{Je("")},c:function(i,c,g){return i>>>=0,c=ae(c>>>0,g>>>0),Nt[i].apply(null,c)},k:function(i,c,g){return i>>>=0,c=ae(c>>>0,g>>>0),Nt[i].apply(null,c)},m:()=>{},j:()=>Date.now(),V:()=>{throw at+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>C?(zo(),Ft(Mo)).cpus().length:navigator.hardwareConcurrency,y:function(i){i>>>=0;var c=o().length;if(i<=c||4294901760=g;g*=2){var x=c*(1+.2/g);x=Math.min(x,i+100663296);var E=Math;x=Math.max(i,x);e:{E=(E.min.call(E,4294901760,x+(65536-x%65536)%65536)-ne.buffer.byteLength+65535)/65536;try{ne.grow(E),G();var k=1;break e}catch{}k=void 0}if(k)return!0}return!1},O:Re,P:O,I:Ht,h:oe,o:Ce,x:ct,n:uo,a:ne||a.wasmMemory,z:po,e:function(i,c,g,x){return po(i>>>0,c>>>0,g>>>0,x>>>0)}},Y=function(){function i(g,x){return Y=g.exports,Y=Xu(),Y=ud(),te.qb.push(Y.Da),Qe.unshift(Y.X),ze=x,Fe(),Y}var c={a:sd};if(Le++,a.instantiateWasm)try{return a.instantiateWasm(c,i)}catch(g){we(`Module.instantiateWasm callback failed with error: ${g}`),m(g)}return St(c,function(g){i(g.instance,g.module)}).catch(m),{}}();a._OrtInit=(i,c)=>(a._OrtInit=Y.Y)(i,c),a._OrtGetLastError=(i,c)=>(a._OrtGetLastError=Y.Z)(i,c),a._OrtCreateSessionOptions=(i,c,g,x,E,k,W,Z,ge,le)=>(a._OrtCreateSessionOptions=Y._)(i,c,g,x,E,k,W,Z,ge,le),a._OrtAppendExecutionProvider=(i,c)=>(a._OrtAppendExecutionProvider=Y.$)(i,c),a._OrtAddFreeDimensionOverride=(i,c,g)=>(a._OrtAddFreeDimensionOverride=Y.aa)(i,c,g),a._OrtAddSessionConfigEntry=(i,c,g)=>(a._OrtAddSessionConfigEntry=Y.ba)(i,c,g),a._OrtReleaseSessionOptions=i=>(a._OrtReleaseSessionOptions=Y.ca)(i),a._OrtCreateSession=(i,c,g)=>(a._OrtCreateSession=Y.da)(i,c,g),a._OrtReleaseSession=i=>(a._OrtReleaseSession=Y.ea)(i),a._OrtGetInputOutputCount=(i,c,g)=>(a._OrtGetInputOutputCount=Y.fa)(i,c,g),a._OrtGetInputName=(i,c)=>(a._OrtGetInputName=Y.ga)(i,c),a._OrtGetOutputName=(i,c)=>(a._OrtGetOutputName=Y.ha)(i,c),a._OrtFree=i=>(a._OrtFree=Y.ia)(i),a._OrtCreateTensor=(i,c,g,x,E,k)=>(a._OrtCreateTensor=Y.ja)(i,c,g,x,E,k),a._OrtGetTensorData=(i,c,g,x,E)=>(a._OrtGetTensorData=Y.ka)(i,c,g,x,E),a._OrtReleaseTensor=i=>(a._OrtReleaseTensor=Y.la)(i),a._OrtCreateRunOptions=(i,c,g,x)=>(a._OrtCreateRunOptions=Y.ma)(i,c,g,x),a._OrtAddRunConfigEntry=(i,c,g)=>(a._OrtAddRunConfigEntry=Y.na)(i,c,g),a._OrtReleaseRunOptions=i=>(a._OrtReleaseRunOptions=Y.oa)(i),a._OrtCreateBinding=i=>(a._OrtCreateBinding=Y.pa)(i),a._OrtBindInput=(i,c,g)=>(a._OrtBindInput=Y.qa)(i,c,g),a._OrtBindOutput=(i,c,g,x)=>(a._OrtBindOutput=Y.ra)(i,c,g,x),a._OrtClearBoundOutputs=i=>(a._OrtClearBoundOutputs=Y.sa)(i),a._OrtReleaseBinding=i=>(a._OrtReleaseBinding=Y.ta)(i),a._OrtRunWithBinding=(i,c,g,x,E)=>(a._OrtRunWithBinding=Y.ua)(i,c,g,x,E),a._OrtRun=(i,c,g,x,E,k,W,Z)=>(a._OrtRun=Y.va)(i,c,g,x,E,k,W,Z),a._OrtEndProfiling=i=>(a._OrtEndProfiling=Y.wa)(i),a._JsepOutput=(i,c,g)=>(a._JsepOutput=Y.xa)(i,c,g),a._JsepGetNodeName=i=>(a._JsepGetNodeName=Y.ya)(i);var go=()=>(go=Y.za)(),Rr=a._pthread_self=()=>(Rr=a._pthread_self=Y.Aa)(),hn=a._malloc=i=>(hn=a._malloc=Y.Ba)(i),yo=a._free=i=>(yo=a._free=Y.Ca)(i);a.__emscripten_tls_init=()=>(a.__emscripten_tls_init=Y.Da)();var bo=a.__emscripten_thread_init=(i,c,g,x,E,k)=>(bo=a.__emscripten_thread_init=Y.Fa)(i,c,g,x,E,k);a.__emscripten_thread_crashed=()=>(a.__emscripten_thread_crashed=Y.Ga)();var wo=(i,c,g,x)=>(wo=Y.Ha)(i,c,g,x),gn=i=>(gn=Y.Ia)(i),yn=a.__emscripten_thread_exit=i=>(yn=a.__emscripten_thread_exit=Y.Ja)(i),vo=()=>(vo=Y.Ka)(),$o=i=>($o=Y.La)(i),_o=(i,c)=>(_o=Y.Ma)(i,c),bn=()=>(bn=Y.Na)(),Br=i=>(Br=Y.Oa)(i),wn=i=>(wn=Y.Pa)(i),xo=a.dynCall_ii=(i,c)=>(xo=a.dynCall_ii=Y.Ra)(i,c),So=i=>(So=Y.Sa)(i),Co=()=>(Co=Y.Ta)(),Io=i=>(Io=Y.Ua)(i),Ao=()=>(Ao=Y.Va)();a.___start_em_js=945539,a.___stop_em_js=945700;function ud(){var i=Y;i=Object.assign({},i);var c=x=>()=>x()>>>0,g=x=>E=>x(E)>>>0;return i.za=c(i.za),i.Aa=c(i.Aa),i.Ba=g(i.Ba),i.emscripten_main_runtime_thread_id=c(i.emscripten_main_runtime_thread_id),i.Na=c(i.Na),i.Pa=g(i.Pa),i}a.wasmMemory=ne,a.stackAlloc=wn,a.stackSave=bn,a.stackRestore=Br,a.keepRuntimeAlive=()=>0Uo)});var Wo=pr((mp,yd)=>{yd.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\\n\'});var En,Tt,fr,Ur,hr,Ko,Pn,ie=q(()=>{"use strict";En=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;default:throw new Error(`unsupported data type: ${e}`)}},Tt=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";default:throw new Error(`unsupported data type: ${e}`)}},fr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Ur=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}`)}},hr=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}`)}},Ko=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",Pn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}});var Vr=q(()=>{"use strict"});var Yo=q(()=>{"use strict";Vr()});var Zo,Qo=q(()=>{"use strict";Zo="1.17.3"});var Xo,rt,On=q(()=>{"use strict";Qo();Xo="warning",rt={wasm:{},webgl:{},webgpu:{},versions:{common:Zo},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}`);Xo=e}},get logLevel(){return Xo}};Object.defineProperty(rt,"logLevel",{enumerable:!0})});var qt,Jo=q(()=>{"use strict";On();qt=rt});var ea=q(()=>{"use strict"});var ta=q(()=>{"use strict";Nr()});var na=q(()=>{"use strict"});var oa=q(()=>{"use strict";Nr()});var Nr=q(()=>{"use strict";ea();ta();na();oa()});var Wr=q(()=>{"use strict";Nr()});var kn,aa,Mt,Et,Rn=q(()=>{"use strict";On();kn=(e,t)=>{(typeof rt.trace>"u"?!rt.wasm.trace:!rt.trace)||console.timeStamp(`${e}::ORT::${t}`)},aa=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let n=0;n{(typeof rt.trace>"u"?!rt.wasm.trace:!rt.trace)||aa("BEGIN",e)},Et=e=>{(typeof rt.trace>"u"?!rt.wasm.trace:!rt.trace)||aa("END",e)}});var ia=q(()=>{"use strict";Vr();Wr();Rn()});var sa=q(()=>{"use strict";ia()});var ua=q(()=>{"use strict"});var da=q(()=>{"use strict"});var la=q(()=>{"use strict"});var ca=q(()=>{"use strict"});var pa=q(()=>{"use strict";Vr();Wr()});var ma=q(()=>{"use strict";pa()});var Kt=q(()=>{"use strict";Yo();Jo();sa();Wr();ua();da();Rn();la();ca();ma()});var Td,Ed,fa,ha,ga,Pd,De,Pt=q(()=>{"use strict";ie();Td=["V","I","W","E","F"],Ed=(e,t)=>{console.log(`[${Td[e]},${new Date().toISOString()}]${t}`)},ga=(e,t)=>{fa=e,ha=t},Pd=(e,t)=>{let r=hr(e),o=hr(fa);r>=o&&Ed(r,typeof t=="function"?t():t)},De=(...e)=>{ha&&Pd(...e)}});var ya,ba=q(()=>{"use strict";ie();ya=(e,t)=>new(Ur(t))(e)});var Gr=q(()=>{"use strict"});var Hr,Od,wa,Dn,Bn,$a,_a=q(()=>{"use strict";Pt();Gr();Hr=e=>Math.ceil(e/16)*16,Od=1,wa=()=>Od++,Dn=async(e,t,r,o)=>{let n=Hr(r),s=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,s,0,n),e.flush(),await s.mapAsync(GPUMapMode.READ);let l=s.getMappedRange();if(o){let a=o();return a.set(new Uint8Array(l,0,r)),a}else return new Uint8Array(l.slice(0,r))}finally{s.destroy()}},Bn=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map}upload(t,r){let o=r.buffer,n=r.byteOffset,s=r.byteLength,u=Hr(s),l=this.storageCache.get(t);if(!l)throw new Error("gpu data for uploading does not exist");if(l.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${s}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:u,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=a.getMappedRange();new Uint8Array(p).set(new Uint8Array(o,n,s)),a.unmap();let m=this.backend.getCommandEncoder();this.backend.endComputePass(),m.copyBufferToBuffer(a,0,l.gpuData.buffer,0,u),De("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(a)}memcpy(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(r);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(o.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=Hr(o.originalSize),u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(t,r,o){let n;if(o){if(n=this.externalBuffers.get(o),n===void 0)throw new Error("previous buffer is not registered");if(t===o)return De("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => 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.\n Please use the previous external buffer!`);this.externalBuffers.delete(o)}else n=wa();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,n),De("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, registered.`),n}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),De("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Hr(t),n,s=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,u=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||u){let a=s?this.freeBuffers:this.freeUniformBuffers,p=a.get(o);p||(p=[],a.set(o,p)),p.length>0?n=p.pop():n=this.backend.device.createBuffer({size:o,usage:r})}else n=this.backend.device.createBuffer({size:o,usage:r});let l={id:wa(),type:0,buffer:n};return this.storageCache.set(l.id,{gpuData:l,originalSize:t}),De("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=this.storageCache.get(t);if(!r)throw new Error("releasing data does not exist");return De("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("data does not exist");await Dn(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending)(t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(t.size).push(t):(t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(t.size).push(t):t.destroy();this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(o=>{o.destroy()}),this.capturedPendingBuffers.delete(t))}},$a=(...e)=>new Bn(...e)});var Mn,$e,je=q(()=>{"use strict";Mn=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},$e=e=>new Mn(e)});var zn,mt,z,zt,Lr,Fr,qr,_e=q(()=>{"use strict";zn=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},mt=class{static calcShape(t,r,o=!1){let n=t.length,s=r.length;if(n===0)return r;if(s===0)return t;let u=Math.max(t.length,r.length),l=new Array(u);if(o){if(n<2||s<2)return;let a=zn.calcMatMulShape([t[n-2],t[n-1]],[r[s-2],r[s-1]]);if(a===void 0)return;[l[u-2],l[u-1]]=a}for(let a=o?3:1;a<=u;a++){let p=n-a<0?1:t[n-a],m=s-a<0?1:r[s-a];if(p!==m&&p>1&&m>1)return;let f=Math.max(p,m);if(p&&m)l[u-a]=Math.max(p,m);else{if(f>1)return;l[u-a]=0}}return l}static isValidBroadcast(t,r){let o=t.length,n=r.length;if(o>n)return!1;for(let s=1;s<=o;s++)if(t[o-s]!==1&&t[o-s]!==r[n-s])return!1;return!0}},z=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let o=t.length;if(o===0)return[];let n=new Array(o),s=o-1;for(;s>=0;){if(t[s]%r===0){n[s]=t[s]/r;break}if(r%t[s]!==0)throw new Error("cannot convert shape");n[s]=1,r/=t[s],s--}for(s--;s>=0;s--)n[s]=t[s];return n}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 e.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 e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,o){let n=1;for(let s=r;s=0;--n)o[n]=o[n+1]*t[n+1];return o}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(o=>this.normalizeAxis(o,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(o=>t[o]):t.slice().reverse()}static padShape(t,r){let o=t.length;return t.map((n,s)=>n+r[s]+r[s+o])}static areEqual(t,r){return t.length!==r.length?!1:t.every((o,n)=>o===r[n])}},zt=class e{static adjustPoolAttributes(t,r,o,n,s,u){if(!t&&o.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 l=0;l=o.length?o.push(r[l+2]):o[l]=r[l+2];for(let l=0;l=o[l]||u[l+o.length]>=o[l])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,o,n,s,u,l){if(l){if(s.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(n.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let a=0;a{"use strict";ie();_e();Kr=64,Vn=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},Pe=(e,t=1)=>{let r=Vn(e,t);return typeof r=="string"?r:r[0]},et=(e,t=1)=>{let r=Vn(e,t);return typeof r=="string"?r:r[1]},j=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:z.computeStrides(r)})}),t},Me=e=>e%4===0?4:e%2===0?2:1,Ye=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,st=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}f(${r})`,tt=(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,re=(e,t,r,o)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?o==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:o==="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,Nn=(e,t,r,o,n)=>{let s=typeof r=="number",u=s?r:r.length,l=[...new Array(u).keys()],a=u<2?"u32":u<=4?`vec${u}`:`array`,p=Vn(t,n),m=typeof p=="string"?p:p[1],f=typeof p=="string"?p:p[0],b={indices:a,value:m,storage:f,tensor:t},_=G=>typeof G=="string"?G:`${G}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},$=s?"uniforms.":"",I=`${$}${e}_shape`,C=`${$}${e}_strides`,v="";for(let G=0;G ${b.indices} {\n var indices: ${b.indices};\n var current = offset;\n ${v}\n return indices;\n }`,T=G=>(y.offsetToIndices=!0,u<2?G:`o2i_${e}(${G})`),D=[];if(u>=2)for(let G=u-1;G>=0;G--)D.push(`${re(C,G,u)} * (indices[${G}])`);let U=u<2?"":`\n fn i2o_${e}(indices: ${b.indices}) -> u32 {\n return ${D.join("+")};\n }`,V=G=>(y.indicesToOffset=!0,u<2?G:`i2o_${e}(${G})`),H=(...G)=>u===0?"0u":`${b.indices}(${G.map(_).join(",")})`,R=(G,J)=>u<2?`${G}`:`${re(G,J,u)}`,L=(G,J,Se)=>u<2?`${G}=${Se};`:`${re(G,J,u)}=${Se};`,pe={},Ie=(G,J)=>{y.broadcastedIndicesToOffset=!0;let Se=`${J.name}broadcastedIndicesTo${e}Offset`;if(Se in pe)return`${Se}(${G})`;let Qe=[];for(let Xe=u-1;Xe>=0;Xe--){let Le=J.indicesGet("outputIndices",Xe+J.rank-u);Qe.push(`${R(C,Xe)} * (${Le} % ${R(I,Xe)})`)}return pe[Se]=`fn ${Se}(outputIndices: ${J.type.indices}) -> u32 {\n return ${Qe.length>0?Qe.join("+"):"0u"};\n }`,`${Se}(${G})`},we=(G,J)=>(()=>{if(b.storage===b.value)return`${e}[${G}]=${J};`;if(b.storage==="vec2"&&b.value==="i32")return`${e}[${G}]=vec2(u32(${J}), select(0u, 0xFFFFFFFFu, ${J} < 0));`;if(b.storage==="vec2"&&b.value==="u32")return`${e}[${G}]=vec2(u32(${J}), 0u);`;if(b.storage==="u32"&&b.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${J}));`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),ne=G=>(()=>{if(b.storage===b.value)return`${e}[${G}]`;if(b.storage==="vec2"&&b.value==="i32")return`i32(${e}[${G}].x)`;if(b.storage==="vec2"&&b.value==="u32")return`u32(${e}[${G}].x)`;if(b.storage==="u32"&&b.value==="vec4")return`vec4(bool(${e}[${G}] & 0xFFu), bool(${e}[${G}] & 0xFF00u), bool(${e}[${G}] & 0xFF0000u), bool(${e}[${G}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),ze=u<2?"":`\n fn get_${e}ByIndices(indices: ${b.indices}) -> ${m} {\n return ${ne(`i2o_${e}(indices)`)};\n }`,Q=u<2?"":(()=>{let G=l.map(Se=>`d${Se}: u32`).join(", "),J=l.map(Se=>`d${Se}`).join(", ");return`\n fn get_${e}(${G}) -> ${m} {\n return get_${e}ByIndices(${H(J)});\n }`})(),xe=(...G)=>{if(G.length!==u)throw new Error(`indices length must be ${u}`);let J=G.map(_).join(",");return u===0?ne("0u"):u===1?ne(J[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${J})`)},me=G=>u<2?ne(G):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${G})`),ue=u<2?"":`\n fn set_${e}ByIndices(indices: ${b.indices}, value: ${m}) {\n ${we(`i2o_${e}(indices)`,"value")}\n }`,se=u<2?"":(()=>{let G=l.map(Se=>`d${Se}: u32`).join(", "),J=l.map(Se=>`d${Se}`).join(", ");return`\n fn set_${e}(${G}, value: ${m}) {\n set_${e}ByIndices(${H(J)}, value);\n }`})();return{impl:()=>{let G=[],J=!1;return y.offsetToIndices&&(G.push(A),J=!0),y.indicesToOffset&&(G.push(U),J=!0),y.broadcastedIndicesToOffset&&(Object.values(pe).forEach(Se=>G.push(Se)),J=!0),y.set&&(G.push(se),J=!0),y.setByIndices&&(G.push(ue),J=!0),y.get&&(G.push(Q),J=!0),y.getByIndices&&(G.push(ze),J=!0),!s&&J&&G.unshift(`const ${I} = ${b.indices}(${r.join(",")});`,`const ${C} = ${b.indices}(${z.computeStrides(r).join(",")});`),G.join(`\n`)},type:b,offsetToIndices:T,indicesToOffset:V,broadcastedIndicesToOffset:Ie,indices:H,indicesGet:R,indicesSet:L,set:(...G)=>{if(G.length!==u+1)throw new Error(`indices length must be ${u}`);let J=G[u];if(typeof J!="string")throw new Error("value must be string");let Se=G.slice(0,u).map(_).join(",");return u===0?we("0u",J):u===1?we(Se[0],J):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${Se}, ${J})`)},setByOffset:we,setByIndices:(G,J)=>u<2?we(G,J):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${J});`),get:xe,getByOffset:ne,getByIndices:me,usage:o,name:e,strides:C,shape:I,rank:u}},M=(e,t,r,o=1)=>Nn(e,t,r,"input",o),F=(e,t,r,o=1)=>Nn(e,t,r,"output",o),jr=(e,t,r,o=1)=>Nn(e,t,r,"internal",o),Un=class{constructor(t){this.normalizedDispatchGroup=t;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=Kr){let r=typeof t=="number"?t:t[0],o=typeof t=="number"?1:t[1],n=typeof t=="number"?1:t[2],s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,u=s?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=s?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r*o*n}u + local_idx;`;return`@compute @workgroup_size(${r}, ${o}, ${n})\n fn main(${u}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let o=t.usage==="input"?"read":"read_write",n=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${n}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,o=1){return this.uniforms.push({name:t,type:r,length:o}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:o,length:n}of this.uniforms)if(n&&n>4)o==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(n/8)}>`):t.push(`${r}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?o:`vec${n}<${o}>`;t.push(`${r}:${s}`)}return`\n struct Uniforms { ${t.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}},xa=e=>new Un(e),jt=(e,t)=>{let r=e.length,o=[];for(let n=0;n1&&u===1&&o.unshift(s)}return o}});var kd,Sa,Rd,Bd,ot,Ca,Ia,Yt=q(()=>{"use strict";ie();_e();je();be();kd=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Sa=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Rd=(e,t)=>z.sortBasedOnPerm(e,Sa(e.length,t)),Bd=(e,t,r,o)=>{let n=[];n.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let s=0;s{let r=e.dataType,o=e.dims.length,n=Sa(o,t),s=Rd(e.dims,n),u=F("output",r,s.length),l=M("a",r,o),a=p=>`\n ${p.registerUniform("output_size","u32").declareVariables(l,u)}\n\n ${Bd(n,o,l,u)}\n\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${u.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${u.setByOffset("global_idx",l.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:p=>{let m=z.size(s);return{outputs:[{dims:s,dataType:p[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...j(p[0].dims,s)]}},getShaderSource:a}},Ca=(e,t)=>{kd(e.inputs),e.compute(ot(e.inputs[0],t.perm))},Ia=e=>$e({perm:e.perm})});var Dd,Md,zd,Ud,Vd,Nd,Wd,Gd,Hd,Ld,ft,Aa,Ta,Ea,Pa,Oa,ka,Ra,Ba,Da,Ma,za=q(()=>{"use strict";ie();_e();be();Yr();Yt();Dd={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"},Md={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"},zd={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Ud={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Vd=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let s=0;se[s]);return[r,n]},Wd=(e,t)=>{let r=e.length+t.length,o=[],n=0;for(let s=0;s{for(let r=0;r{let r=[];if(!Gd(e,t)){for(let o=0;or.push(o))}return r},Ld=(e,t,r,o,n,s,u)=>{let l=r[0].dims,a=z.size(s),p=z.size(u),m=M("_A",r[0].dataType,l),f=F("output",n,s),b=32,_=`\n var aBestValues : array;\n `;return{name:e,shaderCache:t,getShaderSource:$=>`\n ${$.registerUniform("reduceSize","u32").declareVariables(m,f)}\n ${_}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${$.mainStart(b)}\n\n let outputIndex = global_idx / ${b};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${zd[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${b}) {\n let candidate = f32(${m.getByOffset("offset + k")});\n bestValue = ${Dd[o]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${b}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${Md[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${f.setByOffset("outputIndex",`${o==="mean"?`${f.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${f.type.storage}(${Ud[o]})`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:a},programUniforms:[{type:12,data:p}]})}},ft=(e,t,r,o)=>{let n=e.inputs.length===1?r:Wn(e.inputs,r),s=n.axes;s.length===0&&!n.noopWithEmptyAxes&&(s=e.inputs[0].dims.map((_,y)=>y));let u=z.normalizeAxes(s,e.inputs[0].dims.length),l=u,a=e.inputs[0],p=Hd(l,e.inputs[0].dims.length);p.length>0&&(a=e.compute(ot(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=Vd(l.length,a.dims.length));let[m,f]=Nd(a.dims,l),b=m;n.keepDims&&(b=Wd(m,u)),e.compute(Ld(t,{hint:n.cacheKey,inputDependencies:["type"]},[a],o,e.inputs[0].dataType,b,f),{inputs:[a]})},Aa=(e,t)=>{ft(e,"ReduceMeanShared",t,"mean")},Ta=(e,t)=>{ft(e,"ReduceL1Shared",t,"l1")},Ea=(e,t)=>{ft(e,"ReduceL2Shared",t,"l2")},Pa=(e,t)=>{ft(e,"ReduceLogSumExpShared",t,"logSumExp")},Oa=(e,t)=>{ft(e,"ReduceMaxShared",t,"max")},ka=(e,t)=>{ft(e,"ReduceMinShared",t,"min")},Ra=(e,t)=>{ft(e,"ReduceProdShared",t,"prod")},Ba=(e,t)=>{ft(e,"ReduceSumShared",t,"sum")},Da=(e,t)=>{ft(e,"ReduceSumSquareShared",t,"sumSquare")},Ma=(e,t)=>{ft(e,"ReduceLogSumShared",t,"logSum")}});var ht,Fd,Zr,Wn,gt,qd,Kd,jd,Yd,Zd,Qd,Xd,Jd,el,tl,yt,Ua,Va,Na,Wa,Ga,Ha,La,Fa,qa,Ka,Yr=q(()=>{"use strict";ie();_e();je();be();za();ht=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.")},Fd=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Zr=(e,t,r,o,n,s,u=!1,l=!1)=>{let a=[],p=r[0].dims,m=p.length,f=z.normalizeAxes(n,m),b=!l&&f.length===0;p.forEach((I,C)=>{b||f.indexOf(C)>=0?u&&a.push(1):a.push(I)});let _=a.length,y=z.size(a);return{name:e,shaderCache:t,getShaderSource:I=>{let C=[],v=M("_A",r[0].dataType,m),A=F("output",s,_),T=o(v,A,f),D=T[2];for(let U=0,V=0;U=0?(u&&V++,D=`for(var j${U}: u32 = 0; j${U} < ${p[U]}; j${U}++) {\n ${T[2].includes("last_index")?`let last_index = j${U};`:""}\n ${v.indicesSet("input_indices",U,`j${U}`)}\n ${D}\n }`):(C.push(`${v.indicesSet("input_indices",U,A.indicesGet("output_indices",V))};`),V++);return`\n\n ${I.registerUniform("output_size","u32").declareVariables(v,A)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${v.type.indices};\n let output_indices = ${A.offsetToIndices("global_idx")};\n\n ${C.join(`\n`)}\n ${T[0]} // init ops for reduce max/min\n ${T[1]}\n ${D}\n ${T[3]}\n ${T.length===4?A.setByOffset("global_idx","value"):T.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...j(p,a)]})}},Wn=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),$e({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},gt=(e,t,r,o)=>{let n=e.inputs,s=n.length===1?r:Wn(n,r);e.compute(Zr(t,{hint:s.cacheKey,inputDependencies:["rank"]},[n[0]],s.noopWithEmptyAxes&&s.axes.length===0?Fd:o,s.axes,n[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},qd=(e,t)=>{ht(e.inputs),gt(e,"ReduceLogSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Kd=(e,t)=>{ht(e.inputs),gt(e,"ReduceL1",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},jd=(e,t)=>{ht(e.inputs),gt(e,"ReduceL2",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Yd=(e,t)=>{ht(e.inputs),gt(e,"ReduceLogSumExp",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},Zd=(e,t)=>{ht(e.inputs),gt(e,"ReduceMax",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(o.indicesSet("input_indices",l,0));return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = max(value, ${o.getByIndices("input_indices")});`,""]})},Qd=(e,t)=>{ht(e.inputs),gt(e,"ReduceMean",t,(o,n,s)=>{let u=1;for(let l=0;l=0||s.length===0)&&(u*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${o.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${u});`]})},Xd=(e,t)=>{ht(e.inputs),gt(e,"ReduceMin",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = min(value, ${o.getByIndices("input_indices")});`,""]})},Jd=(e,t)=>{ht(e.inputs),gt(e,"ReduceProd",t,(o,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},el=(e,t)=>{ht(e.inputs),gt(e,"ReduceSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},tl=(e,t)=>{ht(e.inputs),gt(e,"ReduceSumSquare",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += t * t;`,""])},yt=(e,t,r)=>{if(t.length===0)return r;let o=1,n=1;for(let s=0;s1024},Ua=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qd(e,t):Aa(e,t)},Va=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Kd(e,t):Ta(e,t)},Na=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jd(e,t):Ea(e,t)},Wa=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yd(e,t):Pa(e,t)},Ga=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zd(e,t):Oa(e,t)},Ha=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xd(e,t):ka(e,t)},La=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Jd(e,t):Ra(e,t)},Fa=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?el(e,t):Ba(e,t)},qa=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?tl(e,t):Da(e,t)},Ka=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qd(e,t):Ma(e,t)}});var ja,Ya,Za,Gn,Qa=q(()=>{"use strict";ie();je();Yr();ja=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.")},Ya=(e,t)=>{ja(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(Zr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Za=(e,t)=>{ja(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(Zr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Gn=e=>$e(e)});var rl,nl,ol,al,Qr,il,Xa,Hn=q(()=>{"use strict";ie();Gr();be();rl=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5];if(u&&l)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error(\'Input "input" must have 3 dimensions\');let a=r.dims[0],p=r.dims[1],m=r.dims[2];if(n.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimensions\');if(o.dims.length!==2)throw new Error(\'Input "weights" is expected to have 2 dimensions\');if(o.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==o.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let f=n.dims[0]/3,b=f,_=b;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let A of t.qkvHiddenSizes)if(A%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");f=t.qkvHiddenSizes[0],b=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let y=p;if(f!==b)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==f+b+_)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let $=0;if(u){if(b!==_)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(u.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(u.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(u.dims[1]!==a)throw new Error(\'Input "past" second dimension must be batch_size\');if(u.dims[2]!==t.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(u.dims[4]!==b/t.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');t.pastPresentShareBuffer||($=u.dims[3])}let I=y+$,C=-1,v=0;if(s)throw new Error("Mask not supported");if(u)throw new Error("past is not supported");if(l)throw new Error("relativePositionBias is not supported");return{batchSize:a,sequenceLength:p,pastSequenceLength:$,kvSequenceLength:y,totalSequenceLength:I,maxSequenceLength:C,inputHiddenSize:m,hiddenSize:f,vHiddenSize:_,headSize:Math.floor(f/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},nl=(e,t,r,o)=>{let n=Me(o),s=64,u=o/n;u{let b=F("x",t.dataType,t.dims,n),_="thread_max_vector";n===2?_="max(thread_max_vector.x, thread_max_vector.y)":n===4&&(_="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let y=et(t.dataType),$=[{name:"d_inv",type:y},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return`\n var wgMax: array;\n var wgSum: array;\n ${f.registerUniforms($).declareVariables(b)}\n ${f.mainStart([s,1,1])}\n let localOffset = local_idx * uniforms.elements_per_wg;\n let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset;\n\n var thread_max_vector = ${Ye("f32",n,"-3.402823e+38f")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n thread_max_vector = max(${st(y,n,"x[offset + i]")}, thread_max_vector);\n }\n wgMax[local_idx] = ${_};\n workgroupBarrier();\n\n var maxValue = -3.402823e+38f;\n for (var i = 0u; i < ${s}; i++) {\n maxValue = max(wgMax[i], maxValue);\n }\n\n var sumVector = ${Ye("f32",n,"0")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n sumVector += exp(${st(y,n,"x[offset + i]")} - maxValue);\n }\n wgSum[local_idx] = ${tt("sumVector",n)};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${s}; i++) {\n sum += wgSum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n x[offset + i] = ${Ye(y,n,"uniforms.d_inv")};\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n let f32input = ${st(y,n,"x[offset + i]")};\n x[offset + i] = ${b.type.value}(exp(f32input - maxValue) / sum);\n }\n }\n }`};e.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${p};${n}`},getShaderSource:m,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:a})},{inputs:[t],outputs:[]})},ol=(e,t,r,o,n,s)=>{let u=[n.batchSize,n.numHeads,n.sequenceLength,n.kvSequenceLength+n.pastSequenceLength],l=s.scale===0?1/Math.sqrt(n.headSize):s.scale,a=Me(n.headSize),p=n.headSize/a,m=12,f={x:Math.ceil(n.totalSequenceLength/m),y:Math.ceil(n.sequenceLength/m),z:n.batchSize*n.numHeads},b=[{type:12,data:n.sequenceLength},{type:12,data:p},{type:12,data:n.totalSequenceLength},{type:12,data:n.kvSequenceLength},{type:t.dataType,data:l}],_=[t,r],y=I=>{let C=M("q",t.dataType,t.dims,a),v=M("key",r.dataType,r.dims,a),A=F("output",t.dataType,u),T=Pe(t.dataType),D=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:T}];return`\n const beta: ${T} = 1.0;\n const TILE_SIZE = ${m}u;\n\n var tileQ: array<${C.type.storage}, ${m*m}>;\n var tileK: array<${C.type.storage}, ${m*m}>;\n ${I.registerUniforms(D).declareVariables(C,v,A)}\n ${I.mainStart([m,m,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let lm = m + local_id.y;\n let ln = n + local_id.x;\n\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${Ye(T,a)};\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m + local_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:f,programUniforms:b}),getShaderSource:y},{inputs:_,outputs:[-1]})[0];return nl(e,$,n.batchSize*n.numHeads*n.sequenceLength,n.totalSequenceLength),$},al=(e,t,r,o)=>{let n=[o.batchSize,o.sequenceLength,o.vHiddenSize],s=12,u={x:Math.ceil(o.vHeadSize/s),y:Math.ceil(o.sequenceLength/s),z:o.batchSize*o.numHeads},l=[{type:12,data:o.sequenceLength},{type:12,data:o.totalSequenceLength},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.vHiddenSize}],a=p=>{let m=M("probs",t.dataType,t.dims),f=M("v",r.dataType,r.dims),b=F("output",t.dataType,n),_=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return`\n const TILE_SIZE = ${s}u;\n var tileQ: array<${m.type.value}, ${s*s}>;\n var tileK: array<${m.type.value}, ${s*s}>;\n ${p.registerUniforms(_).declareVariables(m,f,b)}\n ${p.mainStart([s,s,1])}\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${m.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:n,dataType:t.dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:l}),getShaderSource:a},{inputs:[t,r],outputs:[0]})[0]},Qr=(e,t,r,o,n,s,u,l,a,p,m)=>{let f=ol(e,t,r,a,p,m);al(e,f,o,p)},il=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],o=t.sequenceLength,n=t.inputHiddenSize,s=t.headSize,u=12,l={x:Math.ceil(t.headSize/u),y:Math.ceil(t.sequenceLength/u),z:t.batchSize*t.numHeads},a=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:o},{type:12,data:n},{type:12,data:s},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=f=>{let b=F("output_q",a[0].dataType,r),_=F("output_k",a[0].dataType,r),y=F("output_v",a[0].dataType,r),$=M("input",a[0].dataType,a[0].dims),I=M("weight",a[1].dataType,a[1].dims),C=M("bias",a[2].dataType,a[2].dims),v=$.type.storage,A=[{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`\n const TILE_SIZE = ${u}u;\n var tileInput: array<${v}, ${u*u}>;\n var tileWeightQ: array<${v}, ${u*u}>;\n var tileWeightK: array<${v}, ${u*u}>;\n var tileWeightV: array<${v}, ${u*u}>;\n ${f.registerUniforms(A).declareVariables($,I,C,b,_,y)}\n ${f.mainStart([u,u,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${v}(0);\n var valueK = ${v}(0);\n var valueV = ${v}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n 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:l,programUniforms:p}),getShaderSource:m},{inputs:a,outputs:[-1,-1,-1]})},Xa=(e,t)=>{let r=rl(e.inputs,t),[o,n,s]=il(e,r);return Qr(e,o,n,s,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var sl,ul,dl,Ja,ei=q(()=>{"use strict";Kt();ie();_e();je();be();sl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(o,n,s)=>{let u=n.length;if(u!==o.length)throw new Error(`${s}: num dimensions != ${u}`);n.forEach((l,a)=>{if(l!==o[a])throw new Error(`${s}: dim[${a}] do not match`)})};if(e[0].dims.length>1){let o=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,o,"Invalid input scale"),r(e[2].dims,o,"Invalid input B"),r(e[3].dims,o,"Invalid input mean"),r(e[4].dims,o,"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")},ul=(e,t)=>{let{epsilon:r,spatial:o,format:n}=t,s=e[0].dims,u=o?Me(s[s.length-1]):1,l=n==="NHWC"&&s.length>1?u:1,a=z.size(s)/u,p=o,m=p?s.length:s,f=M("x",e[0].dataType,e[0].dims,u),b=M("scale",e[1].dataType,e[1].dims,l),_=M("bias",e[2].dataType,e[2].dims,l),y=M("inputMean",e[3].dataType,e[3].dims,l),$=M("inputVar",e[4].dataType,e[4].dims,l),I=F("y",e[0].dataType,m,u),C=()=>{let A="";if(o)A=`let cOffset = ${s.length===1?"0u":n==="NHWC"?`outputIndices[${s.length-1}] / ${u}`:"outputIndices[1]"};`;else if(n==="NCHW")A=`\n ${I.indicesSet("outputIndices","0","0")}\n let cOffset = ${I.indicesToOffset("outputIndices")};`;else{A=`var cIndices = ${b.type.indices}(0);\n cIndices[0] = outputIndices[${s.length-1}];`;for(let T=1;T`\n const epsilon = ${r};\n ${A.registerUniform("outputSize","u32").declareVariables(f,b,_,y,$,I)}\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${I.offsetToIndices(`global_idx * ${u}`)};\n ${C()}\n let scale = ${b.getByOffset("cOffset")};\n let bias = ${_.getByOffset("cOffset")};\n let inputMean = ${y.getByOffset("cOffset")};\n let inputVar = ${$.getByOffset("cOffset")};\n let x = ${f.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${I.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${o}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p?[{type:12,data:a},...j(s)]:[{type:12,data:a}]})}},dl=e=>$e(e),Ja=(e,t)=>{let{inputs:r,outputCount:o}=e,n=dl({...t,outputCount:o});if(qt.webgpu.validateInputContent&&sl(r,n),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ul(r,n))}});var ll,cl,ti,ri=q(()=>{"use strict";_e();be();ll=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")},cl=e=>{let t=e[0].dims,r=e[0].dims[2],o=z.size(t)/4,n=e[0].dataType,s=M("input",n,t,4),u=M("bias",n,[r],4),l=M("residual",n,t,4),a=F("output",n,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:m=>`\n const channels = ${r}u / 4;\n ${m.declareVariables(s,u,l,a)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(o)}\n let value = ${s.getByOffset("global_idx")}\n + ${u.getByOffset("global_idx % channels")} + ${l.getByOffset("global_idx")};\n ${a.setByOffset("global_idx","value")}\n }`}},ti=e=>{ll(e.inputs),e.compute(cl(e.inputs))}});var pl,Ee,ni,oi,ai,ii,si,ui,di,li,ci,ml,pi,mi,fi,hi,Xr,gi,Jr,yi,bi,wi,vi,$i,_i,xi,Si,Ci,Ii,Ai,Ti,Ei,Pi,Oi,ki,Ri,Bi,Ln,Fn,Di,Mi,zi,en=q(()=>{"use strict";ie();_e();je();be();pl=(e,t,r,o,n,s)=>{let u=Math.ceil(t/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let a=M("inputData",r,[u],4),p=F("outputData",o,[u],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,p)}\n\n ${s??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${a.getByOffset("global_idx")};\n ${p.setByOffset("global_idx",l)}\n }`},Ee=(e,t,r,o,n,s=e.dataType)=>({name:t,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:u=>pl(u,z.size(e.dims),e.dataType,s,r,o),getRunData:u=>({outputs:[{dims:e.dims,dataType:s}],dispatchGroup:{x:Math.ceil(z.size(u[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(z.size(e.dims)/4)}]})}),ni=e=>{e.compute(Ee(e.inputs[0],"Abs","abs"))},oi=e=>{e.compute(Ee(e.inputs[0],"Acos","acos"))},ai=e=>{e.compute(Ee(e.inputs[0],"Acosh","acosh"))},ii=e=>{e.compute(Ee(e.inputs[0],"Asin","asin"))},si=e=>{e.compute(Ee(e.inputs[0],"Asinh","asinh"))},ui=e=>{e.compute(Ee(e.inputs[0],"Atan","atan"))},di=e=>{e.compute(Ee(e.inputs[0],"Atanh","atanh"))},li=e=>$e(e),ci=(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(Ee(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},ml=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Fr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:qr;return $e({min:t,max:r})},pi=(e,t)=>{let r=e.inputs.length===1?t:ml(e.inputs),o=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Clip",n=>`clamp(${n}, clip_min_, clip_max_)`,`\n const clip_min_: vec4<${o}> = vec4(${o}(${r.min}));\n const clip_max_: vec4<${o}> = vec4(${o}(${r.max}));\n`,r.cacheKey),{inputs:[0]})},mi=e=>{e.compute(Ee(e.inputs[0],"Ceil","ceil"))},fi=e=>{e.compute(Ee(e.inputs[0],"Cos","cos"))},hi=e=>{e.compute(Ee(e.inputs[0],"Cosh","cosh"))},Xr=e=>$e(e),gi=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Elu",o=>`elu_vf32(${o})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Jr=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,yi=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Jr(t)))},bi=e=>{e.compute(Ee(e.inputs[0],"Exp","exp"))},wi=e=>{e.compute(Ee(e.inputs[0],"Floor","floor"))},vi=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Jr(t)))},$i=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"LeakyRelu",o=>`select(leaky_relu_alpha_ * ${o}, ${o}, ${o} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},_i=e=>{e.compute(Ee(e.inputs[0],"Not",t=>`!${t}`))},xi=e=>{e.compute(Ee(e.inputs[0],"Neg",t=>`-${t}`))},Si=e=>{e.compute(Ee(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Ci=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Ii=e=>{e.compute(Ee(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Ai=e=>$e(e),Ti=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"HardSigmoid",o=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${o} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Ei=e=>{e.compute(Ee(e.inputs[0],"Sin","sin"))},Pi=e=>{e.compute(Ee(e.inputs[0],"Sinh","sinh"))},Oi=e=>{e.compute(Ee(e.inputs[0],"Sqrt","sqrt"))},ki=e=>{e.compute(Ee(e.inputs[0],"Tan","tan"))},Ri=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Bi=e=>{e.compute(Ee(e.inputs[0],"Tanh",Ri))},Ln=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Ri("v")};\n}\n`,Fn=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Di=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"FastGelu",Fn,Ln(t),void 0,e.inputs[0].dataType))},Mi=(e,t)=>{let r=et(e.inputs[0].dataType);return e.compute(Ee(e.inputs[0],"ThresholdedRelu",o=>`select(vec4<${r}>(0.0), ${o}, ${o} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},zi=e=>{e.compute(Ee(e.inputs[0],"Log","log"))}});var fl,hl,Vi,Ni=q(()=>{"use strict";_e();be();en();fl=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")},hl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=M("input",e[0].dataType,e[0].dims,4),o=M("bias",e[0].dataType,[e[0].dims[2]],4),n=F("output",e[0].dataType,t,4),s=z.size(t)/4,u=Pe(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:a=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${a.declareVariables(r,o,n)}\n\n ${Jr(u)}\n\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(s)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${n.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},Vi=e=>{fl(e.inputs),e.compute(hl(e.inputs))}});var gl,yl,bt,Wi,Gi,Hi,Li,Fi,qi,Ki,ji,Yi,Zi,Qi=q(()=>{"use strict";ie();_e();be();gl=(e,t,r,o,n,s,u,l,a,p,m,f)=>{let b,_;typeof l=="string"?b=_=(v,A)=>`${l}((${v}),(${A}))`:typeof l=="function"?b=_=l:(b=l.scalar,_=l.vector);let y=F("outputData",m,o.length,4),$=M("aData",a,t.length,4),I=M("bData",p,r.length,4),C;if(n)if(s){let v=z.size(t)===1,A=z.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,D=r.length>0&&r[r.length-1]%4===0;v||A?C=y.setByOffset("global_idx",_(v?`${$.type.value}(${$.getByOffset("0")}.x)`:$.getByOffset("global_idx"),A?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"))):C=`\n let outputIndices = ${y.offsetToIndices("global_idx * 4u")};\n let offsetA = ${$.broadcastedIndicesToOffset("outputIndices",y)};\n let offsetB = ${I.broadcastedIndicesToOffset("outputIndices",y)};\n ${y.setByOffset("global_idx",_(u||T?$.getByOffset("offsetA / 4u"):`${$.type.value}(${$.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||D?I.getByOffset("offsetB / 4u"):`${I.type.value}(${I.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else C=y.setByOffset("global_idx",_($.getByOffset("global_idx"),I.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(A,T,D="")=>{let U=`aData[indexA${T}][componentA${T}]`,V=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${y.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${$.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let offsetB${T} = ${I.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${A}[${T}] = ${D}(${b(U,V)});\n `};m===9?C=`\n var data = vec4(0);\n ${v("data",0,"u32")}\n ${v("data",1,"u32")}\n ${v("data",2,"u32")}\n ${v("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:C=`\n ${v("outputData[global_idx]",0)}\n ${v("outputData[global_idx]",1)}\n ${v("outputData[global_idx]",2)}\n ${v("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables($,I,y)}\n\n ${f??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${C}\n }`},yl=(e,t,r,o,n,s,u=r.dataType)=>{let l=!z.areEqual(r.dims,o.dims),a=r.dims,p=z.size(r.dims),m=!1,f=!1,b=[l];if(l){let _=mt.calcShape(r.dims,o.dims,!1);if(!_)throw new Error("Can\'t perform binary op on the given tensors");a=_,p=z.size(a);let y=z.size(r.dims)===1,$=z.size(o.dims)===1,I=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,C=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;b.push(y),b.push($),b.push(I),b.push(C);let v=1;for(let A=1;A_.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:_=>gl(_,r.dims,o.dims,a,m,l,f,n,r.dataType,o.dataType,u,s),getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(z.size(a)/4)},...j(r.dims,o.dims,a)]})}},bt=(e,t,r,o,n,s)=>{e.compute(yl(t,n??"",e.inputs[0],e.inputs[1],r,o,s))},Wi=e=>{bt(e,"Add",(t,r)=>`${t}+${r}`)},Gi=e=>{bt(e,"Div",(t,r)=>`${t}/${r}`)},Hi=e=>{bt(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Li=e=>{bt(e,"Mul",(t,r)=>`${t}*${r}`)},Fi=e=>{let t=M("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;bt(e,"Pow",{scalar:(o,n)=>`pow_custom(${o},${n})`,vector:(o,n)=>`pow_vector_custom(${o},${n})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n 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))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n 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));\n }\n `)},qi=e=>{bt(e,"Sub",(t,r)=>`${t}-${r}`)},Ki=e=>{bt(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},ji=e=>{bt(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Yi=e=>{bt(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Zi=e=>{bt(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var wl,vl,$l,_l,Xi,Ji,es=q(()=>{"use strict";ie();_e();je();be();wl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,o=e[r],n=o.dataType,s=o.dims.length;e.forEach((u,l)=>{if(l!==r){if(u.dataType!==n)throw new Error("input tensors should be one type");if(u.dims.length!==s)throw new Error("input tensors should have the same shape");u.dims.forEach((a,p)=>{if(p!==t&&a!==o.dims[p])throw new Error("non concat dimensions must match")})}})},vl=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,$l=(e,t)=>{let r=e.length,o=[];for(let n=0;n{let n=z.size(r),s=new Array(e.length),u=new Array(e.length),l=0,a=[],p=[],m=[{type:12,data:n}];for(let $=0;$`uniforms.sizeInConcatAxis${$}`).join(","),y=$=>`\n\n ${(()=>{$.registerUniform("outputSize","u32");for(let I=0;I(${_});\n ${b} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${$l(u,f)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:r,dataType:o}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:m}),getShaderSource:y}},Xi=(e,t)=>{let r=e.inputs,o=r[0].dims,n=z.normalizeAxis(t.axis,o.length);wl(r,n);let s=o.slice();s[n]=r.reduce((l,a)=>l+(a.dims.length>n?a.dims[n]:0),0);let u=r.filter(l=>z.size(l.dims)>0);e.compute(_l(u,n,s,r[0].dataType),{inputs:u})},Ji=e=>$e({axis:e.axis})});var ut,dt,lt,tn,Ot=q(()=>{"use strict";ie();_e();ut=(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"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},dt=(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})},lt=(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"})},tn=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,o]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:o}}else if(t==="Clip"){let[r,o]=e?.activation_params||[Fr,qr];return{activation:t,clipMax:o,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var Ze,rn,nn=q(()=>{"use strict";Ze=(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.`)}},rn=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var on,qn=q(()=>{"use strict";on=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var xl,Sl,gr,ts,Cl,yr,Il,an,br=q(()=>{"use strict";ie();_e();be();Ot();nn();xl=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,Sl=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,gr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32)=>{let a=t[1]*e[1],p=t[0]*e[0],m=n?a:s,f=n?s:a,b=m/t[0],_=s/t[1];if(!((n&&b===4&&e[1]===4||!n&&(b===3||b===4))&&m%t[0]===0&&s%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${b} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${b} must be 3 or 4.\n tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${m/b}>, ${f}>;\nvar mm_Bsub: array, ${p/e[0]}>, ${s}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${b};\nconst tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${a};\n\n let num_tiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${_};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${xl(n,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${o?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${b===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${Sl(n,b)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},ts=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,Cl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",yr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32,a=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],f=n?p:s,b=n?s:p;if(!(b%t[1]===0&&f%t[0]===0&&s%t[1]===0))throw new Error(`tileAHight ${b} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${f} must be divisible by workgroupSize[0]${t[0]}, tileInner ${s} must be divisible by workgroupSize[1]${t[1]}`);let _=b/t[1],y=f/t[0],$=s/t[1],I=a?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${p};\n let globalColStart = i32(workgroupId.x) * ${m};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${b}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${f}; inputCol = inputCol + ${t[0]}) {\n ${ts(n,o)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${n?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${p};\n\nlet tileRowA = i32(localId.y) * ${_};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${$};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${ts(n,o)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${$}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Cl(n)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${b}>;\n var mm_Bsub : array, ${s}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc : array, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${I}\n }\n`},Il=(e,t,r,o,n,s=!1)=>{let[u,l,a]=n,[p,m,f,b]=o,_=jt(u,a),y=jt(l,a),$=Pe(o[0].type.tensor),I=()=>{let A=m.rank,T=p.rank,D=`var aIndices: ${m.type.indices};`;for(let U=A-2-1,V=T-1;U>=0;U--,V--)D+=`\naIndices[${U}] = ${T>1?`batchIndices[${V}]`:"batchIndices"};`;return _.forEach(U=>{D+=`\naIndices[${U}] = 0;`}),D+=`\naIndices[${A-2}] = u32(row);\n aIndices[${A-1}] = u32(colIn);`,D},C=()=>{let A=f.rank,T=p.rank,D=`var bIndices: ${f.type.indices};`;for(let U=A-2-1,V=T-1;U>=0;U--,V--)D+=`\nbIndices[${U}] = ${T>1?`batchIndices[${V}]`:"batchIndices"};`;return y.forEach(U=>{D+=`\nbIndices[${U}] = 0;`}),D+=`\nbIndices[${A-2}] = u32(row);\n bIndices[${A-1}] = u32(colIn);`,D};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ze(e,$)} {\n var value = ${Ze(e,$)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n ${I()}\n value = ${m.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ze(e,$)} {\n var value = ${Ze(e,$)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n ${C()}\n value = ${f.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ze(e,$)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${s?"bias[colIn]":`${Ze(e,$)}(bias[row])`};`:""}\n ${r}\n ${b.setByIndices("vec3(coords)","value")}\n }\n }\n `},an=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s.slice(0,-2),a=u.slice(0,-2),p=o?o.slice(0,-2):r.slice(0,-2),m=z.size(p),f=s[s.length-2],b=s[s.length-1],_=u[u.length-1],y=b%4===0&&_%4===0,$=f<=8?[4,1,1]:[4,4,1],I=[8,8,1],C=[Math.ceil(_/I[0]/$[0]),Math.ceil(f/I[1]/$[1]),Math.ceil(m/I[2]/$[2])],v=y?4:1,A=[...l,f,b/v],T=A.length,D=[...a,b,_/v],U=D.length,V=[m,f,_/v],H=[{type:6,data:f},{type:6,data:_},{type:6,data:b}];dt(t,H),H.push(...j(p,A,D));let R=["rank","rank"],L=e.length>2;L&&(H.push(...j(e[2].dims)),R.push("rank")),H.push(...j(V));let pe=Ie=>{let we=p.length,ne=jr("batchDims",e[0].dataType,we,1),ze=Pe(e[0].dataType),Q=M("a",e[0].dataType,T,v),xe=M("b",e[1].dataType,U,v),me=F("result",e[0].dataType,V.length,v),ue=[Q,xe];if(L){let G=n?v:1;ue.push(M("bias",e[2].dataType,e[2].dims.length,G))}let se=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];lt(t,se);let he=Pe(me.type.tensor),Ae=ut(t,me.type.value,he),He=Il(v,L,Ae,[ne,Q,xe,me],[l,a,p],n);return`\n ${Ie.registerUniforms(se).registerInternalVariables(ne).declareVariables(...ue,me)}\n ${He}\n ${y?gr($,I,ze,ne):yr($,I,ze,ne)}\n `};return{name:"MatMul",shaderCache:{hint:`${$};${t.activation};${y};${n}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:C[0],y:C[1],z:C[2]},programUniforms:H}),getShaderSource:pe}}});var Al,rs,ns=q(()=>{"use strict";ie();Pt();be();Ot();nn();qn();br();Al=(e,t,r,o,n=!1,s,u=4,l=4,a=4,p="f32")=>{let m=L=>{switch(L){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${L} is not supported.`)}},f=L=>{switch(L){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 ${L} is not supported.`)}},b=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,_=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",$=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",I=e?"row":"col",C=e?"col":"row",v=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${I} / outWidth;\n let outCol = ${I} % outWidth;\n\n let WRow = ${C} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${C} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${C} % inChannels;\n var resData = ${Ze(u,p)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the \'same\' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${$}) {\n ${b}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${m(u)}\n }\n return resData;`,A=e?t&&o?`\n let col = colIn * ${u};\n ${v}`:`\n let col = colIn * ${u};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${v}\n }\n return ${Ze(u,p)}(0.0);`:o&&r?`\n let col = colIn * ${u};\n ${v}`:`\n let col = colIn * ${u};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${v}\n }\n return ${Ze(u,p)}(0.0);`,T=`${f(l)}`,D=Ze(a,p),U=e?Ze(u,p):Ze(l,p),V=e?Ze(l,p):Ze(u,p),H=ut(s,D,p);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${U} {\n ${e?A:T}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${V} {\n ${e?T:A}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${D}) {\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${_}\n ${rn(n)}\n ${H}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},rs=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],m=r[0],f=a?r[2]:r[3],b=a?r[1]:r[2],_=a?r[3]:r[1],y=a&&(p%4===0||p%3===0)&&_%4===0,$=a?_:f*b,I=a?f*b:_,C=[8,8,1],v=o<=8?[4,1,1]:[4,4,1],A=[Math.ceil($/C[0]/v[0]),Math.ceil(I/C[1]/v[1]),Math.ceil(m/C[2]/v[2])];De("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${A}`);let T=y?a&&p%4!==0?3:4:1,D=C[1]*v[1],U=C[0]*v[0],V=Math.max(C[0]*T,C[1]),H=o%D===0,R=n%U===0,L=s%V===0,pe=y?[T,4,4]:[1,1,1],Ie=[{type:6,data:o},{type:6,data:n},{type:6,data:s},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];dt(t,Ie),Ie.push(...j(e[0].dims,e[1].dims));let we=["rank","rank"];u&&(Ie.push(...j(e[2].dims)),we.push("rank")),Ie.push(...j(r));let ne=ze=>{let Q=[{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}];lt(t,Q);let xe=y?4:1,me=Pe(e[0].dataType),ue=`\n fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${me}>`:me}) {\n result[flatIndex] = ${y?`vec4<${me}>`:me}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${y?`vec4<${me}>`:me}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${y?"/ 4":""}, value);\n }`,se=M("x",e[0].dataType,e[0].dims.length,T===3?1:T),he=M("w",e[1].dataType,e[1].dims.length,xe),Ae=[se,he],He=F("result",e[0].dataType,r.length,xe);if(u){let G=M("bias",e[2].dataType,e[2].dims.length,xe);Ae.push(G),ue+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${me}>`:me} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}return`\n ${on("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${ze.registerUniforms(Q).declareVariables(...Ae,He)}\n ${ue}\n ${Al(a,H,R,L,u,t,pe[0],pe[1],pe[2],me)}\n ${y?gr(v,C,me,void 0,!a,V):yr(v,C,me,void 0,!a,V,!1,void 0,l)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${T};${y};${H};${R};${L};${D};${U};${V}`,inputDependencies:we},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:Ie}),getShaderSource:ne}}});var Kn,os,as=q(()=>{"use strict";ie();_e();be();jn();Ot();Kn=(e,t,r)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",s=e[0].dims,u=e[1].dims,l=u[0]/t.group,a=t.format==="NHWC",p=sn(s,u,t.dilations,t.pads,t.strides,a),m=z.size(p),f=[{type:12,data:m},{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:l}];dt(t,f),f.push(...j(s,u,p));let b=["rank","rank"];o&&(f.push(...j(e[2].dims)),b.push("rank")),f.push(...j(p));let _=y=>{let $=F("output",e[0].dataType,p.length),I=Pe($.type.tensor),C=ut(t,$.type.value,I),v=M("x",e[0].dataType,s.length),A=M("w",e[1].dataType,u.length),T=[v,A];o&&T.push(M("b",e[2].dataType,e[2].dims));let D=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return lt(t,D),`\n ${y.registerUniforms(D).declareVariables(...T,$)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${$.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${a?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${a?1:2}], outputIndices[${a?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel / uniforms.output_channels_per_group;\n\n var value: ${$.type.value} = ${$.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = group_id * uniforms.w_shape[1] + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[${a?1:2}]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[${a?2:3}]) {\n continue;\n }\n\n let xVal = ${a?v.get("batch","xHeight","xWidth","input_channel"):v.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${A.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${n}\n ${C}\n ${$.setByOffset("global_idx","value")}\n }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:b},getRunData:()=>({outputs:[{dims:r?r(p):p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:f}),getShaderSource:_}},os=(e,t,r)=>{let o=e.length>2,n=Me(r[3]),s=Me(r[2]),u=z.size(r)/n/s,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],a=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[r[0],r[1],r[2],r[3]/n],m=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];dt(t,m),m.push(...j(l,a,p));let f=(s-1)*t.strides[1]+a[1],b=_=>{let y=F("output",e[0].dataType,p.length,n),$=Pe(y.type.tensor),I=ut(t,y.type.value,$),C=M("x",e[0].dataType,l.length,n),v=M("w",e[1].dataType,a.length,n),A=[C,v];o&&A.push(M("b",e[2].dataType,e[2].dims,n));let T=o?"value += b[output_channel];":"",D=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return lt(t,D),`\n ${_.registerUniforms(D).declareVariables(...A,y)}\n ${_.mainStart()}\n ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${s}u;\n let col = (index1 % width1) * ${s}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${C.type.value}, ${f}>;\n var values: array<${y.type.value}, ${s}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w\'s height/width.\n for (var w_height: u32 = 0u; w_height < ${a[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${f}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${C.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${C.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${a[1]}; w_width++) {\n let w_val = ${v.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${s}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${s}u; i++) {\n var value = values[i];\n ${T}\n ${I}\n ${y.set("batch","row","col + i","output_channel","value")};\n }\n }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${n};${s};${f};${a[0]};${a[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:b}}});var Yn,Tl,is,Zn=q(()=>{"use strict";ie();_e();br();be();Ot();Yn=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s[s.length-2],a=u[u.length-1],p=s[s.length-1],m=Me(a),f=Me(p),b=Me(l),_=z.size(r)/m/b,y=e.length>2,$=o?o.slice(0,-2):r.slice(0,-2),C=[z.size($),l,a],v=[{type:12,data:_},{type:12,data:l},{type:12,data:a},{type:12,data:p}];dt(t,v),v.push(...j($,s,u)),y&&v.push(...j(e[2].dims)),v.push(...j(C));let A=T=>{let D=jr("batch_dims",e[0].dataType,$.length),U=M("a",e[0].dataType,s.length,f),V=M("b",e[1].dataType,u.length,m),H=F("output",e[0].dataType,C.length,m),R=Pe(H.type.tensor),L=ut(t,H.type.value,R),pe=[U,V],Ie="";if(y){let se=n?m:1;pe.push(M("bias",e[2].dataType,e[2].dims.length,se)),Ie=`${n?`value += bias[col / ${se}];`:`value += ${H.type.value}(bias[row + i]);`}`}let we=s.slice(0,-2),ne=u.slice(0,-2),ze=jt(we,$),Q=jt(ne,$),xe=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];lt(t,xe);let me=(se,he)=>{let Ae=se.rank,He=se.name;if(Ae===2)return`var ${He}_indices = ${se.type.indices}(0u, 0u);`;let G=D.rank,J=`var ${He}_indices: ${se.type.indices};`;for(let Se=Ae-2-1,Qe=G-1;Se>=0;Se--,Qe--)J+=`\n${He}_indices[${Se}] = ${G>1?`batch_indices[${Qe}]`:"batch_indices"};`;return he.forEach(Se=>{J+=`\n${He}_indices[${Se}] = 0;`}),J+=`${He}_indices[${Ae-2}] = 0u;\n ${He}_indices[${Ae-1}] = 0u;`,J},ue=()=>{let se=`var a_data: ${U.type.value};`;for(let he=0;he;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${f}) {\n ${ue()}\n }\n for (var i = 0u; i < ${b}u; i++) {\n var value = values[i];\n ${Ie}\n ${L}\n let cur_indices = ${H.type.indices}(batch, row + i, col);\n let offset = ${H.indicesToOffset("cur_indices")};\n ${H.setByOffset(`offset / ${m}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${f};${b};${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:A}},Tl=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.")},is=e=>{Tl(e.inputs);let t=mt.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],o=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&o<8?e.compute(Yn(e.inputs,{activation:""},t)):e.compute(an(e.inputs,{activation:""},t))}});var sn,Qn,El,ss,Xn,Pl,Ol,Jn,jn=q(()=>{"use strict";_e();ns();br();as();Ot();Zn();Yt();sn=(e,t,r,o,n,s)=>{let u=e[0],l=e.slice(s?1:2,s?3:4),a=l.length,p=t[0],f=t.slice(2).map((y,$)=>y+(y-1)*(r[$]-1)),_=l.map((y,$)=>y+o[$]+o[$+a]).map((y,$)=>Math.floor((y-f[$]+n[$])/n[$]));return _.splice(0,0,u),_.splice(s?3:1,0,p),_},Qn=[2,3,1,0],El=(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 conv 1D and 2D");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],o=e[1].dims[1]*t.group;if(r!==o)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 n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ss=(e,t)=>{let r=e.kernelShape.slice();for(let s=2;s{let t=tn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,s=e.group,u=e.kernel_shape,l=e.pads,a=e.strides,p=e.w_is_const();return{autoPad:o,format:r,dilations:n,group:s,kernelShape:u,pads:l,strides:a,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Pl=(e,t,r)=>{let o=ss(r,t),n=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&n&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let V=sn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,n),H=e.kernelCustomData.wT??e.compute(ot(t[1],Qn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=H);let R=[t[0],H];t.length===3&&R.push(t[2]),e.compute(os(R,o,V),{inputs:R})}else e.compute(Kn(t,o));return}let s=t.length===3,u=t[0].dims[n?1:2],l=t[0].dims[n?2:3],a=t[0].dims[n?3:1],p=t[1].dims[2],m=t[1].dims[3],f=sn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,n),b=f[n?1:2],_=f[n?2:3],y=f[n?3:1],$=n&&p===u&&m===l&&r.pads[0]===0&&r.pads[1]===0;if($||p===1&&m===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 U=f[0],V,H,R,L=[];if(n){let we=e.kernelCustomData.wT??e.compute(ot(t[1],Qn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=we),$){let ne=u*l*a;V=t[0].reshape([1,U,ne]),H=we.reshape([1,ne,y]),R=[1,U,y]}else V=t[0].reshape([U,u*l,a]),H=we.reshape([1,a,y]),R=[U,b*_,y];L.push(V),L.push(H)}else V=t[0].reshape([U,a,u*l]),H=t[1].reshape([1,y,a]),R=[U,y,b*_],L.push(H),L.push(V);s&&L.push(t[2]);let pe=R[2],Ie=L[0].dims[L[0].dims.length-1];pe<8&&Ie<8?e.compute(Yn(L,o,f,R,n),{inputs:L}):e.compute(an(L,o,f,R,n),{inputs:L});return}let I=!0,C=e.kernelCustomData.wT??e.compute(ot(t[1],Qn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=C);let v=[t[0],C];s&&v.push(t[2]);let A=n?b*_:y,T=n?y:b*_,D=p*m*a;e.compute(rs(v,o,f,A,T,D,s,I),{inputs:v})},Ol=(e,t)=>{let r=t.format==="NHWC",o=[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&&o.push(e.inputs[2]);let n=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),u=[1].concat(t.dilations),l=[1].concat(t.kernelShape),a=ss({...t,pads:n,strides:s,dilations:u,kernelShape:l},o);e.compute(Kn(o,a,p=>r?[p[0],p[2],p[3]]:[]))},Jn=(e,t)=>{El(e.inputs,t),e.inputs[0].dims.length===3?Ol(e,t):Pl(e,e.inputs,t)}});var kl,us,ds=q(()=>{"use strict";ie();Pt();be();Ot();nn();qn();br();kl=(e,t=!1,r,o,n=4)=>{let s=C=>{switch(C){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${o}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${C} is not supported.`)}},u=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,l=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,a=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=e?"row":"col",f=e?"col":"row",b=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${m} / outWidth;\n let outCol = ${m} % outWidth;\n\n let WRow = ${f} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${f} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${a}) || fract(xR) > 0.0) {\n return ${o}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) {\n return ${o}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${f} % inChannels;\n ${u}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${n}];`,_=e?`\n let col = colIn * ${n};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${b}\n }\n return ${o}(0.0);`:`\n let col = colIn * ${n};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${b}\n }\n return ${o}(0.0);`,y=`\n let col = colIn * ${n};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${s(n)}\n }\n return ${o}(0.0);\n `,$=ut(r,o);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?_:y}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?y:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${o}) {\n let col = colIn * ${n};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${l}\n ${rn(t)}\n ${$}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${n}] = value;\n }\n }`},us=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],m=r[0],f=a?r[2]:r[3],b=a?r[1]:r[2],_=a?r[3]:r[1],y=a?p%4===0&&_%4===0:f%4===0&&_%4===0,$=a?_:f*b,I=a?f*b:_,C=y?[8,8,1]:[$<=4||I<=4?4:16,$>4&&I<=4?4:16,1],v=y?[4,4,1]:[$<=4?1:4,$>4&&I<=4?1:4,1],A=[Math.ceil($/C[0]/v[0]),Math.ceil(I/C[1]/v[1]),Math.ceil(m/C[2]/v[2])];De("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${A}`);let T=y?4:1,D=Math.max(C[0]*T,C[1]),U=y?4:1,V=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],H=[V[0]+(t.dilations[0]<=1?0:(V[0]-1)*(t.dilations[0]-1)),V[1]+(t.dilations[1]<=1?0:(V[1]-1)*(t.dilations[1]-1))],R=[H[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),H[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],L=[{type:6,data:o},{type:6,data:n},{type:6,data:s},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:V},{type:6,data:R}];dt(t,L),L.push(...j(e[0].dims,e[1].dims));let pe=["rank","rank"];u&&(L.push(...j(e[2].dims)),pe.push("rank")),L.push(...j(r));let Ie=we=>{let ne=M("x",e[0].dataType,e[0].dims.length,U),ze=M("w",e[1].dataType,e[1].dims.length,1),Q=F("result",e[0].dataType,r.length,U),xe=[ne,ze],me="";if(u){let he=M("bias",e[2].dataType,e[2].dims.length,U);xe.push(he),me+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${he.type.value} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}let ue=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:V.length},{name:"pads",type:"i32",length:R.length}];lt(t,ue);let se=Pe(e[0].dataType,1);if(se!=="f16"&&se!=="f32")throw new Error(`elemType ${se} is not supported.`);return`\n ${on("uniforms.result_strides")}\n ${we.registerUniforms(ue).declareVariables(...xe,Q)};\n ${me}\n ${kl(a,u,t,ne.type.value,T)}\n ${y?gr(v,C,se,void 0,!a,D):yr(v,C,se,void 0,!a,D,!1,void 0,l)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${v};${C};${y}`,inputDependencies:pe},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:L}),getShaderSource:Ie}}});var Rl,eo,ls=q(()=>{"use strict";ie();Pt();_e();be();Rl=(e,t,r,o,n,s=!1,u,l,a=!1)=>{let p=a?1:2,m=a?2:3,f=a?3:1,b=s?2:1,_=`\n fn setOutputAtIndex(flatIndex : u32, value : ${s?`vec4<${u}>`:u}) {\n result[flatIndex] = ${s?`vec4<${u}>`:u}(value);\n }`;o&&(_+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${s?`vec4<${u}>`:u} {\n return bias[coords.${a?"w":"y"}${s?"/ 4":""}];\n }`);let y=s?4:1,$=M("W",t[1].dataType,t[1].dims.length,y),I=M("Dy",t[0].dataType,t[0].dims.length,y),C=[I,$];o&&C.push(M("bias",t[2].dataType,[r[f]].length,y));let v=F("result",t[0].dataType,r.length,y),A=`{\n let batch: u32 = ${n?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${n?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${n?"global_id.y":"workgroup_id.y"} * ${b};\n let d1: u32 = ${n?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${b}>;\n for (var i = 0; i < ${b}; i++) {\n dotProd[i] = vec4<${u}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${u}(dyCorner.x) + ${u}(wR)) / ${u}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${u}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${u}(dyCorner.y) + ${u}(wC)) / ${u}(uniforms.strides.y);\n let dyC2 = (${u}(dyCorner.y) + 1.0 + ${u}(wC)) / ${u}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${u}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${u}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${I.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${I.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${f}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${I.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${I.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${b}; i = i + 1) {\n let value = dotProd[i] + ${o?"bias[c+i]":`vec4<${u}>(0.0)`};\n ${v.set("batch","r","c + i","d1","value")};\n }\n }`,T=`\n let outputIndices = ${v.offsetToIndices("global_idx")};\n let batch = ${v.indicesGet("outputIndices",0)};\n let d1 = ${v.indicesGet("outputIndices",f)};\n let r = ${v.indicesGet("outputIndices",p)};\n let c = ${v.indicesGet("outputIndices",m)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${u}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${u}(dyRCorner) + ${u}(wR)) / ${u}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${u}(uniforms.Dy_shape[${p}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${u}(dyCCorner) + ${u}(wC)) / ${u}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${u}(uniforms.Dy_shape[${m}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${a?I.get("batch","idyR","idyC","inputChannel"):I.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${$.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${o?"bias[d1]":`${u}(0.0)`};\n ${v.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(l).declareVariables(...C,v)}\n ${_}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${s?A:T}}`},eo=(e,t,r)=>{let o=e.length>2,n=t.outputShape,s=z.size(n),u=[Math.ceil(s/64),1,1];De("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let l=t.format==="NHWC",a=["rank","rank"],p=[t.strides[0],t.strides[1]],m=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],f=[t.dilations[0],t.dilations[1]],b=[m[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),m[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],_=[b[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),b[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],y=!1,$=t.group,I=e[1].dims,C=I[0]/$,v=I[1],A=[{type:6,data:s},{type:12,data:p},{type:12,data:m},{type:12,data:f},{type:12,data:b},{type:6,data:_},{type:12,data:C},{type:12,data:v},...j(e[0].dims,e[1].dims)];o&&(A.push(...j(e[2].dims)),a.push("rank")),A.push(...j(n));let T=u[1]===1&&u[2]===1,D=U=>{let V=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.length},{name:"filter_dims",type:"u32",length:m.length},{name:"dilations",type:"u32",length:m.length},{name:"effective_filter_dims",type:"u32",length:b.length},{name:"pads",type:"i32",length:_.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],H=Pe(e[0].dataType);return`${Rl(U,e,n,o,T,y,H,V,l)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:a},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],programUniforms:A}),getShaderSource:D}}});var Bl,Dl,Ml,cs,ps,zl,Ul,Vl,Nl,ms,fs=q(()=>{"use strict";ds();ls();Ot();Yt();Bl=(e,t,r,o,n,s)=>(e-1)*t+r+(o-1)*n+1-s,Dl=(e,t,r,o,n)=>{let s=Math.floor(e/2);t==="SAME_UPPER"?(r[o]=s,r[n]=e-s):t==="SAME_LOWER"&&(r[o]=e-s,r[n]=s)},Ml=(e,t,r,o,n,s,u,l,a,p)=>{let m=e.length-2,f=p.length===0;if(a.length===0)for(let y=0;y{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((f,b)=>f*b,1)===0){r.length=0;for(let f=2;ff+b,0)===0){let f=t[0].dims.length-2;a=new Array(f).fill(1)}let p=e.strides.slice();if(p.reduce((f,b)=>f+b,0)===0){let f=t[0].dims.length-2;p=new Array(f).fill(1)}Ml(l,r,a,e.autoPad,e.group,n,p,o,u,s);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:n,outputPadding:u,outputShape:s,dilations:a,strides:p}),m},ps=e=>{let t=tn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,s=e.group,u=e.kernelShape,l=e.pads,a=e.strides,p=e.wIsConst(),m=e.outputPadding,f=e.outputShape;return{autoPad:o,format:r,dilations:n,group:s,kernelShape:u,outputPadding:m,outputShape:f,pads:l,strides:a,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},zl=(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],o=e[1].dims[0];if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.reduce((m,f)=>m+f,0)>0&&t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.reduce((m,f)=>m+f,0)>0&&t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.reduce((m,f)=>m+f,0)>0&&t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.outputPadding.length!==s&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${s}D`);if(t.kernelShape.reduce((m,f)=>m+f,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")},Ul=[2,3,1,0],Vl=(e,t,r)=>{let o=cs(r,t),n=r.format==="NHWC",s=o.outputShape,u=s[n?3:1],l=t[0].dims[n?3:1];if(o.group!==1||u===1&&l===1){e.compute(eo(t,o));return}let a=s[n?1:2],p=s[n?2:3],m=t[1].dims[2],f=t[1].dims[3],b=n?a*p:u,_=n?u:a*p,y=m*f*l,$=!0,I=e.kernelCustomData.wT??e.compute(ot(t[1],Ul),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let C=[t[0],I],v=t.length===3;v&&(!n&&t[2].dims.length===1?C.push(t[2].reshape([t[2].dims[0],1,1])):C.push(t[2])),e.compute(us(C,o,s,b,_,y,v,$),{inputs:C})},Nl=(e,t)=>{let r=t.format==="NHWC",o=[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]])];o.length===3&&o.push(e.inputs[2]);let n=t.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let s=t.dilations;(s.length===0||s[0]===0)&&(s=[1]);let u=t.strides;(u.length===0||u[0]===0)&&(u=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],u=[1].concat(u),s=[1].concat(s),n=[1].concat(n);let a=cs({...t,pads:l,strides:u,dilations:s,kernelShape:n},o);e.compute(eo(o,a,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},ms=(e,t)=>{zl(e.inputs,t),e.inputs[0].dims.length===3?Nl(e,t):Vl(e,e.inputs,t)}});var Wl,hs,gs,ys=q(()=>{"use strict";ie();_e();je();be();Wl=(e,t,r,o)=>{let n=z.size(t),s=t.length,u=M("input",e,s),l=F("output",e,s),a=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=z.normalizeAxis(a,s),m=f=>{let b=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,_=re("uniforms.input_shape","uniforms.axis",s),y=o.reverse?b+(o.exclusive?" + 1":""):"0",$=o.reverse?_:b+(o.exclusive?"":" + 1");return`\n ${f.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,l)}\n ${f.mainStart()}\n ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${l.offsetToIndices("global_idx")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${$};\n for (var i : i32 = first; i < last; i++) {\n ${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${u.getByIndices("inputIndices")};\n }\n ${l.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:o.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},{type:6,data:p},...j(t,t)]}),getShaderSource:m}},hs=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,n=e.inputs[1];e.compute(Wl(o,r,n,t),{inputs:[0]})},gs=e=>{let t=e.exclusive===1,r=e.reverse===1;return $e({exclusive:t,reverse:r})}});var to,un,bs,Gl,Hl,ro,no,ws,Ll,vs,$s,_s=q(()=>{"use strict";ie();_e();je();be();to="[a-zA-Z]|\\\\.\\\\.\\\\.",un="("+to+")+",bs="^"+un+"$",Gl="("+un+",)*"+un,Hl="^"+Gl+"$",ro=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let o=this.symbolToIndices.get(t);o===void 0?o=[r]:o.push(r),this.symbolToIndices.set(t,o)}},no=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[o,n]=r.includes("->")?r.split("->",2):[r,""];if(!o.match(RegExp(Hl)))throw new Error("Invalid LHS term");if(o.split(",").forEach((l,a)=>{let p=t[a].dims.slice();if(!l.match(RegExp(bs)))throw new Error("Invalid LHS term");let m=this.processTerm(l,!0,p,a);this.lhs.push(m)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([l,a])=>a.count===1||l==="...").map(([l])=>l).join("");else if(!n.match(RegExp(un)))throw new Error("Invalid RHS");n.match(RegExp(to,"g"))?.forEach(l=>{if(l==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(l);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(t,r,o){let n=this.symbolToInfo.get(t);if(n!==void 0){if(n.dimValue!==r&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(o)}else n={count:1,dimValue:r,inputIndices:[o]};this.symbolToInfo.set(t,n)}processTerm(t,r,o,n=-1){let s=o.length,u=!1,l=[],a=0;if(!t.match(RegExp(bs))&&!r&&t!=="")throw new Error("Invalid LHS term");let p=t.match(RegExp(to,"g")),m=new ro(n);return p?.forEach((f,b)=>{if(f==="..."){if(u)throw new Error("Only one ellipsis is allowed per input term");u=!0;let _=s-p.length+1;if(_<0)throw new Error("Ellipsis out of bounds");if(l=o.slice(a,a+_),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let y=0;ye+"_max",Ll=(e,t,r,o)=>{let s=e.map(m=>m.length).map((m,f)=>M(`input${f}`,t,m)),u=z.size(o),l=F("output",t,o.length),a=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),p=m=>{let f=[],b="var prod = 1.0;",_="var sum = 0.0;",y="sum += prod;",$=[],I=[],C=[],v=[],A=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((D,U)=>{if(r.rhs.symbolToIndices.has(U)){let V=r.rhs.symbolToIndices.get(U)?.[0];V!==void 0&&r.lhs.forEach((H,R)=>{if(D.inputIndices.includes(R)){let L=H.symbolToIndices.get(U);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(pe=>{f.push(`${s[R].indicesSet(`input${R}Indices`,pe,l.indicesGet("outputIndices",V))}`)})}})}else r.lhs.forEach((V,H)=>{if(D.inputIndices.includes(H)){let R=V.symbolToIndices.get(U);if(R===void 0)throw new Error("Invalid symbol error");R.forEach(L=>{$.push(`${s[H].indicesSet(`input${H}Indices`,L,`${U}`)}`)}),v.push(`prod *= ${s[H].getByIndices(`input${H}Indices`)};`)}}),I.push(`for(var ${U}: u32 = 0; ${U} < uniforms.${ws(U)}; ${U}++) {`),C.push("}")});let T=A?[...f,`let sum = ${s.map((D,U)=>D.getByIndices(`input${U}Indices`)).join(" * ")};`]:[...f,_,...I,...$,b,...v,y,...C];return`\n ${m.registerUniforms(a.map(D=>({name:`${ws(D)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,l)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${l.offsetToIndices("global_idx")};\n ${s.map((D,U)=>`var input${U}Indices: ${s[U].type.indices};`).join(`\n`)}\n ${T.join(`\n`)};\n ${l.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let m=a.filter(b=>r.symbolToInfo.has(b)).map(b=>({type:12,data:r.symbolToInfo.get(b)?.dimValue||0}));m.push({type:12,data:u});let f=e.map((b,_)=>[...j(b)]).reduce((b,_)=>b.concat(_),m);return f.push(...j(o)),{outputs:[{dims:o,dataType:t}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}},getShaderSource:p}},vs=(e,t)=>{let r=new no(e.inputs,t.equation),o=r.outputDims,n=e.inputs.map((s,u)=>s.dims);e.compute(Ll(n,e.inputs[0].dataType,r,o))},$s=e=>{let t=e.equation.replace(/\\s+/g,"");return $e({equation:t})}});var Fl,xs,ql,Kl,Ss,Cs=q(()=>{"use strict";ie();_e();be();Fl=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),o=r.length{let r=e.length-t.length,o=[];for(let n=0;ne.length>t.length?xs(e,t):xs(t,e),Kl=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=ql(t,r),n=e[0].dataType,s=n===9?4:1,u=Math.ceil(z.size(o)/s),l=p=>{let m=M("input",n,t.length,s),f=F("output",n,o.length,s),b;if(n===9){let _=(y,$,I="")=>`\n let outputIndices${$} = ${f.offsetToIndices(`outputOffset + ${$}u`)};\n let offset${$} = ${m.broadcastedIndicesToOffset(`outputIndices${$}`,f)};\n let index${$} = offset${$} / 4u;\n let component${$} = offset${$} % 4u;\n ${y}[${$}] = ${I}(${m.getByOffset(`index${$}`)}[component${$}]);\n `;b=`\n let outputOffset = global_idx * ${s};\n var data = vec4(0);\n ${_("data",0,"u32")}\n ${_("data",1,"u32")}\n ${_("data",2,"u32")}\n ${_("data",3,"u32")}\n ${f.setByOffset("global_idx","data")}\n }`}else b=`\n let outputIndices = ${f.offsetToIndices("global_idx")};\n let inputOffset = ${m.broadcastedIndicesToOffset("outputIndices",f)};\n ${f.setByOffset("global_idx",m.getByOffset("inputOffset"))}\n }`;return`\n ${p.registerUniform("vec_size","u32").declareVariables(m,f)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${b}`},a=[{type:12,data:u},...j(t,o)];return{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:["rank"]},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:a})}},Ss=e=>{Fl(e.inputs),e.compute(Kl(e.inputs),{inputs:[0]})}});var jl,Is,As=q(()=>{"use strict";ie();_e();be();en();jl=e=>{let t=e[0].dataType,r=z.size(e[0].dims),o=z.size(e[1].dims),n=o%4===0,s=u=>{let l=M("x",t,[1],4),a=M("bias",t,[1],4),p=F("y",t,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],f=_=>`\n let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;\n let bias${_} = ${a.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,b=n?`\n let bias = ${a.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${f(0)}${f(1)}${f(2)}${f(3)}\n let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${u.registerUniforms(m).declareVariables(l,a,p)}\n\n ${Ln(et(t))}\n\n ${u.mainStart(Kr)}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${l.getByOffset("global_idx")};\n ${b}\n let x_in = x + bias;\n ${p.setByOffset("global_idx",Fn("x_in"))}\n }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:s,getRunData:u=>({outputs:[{dims:u[0].dims,dataType:u[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:o}],dispatchGroup:{x:Math.ceil(r/Kr/4)}})}},Is=e=>{e.inputs.length<2||z.size(e.inputs[1].dims)===0?Di(e):e.compute(jl(e.inputs))}});var Yl,Zl,Ts,Es,Ps=q(()=>{"use strict";ie();_e();je();be();Yl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Zl=(e,t)=>{let r=e[0].dims,o=e[1].dims,n=r.length,s=z.normalizeAxis(t.axis,n),u=r.slice(0);u.splice(s,1,...o);let l=r[s],a=e[0].dataType===9?4:1,p=Math.ceil(z.size(u)/a),m=[{type:12,data:p},{type:6,data:l},{type:12,data:s},...j(e[0].dims,e[1].dims,u)],f=b=>{let _=M("data",e[0].dataType,e[0].dims.length,a),y=M("inputIndices",e[1].dataType,e[1].dims.length),$=F("output",e[0].dataType,u.length,a),I=v=>{let A=o.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let D=0;D1?`indicesIndices${v}[${D}]`:`indicesIndices${v}`} = ${u.length>1?`outputIndices${v}[uniforms.axis + ${D}]`:`outputIndices${v}`};`;T+=`\n var idx${v} = ${y.getByIndices(`indicesIndices${v}`)};\n if (idx${v} < 0) {\n idx${v} = idx${v} + uniforms.axisDimLimit;\n }\n var dataIndices${v} : ${_.type.indices};\n `;for(let D=0,U=0;D1?`dataIndices${v}[${D}]`:`dataIndices${v}`} = u32(idx${v});`,U+=A):(T+=`${n>1?`dataIndices${v}[${D}]`:`dataIndices${v}`} = ${u.length>1?`outputIndices${v}[${U}]`:`outputIndices${v}`};`,U++);return T},C;if(e[0].dataType===9){let v=(A,T,D="")=>`\n let outputIndices${T} = ${$.offsetToIndices(`outputOffset + ${T}u`)};\n ${I(T)};\n let offset${T} = ${_.indicesToOffset(`dataIndices${T}`)};\n let index${T} = offset${T} / 4u;\n let component${T} = offset${T} % 4u;\n ${A}[${T}] = ${D}(${_.getByOffset(`index${T}`)}[component${T}]);\n `;C=`\n let outputOffset = global_idx * ${a};\n var value = vec4(0);\n ${v("value",0,"u32")}\n ${v("value",1,"u32")}\n ${v("value",2,"u32")}\n ${v("value",3,"u32")}\n ${$.setByOffset("global_idx","value")}\n `}else C=`\n let outputIndices = ${$.offsetToIndices("global_idx")};\n ${I("")};\n let value = ${_.getByIndices("dataIndices")};\n ${$.setByOffset("global_idx","value")};\n `;return`\n ${b.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,y,$)}\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${C}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:f}},Ts=e=>$e({axis:e.axis}),Es=(e,t)=>{let r=e.inputs;Yl(r),e.compute(Zl(e.inputs,t))}});var Ql,Xl,Os,ks,Rs=q(()=>{"use strict";ie();_e();je();be();Ql=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\n indices input tensors be of same rank.`)},Xl=(e,t)=>{let r=e[0].dims,o=e[0].dataType,n=r.length,s=e[1].dims,u=e[1].dataType,l=z.normalizeAxis(t.axis,n),a=r[l],p=s.slice(0),m=z.size(p),f=M("input",o,n),b=M("indicesInput",u,s.length),_=F("output",o,p.length),y=[{type:12,data:m},{type:6,data:a},{type:12,data:l}];return y.push(...j(r,s,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:C=>`\n ${C.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,b,_)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${_.offsetToIndices("global_idx")};\n\n var idx = ${b.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${f.type.indices}(outputIndices);\n ${f.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${f.getByIndices("inputIndices")};\n\n ${_.setByOffset("global_idx","value")};\n }`}},Os=e=>$e({axis:e.axis}),ks=(e,t)=>{let r=e.inputs;Ql(r),e.compute(Xl(e.inputs,t))}});var Jl,ec,Bs,Ds,Ms=q(()=>{"use strict";ie();_e();be();Jl=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")},ec=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[n,s,u]=Lr.getShapeOfGemmResult(r,t.transA,o,t.transB,e.length===3?e[2].dims:void 0),l=[n,s];if(!l)throw new Error("Can\'t use gemm on the given tensors");let a=z.size(l),p=[{type:12,data:a},{type:12,data:n},{type:12,data:s},{type:12,data:u},{type:1,data:t.alpha},{type:1,data:t.beta}],m=["type","type"];e.length===3&&(p.push(...j(e[2].dims)),m.push("rank")),p.push(...j(l));let f=b=>{let _="";t.transA&&t.transB?_="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?_="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?_="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(_="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let y=t.alpha===1?"":"value *= uniforms.alpha;",$=M("a",e[0].dataType,e[0].dims),I=M("b",e[1].dataType,e[1].dims),C=$.type.value,v=null,A=[$,I];e.length===3&&(v=M("c",e[2].dataType,e[2].dims.length),A.push(v));let T=F("output",e[0].dataType,l.length);A.push(T);let D=[{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`\n ${b.registerUniforms(D).declareVariables(...A)}\n\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${C}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${_}\n }\n\n ${y}\n ${(()=>v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",T)}; value += ${C}(uniforms.beta) * ${v.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:f}},Bs=e=>{let t=e.transA,r=e.transB,o=e.alpha,n=e.beta;return{transA:t,transB:r,alpha:o,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Ds=(e,t)=>{Jl(e.inputs),e.compute(ec(e.inputs,t))}});var tc,rc,nc,zs,Us=q(()=>{"use strict";ie();_e();be();tc=(e,t)=>{let r=e[0].dims,o=r,n=2,s=z.sizeToDimension(r,n),u=z.sizeFromDimension(r,n),l=Me(u),a=u/l,p=[r[0],r[1],a],m=["rank","type","type"],f=[{type:12,data:u},{type:12,data:a}];f.push(...j(p,p));let b=_=>{let y=M("x",e[0].dataType,p.length,l),$=M("scale",e[1].dataType,e[1].dims),I=M("bias",e[2].dataType,e[2].dims),C=F("output",e[0].dataType,p.length,l),v=[y,$,I,C],A=y.type.value,T=l===1?"f32":`vec${l}`,D=64,U=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${T}, ${D}>;\n const workgroupSize = ${D}u;\n ${_.registerUniforms(U).declareVariables(...v)}\n ${_.mainStart(D)}\n let norm = global_idx / workgroupSize;\n let batch = norm / uniforms.x_shape[1];\n let channel = norm % uniforms.x_shape[1];\n let localIndex = local_id.x;\n\n // initialize workgroup memory\n var initial = ${T}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${T}(${y.get("batch","channel","h")});\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the mean of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n meanShared = ${tt("workgroupShared[0]",l)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${T}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${T}(${y.get("batch","channel","h")}) - ${T}(meanShared);\n initial = initial + deviation * deviation;\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the sum of square of deviation of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n squaredNormShared = ${tt("workgroupShared[0]",l)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${$.getByOffset("channel")});\n let channelShift = f32(${I.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${y.get("batch","channel","h")} * ${A}(${T}(channelScale)) + ${A}(${T}(channelShift));\n ${C.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${l}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:s},programUniforms:f}),getShaderSource:b}},rc=(e,t,r,o,n,s,u,l)=>{let a=Me(u),p=64,m=a===1?"vec2f":`mat2x${a}f`,f=a===1?"f32":`vec${a}f`,b=(U,V)=>`${m}(${U}, ${V})`,_=n*u/a,y=Math.ceil(s/p),$=["type"],I=[{type:12,data:y},{type:12,data:s},{type:12,data:Math.floor(u/a)},{type:12,data:Math.floor(s*u/a)}],C=U=>{let V=M("input",t.dataType,t.dims,a);return`\n ${U.declareVariables(V)}\n @group(0) @binding(1) var output : array<${m}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${U.mainStart(p)}\n let currentImageNumber = global_idx / ${p} / uniforms.C;\n let currentChannelNumber = (global_idx / ${p}) % uniforms.C;\n let wgId = global_idx % ${p};\n let wgOffset = wgId * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${Ye("f32",a)};\n var squaredSum = ${Ye("f32",a)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${f}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${b("sum","squaredSum")};\n }`},v=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${a}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:[n,u,p,2],dataType:1}],dispatchGroup:{x:n*u/a},programUniforms:I}),getShaderSource:C},{inputs:[t],outputs:[-1]})[0],A=[{type:12,data:_},{type:12,data:s},{type:12,data:Math.floor(u/a)},{type:12,data:Math.floor(p*u/a)}],T=["type","type","type"],D=U=>{let V=M("scale",r.dataType,r.dims,a),H=M("bias",o.dataType,o.dims,a);return`\n @group(0) @binding(0) var input : array<${m}>;\n @group(0) @binding(1) var scale : array<${V.type.storage}>;\n @group(0) @binding(2) var bias : array<${H.type.storage}>;\n @group(0) @binding(3) var output : array<${m}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${U.mainStart()}\n ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")}\n let currentImageNumber = global_idx / uniforms.C;\n let currentChannelNumber = global_idx % uniforms.C;\n\n let offset = currentImageNumber * uniforms.image_size;\n var sum = ${Ye("f32",a)};\n var squaredSum = ${Ye("f32",a)};\n for (var i: u32 = 0; i < min(${p}, uniforms.H); i++) {\n let value = input[offset + i + currentChannelNumber * ${p}];\n sum += value[0];\n squaredSum += value[1];\n }\n sum = sum / f32(uniforms.H);\n squaredSum = squaredSum / f32(uniforms.H);\n let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${l}));\n let channelScale = invStdDev * ${f}(scale[currentChannelNumber]);\n let channelShift = ${f}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${b("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${a};${l}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:[n,u,2],dataType:1}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:A}),getShaderSource:D},{inputs:[v,r,o],outputs:[-1]})[0]},nc=(e,t,r)=>{let o=t[0].dims,n=o,s=o[0],u=o[o.length-1],l=z.sizeFromDimension(o,1)/u,a=Me(u),p=z.size(n)/a,m=[{type:12,data:l},{type:12,data:Math.floor(u/a)}],f=["type","type"],b=rc(e,t[0],t[1],t[2],s,l,u,r.epsilon),_=y=>{let $=Pe(t[0].dataType),I=a===1?"vec2f":`mat2x${a}f`,C=a===1?$:`vec${a}<${$}>`,v=M("input",t[0].dataType,t[0].dims,a),A=F("output",t[0].dataType,n,a);return`\n @group(0) @binding(0) var input : array<${v.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${I}>;\n @group(0) @binding(2) var output : array<${A.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${y.mainStart()}\n let currentImageNumber = global_idx / (uniforms.C * uniforms.H);\n let currentChannelNumber = global_idx % uniforms.C;\n\n let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber;\n let scale = scaleInput[scaleOffset];\n output[global_idx] = fma(input[global_idx], ${C}(scale[0]), ${C}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${a}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:_},{inputs:[t[0],b]})},zs=(e,t)=>{t.format==="NHWC"?nc(e,e.inputs,t):e.compute(tc(e.inputs,t))}});var oc,ac,Vs,Ns=q(()=>{"use strict";ie();_e();be();oc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},ac=(e,t,r)=>{let o=e[0].dims,n=e[1],s=e[2],u=o,l=z.normalizeAxis(t.axis,o.length),a=z.sizeToDimension(o,l),p=z.sizeFromDimension(o,l),m=z.size(n.dims),f=s?z.size(s.dims):0;if(m!==p||s&&f!==p)throw new Error(`Size of X.shape()[axis:] == ${p}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${m} and bias size of ${f}`);let b=[];for(let T=0;T1,C=r>2,v=T=>{let D=Pe(e[0].dataType),U=[M("x",e[0].dataType,e[0].dims,_),M("scale",n.dataType,n.dims,_)];s&&U.push(M("bias",s.dataType,s.dims,_)),U.push(F("output",e[0].dataType,u,_)),I&&U.push(F("mean_data_output",1,b)),C&&U.push(F("inv_std_output",1,b));let V=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${T.registerUniforms(V).declareVariables(...U)}\n ${T.mainStart()}\n ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${Ye("f32",_)};\n var mean_square_vector = ${Ye("f32",_)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${st(D,_,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${tt("mean_vector",_)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${tt("mean_square_vector",_)} / uniforms.norm_size - mean * mean + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${st(D,_,"x[j + offset]")};\n let f32scale = ${st(D,_,"scale[j]")};\n output[j + offset] = ${U[0].type.value}((f32input - mean) * inv_std_dev * f32scale\n ${s?`+ ${st(D,_,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${C?"inv_std_output[global_idx] = inv_std_dev":""};\n }`},A=[{dims:u,dataType:e[0].dataType}];return I&&A.push({dims:b,dataType:1}),C&&A.push({dims:b,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${r}`,inputDependencies:y},getRunData:()=>({outputs:A,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:$}),getShaderSource:v}},Vs=(e,t)=>{oc(e.inputs),e.compute(ac(e.inputs,t,e.outputCount))}});var ic,sc,Ws,Gs,Hs=q(()=>{"use strict";ie();_e();je();be();ic=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],o=r.dims.length;if(r.dims[o-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let n=Math.floor((t.k+t.blockSize-1)/t.blockSize),s=t.blockSize/8*t.bits,u=e[1];if(!z.areEqual(u.dims,[t.n,n,s]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(z.size(a)!==t.n*n)throw new Error("scales input size error.");if(e.length===4){let m=e[3].dims,f=t.bits>4?t.n*n:t.n*Math.floor((n+1)/2);if(z.size(m)!==f)throw new Error("zeroPoints input size error.")}},sc=(e,t)=>{let r=e[0].dims,o=r.length,n=r.slice(0,o-1).concat(t.n),s=r[o-2],l=t.blockSize/8*t.bits/4,a=Me(s),p=Me(t.n),m=Me(t.k),f=Me(l),b=z.size(n)/p/a,_=[{type:12,data:b},{type:12,data:t.k},{type:12,data:t.n},{type:12,data:t.accuracyLevel},{type:12,data:t.bits},{type:12,data:t.blockSize}],y=r.slice();y.splice(-1,1,t.k/m);let $=z.convertShape(e[1].dims).slice();$.splice(-1,1,l/f),_.push(...j(y)),_.push(...j($)),_.push(...j(e[2].dims)),e.length===4&&_.push(...j(z.convertShape(e[3].dims)));let I=n.slice();I.splice(-1,1,t.n/p),_.push(...j(I));let C=v=>{let A=M("a",e[0].dataType,y.length,m),T=M("b",12,$.length,f),D=M("scales",e[2].dataType,e[2].dims.length),U=[A,T,D],V=e.length===4?M("zero_points",12,e[3].dims.length):void 0;V&&U.push(V);let H=F("output",e[0].dataType,n.length,p),R=[{name:"output_size",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"accuracy_level",type:"u32"},{name:"bits",type:"u32"},{name:"block_size",type:"u32"}],L=Math.floor((t.k+t.blockSize-1)/t.blockSize),pe=Pe(e[0].dataType),Ie=(()=>{switch(m){case 1:return`array<${pe}, 8>`;case 2:return`mat4x2<${pe}>`;case 4:return`mat2x4<${pe}>`;default:throw new Error(`${m}-component is not supported.`)}})(),we=`\n fn dequantize(quantized: ${Ie}, zero_point: ${pe}, scale: ${pe}) -> ${Ie} {\n ${(()=>m===1?`var dequantized = ${Ie}(${Array.from({length:8},(Q,xe)=>`(quantized[${xe}] - zero_point) * scale`).join(", ")});\n return dequantized;`:`var zero_points: ${Ie} = ${Ie}(${Array(8).fill("zero_point").join(",")});\n return (quantized - zero_points) * scale;`)()}\n }`,ne=`\n fn ortUnpack8x4snorm(value: u32) -> ${Ie} {\n var quantized: ${Ie};\n var offset: u32 = 0;\n let count: u32 = 4;\n for (var i: u32 = 0; i < 8u; i++) {\n var result = ${pe}(extractBits(value, offset, count));\n ${(()=>{switch(m){case 1:return"quantized[i] = result;";case 2:return"quantized[i / 2][i % 2] = result;";case 4:return"quantized[i / 4][i % 4] = result;";default:throw new Error(`${m}-component is not supported.`)}})()}\n offset += count;\n }\n return quantized;\n }`,ze=V?`\n zero_point_offset += 4;\n if (zero_point_offset == 32) {\n zero_point_offset = 0;\n zero_point_index++;\n zero_point_word = ${V.getByOffset("zero_point_index")};\n }`:"";return`\n ${we};\n ${ne};\n ${v.registerUniforms(R).declareVariables(...U,H)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var output_values: array<${H.type.value}, ${a}>;\n var output_indices = ${H.offsetToIndices("global_idx")};\n var n = ${H.indicesGet("output_indices",o-1)};\n var m = ${H.indicesGet("output_indices",o-2)};\n var a_indices: ${A.type.indices} = output_indices;\n // Two zero points are packed into one byte because uniforms.bits <= 4.\n // zero_point_offset is either 0 or 4. It is bit offset within one byte.\n // TODO support zero_point_offset for bits > 4\n ${V?`\n var zero_point_index: u32 = n * ${p} * ((${L} + 1) / 2) / 4;\n var zero_point_word: u32 = ${V.getByOffset("zero_point_index")};\n var zero_point_offset: u32 = 0;`:""}\n var scale_index = n * ${L*p};\n var b_indices: ${T.type.indices};\n for (var c: u32 = 0; c < ${p}; c++) {\n ${T.indicesSet("b_indices","0",`n * ${p} + c`)};\n var block_offset: u32 = 0;\n for (var block: u32 = 0; block < ${L}; block++) {\n // The scale and zero points are computed per block.\n let scale = ${D.getByOffset("scale_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${pe}(${V?"extractBits(zero_point_word, zero_point_offset, 4)":8});\n ${T.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block_offset;\n for (var word: u32 = 0; word < ${l}; word += ${f}) {\n ${T.indicesSet("b_indices","2","word")};\n let b_data = ${T.getByIndices("b_indices")};\n for (var i: u32 = 0; i < ${f}; i++) {\n let b_value = ${f===1?"b_data":"b_data[word + i]"};\n let b_quantized_values: ${Ie} = ortUnpack8x4snorm(b_value);\n let b_dequantized_values = dequantize(b_quantized_values, zero_point, scale);\n // Number of B elements per 32-bit word is 32/bits = 32/4 = 8\n var offset: u32 = word_offset;\n for (var j: u32 = 0; j < 8/${m}; j++) {\n ${A.indicesSet("a_indices",o-1,`offset/${m}`)};\n for (var k: u32 = 0; k < ${a}u; k++) {\n ${A.indicesSet("a_indices",o-2,`m * ${a} + k`)};\n let a_data = ${A.getByIndices("a_indices")};\n output_values[k]${p>1?"[c]":""} += ${m===1?"a_data * b_dequantized_values[j]":"dot(a_data, b_dequantized_values[j])"};\n }\n offset += ${m};\n }\n word_offset += 8;\n }\n }\n scale_index++;\n ${ze}\n block_offset += uniforms.block_size;\n }\n // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte.\n ${V?`if (zero_point_offset % 8 > 0) {\n ${ze}\n }`:""}\n }\n for (var k: u32 = 0u; k < ${a}u; k++) {\n ${H.indicesSet("output_indices",o-2,`${a+" * m + k"}`)};\n ${H.setByIndices("output_indices","output_values[k]")}\n }\n }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:_}),getShaderSource:C}},Ws=(e,t)=>{ic(e.inputs,t),e.compute(sc(e.inputs,t))},Gs=e=>$e(e)});var uc,Fs,Ls,dc,oo,qs,Ks=q(()=>{"use strict";ie();_e();je();Gr();Hn();be();Yt();uc=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5],a=e[6],p=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 m=!1,f=r.dims[0],b=r.dims[1],_=r.dims.length===3?m?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=b,$=0,I=0,C=Math.floor(_/t.numHeads);if(a&&p){if(a.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(p.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');$=a.dims[2],I=a.dims[2]}else if(a||p)throw new Error(\'Input "past_key" and "past_value" shall be both present or both absent\');let v;if(o){if(r.dims.length!==3)throw new Error(\'Input "query" is expected to have 3 dimensions when key is given\');if(o.dims.length<3||o.dims.length>5)throw new Error(\'Input "key" is expected to have 3, 4, or 5 dimensions\');if(r.dims[0]!==o.dims[0])throw new Error(\'Input "query" and "key" shall have same dim 0 (batch size)\');if(o.dims.length===3){if(o.dims[2]!==r.dims[2])throw new Error(\'Input "query" and "key" shall have same dim 2 (hidden_size)\');v=2,y=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==C)throw new Error(\'Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv\');if(n)throw new Error(\'Expect "value" be none when "key" has packed kv format.\');v=5,y=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==C)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');v=0,y=o.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\');v=3}if(s){if(s.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(n&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let A=0;if(u){A=8;let H=u.dims;throw H.length===1?H[0]===f?A=1:H[0]===3*f+2&&(A=3):H.length===2&&H[0]===f&&H[1]===y&&(A=5),A===8?new Error(\'Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)\'):new Error("Mask not supported")}let T=!1,D=_;if(n){if(n.dims.length!==3&&n.dims.length!==4)throw new Error(\'Input "value" is expected to have 3 or 4 dimensions\');if(r.dims[0]!==n.dims[0])throw new Error(\'Input "query" and "value" shall have same dim 0 (batch_size)\');if(n.dims.length===3){if(y!==n.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');D=n.dims[2]}else{if(y!==n.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');D=n.dims[1]*n.dims[3],T=!0}}let U=$+y,V=!1;if(u)throw new Error("Key padding mask is not supported");if(l)throw new Error("extraAddQk is not supported");if(a)throw new Error("pastKey is not supported");if(p)throw new Error("pastValue is not supported");return{batchSize:f,sequenceLength:b,pastSequenceLength:$,kvSequenceLength:y,totalSequenceLength:U,maxSequenceLength:I,inputHiddenSize:0,hiddenSize:_,vHiddenSize:D,headSize:C,vHeadSize:Math.floor(D/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:A,scale:t.scale,broadcastResPosBias:V,passPastInKv:T,qkvFormat:v}},Fs=e=>$e({...e}),Ls=$e({perm:[0,2,1,3]}),dc=(e,t,r,o,n,s,u)=>{let l=[o,n,s],a=z.size(l),p=[{type:12,data:a},{type:12,data:u},{type:12,data:s}],m=f=>{let b=F("qkv_with_bias",t.dataType,l),_=M("qkv",t.dataType,l),y=M("bias",r.dataType,l),$=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${f.registerUniforms($).declareVariables(_,y,b)}\n ${f.mainStart()}\n ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},oo=(e,t,r,o,n,s,u,l)=>{let a=s;if(u){if(o===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return a=dc(e,s,u,t,o,r*n,l),a=a.reshape([t,o,r,n]),e.compute(ot(a,Ls.perm),{inputs:[a],outputs:[-1]})[0]}else return s.dims.length===3&&(a=s.reshape([t,o,r,n])),e.compute(ot(a,Ls.perm),{inputs:[a],outputs:[-1]})[0]},qs=(e,t)=>{let r=uc(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 o=e.inputs[1]&&e.inputs[2]&&e.inputs[1].dims.length===4&&e.inputs[2].dims.length===4,n=oo(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],e.inputs[3],0);if(o)return Qr(e,n,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t);let s=oo(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,e.inputs[1],e.inputs[3],r.hiddenSize),u=oo(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,e.inputs[2],e.inputs[3],2*r.hiddenSize);Qr(e,n,s,u,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],r,t)}});var lc,cc,pc,mc,fc,hc,gc,yc,js,Ys=q(()=>{"use strict";ie();_e();be();lc=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].")}},cc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${re("uniforms.x_shape",n,t)})) {\n break;\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n }\n `},pc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${re("uniforms.x_shape",n,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${re("uniforms.x_shape",n,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},mc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${re("uniforms.x_shape",n,t)})) {\n k = i32(${re("uniforms.x_shape",n,t)}) - 1;\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},fc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n k += i32(${re("uniforms.x_shape",n,t)}]);\n }\n if (k >= i32(${re("uniforms.x_shape",n,t)})) {\n k -= i32(${re("uniforms.x_shape",n,t)});\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},hc=(e,t,r)=>{switch(r.mode){case 0:return cc(e,t,r.pads.length);case 1:return pc(e,t,r.pads.length);case 2:return mc(e,t,r.pads.length);case 3:return fc(e,t,r.pads.length);default:throw new Error("Invalid mode")}},gc=(e,t)=>{let r=z.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,n=z.size(r),s=[{type:12,data:n},{type:12,data:t.pads}];t.mode===0&&s.push({type:e[0].dataType,data:t.value}),s.push(...j(e[0].dims,r));let u=["rank"],l=a=>{let p=F("output",e[0].dataType,r.length),m=M("x",e[0].dataType,o.length),f=m.type.value,b=hc(p,o.length,t),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&_.push({name:"constant_value",type:f}),`\n ${a.registerUniforms(_).declareVariables(m,p)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n\n var value = ${f}(0);\n ${b}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(z.size(r)/64)},programUniforms:s}),getShaderSource:l}},yc=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),o=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,n=e[0].dims.length,s=new Int32Array(2*n).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let a=0;as[Number(a)]=Number(l));let u=[];return s.forEach(l=>u.push(l)),{mode:t.mode,value:o,pads:u}}else return t},js=(e,t)=>{lc(e.inputs);let r=yc(e.inputs,t);e.compute(gc(e.inputs,r),{inputs:[0]})}});var dn,Zs,Qs,Xs,Js,bc,wc,eu,tu,ru,nu,ou,au,iu,su,uu,du,lu,cu,pu=q(()=>{"use strict";Kt();ie();_e();be();dn=e=>{if(qt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Zs=(e,t,r)=>{let o=t.format==="NHWC",n=e.dims.slice();o&&n.splice(1,0,n.pop());let s=Object.hasOwnProperty.call(t,"dilations"),u=t.kernelShape.slice(),l=t.strides.slice(),a=s?t.dilations.slice():[],p=t.pads.slice();zt.adjustPoolAttributes(r,n,u,l,a,p);let m=zt.computePoolOutputShape(r,n,l,a,u,p,t.autoPad),f=Object.assign({},t);s?Object.assign(f,{kernelShape:u,strides:l,pads:p,dilations:a,cacheKey:t.cacheKey}):Object.assign(f,{kernelShape:u,strides:l,pads:p,cacheKey:t.cacheKey});let b=m.slice();return b.push(b.splice(1,1)[0]),[f,o?b:m]},Qs=(e,t)=>{let r=t.format==="NHWC",o=z.size(e),n=z.size(t.kernelShape),s=[{type:12,data:o},{type:12,data:n}],u=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],a=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],f=!!(p+m);s.push({type:12,data:l},{type:12,data:a},{type:12,data:p},{type:12,data:m}),u.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let b=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],$=t.pads[t.pads.length/2-2],I=t.pads[t.pads.length-2];b=!!($+I),s.push({type:12,data:_},{type:12,data:y},{type:12,data:$},{type:12,data:I}),u.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[s,u,!0,f,b]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=z.computeStrides(t.kernelShape);s.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),u.push({name:"kernelStrides",type:"u32",length:l.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let a=t.pads.reduce((p,m)=>p+m);return[s,u,!!a,!1,!1]}},Xs=(e,t,r,o,n,s,u,l,a,p,m,f)=>{let b=n.format==="NHWC",_=t.type.value,y=F("output",t.type.tensor,o);if(n.kernelShape.length<=2){let $="",I="",C="",v=r-(b?2:1);if(m?$=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${v}] < 0 || xIndices[${v}]\n >= uniforms.x_shape[${v}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:$=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`,n.kernelShape.length===2){let T=r-(b?3:2);f?I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n `,C=`\n }\n `}return`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var value = ${_}(${l});\n var pad = 0;\n ${I}\n ${$}\n ${C}\n ${u}\n\n output[global_idx] = value;\n }`}else{if(b)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let $=n.kernelShape.length,I=n.pads.length,C="";return p?C=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:C=`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n `,`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${_}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${$-1}u; j++) {\n offsets[j] = offset / ${re("uniforms.kernelStrides","j",$)};\n offset -= offsets[j] * ${re("uniforms.kernelStrides","j",$)};\n }\n offsets[${$-1}] = offset;\n\n isPad = false;\n for (var j = ${r-$}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${re("uniforms.strides",`j - ${r-$}u`,$)}\n + offsets[j - ${r-$}u] - ${re("uniforms.pads","j - 2u",I)};\n ${C}\n }\n ${u}\n\n output[global_idx] = value;\n }`}},Js=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bc=e=>`${Js(e)};${e.countIncludePad}`,wc=e=>`${Js(e)};${e.storageOrder};${e.dilations}`,eu=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}),tu=(e,t,r,o)=>{let[n,s]=Zs(t,o,r),u=M("x",t.dataType,t.dims.length),l=u.type.value,a="value += x_val;",p="";n.countIncludePad?p+=`value /= ${l}(uniforms.kernelSize);`:p+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,f,b,_,y]=Qs(s,n);m.push(...j(t.dims,s));let $=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${b};${_};${y}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(z.size(s)/64)},programUniforms:m}),getShaderSource:I=>Xs(I,u,t.dims.length,s.length,n,a,p,0,f,b,_,y)}},ru=e=>{let t=e.count_include_pad!==0,r=eu(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let o={countIncludePad:t,...r,cacheKey:""};return{...o,cacheKey:bc(o)}},nu=(e,t)=>{dn(e.inputs),e.compute(tu("AveragePool",e.inputs[0],!1,t))},ou={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},au=e=>{let t=e.format;return{format:t,...ou,cacheKey:t}},iu=(e,t)=>{dn(e.inputs),e.compute(tu("GlobalAveragePool",e.inputs[0],!0,t))},su=(e,t,r,o)=>{let[n,s]=Zs(t,o,r),u=`\n value = max(x_val, value);\n `,l="",a=M("x",t.dataType,t.dims.length),p=["rank"],[m,f,b,_,y]=Qs(s,n);return m.push(...j(t.dims,s)),{name:e,shaderCache:{hint:`${o.cacheKey};${b};${_};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(z.size(s)/64)},programUniforms:m}),getShaderSource:$=>Xs($,a,t.dims.length,s.length,n,u,l,t.dataType===10?-65504:-1e5,f,b,_,y)}},uu=(e,t)=>{dn(e.inputs),e.compute(su("MaxPool",e.inputs[0],!1,t))},du=e=>{let t=e.storage_order,r=e.dilations,o=eu(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(o.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:t,dilations:r,...o,cacheKey:""};return{...n,cacheKey:wc(n)}},lu=e=>{let t=e.format;return{format:t,...ou,cacheKey:t}},cu=(e,t)=>{dn(e.inputs),e.compute(su("GlobalMaxPool",e.inputs[0],!0,t))}});var $c,_c,mu,fu=q(()=>{"use strict";Kt();ie();be();$c=(e,t,r)=>{let o=e===t,n=et&&r>0;if(o||n||s)throw new Error("Range these inputs\' contents are invalid.")},_c=(e,t,r,o)=>{let n=Math.abs(Math.ceil((t-e)/r)),s=[n],u=n,l=[{type:12,data:u},{type:o,data:e},{type:o,data:r},...j(s)],a=p=>{let m=F("output",o,s.length),f=m.type.value,b=[{name:"outputSize",type:"u32"},{name:"start",type:f},{name:"delta",type:f}];return`\n ${p.registerUniforms(b).declareVariables(m)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${f}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:a,getRunData:()=>({outputs:[{dims:s,dataType:o}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l})}},mu=e=>{let t=0,r=0,o=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],o=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],o=e.inputs[2].getFloat32Array()[0]),qt.webgpu.validateInputContent&&$c(t,r,o),e.compute(_c(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var xc,Sc,Cc,Ic,Ac,Tc,Ec,Pc,Oc,kc,Rc,hu,Bc,Dc,Mc,zc,Uc,gu,yu,bu=q(()=>{"use strict";ie();_e();je();be();xc=(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\n 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")}},Sc=(e,t,r)=>{t.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let o=new Array(r).fill(1);return t.forEach((n,s)=>o[n]=e[s]),o},Cc=(e,t,r,o,n,s)=>{let[u,l,a]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(u>0&&e.length>u&&e[u].dims.length>0)e[u].getFloat32Array().forEach(m=>s.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(l>0&&e.length>l&&e[l].dims.length>0){if(e[l].getFloat32Array().forEach(m=>o.push(m)),o.length!==0&&o.length!==p&&r>=18&&o.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");xc(o,t),t.axes.length>0&&Sc(o,t.axes,p).forEach((m,f)=>o[f]=m)}if(a>0&&e.length>a&&(e[a].getBigInt64Array().forEach(m=>n.push(Number(m))),n.length!==p||r>=18&&n.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(o.length!==t.axes.length)throw new Error(\'Resize requires "scales" input size to be of axes rank when axes attributes is specified\');if(n.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 o<"u"&&typeof n<"u"&&o.length>0&&n.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},Ic=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n 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) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n 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`)}})()+"}",Ac=(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`)}})()+"}",Tc=(e,t,r)=>{let o=new Array(r).fill(0).concat(new Array(r).fill(1)),n=e.length===0?o:e.slice();return t.length>0?(t.forEach((s,u)=>{o[s]=n[u],o[u+r]=n[t.length+u]}),o):n},Ec=(e,t,r,o)=>{let n=[];if(r.length>0)if(o.length>0){if(e.forEach(s=>n.push(s)),Math.max(...o)>e.length)throw new Error("axes is out of bound");o.forEach((s,u)=>n[s]=r[u])}else r.forEach(s=>n.push(s));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((s,u)=>Math.round(s*t[u]))}return n},Pc=(e,t,r)=>{let o=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(s=>t[s]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(s=>t[s]),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 n=e.slice();return r.axes.length>0?(r.axes.forEach(s=>t[s]=o),r.axes.forEach(s=>n[s]=Math.round(e[s]*t[s]))):(t.fill(o,0,t.length),n.forEach((s,u)=>n[u]=Math.round(s*t[u]))),n},Oc=(e,t,r,o,n)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${re("uniforms.scales","i",o)};\n var roi_low = ${re("uniforms.roi","i",n)};\n var roi_hi = ${re("uniforms.roi",`i + ${t.length}`,n)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${re("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${re("uniforms.output_shape","i",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,kc=(e,t,r,o,n,s,u)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${o.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${re("uniforms.scales","i",n)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${re("uniforms.roi","i",s)};\n var roi_hi = ${re("uniforms.roi",`i + ${r.length}`,s)};\n var input_shape_i = ${re("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${re("uniforms.output_shape","i",o.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${u} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,Rc=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${re("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,hu=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",Bc=(e,t,r,o,n)=>{let[u,l,a,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(col, ${r[a]} - 1))`)};\n ${hu(e,p,u,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${m} = originalIndices[${l}];\n var col:${m} = originalIndices[${a}];\n ${o?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[a]} - 1)) {\n return ${n};\n }`:""};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[a]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${u}])`:"0"};\n var x11: ${m} = getInputValue(batch, channel, row1, col1);\n var x12: ${m} = getInputValue(batch, channel, row1, col2);\n var x21: ${m} = getInputValue(batch, channel, row2, col1);\n var x22: ${m} = getInputValue(batch, channel, row2, col2);\n var dx1: ${m} = abs(row - ${m}(row1));\n var dx2: ${m} = abs(${m}(row2) - row);\n var dy1: ${m} = abs(col - ${m}(col1));\n var dy2: ${m} = abs(${m}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Dc=(e,t,r,o,n,s,u,l,a,p)=>{let m=r.length===2,f=!0,[b,_]=m?[0,1]:f?[2,3]:[1,2],y=e.type.value,$=I=>{let C=I===b?"row":"col";return`\n fn ${C}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet("output_indices",I)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[I]},\n ${o[I]}, ${r[I]}, ${s[I]}, ${s[I]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[I]} - 1))) {\n return ${a};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${C}: ${y} = originalIdx + ${y}(i);\n if (${C} < 0 || ${C} >= ${r[I]}) {\n ${(()=>p?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${a};`:`${C} = max(0, min(${C}, ${r[I]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",I,`u32(${C})`)};\n data[i + 1] = ${I===b?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${$(b)};\n ${$(_)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};\n coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;\n coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${u} * twoMinusAbsS - 5 * ${u}) * twoMinusAbsS + 8 * ${u}) * twoMinusAbsS - 4 * ${u};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Mc=(e,t,r,o,n)=>{let[u,l,a,p,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],f=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${f} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(height, ${r[a]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)};\n ${hu(e,m,u,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${f} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${f} = originalIndices[${l}];\n var height:${f} = originalIndices[${a}];\n var width:${f} = originalIndices[${p}];\n ${o?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[a]} - 1) || width < 0 || (width > ${r[p]} - 1)) {\n return ${n};\n }`:""};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[a]} - 1));\n width = max(0, min(width, ${r[p]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${m}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${u}])`:"0"};\n\n var x111: ${f} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${f} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${f} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${f} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${f} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${f} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${f} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${f} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${f} = abs(depth - ${f}(depth1));\n var dx2: ${f} = abs(${f}(depth2) - depth);\n var dy1: ${f} = abs(height - ${f}(height1));\n var dy2: ${f} = abs(${f}(height2) - height);\n var dz1: ${f} = abs(width - ${f}(width1));\n var dz2: ${f} = abs(${f}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},zc=(e,t,r,o,n,s)=>{let u=e.dims,l=Tc(s,t.axes,u.length),a=Ec(u,o,n,t.axes),p=o.slice();o.length===0&&(p=u.map((v,A)=>v===0?1:a[A]/v),t.keepAspectRatioPolicy!=="stretch"&&(a=Pc(u,p,t)));let m=F("output",e.dataType,a.length),f=M("input",e.dataType,u.length),b=z.size(a),_=u.length===a.length&&u.every((v,A)=>v===a[A]),y=t.coordinateTransformMode==="tf_crop_and_resize",$=t.extrapolationValue,I=f.type.value,C=v=>`\n ${_?"":`\n ${Ic(t.coordinateTransformMode,I)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Rc(f,u)};\n ${Ac(t.nearestMode,r,I)};\n ${kc(f,m,u,a,p.length,l.length,y)};\n `;case"linear":return`\n ${Oc(m,u,a,p.length,l.length)};\n ${(()=>{if(u.length===2||u.length===4)return`${Bc(f,m,u,y,$)}`;if(u.length===3||u.length===5)return`${Mc(f,m,u,y,$)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(u.length===2||u.length===4)return`${Dc(f,m,u,a,p,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${v.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",l.length).declareVariables(f,m)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${_?"output[global_idx] = input[global_idx];":`\n let output_indices = ${m.offsetToIndices("global_idx")};\n var input_indices: ${f.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${f.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${u.length===2||u.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${n.length>0?n:""}|${l.length>0?l:""}|${_}|${u}`,inputDependencies:["rank"]},getShaderSource:C,getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:12,data:b},{type:1,data:p},{type:1,data:l},...j(u,a)]})}},Uc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},gu=(e,t)=>{let r=[],o=[],n=[],s=Uc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Cc(e.inputs,t,s,r,o,n),e.compute(zc(e.inputs[0],t,s,r,o,n),{inputs:[0]})},yu=e=>{let t=e.antialias,r=e.axes,o=e.coordinateTransformMode,n=e.cubicCoeffA,s=e.excludeOutside!==0,u=e.extrapolationValue,l=e.keepAspectRatioPolicy,a=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return $e({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:n,excludeOutside:s,extrapolationValue:u,keepAspectRatioPolicy:l,mode:a,nearestMode:p})}});var Vc,Nc,wu,vu=q(()=>{"use strict";ie();_e();be();Vc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],o=e[2];if(t.dataType!==r.dataType||t.dataType!==o.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 n=t.dims[t.dims.length-1],s=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==s)throw new Error("Skip must have the same sequence length as input");if(o.dims.length!==1)throw new Error("Gamma must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let u=e[3];if(u.dims.length!==1)throw new Error("Beta must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let u=e[4];if(u.dims.length!==1)throw new Error("Bias must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},Nc=(e,t,r,o)=>{let n=e[0].dims,s=z.size(n),u=n,l=s,a=n.slice(-1)[0],p=o?n.slice(0,-1).concat(1):[],m=e.length>3,f=e.length>4,b=o&&r>1,_=o&&r>2,y=r>3,$=Me(a),I=[{type:12,data:l},{type:12,data:$},{type:12,data:a},{type:1,data:t.epsilon}],C=A=>{let T=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],D=[M("x",e[0].dataType,e[0].dims,$),M("skip",e[1].dataType,e[1].dims,$),M("gamma",e[2].dataType,e[2].dims,$)];m&&D.push(M("beta",e[3].dataType,e[3].dims,$)),f&&D.push(M("bias",e[4].dataType,e[4].dims,$)),D.push(F("output",e[0].dataType,u,$)),b&&D.push(F("mean_output",1,p)),_&&D.push(F("inv_std_output",1,p)),y&&D.push(F("input_skip_bias_sum",e[0].dataType,u,$));let U=Pe(e[0].dataType);return`\n\n ${A.registerUniforms(T).declareVariables(...D)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")}\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n let offset = global_idx * hidden_size_vectorized;\n var sum = ${Ye("f32",$)};\n var squareSum = ${Ye("f32",$)};\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${f?"bias[i]":"0.0"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${y?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${st(U,$,"value")};\n sum += f32_value;\n squareSum += f32_value * f32_value;\n }\n let mean = ${tt("sum",$)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${tt("squareSum",$)} / f32(uniforms.hidden_size) - mean * mean + uniforms.epsilon);\n ${b?"mean_output[global_idx] = mean;":""}\n ${_?"inv_std_output[global_idx] = inv_std_dev;":""}\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n output[offset + i] = (output[offset + i] - ${U}(mean)) * ${U}(inv_std_dev) * gamma[i] + ${m?"beta[i]":"0.0"};\n }\n }`},v=[{dims:u,dataType:e[0].dataType}];return r>1&&v.push({dims:p,dataType:1}),r>2&&v.push({dims:p,dataType:1}),r>3&&v.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${$};${b};${_};${y}`,inputDependencies:e.map((A,T)=>"type")},getShaderSource:C,getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(l/a/64)},programUniforms:I})}},wu=(e,t)=>{Vc(e.inputs);let o=[0];e.outputCount>1&&o.push(-3),e.outputCount>2&&o.push(-3),e.outputCount>3&&o.push(3),e.compute(Nc(e.inputs,t,e.outputCount,!1),{outputs:o})}});var Wc,ln,Gc,$u,Hc,Lc,_u,xu,Su=q(()=>{"use strict";ie();_e();je();be();Wc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,o)=>{if(e[o+1].dataType!==6&&e[o+1].dataType!==7)throw new Error(`Input ${o} must be an array of int32 or int64`)})},ln=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(o=>r.push(Number(o)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(o=>r.push(Number(o)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Gc=(e,t)=>{if(e.length>1){let r=ln(e,1),o=ln(e,2),n=ln(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),$e({starts:r,ends:o,axes:n})}else return t},$u=(e,t,r,o,n)=>{let s=e;return e<0&&(s+=r[o[t]]),n[t]<0?Math.max(0,Math.min(s,r[o[t]]-1)):Math.max(0,Math.min(s,r[o[t]]))},Hc=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${re("uniforms.input_shape","i",r.length)};\n let steps_i = ${re("uniforms.steps","i",r.length)};\n let signs_i = ${re("uniforms.signs","i",r.length)};\n let starts_i = ${re("uniforms.starts","i",r.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,Lc=(e,t)=>{let r=e[0].dims,o=z.size(r),n=t.axes.length>0?z.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],s=ln(e,4);s.forEach(C=>C!==0||(()=>{throw new Error("step cannot be 0")})),s.length===0&&(s=Array(n.length).fill(1));let u=t.starts.map((C,v)=>$u(C,v,r,n,s)),l=t.ends.map((C,v)=>$u(C,v,r,n,s));if(n.length!==u.length||n.length!==l.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==r.length)for(let C=0;CMath.sign(C));s.forEach((C,v,A)=>{if(C<0){let T=(l[v]-u[v])/C,D=u[v],U=D+T*s[v];u[v]=U,l[v]=D,A[v]=-C}});let p=r.slice(0);n.forEach((C,v)=>{p[C]=Math.ceil((l[C]-u[C])/s[C])});let m={dims:p,dataType:e[0].dataType},f=F("output",e[0].dataType,p.length),b=M("input",e[0].dataType,e[0].dims.length),_=z.size(p),y=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:u.length},{name:"signs",type:"i32",length:a.length},{name:"steps",type:"u32",length:s.length}],$=[{type:12,data:_},{type:12,data:u},{type:6,data:a},{type:12,data:s},...j(e[0].dims,p)],I=C=>`\n ${C.registerUniforms(y).declareVariables(b,f)}\n ${Hc(b,f,r)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${f.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${f.setByOffset("global_idx",b.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${a.length}_${u.length}_${s.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:$})}},_u=(e,t)=>{Wc(e.inputs,t);let r=Gc(e.inputs,t);e.compute(Lc(e.inputs,r),{inputs:[0]})},xu=e=>{let t=e.starts,r=e.ends,o=e.axes;return $e({starts:t,ends:r,axes:o})}});var Fc,qc,Cu,Iu,Au=q(()=>{"use strict";ie();_e();je();be();Fc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},qc=(e,t)=>{let r=e.dims,o=z.size(r),n=64,s=t.axis;if(s<0&&(s=r.length+s),sC===4?`max(max(${I}.x, ${I}.y), max(${I}.z, ${I}.w))`:C===2?`max(${I}.x, ${I}.y)`:C===3?`max(max(${I}.x, ${I}.y), ${I}.z)`:I,f=M("x",e.dataType,e.dims,a),b=F("result",e.dataType,e.dims,a),_=f.type.value,y=Pe(e.dataType)==="f32"?`var threadMax = ${_}(-3.402823e+38f);`:`var threadMax = ${_}(-65504.0h);`,$=I=>`\n var rowMaxShared : ${_};\n var rowSumShared : ${_};\n var threadShared : array<${_}, ${n}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${_} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${_}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${I.registerUniform("packedCols","i32").declareVariables(f,b)}\n ${I.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${n};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${y}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${_}(${m("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${_}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${_}(${tt("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`;return{name:"Softmax",shaderCache:{hint:`${a}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:l},programUniforms:[{type:12,data:p}]}),getShaderSource:$}},Cu=(e,t)=>{Fc(e.inputs),e.compute(qc(e.inputs[0],t))},Iu=e=>$e({axis:e.axis})});var Kc,jc,Yc,Zc,Qc,Tu,Eu,Pu=q(()=>{"use strict";ie();_e();je();be();Kc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},jc=(e,t)=>{let r=[],o=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),o=r.length),$e({numOutputs:o,axis:t.axis,splitSizes:r})},Yc=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${re("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Zc=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=z.size(r),n=e[0].dataType,s=z.normalizeAxis(t.axis,r.length),u=new Array(t.numOutputs),l=M("input",n,r.length),a=new Array(t.numOutputs),p=[],m=[],f=0,b=[{type:12,data:o}];for(let y=0;y`\n ${y.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",a.length).declareVariables(l,...u)}\n ${Yc(a.length)}\n ${Zc(u)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${l.offsetToIndices("global_idx")};\n var index = ${l.indicesGet("indices",s)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${re("uniforms.size_in_split_axis","output_number - 1u",a.length)};\n ${l.indicesSet("indices",s,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:b})}},Tu=(e,t)=>{Kc(e.inputs);let r=e.inputs.length===1?t:jc(e.inputs,t);e.compute(Qc(e.inputs,r),{inputs:[0]})},Eu=e=>{let t=e.axis,r=e.splitSizes,o=e.numOutputs<0?r.length:e.numOutputs;if(o!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return $e({axis:t,numOutputs:o,splitSizes:r})}});var Ou,Xc,Jc,ep,ku,Ru=q(()=>{"use strict";ie();_e();be();Ou=e=>Array.from(e.getBigInt64Array(),Number),Xc=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, 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(Ou(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")},Jc=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=Ou(e[1]),o=Jc(t,r),n=z.size(o),s=e[0].dataType,u=M("input",s,t.length),l=F("output",s,o.length),a=p=>`\n const inputShape = ${u.indices(...t)};\n ${p.registerUniform("output_size","u32").declareVariables(u,l)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${l.offsetToIndices("global_idx")};\n var input_indices: ${u.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i;\n\n ${u.indicesSet("input_indices","i","input_dim_value")}\n }\n ${l.setByOffset("global_idx",u.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...j(e[0].dims,o)]}),getShaderSource:a}},ku=e=>{Xc(e.inputs),e.compute(ep(e.inputs),{inputs:[0]})}});var tp,rp,Bu,Du=q(()=>{"use strict";ie();_e();be();tp=(e,t,r,o,n)=>{let s=F("output_data",n,r.length,4),u=M("a_data",t[1].dataType,t[1].dims.length,4),l=M("b_data",t[2].dataType,t[2].dims.length,4),a=M("c_data",t[0].dataType,t[0].dims.length,4),p,m=(f,b,_)=>`select(${b}, ${f}, ${_})`;if(!o)p=s.setByOffset("global_idx",m(u.getByOffset("global_idx"),l.getByOffset("global_idx"),a.getByOffset("global_idx")));else{let f=(b,_,y="")=>{let $=`a_data[index_a${_}][component_a${_}]`,I=`b_data[index_b${_}][component_b${_}]`,C=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`\n let output_indices${_} = ${s.offsetToIndices(`global_idx * 4u + ${_}u`)};\n let offset_a${_} = ${u.broadcastedIndicesToOffset(`output_indices${_}`,s)};\n let offset_b${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,s)};\n let offset_c${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,s)};\n let index_a${_} = offset_a${_} / 4u;\n let index_b${_} = offset_b${_} / 4u;\n let index_c${_} = offset_c${_} / 4u;\n let component_a${_} = offset_a${_} % 4u;\n let component_b${_} = offset_b${_} % 4u;\n let component_c${_} = offset_c${_} % 4u;\n ${b}[${_}] = ${y}(${m($,I,C)});\n `};n===9?p=`\n var data = vec4(0);\n ${f("data",0,"u32")}\n ${f("data",1,"u32")}\n ${f("data",2,"u32")}\n ${f("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=`\n ${f("output_data[global_idx]",0)}\n ${f("output_data[global_idx]",1)}\n ${f("output_data[global_idx]",2)}\n ${f("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,u,l,s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${p}\n }`},rp=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,n=e[1].dataType,s=!(z.areEqual(t,r)&&z.areEqual(r,o)),u=t,l=z.size(t);if(s){let p=mt.calcShape(mt.calcShape(t,r,!1),o,!1);if(!p)throw new Error("Can\'t perform where op on the given tensors");u=p,l=z.size(u)}let a=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>tp(p,e,u,s,n),getRunData:()=>({outputs:[{dims:u,dataType:n}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:a},...j(o,t,r,u)]})}},Bu=e=>{e.compute(rp(e.inputs))}});var Mu,zu=q(()=>{"use strict";Qa();Hn();ei();ri();Ni();Qi();es();jn();fs();ys();_s();Cs();As();Ps();Rs();Ms();Us();Ns();Zn();Hs();Ks();Ys();pu();fu();Yr();bu();vu();Su();Au();Pu();Ru();Yt();en();Du();Mu=new Map([["Abs",[ni]],["Acos",[oi]],["Acosh",[ai]],["Add",[Wi]],["ArgMax",[Za,Gn]],["ArgMin",[Ya,Gn]],["Asin",[ii]],["Asinh",[si]],["Atan",[ui]],["Atanh",[di]],["Attention",[Xa]],["AveragePool",[nu,ru]],["BatchNormalization",[Ja]],["BiasAdd",[ti]],["BiasSplitGelu",[Vi]],["Cast",[ci,li]],["Ceil",[mi]],["Clip",[pi]],["Concat",[Xi,Ji]],["Conv",[Jn,Xn]],["ConvTranspose",[ms,ps]],["Cos",[fi]],["Cosh",[hi]],["CumSum",[hs,gs]],["Div",[Gi]],["Einsum",[vs,$s]],["Elu",[gi,Xr]],["Equal",[Hi]],["Erf",[yi]],["Exp",[bi]],["Expand",[Ss]],["FastGelu",[Is]],["Floor",[wi]],["FusedConv",[Jn,Xn]],["Gather",[Es,Ts]],["GatherElements",[ks,Os]],["Gelu",[vi]],["Gemm",[Ds,Bs]],["GlobalAveragePool",[iu,au]],["GlobalMaxPool",[cu,lu]],["Greater",[Ki]],["GreaterOrEqual",[Yi]],["HardSigmoid",[Ti,Ai]],["InstanceNormalization",[zs]],["LayerNormalization",[Vs]],["LeakyRelu",[$i,Xr]],["Less",[ji]],["LessOrEqual",[Zi]],["Log",[zi]],["MatMul",[is]],["MatMulNBits",[Ws,Gs]],["MaxPool",[uu,du]],["Mul",[Li]],["MultiHeadAttention",[qs,Fs]],["Neg",[xi]],["Not",[_i]],["Pad",[js]],["Pow",[Fi]],["Range",[mu]],["Reciprocal",[Si]],["ReduceMin",[Ha]],["ReduceMean",[Ua]],["ReduceMax",[Ga]],["ReduceSum",[Fa]],["ReduceProd",[La]],["ReduceL1",[Va]],["ReduceL2",[Na]],["ReduceLogSum",[Ka]],["ReduceLogSumExp",[Wa]],["ReduceSumSquare",[qa]],["Relu",[Ci]],["Resize",[gu,yu]],["Sigmoid",[Ii]],["Sin",[Ei]],["Sinh",[Pi]],["Slice",[_u,xu]],["SkipLayerNormalization",[wu]],["Split",[Tu,Eu]],["Sqrt",[Oi]],["Softmax",[Cu,Iu]],["Sub",[qi]],["Tan",[ki]],["Tanh",[Bi]],["ThresholdedRelu",[Mi,Xr]],["Tile",[ku]],["Transpose",[Ca,Ia]],["Where",[Bu]]])});var cn,Uu=q(()=>{"use strict";Kt();Pt();be();cn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,o,n,s){Mt(t.programInfo.name);let u=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let m of r)a.push({binding:a.length,resource:{buffer:m.buffer}});for(let m of o)a.push({binding:a.length,resource:{buffer:m.buffer}});s&&a.push({binding:a.length,resource:s});let p=u.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:a,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,p),l.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(),Et(t.programInfo.name)}dispose(){}build(t,r){Mt(t.name);let o=this.backend.device,n=[];o.features.has("shader-f16")&&n.push("enable f16;");let s=xa(r),u=t.getShaderSource(s),l=`${n.join(`\n`)}\n${s.additionalImplementations}\n${u}`,a=o.createShaderModule({code:l,label:t.name});De("verbose",()=>`[WebGPU] ${t.name} shader code: ${l}`);let p=o.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:t.name});return Et(t.name),{programInfo:t,computePipeline:p}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,o=typeof t=="number"?1:t.y||1,n=typeof t=="number"?1:t.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=s&&o<=s&&n<=s)return[r,o,n];let u=r*o*n,l=Math.ceil(Math.sqrt(u));if(l>s){if(l=Math.ceil(Math.cbrt(u)),l>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}});var np,op,ao,pn,Vu=q(()=>{"use strict";Kt();ie();Pt();ba();_a();zu();Uu();np=(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 o=0;o{let o=e.name;return e.shaderCache?.hint&&(o+="["+e.shaderCache.hint+"]"),o+=":"+r+`:${np(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},ao=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},pn=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 t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let o=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:o};r.features.has("chromium-experimental-timestamp-query-inside-passes")?o.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&o.push("timestamp-query"),r.features.has("shader-f16")&&o.push("shader-f16"),this.device=await r.requestDevice(n),this.adapterInfo=new ao(await r.requestAdapterInfo()),this.gpuDataManager=$a(this),this.programManager=new cn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ga(t.logLevel,!!t.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,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 t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Mt(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),o=this.pendingQueries.get(t);for(let n=0;n"u"&&(this.queryTimeBase=_);let $=Number(_-this.queryTimeBase),I=Number(y-this.queryTimeBase);if(!Number.isSafeInteger($)||!Number.isSafeInteger(I))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:f.map(C=>({dims:C.dims,dataType:Tt(C.dataType)})),outputsMetadata:b.map(C=>({dims:C.dims,dataType:Tt(C.dataType)})),kernelId:u,kernelType:a,kernelName:p,programName:m,startTime:$,endTime:I});else{let C="";f.forEach((A,T)=>{C+=`input[${T}]: [${A.dims}] | ${Tt(A.dataType)}, `});let v="";b.forEach((A,T)=>{v+=`output[${T}]: [${A.dims}] | ${Tt(A.dataType)}, `}),console.log(`[profiling] kernel "${u}|${a}|${p}|${m}" ${C}${v}execution time: ${I-$} ns`)}kn("GPU",`${m}::${_}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Et()}run(t,r,o,n,s){Mt(t.name);let u=[];for(let v=0;vA):o;if(m.length!==l.length)throw new Error(`Output size ${m.length} must be equal to ${l.length}.`);let f=[],b=[];for(let v=0;v=l.length)throw new Error(`Invalid output index: ${m[v]}`);if(m[v]===-3)continue;let A=m[v]===-1,T=m[v]===-2,D=A||T?s(l[v].dataType,l[v].dims):n(m[v],l[v].dataType,l[v].dims);if(f.push(D),D.data===0)continue;let U=this.gpuDataManager.get(D.data);if(!U)throw new Error(`no GPU data for output: ${D.data}`);if(A&&this.temporaryData.push(U),T){let V=this.kernelPersistentData.get(this.currentKernelId);V||(V=[],this.kernelPersistentData.set(this.currentKernelId,V)),V.push(U)}b.push(U)}if(u.length!==r.length||b.length!==f.length){if(b.length===0)return Et(t.name),f;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(p){let v=0,A=[];p.forEach(V=>{let H=typeof V.data=="number"?[V.data]:V.data;if(H.length===0)return;let R=V.type===10?2:4,L,pe;V.type===10?(pe=H.length>4?16:H.length>2?8:H.length*R,L=H.length>4?16:R*H.length):(pe=H.length<=2?H.length*R:16,L=16),v=Math.ceil(v/pe)*pe,A.push(v);let Ie=V.type===10?8:4;v+=H.length>4?Math.ceil(H.length/Ie)*L:H.length*R});let T=16;v=Math.ceil(v/T)*T;let D=new ArrayBuffer(v);p.forEach((V,H)=>{let R=A[H],L=typeof V.data=="number"?[V.data]:V.data;if(V.type===6)new Int32Array(D,R,L.length).set(L);else if(V.type===12)new Uint32Array(D,R,L.length).set(L);else if(V.type===10)new Uint16Array(D,R,L.length).set(L);else if(V.type===1)new Float32Array(D,R,L.length).set(L);else throw new Error(`Unsupported uniform type: ${Tt(V.type)}`)});let U=this.gpuDataManager.create(v,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(U.buffer,0,D,0,v),this.gpuDataManager.release(U.id),_={offset:0,size:v,buffer:U.buffer}}let y=this.programManager.normalizeDispatchGroupSize(a),$=y[1]===1&&y[2]===1,I=op(t,r,$),C=this.programManager.getArtifact(I);if(C||(C=this.programManager.build(t,y),this.programManager.setArtifact(I,C),De("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),De("info",()=>`[ProgramManager] run "${t.name}" (key=${I}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let v={kernelId:this.currentKernelId,programName:C.programInfo.name,inputTensorViews:r,outputTensorViews:f};this.pendingKernels.push(v),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(v)}return this.programManager.run(C,u,b,y,_),Et(t.name),f}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,o,n){let s=Mu.get(t);if(!s)throw new Error(`kernel not implemented: ${t}`);let u={kernelType:t,kernelName:n,kernelEntry:s[0],attributes:[s[1],o]};this.kernels.set(r,u)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let o of r)this.gpuDataManager.release(o.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,o){let n=this.kernels.get(t);if(!n)throw new Error(`kernel not created: ${t}`);let s=n.kernelType,u=n.kernelName,l=n.kernelEntry,a=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${u}" is not allowed to be called recursively`);this.currentKernelId=t,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),De("info",()=>`[WebGPU] Start to run kernel "[${s}] ${u}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),l(r,a[1]),0}catch(m){return o.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${u}" failed. ${m}`)),1}finally{p&&o.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel "[${s}] ${u}": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,o,n){let s=this.sessionExternalDataMapping.get(t);s||(s=new Map,this.sessionExternalDataMapping.set(t,s));let u=s.get(r),l=this.gpuDataManager.registerExternalBuffer(o,n,u?.[1]);return s.set(r,[l,o]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(o=>this.gpuDataManager.unregisterExternalBuffer(o[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,o){return async()=>{let n=await Dn(this,t,r);return ya(n.buffer,o)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}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(){De("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(){De("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){De("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),o=t.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var Nu={};Mr(Nu,{init:()=>ap});var wr,io,ap,Wu=q(()=>{"use strict";ie();Vu();Pt();_e();wr=class e{constructor(t,r,o,n){this.module=t;this.dataType=r;this.data=o;this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=z.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=z.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=z.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(z.size(t)!==z.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},io=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let n=t.HEAPU32,s=o>>>2;this.opKernelContext=n[s++];let u=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let l=[];for(let a=0;atypeof l=="number"?this.inputs[l]:l)??this.inputs,n=r?.outputs??[],s=(l,a,p)=>new wr(this.module,a,this.output(l,p),p),u=(l,a)=>{let p=fr(l);if(!p)throw new Error(`Unsupported data type: ${l}`);let m=p*z.size(a),f=m>0?this.backend.gpuDataManager.create(m).id:0;return new wr(this.module,l,f,a)};return this.backend.run(t,o,n,s,u)}output(t,r){let o=this.module.stackSave();try{let n=this.module.stackAlloc((1+r.length)*4),s=n>>2;this.module.HEAPU32[s++]=r.length;for(let u=0;u{let n=t.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let s=new pn;await s.initialize(r,o),n("webgpu",[s,u=>s.alloc(u),u=>s.free(u),(u,l,a,p=!1)=>{if(p)De("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${u}, dst=${l}, size=${a}`),s.memcpy(u,l);else{De("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${u}, gpuDataId=${l}, size=${a}`);let m=t.HEAPU8.subarray(u>>>0,(u>>>0)+a);s.upload(l,m)}},async(u,l,a)=>{De("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${u}, dataOffset=${l}, size=${a}`),await s.download(u,()=>t.HEAPU8.subarray(l>>>0,(l>>>0)+a))},(u,l,a)=>s.createKernel(u,l,a,t.UTF8ToString(t._JsepGetNodeName(l))),u=>s.releaseKernel(u),(u,l,a,p)=>{De("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${a}, kernel=${u}, contextDataOffset=${l}`);let m=new io(t,s,l);return s.computeKernel(u,m,p)},()=>s.captureBegin(),()=>s.captureEnd(),()=>s.replay()])}else n("webnn")}});var Ho;Ho=Ro();var bd=No(),An,Tn=!1,zr=!1,Go=!1,wd=e=>{if(e===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");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}},vd=()=>{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}},$d=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Lo=async e=>{if(Tn)return Promise.resolve();if(zr)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Go)throw new Error("previous call to \'initializeWebAssembly()\' failed.");zr=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,n=wd(r),s=o&&vd(),u=e.wasmPaths,l=typeof u=="string"?u:void 0,a=$d(s,n),p=typeof u=="object"?u[a]:void 0,m=!1,f=[];if(t>0&&f.push(new Promise(b=>{setTimeout(()=>{m=!0,b()},t)})),f.push(new Promise((b,_)=>{let y=n?bd:Ho,$={locateFile:(I,C)=>{if(n&&I.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Wo()],{type:"text/javascript"}));if(I.endsWith(".wasm")){if(p)return p;let v=l??C;return a==="ort-wasm-simd.wasm"?v+"ort-wasm-simd.jsep.wasm":a==="ort-wasm-simd-threaded.wasm"?v+"ort-wasm-simd-threaded.jsep.wasm":v+a}return C+I}};if(n)if($.numThreads=r,typeof Blob>"u")$.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let I=`var ortWasmThreaded=${y.toString()};`;$.mainScriptUrlOrBlob=new Blob([I],{type:"text/javascript"})}y($).then(I=>{zr=!1,Tn=!0,An=I,b()},I=>{zr=!1,Go=!0,_(I)})})),await Promise.race(f),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},We=()=>{if(Tn&&An)return An;throw new Error("WebAssembly is not initialized yet.")};var Ge=(e,t)=>{let r=We(),o=r.lengthBytesUTF8(e)+1,n=r._malloc(o);return r.stringToUTF8(e,n,o),t.push(n),n},mr=(e,t,r,o)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,s])=>{let u=t?t+n:n;if(typeof s=="object")mr(s,u+".",r,o);else if(typeof s=="string"||typeof s=="number")o(u,s.toString());else if(typeof s=="boolean")o(u,s?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof s}`)})},Be=e=>{let t=We(),r=t.stackSave();try{let o=t.stackAlloc(8);t._OrtGetLastError(o,o+4);let n=t.HEAP32[o/4],s=t.HEAPU32[o/4+1],u=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}};var Fo=e=>{let t=We(),r=0,o=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.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)n.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&&(n.terminate=!1);let s=0;return e?.tag!==void 0&&(s=Ge(e.tag,o)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&Be("Can\'t create run options."),e?.extra!==void 0&&mr(e.extra,"",new WeakSet,(u,l)=>{let a=Ge(u,o),p=Ge(l,o);t._OrtAddRunConfigEntry(r,a,p)!==0&&Be(`Can\'t set a run config entry: ${u} - ${l}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(u=>t._free(u)),s}};var _d=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}`)}},xd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Sd=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)},Cd=(e,t,r)=>{for(let o of t){let n=typeof o=="string"?o:o.name;switch(n){case"webnn":if(n="WEBNN",typeof o!="string"){let u=o;if(u?.deviceType){let l=Ge("deviceType",r),a=Ge(u.deviceType,r);We()._OrtAddSessionConfigEntry(e,l,a)!==0&&Be(`Can\'t set a session config entry: \'deviceType\' - ${u.deviceType}.`)}if(u?.numThreads){let l=u.numThreads;(typeof l!="number"||!Number.isInteger(l)||l<0)&&(l=0);let a=Ge("numThreads",r),p=Ge(l.toString(),r);We()._OrtAddSessionConfigEntry(e,a,p)!==0&&Be(`Can\'t set a session config entry: \'numThreads\' - ${u.numThreads}.`)}if(u?.powerPreference){let l=Ge("powerPreference",r),a=Ge(u.powerPreference,r);We()._OrtAddSessionConfigEntry(e,l,a)!==0&&Be(`Can\'t set a session config entry: \'powerPreference\' - ${u.powerPreference}.`)}}break;case"webgpu":if(n="JS",typeof o!="string"){let u=o;if(u?.preferredLayout){if(u.preferredLayout!=="NCHW"&&u.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${u.preferredLayout}`);let l=Ge("preferredLayout",r),a=Ge(u.preferredLayout,r);We()._OrtAddSessionConfigEntry(e,l,a)!==0&&Be(`Can\'t set a session config entry: \'preferredLayout\' - ${u.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let s=Ge(n,r);We()._OrtAppendExecutionProvider(e,s)!==0&&Be(`Can\'t append execution provider: ${n}.`)}},qo=e=>{let t=We(),r=0,o=[],n=e||{};Sd(n);try{let s=_d(n.graphOptimizationLevel??"all"),u=xd(n.executionMode??"sequential"),l=typeof n.logId=="string"?Ge(n.logId,o):0,a=n.logSeverityLevel??2;if(!Number.isInteger(a)||a<0||a>4)throw new Error(`log serverity level is not valid: ${a}`);let p=n.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof n.optimizedModelFilePath=="string"?Ge(n.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,u,!!n.enableProfiling,0,l,a,p,m),r===0&&Be("Can\'t create session options."),n.executionProviders&&Cd(r,n.executionProviders,o),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);let f=Ge("enableGraphCapture",o),b=Ge(n.enableGraphCapture.toString(),o);t._OrtAddSessionConfigEntry(r,f,b)!==0&&Be(`Can\'t set a session config entry: \'enableGraphCapture\' - ${n.enableGraphCapture}.`)}if(n.freeDimensionOverrides)for(let[f,b]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof b!="number"||!Number.isInteger(b)||b<0)throw new Error(`free dimension override value must be a non-negative integer: ${b}`);let _=Ge(f,o);t._OrtAddFreeDimensionOverride(r,_,b)!==0&&Be(`Can\'t set a free dimension override: ${f} - ${b}.`)}return n.extra!==void 0&&mr(n.extra,"",new WeakSet,(f,b)=>{let _=Ge(f,o),y=Ge(b,o);t._OrtAddSessionConfigEntry(r,_,y)!==0&&Be(`Can\'t set a session config entry: ${f} - ${b}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(u=>t._free(u)),s}};ie();var jo=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(e),o=[];for await(let n of r)o.push(n);return new Uint8Array(Buffer.concat(o))}throw t}else{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"),o=r?parseInt(r,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),s;try{s=new ArrayBuffer(o)}catch(l){if(l instanceof RangeError){let a=Math.ceil(o/65536);s=new WebAssembly.Memory({initial:a,maximum:a}).buffer}else throw l}let u=0;for(;;){let{done:l,value:a}=await n.read();if(l)break;let p=a.byteLength;new Uint8Array(s,u,p).set(a),u+=p}return new Uint8Array(s,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var ip=(e,t)=>{We()._OrtInit(e,t)!==0&&Be("Can\'t initialize onnxruntime.")},Hu=async e=>{ip(e.wasm.numThreads,hr(e.logLevel))},Lu=async(e,t)=>{{let r=(Wu(),Ft(Nu)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let o=e.webgpu.adapter;if(o){if(typeof o.limits!="object"||typeof o.features!="object"||typeof o.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let s=e.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(o=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:s}),!o)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\')}if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",We(),e,o)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",We(),e)}}},Ut=new Map,sp=e=>{let t=We(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&Be("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},so=e=>{let t=We(),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]},Fu=async(e,t)=>{let r,o,n=We();Array.isArray(e)?[r,o]=e:e.buffer===n.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=so(e);let s=0,u=0,l=0,a=[],p=[],m=[];try{if([u,a]=qo(t),t?.externalData&&n.mountExternalData){let v=[];for(let A of t.externalData){let T=typeof A=="string"?A:A.path;v.push(jo(typeof A=="string"?A:A.data).then(D=>{n.mountExternalData(T,D)}))}await Promise.all(v)}s=await n._OrtCreateSession(r,o,u),s===0&&Be("Can\'t create a session.");let[f,b]=sp(s),_=!!t?.enableGraphCapture,y=[],$=[],I=[];for(let v=0;vv==="gpu-buffer")&&(l=n._OrtCreateBinding(s),l===0&&Be("Can\'t create IO binding."),C={handle:l,outputPreferredLocations:I,outputPreferredLocationsEncoded:I.map(v=>Pn(v))}),Ut.set(s,[s,p,m,C,_,!1]),[s,y,$]}catch(f){throw p.forEach(b=>n._OrtFree(b)),m.forEach(b=>n._OrtFree(b)),l!==0&&n._OrtReleaseBinding(l),s!==0&&n._OrtReleaseSession(s),f}finally{n._free(r),u!==0&&n._OrtReleaseSessionOptions(u),a.forEach(f=>n._free(f)),n.unmountExternalData?.()}},qu=e=>{let t=We(),r=Ut.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,n,s,u,l]=r;u&&(l&&t._OrtClearBoundOutputs(u.handle),t._OrtReleaseBinding(u.handle)),t.jsepOnReleaseSession?.(e),n.forEach(a=>t._OrtFree(a)),s.forEach(a=>t._OrtFree(a)),t._OrtReleaseSession(o),Ut.delete(e)},Gu=(e,t,r,o,n,s=!1)=>{if(!e){t.push(0);return}let u=We(),l=e[0],a=e[1],p=e[3],m,f;if(l==="string"&&p==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(s&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let y=e[2].gpuBuffer,$=fr(En(l));f=a.reduce((C,v)=>C*v,1)*$;let I=u.jsepRegisterBuffer;if(!I)throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');m=I(o,n,y,f)}else{let y=e[2];if(Array.isArray(y)){f=4*y.length,m=u._malloc(f),r.push(m);let $=m/4;for(let I=0;Iu.HEAP32[y++]=I);let $=u._OrtCreateTensor(En(l),m,f,_,a.length,Pn(p));$===0&&Be(`Can\'t create tensor for input/output. session=${o}, index=${n}.`),t.push($)}finally{u.stackRestore(b)}},Ku=async(e,t,r,o,n,s)=>{let u=We(),l=Ut.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let a=l[0],p=l[1],m=l[2],f=l[3],b=l[4],_=l[5],y=t.length,$=o.length,I=0,C=[],v=[],A=[],T=[],D=u.stackSave(),U=u.stackAlloc(y*4),V=u.stackAlloc(y*4),H=u.stackAlloc($*4),R=u.stackAlloc($*4);try{[I,C]=Fo(s);for(let Q=0;QNe*Fe,1);he=Tt(J);let wt=f?.outputPreferredLocations[o[Q]];if(he==="string"){if(wt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ne=[],Fe=Ae/4;for(let Je=0;Je0){let Ne=u.jsepGetBuffer;if(!Ne)throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');let Fe=Ne(Ae),Je=fr(J);if(Je===void 0||!Ko(he))throw new Error(`Unsupported data type: ${he}`);se=!0,ze.push([he,Xe,{gpuBuffer:Fe,download:u.jsepCreateDownloader(Fe,Le*Je,he),dispose:()=>{u._OrtReleaseTensor(xe)}},"gpu-buffer"])}else{let Ne=Ur(he),Fe=new Ne(Le);new Uint8Array(Fe.buffer,Fe.byteOffset,Fe.byteLength).set(u.HEAPU8.subarray(Ae,Ae+Fe.byteLength)),ze.push([he,Xe,Fe,"cpu"])}}finally{u.stackRestore(me),he==="string"&&Ae&&u._free(Ae),se||u._OrtReleaseTensor(xe)}}return f&&!b&&(u._OrtClearBoundOutputs(f.handle),Ut.set(e,[a,p,m,f,b,!1])),ze}finally{u.stackRestore(D),v.forEach(L=>u._OrtReleaseTensor(L)),A.forEach(L=>u._OrtReleaseTensor(L)),T.forEach(L=>u._free(L)),I!==0&&u._OrtReleaseRunOptions(I),C.forEach(L=>u._free(L))}},ju=e=>{let t=We(),r=Ut.get(e);if(!r)throw new Error("invalid session id");let o=r[0],n=t._OrtEndProfiling(o);n===0&&Be("Can\'t get an profile file name."),t._OrtFree(n)},Yu=e=>{let t=[];for(let r of e){let o=r[2];!Array.isArray(o)&&"buffer"in o&&t.push(o.buffer)}return t};self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Lo(r.wasm).then(()=>{Hu(r).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=r;Lu(n,o).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})});break}case"copy-from":{let{buffer:o}=r,n=so(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=r;Fu(o,n).then(s=>{postMessage({type:t,out:s})},s=>{postMessage({type:t,err:s})});break}case"release":qu(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:s,outputIndices:u,options:l}=r;Ku(o,n,s,u,new Array(u.length).fill(null),l).then(a=>{a.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:a},Yu([...s,...a]))},a=>{postMessage({type:t,err:a})});break}case"end-profiling":ju(r),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}};})();\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n'})),ku=L((()=>{de(),Su(),zo(),tu=()=>!!c.wasm.proxy&&typeof document<"u",ru=!1,au=!1,iu=!1,ou=new Map,lu=(e,t)=>{let n=ou.get(e);n?n.push(t):ou.set(e,[t])},uu=()=>{if(ru||!au||iu||!nu)throw new Error("worker not ready")},du=e=>{switch(e.data.type){case"init-wasm":ru=!1,e.data.err?(iu=!0,su[1](e.data.err)):(au=!0,su[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=ou.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},cu=typeof document<"u"?document?.currentScript?.src:void 0,pu=async()=>{if(!au){if(ru)throw new Error("multiple calls to 'initWasm()' detected.");if(iu)throw new Error("previous call to 'initWasm()' failed.");if(ru=!0,tu())return void 0===c.wasm.wasmPaths&&cu&&0!==cu.indexOf("blob:")&&(c.wasm.wasmPaths=cu.substr(0,+cu.lastIndexOf("/")+1)),new Promise(((e,t)=>{nu?.terminate();let n=URL.createObjectURL(new Blob([Mu()],{type:"text/javascript"}));(nu=new Worker(n,{name:"ort-wasm-proxy-worker"})).onerror=e=>t(e),nu.onmessage=du,URL.revokeObjectURL(n),su=[e,t];let r={type:"init-wasm",in:c};nu.postMessage(r)}));try{await Oe(c.wasm),await Gl(c),au=!0}catch(e){throw iu=!0,e}finally{ru=!1}}},hu=async e=>{if(tu())return uu(),new Promise(((t,n)=>{lu("init-ep",[t,n]);let r={type:"init-ep",in:{epName:e,env:c}};nu.postMessage(r)}));await jl(c,e)},fu=async e=>tu()?(uu(),new Promise(((t,n)=>{lu("copy-from",[t,n]);let r={type:"copy-from",in:{buffer:e}};nu.postMessage(r,[e.buffer])}))):Kl(e),mu=async(e,t)=>{if(tu()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return uu(),new Promise(((n,r)=>{lu("create",[n,r]);let a={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),nu.postMessage(a,i)}))}return Yl(e,t)},gu=async e=>{if(tu())return uu(),new Promise(((t,n)=>{lu("release",[t,n]);let r={type:"release",in:e};nu.postMessage(r)}));Xl(e)},_u=async(e,t,n,r,a,i)=>{if(tu()){if(n.some((e=>"cpu"!==e[3])))throw new Error("input tensor on GPU is not supported for proxy.");if(a.some((e=>e)))throw new Error("pre-allocated output tensor is not supported for proxy.");return uu(),new Promise(((a,s)=>{lu("run",[a,s]);let o=n,l={type:"run",in:{sessionId:e,inputIndices:t,inputs:o,outputIndices:r,options:i}};nu.postMessage(l,eu(o))}))}return Zl(e,t,n,r,a,i)},wu=async e=>{if(tu())return uu(),new Promise(((t,n)=>{lu("end-profiling",[t,n]);let r={type:"end-profiling",in:e};nu.postMessage(r)}));Jl(e)}})),Cu=L((()=>{de(),ku(),Do(),Lo(),yu=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},bu=e=>{switch(e[3]){case"cpu":return new M(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Ye(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:a}=e[2];return M.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:a})}default:throw new Error(`invalid data location: ${e[3]}`)}},vu=class{async fetchModelAndCopyToWasmMemory(e){return fu(await Qe(e))}async loadModel(e,t){let n;E(),n="string"==typeof e?typeof process<"u"&&process.versions&&process.versions.node?await Qe(e):await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames]=await mu(n,t),A()}async dispose(){return gu(this.sessionId)}async run(e,t,n){E();let r=[],a=[];Object.entries(e).forEach((e=>{let t=e[0],n=e[1],i=this.inputNames.indexOf(t);if(-1===i)throw new Error(`invalid input '${t}'`);r.push(n),a.push(i)}));let i=[],s=[];Object.entries(t).forEach((e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(-1===r)throw new Error(`invalid output '${t}'`);i.push(n),s.push(r)}));let o=r.map(((e,t)=>yu(e,(()=>`input "${this.inputNames[a[t]]}"`)))),l=i.map(((e,t)=>e?yu(e,(()=>`output "${this.outputNames[s[t]]}"`)):null)),u=await _u(this.sessionId,a,o,s,l,n),d={};for(let e=0;e{de(),ku(),Cu(),$u=()=>{if(("number"!=typeof c.wasm.initTimeout||c.wasm.initTimeout<0)&&(c.wasm.initTimeout=0),"boolean"!=typeof c.wasm.simd&&(c.wasm.simd=!0),"boolean"!=typeof c.wasm.proxy&&(c.wasm.proxy=!1),"boolean"!=typeof c.wasm.trace&&(c.wasm.trace=!1),"number"!=typeof c.wasm.numThreads||!Number.isInteger(c.wasm.numThreads)||c.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(c.wasm.numThreads=1);let e=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;c.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},xu=class{async init(e){$u(),await pu(),await hu(e)}async createInferenceSessionHandler(e,t){let n=new vu;return await n.loadModel(e,t),Promise.resolve(n)}}})),Au={};U(Au,{wasmBackend:()=>Iu});var Iu,Pu=L((()=>{Eu(),Iu=new xu}));de(),de(),de();var Ou=ue;{let e=(Pu(),W(Au)).wasmBackend;i("webgpu",e,5),i("webnn",e,5),i("cpu",e,10),i("wasm",e,10)}Object.defineProperty(c.versions,"web",{value:"1.17.3",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": /*!******************************!*\ !*** ./src/backends/onnx.js ***! \******************************/(e,t,n)=>{var r;n.r(t),n.d(t,{Tensor:()=>o.Tensor,createInferenceSession:()=>h,deviceToExecutionProviders:()=>p,isONNXProxy:()=>g,isONNXTensor:()=>f});var a=n(/*! ../env.js */"./src/env.js"),i=n(/*! onnxruntime-node */"?2ce3"),s=n(/*! onnxruntime-web/webgpu */"./node_modules/onnxruntime-web/dist/esm/ort.webgpu.min.js"),o=n(/*! onnxruntime-common */"./node_modules/onnxruntime-common/dist/esm/index.js");const l=[];let u,d;a.apis.IS_NODE_ENV?(d=i??(r||(r=n.t(i,2))),l.push("cpu"),u=["cpu"]):(d=s,a.apis.IS_WEBGPU_AVAILABLE&&l.push("webgpu"),l.push("wasm"),u=["wasm"]);const c=d.InferenceSession;function p(e){let t=u;if(e){if(!l.includes(e))throw new Error(`Unsupported device: "${e}". Should be one of: ${l.join(", ")}.`);t=[e]}return t}async function h(e,t){return await c.create(e,t)}function f(e){return e instanceof d.Tensor}const m=d?.env;if(m?.wasm){m.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.3/dist/",m.wasm.proxy=!a.apis.IS_WEBWORKER_ENV,"undefined"!=typeof crossOriginIsolated&&crossOriginIsolated||(m.wasm.numThreads=1);"undefined"!=typeof navigator&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(m.wasm.simd=!1)}function g(){return m?.wasm?.proxy}a.env.backends.onnx=m},"./src/configs.js": /*!************************!*\ !*** ./src/configs.js ***! \************************/(e,t,n)=>{n.r(t),n.d(t,{AutoConfig:()=>i,PretrainedConfig:()=>a});var r=n(/*! ./utils/hub.js */"./src/utils/hub.js");class a{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main"}={}){let o=n??await async function(e,t){return await(0,r.getModelJSON)(e,"config.json",!0,t)}(e,{progress_callback:t,config:n,cache_dir:a,local_files_only:i,revision:s});return new this(o)}}class i{static async from_pretrained(...e){return a.from_pretrained(...e)}}},"./src/env.js": /*!********************!*\ !*** ./src/env.js ***! \********************/(e,t,n)=>{n.r(t),n.d(t,{apis:()=>h,env:()=>w});var r=n(/*! fs */"?569f"),a=n(/*! path */"?3f59"),i=n(/*! url */"?154a");const s="undefined"!=typeof self,o=s&&"DedicatedWorkerGlobalScope"===self.constructor.name,l=s&&"caches"in self,u="undefined"!=typeof navigator&&"gpu"in navigator,d="undefined"!=typeof process&&"node"===process?.release?.name,c=!y(r),p=!y(a),h=Object.freeze({IS_BROWSER_ENV:s,IS_WEBWORKER_ENV:o,IS_WEB_CACHE_AVAILABLE:l,IS_WEBGPU_AVAILABLE:u,IS_NODE_ENV:d,IS_FS_AVAILABLE:c,IS_PATH_AVAILABLE:p}),f=c&&p,m=f?a.dirname(a.dirname(i.fileURLToPath("file:///Users/ajr/Documents/GitHub/transformers.js/src/env.js"))):"./",g=f?a.join(m,"/.cache/"):null,_="/models/",w={version:"3.0.0-alpha.0",backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!s,localModelPath:f?a.join(m,_):_,useFS:c,useBrowserCache:l,useFSCache:c,cacheDir:g,useCustomCache:!1,customCache:null};function y(e){return 0===Object.keys(e).length}},"./src/generation/configuration_utils.js": /*!***********************************************!*\ !*** ./src/generation/configuration_utils.js ***! \***********************************************/(e,t,n)=>{n.r(t),n.d(t,{GenerationConfig:()=>a});var r=n(/*! ../utils/core.js */"./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;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(e){Object.assign(this,(0,r.pick)(e,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js": /*!******************************************!*\ !*** ./src/generation/logits_process.js ***! \******************************************/(e,t,n)=>{n.r(t),n.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>_,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>i,LogitsProcessorList:()=>o,LogitsWarper:()=>s,MinLengthLogitsProcessor:()=>f,MinNewTokensLengthLogitsProcessor:()=>m,NoBadWordsLogitsProcessor:()=>g,NoRepeatNGramLogitsProcessor:()=>p,RepetitionPenaltyLogitsProcessor:()=>h,SuppressTokensAtBeginLogitsProcessor:()=>d,TemperatureLogitsWarper:()=>w,TopKLogitsWarper:()=>b,TopPLogitsWarper:()=>y,WhisperTimeStampLogitsProcessor:()=>c});var r=n(/*! ../utils/generic.js */"./src/utils/generic.js"),a=(n(/*! ../utils/tensor.js */"./src/utils/tensor.js"),n(/*! ../utils/maths.js */"./src/utils/maths.js"));class i extends r.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class s extends r.Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class o extends r.Callable{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(const t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}}class l extends i{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(s&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&null!==this.max_initial_timestamp_index){const e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}const l=(0,a.log_softmax)(r);Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce(((e,t)=>e+t)))>(0,a.max)(l.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}}class p extends i{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,n=[];for(let r=0;r1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.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 ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const n=e.length,r=t.slice([0,n],null),a=t.slice([n,t.dims[0]],null);for(let e=0;e1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(n)||n<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${n}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=n}}class b extends s{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:n=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,n),this.filter_value=t}}},"./src/generation/logits_sampler.js": /*!******************************************!*\ !*** ./src/generation/logits_sampler.js ***! \******************************************/(e,t,n)=>{n.r(t),n.d(t,{LogitsSampler:()=>i});var r=n(/*! ../utils/generic.js */"./src/utils/generic.js"),a=(n(/*! ../utils/tensor.js */"./src/utils/tensor.js"),n(/*! ../utils/maths.js */"./src/utils/maths.js"));n(/*! ../generation/configuration_utils.js */"./src/generation/configuration_utils.js");class i extends r.Callable{constructor(e){super(),this.generation_config=e}_call(e,t=-1){return this.sample(e,t)}sample(e,t){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let n=e.dims.at(-1),r=e.data;if(-1===t)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){let t=e.reduce(((e,t)=>e+t),0),n=Math.random()*t;for(let t=0;t1)return new l(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new s(e)}}class s extends i{sample(e,t=-1){let n=this.getLogits(e,t);return[[(0,a.max)(n)[1],0]]}}class o extends i{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const r=this.getLogits(e,t),i=(0,a.getTopItems)(r,n),s=(0,a.softmax)(i.map((e=>e[1])));return Array.from({length:this.generation_config.num_beams},(()=>{const e=this.randomSelect(s);return[i[e][0],Math.log(s[e])]}))}}class l extends i{sample(e,t=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const r=this.getLogits(e,t),i=(0,a.getTopItems)(r,n),s=(0,a.softmax)(i.map((e=>e[1])));return Array.from({length:this.generation_config.num_beams},((e,t)=>[i[t][0],Math.log(s[t])]))}}},"./src/generation/stopping_criteria.js": /*!*********************************************!*\ !*** ./src/generation/stopping_criteria.js ***! \*********************************************/(e,t,n)=>{n.r(t),n.d(t,{EosTokenCriteria:()=>o,MaxLengthCriteria:()=>s,StoppingCriteria:()=>a,StoppingCriteriaList:()=>i});var r=n(/*! ../utils/generic.js */"./src/utils/generic.js");class a extends r.Callable{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}}class i extends r.Callable{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof i&&(e=e.criteria),this.criteria.push(...e)}_call(e,t){const n=new Array(e.length).fill(!1);for(const r of this.criteria){const a=r(e,t);for(let e=0;ee.length>=this.max_length))}}class o extends a{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map((e=>this.eos_token_id.includes(e.at(-1))))}}},"./src/generation/streamers.js": /*!*************************************!*\ !*** ./src/generation/streamers.js ***! \*************************************/(e,t,n)=>{n.r(t),n.d(t,{BaseStreamer:()=>r});class r{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}}},"./src/models.js": /*!***********************!*\ !*** ./src/models.js ***! \***********************/(e,t,n)=>{n.r(t),n.d(t,{ASTForAudioClassification:()=>Xt,ASTModel:()=>Yt,ASTPreTrainedModel:()=>Kt,AlbertForMaskedLM:()=>it,AlbertForQuestionAnswering:()=>at,AlbertForSequenceClassification:()=>rt,AlbertModel:()=>nt,AlbertPreTrainedModel:()=>tt,AutoModel:()=>is,AutoModelForAudioClassification:()=>xs,AutoModelForAudioFrameClassification:()=>Ss,AutoModelForCTC:()=>$s,AutoModelForCausalLM:()=>ps,AutoModelForDepthEstimation:()=>Es,AutoModelForDocumentQuestionAnswering:()=>Ms,AutoModelForImageClassification:()=>gs,AutoModelForImageFeatureExtraction:()=>As,AutoModelForImageMatting:()=>ks,AutoModelForImageSegmentation:()=>_s,AutoModelForImageToImage:()=>Cs,AutoModelForMaskGeneration:()=>vs,AutoModelForMaskedLM:()=>hs,AutoModelForObjectDetection:()=>ys,AutoModelForQuestionAnswering:()=>fs,AutoModelForSemanticSegmentation:()=>ws,AutoModelForSeq2SeqLM:()=>ls,AutoModelForSequenceClassification:()=>ss,AutoModelForSpeechSeq2Seq:()=>us,AutoModelForTextToSpectrogram:()=>ds,AutoModelForTextToWaveform:()=>cs,AutoModelForTokenClassification:()=>os,AutoModelForVision2Seq:()=>ms,AutoModelForXVector:()=>Ts,AutoModelForZeroShotObjectDetection:()=>bs,BartForConditionalGeneration:()=>_t,BartForSequenceClassification:()=>wt,BartModel:()=>gt,BartPretrainedModel:()=>mt,BaseModelOutput:()=>R,BeitForImageClassification:()=>gr,BeitModel:()=>mr,BeitPreTrainedModel:()=>fr,BertForMaskedLM:()=>N,BertForQuestionAnswering:()=>V,BertForSequenceClassification:()=>U,BertForTokenClassification:()=>W,BertModel:()=>L,BertPreTrainedModel:()=>D,BlenderbotForConditionalGeneration:()=>Mt,BlenderbotModel:()=>St,BlenderbotPreTrainedModel:()=>Tt,BlenderbotSmallForConditionalGeneration:()=>Et,BlenderbotSmallModel:()=>Ct,BlenderbotSmallPreTrainedModel:()=>kt,BloomForCausalLM:()=>Hn,BloomModel:()=>qn,BloomPreTrainedModel:()=>jn,CLIPModel:()=>sn,CLIPPreTrainedModel:()=>an,CLIPSegForImageSegmentation:()=>_n,CLIPSegModel:()=>gn,CLIPSegPreTrainedModel:()=>mn,CLIPTextModelWithProjection:()=>on,CLIPVisionModelWithProjection:()=>ln,CamembertForMaskedLM:()=>pe,CamembertForQuestionAnswering:()=>me,CamembertForSequenceClassification:()=>he,CamembertForTokenClassification:()=>fe,CamembertModel:()=>ce,CamembertPreTrainedModel:()=>de,CausalLMOutput:()=>Rs,CausalLMOutputWithPast:()=>Ds,ChineseCLIPModel:()=>fn,ChineseCLIPPreTrainedModel:()=>hn,ClapAudioModelWithProjection:()=>di,ClapModel:()=>li,ClapPreTrainedModel:()=>oi,ClapTextModelWithProjection:()=>ui,CodeGenForCausalLM:()=>Bn,CodeGenModel:()=>zn,CodeGenPreTrainedModel:()=>On,ConvBertForMaskedLM:()=>ee,ConvBertForQuestionAnswering:()=>re,ConvBertForSequenceClassification:()=>te,ConvBertForTokenClassification:()=>ne,ConvBertModel:()=>J,ConvBertPreTrainedModel:()=>Z,ConvNextForImageClassification:()=>Qr,ConvNextModel:()=>Xr,ConvNextPreTrainedModel:()=>Yr,ConvNextV2ForImageClassification:()=>ea,ConvNextV2Model:()=>Jr,ConvNextV2PreTrainedModel:()=>Zr,DPTForDepthEstimation:()=>Ur,DPTModel:()=>Nr,DPTPreTrainedModel:()=>Lr,DebertaForMaskedLM:()=>we,DebertaForQuestionAnswering:()=>ve,DebertaForSequenceClassification:()=>ye,DebertaForTokenClassification:()=>be,DebertaModel:()=>_e,DebertaPreTrainedModel:()=>ge,DebertaV2ForMaskedLM:()=>Te,DebertaV2ForQuestionAnswering:()=>ke,DebertaV2ForSequenceClassification:()=>Se,DebertaV2ForTokenClassification:()=>Me,DebertaV2Model:()=>xe,DebertaV2PreTrainedModel:()=>$e,DeiTForImageClassification:()=>Er,DeiTModel:()=>Cr,DeiTPreTrainedModel:()=>kr,DepthAnythingForDepthEstimation:()=>Vr,DepthAnythingPreTrainedModel:()=>Wr,DetrForObjectDetection:()=>yr,DetrForSegmentation:()=>br,DetrModel:()=>wr,DetrObjectDetectionOutput:()=>vr,DetrPreTrainedModel:()=>_r,DetrSegmentationOutput:()=>$r,Dinov2ForImageClassification:()=>ra,Dinov2Model:()=>na,Dinov2PreTrainedModel:()=>ta,DistilBertForMaskedLM:()=>Oe,DistilBertForQuestionAnswering:()=>Pe,DistilBertForSequenceClassification:()=>Ae,DistilBertForTokenClassification:()=>Ie,DistilBertModel:()=>Ee,DistilBertPreTrainedModel:()=>Ce,DonutSwinModel:()=>Kr,DonutSwinPreTrainedModel:()=>Hr,EfficientNetForImageClassification:()=>$i,EfficientNetModel:()=>vi,EfficientNetPreTrainedModel:()=>bi,ElectraForMaskedLM:()=>se,ElectraForQuestionAnswering:()=>ue,ElectraForSequenceClassification:()=>oe,ElectraForTokenClassification:()=>le,ElectraModel:()=>ie,ElectraPreTrainedModel:()=>ae,EsmForMaskedLM:()=>Fe,EsmForSequenceClassification:()=>Re,EsmForTokenClassification:()=>De,EsmModel:()=>Be,EsmPreTrainedModel:()=>ze,FalconForCausalLM:()=>si,FalconModel:()=>ii,FalconPreTrainedModel:()=>ai,GLPNForDepthEstimation:()=>qr,GLPNModel:()=>jr,GLPNPreTrainedModel:()=>Gr,GPT2LMHeadModel:()=>bn,GPT2Model:()=>yn,GPT2PreTrainedModel:()=>wn,GPTBigCodeForCausalLM:()=>Pn,GPTBigCodeModel:()=>In,GPTBigCodePreTrainedModel:()=>An,GPTJForCausalLM:()=>En,GPTJModel:()=>Cn,GPTJPreTrainedModel:()=>kn,GPTNeoForCausalLM:()=>xn,GPTNeoModel:()=>$n,GPTNeoPreTrainedModel:()=>vn,GPTNeoXForCausalLM:()=>Mn,GPTNeoXModel:()=>Sn,GPTNeoXPreTrainedModel:()=>Tn,HubertForCTC:()=>Ra,HubertForSequenceClassification:()=>Da,HubertModel:()=>Fa,HubertPreTrainedModel:()=>Ba,ImageMattingOutput:()=>Ls,LlamaForCausalLM:()=>Dn,LlamaModel:()=>Rn,LlamaPreTrainedModel:()=>Fn,LlavaForConditionalGeneration:()=>rn,LlavaPreTrainedModel:()=>nn,LongT5ForConditionalGeneration:()=>ct,LongT5Model:()=>dt,LongT5PreTrainedModel:()=>ut,M2M100ForConditionalGeneration:()=>ga,M2M100Model:()=>ma,M2M100PreTrainedModel:()=>fa,MBartForCausalLM:()=>xt,MBartForConditionalGeneration:()=>vt,MBartForSequenceClassification:()=>$t,MBartModel:()=>bt,MBartPreTrainedModel:()=>yt,MPNetForMaskedLM:()=>qe,MPNetForQuestionAnswering:()=>Ye,MPNetForSequenceClassification:()=>He,MPNetForTokenClassification:()=>Ke,MPNetModel:()=>je,MPNetPreTrainedModel:()=>Ge,MT5ForConditionalGeneration:()=>ft,MT5Model:()=>ht,MT5PreTrainedModel:()=>pt,MarianMTModel:()=>ha,MarianModel:()=>pa,MarianPreTrainedModel:()=>ca,MaskedLMOutput:()=>Bs,MistralForCausalLM:()=>ei,MistralModel:()=>Ja,MistralPreTrainedModel:()=>Za,MobileBertForMaskedLM:()=>Ue,MobileBertForQuestionAnswering:()=>Ve,MobileBertForSequenceClassification:()=>We,MobileBertModel:()=>Ne,MobileBertPreTrainedModel:()=>Le,MobileViTForImageClassification:()=>or,MobileViTModel:()=>sr,MobileViTPreTrainedModel:()=>ir,ModelOutput:()=>F,MptForCausalLM:()=>Xn,MptModel:()=>Yn,MptPreTrainedModel:()=>Kn,MusicgenForCausalLM:()=>Si,MusicgenForConditionalGeneration:()=>Mi,MusicgenModel:()=>Ti,MusicgenPreTrainedModel:()=>xi,NomicBertModel:()=>j,NomicBertPreTrainedModel:()=>G,OPTForCausalLM:()=>Jn,OPTModel:()=>Zn,OPTPreTrainedModel:()=>Qn,OwlViTForObjectDetection:()=>dr,OwlViTModel:()=>ur,OwlViTPreTrainedModel:()=>lr,Owlv2ForObjectDetection:()=>hr,Owlv2Model:()=>pr,Owlv2PreTrainedModel:()=>cr,PhiForCausalLM:()=>Gn,PhiModel:()=>Vn,PhiPreTrainedModel:()=>Wn,PreTrainedModel:()=>B,PretrainedMixin:()=>ki,QuestionAnsweringModelOutput:()=>Fs,Qwen2ForCausalLM:()=>Un,Qwen2Model:()=>Nn,Qwen2PreTrainedModel:()=>Ln,ResNetForImageClassification:()=>Pr,ResNetModel:()=>Ir,ResNetPreTrainedModel:()=>Ar,RoFormerForMaskedLM:()=>K,RoFormerForQuestionAnswering:()=>Q,RoFormerForSequenceClassification:()=>Y,RoFormerForTokenClassification:()=>X,RoFormerModel:()=>H,RoFormerPreTrainedModel:()=>q,RobertaForMaskedLM:()=>Pt,RobertaForQuestionAnswering:()=>Bt,RobertaForSequenceClassification:()=>Ot,RobertaForTokenClassification:()=>zt,RobertaModel:()=>It,RobertaPreTrainedModel:()=>At,SamImageSegmentationOutput:()=>da,SamModel:()=>ua,SamPreTrainedModel:()=>la,SegformerForImageClassification:()=>mi,SegformerForSemanticSegmentation:()=>gi,SegformerModel:()=>fi,SegformerPreTrainedModel:()=>hi,Seq2SeqLMOutput:()=>Is,SequenceClassifierOutput:()=>Ps,SiglipModel:()=>dn,SiglipPreTrainedModel:()=>un,SiglipTextModel:()=>cn,SiglipVisionModel:()=>pn,SpeechT5ForSpeechToText:()=>Ha,SpeechT5ForTextToSpeech:()=>Ka,SpeechT5HifiGan:()=>Ya,SpeechT5Model:()=>qa,SpeechT5PreTrainedModel:()=>ja,SqueezeBertForMaskedLM:()=>Ze,SqueezeBertForQuestionAnswering:()=>et,SqueezeBertForSequenceClassification:()=>Je,SqueezeBertModel:()=>Qe,SqueezeBertPreTrainedModel:()=>Xe,StableLmForCausalLM:()=>yi,StableLmModel:()=>wi,StableLmPreTrainedModel:()=>_i,Starcoder2ForCausalLM:()=>ri,Starcoder2Model:()=>ni,Starcoder2PreTrainedModel:()=>ti,Swin2SRForImageSuperResolution:()=>Dr,Swin2SRModel:()=>Rr,Swin2SRPreTrainedModel:()=>Fr,SwinForImageClassification:()=>Br,SwinModel:()=>zr,SwinPreTrainedModel:()=>Or,T5ForConditionalGeneration:()=>lt,T5Model:()=>ot,T5PreTrainedModel:()=>st,TableTransformerForObjectDetection:()=>Sr,TableTransformerModel:()=>Tr,TableTransformerObjectDetectionOutput:()=>Mr,TableTransformerPreTrainedModel:()=>xr,TokenClassifierOutput:()=>zs,TrOCRForCausalLM:()=>Qa,TrOCRPreTrainedModel:()=>Xa,UniSpeechForCTC:()=>Ta,UniSpeechForSequenceClassification:()=>Sa,UniSpeechModel:()=>xa,UniSpeechPreTrainedModel:()=>$a,UniSpeechSatForAudioFrameClassification:()=>Aa,UniSpeechSatForCTC:()=>Ca,UniSpeechSatForSequenceClassification:()=>Ea,UniSpeechSatModel:()=>ka,UniSpeechSatPreTrainedModel:()=>Ma,ViTForImageClassification:()=>nr,ViTModel:()=>tr,ViTPreTrainedModel:()=>er,VisionEncoderDecoderModel:()=>tn,VitMatteForImageMatting:()=>ar,VitMattePreTrainedModel:()=>rr,VitsModel:()=>pi,VitsModelOutput:()=>Ns,VitsPreTrainedModel:()=>ci,Wav2Vec2BertForCTC:()=>Oa,Wav2Vec2BertForSequenceClassification:()=>za,Wav2Vec2BertModel:()=>Pa,Wav2Vec2BertPreTrainedModel:()=>Ia,Wav2Vec2ForAudioFrameClassification:()=>va,Wav2Vec2ForCTC:()=>ya,Wav2Vec2ForSequenceClassification:()=>ba,Wav2Vec2Model:()=>wa,Wav2Vec2PreTrainedModel:()=>_a,WavLMForAudioFrameClassification:()=>Ga,WavLMForCTC:()=>Ua,WavLMForSequenceClassification:()=>Wa,WavLMForXVector:()=>Va,WavLMModel:()=>Na,WavLMPreTrainedModel:()=>La,WhisperForConditionalGeneration:()=>en,WhisperModel:()=>Zt,WhisperPreTrainedModel:()=>Qt,XLMForQuestionAnswering:()=>Ut,XLMForSequenceClassification:()=>Lt,XLMForTokenClassification:()=>Nt,XLMModel:()=>Rt,XLMPreTrainedModel:()=>Ft,XLMRobertaForMaskedLM:()=>Gt,XLMRobertaForQuestionAnswering:()=>Ht,XLMRobertaForSequenceClassification:()=>jt,XLMRobertaForTokenClassification:()=>qt,XLMRobertaModel:()=>Vt,XLMRobertaPreTrainedModel:()=>Wt,XLMWithLMHeadModel:()=>Dt,XVectorOutput:()=>Os,YolosForObjectDetection:()=>sa,YolosModel:()=>ia,YolosObjectDetectionOutput:()=>oa,YolosPreTrainedModel:()=>aa});var r=n(/*! ./configs.js */"./src/configs.js"),a=n(/*! ./backends/onnx.js */"./src/backends/onnx.js"),i=n(/*! ./utils/dtypes.js */"./src/utils/dtypes.js"),s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),o=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/hub.js */"./src/utils/hub.js"),u=n(/*! ./generation/logits_process.js */"./src/generation/logits_process.js"),d=n(/*! ./generation/configuration_utils.js */"./src/generation/configuration_utils.js"),c=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),p=n(/*! ./utils/maths.js */"./src/utils/maths.js"),h=n(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),f=n(/*! ./generation/logits_sampler.js */"./src/generation/logits_sampler.js");const m=0,g=1,_=2,w=3,y=4,b=5,v=6,$=7,x=new Map,T=new Map,S=new Map;async function M(e,t,n){const r=Object.keys(t),s=await Promise.all(r.map((async r=>async function(e,t,n){let r=n.device;r&&"string"!=typeof r&&(r.hasOwnProperty(t)?r=r[t]:(console.warn(`Device not specified for ${t}. Using the default device.`),r=null));const s=(0,a.deviceToExecutionProviders)(r);let o=n.dtype;if("string"!=typeof o&&(o&&o.hasOwnProperty(t)?o=o[t]:(o=i.DEFAULT_DEVICE_DTYPE_MAPPING[s[0]],console.warn(`Dtype not specified for ${t}. Using the default dtype: ${o}.`))),!i.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(o))throw new Error(`Invalid dtype: ${o}. Should be one of: ${Object.keys(i.DATA_TYPES).join(", ")}`);if(o===i.DATA_TYPES.fp16&&!await(0,i.isFp16Supported)())throw new Error("The device does not support fp16.");const u=i.DEFAULT_DTYPE_SUFFIX_MAPPING[o],d=`${n.subfolder??""}/${t}${u}.onnx`,c=await(0,l.getModelFile)(e,d,!0,n),p={...n.session_options}??{};if(p.executionProviders??=s,void 0!==p.externalData)for(let t=0;t0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const i=Object.keys(t).length,s=e.inputNames.length;if(i>s){let n=Object.keys(t).filter((t=>!e.inputNames.includes(t)));console.warn(`WARNING: Too many inputs were provided (${i} > ${s}). The following inputs will be ignored: "${n.join(", ")}".`)}return n}(e,t);try{const t=Object.fromEntries(Object.entries(n).map((([e,t])=>[e,t.ort_tensor])));let r=await e.run(t);r=C(r);for(const[e,t]of Object.entries(n))e.startsWith("past_key_values")&&t.dispose();return r}catch(e){throw console.error(`An error occurred during model execution: "${e}".`),console.error("Inputs given to model:",n),e}}function C(e){for(let t in e)(0,a.isONNXTensor)(e[t])?e[t]=new c.Tensor(e[t]):"object"==typeof e[t]&&C(e[t]);return e}function E(e){return new c.Tensor("bool",[e],[1])}async function A(e,t){let{encoder_outputs:n,past_key_values:r}=t;if(!n){const r=(0,o.pick)(t,e.sessions.model.inputNames);n=(await I(e,r)).last_hidden_state}const{input_ids:a,decoder_input_ids:i,...s}=t;s.input_ids=i,s.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(s.encoder_attention_mask=t.attention_mask);return await P(e,s,!0)}async function I(e,t){const n=e.sessions.model,r=Object.create(null);for(const e of n.inputNames)r[e]=t[e];return n.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new c.Tensor("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await k(n,r)}async function P(e,t,n=!1){const r=e.sessions[n?"decoder_model_merged":"model"],{past_key_values:a,...i}=t;r.inputNames.includes("use_cache_branch")&&(i.use_cache_branch=E(!!a)),e.addPastKeyValues(i,a);const s=(0,o.pick)(i,r.inputNames);return await k(r,s)}function O(e,t,n,r){if(e.sessions.model.inputNames.includes("position_ids")&&n.attention_mask&&!n.position_ids){const[e,t]=n.attention_mask.dims,r=new BigInt64Array(n.attention_mask.data.length);for(let a=0;a[e.at(-1)]))),a.decoder_input_ids=function(e){if(e instanceof c.Tensor)return e;if(0===e.length)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some((t=>t.length!==e[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 c.Tensor("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}return new c.Tensor("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}(t),a}class B extends s.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t){super(),this.config=e,this.sessions=t;const n=S.get(this.constructor),r=x.get(n);this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,r===y?(this.can_generate=!0,this._forward=P,this._prepare_inputs_for_generation=O):r===_||r===w||r===$?(this.can_generate=!0,this._forward=A,this._prepare_inputs_for_generation=z):r===g?this._forward=A:r===v?(this.can_generate=!0,console.warn("TODO: Implement visionDecoderForward")):this._forward=I}async dispose(){const e=[];for(let t of Object.keys(this)){let n=this[t];void 0!==n?.handler?.dispose&&e.push(n.handler.dispose())}return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",model_file_name:o=null,subfolder:u="onnx",device:d=null,dtype:c=null,session_options:p={}}={}){let h={progress_callback:t,config:n,cache_dir:a,local_files_only:i,revision:s,model_file_name:o,subfolder:u,device:d,dtype:c,session_options:p};const f=S.get(this),T=x.get(f);let k;return T===y?k=await Promise.all([r.AutoConfig.from_pretrained(e,h),M(e,{model:h.model_file_name??"model"},h),(0,l.getModelJSON)(e,"generation_config.json",!1,h)]):T===_||T===w?k=await Promise.all([r.AutoConfig.from_pretrained(e,h),M(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h),(0,l.getModelJSON)(e,"generation_config.json",!1,h)]):T===b?k=await Promise.all([r.AutoConfig.from_pretrained(e,h),M(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]):T===g?k=await Promise.all([r.AutoConfig.from_pretrained(e,h),M(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h)]):T===v?k=await Promise.all([r.AutoConfig.from_pretrained(e,h),M(e,{embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"},h),(0,l.getModelJSON)(e,"generation_config.json",!1,h)]):T===$?k=await Promise.all([r.AutoConfig.from_pretrained(e,h),M(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h),(0,l.getModelJSON)(e,"generation_config.json",!1,h)]):(T!==m&&console.warn(`Model type for '${f??n?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),k=await Promise.all([r.AutoConfig.from_pretrained(e,h),M(e,{model:h.model_file_name??"model"},h)])),new this(...k)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_warper(e){const t=new u.LogitsProcessorList;return null!==e.temperature&&1!==e.temperature&&t.push(new u.TemperatureLogitsWarper(e.temperature)),null!==e.top_k&&0!==e.top_k&&t.push(new u.TopKLogitsWarper(e.top_k)),null!==e.top_p&&e.top_p<1&&t.push(new u.TopPLogitsWarper(e.top_p)),t}_get_logits_processor(e,t,n=null){const r=new u.LogitsProcessorList;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&r.push(new u.RepetitionPenaltyLogitsProcessor(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&r.push(new u.NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&r.push(new u.NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&r.push(new u.MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&r.push(new u.MinNewTokensLengthLogitsProcessor(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&r.push(new u.ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&r.push(new u.ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){let n=t>1||null===e.forced_bos_token_id?t:t+1;null!==e.forced_decoder_ids&&(n+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),r.push(new u.SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,n))}return null!==e.guidance_scale&&e.guidance_scale>1&&r.push(new u.ClassifierFreeGuidanceLogitsProcessor(e.guidance_scale)),null!==n&&r.extend(n),r}_prepare_generation_config(e,t){const n=new d.GenerationConfig(this.config);return"generation_config"in this&&Object.assign(n,this.generation_config),e&&Object.assign(n,e),t&&Object.assign(n,(0,o.pick)(t,Object.getOwnPropertyNames(n))),n}_get_stopping_criteria(e,t=null){const n=new h.StoppingCriteriaList;return null!==e.max_length&&n.push(new h.MaxLengthCriteria(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&n.push(new h.EosTokenCriteria(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){const e=[Ri,Ni,Fi,Ii],t=S.get(this.constructor),n=new Set,r=this.config.model_type;for(const t of e){const e=t.get(r);e&&n.add(e[0])}let a=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(a+=` Please use the following class instead: ${[...n].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...e){return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=this.getPastKeyValues(t,n.past_key_values),n.input_ids=new c.Tensor("int64",e,[e.length,1]),r||(n.attention_mask=(0,c.cat)([n.attention_mask,(0,c.ones)([n.attention_mask.dims[0],1])],1)),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){const r=(0,o.pick)(n,this.forward_params),a=this.main_input_name;if(a in r){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[a]=e;return{inputs_tensor:r[a],model_inputs:r,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){const a=(0,o.pick)(t,this.sessions.model.inputNames);let{last_hidden_state:i}=await I(this,a);return null!==r.guidance_scale&&r.guidance_scale>1&&(i=(0,c.cat)([i,(0,c.full_like)(i,0)],0),"attention_mask"in t&&(t.attention_mask=(0,c.cat)([t.attention_mask,(0,c.zeros_like)(t.attention_mask)],0))),t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:a,generation_config:i}){let s;if(r=r??a,"musicgen"===this.config.model_type)s=new Array(e*this.config.decoder.num_codebooks).fill(r);else if(Array.isArray(r)){if(r.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);s=r}else s=new Array(e).fill(r);const o=new c.Tensor("int64",s,[s.length,1]);return n.decoder_attention_mask=(0,c.ones_like)(o),{input_ids:o,model_inputs:n}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:a=null,...i}){this._validate_model_class(),t=this._prepare_generation_config(t,i);let{inputs_tensor:s,model_inputs:o,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:i});const u=this.config.is_encoder_decoder;let d;u&&("encoder_outputs"in o||(o=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:s,model_inputs:o,model_input_name:l,generation_config:t}))),u?({input_ids:d,model_inputs:o}=this._prepare_decoder_input_ids_for_generation({batch_size:o[l].dims.at(0),model_input_name:l,model_kwargs:o,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t})):d=o[l];let p=d.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=p+t.max_new_tokens);const h=this._get_logits_processor(t,p,n),m=this._get_stopping_criteria(t,r),g=o[l].dims.at(0),_=f.LogitsSampler.getSampler(t),w=new Array(g).fill(0),y=d.tolist();for(a&&a.put(y);;){o=this.prepare_inputs_for_generation(y,o,t);const e=await this.forward(o),n=h(y,e.logits.slice(null,-1,null)),r=[];for(let e=0;ee)))break;o=this._update_model_kwargs_for_generation({generated_input_ids:r,outputs:e,model_inputs:o,is_encoder_decoder:u})}return a&&a.end(),new c.Tensor("int64",y.flat(),[y.length,y[0].length])}addAttentionsToBeam(e,t){if(this.config.is_encoder_decoder){if(!t.cross_attentions||0===t.cross_attentions.length)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.cross_attentions||(e.cross_attentions=[]),e.cross_attentions.push(t.cross_attentions)}if(!t.decoder_attentions||0===t.decoder_attentions.length)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.decoder_attentions||(e.decoder_attentions=[]),e.decoder_attentions.push(t.decoder_attentions)}groupBeams(e){const t=Object.create(null);for(const n of e)void 0===t[n.id]?t[n.id]=[n]:t[n.id].push(n);return Object.values(t)}getPastKeyValues(e,t){const n=Object.create(null);for(const r in e)if(r.startsWith("present")){let a=r.replace("present","past_key_values");t&&r.includes("encoder")?n[a]=t[a]:n[a]=e[r]}return n}getAttentions(e){const t=Object.create(null);for(const n of["cross_attentions","decoder_attentions"]){const r=[];for(const t in e)if(t.startsWith(n)){r[t.split(".").pop()]=e[t]}t[n]=r}return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const t=1,n="float32",r=[];if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??1)){let a=[t,this.num_encoder_heads,0,this.encoder_dim_kv],i=[t,this.num_decoder_heads,0,this.decoder_dim_kv];for(let t=0;t{let r=Array.from({length:this.config.decoder_layers},((t,n)=>(0,c.cat)(e.map((e=>e[n])),2))),i=(0,c.stack)(t.map((([e,t])=>n?r[e].slice(null,t,null,[0,n]):r[e].slice(null,t))));i=i.transpose(1,0,2,3);let[s,o]=(0,c.std_mean)(i,-2,0,!0),l=i.clone();for(let e=0;en[t+1]-n[t])),u=(0,o.mergeArrays)([1],s).map((e=>!!e)),d=[];for(let e=0;ee.findIndex((e=>e==a)))),s=i.every((e=>-1===e)),o=i.every((e=>-1!==e));if(!s&&!o)throw new Error("Every input should contain either 0 or 1 image token.");if(s)return{inputs_embeds:e,attention_mask:r,position_ids:null};let l=[],u=[];for(let n=0;ne*t),1);e.input_labels=new c.Tensor("int64",new BigInt64Array(n).fill(1n),t)}const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await k(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new da(await super._call(e))}}class da extends F{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class ca extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class pa extends ca{}class ha extends ca{}class fa extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class ma extends fa{}class ga extends fa{}class _a extends B{}class wa extends _a{}class ya extends _a{async _call(e){return new Rs(await super._call(e))}}class ba extends _a{async _call(e){return new Ps(await super._call(e))}}class va extends _a{async _call(e){return new zs(await super._call(e))}}class $a extends B{}class xa extends $a{}class Ta extends $a{async _call(e){return new Rs(await super._call(e))}}class Sa extends $a{async _call(e){return new Ps(await super._call(e))}}class Ma extends B{}class ka extends Ma{}class Ca extends Ma{async _call(e){return new Rs(await super._call(e))}}class Ea extends Ma{async _call(e){return new Ps(await super._call(e))}}class Aa extends Ma{async _call(e){return new zs(await super._call(e))}}class Ia extends B{}class Pa extends Ia{}class Oa extends Ia{async _call(e){return new Rs(await super._call(e))}}class za extends Ia{async _call(e){return new Ps(await super._call(e))}}class Ba extends B{}class Fa extends _a{}class Ra extends _a{async _call(e){return new Rs(await super._call(e))}}class Da extends _a{async _call(e){return new Ps(await super._call(e))}}class La extends B{}class Na extends La{}class Ua extends La{async _call(e){return new Rs(await super._call(e))}}class Wa extends La{async _call(e){return new Ps(await super._call(e))}}class Va extends La{async _call(e){return new Os(await super._call(e))}}class Ga extends La{async _call(e){return new zs(await super._call(e))}}class ja extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.hidden_size/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.hidden_size/this.num_encoder_heads}}class qa extends ja{}class Ha extends ja{}class Ka extends ja{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:a=20,vocoder:i=null}={}){const s={input_ids:e},{encoder_outputs:o,encoder_attention_mask:l}=await I(this,s),u=o.dims[1]/this.config.reduction_factor,d=Math.floor(u*a),p=Math.floor(u*r),h=this.config.num_mel_bins;let f=[],m=null,g=null,_=0;for(;;){++_;const e=E(!!g);let r;r=g?g.output_sequence_out:new c.Tensor("float32",new Float32Array(h),[1,1,h]);let a={use_cache_branch:e,output_sequence:r,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:o};this.addPastKeyValues(a,m),g=await k(this.sessions.decoder_model_merged,a),m=this.getPastKeyValues(g,m);const{prob:i,spectrum:s}=g;if(f.push(s),_>=p&&(Array.from(i.data).filter((e=>e>=n)).length>0||_>=d))break}const w=(0,c.cat)(f),{waveform:y}=await k(i.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:y}}}class Ya extends B{main_input_name="spectrogram"}class Xa extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_encoder_layers=this.num_decoder_layers=this.config.decoder_layers,this.num_encoder_heads=this.num_decoder_heads=this.config.decoder_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads}}class Qa extends Xa{}class Za extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Ja extends Za{}class ei extends Za{}class ti extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class ni extends ti{}class ri extends ti{}class ai extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class ii extends ai{}class si extends ai{}class oi extends B{}class li extends oi{}class ui extends oi{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class di extends oi{static async from_pretrained(e,t={}){return t.model_file_name??="audio_model",super.from_pretrained(e,t)}}class ci extends B{}class pi extends ci{async _call(e){return new Ns(await super._call(e))}}class hi extends B{}class fi extends hi{}class mi extends hi{}class gi extends hi{}class _i extends B{constructor(e,t,n){super(e,t),this.generation_config=n,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.num_heads}}class wi extends _i{}class yi extends _i{}class bi extends B{}class vi extends bi{}class $i extends bi{async _call(e){return new Ps(await super._call(e))}}class xi extends B{}class Ti extends xi{}class Si extends xi{}class Mi extends B{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(e,t,n){super(e,t),this.generation_config=n;const r=e.decoder;this.num_encoder_layers=this.num_decoder_layers=r.num_hidden_layers,this.num_encoder_heads=this.num_decoder_heads=r.num_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=r.hidden_size/this.num_decoder_heads}_apply_and_filter_by_delay_pattern_mask(e){const[t,n]=e.dims,r=this.config.decoder.num_codebooks,a=n-r;let i=0;for(let t=0;t0&&s<=a&&(e.data[i++]=e.data[t])}const s=Math.floor(t/r),o=i/(s*r);return new c.Tensor(e.type,e.data.slice(0,i),[s,r,o])}prepare_inputs_for_generation(e,t,n){let r=structuredClone(e);for(let e=0;e=t&&(r[e][t]=BigInt(this.config.decoder.pad_token_id));null!==n.guidance_scale&&n.guidance_scale>1&&(r=r.concat(r));return super.prepare_inputs_for_generation(r,t,n)}async generate(e){const t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await k(this.sessions.encodec_decode,{audio_codes:n});return r}}class ki{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:d=null,session_options:c={}}={}){let p={progress_callback:t,config:n,cache_dir:a,local_files_only:i,revision:s,model_file_name:o,subfolder:l,device:u,dtype:d,session_options:c};if(n=await r.AutoConfig.from_pretrained(e,p),p.config||(p.config=n),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let t of this.MODEL_CLASS_MAPPINGS){const r=t.get(n.model_type);if(r)return await r[1].from_pretrained(e,p)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${n.model_type}", attempting to construct from base class.`),await B.from_pretrained(e,p);throw Error(`Unsupported model type: ${n.model_type}`)}}const Ci=new Map([["bert",["BertModel",L]],["nomic_bert",["NomicBertModel",j]],["roformer",["RoFormerModel",H]],["electra",["ElectraModel",ie]],["esm",["EsmModel",Be]],["convbert",["ConvBertModel",J]],["camembert",["CamembertModel",ce]],["deberta",["DebertaModel",_e]],["deberta-v2",["DebertaV2Model",xe]],["mpnet",["MPNetModel",je]],["albert",["AlbertModel",nt]],["distilbert",["DistilBertModel",Ee]],["roberta",["RobertaModel",It]],["xlm",["XLMModel",Rt]],["xlm-roberta",["XLMRobertaModel",Vt]],["clap",["ClapModel",li]],["clip",["CLIPModel",sn]],["clipseg",["CLIPSegModel",gn]],["chinese_clip",["ChineseCLIPModel",fn]],["siglip",["SiglipModel",dn]],["mobilebert",["MobileBertModel",Ne]],["squeezebert",["SqueezeBertModel",Qe]],["wav2vec2",["Wav2Vec2Model",wa]],["wav2vec2-bert",["Wav2Vec2BertModel",Pa]],["unispeech",["UniSpeechModel",xa]],["unispeech-sat",["UniSpeechSatModel",ka]],["hubert",["HubertModel",Fa]],["wavlm",["WavLMModel",Na]],["audio-spectrogram-transformer",["ASTModel",Yt]],["vits",["VitsModel",pi]],["detr",["DetrModel",wr]],["table-transformer",["TableTransformerModel",Tr]],["vit",["ViTModel",tr]],["mobilevit",["MobileViTModel",sr]],["owlvit",["OwlViTModel",ur]],["owlv2",["Owlv2Model",pr]],["beit",["BeitModel",mr]],["deit",["DeiTModel",Cr]],["convnext",["ConvNextModel",Xr]],["convnextv2",["ConvNextV2Model",Jr]],["dinov2",["Dinov2Model",na]],["resnet",["ResNetModel",Ir]],["swin",["SwinModel",zr]],["swin2sr",["Swin2SRModel",Rr]],["donut-swin",["DonutSwinModel",Kr]],["yolos",["YolosModel",ia]],["dpt",["DPTModel",Nr]],["glpn",["GLPNModel",jr]],["hifigan",["SpeechT5HifiGan",Ya]],["efficientnet",["EfficientNetModel",vi]]]),Ei=new Map([["t5",["T5Model",ot]],["longt5",["LongT5Model",dt]],["mt5",["MT5Model",ht]],["bart",["BartModel",gt]],["mbart",["MBartModel",bt]],["marian",["MarianModel",pa]],["whisper",["WhisperModel",Zt]],["m2m_100",["M2M100Model",ma]],["blenderbot",["BlenderbotModel",St]],["blenderbot-small",["BlenderbotSmallModel",Ct]]]),Ai=new Map([["bloom",["BloomModel",qn]],["gpt2",["GPT2Model",yn]],["gptj",["GPTJModel",Cn]],["gpt_bigcode",["GPTBigCodeModel",In]],["gpt_neo",["GPTNeoModel",$n]],["gpt_neox",["GPTNeoXModel",Sn]],["codegen",["CodeGenModel",zn]],["llama",["LlamaModel",Rn]],["qwen2",["Qwen2Model",Nn]],["phi",["PhiModel",Vn]],["mpt",["MptModel",Yn]],["opt",["OPTModel",Zn]],["mistral",["MistralModel",Ja]],["starcoder2",["Starcoder2Model",ni]],["falcon",["FalconModel",ii]]]),Ii=new Map([["speecht5",["SpeechT5ForSpeechToText",Ha]],["whisper",["WhisperForConditionalGeneration",en]]]),Pi=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ka]]]),Oi=new Map([["vits",["VitsModel",pi]],["musicgen",["MusicgenForConditionalGeneration",Mi]]]),zi=new Map([["bert",["BertForSequenceClassification",U]],["roformer",["RoFormerForSequenceClassification",Y]],["electra",["ElectraForSequenceClassification",oe]],["esm",["EsmForSequenceClassification",Re]],["convbert",["ConvBertForSequenceClassification",te]],["camembert",["CamembertForSequenceClassification",he]],["deberta",["DebertaForSequenceClassification",ye]],["deberta-v2",["DebertaV2ForSequenceClassification",Se]],["mpnet",["MPNetForSequenceClassification",He]],["albert",["AlbertForSequenceClassification",rt]],["distilbert",["DistilBertForSequenceClassification",Ae]],["roberta",["RobertaForSequenceClassification",Ot]],["xlm",["XLMForSequenceClassification",Lt]],["xlm-roberta",["XLMRobertaForSequenceClassification",jt]],["bart",["BartForSequenceClassification",wt]],["mbart",["MBartForSequenceClassification",$t]],["mobilebert",["MobileBertForSequenceClassification",We]],["squeezebert",["SqueezeBertForSequenceClassification",Je]]]),Bi=new Map([["bert",["BertForTokenClassification",W]],["roformer",["RoFormerForTokenClassification",X]],["electra",["ElectraForTokenClassification",le]],["esm",["EsmForTokenClassification",De]],["convbert",["ConvBertForTokenClassification",ne]],["camembert",["CamembertForTokenClassification",fe]],["deberta",["DebertaForTokenClassification",be]],["deberta-v2",["DebertaV2ForTokenClassification",Me]],["mpnet",["MPNetForTokenClassification",Ke]],["distilbert",["DistilBertForTokenClassification",Ie]],["roberta",["RobertaForTokenClassification",zt]],["xlm",["XLMForTokenClassification",Nt]],["xlm-roberta",["XLMRobertaForTokenClassification",qt]]]),Fi=new Map([["t5",["T5ForConditionalGeneration",lt]],["longt5",["LongT5ForConditionalGeneration",ct]],["mt5",["MT5ForConditionalGeneration",ft]],["bart",["BartForConditionalGeneration",_t]],["mbart",["MBartForConditionalGeneration",vt]],["marian",["MarianMTModel",ha]],["m2m_100",["M2M100ForConditionalGeneration",ga]],["blenderbot",["BlenderbotForConditionalGeneration",Mt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Et]]]),Ri=new Map([["bloom",["BloomForCausalLM",Hn]],["gpt2",["GPT2LMHeadModel",bn]],["gptj",["GPTJForCausalLM",En]],["gpt_bigcode",["GPTBigCodeForCausalLM",Pn]],["gpt_neo",["GPTNeoForCausalLM",xn]],["gpt_neox",["GPTNeoXForCausalLM",Mn]],["codegen",["CodeGenForCausalLM",Bn]],["llama",["LlamaForCausalLM",Dn]],["qwen2",["Qwen2ForCausalLM",Un]],["phi",["PhiForCausalLM",Gn]],["mpt",["MptForCausalLM",Xn]],["opt",["OPTForCausalLM",Jn]],["mbart",["MBartForCausalLM",xt]],["mistral",["MistralForCausalLM",ei]],["starcoder2",["Starcoder2ForCausalLM",ri]],["falcon",["FalconForCausalLM",si]],["trocr",["TrOCRForCausalLM",Qa]],["stablelm",["StableLmForCausalLM",yi]]]),Di=new Map([["bert",["BertForMaskedLM",N]],["roformer",["RoFormerForMaskedLM",K]],["electra",["ElectraForMaskedLM",se]],["esm",["EsmForMaskedLM",Fe]],["convbert",["ConvBertForMaskedLM",ee]],["camembert",["CamembertForMaskedLM",pe]],["deberta",["DebertaForMaskedLM",we]],["deberta-v2",["DebertaV2ForMaskedLM",Te]],["mpnet",["MPNetForMaskedLM",qe]],["albert",["AlbertForMaskedLM",it]],["distilbert",["DistilBertForMaskedLM",Oe]],["roberta",["RobertaForMaskedLM",Pt]],["xlm",["XLMWithLMHeadModel",Dt]],["xlm-roberta",["XLMRobertaForMaskedLM",Gt]],["mobilebert",["MobileBertForMaskedLM",Ue]],["squeezebert",["SqueezeBertForMaskedLM",Ze]]]),Li=new Map([["bert",["BertForQuestionAnswering",V]],["roformer",["RoFormerForQuestionAnswering",Q]],["electra",["ElectraForQuestionAnswering",ue]],["convbert",["ConvBertForQuestionAnswering",re]],["camembert",["CamembertForQuestionAnswering",me]],["deberta",["DebertaForQuestionAnswering",ve]],["deberta-v2",["DebertaV2ForQuestionAnswering",ke]],["mpnet",["MPNetForQuestionAnswering",Ye]],["albert",["AlbertForQuestionAnswering",at]],["distilbert",["DistilBertForQuestionAnswering",Pe]],["roberta",["RobertaForQuestionAnswering",Bt]],["xlm",["XLMForQuestionAnswering",Ut]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ht]],["mobilebert",["MobileBertForQuestionAnswering",Ve]],["squeezebert",["SqueezeBertForQuestionAnswering",et]]]),Ni=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",tn]]]),Ui=new Map([["llava",["LlavaForConditionalGeneration",rn]]]),Wi=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",tn]]]),Vi=new Map([["vit",["ViTForImageClassification",nr]],["mobilevit",["MobileViTForImageClassification",or]],["beit",["BeitForImageClassification",gr]],["deit",["DeiTForImageClassification",Er]],["convnext",["ConvNextForImageClassification",Qr]],["convnextv2",["ConvNextV2ForImageClassification",ea]],["dinov2",["Dinov2ForImageClassification",ra]],["resnet",["ResNetForImageClassification",Pr]],["swin",["SwinForImageClassification",Br]],["segformer",["SegformerForImageClassification",mi]],["efficientnet",["EfficientNetForImageClassification",$i]]]),Gi=new Map([["detr",["DetrForObjectDetection",yr]],["table-transformer",["TableTransformerForObjectDetection",Sr]],["yolos",["YolosForObjectDetection",sa]]]),ji=new Map([["owlvit",["OwlViTForObjectDetection",dr]],["owlv2",["Owlv2ForObjectDetection",hr]]]),qi=new Map([["detr",["DetrForSegmentation",br]],["clipseg",["CLIPSegForImageSegmentation",_n]]]),Hi=new Map([["segformer",["SegformerForSemanticSegmentation",gi]]]),Ki=new Map([["sam",["SamModel",ua]]]),Yi=new Map([["wav2vec2",["Wav2Vec2ForCTC",ya]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Oa]],["unispeech",["UniSpeechForCTC",Ta]],["unispeech-sat",["UniSpeechSatForCTC",Ca]],["wavlm",["WavLMForCTC",Ua]],["hubert",["HubertForCTC",Ra]]]),Xi=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ba]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",za]],["unispeech",["UniSpeechForSequenceClassification",Sa]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Ea]],["wavlm",["WavLMForSequenceClassification",Wa]],["hubert",["HubertForSequenceClassification",Da]],["audio-spectrogram-transformer",["ASTForAudioClassification",Xt]]]),Qi=new Map([["wavlm",["WavLMForXVector",Va]]]),Zi=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Aa]],["wavlm",["WavLMForAudioFrameClassification",Ga]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",va]]]),Ji=new Map([["vitmatte",["VitMatteForImageMatting",ar]]]),es=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Dr]]]),ts=new Map([["dpt",["DPTForDepthEstimation",Ur]],["depth_anything",["DepthAnythingForDepthEstimation",Vr]],["glpn",["GLPNForDepthEstimation",qr]]]),ns=new Map([["clip",["CLIPVisionModelWithProjection",ln]],["siglip",["SiglipVisionModel",pn]]]),rs=[[Ci,m],[Ei,g],[Ai,y],[zi,m],[Bi,m],[Fi,_],[Ii,_],[Ri,y],[Di,m],[Li,m],[Ni,w],[Ui,v],[Vi,m],[qi,m],[Hi,m],[Ji,m],[es,m],[ts,m],[Gi,m],[ji,m],[Ki,b],[Yi,m],[Xi,m],[Pi,_],[Oi,m],[Qi,m],[Zi,m],[ns,m]];for(const[e,t]of rs)for(const[n,r]of e.values())x.set(n,t),S.set(r,n),T.set(n,r);const as=[["MusicgenForConditionalGeneration",Mi,$],["CLIPTextModelWithProjection",on,m],["SiglipTextModel",cn,m],["ClapTextModelWithProjection",ui,m],["ClapAudioModelWithProjection",di,m]];for(const[e,t,n]of as)x.set(e,n),S.set(t,e),T.set(e,t);class is extends ki{static MODEL_CLASS_MAPPINGS=rs.map((e=>e[0]));static BASE_IF_FAIL=!0}class ss extends ki{static MODEL_CLASS_MAPPINGS=[zi]}class os extends ki{static MODEL_CLASS_MAPPINGS=[Bi]}class ls extends ki{static MODEL_CLASS_MAPPINGS=[Fi]}class us extends ki{static MODEL_CLASS_MAPPINGS=[Ii]}class ds extends ki{static MODEL_CLASS_MAPPINGS=[Pi]}class cs extends ki{static MODEL_CLASS_MAPPINGS=[Oi]}class ps extends ki{static MODEL_CLASS_MAPPINGS=[Ri]}class hs extends ki{static MODEL_CLASS_MAPPINGS=[Di]}class fs extends ki{static MODEL_CLASS_MAPPINGS=[Li]}class ms extends ki{static MODEL_CLASS_MAPPINGS=[Ni]}class gs extends ki{static MODEL_CLASS_MAPPINGS=[Vi]}class _s extends ki{static MODEL_CLASS_MAPPINGS=[qi]}class ws extends ki{static MODEL_CLASS_MAPPINGS=[Hi]}class ys extends ki{static MODEL_CLASS_MAPPINGS=[Gi]}class bs extends ki{static MODEL_CLASS_MAPPINGS=[ji]}class vs extends ki{static MODEL_CLASS_MAPPINGS=[Ki]}class $s extends ki{static MODEL_CLASS_MAPPINGS=[Yi]}class xs extends ki{static MODEL_CLASS_MAPPINGS=[Xi]}class Ts extends ki{static MODEL_CLASS_MAPPINGS=[Qi]}class Ss extends ki{static MODEL_CLASS_MAPPINGS=[Zi]}class Ms extends ki{static MODEL_CLASS_MAPPINGS=[Wi]}class ks extends ki{static MODEL_CLASS_MAPPINGS=[Ji]}class Cs extends ki{static MODEL_CLASS_MAPPINGS=[es]}class Es extends ki{static MODEL_CLASS_MAPPINGS=[ts]}class As extends ki{static MODEL_CLASS_MAPPINGS=[ns]}class Is extends F{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:a=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=r,this.cross_attentions=a}}class Ps extends F{constructor({logits:e}){super(),this.logits=e}}class Os extends F{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class zs extends F{constructor({logits:e}){super(),this.logits=e}}class Bs extends F{constructor({logits:e}){super(),this.logits=e}}class Fs extends F{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class Rs extends F{constructor({logits:e}){super(),this.logits=e}}class Ds extends F{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}}class Ls extends F{constructor({alphas:e}){super(),this.alphas=e}}class Ns extends F{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}},"./src/ops/registry.js": /*!*****************************!*\ !*** ./src/ops/registry.js ***! \*****************************/(e,t,n)=>{n.r(t),n.d(t,{TensorOpRegistry:()=>s});var r=n(/*! ../backends/onnx.js */"./src/backends/onnx.js"),a=n(/*! ../utils/tensor.js */"./src/utils/tensor.js");const i=async(e,t,n)=>{const i=await(0,r.createInferenceSession)(e,t);return async e=>{const t=Object.fromEntries(Object.entries(e).map((([e,t])=>[e,t.ort_tensor]))),r=await i.run(t);return new a.Tensor(r[n])}};class s{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=i(new Uint8Array([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=i(new Uint8Array([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}}},"./src/pipelines.js": /*!**************************!*\ !*** ./src/pipelines.js ***! \**************************/(e,t,n)=>{n.r(t),n.d(t,{AudioClassificationPipeline:()=>k,AutomaticSpeechRecognitionPipeline:()=>E,DepthEstimationPipeline:()=>L,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>S,FillMaskPipeline:()=>y,ImageClassificationPipeline:()=>I,ImageFeatureExtractionPipeline:()=>M,ImageSegmentationPipeline:()=>P,ImageToImagePipeline:()=>D,ImageToTextPipeline:()=>A,ObjectDetectionPipeline:()=>z,Pipeline:()=>m,QuestionAnsweringPipeline:()=>w,SummarizationPipeline:()=>v,Text2TextGenerationPipeline:()=>b,TextClassificationPipeline:()=>g,TextGenerationPipeline:()=>x,TextToAudioPipeline:()=>R,TokenClassificationPipeline:()=>_,TranslationPipeline:()=>$,ZeroShotAudioClassificationPipeline:()=>C,ZeroShotClassificationPipeline:()=>T,ZeroShotImageClassificationPipeline:()=>O,ZeroShotObjectDetectionPipeline:()=>B,pipeline:()=>W});var r=n(/*! ./tokenizers.js */"./src/tokenizers.js"),a=n(/*! ./models.js */"./src/models.js"),i=n(/*! ./processors.js */"./src/processors.js"),s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),o=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/maths.js */"./src/utils/maths.js"),u=n(/*! ./utils/audio.js */"./src/utils/audio.js"),d=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),c=n(/*! ./utils/image.js */"./src/utils/image.js");async function p(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>c.RawImage.read(e))))}async function h(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>"string"==typeof e||e instanceof URL?(0,u.read_audio)(e,t):e instanceof Float64Array?new Float32Array(e):e)))}function f(e,t){t&&(e=e.map((e=>0|e)));const[n,r,a,i]=e;return{xmin:n,ymin:r,xmax:a,ymax:i}}class m extends s.Callable{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}}class g extends m{constructor(e){super(e)}async _call(e,{topk:t=1}={}){const n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),a="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid().data:e=>(0,l.softmax)(e.data),i=this.model.config.id2label,s=[];for(const e of r.logits){const n=a(e),r=(0,l.getTopItems)(n,t).map((e=>({label:i[e[0]],score:e[1]})));1===t?s.push(...r):s.push(r)}return Array.isArray(e)||1===t?s:s[0]}}class _ extends m{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const n=Array.isArray(e),r=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),a=(await this.model(r)).logits,i=this.model.config.id2label,s=[];for(let e=0;e[e,t])).filter((e=>e[1]>s)),d=Array.from((0,l.softmax)(a.end_logits[e].data)).map(((e,t)=>[e,t])).filter((e=>e[1]>s)),c=(0,o.product)(u,d).filter((e=>e[0][1]<=e[1][1])).map((e=>[e[0][1],e[1][1],e[0][0]*e[1][0]])).sort(((e,t)=>t[2]-e[2]));for(let e=0;e{const t=[...i];return t[s]=e[0],{score:e[1],token:e[0],token_str:this.tokenizer.model.vocab[e[0]],sequence:this.tokenizer.decode(t,{skip_special_tokens:!0})}})))}return Array.isArray(e)?a:a[0]}}class b extends m{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class v extends b{_key="summary_text";constructor(e){super(e)}}class $ extends b{_key="translation_text";constructor(e){super(e)}}class x extends m{constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class T extends m{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map((([e,t])=>[e.toLowerCase(),t]))),this.entailment_id=this.label2id.entailment,void 0===this.entailment_id&&(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,void 0===this.contradiction_id&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n="This example is {}.",multi_label:r=!1}={}){const a=Array.isArray(e);a||(e=[e]),Array.isArray(t)||(t=[t]);const i=t.map((e=>n.replace("{}",e))),s=r||1===t.length,o=[];for(const n of e){const e=[];for(const t of i){const r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),a=await this.model(r);s?e.push([a.logits.data[this.contradiction_id],a.logits.data[this.entailment_id]]):e.push(a.logits.data[this.entailment_id])}const r=(s?e.map((e=>(0,l.softmax)(e)[1])):(0,l.softmax)(e)).map(((e,t)=>[e,t])).sort(((e,t)=>t[0]-e[0]));o.push({sequence:n,labels:r.map((e=>t[e[1]])),scores:r.map((e=>e[0]))})}return a?o:o[0]}}class S extends m{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:n=!1,quantize:r=!1,precision:a="binary"}={}){const i=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(i);let o=s.last_hidden_state??s.logits;if("none"===t);else if("mean"===t)o=(0,d.mean_pooling)(o,i.attention_mask);else{if("cls"!==t)throw Error(`Pooling method '${t}' not supported.`);o=o.slice(null,0)}return n&&(o=o.normalize(2,-1)),r&&(o=(0,d.quantize_embeddings)(o,a)),o}}class M extends m{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const n=await p(e),{pixel_values:r}=await this.processor(n),a=await this.model({pixel_values:r});let i;if(t){if(!("pooler_output"in a))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");i=a.pooler_output}else i=a.last_hidden_state??a.logits??a.image_embeds;return i}}class k extends m{constructor(e){super(e)}async _call(e,{topk:t=null}={}){const n=!Array.isArray(e),r=this.processor.feature_extractor.config.sampling_rate,a=await h(e,r),i=this.model.config.id2label,s=[];for(const e of a){const n=await this.processor(e),r=(await this.model(n)).logits[0],a=(0,l.getTopItems)((0,l.softmax)(r.data),t).map((e=>({label:i[e[0]],score:e[1]})));1===t?s.push(...a):s.push(a)}return n&&1!==t?s[0]:s}}class C extends m{constructor(e){super(e)}async _call(e,t,{hypothesis_template:n="This is a sound of {}."}={}){const r=!Array.isArray(e);r&&(e=[e]);const a=t.map((e=>n.replace("{}",e))),i=this.tokenizer(a,{padding:!0,truncation:!0}),s=this.processor.feature_extractor.config.sampling_rate,o=await h(e,s),u=[];for(const e of o){const n=await this.processor(e),r=await this.model({...i,...n}),a=(0,l.softmax)(r.logits_per_audio.data);u.push([...a].map(((e,n)=>({score:e,label:t[n]}))))}return r?u[0]:u}}class E extends m{constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}async _call_wav2vec2(e,t={}){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const n=!Array.isArray(e);n&&(e=[e]);const r=this.processor.feature_extractor.config.sampling_rate,a=await h(e,r),i=[];for(const e of a){const t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(const e of n)r.push((0,l.max)(e.data)[1]);const a=this.tokenizer.decode(r);i.push({text:a})}return n?i[0]:i}async _call_whisper(e,t={}){const n=t.return_timestamps??!1,r=t.chunk_length_s??0,a=t.chunk_callback??null,i=t.force_full_sequences??!1;let s=t.stride_length_s??null;"word"===n&&(t.return_token_timestamps=!0);const u=(0,o.pop)(t,"language",null),d=(0,o.pop)(t,"task",null);if(u||d||n){if(t.forced_decoder_ids)throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.");const e=this.tokenizer.get_decoder_prompt_ids({language:u,task:d,no_timestamps:!n});e.length>0&&(t.forced_decoder_ids=e)}const c=!Array.isArray(e);c&&(e=[e]);const p=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,f=this.processor.feature_extractor.config.hop_length,m=this.processor.feature_extractor.config.sampling_rate,g=await h(e,m),_=[];for(const e of g){let o=[];if(r>0){if(null===s)s=r/6;else if(r<=s)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const t=m*r,n=m*s,a=t-2*n;let i=0;for(;i=e.length;o.push({stride:[r.length,l?0:n,u?0:n],input_features:s.input_features,is_last:u}),i+=a}}else o=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(const e of o){t.num_frames=Math.floor(e.stride[0]/f);const r=await this.model.generate({inputs:e.input_features,...t});"word"===n?(e.tokens=r.sequences[0],e.token_timestamps=r.token_timestamps.tolist()[0].map((e=>(0,l.round)(e,2)))):e.tokens=r[0],e.stride=e.stride.map((e=>e/m)),null!==a&&a(e)}const[u,d]=this.tokenizer._decode_asr(o,{time_precision:p,return_timestamps:n,force_full_sequences:i});_.push({text:u,...d})}return c?_[0]:_}}class A extends m{constructor(e){super(e)}async _call(e,t={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class I extends m{constructor(e){super(e)}async _call(e,{topk:t=1}={}){const n=Array.isArray(e),r=await p(e),{pixel_values:a}=await this.processor(r),i=await this.model({pixel_values:a}),s=this.model.config.id2label,o=[];for(const e of i.logits){const n=(0,l.getTopItems)((0,l.softmax)(e.data),t).map((e=>({label:s[e[0]],score:e[1]})));1===t?o.push(...n):o.push(n)}return n||1===t?o:o[0]}}class P extends m{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:a=null,target_sizes:i=null,subtask:s=null}={}){if(Array.isArray(e)&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const o=await p(e),l=o.map((e=>[e.height,e.width])),{pixel_values:u,pixel_mask:d}=await this.processor(o),h=await this.model({pixel_values:u,pixel_mask:d});let f=null;if(null!==s)f=this.subtasks_mapping[s];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.feature_extractor){f=this.processor.feature_extractor[t].bind(this.processor.feature_extractor),s=e;break}const m=this.model.config.id2label,g=[];if("panoptic"===s||"instance"===s){const e=f(h,t,n,r,a,i??l)[0],s=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(s.data.length);for(let n=0;nn.replace("{}",e))),s=this.tokenizer(i,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:o}=await this.processor(a),u=await this.model({...s,pixel_values:o}),d="siglip"===this.model.config.model_type?e=>e.sigmoid().data:e=>(0,l.softmax)(e.data),c=[];for(const e of u.logits_per_image){const n=[...d(e)].map(((e,n)=>({score:e,label:t[n]})));n.sort(((e,t)=>t.score-e.score)),c.push(n)}return r?c:c[0]}}class z extends m{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:n=!1}={}){const r=Array.isArray(e);if(r&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");const a=await p(e),i=n?null:a.map((e=>[e.height,e.width])),{pixel_values:s,pixel_mask:o}=await this.processor(a),l=await this.model({pixel_values:s,pixel_mask:o}),u=this.processor.feature_extractor.post_process_object_detection(l,t,i),d=this.model.config.id2label,c=u.map((e=>e.boxes.map(((t,r)=>({score:e.scores[r],label:d[e.classes[r]],box:f(t,!n)})))));return r?c:c[0]}}class B extends m{constructor(e){super(e)}async _call(e,t,{threshold:n=.1,topk:r=null,percentage:a=!1}={}){const i=Array.isArray(e),s=await p(e),o=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(s),u=[];for(let e=0;e({score:h.scores[n],label:t[h.classes[n]],box:f(e,!a)}))).sort(((e,t)=>t.score-e.score));null!==r&&(m=m.slice(0,r)),u.push(m)}return i?u:u[0]}}class F extends m{constructor(e){super(e)}async _call(e,t,n={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class R extends m{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),r=this.model.config.sampling_rate;return{audio:n.data,sampling_rate:r}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){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"})),("string"==typeof t||t instanceof URL)&&(t=new Float32Array(await(await fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new d.Tensor("float32",t,[1,t.length]);else if(!(t instanceof d.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),i=this.processor.feature_extractor.config.sampling_rate;return{audio:r.data,sampling_rate:i}}}class D extends m{constructor(e){super(e)}async _call(e){const t=await p(e),n=await this.processor(t),r=await this.model(n),a=[];for(const e of r.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");a.push(c.RawImage.fromTensor(t))}return a.length>1?a:a[0]}}class L extends m{constructor(e){super(e)}async _call(e){const t=await p(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),a=[];for(let e=0;e1?a:a[0]}}const N=Object.freeze({"text-classification":{tokenizer:r.AutoTokenizer,pipeline:g,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:r.AutoTokenizer,pipeline:_,model:a.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:r.AutoTokenizer,pipeline:w,model:a.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:r.AutoTokenizer,pipeline:y,model:a.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:r.AutoTokenizer,pipeline:v,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:r.AutoTokenizer,pipeline:$,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:r.AutoTokenizer,pipeline:b,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:r.AutoTokenizer,pipeline:x,model:a.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:r.AutoTokenizer,pipeline:T,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:k,model:a.AutoModelForAudioClassification,processor:i.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:r.AutoTokenizer,pipeline:C,model:a.AutoModel,processor:i.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:r.AutoTokenizer,pipeline:E,model:[a.AutoModelForSpeechSeq2Seq,a.AutoModelForCTC],processor:i.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:r.AutoTokenizer,pipeline:R,model:[a.AutoModelForTextToWaveform,a.AutoModelForTextToSpectrogram],processor:[i.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:r.AutoTokenizer,pipeline:A,model:a.AutoModelForVision2Seq,processor:i.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:I,model:a.AutoModelForImageClassification,processor:i.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:P,model:[a.AutoModelForImageSegmentation,a.AutoModelForSemanticSegmentation],processor:i.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:r.AutoTokenizer,pipeline:O,model:a.AutoModel,processor:i.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:z,model:a.AutoModelForObjectDetection,processor:i.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:r.AutoTokenizer,pipeline:B,model:a.AutoModelForZeroShotObjectDetection,processor:i.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:r.AutoTokenizer,pipeline:F,model:a.AutoModelForDocumentQuestionAnswering,processor:i.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:D,model:a.AutoModelForImageToImage,processor:i.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:L,model:a.AutoModelForDepthEstimation,processor:i.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:r.AutoTokenizer,pipeline:S,model:a.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:i.AutoProcessor,pipeline:M,model:[a.AutoModelForImageFeatureExtraction,a.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),U=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function W(e,t=null,{progress_callback:n=null,config:r=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",device:l=null,dtype:u=null,model_file_name:d=null,session_options:c={}}={}){e=U[e]??e;const p=N[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(N)}]`);t||(t=p.default.model,console.log(`No model specified. Using default model: "${t}".`));const h={progress_callback:n,config:r,cache_dir:a,local_files_only:i,revision:s,device:l,dtype:u,model_file_name:d,session_options:c},f=new Map([["tokenizer",p.tokenizer],["model",p.model],["processor",p.processor]]),m=await async function(e,t,n){const r=Object.create(null),a=[];for(let[i,s]of e.entries()){if(!s)continue;let e;e=Array.isArray(s)?new Promise((async(e,r)=>{let a;for(let i of s){if(null===i)return void e(null);try{return void e(await i.from_pretrained(t,n))}catch(e){if(!e.message?.includes("Unsupported model type"))return void r(e);a=e}}r(a)})):s.from_pretrained(t,n),r[i]=e,a.push(e)}await Promise.all(a);for(let[e,t]of Object.entries(r))r[e]=await t;return r}(f,t,h);m.task=e,(0,o.dispatchCallback)(n,{status:"ready",task:e,model:t});return new(0,p.pipeline)(m)}},"./src/processors.js": /*!***************************!*\ !*** ./src/processors.js ***! \***************************/(e,t,n)=>{n.r(t),n.d(t,{ASTFeatureExtractor:()=>j,AutoProcessor:()=>ee,BeitFeatureExtractor:()=>z,BitImageProcessor:()=>y,CLIPFeatureExtractor:()=>v,CLIPImageProcessor:()=>$,ChineseCLIPFeatureExtractor:()=>x,ClapFeatureExtractor:()=>q,ConvNextFeatureExtractor:()=>S,ConvNextImageProcessor:()=>M,DPTFeatureExtractor:()=>_,DPTImageProcessor:()=>w,DeiTFeatureExtractor:()=>O,DetrFeatureExtractor:()=>R,DonutFeatureExtractor:()=>B,EfficientNetImageProcessor:()=>E,FeatureExtractor:()=>f,GLPNFeatureExtractor:()=>b,ImageFeatureExtractor:()=>m,MobileViTFeatureExtractor:()=>A,NougatImageProcessor:()=>F,OwlViTFeatureExtractor:()=>I,OwlViTProcessor:()=>J,Owlv2ImageProcessor:()=>P,Processor:()=>K,SamImageProcessor:()=>L,SamProcessor:()=>Y,SeamlessM4TFeatureExtractor:()=>G,SegformerFeatureExtractor:()=>g,SiglipImageProcessor:()=>T,SpeechT5FeatureExtractor:()=>H,SpeechT5Processor:()=>Z,Swin2SRImageProcessor:()=>N,ViTFeatureExtractor:()=>k,ViTImageProcessor:()=>C,VitMatteImageProcessor:()=>U,Wav2Vec2FeatureExtractor:()=>V,Wav2Vec2ProcessorWithLM:()=>Q,WhisperFeatureExtractor:()=>W,WhisperProcessor:()=>X,YolosFeatureExtractor:()=>D});var r=n(/*! ./utils/generic.js */"./src/utils/generic.js"),a=n(/*! ./utils/core.js */"./src/utils/core.js"),i=n(/*! ./utils/hub.js */"./src/utils/hub.js"),s=n(/*! ./utils/maths.js */"./src/utils/maths.js"),o=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=(n(/*! ./utils/image.js */"./src/utils/image.js"),n(/*! ./utils/audio.js */"./src/utils/audio.js"));function u([e,t,n,r]){return[e-n/2,t-r/2,e+n/2,t+r/2]}function d(e,t=.5,n=null,r=!1){const a=e.logits,i=e.pred_boxes,[o,l,d]=a.dims;if(null!==n&&n.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let e=0;et&&i.push(e)}else{let e=(0,s.max)(a.data)[1];if(e===d-1)continue;if(n=(0,s.softmax)(a.data),n[e]e*o[(t+1)%2]))),p.boxes.push(r),p.classes.push(t),p.scores.push(n[t])}}c.push(p)}return c}function c(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function p(e,t,n=0,r=null){const a=e/t;let i=(0,s.bankers_round)(a)*t;return null!==r&&i>r&&(i=Math.floor(a)*t),ia?l=Math.floor(a*o/r):a>r&&(o=Math.floor(r*l/a)),await e.resize(l,o,{resample:n}))}async crop_margin(e,t=200){const n=e.clone().grayscale(),r=(0,s.min)(n.data)[0],a=(0,s.max)(n.data)[0]-r;if(0===a)return e;const i=t/255;let o=n.width,l=n.height,u=0,d=0;const c=n.data;for(let e=0;ethis.preprocess(e))));return{pixel_values:(0,o.stack)(n.map((e=>e.pixel_values)),0),original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class g extends m{post_process_semantic_segmentation(e,t=null){const n=e.logits,r=n.dims[0];if(null!==t&&t.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const a=[];for(let e=0;ed[n]&&(d[n]=t[n],c[n]=e)}const p=new Array(i.dims[0]),h=u.data;for(let e=0;evoid 0!==e));a.push({segmentation:u,labels:f})}return a}}class _ extends m{}class w extends _{}class y extends m{}class b extends m{}class v extends m{}class $ extends v{}class x extends m{}class T extends m{}class S extends m{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){const t=this.size?.shortest_edge;if(void 0===t)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const n=Math.floor(t/this.crop_pct),[r,a]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,a,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class M extends S{}class k extends m{}class C extends m{}class E extends m{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map((e=>e*e)))}}class A extends m{}class I extends m{post_process_object_detection(...e){return d(...e)}}class P extends I{}class O extends m{}class z extends m{}class B extends m{pad_image(e,t,n,r={}){const[a,i,s]=t;let o=this.image_mean;Array.isArray(this.image_mean)||(o=new Array(s).fill(o));let l=this.image_std;Array.isArray(l)||(l=new Array(s).fill(o));const u=o.map(((e,t)=>-e/l[t]));return super.pad_image(e,t,n,{center:!0,constant_values:u,...r})}}class F extends B{}class R extends m{async _call(e){const t=await super._call(e),n=[t.pixel_values.dims[0],64,64],r=new o.Tensor("int64",new BigInt64Array(n.reduce(((e,t)=>e*t))).fill(1n),n);return{...t,pixel_mask:r}}post_process_object_detection(...e){return d(...e)}remove_low_and_no_objects(e,t,n,r){let a=[],i=[],o=[];for(let l=0;ln&&(a.push(d),i.push(p),o.push(c))}return[a,i,o]}check_segment_validity(e,t,n,r=.5,a=.8){let i=[],s=0,o=0;const l=t[n].data;for(let t=0;t=r&&++o;let u=s>0&&o>0;if(u){u=s/o>a}return[u,i]}compute_segments(e,t,n,r,a,i=null,s=null){let[l,u]=s??e[0].dims,d=new o.Tensor("int32",new Int32Array(l*u),[l,u]),c=[];if(null!==s)for(let t=0;th[e]&&(p[e]=n,h[e]=a[e])}let f=0;const m=d.data;for(let i=0;ie!==t.dims[n])))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",e.flat(1/0).map(BigInt),n)}async _call(e,t=null,n=null,r=null){const a=await super._call(e);if(t&&(a.input_points=this.reshape_input_points(t,a.original_sizes,a.reshaped_input_sizes)),n){if(!a.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");a.input_labels=this.add_input_labels(n,a.input_points)}return r&&(a.input_boxes=this.reshape_input_points(r,a.original_sizes,a.reshaped_input_sizes,!0)),a}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:a=!0,pad_size:i=null}={}){const s=[],l=[(i=i??this.pad_size).height,i.width];for(let i=0;ir&&(t[n]=1);c=new o.Tensor("bool",t,c.dims)}s.push(c)}return s}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:a=32,crop_n_points_downscale_factor:i=1}={}){}}class N extends m{pad_image(e,t,n,r={}){const[a,i,s]=t;return super.pad_image(e,t,{width:i+(n-i%n)%n,height:a+(n-a%n)%n},{mode:"symmetric",center:!1,constant_values:-1,...r})}}class U extends m{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const n=await Promise.all(e.map((e=>this.preprocess(e)))),r=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0}))));return{pixel_values:(0,o.stack)(n.map(((e,t)=>(0,o.cat)([e.pixel_values,r[t].pixel_values],0))),0),original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class W extends f{constructor(e){super(e),this.config.mel_filters??=(0,l.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=(0,l.window_function)(this.config.n_fft,"hann")}_extract_fbank_features(e){const{data:t,dims:n}=(0,l.spectrogram)(e,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}),r=(0,s.max)(t)[0];for(let e=0;ethis.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=e.slice(0,this.config.n_samples)):(t=new Float32Array(this.config.n_samples),t.set(e));const{data:n,dims:r}=this._extract_fbank_features(t);return{input_features:new o.Tensor("float32",n,[1,...r])}}}class V extends f{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,n=e.reduce(((e,n)=>e+(n-t)**2),0)/e.length;return e.map((e=>(e-t)/Math.sqrt(n+1e-7)))}async _call(e){c(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const n=[1,t.length];return{input_values:new o.Tensor("float32",t,n),attention_mask:new o.Tensor("int64",new BigInt64Array(t.length).fill(1n),n)}}}class G extends f{constructor(e){super(e);const t=this.config.sampling_rate,n=(0,l.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e32768*e)),(0,l.spectrogram)(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:a=!0}={}){c(e,"SeamlessM4TFeatureExtractor");let i=this._extract_fbank_features(e,this.config.max_length);const s=i.data;if(r){const[e,t]=i.dims;for(let n=0;n0){const n=new Float32Array(t*(e+r));n.set(s),n.fill(this.config.padding_value,s.length);const u=e+r;i={data:n,dims:[u,t]},a&&(l=new o.Tensor("int64",new BigInt64Array(u),[1,u]),l.data.fill(1n,0,e))}}const[u,d]=i.dims,p=this.config.stride;if(0!==u%p)throw new Error(`The number of frames (${u}) must be a multiple of the stride (${p}).`);const h=new o.Tensor("float32",s,i.dims).view(1,Math.floor(u/p),d*p),f={input_features:h};if(a){const e=h.dims[1],t=new BigInt64Array(e);if(l){const e=l.data;for(let n=1,r=0;n0){if("rand_trunc"!==n)throw new Error(`Truncation strategy "${n}" not implemented`);{i=!0;const n=Math.floor(Math.random()*(s+1));e=e.subarray(n,n+t),a=this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples),a.dims=[1,...a.dims]}}else{if(s<0){let n=new Float64Array(t);if(n.set(e),"repeat"===r)for(let r=e.length;r{n.r(t),n.d(t,{AlbertTokenizer:()=>_e,AutoTokenizer:()=>ct,BartTokenizer:()=>Ie,BertTokenizer:()=>ge,BlenderbotSmallTokenizer:()=>st,BlenderbotTokenizer:()=>it,BloomTokenizer:()=>Be,CLIPTokenizer:()=>tt,CamembertTokenizer:()=>Me,CodeGenTokenizer:()=>et,CodeLlamaTokenizer:()=>De,CohereTokenizer:()=>dt,ConvBertTokenizer:()=>xe,DebertaTokenizer:()=>be,DebertaV2Tokenizer:()=>ve,DistilBertTokenizer:()=>Se,ElectraTokenizer:()=>Ce,EsmTokenizer:()=>Ve,FalconTokenizer:()=>Ue,GPT2Tokenizer:()=>Ae,GPTNeoXTokenizer:()=>We,GemmaTokenizer:()=>je,Grok1Tokenizer:()=>qe,HerbertTokenizer:()=>$e,LlamaTokenizer:()=>Re,M2M100Tokenizer:()=>Ye,MBart50Tokenizer:()=>Oe,MBartTokenizer:()=>Pe,MPNetTokenizer:()=>Ne,MarianTokenizer:()=>rt,MobileBertTokenizer:()=>we,NllbTokenizer:()=>Ke,NougatTokenizer:()=>lt,PreTrainedTokenizer:()=>me,Qwen2Tokenizer:()=>Ge,RoFormerTokenizer:()=>Te,RobertaTokenizer:()=>ze,SiglipTokenizer:()=>nt,SpeechT5Tokenizer:()=>ot,SqueezeBertTokenizer:()=>ye,T5Tokenizer:()=>Ee,TokenizerModel:()=>y,VitsTokenizer:()=>ut,Wav2Vec2CTCTokenizer:()=>at,WhisperTokenizer:()=>Je,XLMRobertaTokenizer:()=>Le,XLMTokenizer:()=>ke});var r=n(/*! ./utils/generic.js */"./src/utils/generic.js"),a=n(/*! ./utils/core.js */"./src/utils/core.js"),i=n(/*! ./utils/hub.js */"./src/utils/hub.js"),s=n(/*! ./utils/maths.js */"./src/utils/maths.js"),o=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=n(/*! ./utils/data-structures.js */"./src/utils/data-structures.js"),u=n(/*! @huggingface/jinja */"./node_modules/@huggingface/jinja/dist/index.js");async function d(e,t){const n=await Promise.all([(0,i.getModelJSON)(e,"tokenizer.json",!0,t),(0,i.getModelJSON)(e,"tokenizer_config.json",!0,t)]);return null!==t.legacy&&(n[1].legacy=t.legacy),n}function c(e,t=!0){if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,n]of _)t=t.replaceAll(e,n);return new RegExp(t,"gu")}if(void 0!==e.String){const n=(0,a.escapeRegExp)(e.String);return new RegExp(t?n:`(${n})`,"gu")}return console.warn("Unknown pattern type:",e),null}function p(e){return new Map(Object.entries(e))}function h(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(1!==t[0])throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}function f(e){return e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function m(e){return e.replace(/[\u0300-\u036f]/g,"")}const g="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",_=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"]]);class w{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??null}}class y extends r.Callable{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new b(e);case"Unigram":return new v(e,...t);case"BPE":return new T(e);default:if(e.vocab)return new S(e,...t);throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=function(e,t,n){const r=[];let a=0;for(;athis.tokens_to_ids.get(e)??this.unk_token_id))}convert_ids_to_tokens(e){return e.map((e=>this.vocab[e]??this.unk_token))}}class b extends y{constructor(e){super(e),this.tokens_to_ids=p(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){const t=[];for(const n of e){const e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,a=0;const i=[];for(;a0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(null===n){r=!0;break}i.push(n),a=t}r?t.push(this.unk_token):t.push(...i)}return t}}class v extends y{constructor(e,t){super(e);const n=e.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let t=0;t[e,t]))),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=t.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,s.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.sentence,n=t.length;let r=0;for(;r{const e=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},((e,t)=>t+"!".charCodeAt(0))),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},((e,t)=>t+"¡".charCodeAt(0))),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},((e,t)=>t+"®".charCodeAt(0)))],t=e.slice();let n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);const r=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,r[t]])))})(),x=(0,a.reverseDictionary)($);class T extends y{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=p(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e;this.bpe_ranks=new Map(e.merges.map(((e,t)=>[e,t]))),this.merges=e.merges.map((e=>e.split(this.BPE_SPLIT_TOKEN))),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(e){if(0===e.length)return[];const t=this.cache.get(e);if(void 0!==t)return t;const n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){const e=new l.PriorityQueue(((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`))):t.push(this.unk_token)}return t}}class S extends y{constructor(e,t){super(e),this.tokens_to_ids=p(t.target_lang?e.vocab[t.target_lang]:e.vocab),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.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[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}}class M extends r.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new F(e);case"Precompiled":return new oe(e);case"Sequence":return new B(e);case"Replace":return new k(e);case"NFC":return new C(e);case"NFKC":return new E(e);case"NFKD":return new A(e);case"Strip":return new I(e);case"StripAccents":return new P(e);case"Lowercase":return new O(e);case"Prepend":return new z(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class k extends M{normalize(e){const t=c(this.config.pattern);return null===t?e:e.replaceAll(t,this.config.content)}}class C extends M{normalize(e){return e=e.normalize("NFC")}}class E extends M{normalize(e){return e=e.normalize("NFKC")}}class A extends M{normalize(e){return e=e.normalize("NFKD")}}class I extends M{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class P extends M{normalize(e){return e=m(e)}}class O extends M{normalize(e){return e=e.toLowerCase()}}class z extends M{normalize(e){return e=this.config.prepend+e}}class B extends M{constructor(e){super(e),this.normalizers=e.normalizers.map((e=>M.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class F extends M{_tokenize_chinese_chars(e){const t=[];for(let n=0;n=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103}stripAccents(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_is_control(e){switch(e){case"\t":case"\n":case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}_clean_text(e){const t=[];for(const n of e){const e=n.charCodeAt(0);0===e||65533===e||this._is_control(n)||(/^\s$/.test(n)?t.push(" "):t.push(n))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this._clean_text(e)),this.config.handle_chinese_chars&&(e=this._tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),!1!==this.config.strip_accents&&(e=this.stripAccents(e))):this.config.strip_accents&&(e=this.stripAccents(e)),e}}class R extends r.Callable{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new D(e);case"Sequence":return new le(e);case"Whitespace":return new ue(e);case"WhitespaceSplit":return new de(e);case"Metaspace":return new ie(e);case"ByteLevel":return new L(e);case"Split":return new N(e);case"Punctuation":return new U(e);case"Digits":return new W(e);case"Replace":return new ce(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e,t){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e,t){return(Array.isArray(e)?e.map((e=>this.pre_tokenize_text(e,t))):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}}class D extends R{constructor(e){super(),this.pattern=new RegExp(`[^\\s${g}]+|[${g}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class L extends R{constructor(e){super(),this.config=e,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=$,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e);return(this.use_regex?e.match(this.pattern)||[]:[e]).map((e=>Array.from(this.text_encoder.encode(e),(e=>this.byte_encoder[e])).join("")))}}class N extends R{constructor(e){super(),this.config=e,this.pattern=c(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:function(e,t){const n=[];let r=0;for(const a of e.matchAll(t)){const t=a[0];r0&&n.push(t),r=a.index+t.length}return re.replaceAll(t,this.config.content)))}}class X extends K{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let n=[];for(const r of e){let e=null;if(6===r.length&&r.startsWith("<0x")&&r.endsWith(">")){const t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)n.push(e);else{if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}}class Q extends K{decode_chain(e){return[e.join("")]}}class Z extends K{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map((e=>{let t=0;for(let n=0;n(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=f(e)),e)))}}class ee extends K{constructor(e){super(e),this.byte_decoder=x,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),n=new Uint8Array([...t].map((e=>this.byte_decoder[e])));return this.text_decoder.decode(n)}decode_chain(e){const t=[];let n=[];for(const r of e)void 0!==this.added_tokens.find((e=>e.content===r))?(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r)):n.push(r);return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}}class te extends K{constructor(e){super(e),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(e){if(0===e.length)return"";const t=[e[0]];for(let n=1;ne!==this.pad_token)).join("");return this.cleanup&&(n=f(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class ne extends K{constructor(e){super(e),this.decoders=e.decoders.map((e=>K.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class re extends K{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,n)=>t.replaceAll(this.suffix,n===e.length-1?"":" ")))}}class ae extends K{decode_chain(e){let t="";for(let n=1;ne.normalize("NFKC"))).join("~")}else e=e.normalize("NFKC");return e}}class le extends R{constructor(e){super(),this.tokenizers=e.pretokenizers.map((e=>R.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,n)=>n.pre_tokenize(e,t)),[e])}}class ue extends R{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class de extends R{constructor(e){super()}pre_tokenize_text(e,t){return function(e){return e.match(/\S+/g)||[]}(e)}}class ce extends R{constructor(e){super(),this.config=e,this.pattern=c(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,t){return null===this.pattern?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const pe=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function he(e,t,n,r){for(const i of Object.keys(e)){const s=t-e[i].length,o=n(i),l=new Array(s).fill(o);e[i]="right"===r?(0,a.mergeArrays)(e[i],l):(0,a.mergeArrays)(l,e[i])}}function fe(e,t){for(const n of Object.keys(e))e[n].length=t}class me extends r.Callable{return_token_type_ids=!1;_default_chat_template="{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}";padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=M.fromConfig(e.normalizer),this.pre_tokenizer=R.fromConfig(e.pre_tokenizer),this.model=y.fromConfig(e.model,t),this.post_processor=V.fromConfig(e.post_processor),this.decoder=K.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const t of e.added_tokens){const e=new w(t);this.added_tokens.push(e),this.model.tokens_to_ids.set(e.content,e.id),this.model.vocab[e.id]=e.content,e.special&&(this.special_tokens.push(e.content),this.all_special_ids.push(e.id))}if(this.additional_special_tokens=t.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.map((e=>`${e.lstrip?"\\s*":""}(${(0,a.escapeRegExp)(e.content)})${e.rstrip?"\\s*":""}`)).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,t.padding_side&&(this.padding_side=t.padding_side),this.legacy=!1,this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const e=Object.create(null);for(const{name:t,template:n}of this.chat_template){if("string"!=typeof t||"string"!=typeof n)throw new Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map}getToken(...e){for(const t of e){const e=this._tokenizer_config[t];if(e){if("object"==typeof e){if("AddedToken"===e.__type)return e.content;throw Error(`Unknown token: ${e}`)}return e}}return null}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:a=!1,revision:i="main",legacy:s=null}={}){return new this(...await d(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:a,revision:i,legacy:s}))}_call(e,{text_pair:t=null,add_special_tokens:n=!0,padding:r=!1,truncation:a=null,max_length:i=null,return_tensor:l=!0}={}){const u=Array.isArray(e);let d;if(u){if(0===e.length)throw Error("text array must be non-empty");if(null!==t){if(!Array.isArray(t))throw Error("text_pair must also be an array");if(e.length!==t.length)throw Error("text and text_pair must have the same length");d=e.map(((e,r)=>this._encode_plus(e,{text_pair:t[r],add_special_tokens:n})))}else d=e.map((e=>this._encode_plus(e,{add_special_tokens:n})))}else{if(null==e)throw Error("text may not be null or undefined");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");d=[this._encode_plus(e,{text_pair:t,add_special_tokens:n})]}if(null===i?i="max_length"===r?this.model_max_length:(0,s.max)(d.map((e=>e.input_ids.length)))[0]:a||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."),i=Math.min(i,this.model_max_length),r||a)for(let e=0;ei?a&&fe(d[e],i):r&&he(d[e],i,(e=>"input_ids"===e?this.pad_token_id:0),this.padding_side));const c={};if(l){if((!r||!a)&&d.some((e=>{for(const t of Object.keys(e))if(e[t].length!==d[0][t]?.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 e=[d.length,d[0].input_ids.length];for(const t of Object.keys(d[0]))c[t]=new o.Tensor("int64",BigInt64Array.from(d.flatMap((e=>e[t])).map(BigInt)),e)}else{for(const e of Object.keys(d[0]))c[e]=d.map((t=>t[e]));if(!u)for(const e of Object.keys(c))c[e]=c[e][0]}return c}_encode_text(e){if(null===e)return null;const t=(this.added_tokens_regex?e.split(this.added_tokens_regex).filter((e=>e)):[e]).map(((e,t)=>{if(void 0!==this.added_tokens.find((t=>t.content===e)))return e;{if(!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=function(e){return m(e.toLowerCase())}(e)),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];const n=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(n)}})).flat();return t}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0}={}){const{tokens:r,token_type_ids:a}=this._tokenize_helper(e,{pair:t,add_special_tokens:n}),i=this.model.convert_tokens_to_ids(r),s={input_ids:i,attention_mask:new Array(i.length).fill(1)};return this.return_token_type_ids&&a&&(s.token_type_ids=a),s}_tokenize_helper(e,{pair:t=null,add_special_tokens:n=!1}={}){const r=this._encode_text(e),i=this._encode_text(t);return this.post_processor?this.post_processor(r,i,{add_special_tokens:n}):{tokens:(0,a.mergeArrays)(r??[],i??[])}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:n}).tokens}encode(e,{text_pair:t=null,add_special_tokens:n=!0}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:n}).input_ids}batch_decode(e,t={}){return e instanceof o.Tensor&&(e=e.tolist()),e.map((e=>this.decode(e,t)))}decode(e,t={}){if(e instanceof o.Tensor&&(e=h(e)),!Array.isArray(e)||0===e.length||!(0,a.isIntegralNumber)(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){let r=this.model.convert_ids_to_tokens(e);t&&(r=r.filter((e=>!this.special_tokens.includes(e))));let a=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(a=a.replaceAll(this.decoder.end_of_word_suffix," "),t&&(a=a.trim())),(n??this.clean_up_tokenization_spaces)&&(a=f(a)),a}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(e,{chat_template:t=null,add_generation_prompt:n=!1,tokenize:r=!0,padding:a=!1,truncation:i=!1,max_length:s=null,return_tensor:o=!0,tokenizer_kwargs:l={},...d}={}){if(this.chat_template&&"object"==typeof this.chat_template||null===this.chat_template&&this.default_chat_template&&"object"==typeof this.default_chat_template){const e=this.chat_template??this.default_chat_template;if(null!==t&&Object.hasOwn(e,t))t=e[t];else if(null===t&&"default"in e)t=e.default;else if(null===t)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(e).sort()}.`)}else t??=this.chat_template??this.default_chat_template;if("string"!=typeof t)throw Error("chat_template must be a string, but got "+typeof t);let c=this._compiled_template_cache.get(t);void 0===c&&(c=new u.Template(t),this._compiled_template_cache.set(t,c));const p=Object.create(null);for(const e of pe){const t=this.getToken(e);t&&(p[e]=t)}const h=c.render({messages:e,add_generation_prompt:n,...p,...d});return r?this._call(h,{add_special_tokens:!1,padding:a,truncation:i,max_length:s,return_tensor:o,...l}).input_ids:h}}class ge extends me{return_token_type_ids=!0}class _e extends me{return_token_type_ids=!0}class we extends me{return_token_type_ids=!0}class ye extends me{return_token_type_ids=!0}class be extends me{return_token_type_ids=!0}class ve extends me{return_token_type_ids=!0}class $e extends me{return_token_type_ids=!0}class xe extends me{return_token_type_ids=!0}class Te extends me{return_token_type_ids=!0}class Se extends me{}class Me extends me{}class ke extends me{return_token_type_ids=!0;constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ce extends me{return_token_type_ids=!0}class Ee extends me{}class Ae extends me{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}'}class Ie extends me{}class Pe extends me{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return He(this,e,t,n)}}class Oe extends Pe{}class ze extends me{}class Be extends Ae{constructor(e,t){const n=".,!?…。,、।۔،",r=e.pre_tokenizer?.pretokenizers[0]?.pattern;r&&r.Regex===` ?[^(\\s|[${n}])]+`&&(r.Regex=` ?[^\\s${n}]+`),super(e,t)}}const Fe="▁";class Re extends me{_default_chat_template="{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<>\n' + system_message + '\n<>\n\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<>\n' + content.strip() + '\n<>\n\n' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}";DEFAULT_SYSTEM_PROMPT="You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.";padding_side="left";constructor(e,t){super(e,t),this.use_default_system_prompt=t.use_default_system_prompt??!1,this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new ie({replacement:Fe,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(e){if(null===e)return null;if(this.legacy||0===e.length)return super._encode_text(e);let t=super._encode_text(Fe+e.replaceAll(Fe," "));return t.length>1&&t[0]===Fe&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll("\n","\\n").replaceAll("'","\\'"))}}class De extends Re{}class Le extends me{}class Ne extends me{}class Ue extends me{}class We extends me{}class Ve extends me{}class Ge extends me{}class je extends me{_default_chat_template="{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + '\n' + message['content'] | trim + '\n' }}{% endfor %}{% if add_generation_prompt %}{{'model\n'}}{% endif %}"}class qe extends me{}function He(e,t,n,r){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e&&e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||"function"!=typeof e.lang_to_token)throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const a=r.src_lang,i=r.tgt_lang;if(!e.language_codes.includes(i))throw new Error(`Target language code "${i}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==a){if(!e.language_codes.includes(a))throw new Error(`Source language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const t of e.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(a);break}}return r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(i)])[0],e._call(t,n)}class Ke extends me{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return He(this,e,t,n)}}class Ye extends me{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))).map((e=>e.slice(2,-2))),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return He(this,e,t,n)}}const Xe=[["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"]],Qe=new Map(Xe),Ze=new Map([...Xe.map((([e,t])=>[t,e])),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class Je extends me{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}';_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:a=!0}={}){if(null===r)throw Error("Must specify time_precision");let i=null;const o="word"===t;function l(){return{language:i,timestamp:[null,null],text:""}}const u=[];let d=l(),c=0;const p=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let h=[],f=[],m=!1,g=null;const _=new Set(this.all_special_ids);for(const n of e){const e=n.tokens,a=o?n.token_timestamps:null;let w=null,y=p;if("stride"in n){const[t,a,i]=n.stride;if(c-=a,g=t-i,a&&(y=a/r+p),i)for(let t=e.length-1;t>=0;--t){const n=e[t];if(n>=p){if(null!==w&&(n-p)*r=p){const e=(g-p)*r+c,t=(0,s.round)(e,2);if(null!==w&&g>=w)m=!0;else if(m||h.length>0&&g0?(h.push(b),o&&f.push(v)):h.every((e=>0===e.length))&&(d=l(),h=[],b=[],f=[],v=[])}if(h.length>0){if(a&&t)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[e,n]=this.findLongestCommonSequence(h,f),r=this.decode(e);d.text=r,o&&(d.words=this.collateWordTimestamps(e,n,i)),u.push(d)}let w=Object.create(null);const y=u.map((e=>e.text)).join("");if(t||n){for(let e=0;e0;let s=i?[]:null,o=i?t[0]:null;for(let l=1;le===h[t])).length,m=f/e+t;f>1&&m>d&&(d=m,c=[a,i,o,l])}const[h,f,m,g]=c,_=Math.floor((f+h)/2),w=Math.floor((g+m)/2);a.push(...n.slice(0,_)),n=u.slice(w),r=n.length,i&&(s.push(...o.slice(0,_)),o=t[l].slice(w))}return a.push(...n),i?(s.push(...o),[a,s]):[a,[]]}collateWordTimestamps(e,t,n){const[r,a,i]=this.combineTokensIntoWords(e,n),s=[];for(let e=0;e=r){const e=(0,s.round)((t-r)*n,2);a.push(`<|${e}|>`),a.push([])}else a[a.length-1].push(t);return a=a.map((e=>"string"==typeof e?e:super.decode(e,t))),a.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],a=[];let i=[],s=[],o=0;for(let l=0;l=this.model.tokens_to_ids.get("<|endoftext|>"),p=l.startsWith(" "),h=l.trim(),f=o.test(h);if(c||p||f||0===a.length)a.push(l),i.push(u),s.push(d);else{const e=a.length-1;a[e]+=l,i[e].push(...u),s[e].push(...d)}}return[a,i,s]}mergePunctuations(e,t,n,r,i){const s=structuredClone(e),o=structuredClone(t),l=structuredClone(n);let u=s.length-2,d=s.length-1;for(;u>=0;)s[u].startsWith(" ")&&r.includes(s[u].trim())?(s[d]=s[u]+s[d],o[d]=(0,a.mergeArrays)(o[u],o[d]),l[d]=(0,a.mergeArrays)(l[u],l[d]),s[u]="",o[u]=[],l[u]=[]):d=u,--u;for(u=0,d=1;de)),o.filter((e=>e.length>0)),l.filter((e=>e.length>0))]}get_decoder_prompt_ids({language:e=null,task:t=null,no_timestamps:n=!0}={}){const r=[];if(e){e=e.toLowerCase();let t=Ze.get(e);if(void 0===t){if(!Qe.has(e)){const t=2===e.length?Qe.keys():Qe.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(t)}`)}t=e}const n=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===n)throw new Error(`Unable to find language "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);r.push(n)}else r.push(null);if(t){if("transcribe"!==(t=t.toLowerCase())&&"translate"!==t)throw new Error(`Task "${t}" is not supported. Must be one of: ["transcribe", "translate"]`);const e=this.model.tokens_to_ids.get(`<|${t}|>`);if(void 0===e)throw new Error(`Unable to find task "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);r.push(e)}else r.push(null);if(n){const e=this.model.tokens_to_ids.get("<|notimestamps|>");if(void 0===e)throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');r.push(e)}return r.map(((e,t)=>[t+1,e])).filter((e=>null!==e[1]))}}class et extends me{}class tt extends me{}class nt extends me{}class rt extends me{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter((e=>this.languageRegex.test(e))),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(null===e)return null;const[t,...n]=e.trim().split(this.languageRegex);if(0===n.length)return super._encode_text(t);if(2===n.length){const[e,t]=n;return this.supported_language_codes.includes(e)||console.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,a.mergeArrays)([e],super._encode_text(t))}}}class at extends me{}class it extends me{_default_chat_template="{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}"}class st extends it{}class ot extends me{}class lt extends me{}class ut extends me{constructor(e,t){super(e,t),this.decoder=new ae({})}}class dt extends me{}class ct{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:Ee,DistilBertTokenizer:Se,CamembertTokenizer:Me,DebertaTokenizer:be,DebertaV2Tokenizer:ve,BertTokenizer:ge,HerbertTokenizer:$e,ConvBertTokenizer:xe,RoFormerTokenizer:Te,XLMTokenizer:ke,ElectraTokenizer:Ce,MobileBertTokenizer:we,SqueezeBertTokenizer:ye,AlbertTokenizer:_e,GPT2Tokenizer:Ae,BartTokenizer:Ie,MBartTokenizer:Pe,MBart50Tokenizer:Oe,RobertaTokenizer:ze,WhisperTokenizer:Je,CodeGenTokenizer:et,CLIPTokenizer:tt,SiglipTokenizer:nt,MarianTokenizer:rt,BloomTokenizer:Be,NllbTokenizer:Ke,M2M100Tokenizer:Ye,LlamaTokenizer:Re,CodeLlamaTokenizer:De,XLMRobertaTokenizer:Le,MPNetTokenizer:Ne,FalconTokenizer:Ue,GPTNeoXTokenizer:We,EsmTokenizer:Ve,Wav2Vec2CTCTokenizer:at,BlenderbotTokenizer:it,BlenderbotSmallTokenizer:st,SpeechT5Tokenizer:ot,NougatTokenizer:lt,VitsTokenizer:ut,Qwen2Tokenizer:Ge,GemmaTokenizer:je,Grok1Tokenizer:qe,CohereTokenizer:dt,PreTrainedTokenizer:me};static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:a=!1,revision:i="main",legacy:s=null}={}){const[o,l]=await d(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:a,revision:i,legacy:s}),u=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let c=this.TOKENIZER_CLASS_MAPPING[u];return c||(console.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),c=me),new c(o,l)}}},"./src/utils/audio.js": /*!****************************!*\ !*** ./src/utils/audio.js ***! \****************************/(e,t,n)=>{n.r(t),n.d(t,{hanning:()=>o,mel_filter_bank:()=>p,read_audio:()=>s,spectrogram:()=>f,window_function:()=>m});var r=n(/*! ./hub.js */"./src/utils/hub.js"),a=n(/*! ./maths.js */"./src/utils/maths.js"),i=n(/*! ./core.js */"./src/utils/core.js");async function s(e,t){if("undefined"==typeof AudioContext)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 n=await(await(0,r.getFile)(e)).arrayBuffer(),a=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${a.sampleRate}Hz.`);const i=await a.decodeAudioData(n);let s;if(2===i.numberOfChannels){const e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);s=new Float32Array(t.length);for(let r=0;r2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function u(e,t="htk"){const n=l[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}const d={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function c(e,t,n){const r=(t-e)/(n-1);return Float64Array.from({length:n},((t,n)=>e+r*n))}function p(e,t,n,r,a,i=null,s="htk",o=!1){if(null!==i&&"slaney"!==i)throw new Error('norm must be one of null or "slaney"');const l=c(u(n,s),u(r,s),t+2);let p,h=function(e,t="htk"){const n=d[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}(l,s);if(o){const t=a/(2*e);p=u(Float64Array.from({length:e},((e,n)=>n*t)),s),h=l}else p=c(0,Math.floor(a/2),e);const f=function(e,t){const n=Float64Array.from({length:t.length-1},((e,n)=>t[n+1]-t[n])),r=Array.from({length:e.length},(()=>new Array(t.length)));for(let n=0;nnew Array(e.length)));for(let t=0;ts)throw Error(`frame_length (${n}) may not be larger than fft_length (${s})`);if(x!==n)throw new Error(`Length of the window (${x}) must equal frame_length (${n})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(l){if("reflect"!==u)throw new Error(`pad_mode="${u}" not implemented yet.`);const t=Math.floor((s-1)/2)+1;e=function(e,t,n){const r=new e.constructor(e.length+t+n),a=e.length-1;for(let n=0;nT?v&&(k=b):k=M=b);const C=new a.FFT(s),E=new Float64Array(s),A=new Float64Array(C.outputBufferSize),I=new Array(M);for(let a=0;a=1;--e)E[e]-=c*E[e-1];E[0]*=1-c}for(let e=0;eMath.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(n&&(s=s.subarray(0,e)),null===r)return s;if(e>r)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);return s}},"./src/utils/core.js": /*!***************************!*\ !*** ./src/utils/core.js ***! \***************************/(e,t,n)=>{function r(e,t){e&&e(t)}function a(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[t,e])))}function i(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s(e){return"TypedArray"===e?.prototype?.__proto__?.constructor?.name}function o(e){return Number.isInteger(e)||"bigint"==typeof e}function l(e){const t=[];let n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function u(e,t,n=void 0){const r=e[t];if(void 0!==r)return delete e[t],r;if(void 0===n)throw Error(`Key ${t} does not exist in object.`);return n}function d(...e){return Array.prototype.concat.apply([],e)}function c(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t]))))))}function p(e,t){return Math.abs((e+t)%(2*t)-t)}function h(e,t){return Object.assign({},...t.map((t=>{if(void 0!==e[t])return{[t]:e[t]}})))}n.r(t),n.d(t,{calculateDimensions:()=>l,calculateReflectOffset:()=>p,dispatchCallback:()=>r,escapeRegExp:()=>i,isIntegralNumber:()=>o,isTypedArray:()=>s,mergeArrays:()=>d,pick:()=>h,pop:()=>u,product:()=>c,reverseDictionary:()=>a})},"./src/utils/data-structures.js": /*!**************************************!*\ !*** ./src/utils/data-structures.js ***! \**************************************/(e,t,n)=>{n.r(t),n.d(t,{CharTrie:()=>a,PriorityQueue:()=>r,TokenLattice:()=>s});class r{constructor(e=((e,t)=>e>t)){this._heap=[],this._comparator=e}get size(){return this._heap.length}isEmpty(){return 0===this.size}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)this._heap.push(t),this._siftUp();return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._siftDown(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._siftDown(),t}_parent(e){return(e+1>>>1)-1}_left(e){return 1+(e<<1)}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_siftUp(){let e=this.size-1;for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)[])),this.endNodes=Array.from({length:this.len+1},(()=>[]));const r=new o(this.bosTokenId,0,0,0,0),a=new o(this.eosTokenId,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(a.clone()),this.beginNodes[this.len].push(a),this.endNodes[0].push(r)}insert(e,t,n,r){const a=this.nodes.length,i=new o(r,a,e,t,n);this.beginNodes[e].push(i),this.endNodes[e+t].push(i),this.nodes.push(i)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(0==this.beginNodes[t].length)return[];for(let e of this.beginNodes[t]){e.prev=null;let n=0,r=null;for(let a of this.endNodes[t]){const t=a.backtraceScore+e.score;(null===r||t>n)&&(r=a.clone(),n=t)}if(null===r)return[];e.prev=r,e.backtraceScore=n}++t}const n=[],r=this.beginNodes[e][0].prev;if(null===r)return[];let a=r.clone();for(;null!==a.prev;){n.push(a.clone());const e=a.clone();a=e.prev.clone()}return n.reverse(),n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){return this.viterbi().map((e=>this.piece(e)))}tokenIds(){return this.viterbi().map((e=>e.tokenId))}}class o{constructor(e,t,n,r,a){this.tokenId=e,this.nodeId=t,this.pos=n,this.length=r,this.score=a,this.prev=null,this.backtraceScore=0}clone(){const e=new o(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}},"./src/utils/devices.js": /*!******************************!*\ !*** ./src/utils/devices.js ***! \******************************/(e,t,n)=>{n.r(t),n.d(t,{DEVICE_TYPES:()=>r});const r=Object.freeze({cpu:"cpu",gpu:"gpu",wasm:"wasm",webgpu:"webgpu"})},"./src/utils/dtypes.js": /*!*****************************!*\ !*** ./src/utils/dtypes.js ***! \*****************************/(e,t,n)=>{n.r(t),n.d(t,{DATA_TYPES:()=>s,DEFAULT_DEVICE_DTYPE_MAPPING:()=>o,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isFp16Supported:()=>i});var r=n(/*! ../env.js */"./src/env.js"),a=n(/*! ./devices.js */"./src/utils/devices.js");const i=function(){let e;return async function(){if(void 0===e)if(r.apis.IS_NODE_ENV)e=!0;else if(r.apis.IS_WEBGPU_AVAILABLE)try{const t=await navigator.gpu.requestAdapter();e=t.features.has("shader-f16")}catch(t){e=!1}else e=!1;return e}}(),s=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8"}),o=Object.freeze({[a.DEVICE_TYPES.cpu]:s.q8,[a.DEVICE_TYPES.gpu]:s.fp32,[a.DEVICE_TYPES.wasm]:s.q8,[a.DEVICE_TYPES.webgpu]:s.fp32}),l=Object.freeze({[s.fp32]:"",[s.fp16]:"_fp16",[s.int8]:"_int8",[s.uint8]:"_uint8",[s.q8]:"_quantized"})},"./src/utils/generic.js": /*!******************************!*\ !*** ./src/utils/generic.js ***! \******************************/(e,t,n)=>{n.r(t),n.d(t,{Callable:()=>r});const r=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js": /*!**************************!*\ !*** ./src/utils/hub.js ***! \**************************/(e,t,n)=>{n.r(t),n.d(t,{getFile:()=>u,getModelFile:()=>p,getModelJSON:()=>h});var r=n(/*! fs */"?7a2c"),a=n(/*! path */"?a42a"),i=n(/*! ../env.js */"./src/env.js"),s=n(/*! ./core.js */"./src/utils/core.js");class o{_CONTENT_TYPE_MAP={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"};constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=r.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=r.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let n=this;this.body=new ReadableStream({start(e){n.arrayBuffer().then((t=>{e.enqueue(new Uint8Array(t)),e.close()}))}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new o(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await r.promises.readFile(this.filePath)).buffer}async blob(){const e=await r.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await r.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function l(e,t=null){let n;try{n=new URL(e)}catch(e){return!1}return!(t&&!t.includes(n.hostname))&&("http:"===n.protocol||"https:"===n.protocol)}async function u(e){if(i.env.useFS&&!l(e))return new o(e);if("undefined"!=typeof process&&"node"===process?.release?.name){const t=!!process.env?.TESTING_REMOTELY,n=i.env.version,r=new Headers;r.set("User-Agent",`transformers.js/${n}; is_ci/${t};`);if(l(e,["huggingface.co","hf.co"])){const e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;e&&r.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:r})}return fetch(e)}const d={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"};class c{constructor(e){this.path=e}async match(e){let t=a.join(this.path,e),n=new o(t);return n.exists?n:void 0}async put(e,t){const n=Buffer.from(await t.arrayBuffer());let i=a.join(this.path,e);try{await r.promises.mkdir(a.dirname(i),{recursive:!0}),await r.promises.writeFile(i,n)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}}async function p(e,t,n=!0,r={}){if(!i.env.allowLocalModels){if(r.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(!i.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let a;if((0,s.dispatchCallback)(r.progress_callback,{status:"initiate",name:e,file:t}),!a&&i.env.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{a=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!a&&i.env.useFSCache&&(a=new c(r.cache_dir??i.env.cacheDir)),!a&&i.env.useCustomCache){if(!i.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!i.env.customCache.match||!i.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");a=i.env.customCache}const o=r.revision??"main";let p,h,m=f(e,t),g=f(i.env.localModelPath,m),_=f(i.env.remoteHost,i.env.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(o)),t),w="main"===o?m:f(e,o,t),y=a instanceof c?w:_,b=!1;a&&(h=await async function(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch(e){continue}}(a,g,y));const v=void 0!==h;if(void 0===h){if(i.env.allowLocalModels){if(l(m)){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${m}.`);if(!i.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${m}.`)}else try{h=await u(g),p=g}catch(e){console.warn(`Unable to load from local path "${g}": "${e}"`)}}if(void 0===h||404===h.status){if(r.local_files_only||!i.env.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${g}".`);return null}if(h=await u(_),200!==h.status)return function(e,t,n){if(!n)return null;const r=d[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}(h.status,_,n);p=y}b=a&&"undefined"!=typeof Response&&h instanceof Response&&200===h.status}(0,s.dispatchCallback)(r.progress_callback,{status:"download",name:e,file:t});const $={status:"progress",name:e,file:t};let x;return r.progress_callback?v&&"undefined"!=typeof navigator&&/firefox/i.test(navigator.userAgent)?(x=new Uint8Array(await h.arrayBuffer()),(0,s.dispatchCallback)(r.progress_callback,{...$,progress:100,loaded:x.length,total:x.length})):x=await async function(e,t){const n=e.headers.get("Content-Length");null===n&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(n??"0"),a=new Uint8Array(r),i=0;const s=e.body.getReader();async function o(){const{done:e,value:n}=await s.read();if(e)return;let l=i+n.length;if(l>r){r=l;let e=new Uint8Array(r);e.set(a),a=e}a.set(n,i),i=l;return t({progress:i/r*100,loaded:i,total:r}),o()}return await o(),a}(h,(e=>{(0,s.dispatchCallback)(r.progress_callback,{...$,...e})})):x=new Uint8Array(await h.arrayBuffer()),b&&p&&void 0===await a.match(p)&&await a.put(p,new Response(x,{headers:h.headers})).catch((e=>{console.warn(`Unable to add response to browser cache: ${e}.`)})),(0,s.dispatchCallback)(r.progress_callback,{status:"done",name:e,file:t}),x}async function h(e,t,n=!0,r={}){let a=await p(e,t,n,r);if(null===a)return{};let i=new TextDecoder("utf-8").decode(a);return JSON.parse(i)}function f(...e){return(e=e.map(((t,n)=>(n&&(t=t.replace(new RegExp("^/"),"")),n!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)))).join("/")}},"./src/utils/image.js": /*!****************************!*\ !*** ./src/utils/image.js ***! \****************************/(e,t,n)=>{n.r(t),n.d(t,{RawImage:()=>f});var r=n(/*! ./hub.js */"./src/utils/hub.js"),a=n(/*! ../env.js */"./src/env.js"),i=n(/*! ./tensor.js */"./src/utils/tensor.js"),s=n(/*! sharp */"?2b25");const o="undefined"!=typeof self,l=o&&"DedicatedWorkerGlobalScope"===self.constructor.name;let u,d,c;if(o)u=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},c=self.createImageBitmap,d=self.ImageData;else{if(!s)throw new Error("Unable to load image processing library.");c=async e=>{const t=(await e.metadata()).channels,{data:n,info:r}=await e.raw().toBuffer({resolveWithObject:!0}),a=new f(new Uint8ClampedArray(n),r.width,r.height,r.channels);return void 0!==t&&t!==r.channels&&a.convert(t),a}}const p={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},h=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class f{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(e){if(e instanceof f)return e;if("string"==typeof e||e instanceof URL)return await this.fromURL(e);throw new Error("Unsupported input type: "+typeof e)}static fromCanvas(e){if(!o)throw new Error("fromCanvas() is only supported in browser environments.");const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new f(t,e.width,e.height,4)}static async fromURL(e){const t=await(0,r.getFile)(e);if(200!==t.status)throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);const n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(o){const t=await c(e),n=u(t.width,t.height).getContext("2d");return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{const t=s(await e.arrayBuffer());return await c(t)}}static fromTensor(e,t="CHW"){if(3!==e.dims.length)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if("CHW"===t)e=e.transpose(1,2,0);else if("HWC"!==t)throw new Error(`Unsupported channel format: ${t}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new f(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(1===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?o=n:d=-n,r>=0?l=r:c=-r,s.drawImage(i,o,l,e,t,d,c,e,t);return new f(s.getImageData(0,0,e,t).data,e,t,4).convert(a)}{let a=this.toSharp();if(n>=0&&r>=0)a=a.extract({left:Math.floor(n),top:Math.floor(r),width:e,height:t});else if(n<=0&&r<=0){const i=Math.floor(-r),s=Math.floor(-n);a=a.extend({top:i,left:s,right:e-this.width-s,bottom:t-this.height-i})}else{let i=[0,0],s=0;r<0?(i[0]=Math.floor(-r),i[1]=t-this.height-i[0]):s=Math.floor(r);let o=[0,0],l=0;n<0?(o[0]=Math.floor(-n),o[1]=e-this.width-o[0]):l=Math.floor(n),a=a.extend({top:i[0],bottom:i[1],left:o[0],right:o[1]}).extract({left:l,top:s,width:e,height:t})}return await c(a)}}async toBlob(e="image/png",t=1){if(!o)throw new Error("toBlob() is only supported in browser environments.");const n=this.toCanvas();return await n.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if("HWC"===e);else{if("CHW"!==e)throw new Error(`Unsupported channel format: ${e}`);t=t.permute(2,0,1)}return t}toCanvas(){if(!o)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),t=u(e.width,e.height),n=new d(e.data,e.width,e.height);return t.getContext("2d").putImageData(n,0,0),t}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,null!==r&&(this.channels=r),this}clone(){return new f(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){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(e){if(!o){if(a.env.useFS){const t=this.toSharp();return await t.toFile(e)}throw new Error("Unable to save the image because filesystem is disabled in this environment.")}{if(l)throw new Error("Unable to save an image from a Web Worker.");const t=e.split(".").pop().toLowerCase(),n=h.get(t)??"image/png",r=await this.toBlob(n),a=URL.createObjectURL(r),i=document.createElement("a");i.href=a,i.download=e,i.click(),i.remove()}}toSharp(){if(o)throw new Error("toSharp() is only supported in server-side environments.");return s(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js": /*!****************************!*\ !*** ./src/utils/maths.js ***! \****************************/(e,t,n)=>{function r(e,[t,n,r],[a,i],s="bilinear",o=!1){const l=i/r,u=a/n,d=new e.constructor(a*i*t),c=n*r,p=a*i;for(let s=0;s=0;--e)a[e]=i,r[e]=t[n[e]],i*=r[e];const i=n.map(((e,t)=>a[n.indexOf(t)])),s=new e.constructor(e.length);for(let n=0;n=0;--e)r+=a%t[e]*i[e],a=Math.floor(a/t[e]);s[r]=e[n]}return[s,r]}function i(e){const t=p(e)[0],n=e.map((e=>Math.exp(e-t))),r=n.reduce(((e,t)=>e+t),0);return n.map((e=>e/r))}function s(e){return i(e).map((e=>Math.log(e)))}function o(e,t){let n=0;for(let r=0;r[t,e])).sort(((e,t)=>t[1]-e[1])),null!==t&&t>0&&(e=e.slice(0,t)),e}function u(e,t){return o(e,t)/(d(e)*d(t))}function d(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}function c(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[Number(t),n]}function h(e){return e>0&&0==(e&e-1)}n.r(t),n.d(t,{FFT:()=>g,bankers_round:()=>y,cos_sim:()=>u,dot:()=>o,getTopItems:()=>l,interpolate_data:()=>r,log_softmax:()=>s,magnitude:()=>d,max:()=>p,medianFilter:()=>_,min:()=>c,permute_data:()=>a,round:()=>w,softmax:()=>i});class f{constructor(e){if(this.size=0|e,this.size<=1||!h(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(2*this.size);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){const n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}completeSpectrum(e){const t=this._csize,n=t>>>1;for(let r=2;r>=2;s>=2;s>>=2){o=r/s<<1;const t=o>>>2;for(a=0;a>>1,s>>>1)}else for(a=0,i=0;a>>1,s>>>1,n)}for(s>>=2;s>=2;s>>=2){o=r/s<<1;const t=o>>>2;for(a=0;a>1;++t){const n=(t+1-e)**2/2,r=Math.sqrt(o**2+l**2)**n,s=n*Math.atan2(l,o),u=2*t;a[u]=r*Math.cos(s),a[u+1]=r*Math.sin(s),i[u]=a[u],i[u+1]=-a[u+1]}this._slicedChirpBuffer=a.subarray(t,n),this._f=new f(r>>1),this._f.transform(this._chirpBuffer,i)}_transform(e,t,n){const r=this._buffer1,a=this._buffer2,i=this._outBuffer1,s=this._outBuffer2,o=this._chirpBuffer,l=this._slicedChirpBuffer,u=this._a;if(n)for(let e=0;e>1];r[e]=a*l[e],r[n]=a*l[n]}else for(let e=0;e=e.length&&(a=2*(e.length-1)-a),r[i++]=e[a]}r.sort(),n[t]=r[a]}return n}function w(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}function y(e){const t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}},"./src/utils/tensor.js": /*!*****************************!*\ !*** ./src/utils/tensor.js ***! \*****************************/(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>o,cat:()=>g,dynamicTimeWarping:()=>b,full:()=>$,full_like:()=>x,interpolate:()=>u,interpolate_4d:()=>d,layer_norm:()=>p,mean:()=>y,mean_pooling:()=>c,ones:()=>T,ones_like:()=>S,permute:()=>l,quantize_embeddings:()=>C,stack:()=>_,std_mean:()=>w,zeros:()=>M,zeros_like:()=>k});var r=n(/*! ./maths.js */"./src/utils/maths.js"),a=n(/*! ../backends/onnx.js */"./src/backends/onnx.js"),i=n(/*! ../ops/registry.js */"./src/ops/registry.js");const s=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class o{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}ort_tensor;constructor(...e){return(0,a.isONNXTensor)(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new a.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const n=t.reduce(((e,t)=>e*t));for(let r=0;r0){const t=n.reduce(((e,t)=>e*t));return this._subarray(e,t,n)}return new o(this.type,[this.data[e]],n)}indexOf(e){const t=this.data;for(let n=0;ne*t));if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${t})`);let a=e;for(let e=t.length-1;e>=0;e--)a=a.reduce(((n,r)=>{let a=n[n.length-1];return a.lengtha[1])throw new Error(`Invalid slice: ${a}`);let e=[Math.max(a[0],0),Math.min(a[1],this.dims[r])];n.push(e),t.push(e[1]-e[0])}}}let r=n.map((([e,t])=>t-e)),a=r.reduce(((e,t)=>e*t));const i=this.data;let s=new i.constructor(a);const l=this.stride();for(let e=0;e=0;--a){const e=r[a];t+=(i%e+n[a][0])*l[a],i=Math.floor(i/e)}s[e]=i[t]}return new o(this.type,s,t)}permute(...e){return l(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,n=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);const r=this.data;if(null===t){let t=r.reduce(((t,n)=>t+n**e),0)**(1/e);return new o(this.type,[t],[])}t=m(t,this.dims.length);const a=this.dims.slice();a[t]=1;const i=new r.constructor(r.length/this.dims[t]);for(let n=0;n=0;--e){const n=this.dims[e];if(e!==t){s+=r%n*i,i*=a[e]}r=Math.floor(r/n)}i[s]+=r[n]**e}if(1!==e)for(let t=0;t=0;--n){const e=this.dims[n];if(n!==t){a+=r%e*i,i*=this.dims[n]}r=Math.floor(r/e)}r[e]/=n.data[a]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){const t=new Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}(this.dims)}squeeze(e=null){return new o(this.type,this.data,h(this.dims,e))}squeeze_(e=null){return this.dims=h(this.dims,e),this}unsqueeze(e=null){return new o(this.type,this.data,f(this.dims,e))}unsqueeze_(e=null){return this.dims=f(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),a=this.dims.slice(t+1);return this.dims=[...n,r.reduce(((e,t)=>e*t),1),...a],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let n=0;nr!==t?e*n:e),1);e[t]=this.data.length/n}return new o(this.type,this.data,e)}neg_(){const e=this.data;for(let t=0;t1!==e)):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter(((e,n)=>1!==e||!t.includes(n)))),e}function f(e,t){return t=m(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function m(e,t,n=null){if(e<-t||e>=t)throw new Error(`IndexError: index ${e} is out of bounds for dimension${null===n?"":" "+n} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function g(e,t=0){t=m(t,e[0].dims.length);const n=e[0].dims.slice();n[t]=e.reduce(((e,n)=>e+n.dims[t]),0);const r=n.reduce(((e,t)=>e*t),1),a=new e[0].data.constructor(r),i=e[0].type;if(0===t){let t=0;for(let n of e)a.set(n.data,t),t+=n.data.length}else{let r=0;for(let i=0;i=0;--a){const e=s.dims[a];let u=o%e;a===t&&(u+=r),i+=u*l,l*=n[a],o=Math.floor(o/e)}a[i]=s.data[e]}r+=s.dims[t]}}return new o(i,a,n)}function _(e,t=0){return g(e.map((e=>e.unsqueeze(t))),t)}function w(e,t=null,n=1,r=!1){if(null===t){const t=e.data.reduce(((e,t)=>e+t),0)/e.data.length,r=Math.sqrt(e.data.reduce(((e,n)=>e+(n-t)**2),0)/(e.data.length-n)),a=new o(e.type,[t],[]);return[new o(e.type,[r],[]),a]}const a=y(e,t=m(t,e.dims.length),r),i=e.dims.slice();i[t]=1;const s=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n=0;--a){const n=e.dims[a];if(a!==t){r+=s%n*o,o*=i[a]}s=Math.floor(s/n)}s[r]+=(e.data[n]-a.data[r])**2}for(let r=0;re+t),0);return new o(e.type,[t/e.data.length],[])}t=m(t,e.dims.length);const r=e.dims.slice();r[t]=1;const a=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n=0;--a){const n=e.dims[a];if(a!==t){i+=s%n*o,o*=r[a]}s=Math.floor(s/n)}a[i]+=e.data[n]}if(1!==e.dims[t])for(let n=0;n0||l>0;){u.push(s-1),d.push(l-1);switch(i[s][l].item()){case 0:--s,--l;break;case 1:--s;break;case 2:--l;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${l}]. Please file a bug report.`)}}return u.reverse(),d.reverse(),[u,d]}function v(e,t,n,r){const a=e.reduce(((e,t)=>e*t),1);return new o(n,new r(a).fill(t),e)}function $(e,t){let n,r;if("number"==typeof t)n="float32",r=Float32Array;else{if("bigint"!=typeof t)throw new Error("Unsupported data type: "+typeof t);n="int64",r=BigInt64Array}return v(e,t,n,r)}function x(e,t){return $(e.dims,t)}function T(e){return v(e,1n,"int64",BigInt64Array)}function S(e){return T(e.dims)}function M(e){return v(e,0n,"int64",BigInt64Array)}function k(e){return M(e.dims)}function C(e,t){if(2!==e.dims.length)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!=0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const n="binary"===t,r=n?"int8":"uint8",a=n?Int8Array:Uint8Array,i=e.data,s=new a(i.length/8);for(let e=0;e0?1:0,r=Math.floor(e/8),a=e%8;s[r]|=t<<7-a,n&&0===a&&(s[r]-=128)}return new o(r,s,[e.dims[0],e.dims[1]/8])}}},r={};function a(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return n[e](i,i.exports,a),i.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,a.t=function(n,r){if(1&r&&(n=this(n)),8&r)return n;if("object"==typeof n&&n){if(4&r&&n.__esModule)return n;if(16&r&&"function"==typeof n.then)return n}var i=Object.create(null);a.r(i);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&r&&n;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>s[e]=()=>n[e]));return s.default=()=>n,a.d(i,s),i},a.d=(e,t)=>{for(var n in t)a.o(t,n)&&!a.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};(()=>{ /*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/ a.r(i),a.d(i,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ASTForAudioClassification:()=>n.ASTForAudioClassification,ASTModel:()=>n.ASTModel,ASTPreTrainedModel:()=>n.ASTPreTrainedModel,AlbertForMaskedLM:()=>n.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>n.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>n.AlbertForSequenceClassification,AlbertModel:()=>n.AlbertModel,AlbertPreTrainedModel:()=>n.AlbertPreTrainedModel,AlbertTokenizer:()=>r.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>o.AutoConfig,AutoModel:()=>n.AutoModel,AutoModelForAudioClassification:()=>n.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>n.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>n.AutoModelForCTC,AutoModelForCausalLM:()=>n.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>n.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>n.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>n.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>n.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>n.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>n.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>n.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>n.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>n.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>n.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>n.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>n.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>n.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>n.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>n.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>n.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>n.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>n.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>n.AutoModelForVision2Seq,AutoModelForXVector:()=>n.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>n.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>s.AutoProcessor,AutoTokenizer:()=>r.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>n.BartForConditionalGeneration,BartForSequenceClassification:()=>n.BartForSequenceClassification,BartModel:()=>n.BartModel,BartPretrainedModel:()=>n.BartPretrainedModel,BartTokenizer:()=>r.BartTokenizer,BaseModelOutput:()=>n.BaseModelOutput,BaseStreamer:()=>p.BaseStreamer,BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BeitForImageClassification:()=>n.BeitForImageClassification,BeitModel:()=>n.BeitModel,BeitPreTrainedModel:()=>n.BeitPreTrainedModel,BertForMaskedLM:()=>n.BertForMaskedLM,BertForQuestionAnswering:()=>n.BertForQuestionAnswering,BertForSequenceClassification:()=>n.BertForSequenceClassification,BertForTokenClassification:()=>n.BertForTokenClassification,BertModel:()=>n.BertModel,BertPreTrainedModel:()=>n.BertPreTrainedModel,BertTokenizer:()=>r.BertTokenizer,BitImageProcessor:()=>s.BitImageProcessor,BlenderbotForConditionalGeneration:()=>n.BlenderbotForConditionalGeneration,BlenderbotModel:()=>n.BlenderbotModel,BlenderbotPreTrainedModel:()=>n.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>n.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>n.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>n.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>r.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>r.BlenderbotTokenizer,BloomForCausalLM:()=>n.BloomForCausalLM,BloomModel:()=>n.BloomModel,BloomPreTrainedModel:()=>n.BloomPreTrainedModel,BloomTokenizer:()=>r.BloomTokenizer,CLIPFeatureExtractor:()=>s.CLIPFeatureExtractor,CLIPImageProcessor:()=>s.CLIPImageProcessor,CLIPModel:()=>n.CLIPModel,CLIPPreTrainedModel:()=>n.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>n.CLIPSegForImageSegmentation,CLIPSegModel:()=>n.CLIPSegModel,CLIPSegPreTrainedModel:()=>n.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>n.CLIPTextModelWithProjection,CLIPTokenizer:()=>r.CLIPTokenizer,CLIPVisionModelWithProjection:()=>n.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>n.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>n.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>n.CamembertForSequenceClassification,CamembertForTokenClassification:()=>n.CamembertForTokenClassification,CamembertModel:()=>n.CamembertModel,CamembertPreTrainedModel:()=>n.CamembertPreTrainedModel,CamembertTokenizer:()=>r.CamembertTokenizer,CausalLMOutput:()=>n.CausalLMOutput,CausalLMOutputWithPast:()=>n.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>s.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>n.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>n.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>n.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>s.ClapFeatureExtractor,ClapModel:()=>n.ClapModel,ClapPreTrainedModel:()=>n.ClapPreTrainedModel,ClapTextModelWithProjection:()=>n.ClapTextModelWithProjection,CodeGenForCausalLM:()=>n.CodeGenForCausalLM,CodeGenModel:()=>n.CodeGenModel,CodeGenPreTrainedModel:()=>n.CodeGenPreTrainedModel,CodeGenTokenizer:()=>r.CodeGenTokenizer,CodeLlamaTokenizer:()=>r.CodeLlamaTokenizer,CohereTokenizer:()=>r.CohereTokenizer,ConvBertForMaskedLM:()=>n.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>n.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>n.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>n.ConvBertForTokenClassification,ConvBertModel:()=>n.ConvBertModel,ConvBertPreTrainedModel:()=>n.ConvBertPreTrainedModel,ConvBertTokenizer:()=>r.ConvBertTokenizer,ConvNextFeatureExtractor:()=>s.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>n.ConvNextForImageClassification,ConvNextImageProcessor:()=>s.ConvNextImageProcessor,ConvNextModel:()=>n.ConvNextModel,ConvNextPreTrainedModel:()=>n.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>n.ConvNextV2ForImageClassification,ConvNextV2Model:()=>n.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>n.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>s.DPTFeatureExtractor,DPTForDepthEstimation:()=>n.DPTForDepthEstimation,DPTImageProcessor:()=>s.DPTImageProcessor,DPTModel:()=>n.DPTModel,DPTPreTrainedModel:()=>n.DPTPreTrainedModel,DebertaForMaskedLM:()=>n.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>n.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>n.DebertaForSequenceClassification,DebertaForTokenClassification:()=>n.DebertaForTokenClassification,DebertaModel:()=>n.DebertaModel,DebertaPreTrainedModel:()=>n.DebertaPreTrainedModel,DebertaTokenizer:()=>r.DebertaTokenizer,DebertaV2ForMaskedLM:()=>n.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>n.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>n.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>n.DebertaV2ForTokenClassification,DebertaV2Model:()=>n.DebertaV2Model,DebertaV2PreTrainedModel:()=>n.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>r.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>s.DeiTFeatureExtractor,DeiTForImageClassification:()=>n.DeiTForImageClassification,DeiTModel:()=>n.DeiTModel,DeiTPreTrainedModel:()=>n.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>n.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>n.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DetrFeatureExtractor:()=>s.DetrFeatureExtractor,DetrForObjectDetection:()=>n.DetrForObjectDetection,DetrForSegmentation:()=>n.DetrForSegmentation,DetrModel:()=>n.DetrModel,DetrObjectDetectionOutput:()=>n.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>n.DetrPreTrainedModel,DetrSegmentationOutput:()=>n.DetrSegmentationOutput,Dinov2ForImageClassification:()=>n.Dinov2ForImageClassification,Dinov2Model:()=>n.Dinov2Model,Dinov2PreTrainedModel:()=>n.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>n.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>n.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>n.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>n.DistilBertForTokenClassification,DistilBertModel:()=>n.DistilBertModel,DistilBertPreTrainedModel:()=>n.DistilBertPreTrainedModel,DistilBertTokenizer:()=>r.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>s.DonutFeatureExtractor,DonutSwinModel:()=>n.DonutSwinModel,DonutSwinPreTrainedModel:()=>n.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>n.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>s.EfficientNetImageProcessor,EfficientNetModel:()=>n.EfficientNetModel,EfficientNetPreTrainedModel:()=>n.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>n.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>n.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>n.ElectraForSequenceClassification,ElectraForTokenClassification:()=>n.ElectraForTokenClassification,ElectraModel:()=>n.ElectraModel,ElectraPreTrainedModel:()=>n.ElectraPreTrainedModel,ElectraTokenizer:()=>r.ElectraTokenizer,EsmForMaskedLM:()=>n.EsmForMaskedLM,EsmForSequenceClassification:()=>n.EsmForSequenceClassification,EsmForTokenClassification:()=>n.EsmForTokenClassification,EsmModel:()=>n.EsmModel,EsmPreTrainedModel:()=>n.EsmPreTrainedModel,EsmTokenizer:()=>r.EsmTokenizer,FFT:()=>c.FFT,FalconForCausalLM:()=>n.FalconForCausalLM,FalconModel:()=>n.FalconModel,FalconPreTrainedModel:()=>n.FalconPreTrainedModel,FalconTokenizer:()=>r.FalconTokenizer,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>s.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,GLPNFeatureExtractor:()=>s.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>n.GLPNForDepthEstimation,GLPNModel:()=>n.GLPNModel,GLPNPreTrainedModel:()=>n.GLPNPreTrainedModel,GPT2LMHeadModel:()=>n.GPT2LMHeadModel,GPT2Model:()=>n.GPT2Model,GPT2PreTrainedModel:()=>n.GPT2PreTrainedModel,GPT2Tokenizer:()=>r.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>n.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>n.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>n.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>n.GPTJForCausalLM,GPTJModel:()=>n.GPTJModel,GPTJPreTrainedModel:()=>n.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>n.GPTNeoForCausalLM,GPTNeoModel:()=>n.GPTNeoModel,GPTNeoPreTrainedModel:()=>n.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>n.GPTNeoXForCausalLM,GPTNeoXModel:()=>n.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>n.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>r.GPTNeoXTokenizer,GemmaTokenizer:()=>r.GemmaTokenizer,Grok1Tokenizer:()=>r.Grok1Tokenizer,HerbertTokenizer:()=>r.HerbertTokenizer,HubertForCTC:()=>n.HubertForCTC,HubertForSequenceClassification:()=>n.HubertForSequenceClassification,HubertModel:()=>n.HubertModel,HubertPreTrainedModel:()=>n.HubertPreTrainedModel,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>s.ImageFeatureExtractor,ImageMattingOutput:()=>n.ImageMattingOutput,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,LlamaForCausalLM:()=>n.LlamaForCausalLM,LlamaModel:()=>n.LlamaModel,LlamaPreTrainedModel:()=>n.LlamaPreTrainedModel,LlamaTokenizer:()=>r.LlamaTokenizer,LlavaForConditionalGeneration:()=>n.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>n.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>n.LongT5ForConditionalGeneration,LongT5Model:()=>n.LongT5Model,LongT5PreTrainedModel:()=>n.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>n.M2M100ForConditionalGeneration,M2M100Model:()=>n.M2M100Model,M2M100PreTrainedModel:()=>n.M2M100PreTrainedModel,M2M100Tokenizer:()=>r.M2M100Tokenizer,MBart50Tokenizer:()=>r.MBart50Tokenizer,MBartForCausalLM:()=>n.MBartForCausalLM,MBartForConditionalGeneration:()=>n.MBartForConditionalGeneration,MBartForSequenceClassification:()=>n.MBartForSequenceClassification,MBartModel:()=>n.MBartModel,MBartPreTrainedModel:()=>n.MBartPreTrainedModel,MBartTokenizer:()=>r.MBartTokenizer,MPNetForMaskedLM:()=>n.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>n.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>n.MPNetForSequenceClassification,MPNetForTokenClassification:()=>n.MPNetForTokenClassification,MPNetModel:()=>n.MPNetModel,MPNetPreTrainedModel:()=>n.MPNetPreTrainedModel,MPNetTokenizer:()=>r.MPNetTokenizer,MT5ForConditionalGeneration:()=>n.MT5ForConditionalGeneration,MT5Model:()=>n.MT5Model,MT5PreTrainedModel:()=>n.MT5PreTrainedModel,MarianMTModel:()=>n.MarianMTModel,MarianModel:()=>n.MarianModel,MarianPreTrainedModel:()=>n.MarianPreTrainedModel,MarianTokenizer:()=>r.MarianTokenizer,MaskedLMOutput:()=>n.MaskedLMOutput,MistralForCausalLM:()=>n.MistralForCausalLM,MistralModel:()=>n.MistralModel,MistralPreTrainedModel:()=>n.MistralPreTrainedModel,MobileBertForMaskedLM:()=>n.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>n.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>n.MobileBertForSequenceClassification,MobileBertModel:()=>n.MobileBertModel,MobileBertPreTrainedModel:()=>n.MobileBertPreTrainedModel,MobileBertTokenizer:()=>r.MobileBertTokenizer,MobileViTFeatureExtractor:()=>s.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>n.MobileViTForImageClassification,MobileViTModel:()=>n.MobileViTModel,MobileViTPreTrainedModel:()=>n.MobileViTPreTrainedModel,ModelOutput:()=>n.ModelOutput,MptForCausalLM:()=>n.MptForCausalLM,MptModel:()=>n.MptModel,MptPreTrainedModel:()=>n.MptPreTrainedModel,MusicgenForCausalLM:()=>n.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>n.MusicgenForConditionalGeneration,MusicgenModel:()=>n.MusicgenModel,MusicgenPreTrainedModel:()=>n.MusicgenPreTrainedModel,NllbTokenizer:()=>r.NllbTokenizer,NomicBertModel:()=>n.NomicBertModel,NomicBertPreTrainedModel:()=>n.NomicBertPreTrainedModel,NougatImageProcessor:()=>s.NougatImageProcessor,NougatTokenizer:()=>r.NougatTokenizer,OPTForCausalLM:()=>n.OPTForCausalLM,OPTModel:()=>n.OPTModel,OPTPreTrainedModel:()=>n.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,OwlViTFeatureExtractor:()=>s.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>n.OwlViTForObjectDetection,OwlViTModel:()=>n.OwlViTModel,OwlViTPreTrainedModel:()=>n.OwlViTPreTrainedModel,OwlViTProcessor:()=>s.OwlViTProcessor,Owlv2ForObjectDetection:()=>n.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>s.Owlv2ImageProcessor,Owlv2Model:()=>n.Owlv2Model,Owlv2PreTrainedModel:()=>n.Owlv2PreTrainedModel,PhiForCausalLM:()=>n.PhiForCausalLM,PhiModel:()=>n.PhiModel,PhiPreTrainedModel:()=>n.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>n.PreTrainedModel,PreTrainedTokenizer:()=>r.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>n.PretrainedMixin,Processor:()=>s.Processor,QuestionAnsweringModelOutput:()=>n.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>n.Qwen2ForCausalLM,Qwen2Model:()=>n.Qwen2Model,Qwen2PreTrainedModel:()=>n.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>r.Qwen2Tokenizer,RawImage:()=>u.RawImage,ResNetForImageClassification:()=>n.ResNetForImageClassification,ResNetModel:()=>n.ResNetModel,ResNetPreTrainedModel:()=>n.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>n.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>n.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>n.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>n.RoFormerForTokenClassification,RoFormerModel:()=>n.RoFormerModel,RoFormerPreTrainedModel:()=>n.RoFormerPreTrainedModel,RoFormerTokenizer:()=>r.RoFormerTokenizer,RobertaForMaskedLM:()=>n.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>n.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>n.RobertaForSequenceClassification,RobertaForTokenClassification:()=>n.RobertaForTokenClassification,RobertaModel:()=>n.RobertaModel,RobertaPreTrainedModel:()=>n.RobertaPreTrainedModel,RobertaTokenizer:()=>r.RobertaTokenizer,SamImageProcessor:()=>s.SamImageProcessor,SamImageSegmentationOutput:()=>n.SamImageSegmentationOutput,SamModel:()=>n.SamModel,SamPreTrainedModel:()=>n.SamPreTrainedModel,SamProcessor:()=>s.SamProcessor,SeamlessM4TFeatureExtractor:()=>s.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>s.SegformerFeatureExtractor,SegformerForImageClassification:()=>n.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>n.SegformerForSemanticSegmentation,SegformerModel:()=>n.SegformerModel,SegformerPreTrainedModel:()=>n.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>n.Seq2SeqLMOutput,SequenceClassifierOutput:()=>n.SequenceClassifierOutput,SiglipImageProcessor:()=>s.SiglipImageProcessor,SiglipModel:()=>n.SiglipModel,SiglipPreTrainedModel:()=>n.SiglipPreTrainedModel,SiglipTextModel:()=>n.SiglipTextModel,SiglipTokenizer:()=>r.SiglipTokenizer,SiglipVisionModel:()=>n.SiglipVisionModel,SpeechT5FeatureExtractor:()=>s.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>n.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>n.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>n.SpeechT5HifiGan,SpeechT5Model:()=>n.SpeechT5Model,SpeechT5PreTrainedModel:()=>n.SpeechT5PreTrainedModel,SpeechT5Processor:()=>s.SpeechT5Processor,SpeechT5Tokenizer:()=>r.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>n.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>n.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>n.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>n.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>n.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>r.SqueezeBertTokenizer,StableLmForCausalLM:()=>n.StableLmForCausalLM,StableLmModel:()=>n.StableLmModel,StableLmPreTrainedModel:()=>n.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>n.Starcoder2ForCausalLM,Starcoder2Model:()=>n.Starcoder2Model,Starcoder2PreTrainedModel:()=>n.Starcoder2PreTrainedModel,SummarizationPipeline:()=>t.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>n.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>s.Swin2SRImageProcessor,Swin2SRModel:()=>n.Swin2SRModel,Swin2SRPreTrainedModel:()=>n.Swin2SRPreTrainedModel,SwinForImageClassification:()=>n.SwinForImageClassification,SwinModel:()=>n.SwinModel,SwinPreTrainedModel:()=>n.SwinPreTrainedModel,T5ForConditionalGeneration:()=>n.T5ForConditionalGeneration,T5Model:()=>n.T5Model,T5PreTrainedModel:()=>n.T5PreTrainedModel,T5Tokenizer:()=>r.T5Tokenizer,TableTransformerForObjectDetection:()=>n.TableTransformerForObjectDetection,TableTransformerModel:()=>n.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>n.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>n.TableTransformerPreTrainedModel,Tensor:()=>d.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>n.TokenClassifierOutput,TokenizerModel:()=>r.TokenizerModel,TrOCRForCausalLM:()=>n.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>n.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>n.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>n.UniSpeechForSequenceClassification,UniSpeechModel:()=>n.UniSpeechModel,UniSpeechPreTrainedModel:()=>n.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>n.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>n.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>n.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>n.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>n.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>s.ViTFeatureExtractor,ViTForImageClassification:()=>n.ViTForImageClassification,ViTImageProcessor:()=>s.ViTImageProcessor,ViTModel:()=>n.ViTModel,ViTPreTrainedModel:()=>n.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>n.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>n.VitMatteForImageMatting,VitMatteImageProcessor:()=>s.VitMatteImageProcessor,VitMattePreTrainedModel:()=>n.VitMattePreTrainedModel,VitsModel:()=>n.VitsModel,VitsModelOutput:()=>n.VitsModelOutput,VitsPreTrainedModel:()=>n.VitsPreTrainedModel,VitsTokenizer:()=>r.VitsTokenizer,Wav2Vec2BertForCTC:()=>n.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>n.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>n.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>n.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>r.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>s.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>n.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>n.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>n.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>n.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>n.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>s.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>n.WavLMForAudioFrameClassification,WavLMForCTC:()=>n.WavLMForCTC,WavLMForSequenceClassification:()=>n.WavLMForSequenceClassification,WavLMForXVector:()=>n.WavLMForXVector,WavLMModel:()=>n.WavLMModel,WavLMPreTrainedModel:()=>n.WavLMPreTrainedModel,WhisperFeatureExtractor:()=>s.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>n.WhisperForConditionalGeneration,WhisperModel:()=>n.WhisperModel,WhisperPreTrainedModel:()=>n.WhisperPreTrainedModel,WhisperProcessor:()=>s.WhisperProcessor,WhisperTokenizer:()=>r.WhisperTokenizer,XLMForQuestionAnswering:()=>n.XLMForQuestionAnswering,XLMForSequenceClassification:()=>n.XLMForSequenceClassification,XLMForTokenClassification:()=>n.XLMForTokenClassification,XLMModel:()=>n.XLMModel,XLMPreTrainedModel:()=>n.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>n.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>n.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>n.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>n.XLMRobertaForTokenClassification,XLMRobertaModel:()=>n.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>n.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>r.XLMRobertaTokenizer,XLMTokenizer:()=>r.XLMTokenizer,XLMWithLMHeadModel:()=>n.XLMWithLMHeadModel,XVectorOutput:()=>n.XVectorOutput,YolosFeatureExtractor:()=>s.YolosFeatureExtractor,YolosForObjectDetection:()=>n.YolosForObjectDetection,YolosModel:()=>n.YolosModel,YolosObjectDetectionOutput:()=>n.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>n.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>t.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>t.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>t.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>t.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>d.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamicTimeWarping:()=>d.dynamicTimeWarping,env:()=>e.env,full:()=>d.full,full_like:()=>d.full_like,getTopItems:()=>c.getTopItems,hanning:()=>l.hanning,interpolate:()=>d.interpolate,interpolate_4d:()=>d.interpolate_4d,interpolate_data:()=>c.interpolate_data,layer_norm:()=>d.layer_norm,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,max:()=>c.max,mean:()=>d.mean,mean_pooling:()=>d.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>l.mel_filter_bank,min:()=>c.min,ones:()=>d.ones,ones_like:()=>d.ones_like,permute:()=>d.permute,permute_data:()=>c.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>d.quantize_embeddings,read_audio:()=>l.read_audio,round:()=>c.round,softmax:()=>c.softmax,spectrogram:()=>l.spectrogram,stack:()=>d.stack,std_mean:()=>d.std_mean,window_function:()=>l.window_function,zeros:()=>d.zeros,zeros_like:()=>d.zeros_like});var e=a(/*! ./env.js */"./src/env.js"),t=a(/*! ./pipelines.js */"./src/pipelines.js"),n=a(/*! ./models.js */"./src/models.js"),r=a(/*! ./tokenizers.js */"./src/tokenizers.js"),s=a(/*! ./processors.js */"./src/processors.js"),o=a(/*! ./configs.js */"./src/configs.js"),l=a(/*! ./utils/audio.js */"./src/utils/audio.js"),u=a(/*! ./utils/image.js */"./src/utils/image.js"),d=a(/*! ./utils/tensor.js */"./src/utils/tensor.js"),c=a(/*! ./utils/maths.js */"./src/utils/maths.js"),p=a(/*! ./generation/streamers.js */"./src/generation/streamers.js")})();var s=i.ASTFeatureExtractor,o=i.ASTForAudioClassification,l=i.ASTModel,u=i.ASTPreTrainedModel,d=i.AlbertForMaskedLM,c=i.AlbertForQuestionAnswering,p=i.AlbertForSequenceClassification,h=i.AlbertModel,f=i.AlbertPreTrainedModel,m=i.AlbertTokenizer,g=i.AudioClassificationPipeline,_=i.AutoConfig,w=i.AutoModel,y=i.AutoModelForAudioClassification,b=i.AutoModelForAudioFrameClassification,v=i.AutoModelForCTC,$=i.AutoModelForCausalLM,x=i.AutoModelForDepthEstimation,T=i.AutoModelForDocumentQuestionAnswering,S=i.AutoModelForImageClassification,M=i.AutoModelForImageFeatureExtraction,k=i.AutoModelForImageMatting,C=i.AutoModelForImageSegmentation,E=i.AutoModelForImageToImage,A=i.AutoModelForMaskGeneration,I=i.AutoModelForMaskedLM,P=i.AutoModelForObjectDetection,O=i.AutoModelForQuestionAnswering,z=i.AutoModelForSemanticSegmentation,B=i.AutoModelForSeq2SeqLM,F=i.AutoModelForSequenceClassification,R=i.AutoModelForSpeechSeq2Seq,D=i.AutoModelForTextToSpectrogram,L=i.AutoModelForTextToWaveform,N=i.AutoModelForTokenClassification,U=i.AutoModelForVision2Seq,W=i.AutoModelForXVector,V=i.AutoModelForZeroShotObjectDetection,G=i.AutoProcessor,j=i.AutoTokenizer,q=i.AutomaticSpeechRecognitionPipeline,H=i.BartForConditionalGeneration,K=i.BartForSequenceClassification,Y=i.BartModel,X=i.BartPretrainedModel,Q=i.BartTokenizer,Z=i.BaseModelOutput,J=i.BaseStreamer,ee=i.BeitFeatureExtractor,te=i.BeitForImageClassification,ne=i.BeitModel,re=i.BeitPreTrainedModel,ae=i.BertForMaskedLM,ie=i.BertForQuestionAnswering,se=i.BertForSequenceClassification,oe=i.BertForTokenClassification,le=i.BertModel,ue=i.BertPreTrainedModel,de=i.BertTokenizer,ce=i.BitImageProcessor,pe=i.BlenderbotForConditionalGeneration,he=i.BlenderbotModel,fe=i.BlenderbotPreTrainedModel,me=i.BlenderbotSmallForConditionalGeneration,ge=i.BlenderbotSmallModel,_e=i.BlenderbotSmallPreTrainedModel,we=i.BlenderbotSmallTokenizer,ye=i.BlenderbotTokenizer,be=i.BloomForCausalLM,ve=i.BloomModel,$e=i.BloomPreTrainedModel,xe=i.BloomTokenizer,Te=i.CLIPFeatureExtractor,Se=i.CLIPImageProcessor,Me=i.CLIPModel,ke=i.CLIPPreTrainedModel,Ce=i.CLIPSegForImageSegmentation,Ee=i.CLIPSegModel,Ae=i.CLIPSegPreTrainedModel,Ie=i.CLIPTextModelWithProjection,Pe=i.CLIPTokenizer,Oe=i.CLIPVisionModelWithProjection,ze=i.CamembertForMaskedLM,Be=i.CamembertForQuestionAnswering,Fe=i.CamembertForSequenceClassification,Re=i.CamembertForTokenClassification,De=i.CamembertModel,Le=i.CamembertPreTrainedModel,Ne=i.CamembertTokenizer,Ue=i.CausalLMOutput,We=i.CausalLMOutputWithPast,Ve=i.ChineseCLIPFeatureExtractor,Ge=i.ChineseCLIPModel,je=i.ChineseCLIPPreTrainedModel,qe=i.ClapAudioModelWithProjection,He=i.ClapFeatureExtractor,Ke=i.ClapModel,Ye=i.ClapPreTrainedModel,Xe=i.ClapTextModelWithProjection,Qe=i.CodeGenForCausalLM,Ze=i.CodeGenModel,Je=i.CodeGenPreTrainedModel,et=i.CodeGenTokenizer,tt=i.CodeLlamaTokenizer,nt=i.CohereTokenizer,rt=i.ConvBertForMaskedLM,at=i.ConvBertForQuestionAnswering,it=i.ConvBertForSequenceClassification,st=i.ConvBertForTokenClassification,ot=i.ConvBertModel,lt=i.ConvBertPreTrainedModel,ut=i.ConvBertTokenizer,dt=i.ConvNextFeatureExtractor,ct=i.ConvNextForImageClassification,pt=i.ConvNextImageProcessor,ht=i.ConvNextModel,ft=i.ConvNextPreTrainedModel,mt=i.ConvNextV2ForImageClassification,gt=i.ConvNextV2Model,_t=i.ConvNextV2PreTrainedModel,wt=i.DPTFeatureExtractor,yt=i.DPTForDepthEstimation,bt=i.DPTImageProcessor,vt=i.DPTModel,$t=i.DPTPreTrainedModel,xt=i.DebertaForMaskedLM,Tt=i.DebertaForQuestionAnswering,St=i.DebertaForSequenceClassification,Mt=i.DebertaForTokenClassification,kt=i.DebertaModel,Ct=i.DebertaPreTrainedModel,Et=i.DebertaTokenizer,At=i.DebertaV2ForMaskedLM,It=i.DebertaV2ForQuestionAnswering,Pt=i.DebertaV2ForSequenceClassification,Ot=i.DebertaV2ForTokenClassification,zt=i.DebertaV2Model,Bt=i.DebertaV2PreTrainedModel,Ft=i.DebertaV2Tokenizer,Rt=i.DeiTFeatureExtractor,Dt=i.DeiTForImageClassification,Lt=i.DeiTModel,Nt=i.DeiTPreTrainedModel,Ut=i.DepthAnythingForDepthEstimation,Wt=i.DepthAnythingPreTrainedModel,Vt=i.DepthEstimationPipeline,Gt=i.DetrFeatureExtractor,jt=i.DetrForObjectDetection,qt=i.DetrForSegmentation,Ht=i.DetrModel,Kt=i.DetrObjectDetectionOutput,Yt=i.DetrPreTrainedModel,Xt=i.DetrSegmentationOutput,Qt=i.Dinov2ForImageClassification,Zt=i.Dinov2Model,Jt=i.Dinov2PreTrainedModel,en=i.DistilBertForMaskedLM,tn=i.DistilBertForQuestionAnswering,nn=i.DistilBertForSequenceClassification,rn=i.DistilBertForTokenClassification,an=i.DistilBertModel,sn=i.DistilBertPreTrainedModel,on=i.DistilBertTokenizer,ln=i.DocumentQuestionAnsweringPipeline,un=i.DonutFeatureExtractor,dn=i.DonutSwinModel,cn=i.DonutSwinPreTrainedModel,pn=i.EfficientNetForImageClassification,hn=i.EfficientNetImageProcessor,fn=i.EfficientNetModel,mn=i.EfficientNetPreTrainedModel,gn=i.ElectraForMaskedLM,_n=i.ElectraForQuestionAnswering,wn=i.ElectraForSequenceClassification,yn=i.ElectraForTokenClassification,bn=i.ElectraModel,vn=i.ElectraPreTrainedModel,$n=i.ElectraTokenizer,xn=i.EsmForMaskedLM,Tn=i.EsmForSequenceClassification,Sn=i.EsmForTokenClassification,Mn=i.EsmModel,kn=i.EsmPreTrainedModel,Cn=i.EsmTokenizer,En=i.FFT,An=i.FalconForCausalLM,In=i.FalconModel,Pn=i.FalconPreTrainedModel,On=i.FalconTokenizer,zn=i.FeatureExtractionPipeline,Bn=i.FeatureExtractor,Fn=i.FillMaskPipeline,Rn=i.GLPNFeatureExtractor,Dn=i.GLPNForDepthEstimation,Ln=i.GLPNModel,Nn=i.GLPNPreTrainedModel,Un=i.GPT2LMHeadModel,Wn=i.GPT2Model,Vn=i.GPT2PreTrainedModel,Gn=i.GPT2Tokenizer,jn=i.GPTBigCodeForCausalLM,qn=i.GPTBigCodeModel,Hn=i.GPTBigCodePreTrainedModel,Kn=i.GPTJForCausalLM,Yn=i.GPTJModel,Xn=i.GPTJPreTrainedModel,Qn=i.GPTNeoForCausalLM,Zn=i.GPTNeoModel,Jn=i.GPTNeoPreTrainedModel,er=i.GPTNeoXForCausalLM,tr=i.GPTNeoXModel,nr=i.GPTNeoXPreTrainedModel,rr=i.GPTNeoXTokenizer,ar=i.GemmaTokenizer,ir=i.Grok1Tokenizer,sr=i.HerbertTokenizer,or=i.HubertForCTC,lr=i.HubertForSequenceClassification,ur=i.HubertModel,dr=i.HubertPreTrainedModel,cr=i.ImageClassificationPipeline,pr=i.ImageFeatureExtractionPipeline,hr=i.ImageFeatureExtractor,fr=i.ImageMattingOutput,mr=i.ImageSegmentationPipeline,gr=i.ImageToImagePipeline,_r=i.ImageToTextPipeline,wr=i.LlamaForCausalLM,yr=i.LlamaModel,br=i.LlamaPreTrainedModel,vr=i.LlamaTokenizer,$r=i.LlavaForConditionalGeneration,xr=i.LlavaPreTrainedModel,Tr=i.LongT5ForConditionalGeneration,Sr=i.LongT5Model,Mr=i.LongT5PreTrainedModel,kr=i.M2M100ForConditionalGeneration,Cr=i.M2M100Model,Er=i.M2M100PreTrainedModel,Ar=i.M2M100Tokenizer,Ir=i.MBart50Tokenizer,Pr=i.MBartForCausalLM,Or=i.MBartForConditionalGeneration,zr=i.MBartForSequenceClassification,Br=i.MBartModel,Fr=i.MBartPreTrainedModel,Rr=i.MBartTokenizer,Dr=i.MPNetForMaskedLM,Lr=i.MPNetForQuestionAnswering,Nr=i.MPNetForSequenceClassification,Ur=i.MPNetForTokenClassification,Wr=i.MPNetModel,Vr=i.MPNetPreTrainedModel,Gr=i.MPNetTokenizer,jr=i.MT5ForConditionalGeneration,qr=i.MT5Model,Hr=i.MT5PreTrainedModel,Kr=i.MarianMTModel,Yr=i.MarianModel,Xr=i.MarianPreTrainedModel,Qr=i.MarianTokenizer,Zr=i.MaskedLMOutput,Jr=i.MistralForCausalLM,ea=i.MistralModel,ta=i.MistralPreTrainedModel,na=i.MobileBertForMaskedLM,ra=i.MobileBertForQuestionAnswering,aa=i.MobileBertForSequenceClassification,ia=i.MobileBertModel,sa=i.MobileBertPreTrainedModel,oa=i.MobileBertTokenizer,la=i.MobileViTFeatureExtractor,ua=i.MobileViTForImageClassification,da=i.MobileViTModel,ca=i.MobileViTPreTrainedModel,pa=i.ModelOutput,ha=i.MptForCausalLM,fa=i.MptModel,ma=i.MptPreTrainedModel,ga=i.MusicgenForCausalLM,_a=i.MusicgenForConditionalGeneration,wa=i.MusicgenModel,ya=i.MusicgenPreTrainedModel,ba=i.NllbTokenizer,va=i.NomicBertModel,$a=i.NomicBertPreTrainedModel,xa=i.NougatImageProcessor,Ta=i.NougatTokenizer,Sa=i.OPTForCausalLM,Ma=i.OPTModel,ka=i.OPTPreTrainedModel,Ca=i.ObjectDetectionPipeline,Ea=i.OwlViTFeatureExtractor,Aa=i.OwlViTForObjectDetection,Ia=i.OwlViTModel,Pa=i.OwlViTPreTrainedModel,Oa=i.OwlViTProcessor,za=i.Owlv2ForObjectDetection,Ba=i.Owlv2ImageProcessor,Fa=i.Owlv2Model,Ra=i.Owlv2PreTrainedModel,Da=i.PhiForCausalLM,La=i.PhiModel,Na=i.PhiPreTrainedModel,Ua=i.Pipeline,Wa=i.PreTrainedModel,Va=i.PreTrainedTokenizer,Ga=i.PretrainedConfig,ja=i.PretrainedMixin,qa=i.Processor,Ha=i.QuestionAnsweringModelOutput,Ka=i.QuestionAnsweringPipeline,Ya=i.Qwen2ForCausalLM,Xa=i.Qwen2Model,Qa=i.Qwen2PreTrainedModel,Za=i.Qwen2Tokenizer,Ja=i.RawImage,ei=i.ResNetForImageClassification,ti=i.ResNetModel,ni=i.ResNetPreTrainedModel,ri=i.RoFormerForMaskedLM,ai=i.RoFormerForQuestionAnswering,ii=i.RoFormerForSequenceClassification,si=i.RoFormerForTokenClassification,oi=i.RoFormerModel,li=i.RoFormerPreTrainedModel,ui=i.RoFormerTokenizer,di=i.RobertaForMaskedLM,ci=i.RobertaForQuestionAnswering,pi=i.RobertaForSequenceClassification,hi=i.RobertaForTokenClassification,fi=i.RobertaModel,mi=i.RobertaPreTrainedModel,gi=i.RobertaTokenizer,_i=i.SamImageProcessor,wi=i.SamImageSegmentationOutput,yi=i.SamModel,bi=i.SamPreTrainedModel,vi=i.SamProcessor,$i=i.SeamlessM4TFeatureExtractor,xi=i.SegformerFeatureExtractor,Ti=i.SegformerForImageClassification,Si=i.SegformerForSemanticSegmentation,Mi=i.SegformerModel,ki=i.SegformerPreTrainedModel,Ci=i.Seq2SeqLMOutput,Ei=i.SequenceClassifierOutput,Ai=i.SiglipImageProcessor,Ii=i.SiglipModel,Pi=i.SiglipPreTrainedModel,Oi=i.SiglipTextModel,zi=i.SiglipTokenizer,Bi=i.SiglipVisionModel,Fi=i.SpeechT5FeatureExtractor,Ri=i.SpeechT5ForSpeechToText,Di=i.SpeechT5ForTextToSpeech,Li=i.SpeechT5HifiGan,Ni=i.SpeechT5Model,Ui=i.SpeechT5PreTrainedModel,Wi=i.SpeechT5Processor,Vi=i.SpeechT5Tokenizer,Gi=i.SqueezeBertForMaskedLM,ji=i.SqueezeBertForQuestionAnswering,qi=i.SqueezeBertForSequenceClassification,Hi=i.SqueezeBertModel,Ki=i.SqueezeBertPreTrainedModel,Yi=i.SqueezeBertTokenizer,Xi=i.StableLmForCausalLM,Qi=i.StableLmModel,Zi=i.StableLmPreTrainedModel,Ji=i.Starcoder2ForCausalLM,es=i.Starcoder2Model,ts=i.Starcoder2PreTrainedModel,ns=i.SummarizationPipeline,rs=i.Swin2SRForImageSuperResolution,as=i.Swin2SRImageProcessor,is=i.Swin2SRModel,ss=i.Swin2SRPreTrainedModel,os=i.SwinForImageClassification,ls=i.SwinModel,us=i.SwinPreTrainedModel,ds=i.T5ForConditionalGeneration,cs=i.T5Model,ps=i.T5PreTrainedModel,hs=i.T5Tokenizer,fs=i.TableTransformerForObjectDetection,ms=i.TableTransformerModel,gs=i.TableTransformerObjectDetectionOutput,_s=i.TableTransformerPreTrainedModel,ws=i.Tensor,ys=i.Text2TextGenerationPipeline,bs=i.TextClassificationPipeline,vs=i.TextGenerationPipeline,$s=i.TextToAudioPipeline,xs=i.TokenClassificationPipeline,Ts=i.TokenClassifierOutput,Ss=i.TokenizerModel,Ms=i.TrOCRForCausalLM,ks=i.TrOCRPreTrainedModel,Cs=i.TranslationPipeline,Es=i.UniSpeechForCTC,As=i.UniSpeechForSequenceClassification,Is=i.UniSpeechModel,Ps=i.UniSpeechPreTrainedModel,Os=i.UniSpeechSatForAudioFrameClassification,zs=i.UniSpeechSatForCTC,Bs=i.UniSpeechSatForSequenceClassification,Fs=i.UniSpeechSatModel,Rs=i.UniSpeechSatPreTrainedModel,Ds=i.ViTFeatureExtractor,Ls=i.ViTForImageClassification,Ns=i.ViTImageProcessor,Us=i.ViTModel,Ws=i.ViTPreTrainedModel,Vs=i.VisionEncoderDecoderModel,Gs=i.VitMatteForImageMatting,js=i.VitMatteImageProcessor,qs=i.VitMattePreTrainedModel,Hs=i.VitsModel,Ks=i.VitsModelOutput,Ys=i.VitsPreTrainedModel,Xs=i.VitsTokenizer,Qs=i.Wav2Vec2BertForCTC,Zs=i.Wav2Vec2BertForSequenceClassification,Js=i.Wav2Vec2BertModel,eo=i.Wav2Vec2BertPreTrainedModel,to=i.Wav2Vec2CTCTokenizer,no=i.Wav2Vec2FeatureExtractor,ro=i.Wav2Vec2ForAudioFrameClassification,ao=i.Wav2Vec2ForCTC,io=i.Wav2Vec2ForSequenceClassification,so=i.Wav2Vec2Model,oo=i.Wav2Vec2PreTrainedModel,lo=i.Wav2Vec2ProcessorWithLM,uo=i.WavLMForAudioFrameClassification,co=i.WavLMForCTC,po=i.WavLMForSequenceClassification,ho=i.WavLMForXVector,fo=i.WavLMModel,mo=i.WavLMPreTrainedModel,go=i.WhisperFeatureExtractor,_o=i.WhisperForConditionalGeneration,wo=i.WhisperModel,yo=i.WhisperPreTrainedModel,bo=i.WhisperProcessor,vo=i.WhisperTokenizer,$o=i.XLMForQuestionAnswering,xo=i.XLMForSequenceClassification,To=i.XLMForTokenClassification,So=i.XLMModel,Mo=i.XLMPreTrainedModel,ko=i.XLMRobertaForMaskedLM,Co=i.XLMRobertaForQuestionAnswering,Eo=i.XLMRobertaForSequenceClassification,Ao=i.XLMRobertaForTokenClassification,Io=i.XLMRobertaModel,Po=i.XLMRobertaPreTrainedModel,Oo=i.XLMRobertaTokenizer,zo=i.XLMTokenizer,Bo=i.XLMWithLMHeadModel,Fo=i.XVectorOutput,Ro=i.YolosFeatureExtractor,Do=i.YolosForObjectDetection,Lo=i.YolosModel,No=i.YolosObjectDetectionOutput,Uo=i.YolosPreTrainedModel,Wo=i.ZeroShotAudioClassificationPipeline,Vo=i.ZeroShotClassificationPipeline,Go=i.ZeroShotImageClassificationPipeline,jo=i.ZeroShotObjectDetectionPipeline,qo=i.bankers_round,Ho=i.cat,Ko=i.cos_sim,Yo=i.dot,Xo=i.dynamicTimeWarping,Qo=i.env,Zo=i.full,Jo=i.full_like,el=i.getTopItems,tl=i.hanning,nl=i.interpolate,rl=i.interpolate_4d,al=i.interpolate_data,il=i.layer_norm,sl=i.log_softmax,ol=i.magnitude,ll=i.max,ul=i.mean,dl=i.mean_pooling,cl=i.medianFilter,pl=i.mel_filter_bank,hl=i.min,fl=i.ones,ml=i.ones_like,gl=i.permute,_l=i.permute_data,wl=i.pipeline,yl=i.quantize_embeddings,bl=i.read_audio,vl=i.round,$l=i.softmax,xl=i.spectrogram,Tl=i.stack,Sl=i.std_mean,Ml=i.window_function,kl=i.zeros,Cl=i.zeros_like;export{s as ASTFeatureExtractor,o as ASTForAudioClassification,l as ASTModel,u as ASTPreTrainedModel,d as AlbertForMaskedLM,c as AlbertForQuestionAnswering,p as AlbertForSequenceClassification,h as AlbertModel,f as AlbertPreTrainedModel,m as AlbertTokenizer,g as AudioClassificationPipeline,_ as AutoConfig,w as AutoModel,y as AutoModelForAudioClassification,b as AutoModelForAudioFrameClassification,v as AutoModelForCTC,$ as AutoModelForCausalLM,x as AutoModelForDepthEstimation,T as AutoModelForDocumentQuestionAnswering,S as AutoModelForImageClassification,M as AutoModelForImageFeatureExtraction,k as AutoModelForImageMatting,C as AutoModelForImageSegmentation,E as AutoModelForImageToImage,A as AutoModelForMaskGeneration,I as AutoModelForMaskedLM,P as AutoModelForObjectDetection,O as AutoModelForQuestionAnswering,z as AutoModelForSemanticSegmentation,B as AutoModelForSeq2SeqLM,F as AutoModelForSequenceClassification,R as AutoModelForSpeechSeq2Seq,D as AutoModelForTextToSpectrogram,L as AutoModelForTextToWaveform,N as AutoModelForTokenClassification,U as AutoModelForVision2Seq,W as AutoModelForXVector,V as AutoModelForZeroShotObjectDetection,G as AutoProcessor,j as AutoTokenizer,q as AutomaticSpeechRecognitionPipeline,H as BartForConditionalGeneration,K as BartForSequenceClassification,Y as BartModel,X as BartPretrainedModel,Q as BartTokenizer,Z as BaseModelOutput,J as BaseStreamer,ee as BeitFeatureExtractor,te as BeitForImageClassification,ne as BeitModel,re as BeitPreTrainedModel,ae as BertForMaskedLM,ie as BertForQuestionAnswering,se as BertForSequenceClassification,oe as BertForTokenClassification,le as BertModel,ue as BertPreTrainedModel,de as BertTokenizer,ce as BitImageProcessor,pe as BlenderbotForConditionalGeneration,he as BlenderbotModel,fe as BlenderbotPreTrainedModel,me as BlenderbotSmallForConditionalGeneration,ge as BlenderbotSmallModel,_e as BlenderbotSmallPreTrainedModel,we as BlenderbotSmallTokenizer,ye as BlenderbotTokenizer,be as BloomForCausalLM,ve as BloomModel,$e as BloomPreTrainedModel,xe as BloomTokenizer,Te as CLIPFeatureExtractor,Se as CLIPImageProcessor,Me as CLIPModel,ke as CLIPPreTrainedModel,Ce as CLIPSegForImageSegmentation,Ee as CLIPSegModel,Ae as CLIPSegPreTrainedModel,Ie as CLIPTextModelWithProjection,Pe as CLIPTokenizer,Oe as CLIPVisionModelWithProjection,ze as CamembertForMaskedLM,Be as CamembertForQuestionAnswering,Fe as CamembertForSequenceClassification,Re as CamembertForTokenClassification,De as CamembertModel,Le as CamembertPreTrainedModel,Ne as CamembertTokenizer,Ue as CausalLMOutput,We as CausalLMOutputWithPast,Ve as ChineseCLIPFeatureExtractor,Ge as ChineseCLIPModel,je as ChineseCLIPPreTrainedModel,qe as ClapAudioModelWithProjection,He as ClapFeatureExtractor,Ke as ClapModel,Ye as ClapPreTrainedModel,Xe as ClapTextModelWithProjection,Qe as CodeGenForCausalLM,Ze as CodeGenModel,Je as CodeGenPreTrainedModel,et as CodeGenTokenizer,tt as CodeLlamaTokenizer,nt as CohereTokenizer,rt as ConvBertForMaskedLM,at as ConvBertForQuestionAnswering,it as ConvBertForSequenceClassification,st as ConvBertForTokenClassification,ot as ConvBertModel,lt as ConvBertPreTrainedModel,ut as ConvBertTokenizer,dt as ConvNextFeatureExtractor,ct as ConvNextForImageClassification,pt as ConvNextImageProcessor,ht as ConvNextModel,ft as ConvNextPreTrainedModel,mt as ConvNextV2ForImageClassification,gt as ConvNextV2Model,_t as ConvNextV2PreTrainedModel,wt as DPTFeatureExtractor,yt as DPTForDepthEstimation,bt as DPTImageProcessor,vt as DPTModel,$t as DPTPreTrainedModel,xt as DebertaForMaskedLM,Tt as DebertaForQuestionAnswering,St as DebertaForSequenceClassification,Mt as DebertaForTokenClassification,kt as DebertaModel,Ct as DebertaPreTrainedModel,Et as DebertaTokenizer,At as DebertaV2ForMaskedLM,It as DebertaV2ForQuestionAnswering,Pt as DebertaV2ForSequenceClassification,Ot as DebertaV2ForTokenClassification,zt as DebertaV2Model,Bt as DebertaV2PreTrainedModel,Ft as DebertaV2Tokenizer,Rt as DeiTFeatureExtractor,Dt as DeiTForImageClassification,Lt as DeiTModel,Nt as DeiTPreTrainedModel,Ut as DepthAnythingForDepthEstimation,Wt as DepthAnythingPreTrainedModel,Vt as DepthEstimationPipeline,Gt as DetrFeatureExtractor,jt as DetrForObjectDetection,qt as DetrForSegmentation,Ht as DetrModel,Kt as DetrObjectDetectionOutput,Yt as DetrPreTrainedModel,Xt as DetrSegmentationOutput,Qt as Dinov2ForImageClassification,Zt as Dinov2Model,Jt as Dinov2PreTrainedModel,en as DistilBertForMaskedLM,tn as DistilBertForQuestionAnswering,nn as DistilBertForSequenceClassification,rn as DistilBertForTokenClassification,an as DistilBertModel,sn as DistilBertPreTrainedModel,on as DistilBertTokenizer,ln as DocumentQuestionAnsweringPipeline,un as DonutFeatureExtractor,dn as DonutSwinModel,cn as DonutSwinPreTrainedModel,pn as EfficientNetForImageClassification,hn as EfficientNetImageProcessor,fn as EfficientNetModel,mn as EfficientNetPreTrainedModel,gn as ElectraForMaskedLM,_n as ElectraForQuestionAnswering,wn as ElectraForSequenceClassification,yn as ElectraForTokenClassification,bn as ElectraModel,vn as ElectraPreTrainedModel,$n as ElectraTokenizer,xn as EsmForMaskedLM,Tn as EsmForSequenceClassification,Sn as EsmForTokenClassification,Mn as EsmModel,kn as EsmPreTrainedModel,Cn as EsmTokenizer,En as FFT,An as FalconForCausalLM,In as FalconModel,Pn as FalconPreTrainedModel,On as FalconTokenizer,zn as FeatureExtractionPipeline,Bn as FeatureExtractor,Fn as FillMaskPipeline,Rn as GLPNFeatureExtractor,Dn as GLPNForDepthEstimation,Ln as GLPNModel,Nn as GLPNPreTrainedModel,Un as GPT2LMHeadModel,Wn as GPT2Model,Vn as GPT2PreTrainedModel,Gn as GPT2Tokenizer,jn as GPTBigCodeForCausalLM,qn as GPTBigCodeModel,Hn as GPTBigCodePreTrainedModel,Kn as GPTJForCausalLM,Yn as GPTJModel,Xn as GPTJPreTrainedModel,Qn as GPTNeoForCausalLM,Zn as GPTNeoModel,Jn as GPTNeoPreTrainedModel,er as GPTNeoXForCausalLM,tr as GPTNeoXModel,nr as GPTNeoXPreTrainedModel,rr as GPTNeoXTokenizer,ar as GemmaTokenizer,ir as Grok1Tokenizer,sr as HerbertTokenizer,or as HubertForCTC,lr as HubertForSequenceClassification,ur as HubertModel,dr as HubertPreTrainedModel,cr as ImageClassificationPipeline,pr as ImageFeatureExtractionPipeline,hr as ImageFeatureExtractor,fr as ImageMattingOutput,mr as ImageSegmentationPipeline,gr as ImageToImagePipeline,_r as ImageToTextPipeline,wr as LlamaForCausalLM,yr as LlamaModel,br as LlamaPreTrainedModel,vr as LlamaTokenizer,$r as LlavaForConditionalGeneration,xr as LlavaPreTrainedModel,Tr as LongT5ForConditionalGeneration,Sr as LongT5Model,Mr as LongT5PreTrainedModel,kr as M2M100ForConditionalGeneration,Cr as M2M100Model,Er as M2M100PreTrainedModel,Ar as M2M100Tokenizer,Ir as MBart50Tokenizer,Pr as MBartForCausalLM,Or as MBartForConditionalGeneration,zr as MBartForSequenceClassification,Br as MBartModel,Fr as MBartPreTrainedModel,Rr as MBartTokenizer,Dr as MPNetForMaskedLM,Lr as MPNetForQuestionAnswering,Nr as MPNetForSequenceClassification,Ur as MPNetForTokenClassification,Wr as MPNetModel,Vr as MPNetPreTrainedModel,Gr as MPNetTokenizer,jr as MT5ForConditionalGeneration,qr as MT5Model,Hr as MT5PreTrainedModel,Kr as MarianMTModel,Yr as MarianModel,Xr as MarianPreTrainedModel,Qr as MarianTokenizer,Zr as MaskedLMOutput,Jr as MistralForCausalLM,ea as MistralModel,ta as MistralPreTrainedModel,na as MobileBertForMaskedLM,ra as MobileBertForQuestionAnswering,aa as MobileBertForSequenceClassification,ia as MobileBertModel,sa as MobileBertPreTrainedModel,oa as MobileBertTokenizer,la as MobileViTFeatureExtractor,ua as MobileViTForImageClassification,da as MobileViTModel,ca as MobileViTPreTrainedModel,pa as ModelOutput,ha as MptForCausalLM,fa as MptModel,ma as MptPreTrainedModel,ga as MusicgenForCausalLM,_a as MusicgenForConditionalGeneration,wa as MusicgenModel,ya as MusicgenPreTrainedModel,ba as NllbTokenizer,va as NomicBertModel,$a as NomicBertPreTrainedModel,xa as NougatImageProcessor,Ta as NougatTokenizer,Sa as OPTForCausalLM,Ma as OPTModel,ka as OPTPreTrainedModel,Ca as ObjectDetectionPipeline,Ea as OwlViTFeatureExtractor,Aa as OwlViTForObjectDetection,Ia as OwlViTModel,Pa as OwlViTPreTrainedModel,Oa as OwlViTProcessor,za as Owlv2ForObjectDetection,Ba as Owlv2ImageProcessor,Fa as Owlv2Model,Ra as Owlv2PreTrainedModel,Da as PhiForCausalLM,La as PhiModel,Na as PhiPreTrainedModel,Ua as Pipeline,Wa as PreTrainedModel,Va as PreTrainedTokenizer,Ga as PretrainedConfig,ja as PretrainedMixin,qa as Processor,Ha as QuestionAnsweringModelOutput,Ka as QuestionAnsweringPipeline,Ya as Qwen2ForCausalLM,Xa as Qwen2Model,Qa as Qwen2PreTrainedModel,Za as Qwen2Tokenizer,Ja as RawImage,ei as ResNetForImageClassification,ti as ResNetModel,ni as ResNetPreTrainedModel,ri as RoFormerForMaskedLM,ai as RoFormerForQuestionAnswering,ii as RoFormerForSequenceClassification,si as RoFormerForTokenClassification,oi as RoFormerModel,li as RoFormerPreTrainedModel,ui as RoFormerTokenizer,di as RobertaForMaskedLM,ci as RobertaForQuestionAnswering,pi as RobertaForSequenceClassification,hi as RobertaForTokenClassification,fi as RobertaModel,mi as RobertaPreTrainedModel,gi as RobertaTokenizer,_i as SamImageProcessor,wi as SamImageSegmentationOutput,yi as SamModel,bi as SamPreTrainedModel,vi as SamProcessor,$i as SeamlessM4TFeatureExtractor,xi as SegformerFeatureExtractor,Ti as SegformerForImageClassification,Si as SegformerForSemanticSegmentation,Mi as SegformerModel,ki as SegformerPreTrainedModel,Ci as Seq2SeqLMOutput,Ei as SequenceClassifierOutput,Ai as SiglipImageProcessor,Ii as SiglipModel,Pi as SiglipPreTrainedModel,Oi as SiglipTextModel,zi as SiglipTokenizer,Bi as SiglipVisionModel,Fi as SpeechT5FeatureExtractor,Ri as SpeechT5ForSpeechToText,Di as SpeechT5ForTextToSpeech,Li as SpeechT5HifiGan,Ni as SpeechT5Model,Ui as SpeechT5PreTrainedModel,Wi as SpeechT5Processor,Vi as SpeechT5Tokenizer,Gi as SqueezeBertForMaskedLM,ji as SqueezeBertForQuestionAnswering,qi as SqueezeBertForSequenceClassification,Hi as SqueezeBertModel,Ki as SqueezeBertPreTrainedModel,Yi as SqueezeBertTokenizer,Xi as StableLmForCausalLM,Qi as StableLmModel,Zi as StableLmPreTrainedModel,Ji as Starcoder2ForCausalLM,es as Starcoder2Model,ts as Starcoder2PreTrainedModel,ns as SummarizationPipeline,rs as Swin2SRForImageSuperResolution,as as Swin2SRImageProcessor,is as Swin2SRModel,ss as Swin2SRPreTrainedModel,os as SwinForImageClassification,ls as SwinModel,us as SwinPreTrainedModel,ds as T5ForConditionalGeneration,cs as T5Model,ps as T5PreTrainedModel,hs as T5Tokenizer,fs as TableTransformerForObjectDetection,ms as TableTransformerModel,gs as TableTransformerObjectDetectionOutput,_s as TableTransformerPreTrainedModel,ws as Tensor,ys as Text2TextGenerationPipeline,bs as TextClassificationPipeline,vs as TextGenerationPipeline,$s as TextToAudioPipeline,xs as TokenClassificationPipeline,Ts as TokenClassifierOutput,Ss as TokenizerModel,Ms as TrOCRForCausalLM,ks as TrOCRPreTrainedModel,Cs as TranslationPipeline,Es as UniSpeechForCTC,As as UniSpeechForSequenceClassification,Is as UniSpeechModel,Ps as UniSpeechPreTrainedModel,Os as UniSpeechSatForAudioFrameClassification,zs as UniSpeechSatForCTC,Bs as UniSpeechSatForSequenceClassification,Fs as UniSpeechSatModel,Rs as UniSpeechSatPreTrainedModel,Ds as ViTFeatureExtractor,Ls as ViTForImageClassification,Ns as ViTImageProcessor,Us as ViTModel,Ws as ViTPreTrainedModel,Vs as VisionEncoderDecoderModel,Gs as VitMatteForImageMatting,js as VitMatteImageProcessor,qs as VitMattePreTrainedModel,Hs as VitsModel,Ks as VitsModelOutput,Ys as VitsPreTrainedModel,Xs as VitsTokenizer,Qs as Wav2Vec2BertForCTC,Zs as Wav2Vec2BertForSequenceClassification,Js as Wav2Vec2BertModel,eo as Wav2Vec2BertPreTrainedModel,to as Wav2Vec2CTCTokenizer,no as Wav2Vec2FeatureExtractor,ro as Wav2Vec2ForAudioFrameClassification,ao as Wav2Vec2ForCTC,io as Wav2Vec2ForSequenceClassification,so as Wav2Vec2Model,oo as Wav2Vec2PreTrainedModel,lo as Wav2Vec2ProcessorWithLM,uo as WavLMForAudioFrameClassification,co as WavLMForCTC,po as WavLMForSequenceClassification,ho as WavLMForXVector,fo as WavLMModel,mo as WavLMPreTrainedModel,go as WhisperFeatureExtractor,_o as WhisperForConditionalGeneration,wo as WhisperModel,yo as WhisperPreTrainedModel,bo as WhisperProcessor,vo as WhisperTokenizer,$o as XLMForQuestionAnswering,xo as XLMForSequenceClassification,To as XLMForTokenClassification,So as XLMModel,Mo as XLMPreTrainedModel,ko as XLMRobertaForMaskedLM,Co as XLMRobertaForQuestionAnswering,Eo as XLMRobertaForSequenceClassification,Ao as XLMRobertaForTokenClassification,Io as XLMRobertaModel,Po as XLMRobertaPreTrainedModel,Oo as XLMRobertaTokenizer,zo as XLMTokenizer,Bo as XLMWithLMHeadModel,Fo as XVectorOutput,Ro as YolosFeatureExtractor,Do as YolosForObjectDetection,Lo as YolosModel,No as YolosObjectDetectionOutput,Uo as YolosPreTrainedModel,Wo as ZeroShotAudioClassificationPipeline,Vo as ZeroShotClassificationPipeline,Go as ZeroShotImageClassificationPipeline,jo as ZeroShotObjectDetectionPipeline,qo as bankers_round,Ho as cat,Ko as cos_sim,Yo as dot,Xo as dynamicTimeWarping,Qo as env,Zo as full,Jo as full_like,el as getTopItems,tl as hanning,nl as interpolate,rl as interpolate_4d,al as interpolate_data,il as layer_norm,sl as log_softmax,ol as magnitude,ll as max,ul as mean,dl as mean_pooling,cl as medianFilter,pl as mel_filter_bank,hl as min,fl as ones,ml as ones_like,gl as permute,_l as permute_data,wl as pipeline,yl as quantize_embeddings,bl as read_audio,vl as round,$l as softmax,xl as spectrogram,Tl as stack,Sl as std_mean,Ml as window_function,kl as zeros,Cl as zeros_like}; //# sourceMappingURL=transformers.min.js.map