=g){var h=a.charCodeAt(++f);g=65536+((g&1023)<<10)|h&1023}H()[b>>>2>>>0]=g;b+=4;if(b+4>c)break}H()[b>>>2>>>0]=0;return b-d},yd=a=>{for(var b=0,c=0;c=
+d&&++c;b+=4}return b};
+function Bb(a,b,c){a>>>=0;b>>>=0;c>>>=0;c=R(c);if(2===b){var d=td;var f=ud;var g=vd;var h=l=>Fa()[l>>>1>>>0]}else 4===b&&(d=wd,f=xd,g=yd,h=l=>I()[l>>>2>>>0]);T(a,{name:c,fromWireType:l=>{for(var m=I()[l>>>2>>>0],p,r=l+4,u=0;u<=m;++u){var w=l+4+u*b;if(u==m||0==h(w))r=d(r,w-r),void 0===p?p=r:(p+=String.fromCharCode(0),p+=r),r=w+b}Y(l);return p},toWireType:(l,m)=>{if("string"!=typeof m)throw new S(`Cannot pass non-string to C++ string type ${c}`);var p=g(m),r=rd(4+p+b);I()[r>>>2>>>0]=p/b;f(m,r+4,p+b);
+null!==l&&l.push(Y,r);return r},Cb:U,readValueFromPointer:od,Db(l){Y(l)}})}function Cb(a,b){a>>>=0;b=R(b>>>0);T(a,{Tb:!0,name:b,Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function Db(a){Ma(a>>>0,!k,1,!ea,131072,!1);Na()}var zd=a=>{if(!A)try{if(a(),!(0>>=0;"function"===typeof Atomics.jc&&(Atomics.jc(H(),a>>>2,a).value.then(Ra),a+=128,Atomics.store(H(),a>>>2,1))}var Ra=()=>{var a=Ka();a&&(Oa(a),zd(Ad))};function Eb(a,b){a>>>=0;a==b>>>0?setTimeout(Ra):q?postMessage({Gb:a,Bb:"checkMailbox"}):(a=O[a])&&a.postMessage({Bb:"checkMailbox"})}var Bd=[];function Fb(a,b,c,d,f){b>>>=0;d/=2;Bd.length=d;c=f>>>0>>>3;for(f=0;f>>0];return(b?Dc[b]:Cd[a])(...Bd)}var Gb=()=>{P=0};
+function Hb(a){a>>>=0;q?postMessage({Bb:"cleanupThread",hc:a}):Vc(O[a])}function Ib(a){n&&O[a>>>0].ref()}var Ed=(a,b)=>{var c=jd[a];if(void 0===c)throw a=Dd(a),c=R(a),Y(a),new S(`${b} has unknown type ${c}`);return c},Fd=(a,b,c)=>{var d=[];a=a.toWireType(d,c);d.length&&(I()[b>>>2>>>0]=X(d));return a};function Jb(a,b,c){b>>>=0;c>>>=0;a=W(a>>>0);b=Ed(b,"emval::as");return Fd(b,c,a)}function Kb(a,b){b>>>=0;a=W(a>>>0);b=Ed(b,"emval::as");return b.toWireType(null,a)}var Gd=a=>{try{a()}catch(b){L(b)}};
+function Hd(){var a=K,b={};for(let [c,d]of Object.entries(a))b[c]="function"==typeof d?(...f)=>{Id.push(c);try{return d(...f)}finally{A||(Id.pop(),t&&1===Z&&0===Id.length&&(Z=0,P+=1,Gd(Jd),"undefined"!=typeof Fibers&&Fibers.rc()))}}:d;return b}var Z=0,t=null,Kd=0,Id=[],Ld={},Md={},Nd=0,Od=null,Pd=[];function ia(){return new Promise((a,b)=>{Od={resolve:a,reject:b}})}
+function Qd(){var a=rd(65548),b=a+12;I()[a>>>2>>>0]=b;I()[a+4>>>2>>>0]=b+65536;b=Id[0];var c=Ld[b];void 0===c&&(c=Nd++,Ld[b]=c,Md[c]=b);b=c;H()[a+8>>>2>>>0]=b;return a}function Rd(){var a=H()[t+8>>>2>>>0];a=K[Md[a]];--P;return a()}
+function Sd(a){if(!A){if(0===Z){var b=!1,c=!1;a((d=0)=>{if(!A&&(Kd=d,b=!0,c)){Z=2;Gd(()=>Td(t));"undefined"!=typeof MainLoop&&MainLoop.Pb&&MainLoop.resume();d=!1;try{var f=Rd()}catch(l){f=l,d=!0}var g=!1;if(!t){var h=Od;h&&(Od=null,(d?h.reject:h.resolve)(f),g=!0)}if(d&&!g)throw f;}});c=!0;b||(Z=1,t=Qd(),"undefined"!=typeof MainLoop&&MainLoop.Pb&&MainLoop.pause(),Gd(()=>Ud(t)))}else 2===Z?(Z=0,Gd(Wd),Y(t),t=null,Pd.forEach(zd)):L(`invalid state: ${Z}`);return Kd}}
+function Ec(a){return Sd(b=>{a().then(b)})}function Lb(a){a>>>=0;return Ec(async()=>{var b=await W(a);return X(b)})}var Xd=[];function Mb(a,b,c,d){c>>>=0;d>>>=0;a=Xd[a>>>0];b=W(b>>>0);return a(null,b,c,d)}var Yd={},Zd=a=>{var b=Yd[a];return void 0===b?R(a):b};function Nb(a,b,c,d,f){c>>>=0;d>>>=0;f>>>=0;a=Xd[a>>>0];b=W(b>>>0);c=Zd(c);return a(b,b[c],d,f)}var $d=()=>"object"==typeof globalThis?globalThis:Function("return this")();
+function Pb(a){a>>>=0;if(0===a)return X($d());a=Zd(a);return X($d()[a])}var ae=a=>{var b=Xd.length;Xd.push(a);return b},be=(a,b)=>{for(var c=Array(a),d=0;d>>2>>>0],"parameter "+d);return c},ce=(a,b)=>Object.defineProperty(b,"name",{value:a});
+function de(a){var b=Function;if(!(b instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof b} which is not a function`);var c=ce(b.name||"unknownFunctionName",function(){});c.prototype=b.prototype;c=new c;a=b.apply(c,a);return a instanceof Object?a:c}
+function Qb(a,b,c){b=be(a,b>>>0);var d=b.shift();a--;var f="return function (obj, func, destructorsRef, args) {\n",g=0,h=[];0===c&&h.push("obj");for(var l=["retType"],m=[d],p=0;pr.name).join(", ")}) => ${d.name}>`;return ae(ce(c,a))}function Rb(a){a=Zd(a>>>0);return X(e[a])}function Sb(a,b){b>>>=0;a=W(a>>>0);b=W(b);return X(a[b])}function Tb(a){a>>>=0;9>>0);for(var b=Array(a.length),c=0;c>>0))}function Xb(){return X({})}
+function Yb(a){a>>>=0;for(var b=W(a);b.length;){var c=b.pop();b.pop()(c)}Ob(a)}function Zb(a,b,c){b>>>=0;c>>>=0;a=W(a>>>0);b=W(b);c=W(c);a[b]=c}function $b(a,b){b>>>=0;a=Ed(a>>>0,"_emval_take_value");a=a.readValueFromPointer(b);return X(a)}
+function ac(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);H()[b>>>2>>>0]=a.getUTCSeconds();H()[b+4>>>2>>>0]=a.getUTCMinutes();H()[b+8>>>2>>>0]=a.getUTCHours();H()[b+12>>>2>>>0]=a.getUTCDate();H()[b+16>>>2>>>0]=a.getUTCMonth();H()[b+20>>>2>>>0]=a.getUTCFullYear()-1900;H()[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;H()[b+28>>>2>>>0]=a}
+var ee=a=>0===a%4&&(0!==a%100||0===a%400),fe=[0,31,60,91,121,152,182,213,244,274,305,335],ge=[0,31,59,90,120,151,181,212,243,273,304,334];
+function bc(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);H()[b>>>2>>>0]=a.getSeconds();H()[b+4>>>2>>>0]=a.getMinutes();H()[b+8>>>2>>>0]=a.getHours();H()[b+12>>>2>>>0]=a.getDate();H()[b+16>>>2>>>0]=a.getMonth();H()[b+20>>>2>>>0]=a.getFullYear()-1900;H()[b+24>>>2>>>0]=a.getDay();var c=(ee(a.getFullYear())?fe:ge)[a.getMonth()]+a.getDate()-1|0;H()[b+28>>>2>>>0]=c;H()[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());c=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();
+var d=(new Date(a.getFullYear(),0,1)).getTimezoneOffset();a=(c!=d&&a.getTimezoneOffset()==Math.min(d,c))|0;H()[b+32>>>2>>>0]=a}
+function cc(a){a>>>=0;var b=new Date(H()[a+20>>>2>>>0]+1900,H()[a+16>>>2>>>0],H()[a+12>>>2>>>0],H()[a+8>>>2>>>0],H()[a+4>>>2>>>0],H()[a>>>2>>>0],0),c=H()[a+32>>>2>>>0],d=b.getTimezoneOffset(),f=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),g=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),h=Math.min(g,f);0>c?H()[a+32>>>2>>>0]=Number(f!=g&&h==d):0>>2>>>0]=b.getDay();c=(ee(b.getFullYear())?fe:ge)[b.getMonth()]+
+b.getDate()-1|0;H()[a+28>>>2>>>0]=c;H()[a>>>2>>>0]=b.getSeconds();H()[a+4>>>2>>>0]=b.getMinutes();H()[a+8>>>2>>>0]=b.getHours();H()[a+12>>>2>>>0]=b.getDate();H()[a+16>>>2>>>0]=b.getMonth();H()[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function dc(a,b,c,d,f,g,h){return q?Q(16,1,a,b,c,d,f,g,h):-52}function ec(a,b,c,d,f,g){if(q)return Q(17,1,a,b,c,d,f,g)}var he={},pc=()=>performance.timeOrigin+performance.now();
+function fc(a,b){if(q)return Q(18,1,a,b);he[a]&&(clearTimeout(he[a].id),delete he[a]);if(!b)return 0;var c=setTimeout(()=>{delete he[a];zd(()=>ie(a,performance.timeOrigin+performance.now()))},b);he[a]={id:c,qc:b};return 0}
+function gc(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;var f=(new Date).getFullYear(),g=(new Date(f,0,1)).getTimezoneOffset();f=(new Date(f,6,1)).getTimezoneOffset();var h=Math.max(g,f);I()[a>>>2>>>0]=60*h;H()[b>>>2>>>0]=Number(g!=f);b=l=>{var m=Math.abs(l);return`UTC${0<=l?"-":"+"}${String(Math.floor(m/60)).padStart(2,"0")}${String(m%60).padStart(2,"0")}`};a=b(g);b=b(f);fDate.now(),je=1;
+function hc(a,b,c){if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(je)a=performance.timeOrigin+performance.now();else return 52;C[c>>>0>>>3]=BigInt(Math.round(1E6*a));return 0}var ke=[],le=(a,b)=>{ke.length=0;for(var c;c=F()[a++>>>0];){var d=105!=c;d&=112!=c;b+=d&&b%8?4:0;ke.push(112==c?I()[b>>>2>>>0]:106==c?C[b>>>3]:105==c?H()[b>>>2>>>0]:J()[b>>>3>>>0]);b+=d?8:4}return ke};function ic(a,b,c){a>>>=0;b=le(b>>>0,c>>>0);return Dc[a](...b)}
+function jc(a,b,c){a>>>=0;b=le(b>>>0,c>>>0);return Dc[a](...b)}var kc=()=>{};function mc(a,b){return x(M(a>>>0,b>>>0))}var nc=()=>{P+=1;throw"unwind";};function oc(){return 4294901760}var qc=()=>n?require("os").cpus().length:navigator.hardwareConcurrency;function rc(){L("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER");return 0}
+function sc(a){a>>>=0;var b=F().length;if(a<=b||4294901760=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(4294901760,65536*Math.ceil(Math.max(a,d)/65536))-z.buffer.byteLength+65535)/65536|0;try{z.grow(d);E();var f=1;break a}catch(g){}f=void 0}if(f)return!0}return!1}var me=()=>{L("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER");return 0},ne={},oe=a=>{a.forEach(b=>{var c=me();c&&(ne[c]=b)})};
+function tc(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();oe(a);ne.Lb=me();ne.cc=a;return ne.Lb}function uc(a,b,c){a>>>=0;b>>>=0;if(ne.Lb==a)var d=ne.cc;else d=Error().stack.toString().split("\n"),"Error"==d[0]&&d.shift(),oe(d);for(var f=3;d[f]&&me()!=a;)++f;for(a=0;a>>2>>>0]=me();return a}
+var pe={},re=()=>{if(!qe){var a={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",_:la||"./this.program"},b;for(b in pe)void 0===pe[b]?delete a[b]:a[b]=pe[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`);qe=c}return qe},qe;
+function vc(a,b){if(q)return Q(19,1,a,b);a>>>=0;b>>>=0;var c=0;re().forEach((d,f)=>{var g=b+c;f=I()[a+4*f>>>2>>>0]=g;for(g=0;g>>0]=d.charCodeAt(g);D()[f>>>0]=0;c+=d.length+1});return 0}function wc(a,b){if(q)return Q(20,1,a,b);a>>>=0;b>>>=0;var c=re();I()[a>>>2>>>0]=c.length;var d=0;c.forEach(f=>d+=f.length+1);I()[b>>>2>>>0]=d;return 0}function yc(a){return q?Q(21,1,a):52}function zc(a,b,c,d){return q?Q(22,1,a,b,c,d):52}function Ac(a,b,c,d){return q?Q(23,1,a,b,c,d):70}
+var se=[null,[],[]];function Bc(a,b,c,d){if(q)return Q(24,1,a,b,c,d);b>>>=0;c>>>=0;d>>>=0;for(var f=0,g=0;g>>2>>>0],l=I()[b+4>>>2>>>0];b+=8;for(var m=0;m>>0],r=se[a];0===p||10===p?((1===a?ta:x)(dd(r)),r.length=0):r.push(p)}f+=l}I()[d>>>2>>>0]=f;return 0}q||Sc();for(var te=Array(256),ue=0;256>ue;++ue)te[ue]=String.fromCharCode(ue);gd=te;S=e.BindingError=class extends Error{constructor(a){super(a);this.name="BindingError"}};
+e.InternalError=class extends Error{constructor(a){super(a);this.name="InternalError"}};V.push(0,1,void 0,1,null,1,!0,1,!1,1);e.count_emval_handles=()=>V.length/2-5-nd.length;var Cd=[Cc,Qc,bd,gb,hb,ib,jb,kb,lb,mb,nb,ob,pb,qb,rb,sb,dc,ec,fc,vc,wc,yc,zc,Ac,Bc],bb,K;
+(async function(){function a(d,f){K=d.exports;K=Hd();K=ve();Rc.push(K.ib);va=f;Wa();return K}Ua++;var b=ab();if(e.instantiateWasm)return new Promise(d=>{e.instantiateWasm(b,(f,g)=>{a(f,g);d(f.exports)})});if(q)return new Promise(d=>{Ha=f=>{var g=new WebAssembly.Instance(f,ab());d(a(g,f))}});Xa??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.jsep.wasm",v):v+"ort-wasm-simd-threaded.jsep.wasm":(new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url)).href;try{var c=await $a(b);
+return a(c.instance,c.module)}catch(d){return ca(d),Promise.reject(d)}})();var Dd=a=>(Dd=K.Da)(a),Pa=()=>(Pa=K.Ea)();e._OrtInit=(a,b)=>(e._OrtInit=K.Fa)(a,b);e._OrtGetLastError=(a,b)=>(e._OrtGetLastError=K.Ga)(a,b);e._OrtCreateSessionOptions=(a,b,c,d,f,g,h,l,m,p)=>(e._OrtCreateSessionOptions=K.Ha)(a,b,c,d,f,g,h,l,m,p);e._OrtAppendExecutionProvider=(a,b,c,d,f)=>(e._OrtAppendExecutionProvider=K.Ia)(a,b,c,d,f);e._OrtAddFreeDimensionOverride=(a,b,c)=>(e._OrtAddFreeDimensionOverride=K.Ja)(a,b,c);
+e._OrtAddSessionConfigEntry=(a,b,c)=>(e._OrtAddSessionConfigEntry=K.Ka)(a,b,c);e._OrtReleaseSessionOptions=a=>(e._OrtReleaseSessionOptions=K.La)(a);e._OrtCreateSession=(a,b,c)=>(e._OrtCreateSession=K.Ma)(a,b,c);e._OrtReleaseSession=a=>(e._OrtReleaseSession=K.Na)(a);e._OrtGetInputOutputCount=(a,b,c)=>(e._OrtGetInputOutputCount=K.Oa)(a,b,c);e._OrtGetInputOutputMetadata=(a,b,c,d)=>(e._OrtGetInputOutputMetadata=K.Pa)(a,b,c,d);e._OrtFree=a=>(e._OrtFree=K.Qa)(a);
+e._OrtCreateTensor=(a,b,c,d,f,g)=>(e._OrtCreateTensor=K.Ra)(a,b,c,d,f,g);e._OrtGetTensorData=(a,b,c,d,f)=>(e._OrtGetTensorData=K.Sa)(a,b,c,d,f);e._OrtReleaseTensor=a=>(e._OrtReleaseTensor=K.Ta)(a);e._OrtCreateRunOptions=(a,b,c,d)=>(e._OrtCreateRunOptions=K.Ua)(a,b,c,d);e._OrtAddRunConfigEntry=(a,b,c)=>(e._OrtAddRunConfigEntry=K.Va)(a,b,c);e._OrtReleaseRunOptions=a=>(e._OrtReleaseRunOptions=K.Wa)(a);e._OrtCreateBinding=a=>(e._OrtCreateBinding=K.Xa)(a);
+e._OrtBindInput=(a,b,c)=>(e._OrtBindInput=K.Ya)(a,b,c);e._OrtBindOutput=(a,b,c,d)=>(e._OrtBindOutput=K.Za)(a,b,c,d);e._OrtClearBoundOutputs=a=>(e._OrtClearBoundOutputs=K._a)(a);e._OrtReleaseBinding=a=>(e._OrtReleaseBinding=K.$a)(a);e._OrtRunWithBinding=(a,b,c,d,f)=>(e._OrtRunWithBinding=K.ab)(a,b,c,d,f);e._OrtRun=(a,b,c,d,f,g,h,l)=>(e._OrtRun=K.bb)(a,b,c,d,f,g,h,l);e._OrtEndProfiling=a=>(e._OrtEndProfiling=K.cb)(a);e._JsepOutput=(a,b,c)=>(e._JsepOutput=K.db)(a,b,c);
+e._JsepGetNodeName=a=>(e._JsepGetNodeName=K.eb)(a);
+var Ka=()=>(Ka=K.fb)(),Y=e._free=a=>(Y=e._free=K.gb)(a),rd=e._malloc=a=>(rd=e._malloc=K.hb)(a),Ma=(a,b,c,d,f,g)=>(Ma=K.kb)(a,b,c,d,f,g),Sa=()=>(Sa=K.lb)(),Oc=(a,b,c,d,f)=>(Oc=K.mb)(a,b,c,d,f),Uc=a=>(Uc=K.nb)(a),Yc=a=>(Yc=K.ob)(a),ie=(a,b)=>(ie=K.pb)(a,b),Ad=()=>(Ad=K.qb)(),Wc=(a,b)=>(Wc=K.rb)(a,b),Pc=a=>(Pc=K.sb)(a),Nc=a=>(Nc=K.tb)(a),Mc=()=>(Mc=K.ub)(),Xc=e.dynCall_ii=(a,b)=>(Xc=e.dynCall_ii=K.vb)(a,b),Ud=a=>(Ud=K.wb)(a),Jd=()=>(Jd=K.xb)(),Td=a=>(Td=K.yb)(a),Wd=()=>(Wd=K.zb)();
+function ve(){var a=K;a=Object.assign({},a);var b=d=>f=>d(f)>>>0,c=d=>()=>d()>>>0;a.Da=b(a.Da);a.fb=c(a.fb);a.hb=b(a.hb);a.tb=b(a.tb);a.ub=c(a.ub);a.__cxa_get_exception_ptr=b(a.__cxa_get_exception_ptr);return a}e.stackSave=()=>Mc();e.stackRestore=a=>Pc(a);e.stackAlloc=a=>Nc(a);
+e.setValue=function(a,b,c="i8"){c.endsWith("*")&&(c="*");switch(c){case "i1":D()[a>>>0]=b;break;case "i8":D()[a>>>0]=b;break;case "i16":G()[a>>>1>>>0]=b;break;case "i32":H()[a>>>2>>>0]=b;break;case "i64":C[a>>>3]=BigInt(b);break;case "float":Ga()[a>>>2>>>0]=b;break;case "double":J()[a>>>3>>>0]=b;break;case "*":I()[a>>>2>>>0]=b;break;default:L(`invalid type for setValue: ${c}`)}};
+e.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return D()[a>>>0];case "i8":return D()[a>>>0];case "i16":return G()[a>>>1>>>0];case "i32":return H()[a>>>2>>>0];case "i64":return C[a>>>3];case "float":return Ga()[a>>>2>>>0];case "double":return J()[a>>>3>>>0];case "*":return I()[a>>>2>>>0];default:L(`invalid type for getValue: ${b}`)}};e.UTF8ToString=M;e.stringToUTF8=fd;e.lengthBytesUTF8=ed;
+function we(){if(0 key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
+}) : x)(function(x) {
+ if (typeof require !== "undefined") return require.apply(this, arguments);
+ throw Error('Dynamic require of "' + x + '" is not supported');
+});
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
+
+// node_modules/onnxruntime-common/dist/esm/index.js
+var esm_exports = {};
+__export(esm_exports, {
+ InferenceSession: () => InferenceSession2,
+ TRACE: () => TRACE,
+ TRACE_FUNC_BEGIN: () => TRACE_FUNC_BEGIN,
+ TRACE_FUNC_END: () => TRACE_FUNC_END,
+ Tensor: () => Tensor2,
+ env: () => env2,
+ registerBackend: () => registerBackend
+});
+
+// node_modules/onnxruntime-common/dist/esm/backend-impl.js
+var backends = /* @__PURE__ */ new Map();
+var backendsSortedByPriority = [];
+var registerBackend = (name, backend, priority) => {
+ if (backend && typeof backend.init === "function" && typeof backend.createInferenceSessionHandler === "function") {
+ const currentBackend = backends.get(name);
+ if (currentBackend === void 0) {
+ backends.set(name, { backend, priority });
+ } else if (currentBackend.priority > priority) {
+ return;
+ } else if (currentBackend.priority === priority) {
+ if (currentBackend.backend !== backend) {
+ throw new Error(`cannot register backend "${name}" using priority ${priority}`);
+ }
+ }
+ if (priority >= 0) {
+ const i = backendsSortedByPriority.indexOf(name);
+ if (i !== -1) {
+ backendsSortedByPriority.splice(i, 1);
+ }
+ for (let i2 = 0; i2 < backendsSortedByPriority.length; i2++) {
+ if (backends.get(backendsSortedByPriority[i2]).priority <= priority) {
+ backendsSortedByPriority.splice(i2, 0, name);
+ return;
+ }
+ }
+ backendsSortedByPriority.push(name);
+ }
+ return;
+ }
+ throw new TypeError("not a valid backend");
+};
+var tryResolveAndInitializeBackend = async (backendName) => {
+ const backendInfo = backends.get(backendName);
+ if (!backendInfo) {
+ return "backend not found.";
+ }
+ if (backendInfo.initialized) {
+ return backendInfo.backend;
+ } else if (backendInfo.aborted) {
+ return backendInfo.error;
+ } else {
+ const isInitializing = !!backendInfo.initPromise;
+ try {
+ if (!isInitializing) {
+ backendInfo.initPromise = backendInfo.backend.init(backendName);
+ }
+ await backendInfo.initPromise;
+ backendInfo.initialized = true;
+ return backendInfo.backend;
+ } catch (e) {
+ if (!isInitializing) {
+ backendInfo.error = `${e}`;
+ backendInfo.aborted = true;
+ }
+ return backendInfo.error;
+ } finally {
+ delete backendInfo.initPromise;
+ }
+ }
+};
+var resolveBackendAndExecutionProviders = async (options) => {
+ const eps = options.executionProviders || [];
+ const backendHints = eps.map((i) => typeof i === "string" ? i : i.name);
+ const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;
+ let backend;
+ const errors = [];
+ const availableBackendNames = /* @__PURE__ */ new Set();
+ for (const backendName of backendNames) {
+ const resolveResult = await tryResolveAndInitializeBackend(backendName);
+ if (typeof resolveResult === "string") {
+ errors.push({ name: backendName, err: resolveResult });
+ } else {
+ if (!backend) {
+ backend = resolveResult;
+ }
+ if (backend === resolveResult) {
+ availableBackendNames.add(backendName);
+ }
+ }
+ }
+ if (!backend) {
+ throw new Error(`no available backend found. ERR: ${errors.map((e) => `[${e.name}] ${e.err}`).join(", ")}`);
+ }
+ for (const { name, err } of errors) {
+ if (backendHints.includes(name)) {
+ console.warn(`removing requested execution provider "${name}" from session options because it is not available: ${err}`);
+ }
+ }
+ const filteredEps = eps.filter((i) => availableBackendNames.has(typeof i === "string" ? i : i.name));
+ return [
+ backend,
+ new Proxy(options, {
+ get: (target, prop) => {
+ if (prop === "executionProviders") {
+ return filteredEps;
+ }
+ return Reflect.get(target, prop);
+ }
+ })
+ ];
+};
+
+// node_modules/onnxruntime-common/dist/esm/version.js
+var version = "1.21.0";
+
+// node_modules/onnxruntime-common/dist/esm/env-impl.js
+var logLevelValue = "warning";
+var env = {
+ wasm: {},
+ webgl: {},
+ webgpu: {},
+ versions: { common: version },
+ set logLevel(value) {
+ if (value === void 0) {
+ return;
+ }
+ if (typeof value !== "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(value) === -1) {
+ throw new Error(`Unsupported logging level: ${value}`);
+ }
+ logLevelValue = value;
+ },
+ get logLevel() {
+ return logLevelValue;
+ }
+};
+Object.defineProperty(env, "logLevel", { enumerable: true });
+
+// node_modules/onnxruntime-common/dist/esm/env.js
+var env2 = env;
+
+// node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js
+var tensorToDataURL = (tensor, options) => {
+ const canvas = typeof document !== "undefined" ? document.createElement("canvas") : new OffscreenCanvas(1, 1);
+ canvas.width = tensor.dims[3];
+ canvas.height = tensor.dims[2];
+ const pixels2DContext = canvas.getContext("2d");
+ if (pixels2DContext != null) {
+ let width;
+ let height;
+ if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") {
+ width = tensor.dims[2];
+ height = tensor.dims[3];
+ } else {
+ width = tensor.dims[3];
+ height = tensor.dims[2];
+ }
+ const inputformat = options?.format !== void 0 ? options.format : "RGB";
+ const norm = options?.norm;
+ let normMean;
+ let normBias;
+ if (norm === void 0 || norm.mean === void 0) {
+ normMean = [255, 255, 255, 255];
+ } else {
+ if (typeof norm.mean === "number") {
+ normMean = [norm.mean, norm.mean, norm.mean, norm.mean];
+ } else {
+ normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];
+ if (norm.mean[3] !== void 0) {
+ normMean[3] = norm.mean[3];
+ }
+ }
+ }
+ if (norm === void 0 || norm.bias === void 0) {
+ normBias = [0, 0, 0, 0];
+ } else {
+ if (typeof norm.bias === "number") {
+ normBias = [norm.bias, norm.bias, norm.bias, norm.bias];
+ } else {
+ normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];
+ if (norm.bias[3] !== void 0) {
+ normBias[3] = norm.bias[3];
+ }
+ }
+ }
+ const stride = height * width;
+ let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;
+ if (inputformat === "RGBA") {
+ rTensorPointer = 0;
+ gTensorPointer = stride;
+ bTensorPointer = stride * 2;
+ aTensorPointer = stride * 3;
+ } else if (inputformat === "RGB") {
+ rTensorPointer = 0;
+ gTensorPointer = stride;
+ bTensorPointer = stride * 2;
+ } else if (inputformat === "RBG") {
+ rTensorPointer = 0;
+ bTensorPointer = stride;
+ gTensorPointer = stride * 2;
+ }
+ for (let i = 0; i < height; i++) {
+ for (let j = 0; j < width; j++) {
+ const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0];
+ const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1];
+ const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2];
+ const A = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3];
+ pixels2DContext.fillStyle = "rgba(" + R + "," + G + "," + B + "," + A + ")";
+ pixels2DContext.fillRect(j, i, 1, 1);
+ }
+ }
+ if ("toDataURL" in canvas) {
+ return canvas.toDataURL();
+ } else {
+ throw new Error("toDataURL is not supported");
+ }
+ } else {
+ throw new Error("Can not access image data");
+ }
+};
+var tensorToImageData = (tensor, options) => {
+ const pixels2DContext = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d");
+ let image;
+ if (pixels2DContext != null) {
+ let width;
+ let height;
+ let channels;
+ if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") {
+ width = tensor.dims[2];
+ height = tensor.dims[1];
+ channels = tensor.dims[3];
+ } else {
+ width = tensor.dims[3];
+ height = tensor.dims[2];
+ channels = tensor.dims[1];
+ }
+ const inputformat = options !== void 0 ? options.format !== void 0 ? options.format : "RGB" : "RGB";
+ const norm = options?.norm;
+ let normMean;
+ let normBias;
+ if (norm === void 0 || norm.mean === void 0) {
+ normMean = [255, 255, 255, 255];
+ } else {
+ if (typeof norm.mean === "number") {
+ normMean = [norm.mean, norm.mean, norm.mean, norm.mean];
+ } else {
+ normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];
+ if (norm.mean[3] !== void 0) {
+ normMean[3] = norm.mean[3];
+ }
+ }
+ }
+ if (norm === void 0 || norm.bias === void 0) {
+ normBias = [0, 0, 0, 0];
+ } else {
+ if (typeof norm.bias === "number") {
+ normBias = [norm.bias, norm.bias, norm.bias, norm.bias];
+ } else {
+ normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];
+ if (norm.bias[3] !== void 0) {
+ normBias[3] = norm.bias[3];
+ }
+ }
+ }
+ const stride = height * width;
+ if (options !== void 0) {
+ if (options.format !== void 0 && channels === 4 && options.format !== "RGBA" || channels === 3 && options.format !== "RGB" && options.format !== "BGR") {
+ throw new Error("Tensor format doesn't match input tensor dims");
+ }
+ }
+ const step = 4;
+ let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
+ let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;
+ if (inputformat === "RGBA") {
+ rTensorPointer = 0;
+ gTensorPointer = stride;
+ bTensorPointer = stride * 2;
+ aTensorPointer = stride * 3;
+ } else if (inputformat === "RGB") {
+ rTensorPointer = 0;
+ gTensorPointer = stride;
+ bTensorPointer = stride * 2;
+ } else if (inputformat === "RBG") {
+ rTensorPointer = 0;
+ bTensorPointer = stride;
+ gTensorPointer = stride * 2;
+ }
+ image = pixels2DContext.createImageData(width, height);
+ for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {
+ image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0];
+ image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1];
+ image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2];
+ image.data[aImagePointer] = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3];
+ }
+ } else {
+ throw new Error("Can not access image data");
+ }
+ return image;
+};
+
+// node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js
+var bufferToTensor = (buffer, options) => {
+ if (buffer === void 0) {
+ throw new Error("Image buffer must be defined");
+ }
+ if (options.height === void 0 || options.width === void 0) {
+ throw new Error("Image height and width must be defined");
+ }
+ if (options.tensorLayout === "NHWC") {
+ throw new Error("NHWC Tensor layout is not supported yet");
+ }
+ const { height, width } = options;
+ const norm = options.norm ?? { mean: 255, bias: 0 };
+ let normMean;
+ let normBias;
+ if (typeof norm.mean === "number") {
+ normMean = [norm.mean, norm.mean, norm.mean, norm.mean];
+ } else {
+ normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255];
+ }
+ if (typeof norm.bias === "number") {
+ normBias = [norm.bias, norm.bias, norm.bias, norm.bias];
+ } else {
+ normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0];
+ }
+ const inputformat = options.format !== void 0 ? options.format : "RGBA";
+ const outputformat = options.tensorFormat !== void 0 ? options.tensorFormat !== void 0 ? options.tensorFormat : "RGB" : "RGB";
+ const stride = height * width;
+ const float32Data = outputformat === "RGBA" ? new Float32Array(stride * 4) : new Float32Array(stride * 3);
+ let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
+ let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;
+ if (inputformat === "RGB") {
+ step = 3;
+ rImagePointer = 0;
+ gImagePointer = 1;
+ bImagePointer = 2;
+ aImagePointer = -1;
+ }
+ if (outputformat === "RGBA") {
+ aTensorPointer = stride * 3;
+ } else if (outputformat === "RBG") {
+ rTensorPointer = 0;
+ bTensorPointer = stride;
+ gTensorPointer = stride * 2;
+ } else if (outputformat === "BGR") {
+ bTensorPointer = 0;
+ gTensorPointer = stride;
+ rTensorPointer = stride * 2;
+ }
+ for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {
+ float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];
+ float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];
+ float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];
+ if (aTensorPointer !== -1 && aImagePointer !== -1) {
+ float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];
+ }
+ }
+ const outputTensor = outputformat === "RGBA" ? new Tensor("float32", float32Data, [1, 4, height, width]) : new Tensor("float32", float32Data, [1, 3, height, width]);
+ return outputTensor;
+};
+var tensorFromImage = async (image, options) => {
+ const isHTMLImageEle = typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement;
+ const isImageDataEle = typeof ImageData !== "undefined" && image instanceof ImageData;
+ const isImageBitmap = typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap;
+ const isString = typeof image === "string";
+ let data;
+ let bufferToTensorOptions = options ?? {};
+ const createCanvas = () => {
+ if (typeof document !== "undefined") {
+ return document.createElement("canvas");
+ } else if (typeof OffscreenCanvas !== "undefined") {
+ return new OffscreenCanvas(1, 1);
+ } else {
+ throw new Error("Canvas is not supported");
+ }
+ };
+ const createCanvasContext = (canvas) => {
+ if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
+ return canvas.getContext("2d");
+ } else if (canvas instanceof OffscreenCanvas) {
+ return canvas.getContext("2d");
+ } else {
+ return null;
+ }
+ };
+ if (isHTMLImageEle) {
+ const canvas = createCanvas();
+ canvas.width = image.width;
+ canvas.height = image.height;
+ const pixels2DContext = createCanvasContext(canvas);
+ if (pixels2DContext != null) {
+ let height = image.height;
+ let width = image.width;
+ if (options !== void 0 && options.resizedHeight !== void 0 && options.resizedWidth !== void 0) {
+ height = options.resizedHeight;
+ width = options.resizedWidth;
+ }
+ if (options !== void 0) {
+ bufferToTensorOptions = options;
+ if (options.tensorFormat !== void 0) {
+ throw new Error("Image input config format must be RGBA for HTMLImageElement");
+ } else {
+ bufferToTensorOptions.tensorFormat = "RGBA";
+ }
+ bufferToTensorOptions.height = height;
+ bufferToTensorOptions.width = width;
+ } else {
+ bufferToTensorOptions.tensorFormat = "RGBA";
+ bufferToTensorOptions.height = height;
+ bufferToTensorOptions.width = width;
+ }
+ pixels2DContext.drawImage(image, 0, 0);
+ data = pixels2DContext.getImageData(0, 0, width, height).data;
+ } else {
+ throw new Error("Can not access image data");
+ }
+ } else if (isImageDataEle) {
+ let height;
+ let width;
+ if (options !== void 0 && options.resizedWidth !== void 0 && options.resizedHeight !== void 0) {
+ height = options.resizedHeight;
+ width = options.resizedWidth;
+ } else {
+ height = image.height;
+ width = image.width;
+ }
+ if (options !== void 0) {
+ bufferToTensorOptions = options;
+ }
+ bufferToTensorOptions.format = "RGBA";
+ bufferToTensorOptions.height = height;
+ bufferToTensorOptions.width = width;
+ if (options !== void 0) {
+ const tempCanvas = createCanvas();
+ tempCanvas.width = width;
+ tempCanvas.height = height;
+ const pixels2DContext = createCanvasContext(tempCanvas);
+ if (pixels2DContext != null) {
+ pixels2DContext.putImageData(image, 0, 0);
+ data = pixels2DContext.getImageData(0, 0, width, height).data;
+ } else {
+ throw new Error("Can not access image data");
+ }
+ } else {
+ data = image.data;
+ }
+ } else if (isImageBitmap) {
+ if (options === void 0) {
+ throw new Error("Please provide image config with format for Imagebitmap");
+ }
+ const canvas = createCanvas();
+ canvas.width = image.width;
+ canvas.height = image.height;
+ const pixels2DContext = createCanvasContext(canvas);
+ if (pixels2DContext != null) {
+ const height = image.height;
+ const width = image.width;
+ pixels2DContext.drawImage(image, 0, 0, width, height);
+ data = pixels2DContext.getImageData(0, 0, width, height).data;
+ bufferToTensorOptions.height = height;
+ bufferToTensorOptions.width = width;
+ return bufferToTensor(data, bufferToTensorOptions);
+ } else {
+ throw new Error("Can not access image data");
+ }
+ } else if (isString) {
+ return new Promise((resolve, reject) => {
+ const canvas = createCanvas();
+ const context = createCanvasContext(canvas);
+ if (!image || !context) {
+ return reject();
+ }
+ const newImage = new Image();
+ newImage.crossOrigin = "Anonymous";
+ newImage.src = image;
+ newImage.onload = () => {
+ canvas.width = newImage.width;
+ canvas.height = newImage.height;
+ context.drawImage(newImage, 0, 0, canvas.width, canvas.height);
+ const img = context.getImageData(0, 0, canvas.width, canvas.height);
+ bufferToTensorOptions.height = canvas.height;
+ bufferToTensorOptions.width = canvas.width;
+ resolve(bufferToTensor(img.data, bufferToTensorOptions));
+ };
+ });
+ } else {
+ throw new Error("Input data provided is not supported - aborted tensor creation");
+ }
+ if (data !== void 0) {
+ return bufferToTensor(data, bufferToTensorOptions);
+ } else {
+ throw new Error("Input data provided is not supported - aborted tensor creation");
+ }
+};
+var tensorFromTexture = (texture, options) => {
+ const { width, height, download, dispose } = options;
+ const dims = [1, height, width, 4];
+ return new Tensor({ location: "texture", type: "float32", texture, dims, download, dispose });
+};
+var tensorFromGpuBuffer = (gpuBuffer, options) => {
+ const { dataType, dims, download, dispose } = options;
+ return new Tensor({ location: "gpu-buffer", type: dataType ?? "float32", gpuBuffer, dims, download, dispose });
+};
+var tensorFromMLTensor = (mlTensor, options) => {
+ const { dataType, dims, download, dispose } = options;
+ return new Tensor({ location: "ml-tensor", type: dataType ?? "float32", mlTensor, dims, download, dispose });
+};
+var tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: "cpu-pinned", type, data: buffer, dims: dims ?? [buffer.length] });
+
+// node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js
+var NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = /* @__PURE__ */ new Map([
+ ["float32", Float32Array],
+ ["uint8", Uint8Array],
+ ["int8", Int8Array],
+ ["uint16", Uint16Array],
+ ["int16", Int16Array],
+ ["int32", Int32Array],
+ ["bool", Uint8Array],
+ ["float64", Float64Array],
+ ["uint32", Uint32Array],
+ ["int4", Uint8Array],
+ ["uint4", Uint8Array]
+]);
+var NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = /* @__PURE__ */ new Map([
+ [Float32Array, "float32"],
+ [Uint8Array, "uint8"],
+ [Int8Array, "int8"],
+ [Uint16Array, "uint16"],
+ [Int16Array, "int16"],
+ [Int32Array, "int32"],
+ [Float64Array, "float64"],
+ [Uint32Array, "uint32"]
+]);
+var isTypedArrayChecked = false;
+var checkTypedArray = () => {
+ if (!isTypedArrayChecked) {
+ isTypedArrayChecked = true;
+ const isBigInt64ArrayAvailable = typeof BigInt64Array !== "undefined" && BigInt64Array.from;
+ const isBigUint64ArrayAvailable = typeof BigUint64Array !== "undefined" && BigUint64Array.from;
+ const Float16Array2 = globalThis.Float16Array;
+ const isFloat16ArrayAvailable = typeof Float16Array2 !== "undefined" && Float16Array2.from;
+ if (isBigInt64ArrayAvailable) {
+ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64", BigInt64Array);
+ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, "int64");
+ }
+ if (isBigUint64ArrayAvailable) {
+ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64", BigUint64Array);
+ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, "uint64");
+ }
+ if (isFloat16ArrayAvailable) {
+ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Float16Array2);
+ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array2, "float16");
+ } else {
+ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Uint16Array);
+ }
+ }
+};
+
+// node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js
+var calculateSize = (dims) => {
+ let size = 1;
+ for (let i = 0; i < dims.length; i++) {
+ const dim = dims[i];
+ if (typeof dim !== "number" || !Number.isSafeInteger(dim)) {
+ throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);
+ }
+ if (dim < 0) {
+ throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);
+ }
+ size *= dim;
+ }
+ return size;
+};
+var tensorReshape = (tensor, dims) => {
+ switch (tensor.location) {
+ case "cpu":
+ return new Tensor(tensor.type, tensor.data, dims);
+ case "cpu-pinned":
+ return new Tensor({
+ location: "cpu-pinned",
+ data: tensor.data,
+ type: tensor.type,
+ dims
+ });
+ case "texture":
+ return new Tensor({
+ location: "texture",
+ texture: tensor.texture,
+ type: tensor.type,
+ dims
+ });
+ case "gpu-buffer":
+ return new Tensor({
+ location: "gpu-buffer",
+ gpuBuffer: tensor.gpuBuffer,
+ type: tensor.type,
+ dims
+ });
+ case "ml-tensor":
+ return new Tensor({
+ location: "ml-tensor",
+ mlTensor: tensor.mlTensor,
+ type: tensor.type,
+ dims
+ });
+ default:
+ throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);
+ }
+};
+
+// node_modules/onnxruntime-common/dist/esm/tensor-impl.js
+var Tensor = class {
+ /**
+ * implementation.
+ */
+ constructor(arg0, arg1, arg2) {
+ checkTypedArray();
+ let type;
+ let dims;
+ if (typeof arg0 === "object" && "location" in arg0) {
+ this.dataLocation = arg0.location;
+ type = arg0.type;
+ dims = arg0.dims;
+ switch (arg0.location) {
+ case "cpu-pinned": {
+ const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);
+ if (!expectedTypedArrayConstructor) {
+ throw new TypeError(`unsupported type "${type}" to create tensor from pinned buffer`);
+ }
+ if (!(arg0.data instanceof expectedTypedArrayConstructor)) {
+ throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);
+ }
+ this.cpuData = arg0.data;
+ break;
+ }
+ case "texture": {
+ if (type !== "float32") {
+ throw new TypeError(`unsupported type "${type}" to create tensor from texture`);
+ }
+ this.gpuTextureData = arg0.texture;
+ this.downloader = arg0.download;
+ this.disposer = arg0.dispose;
+ break;
+ }
+ case "gpu-buffer": {
+ if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint8" && type !== "bool" && type !== "uint4" && type !== "int4") {
+ throw new TypeError(`unsupported type "${type}" to create tensor from gpu buffer`);
+ }
+ this.gpuBufferData = arg0.gpuBuffer;
+ this.downloader = arg0.download;
+ this.disposer = arg0.dispose;
+ break;
+ }
+ case "ml-tensor": {
+ if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint64" && type !== "int8" && type !== "uint8" && type !== "bool" && type !== "uint4" && type !== "int4") {
+ throw new TypeError(`unsupported type "${type}" to create tensor from MLTensor`);
+ }
+ this.mlTensorData = arg0.mlTensor;
+ this.downloader = arg0.download;
+ this.disposer = arg0.dispose;
+ break;
+ }
+ default:
+ throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);
+ }
+ } else {
+ let data;
+ let maybeDims;
+ if (typeof arg0 === "string") {
+ type = arg0;
+ maybeDims = arg2;
+ if (arg0 === "string") {
+ if (!Array.isArray(arg1)) {
+ throw new TypeError("A string tensor's data must be a string array.");
+ }
+ data = arg1;
+ } else {
+ const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);
+ if (typedArrayConstructor === void 0) {
+ throw new TypeError(`Unsupported tensor type: ${arg0}.`);
+ }
+ if (Array.isArray(arg1)) {
+ if (arg0 === "float16" && typedArrayConstructor === Uint16Array || arg0 === "uint4" || arg0 === "int4") {
+ throw new TypeError(`Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} as data.`);
+ } else if (arg0 === "uint64" || arg0 === "int64") {
+ data = typedArrayConstructor.from(arg1, BigInt);
+ } else {
+ data = typedArrayConstructor.from(arg1);
+ }
+ } else if (arg1 instanceof typedArrayConstructor) {
+ data = arg1;
+ } else if (arg1 instanceof Uint8ClampedArray) {
+ if (arg0 === "uint8") {
+ data = Uint8Array.from(arg1);
+ } else {
+ throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);
+ }
+ } else if (arg0 === "float16" && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) {
+ data = new globalThis.Float16Array(arg1.buffer, arg1.byteOffset, arg1.length);
+ } else {
+ throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);
+ }
+ }
+ } else {
+ maybeDims = arg1;
+ if (Array.isArray(arg0)) {
+ if (arg0.length === 0) {
+ throw new TypeError("Tensor type cannot be inferred from an empty array.");
+ }
+ const firstElementType = typeof arg0[0];
+ if (firstElementType === "string") {
+ type = "string";
+ data = arg0;
+ } else if (firstElementType === "boolean") {
+ type = "bool";
+ data = Uint8Array.from(arg0);
+ } else {
+ throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);
+ }
+ } else if (arg0 instanceof Uint8ClampedArray) {
+ type = "uint8";
+ data = Uint8Array.from(arg0);
+ } else {
+ const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);
+ if (mappedType === void 0) {
+ throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);
+ }
+ type = mappedType;
+ data = arg0;
+ }
+ }
+ if (maybeDims === void 0) {
+ maybeDims = [data.length];
+ } else if (!Array.isArray(maybeDims)) {
+ throw new TypeError("A tensor's dims must be a number array");
+ }
+ dims = maybeDims;
+ this.cpuData = data;
+ this.dataLocation = "cpu";
+ }
+ const size = calculateSize(dims);
+ if (this.cpuData && size !== this.cpuData.length) {
+ if ((type === "uint4" || type === "int4") && Math.ceil(size / 2) === this.cpuData.length) {
+ } else {
+ throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);
+ }
+ }
+ this.type = type;
+ this.dims = dims;
+ this.size = size;
+ }
+ // #endregion
+ // #region factory
+ static async fromImage(image, options) {
+ return tensorFromImage(image, options);
+ }
+ static fromTexture(texture, options) {
+ return tensorFromTexture(texture, options);
+ }
+ static fromGpuBuffer(gpuBuffer, options) {
+ return tensorFromGpuBuffer(gpuBuffer, options);
+ }
+ static fromMLTensor(mlTensor, options) {
+ return tensorFromMLTensor(mlTensor, options);
+ }
+ static fromPinnedBuffer(type, buffer, dims) {
+ return tensorFromPinnedBuffer(type, buffer, dims);
+ }
+ // #endregion
+ // #region conversions
+ toDataURL(options) {
+ return tensorToDataURL(this, options);
+ }
+ toImageData(options) {
+ return tensorToImageData(this, options);
+ }
+ // #endregion
+ // #region properties
+ get data() {
+ this.ensureValid();
+ if (!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() {
+ this.ensureValid();
+ if (!this.gpuTextureData) {
+ throw new Error("The data is not stored as a WebGL texture.");
+ }
+ return this.gpuTextureData;
+ }
+ get gpuBuffer() {
+ this.ensureValid();
+ if (!this.gpuBufferData) {
+ throw new Error("The data is not stored as a WebGPU buffer.");
+ }
+ return this.gpuBufferData;
+ }
+ get mlTensor() {
+ this.ensureValid();
+ if (!this.mlTensorData) {
+ throw new Error("The data is not stored as a WebNN MLTensor.");
+ }
+ return this.mlTensorData;
+ }
+ // #endregion
+ // #region methods
+ async getData(releaseData) {
+ this.ensureValid();
+ switch (this.dataLocation) {
+ case "cpu":
+ case "cpu-pinned":
+ return this.data;
+ case "texture":
+ case "gpu-buffer":
+ case "ml-tensor": {
+ if (!this.downloader) {
+ throw new Error("The current tensor is not created with a specified data downloader.");
+ }
+ if (this.isDownloading) {
+ throw new Error("The current tensor is being downloaded.");
+ }
+ try {
+ this.isDownloading = true;
+ const data = await this.downloader();
+ this.downloader = void 0;
+ this.dataLocation = "cpu";
+ this.cpuData = data;
+ if (releaseData && this.disposer) {
+ this.disposer();
+ this.disposer = void 0;
+ }
+ return data;
+ } finally {
+ this.isDownloading = false;
+ }
+ }
+ default:
+ throw new Error(`cannot get data from location: ${this.dataLocation}`);
+ }
+ }
+ dispose() {
+ if (this.isDownloading) {
+ throw new Error("The current tensor is being downloaded.");
+ }
+ if (this.disposer) {
+ this.disposer();
+ this.disposer = void 0;
+ }
+ this.cpuData = void 0;
+ this.gpuTextureData = void 0;
+ this.gpuBufferData = void 0;
+ this.mlTensorData = void 0;
+ this.downloader = void 0;
+ this.isDownloading = void 0;
+ this.dataLocation = "none";
+ }
+ // #endregion
+ // #region tensor utilities
+ ensureValid() {
+ if (this.dataLocation === "none") {
+ throw new Error("The tensor is disposed.");
+ }
+ }
+ reshape(dims) {
+ this.ensureValid();
+ if (this.downloader || this.disposer) {
+ throw new Error("Cannot reshape a tensor that owns GPU resource.");
+ }
+ return tensorReshape(this, dims);
+ }
+};
+
+// node_modules/onnxruntime-common/dist/esm/tensor.js
+var Tensor2 = Tensor;
+
+// node_modules/onnxruntime-common/dist/esm/trace.js
+var TRACE = (deviceType, label) => {
+ if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
+ return;
+ }
+ console.timeStamp(`${deviceType}::ORT::${label}`);
+};
+var TRACE_FUNC = (msg, extraMsg) => {
+ const stack = new Error().stack?.split(/\r\n|\r|\n/g) || [];
+ let hasTraceFunc = false;
+ for (let i = 0; i < stack.length; i++) {
+ if (hasTraceFunc && !stack[i].includes("TRACE_FUNC")) {
+ let label = `FUNC_${msg}::${stack[i].trim().split(" ")[1]}`;
+ if (extraMsg) {
+ label += `::${extraMsg}`;
+ }
+ TRACE("CPU", label);
+ return;
+ }
+ if (stack[i].includes("TRACE_FUNC")) {
+ hasTraceFunc = true;
+ }
+ }
+};
+var TRACE_FUNC_BEGIN = (extraMsg) => {
+ if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
+ return;
+ }
+ TRACE_FUNC("BEGIN", extraMsg);
+};
+var TRACE_FUNC_END = (extraMsg) => {
+ if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
+ return;
+ }
+ TRACE_FUNC("END", extraMsg);
+};
+
+// node_modules/onnxruntime-common/dist/esm/inference-session-impl.js
+var InferenceSession = class _InferenceSession {
+ constructor(handler) {
+ this.handler = handler;
+ }
+ async run(feeds, arg1, arg2) {
+ TRACE_FUNC_BEGIN();
+ const fetches = {};
+ let options = {};
+ if (typeof feeds !== "object" || feeds === null || feeds instanceof Tensor2 || Array.isArray(feeds)) {
+ throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");
+ }
+ let isFetchesEmpty = true;
+ if (typeof arg1 === "object") {
+ if (arg1 === null) {
+ throw new TypeError("Unexpected argument[1]: cannot be null.");
+ }
+ if (arg1 instanceof Tensor2) {
+ throw new TypeError("'fetches' cannot be a Tensor");
+ }
+ if (Array.isArray(arg1)) {
+ if (arg1.length === 0) {
+ throw new TypeError("'fetches' cannot be an empty array.");
+ }
+ isFetchesEmpty = false;
+ for (const name of arg1) {
+ if (typeof name !== "string") {
+ throw new TypeError("'fetches' must be a string array or an object.");
+ }
+ if (this.outputNames.indexOf(name) === -1) {
+ throw new RangeError(`'fetches' contains invalid output name: ${name}.`);
+ }
+ fetches[name] = null;
+ }
+ if (typeof arg2 === "object" && arg2 !== null) {
+ options = arg2;
+ } else if (typeof arg2 !== "undefined") {
+ throw new TypeError("'options' must be an object.");
+ }
+ } else {
+ let isFetches = false;
+ const arg1Keys = Object.getOwnPropertyNames(arg1);
+ for (const name of this.outputNames) {
+ if (arg1Keys.indexOf(name) !== -1) {
+ const v = arg1[name];
+ if (v === null || v instanceof Tensor2) {
+ isFetches = true;
+ isFetchesEmpty = false;
+ fetches[name] = v;
+ }
+ }
+ }
+ if (isFetches) {
+ if (typeof arg2 === "object" && arg2 !== null) {
+ options = arg2;
+ } else if (typeof arg2 !== "undefined") {
+ throw new TypeError("'options' must be an object.");
+ }
+ } else {
+ options = arg1;
+ }
+ }
+ } else if (typeof arg1 !== "undefined") {
+ throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");
+ }
+ for (const name of this.inputNames) {
+ if (typeof feeds[name] === "undefined") {
+ throw new Error(`input '${name}' is missing in 'feeds'.`);
+ }
+ }
+ if (isFetchesEmpty) {
+ for (const name of this.outputNames) {
+ fetches[name] = null;
+ }
+ }
+ const results = await this.handler.run(feeds, fetches, options);
+ const returnValue = {};
+ for (const key in results) {
+ if (Object.hasOwnProperty.call(results, key)) {
+ const result = results[key];
+ if (result instanceof Tensor2) {
+ returnValue[key] = result;
+ } else {
+ returnValue[key] = new Tensor2(result.type, result.data, result.dims);
+ }
+ }
+ }
+ TRACE_FUNC_END();
+ return returnValue;
+ }
+ async release() {
+ return this.handler.dispose();
+ }
+ static async create(arg0, arg1, arg2, arg3) {
+ TRACE_FUNC_BEGIN();
+ let filePathOrUint8Array;
+ let options = {};
+ if (typeof arg0 === "string") {
+ filePathOrUint8Array = arg0;
+ if (typeof arg1 === "object" && arg1 !== null) {
+ options = arg1;
+ } else if (typeof arg1 !== "undefined") {
+ throw new TypeError("'options' must be an object.");
+ }
+ } else if (arg0 instanceof Uint8Array) {
+ filePathOrUint8Array = arg0;
+ if (typeof arg1 === "object" && arg1 !== null) {
+ options = arg1;
+ } else if (typeof arg1 !== "undefined") {
+ throw new TypeError("'options' must be an object.");
+ }
+ } else if (arg0 instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && arg0 instanceof SharedArrayBuffer) {
+ const buffer = arg0;
+ let byteOffset = 0;
+ let byteLength = arg0.byteLength;
+ if (typeof arg1 === "object" && arg1 !== null) {
+ options = arg1;
+ } else if (typeof arg1 === "number") {
+ byteOffset = arg1;
+ if (!Number.isSafeInteger(byteOffset)) {
+ throw new RangeError("'byteOffset' must be an integer.");
+ }
+ if (byteOffset < 0 || byteOffset >= buffer.byteLength) {
+ throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);
+ }
+ byteLength = arg0.byteLength - byteOffset;
+ if (typeof arg2 === "number") {
+ byteLength = arg2;
+ if (!Number.isSafeInteger(byteLength)) {
+ throw new RangeError("'byteLength' must be an integer.");
+ }
+ if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {
+ throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);
+ }
+ if (typeof arg3 === "object" && arg3 !== null) {
+ options = arg3;
+ } else if (typeof arg3 !== "undefined") {
+ throw new TypeError("'options' must be an object.");
+ }
+ } else if (typeof arg2 !== "undefined") {
+ throw new TypeError("'byteLength' must be a number.");
+ }
+ } else if (typeof arg1 !== "undefined") {
+ throw new TypeError("'options' must be an object.");
+ }
+ filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);
+ } else {
+ throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");
+ }
+ const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);
+ const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);
+ TRACE_FUNC_END();
+ return new _InferenceSession(handler);
+ }
+ 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
+var InferenceSession2 = InferenceSession;
+
+// node_modules/onnxruntime-web/dist/ort.bundle.min.mjs
+var ort_bundle_min_exports = {};
+__export(ort_bundle_min_exports, {
+ InferenceSession: () => Gp,
+ TRACE: () => gr,
+ TRACE_FUNC_BEGIN: () => Re,
+ TRACE_FUNC_END: () => Oe,
+ Tensor: () => Ge,
+ default: () => IS,
+ env: () => ge,
+ registerBackend: () => $t
+});
+var zn = Object.defineProperty;
+var Up = Object.getOwnPropertyDescriptor;
+var Np = Object.getOwnPropertyNames;
+var Vp = Object.prototype.hasOwnProperty;
+var On = ((e) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(e, { get: (t, r) => (typeof __require < "u" ? __require : t)[r] }) : e)(function(e) {
+ if (typeof __require < "u") return __require.apply(this, arguments);
+ throw Error('Dynamic require of "' + e + '" is not supported');
+});
+var U = (e, t) => () => (e && (t = e(e = 0)), t);
+var Dt = (e, t) => {
+ for (var r in t) zn(e, r, { get: t[r], enumerable: true });
+};
+var Wp = (e, t, r, n) => {
+ if (t && typeof t == "object" || typeof t == "function") for (let o of Np(t)) !Vp.call(e, o) && o !== r && zn(e, o, { get: () => t[o], enumerable: !(n = Up(t, o)) || n.enumerable });
+ return e;
+};
+var Ft = (e) => Wp(zn({}, "__esModule", { value: true }), e);
+var fr;
+var vt;
+var $t;
+var Lp;
+var Fi;
+var Bn = U(() => {
+ "use strict";
+ fr = /* @__PURE__ */ new Map(), vt = [], $t = (e, t, r) => {
+ if (t && typeof t.init == "function" && typeof t.createInferenceSessionHandler == "function") {
+ let n = fr.get(e);
+ if (n === void 0) fr.set(e, { backend: t, priority: r });
+ else {
+ if (n.priority > r) return;
+ if (n.priority === r && n.backend !== t) throw new Error(`cannot register backend "${e}" using priority ${r}`);
+ }
+ if (r >= 0) {
+ let o = vt.indexOf(e);
+ o !== -1 && vt.splice(o, 1);
+ for (let i = 0; i < vt.length; i++) if (fr.get(vt[i]).priority <= r) {
+ vt.splice(i, 0, e);
+ return;
+ }
+ vt.push(e);
+ }
+ return;
+ }
+ throw new TypeError("not a valid backend");
+ }, Lp = async (e) => {
+ let t = fr.get(e);
+ if (!t) return "backend not found.";
+ if (t.initialized) return t.backend;
+ if (t.aborted) return t.error;
+ {
+ let r = !!t.initPromise;
+ try {
+ return r || (t.initPromise = t.backend.init(e)), await t.initPromise, t.initialized = true, t.backend;
+ } catch (n) {
+ return r || (t.error = `${n}`, t.aborted = true), t.error;
+ } finally {
+ delete t.initPromise;
+ }
+ }
+ }, Fi = async (e) => {
+ let t = e.executionProviders || [], r = t.map((d) => typeof d == "string" ? d : d.name), n = r.length === 0 ? vt : r, o, i = [], a = /* @__PURE__ */ new Set();
+ for (let d of n) {
+ let c = await Lp(d);
+ typeof c == "string" ? i.push({ name: d, err: c }) : (o || (o = c), o === c && a.add(d));
+ }
+ if (!o) throw new Error(`no available backend found. ERR: ${i.map((d) => `[${d.name}] ${d.err}`).join(", ")}`);
+ for (let { name: d, err: c } of i) r.includes(d) && console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${c}`);
+ let u = t.filter((d) => a.has(typeof d == "string" ? d : d.name));
+ return [o, new Proxy(e, { get: (d, c) => c === "executionProviders" ? u : Reflect.get(d, c) })];
+ };
+});
+var qi = U(() => {
+ "use strict";
+ Bn();
+});
+var ji;
+var Ki = U(() => {
+ "use strict";
+ ji = "1.22.0-dev.20250409-89f8206ba4";
+});
+var Zi;
+var Me;
+var Dn = U(() => {
+ "use strict";
+ Ki();
+ Zi = "warning", Me = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: ji }, 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}`);
+ Zi = e;
+ }
+ }, get logLevel() {
+ return Zi;
+ } };
+ Object.defineProperty(Me, "logLevel", { enumerable: true });
+});
+var ge;
+var Qi = U(() => {
+ "use strict";
+ Dn();
+ ge = Me;
+});
+var Yi;
+var Xi;
+var Ji = U(() => {
+ "use strict";
+ Yi = (e, t) => {
+ let r = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1);
+ r.width = e.dims[3], r.height = e.dims[2];
+ let n = r.getContext("2d");
+ if (n != null) {
+ let o, i;
+ t?.tensorLayout !== void 0 && t.tensorLayout === "NHWC" ? (o = e.dims[2], i = e.dims[3]) : (o = e.dims[3], i = e.dims[2]);
+ let a = t?.format !== void 0 ? t.format : "RGB", u = t?.norm, d, c;
+ u === void 0 || u.mean === void 0 ? d = [255, 255, 255, 255] : typeof u.mean == "number" ? d = [u.mean, u.mean, u.mean, u.mean] : (d = [u.mean[0], u.mean[1], u.mean[2], 0], u.mean[3] !== void 0 && (d[3] = u.mean[3])), u === void 0 || u.bias === void 0 ? c = [0, 0, 0, 0] : typeof u.bias == "number" ? c = [u.bias, u.bias, u.bias, u.bias] : (c = [u.bias[0], u.bias[1], u.bias[2], 0], u.bias[3] !== void 0 && (c[3] = u.bias[3]));
+ let p = i * o, m = 0, f = p, b = p * 2, g = -1;
+ a === "RGBA" ? (m = 0, f = p, b = p * 2, g = p * 3) : a === "RGB" ? (m = 0, f = p, b = p * 2) : a === "RBG" && (m = 0, b = p, f = p * 2);
+ for (let _ = 0; _ < i; _++) for (let S = 0; S < o; S++) {
+ let $ = (e.data[m++] - c[0]) * d[0], v = (e.data[f++] - c[1]) * d[1], x = (e.data[b++] - c[2]) * d[2], T = g === -1 ? 255 : (e.data[g++] - c[3]) * d[3];
+ n.fillStyle = "rgba(" + $ + "," + v + "," + x + "," + T + ")", n.fillRect(S, _, 1, 1);
+ }
+ if ("toDataURL" in r) return r.toDataURL();
+ throw new Error("toDataURL is not supported");
+ } else throw new Error("Can not access image data");
+ }, Xi = (e, t) => {
+ let r = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"), n;
+ if (r != null) {
+ let o, i, a;
+ t?.tensorLayout !== void 0 && t.tensorLayout === "NHWC" ? (o = e.dims[2], i = e.dims[1], a = e.dims[3]) : (o = e.dims[3], i = e.dims[2], a = e.dims[1]);
+ let u = t !== void 0 && t.format !== void 0 ? t.format : "RGB", d = t?.norm, c, p;
+ d === void 0 || d.mean === void 0 ? c = [255, 255, 255, 255] : typeof d.mean == "number" ? c = [d.mean, d.mean, d.mean, d.mean] : (c = [d.mean[0], d.mean[1], d.mean[2], 255], d.mean[3] !== void 0 && (c[3] = d.mean[3])), d === void 0 || d.bias === void 0 ? p = [0, 0, 0, 0] : typeof d.bias == "number" ? p = [d.bias, d.bias, d.bias, d.bias] : (p = [d.bias[0], d.bias[1], d.bias[2], 0], d.bias[3] !== void 0 && (p[3] = d.bias[3]));
+ let m = i * o;
+ if (t !== void 0 && (t.format !== void 0 && a === 4 && t.format !== "RGBA" || a === 3 && t.format !== "RGB" && t.format !== "BGR")) throw new Error("Tensor format doesn't match input tensor dims");
+ let f = 4, b = 0, g = 1, _ = 2, S = 3, $ = 0, v = m, x = m * 2, T = -1;
+ u === "RGBA" ? ($ = 0, v = m, x = m * 2, T = m * 3) : u === "RGB" ? ($ = 0, v = m, x = m * 2) : u === "RBG" && ($ = 0, x = m, v = m * 2), n = r.createImageData(o, i);
+ for (let E = 0; E < i * o; b += f, g += f, _ += f, S += f, E++) n.data[b] = (e.data[$++] - p[0]) * c[0], n.data[g] = (e.data[v++] - p[1]) * c[1], n.data[_] = (e.data[x++] - p[2]) * c[2], n.data[S] = T === -1 ? 255 : (e.data[T++] - p[3]) * c[3];
+ } else throw new Error("Can not access image data");
+ return n;
+ };
+});
+var Mn;
+var ea;
+var ta;
+var ra;
+var na;
+var oa;
+var ia = U(() => {
+ "use strict";
+ hr();
+ Mn = (e, t) => {
+ if (e === void 0) throw new Error("Image buffer must be defined");
+ if (t.height === void 0 || t.width === void 0) throw new Error("Image height and width must be defined");
+ if (t.tensorLayout === "NHWC") throw new Error("NHWC Tensor layout is not supported yet");
+ let { height: r, width: n } = t, o = t.norm ?? { mean: 255, bias: 0 }, i, a;
+ typeof o.mean == "number" ? i = [o.mean, o.mean, o.mean, o.mean] : i = [o.mean[0], o.mean[1], o.mean[2], o.mean[3] ?? 255], typeof o.bias == "number" ? a = [o.bias, o.bias, o.bias, o.bias] : a = [o.bias[0], o.bias[1], o.bias[2], o.bias[3] ?? 0];
+ let u = t.format !== void 0 ? t.format : "RGBA", d = t.tensorFormat !== void 0 && t.tensorFormat !== void 0 ? t.tensorFormat : "RGB", c = r * n, p = d === "RGBA" ? new Float32Array(c * 4) : new Float32Array(c * 3), m = 4, f = 0, b = 1, g = 2, _ = 3, S = 0, $ = c, v = c * 2, x = -1;
+ u === "RGB" && (m = 3, f = 0, b = 1, g = 2, _ = -1), d === "RGBA" ? x = c * 3 : d === "RBG" ? (S = 0, v = c, $ = c * 2) : d === "BGR" && (v = 0, $ = c, S = c * 2);
+ for (let E = 0; E < c; E++, f += m, g += m, b += m, _ += m) p[S++] = (e[f] + a[0]) / i[0], p[$++] = (e[b] + a[1]) / i[1], p[v++] = (e[g] + a[2]) / i[2], x !== -1 && _ !== -1 && (p[x++] = (e[_] + a[3]) / i[3]);
+ return d === "RGBA" ? new Pe("float32", p, [1, 4, r, n]) : new Pe("float32", p, [1, 3, r, n]);
+ }, ea = async (e, t) => {
+ let r = typeof HTMLImageElement < "u" && e instanceof HTMLImageElement, n = typeof ImageData < "u" && e instanceof ImageData, o = typeof ImageBitmap < "u" && e instanceof ImageBitmap, i = typeof e == "string", a, u = t ?? {}, d = () => {
+ if (typeof document < "u") return document.createElement("canvas");
+ if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(1, 1);
+ throw new Error("Canvas is not supported");
+ }, c = (p) => typeof HTMLCanvasElement < "u" && p instanceof HTMLCanvasElement || p instanceof OffscreenCanvas ? p.getContext("2d") : null;
+ if (r) {
+ let p = d();
+ p.width = e.width, p.height = e.height;
+ let m = c(p);
+ if (m != null) {
+ let f = e.height, b = e.width;
+ if (t !== void 0 && t.resizedHeight !== void 0 && t.resizedWidth !== void 0 && (f = t.resizedHeight, b = t.resizedWidth), t !== void 0) {
+ if (u = t, t.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement");
+ u.tensorFormat = "RGBA", u.height = f, u.width = b;
+ } else u.tensorFormat = "RGBA", u.height = f, u.width = b;
+ m.drawImage(e, 0, 0), a = m.getImageData(0, 0, b, f).data;
+ } else throw new Error("Can not access image data");
+ } else if (n) {
+ let p, m;
+ if (t !== void 0 && t.resizedWidth !== void 0 && t.resizedHeight !== void 0 ? (p = t.resizedHeight, m = t.resizedWidth) : (p = e.height, m = e.width), t !== void 0 && (u = t), u.format = "RGBA", u.height = p, u.width = m, t !== void 0) {
+ let f = d();
+ f.width = m, f.height = p;
+ let b = c(f);
+ if (b != null) b.putImageData(e, 0, 0), a = b.getImageData(0, 0, m, p).data;
+ else throw new Error("Can not access image data");
+ } else a = e.data;
+ } else if (o) {
+ if (t === void 0) throw new Error("Please provide image config with format for Imagebitmap");
+ let p = d();
+ p.width = e.width, p.height = e.height;
+ let m = c(p);
+ if (m != null) {
+ let f = e.height, b = e.width;
+ return m.drawImage(e, 0, 0, b, f), a = m.getImageData(0, 0, b, f).data, u.height = f, u.width = b, Mn(a, u);
+ } else throw new Error("Can not access image data");
+ } else {
+ if (i) return new Promise((p, m) => {
+ let f = d(), b = c(f);
+ if (!e || !b) return m();
+ let g = new Image();
+ g.crossOrigin = "Anonymous", g.src = e, g.onload = () => {
+ f.width = g.width, f.height = g.height, b.drawImage(g, 0, 0, f.width, f.height);
+ let _ = b.getImageData(0, 0, f.width, f.height);
+ u.height = f.height, u.width = f.width, p(Mn(_.data, u));
+ };
+ });
+ throw new Error("Input data provided is not supported - aborted tensor creation");
+ }
+ if (a !== void 0) return Mn(a, u);
+ throw new Error("Input data provided is not supported - aborted tensor creation");
+ }, ta = (e, t) => {
+ let { width: r, height: n, download: o, dispose: i } = t, a = [1, n, r, 4];
+ return new Pe({ location: "texture", type: "float32", texture: e, dims: a, download: o, dispose: i });
+ }, ra = (e, t) => {
+ let { dataType: r, dims: n, download: o, dispose: i } = t;
+ return new Pe({ location: "gpu-buffer", type: r ?? "float32", gpuBuffer: e, dims: n, download: o, dispose: i });
+ }, na = (e, t) => {
+ let { dataType: r, dims: n, download: o, dispose: i } = t;
+ return new Pe({ location: "ml-tensor", type: r ?? "float32", mlTensor: e, dims: n, download: o, dispose: i });
+ }, oa = (e, t, r) => new Pe({ location: "cpu-pinned", type: e, data: t, dims: r ?? [t.length] });
+});
+var xt;
+var qt;
+var aa;
+var sa;
+var ua = U(() => {
+ "use strict";
+ xt = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array], ["int4", Uint8Array], ["uint4", Uint8Array]]), qt = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]), aa = false, sa = () => {
+ if (!aa) {
+ aa = true;
+ let e = typeof BigInt64Array < "u" && BigInt64Array.from, t = typeof BigUint64Array < "u" && BigUint64Array.from, r = globalThis.Float16Array, n = typeof r < "u" && r.from;
+ e && (xt.set("int64", BigInt64Array), qt.set(BigInt64Array, "int64")), t && (xt.set("uint64", BigUint64Array), qt.set(BigUint64Array, "uint64")), n ? (xt.set("float16", r), qt.set(r, "float16")) : xt.set("float16", Uint16Array);
+ }
+ };
+});
+var da;
+var la;
+var ca = U(() => {
+ "use strict";
+ hr();
+ da = (e) => {
+ let t = 1;
+ for (let r = 0; r < e.length; r++) {
+ let n = e[r];
+ if (typeof n != "number" || !Number.isSafeInteger(n)) throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);
+ if (n < 0) throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);
+ t *= n;
+ }
+ return t;
+ }, la = (e, t) => {
+ switch (e.location) {
+ case "cpu":
+ return new Pe(e.type, e.data, t);
+ case "cpu-pinned":
+ return new Pe({ location: "cpu-pinned", data: e.data, type: e.type, dims: t });
+ case "texture":
+ return new Pe({ location: "texture", texture: e.texture, type: e.type, dims: t });
+ case "gpu-buffer":
+ return new Pe({ location: "gpu-buffer", gpuBuffer: e.gpuBuffer, type: e.type, dims: t });
+ case "ml-tensor":
+ return new Pe({ location: "ml-tensor", mlTensor: e.mlTensor, type: e.type, dims: t });
+ default:
+ throw new Error(`tensorReshape: tensor location ${e.location} is not supported`);
+ }
+ };
+});
+var Pe;
+var hr = U(() => {
+ "use strict";
+ Ji();
+ ia();
+ ua();
+ ca();
+ Pe = class {
+ constructor(t, r, n) {
+ sa();
+ let o, i;
+ if (typeof t == "object" && "location" in t) switch (this.dataLocation = t.location, o = t.type, i = t.dims, t.location) {
+ case "cpu-pinned": {
+ let u = xt.get(o);
+ if (!u) throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);
+ if (!(t.data instanceof u)) throw new TypeError(`buffer should be of type ${u.name}`);
+ this.cpuData = t.data;
+ break;
+ }
+ case "texture": {
+ if (o !== "float32") throw new TypeError(`unsupported type "${o}" to create tensor from texture`);
+ this.gpuTextureData = t.texture, this.downloader = t.download, this.disposer = t.dispose;
+ break;
+ }
+ case "gpu-buffer": {
+ if (o !== "float32" && o !== "float16" && o !== "int32" && o !== "int64" && o !== "uint32" && o !== "uint8" && o !== "bool" && o !== "uint4" && o !== "int4") throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);
+ this.gpuBufferData = t.gpuBuffer, this.downloader = t.download, this.disposer = t.dispose;
+ break;
+ }
+ case "ml-tensor": {
+ if (o !== "float32" && o !== "float16" && o !== "int32" && o !== "int64" && o !== "uint32" && o !== "uint64" && o !== "int8" && o !== "uint8" && o !== "bool" && o !== "uint4" && o !== "int4") throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);
+ this.mlTensorData = t.mlTensor, this.downloader = t.download, this.disposer = t.dispose;
+ break;
+ }
+ default:
+ throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);
+ }
+ else {
+ let u, d;
+ if (typeof t == "string") if (o = t, d = n, t === "string") {
+ if (!Array.isArray(r)) throw new TypeError("A string tensor's data must be a string array.");
+ u = r;
+ } else {
+ let c = xt.get(t);
+ if (c === void 0) throw new TypeError(`Unsupported tensor type: ${t}.`);
+ if (Array.isArray(r)) {
+ if (t === "float16" && c === Uint16Array || t === "uint4" || t === "int4") throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);
+ t === "uint64" || t === "int64" ? u = c.from(r, BigInt) : u = c.from(r);
+ } else if (r instanceof c) u = r;
+ else if (r instanceof Uint8ClampedArray) if (t === "uint8") u = Uint8Array.from(r);
+ else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");
+ else if (t === "float16" && r instanceof Uint16Array && c !== Uint16Array) u = new globalThis.Float16Array(r.buffer, r.byteOffset, r.length);
+ else throw new TypeError(`A ${o} tensor's data must be type of ${c}`);
+ }
+ else if (d = r, Array.isArray(t)) {
+ if (t.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array.");
+ let c = typeof t[0];
+ if (c === "string") o = "string", u = t;
+ else if (c === "boolean") o = "bool", u = Uint8Array.from(t);
+ else throw new TypeError(`Invalid element type of data array: ${c}.`);
+ } else if (t instanceof Uint8ClampedArray) o = "uint8", u = Uint8Array.from(t);
+ else {
+ let c = qt.get(t.constructor);
+ if (c === void 0) throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);
+ o = c, u = t;
+ }
+ if (d === void 0) d = [u.length];
+ else if (!Array.isArray(d)) throw new TypeError("A tensor's dims must be a number array");
+ i = d, this.cpuData = u, this.dataLocation = "cpu";
+ }
+ let a = da(i);
+ if (this.cpuData && a !== this.cpuData.length && !((o === "uint4" || o === "int4") && Math.ceil(a / 2) === this.cpuData.length)) throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);
+ this.type = o, this.dims = i, this.size = a;
+ }
+ static async fromImage(t, r) {
+ return ea(t, r);
+ }
+ static fromTexture(t, r) {
+ return ta(t, r);
+ }
+ static fromGpuBuffer(t, r) {
+ return ra(t, r);
+ }
+ static fromMLTensor(t, r) {
+ return na(t, r);
+ }
+ static fromPinnedBuffer(t, r, n) {
+ return oa(t, r, n);
+ }
+ toDataURL(t) {
+ return Yi(this, t);
+ }
+ toImageData(t) {
+ return Xi(this, t);
+ }
+ get data() {
+ if (this.ensureValid(), !this.cpuData) throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");
+ return this.cpuData;
+ }
+ get location() {
+ return this.dataLocation;
+ }
+ get texture() {
+ if (this.ensureValid(), !this.gpuTextureData) throw new Error("The data is not stored as a WebGL texture.");
+ return this.gpuTextureData;
+ }
+ get gpuBuffer() {
+ if (this.ensureValid(), !this.gpuBufferData) throw new Error("The data is not stored as a WebGPU buffer.");
+ return this.gpuBufferData;
+ }
+ get mlTensor() {
+ if (this.ensureValid(), !this.mlTensorData) throw new Error("The data is not stored as a WebNN MLTensor.");
+ return this.mlTensorData;
+ }
+ async getData(t) {
+ switch (this.ensureValid(), this.dataLocation) {
+ case "cpu":
+ case "cpu-pinned":
+ return this.data;
+ case "texture":
+ case "gpu-buffer":
+ case "ml-tensor": {
+ if (!this.downloader) throw new Error("The current tensor is not created with a specified data downloader.");
+ if (this.isDownloading) throw new Error("The current tensor is being downloaded.");
+ try {
+ this.isDownloading = true;
+ let r = await this.downloader();
+ return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = r, t && this.disposer && (this.disposer(), this.disposer = void 0), r;
+ } finally {
+ this.isDownloading = false;
+ }
+ }
+ default:
+ throw new Error(`cannot get data from location: ${this.dataLocation}`);
+ }
+ }
+ dispose() {
+ if (this.isDownloading) throw new Error("The current tensor is being downloaded.");
+ this.disposer && (this.disposer(), this.disposer = void 0), this.cpuData = void 0, this.gpuTextureData = void 0, this.gpuBufferData = void 0, this.mlTensorData = void 0, this.downloader = void 0, this.isDownloading = void 0, this.dataLocation = "none";
+ }
+ ensureValid() {
+ if (this.dataLocation === "none") throw new Error("The tensor is disposed.");
+ }
+ reshape(t) {
+ if (this.ensureValid(), this.downloader || this.disposer) throw new Error("Cannot reshape a tensor that owns GPU resource.");
+ return la(this, t);
+ }
+ };
+});
+var Ge;
+var Rn = U(() => {
+ "use strict";
+ hr();
+ Ge = Pe;
+});
+var gr;
+var pa;
+var Re;
+var Oe;
+var Un = U(() => {
+ "use strict";
+ Dn();
+ gr = (e, t) => {
+ (typeof Me.trace > "u" ? !Me.wasm.trace : !Me.trace) || console.timeStamp(`${e}::ORT::${t}`);
+ }, pa = (e, t) => {
+ let r = new Error().stack?.split(/\r\n|\r|\n/g) || [], n = false;
+ for (let o = 0; o < r.length; o++) {
+ if (n && !r[o].includes("TRACE_FUNC")) {
+ let i = `FUNC_${e}::${r[o].trim().split(" ")[1]}`;
+ t && (i += `::${t}`), gr("CPU", i);
+ return;
+ }
+ r[o].includes("TRACE_FUNC") && (n = true);
+ }
+ }, Re = (e) => {
+ (typeof Me.trace > "u" ? !Me.wasm.trace : !Me.trace) || pa("BEGIN", e);
+ }, Oe = (e) => {
+ (typeof Me.trace > "u" ? !Me.wasm.trace : !Me.trace) || pa("END", e);
+ };
+});
+var br;
+var ma = U(() => {
+ "use strict";
+ Bn();
+ Rn();
+ Un();
+ br = class e {
+ constructor(t) {
+ this.handler = t;
+ }
+ async run(t, r, n) {
+ Re();
+ let o = {}, i = {};
+ if (typeof t != "object" || t === null || t instanceof Ge || Array.isArray(t)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");
+ let a = true;
+ if (typeof r == "object") {
+ if (r === null) throw new TypeError("Unexpected argument[1]: cannot be null.");
+ if (r instanceof Ge) throw new TypeError("'fetches' cannot be a Tensor");
+ if (Array.isArray(r)) {
+ if (r.length === 0) throw new TypeError("'fetches' cannot be an empty array.");
+ a = false;
+ for (let c of r) {
+ if (typeof c != "string") throw new TypeError("'fetches' must be a string array or an object.");
+ if (this.outputNames.indexOf(c) === -1) throw new RangeError(`'fetches' contains invalid output name: ${c}.`);
+ o[c] = null;
+ }
+ if (typeof n == "object" && n !== null) i = n;
+ else if (typeof n < "u") throw new TypeError("'options' must be an object.");
+ } else {
+ let c = false, p = Object.getOwnPropertyNames(r);
+ for (let m of this.outputNames) if (p.indexOf(m) !== -1) {
+ let f = r[m];
+ (f === null || f instanceof Ge) && (c = true, a = false, o[m] = f);
+ }
+ if (c) {
+ if (typeof n == "object" && n !== null) i = n;
+ else if (typeof n < "u") throw new TypeError("'options' must be an object.");
+ } else i = r;
+ }
+ } else if (typeof r < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");
+ for (let c of this.inputNames) if (typeof t[c] > "u") throw new Error(`input '${c}' is missing in 'feeds'.`);
+ if (a) for (let c of this.outputNames) o[c] = null;
+ let u = await this.handler.run(t, o, i), d = {};
+ for (let c in u) if (Object.hasOwnProperty.call(u, c)) {
+ let p = u[c];
+ p instanceof Ge ? d[c] = p : d[c] = new Ge(p.type, p.data, p.dims);
+ }
+ return Oe(), d;
+ }
+ async release() {
+ return this.handler.dispose();
+ }
+ static async create(t, r, n, o) {
+ Re();
+ let i, a = {};
+ if (typeof t == "string") {
+ if (i = t, typeof r == "object" && r !== null) a = r;
+ else if (typeof r < "u") throw new TypeError("'options' must be an object.");
+ } else if (t instanceof Uint8Array) {
+ if (i = t, typeof r == "object" && r !== null) a = r;
+ else if (typeof r < "u") throw new TypeError("'options' must be an object.");
+ } else if (t instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && t instanceof SharedArrayBuffer) {
+ let p = t, m = 0, f = t.byteLength;
+ if (typeof r == "object" && r !== null) a = r;
+ else if (typeof r == "number") {
+ if (m = r, !Number.isSafeInteger(m)) throw new RangeError("'byteOffset' must be an integer.");
+ if (m < 0 || m >= p.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);
+ if (f = t.byteLength - m, typeof n == "number") {
+ if (f = n, !Number.isSafeInteger(f)) throw new RangeError("'byteLength' must be an integer.");
+ if (f <= 0 || m + f > p.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength - m}].`);
+ if (typeof o == "object" && o !== null) a = o;
+ else if (typeof o < "u") throw new TypeError("'options' must be an object.");
+ } else if (typeof n < "u") throw new TypeError("'byteLength' must be a number.");
+ } else if (typeof r < "u") throw new TypeError("'options' must be an object.");
+ i = new Uint8Array(p, m, f);
+ } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");
+ let [u, d] = await Fi(a), c = await u.createInferenceSessionHandler(i, d);
+ return Oe(), new e(c);
+ }
+ startProfiling() {
+ this.handler.startProfiling();
+ }
+ endProfiling() {
+ this.handler.endProfiling();
+ }
+ get inputNames() {
+ return this.handler.inputNames;
+ }
+ get outputNames() {
+ return this.handler.outputNames;
+ }
+ get inputMetadata() {
+ return this.handler.inputMetadata;
+ }
+ get outputMetadata() {
+ return this.handler.outputMetadata;
+ }
+ };
+});
+var Gp;
+var fa = U(() => {
+ "use strict";
+ ma();
+ Gp = br;
+});
+var ha = U(() => {
+ "use strict";
+});
+var ga = U(() => {
+ "use strict";
+});
+var ba = U(() => {
+ "use strict";
+});
+var ya = U(() => {
+ "use strict";
+});
+var Nn = {};
+Dt(Nn, { InferenceSession: () => Gp, TRACE: () => gr, TRACE_FUNC_BEGIN: () => Re, TRACE_FUNC_END: () => Oe, Tensor: () => Ge, env: () => ge, registerBackend: () => $t });
+var We = U(() => {
+ "use strict";
+ qi();
+ Qi();
+ fa();
+ Rn();
+ ha();
+ ga();
+ Un();
+ ba();
+ ya();
+});
+var yr = U(() => {
+ "use strict";
+});
+var $a = {};
+Dt($a, { default: () => Hp });
+var wa;
+var va;
+var Hp;
+var xa = U(() => {
+ "use strict";
+ Vn();
+ ht();
+ _r();
+ wa = "ort-wasm-proxy-worker", va = globalThis.self?.name === wa;
+ va && (self.onmessage = (e) => {
+ let { type: t, in: r } = e.data;
+ try {
+ switch (t) {
+ case "init-wasm":
+ wr(r.wasm).then(() => {
+ vr(r).then(() => {
+ postMessage({ type: t });
+ }, (n) => {
+ postMessage({ type: t, err: n });
+ });
+ }, (n) => {
+ postMessage({ type: t, err: n });
+ });
+ break;
+ case "init-ep": {
+ let { epName: n, env: o } = r;
+ $r(o, n).then(() => {
+ postMessage({ type: t });
+ }, (i) => {
+ postMessage({ type: t, err: i });
+ });
+ break;
+ }
+ case "copy-from": {
+ let { buffer: n } = r, o = jt(n);
+ postMessage({ type: t, out: o });
+ break;
+ }
+ case "create": {
+ let { model: n, options: o } = r;
+ xr(n, o).then((i) => {
+ postMessage({ type: t, out: i });
+ }, (i) => {
+ postMessage({ type: t, err: i });
+ });
+ break;
+ }
+ case "release":
+ Sr(r), postMessage({ type: t });
+ break;
+ case "run": {
+ let { sessionId: n, inputIndices: o, inputs: i, outputIndices: a, options: u } = r;
+ Tr(n, o, i, a, new Array(a.length).fill(null), u).then((d) => {
+ d.some((c) => c[3] !== "cpu") ? postMessage({ type: t, err: "Proxy does not support non-cpu tensor location." }) : postMessage({ type: t, out: d }, Cr([...i, ...d]));
+ }, (d) => {
+ postMessage({ type: t, err: d });
+ });
+ break;
+ }
+ case "end-profiling":
+ Ir(r), postMessage({ type: t });
+ break;
+ default:
+ }
+ } catch (n) {
+ postMessage({ type: t, err: n });
+ }
+ });
+ Hp = va ? null : (e) => new Worker(e ?? Ue, { type: "module", name: wa });
+});
+var Ta = {};
+Dt(Ta, { default: () => Fp });
+var Wn;
+var Sa;
+var Fp;
+var qp;
+var Ia = U(() => {
+ "use strict";
+ Sa = (Wn = import.meta.url, async function(e = {}) {
+ var t, r, n = e, o = new Promise((s, l) => {
+ t = s, r = l;
+ }), i = typeof window == "object", a = typeof WorkerGlobalScope < "u", u = a && self.name?.startsWith("em-pthread");
+ n.mountExternalData = (s, l) => {
+ s.startsWith("./") && (s = s.substring(2)), (n.Eb || (n.Eb = /* @__PURE__ */ new Map())).set(s, l);
+ }, n.unmountExternalData = () => {
+ delete n.Eb;
+ };
+ var d = globalThis.SharedArrayBuffer ?? new WebAssembly.Memory({ initial: 0, maximum: 0, pc: true }).buffer.constructor;
+ let c = (s) => async (...l) => {
+ try {
+ if (n.Fb) throw Error("Session already started");
+ let h = n.Fb = { dc: l[0], errors: [] }, y = await s(...l);
+ if (n.Fb !== h) throw Error("Session mismatch");
+ n.Jb?.flush();
+ let w = h.errors;
+ if (0 < w.length) {
+ let A = await Promise.all(w);
+ if (A = A.filter((B) => B), 0 < A.length) throw Error(A.join(`
+`));
+ }
+ return y;
+ } finally {
+ n.Fb = null;
+ }
+ };
+ n.jsepInit = (s, l) => {
+ if (s === "webgpu") {
+ [n.Jb, n.Ub, n.Yb, n.Kb, n.Xb, n.jb, n.Zb, n.ac, n.Vb, n.Wb, n.$b] = l;
+ let h = n.Jb;
+ n.jsepRegisterBuffer = (y, w, A, B) => h.registerBuffer(y, w, A, B), n.jsepGetBuffer = (y) => h.getBuffer(y), n.jsepCreateDownloader = (y, w, A) => h.createDownloader(y, w, A), n.jsepOnCreateSession = (y) => {
+ h.onCreateSession(y);
+ }, n.jsepOnReleaseSession = (y) => {
+ h.onReleaseSession(y);
+ }, n.jsepOnRunStart = (y) => h.onRunStart(y), n.bc = (y, w) => {
+ h.upload(y, w);
+ };
+ } else if (s === "webnn") {
+ let h = l[0];
+ [n.nc, n.Nb, n.webnnEnsureTensor, n.Ob, n.webnnDownloadTensor] = l.slice(1), n.webnnReleaseTensorId = n.Nb, n.webnnUploadTensor = n.Ob, n.webnnOnRunStart = (y) => h.onRunStart(y), n.webnnOnRunEnd = h.onRunEnd.bind(h), n.webnnRegisterMLContext = (y, w) => {
+ h.registerMLContext(y, w);
+ }, n.webnnOnReleaseSession = (y) => {
+ h.onReleaseSession(y);
+ }, n.webnnCreateMLTensorDownloader = (y, w) => h.createMLTensorDownloader(y, w), n.webnnRegisterMLTensor = (y, w, A, B) => h.registerMLTensor(y, w, A, B), n.webnnCreateMLContext = (y) => h.createMLContext(y), n.webnnRegisterMLConstant = (y, w, A, B, R, G) => h.registerMLConstant(y, w, A, B, R, n.Eb, G), n.webnnRegisterGraphInput = h.registerGraphInput.bind(h), n.webnnIsGraphInput = h.isGraphInput.bind(h), n.webnnCreateTemporaryTensor = h.createTemporaryTensor.bind(h), n.webnnIsInt64Supported = h.isInt64Supported.bind(h);
+ }
+ };
+ let p = () => {
+ let s = (l, h, y) => (...w) => {
+ let A = Ze, B = h?.();
+ w = l(...w);
+ let R = h?.();
+ return B !== R && (l = R, y(B), h = y = null), Ze != A ? new Promise((G, K) => {
+ Sn = { resolve: G, reject: K };
+ }) : w;
+ };
+ (() => {
+ for (let l of ["_OrtAppendExecutionProvider", "_OrtCreateSession", "_OrtRun", "_OrtRunWithBinding", "_OrtBindInput"]) n[l] = s(n[l], () => n[l], (h) => n[l] = h);
+ })(), c !== void 0 && (n._OrtRun = c(n._OrtRun), n._OrtRunWithBinding = c(n._OrtRunWithBinding)), p = void 0;
+ };
+ n.asyncInit = () => {
+ p?.();
+ };
+ var m, f, b = Object.assign({}, n), g = (s, l) => {
+ throw l;
+ }, _ = "";
+ (i || a) && (a ? _ = self.location.href : typeof document < "u" && document.currentScript && (_ = document.currentScript.src), Wn && (_ = Wn), _ = _.startsWith("blob:") ? "" : _.slice(0, _.replace(/[?#].*/, "").lastIndexOf("/") + 1), a && (f = (s) => {
+ var l = new XMLHttpRequest();
+ return l.open("GET", s, false), l.responseType = "arraybuffer", l.send(null), new Uint8Array(l.response);
+ }), m = async (s) => {
+ if (X(s)) return new Promise((h, y) => {
+ var w = new XMLHttpRequest();
+ w.open("GET", s, true), w.responseType = "arraybuffer", w.onload = () => {
+ w.status == 200 || w.status == 0 && w.response ? h(w.response) : y(w.status);
+ }, w.onerror = y, w.send(null);
+ });
+ var l = await fetch(s, { credentials: "same-origin" });
+ if (l.ok) return l.arrayBuffer();
+ throw Error(l.status + " : " + l.url);
+ });
+ var S = console.log.bind(console), $ = console.error.bind(console), v = S, x = $;
+ Object.assign(n, b), b = null;
+ var T, E, I, z, O, D, L, q, Q, W, Z, we, H, j = n.wasmBinary, te = false, X = (s) => s.startsWith("file://");
+ function ue() {
+ return T.buffer != z.buffer && Ce(), z;
+ }
+ function he() {
+ return T.buffer != z.buffer && Ce(), O;
+ }
+ function ye() {
+ return T.buffer != z.buffer && Ce(), D;
+ }
+ function re() {
+ return T.buffer != z.buffer && Ce(), L;
+ }
+ function C() {
+ return T.buffer != z.buffer && Ce(), q;
+ }
+ function V() {
+ return T.buffer != z.buffer && Ce(), Q;
+ }
+ function de() {
+ return T.buffer != z.buffer && Ce(), W;
+ }
+ function ze() {
+ return T.buffer != z.buffer && Ce(), H;
+ }
+ if (u) {
+ let s = function(l) {
+ try {
+ var h = l.data, y = h.Bb;
+ if (y === "load") {
+ let w = [];
+ self.onmessage = (A) => w.push(A), self.startWorker = () => {
+ postMessage({ Bb: "loaded" });
+ for (let A of w) s(A);
+ self.onmessage = s;
+ };
+ for (let A of h.Rb) n[A] && !n[A].proxy || (n[A] = (...B) => {
+ postMessage({ Bb: "callHandler", Qb: A, args: B });
+ }, A == "print" && (v = n[A]), A == "printErr" && (x = n[A]));
+ T = h.kc, Ce(), ve(h.lc);
+ } else if (y === "run") {
+ _c(h.Ab), An(h.Ab, 0, 0, 1, 0, 0), No(), $n(h.Ab), $e || (Oi(), $e = true);
+ try {
+ wc(h.fc, h.Hb);
+ } catch (w) {
+ if (w != "unwind") throw w;
+ }
+ } else h.target !== "setimmediate" && (y === "checkMailbox" ? $e && nr() : y && (x(`worker: received unknown command ${y}`), x(h)));
+ } catch (w) {
+ throw Bi(), w;
+ }
+ };
+ var wg = s, ve, $e = false;
+ x = function(...l) {
+ l = l.join(" "), console.error(l);
+ }, self.alert = function(...l) {
+ postMessage({ Bb: "alert", text: l.join(" "), ic: cr() });
+ }, self.onunhandledrejection = (l) => {
+ throw l.reason || l;
+ }, self.onmessage = s;
+ }
+ function Ce() {
+ var s = T.buffer;
+ n.HEAP8 = z = new Int8Array(s), n.HEAP16 = D = new Int16Array(s), n.HEAPU8 = O = new Uint8Array(s), n.HEAPU16 = L = new Uint16Array(s), n.HEAP32 = q = new Int32Array(s), n.HEAPU32 = Q = new Uint32Array(s), n.HEAPF32 = W = new Float32Array(s), n.HEAPF64 = H = new Float64Array(s), n.HEAP64 = Z = new BigInt64Array(s), n.HEAPU64 = we = new BigUint64Array(s);
+ }
+ function _t() {
+ u ? startWorker(n) : Y.Ca();
+ }
+ u || (T = new WebAssembly.Memory({ initial: 256, maximum: 65536, shared: true }), Ce());
+ var kt, Pt = 0, Lt = null;
+ function zo() {
+ if (--Pt == 0 && Lt) {
+ var s = Lt;
+ Lt = null, s();
+ }
+ }
+ function dt(s) {
+ throw x(s = "Aborted(" + s + ")"), te = true, s = new WebAssembly.RuntimeError(s + ". Build with -sASSERTIONS for more info."), r(s), s;
+ }
+ function Oo() {
+ return { a: { L: yc, Aa: bc, b: $c, $: Go, A: qo, pa: jo, X: Zo, Z: Qo, qa: Yo, na: Xo, ga: Jo, ma: ei, J: ti, Y: ri, V: ni, oa: oi, W: ii, va: xc, E: Tc, Q: Ic, O: Ac, D: kc, u: Pc, r: zc, P: Oc, z: Vc, R: Wc, ja: Lc, T: Gc, aa: Hc, M: Fc, F: qc, ia: $n, sa: jc, t: Kc, Ba: Zc, w: Xc, o: Jc, l: tp, c: _n, n: rp, j: ip, v: ap, p: sp, f: up, s: dp, m: lp, e: cp, k: pp, i: mp, g: fp, d: hp, da: gp, ea: bp, fa: yp, ba: _i, ca: wi, N: vi, xa: wp, ua: xp, h: Sp, C: Tp, G: Ip, ta: vp, x: Cp, ra: Ap, U: Ep, q: _p, y: kp, K: Pp, S: zp, za: Op, ya: Bp, ka: Ti, la: Ii, _: hn, B: Ci, I: Ai, ha: Ei, H: ki, a: T, wa: fn } };
+ }
+ var cn = { 829644: (s, l, h, y, w) => {
+ if (n === void 0 || !n.Eb) return 1;
+ if ((s = Te(Number(s >>> 0))).startsWith("./") && (s = s.substring(2)), !(s = n.Eb.get(s))) return 2;
+ if (l = Number(l >>> 0), h = Number(h >>> 0), y = Number(y >>> 0), l + h > s.byteLength) return 3;
+ try {
+ let A = s.subarray(l, l + h);
+ switch (w) {
+ case 0:
+ he().set(A, y >>> 0);
+ break;
+ case 1:
+ n.mc ? n.mc(y, A) : n.bc(y, A);
+ break;
+ default:
+ return 4;
+ }
+ return 0;
+ } catch {
+ return 4;
+ }
+ }, 830468: (s, l, h) => {
+ n.Ob(s, he().subarray(l >>> 0, l + h >>> 0));
+ }, 830532: () => n.nc(), 830574: (s) => {
+ n.Nb(s);
+ }, 830611: () => {
+ n.Vb();
+ }, 830642: () => {
+ n.Wb();
+ }, 830671: () => {
+ n.$b();
+ }, 830696: (s) => n.Ub(s), 830729: (s) => n.Yb(s), 830761: (s, l, h) => {
+ n.Kb(Number(s), Number(l), Number(h), true);
+ }, 830824: (s, l, h) => {
+ n.Kb(Number(s), Number(l), Number(h));
+ }, 830881: () => typeof wasmOffsetConverter < "u", 830938: (s) => {
+ n.jb("Abs", s, void 0);
+ }, 830989: (s) => {
+ n.jb("Neg", s, void 0);
+ }, 831040: (s) => {
+ n.jb("Floor", s, void 0);
+ }, 831093: (s) => {
+ n.jb("Ceil", s, void 0);
+ }, 831145: (s) => {
+ n.jb("Reciprocal", s, void 0);
+ }, 831203: (s) => {
+ n.jb("Sqrt", s, void 0);
+ }, 831255: (s) => {
+ n.jb("Exp", s, void 0);
+ }, 831306: (s) => {
+ n.jb("Erf", s, void 0);
+ }, 831357: (s) => {
+ n.jb("Sigmoid", s, void 0);
+ }, 831412: (s, l, h) => {
+ n.jb("HardSigmoid", s, { alpha: l, beta: h });
+ }, 831491: (s) => {
+ n.jb("Log", s, void 0);
+ }, 831542: (s) => {
+ n.jb("Sin", s, void 0);
+ }, 831593: (s) => {
+ n.jb("Cos", s, void 0);
+ }, 831644: (s) => {
+ n.jb("Tan", s, void 0);
+ }, 831695: (s) => {
+ n.jb("Asin", s, void 0);
+ }, 831747: (s) => {
+ n.jb("Acos", s, void 0);
+ }, 831799: (s) => {
+ n.jb("Atan", s, void 0);
+ }, 831851: (s) => {
+ n.jb("Sinh", s, void 0);
+ }, 831903: (s) => {
+ n.jb("Cosh", s, void 0);
+ }, 831955: (s) => {
+ n.jb("Asinh", s, void 0);
+ }, 832008: (s) => {
+ n.jb("Acosh", s, void 0);
+ }, 832061: (s) => {
+ n.jb("Atanh", s, void 0);
+ }, 832114: (s) => {
+ n.jb("Tanh", s, void 0);
+ }, 832166: (s) => {
+ n.jb("Not", s, void 0);
+ }, 832217: (s, l, h) => {
+ n.jb("Clip", s, { min: l, max: h });
+ }, 832286: (s) => {
+ n.jb("Clip", s, void 0);
+ }, 832338: (s, l) => {
+ n.jb("Elu", s, { alpha: l });
+ }, 832396: (s) => {
+ n.jb("Gelu", s, void 0);
+ }, 832448: (s) => {
+ n.jb("Relu", s, void 0);
+ }, 832500: (s, l) => {
+ n.jb("LeakyRelu", s, { alpha: l });
+ }, 832564: (s, l) => {
+ n.jb("ThresholdedRelu", s, { alpha: l });
+ }, 832634: (s, l) => {
+ n.jb("Cast", s, { to: l });
+ }, 832692: (s) => {
+ n.jb("Add", s, void 0);
+ }, 832743: (s) => {
+ n.jb("Sub", s, void 0);
+ }, 832794: (s) => {
+ n.jb("Mul", s, void 0);
+ }, 832845: (s) => {
+ n.jb("Div", s, void 0);
+ }, 832896: (s) => {
+ n.jb("Pow", s, void 0);
+ }, 832947: (s) => {
+ n.jb("Equal", s, void 0);
+ }, 833e3: (s) => {
+ n.jb("Greater", s, void 0);
+ }, 833055: (s) => {
+ n.jb("GreaterOrEqual", s, void 0);
+ }, 833117: (s) => {
+ n.jb("Less", s, void 0);
+ }, 833169: (s) => {
+ n.jb("LessOrEqual", s, void 0);
+ }, 833228: (s, l, h, y, w) => {
+ n.jb("ReduceMean", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 833403: (s, l, h, y, w) => {
+ n.jb("ReduceMax", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 833577: (s, l, h, y, w) => {
+ n.jb("ReduceMin", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 833751: (s, l, h, y, w) => {
+ n.jb("ReduceProd", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 833926: (s, l, h, y, w) => {
+ n.jb("ReduceSum", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 834100: (s, l, h, y, w) => {
+ n.jb("ReduceL1", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 834273: (s, l, h, y, w) => {
+ n.jb("ReduceL2", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 834446: (s, l, h, y, w) => {
+ n.jb("ReduceLogSum", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 834623: (s, l, h, y, w) => {
+ n.jb("ReduceSumSquare", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 834803: (s, l, h, y, w) => {
+ n.jb("ReduceLogSumExp", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 834983: (s) => {
+ n.jb("Where", s, void 0);
+ }, 835036: (s, l, h) => {
+ n.jb("Transpose", s, { perm: l ? Array.from(C().subarray(Number(l) >>> 0, Number(h) >>> 0)) : [] });
+ }, 835160: (s, l, h, y) => {
+ n.jb("DepthToSpace", s, { blocksize: l, mode: Te(h), format: y ? "NHWC" : "NCHW" });
+ }, 835293: (s, l, h, y) => {
+ n.jb("DepthToSpace", s, { blocksize: l, mode: Te(h), format: y ? "NHWC" : "NCHW" });
+ }, 835426: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke, Bt) => {
+ n.jb("ConvTranspose", s, { format: G ? "NHWC" : "NCHW", autoPad: l, dilations: [h], group: y, kernelShape: [w], pads: [A, B], strides: [R], wIsConst: () => !!ue()[K >>> 0], outputPadding: ae ? Array.from(C().subarray(Number(ae) >>> 0, Number(le) >>> 0)) : [], outputShape: _e ? Array.from(C().subarray(Number(_e) >>> 0, Number(ke) >>> 0)) : [], activation: Te(Bt) });
+ }, 835859: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => {
+ n.jb("ConvTranspose", s, { format: R ? "NHWC" : "NCHW", autoPad: l, dilations: Array.from(C().subarray(Number(h) >>> 0, 2 + (Number(h) >>> 0) >>> 0)), group: y, kernelShape: Array.from(C().subarray(Number(w) >>> 0, 2 + (Number(w) >>> 0) >>> 0)), pads: Array.from(C().subarray(Number(A) >>> 0, 4 + (Number(A) >>> 0) >>> 0)), strides: Array.from(C().subarray(Number(B) >>> 0, 2 + (Number(B) >>> 0) >>> 0)), wIsConst: () => !!ue()[G >>> 0], outputPadding: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], outputShape: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [], activation: Te(ke) });
+ }, 836520: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke, Bt) => {
+ n.jb("ConvTranspose", s, { format: G ? "NHWC" : "NCHW", autoPad: l, dilations: [h], group: y, kernelShape: [w], pads: [A, B], strides: [R], wIsConst: () => !!ue()[K >>> 0], outputPadding: ae ? Array.from(C().subarray(Number(ae) >>> 0, Number(le) >>> 0)) : [], outputShape: _e ? Array.from(C().subarray(Number(_e) >>> 0, Number(ke) >>> 0)) : [], activation: Te(Bt) });
+ }, 836953: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => {
+ n.jb("ConvTranspose", s, { format: R ? "NHWC" : "NCHW", autoPad: l, dilations: Array.from(C().subarray(Number(h) >>> 0, 2 + (Number(h) >>> 0) >>> 0)), group: y, kernelShape: Array.from(C().subarray(Number(w) >>> 0, 2 + (Number(w) >>> 0) >>> 0)), pads: Array.from(C().subarray(Number(A) >>> 0, 4 + (Number(A) >>> 0) >>> 0)), strides: Array.from(C().subarray(Number(B) >>> 0, 2 + (Number(B) >>> 0) >>> 0)), wIsConst: () => !!ue()[G >>> 0], outputPadding: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], outputShape: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [], activation: Te(ke) });
+ }, 837614: (s, l) => {
+ n.jb("GlobalAveragePool", s, { format: l ? "NHWC" : "NCHW" });
+ }, 837705: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => {
+ n.jb("AveragePool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] });
+ }, 838184: (s, l) => {
+ n.jb("GlobalAveragePool", s, { format: l ? "NHWC" : "NCHW" });
+ }, 838275: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => {
+ n.jb("AveragePool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] });
+ }, 838754: (s, l) => {
+ n.jb("GlobalMaxPool", s, { format: l ? "NHWC" : "NCHW" });
+ }, 838841: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => {
+ n.jb("MaxPool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] });
+ }, 839316: (s, l) => {
+ n.jb("GlobalMaxPool", s, { format: l ? "NHWC" : "NCHW" });
+ }, 839403: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => {
+ n.jb("MaxPool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] });
+ }, 839878: (s, l, h, y, w) => {
+ n.jb("Gemm", s, { alpha: l, beta: h, transA: y, transB: w });
+ }, 839982: (s) => {
+ n.jb("MatMul", s, void 0);
+ }, 840036: (s, l, h, y) => {
+ n.jb("ArgMax", s, { keepDims: !!l, selectLastIndex: !!h, axis: y });
+ }, 840144: (s, l, h, y) => {
+ n.jb("ArgMin", s, { keepDims: !!l, selectLastIndex: !!h, axis: y });
+ }, 840252: (s, l) => {
+ n.jb("Softmax", s, { axis: l });
+ }, 840315: (s, l) => {
+ n.jb("Concat", s, { axis: l });
+ }, 840375: (s, l, h, y, w) => {
+ n.jb("Split", s, { axis: l, numOutputs: h, splitSizes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 840531: (s) => {
+ n.jb("Expand", s, void 0);
+ }, 840585: (s, l) => {
+ n.jb("Gather", s, { axis: Number(l) });
+ }, 840656: (s, l) => {
+ n.jb("GatherElements", s, { axis: Number(l) });
+ }, 840735: (s, l) => {
+ n.jb("GatherND", s, { batch_dims: Number(l) });
+ }, 840814: (s, l, h, y, w, A, B, R, G, K, ae) => {
+ n.jb("Resize", s, { antialias: l, axes: h ? Array.from(C().subarray(Number(h) >>> 0, Number(y) >>> 0)) : [], coordinateTransformMode: Te(w), cubicCoeffA: A, excludeOutside: B, extrapolationValue: R, keepAspectRatioPolicy: Te(G), mode: Te(K), nearestMode: Te(ae) });
+ }, 841176: (s, l, h, y, w, A, B) => {
+ n.jb("Slice", s, { starts: l ? Array.from(C().subarray(Number(l) >>> 0, Number(h) >>> 0)) : [], ends: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [], axes: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [] });
+ }, 841440: (s) => {
+ n.jb("Tile", s, void 0);
+ }, 841492: (s, l, h) => {
+ n.jb("InstanceNormalization", s, { epsilon: l, format: h ? "NHWC" : "NCHW" });
+ }, 841606: (s, l, h) => {
+ n.jb("InstanceNormalization", s, { epsilon: l, format: h ? "NHWC" : "NCHW" });
+ }, 841720: (s) => {
+ n.jb("Range", s, void 0);
+ }, 841773: (s, l) => {
+ n.jb("Einsum", s, { equation: Te(l) });
+ }, 841854: (s, l, h, y, w) => {
+ n.jb("Pad", s, { mode: l, value: h, pads: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] });
+ }, 841997: (s, l, h, y, w, A) => {
+ n.jb("BatchNormalization", s, { epsilon: l, momentum: h, spatial: !!w, trainingMode: !!y, format: A ? "NHWC" : "NCHW" });
+ }, 842166: (s, l, h, y, w, A) => {
+ n.jb("BatchNormalization", s, { epsilon: l, momentum: h, spatial: !!w, trainingMode: !!y, format: A ? "NHWC" : "NCHW" });
+ }, 842335: (s, l, h) => {
+ n.jb("CumSum", s, { exclusive: Number(l), reverse: Number(h) });
+ }, 842432: (s, l, h) => {
+ n.jb("DequantizeLinear", s, { axis: l, blockSize: h });
+ }, 842522: (s, l, h, y, w) => {
+ n.jb("GridSample", s, { align_corners: l, mode: Te(h), padding_mode: Te(y), format: w ? "NHWC" : "NCHW" });
+ }, 842692: (s, l, h, y, w) => {
+ n.jb("GridSample", s, { align_corners: l, mode: Te(h), padding_mode: Te(y), format: w ? "NHWC" : "NCHW" });
+ }, 842862: (s, l) => {
+ n.jb("ScatterND", s, { reduction: Te(l) });
+ }, 842947: (s, l, h, y, w, A, B, R, G) => {
+ n.jb("Attention", s, { numHeads: l, isUnidirectional: h, maskFilterValue: y, scale: w, doRotary: A, qkvHiddenSizes: B ? Array.from(C().subarray(Number(R) >>> 0, Number(R) + B >>> 0)) : [], pastPresentShareBuffer: !!G });
+ }, 843219: (s) => {
+ n.jb("BiasAdd", s, void 0);
+ }, 843274: (s) => {
+ n.jb("BiasSplitGelu", s, void 0);
+ }, 843335: (s) => {
+ n.jb("FastGelu", s, void 0);
+ }, 843391: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke, Bt, Rp) => {
+ n.jb("Conv", s, { format: le ? "NHWC" : "NCHW", auto_pad: l, dilations: h ? Array.from(C().subarray(Number(h) >>> 0, Number(y) >>> 0)) : [], group: w, kernel_shape: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], pads: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], strides: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], w_is_const: () => !!ue()[Number(_e) >>> 0], activation: Te(ke), activation_params: Bt ? Array.from(de().subarray(Number(Bt) >>> 0, Number(Rp) >>> 0)) : [] });
+ }, 843975: (s) => {
+ n.jb("Gelu", s, void 0);
+ }, 844027: (s, l, h, y, w, A, B, R, G) => {
+ n.jb("GroupQueryAttention", s, { numHeads: l, kvNumHeads: h, scale: y, softcap: w, doRotary: A, rotaryInterleaved: B, smoothSoftmax: R, localWindowSize: G });
+ }, 844244: (s, l, h, y) => {
+ n.jb("LayerNormalization", s, { axis: l, epsilon: h, simplified: !!y });
+ }, 844355: (s, l, h, y) => {
+ n.jb("LayerNormalization", s, { axis: l, epsilon: h, simplified: !!y });
+ }, 844466: (s, l, h, y, w, A) => {
+ n.jb("MatMulNBits", s, { k: l, n: h, accuracyLevel: y, bits: w, blockSize: A });
+ }, 844593: (s, l, h, y, w, A) => {
+ n.jb("MultiHeadAttention", s, { numHeads: l, isUnidirectional: h, maskFilterValue: y, scale: w, doRotary: A });
+ }, 844752: (s, l) => {
+ n.jb("QuickGelu", s, { alpha: l });
+ }, 844816: (s, l, h, y, w) => {
+ n.jb("RotaryEmbedding", s, { interleaved: !!l, numHeads: h, rotaryEmbeddingDim: y, scale: w });
+ }, 844955: (s, l, h) => {
+ n.jb("SkipLayerNormalization", s, { epsilon: l, simplified: !!h });
+ }, 845057: (s, l, h) => {
+ n.jb("SkipLayerNormalization", s, { epsilon: l, simplified: !!h });
+ }, 845159: (s, l, h, y) => {
+ n.jb("GatherBlockQuantized", s, { gatherAxis: l, quantizeAxis: h, blockSize: y });
+ }, 845280: (s) => {
+ n.Zb(s);
+ }, 845314: (s, l) => n.ac(Number(s), Number(l), n.Fb.dc, n.Fb.errors) };
+ function bc(s, l, h) {
+ return mi(async () => {
+ await n.Xb(Number(s), Number(l), Number(h));
+ });
+ }
+ function yc() {
+ return typeof wasmOffsetConverter < "u";
+ }
+ class pn {
+ constructor(l) {
+ __publicField(this, "name", "ExitStatus");
+ this.message = `Program terminated with exit(${l})`, this.status = l;
+ }
+ }
+ var Bo = (s) => {
+ s.terminate(), s.onmessage = () => {
+ };
+ }, mn = [], Do = (s) => {
+ ct.length == 0 && (Wo(), Vo(ct[0]));
+ var l = ct.pop();
+ if (!l) return 6;
+ Gt.push(l), wt[s.Ab] = l, l.Ab = s.Ab;
+ var h = { Bb: "run", fc: s.ec, Hb: s.Hb, Ab: s.Ab };
+ return l.postMessage(h, s.Mb), 0;
+ }, lt = 0, xe = (s, l, ...h) => {
+ for (var y = 2 * h.length, w = Pn(), A = kn(8 * y), B = A >>> 3, R = 0; R < h.length; R++) {
+ var G = h[R];
+ typeof G == "bigint" ? (Z[B + 2 * R] = 1n, Z[B + 2 * R + 1] = G) : (Z[B + 2 * R] = 0n, ze()[B + 2 * R + 1 >>> 0] = G);
+ }
+ return s = Di(s, 0, y, A, l), mr(w), s;
+ };
+ function fn(s) {
+ if (u) return xe(0, 1, s);
+ if (I = s, !(0 < lt)) {
+ for (var l of Gt) Bo(l);
+ for (l of ct) Bo(l);
+ ct = [], Gt = [], wt = {}, te = true;
+ }
+ g(0, new pn(s));
+ }
+ function Mo(s) {
+ if (u) return xe(1, 0, s);
+ hn(s);
+ }
+ var hn = (s) => {
+ if (I = s, u) throw Mo(s), "unwind";
+ fn(s);
+ }, ct = [], Gt = [], Ro = [], wt = {}, Uo = (s) => {
+ var l = s.Ab;
+ delete wt[l], ct.push(s), Gt.splice(Gt.indexOf(s), 1), s.Ab = 0, Mi(l);
+ };
+ function No() {
+ Ro.forEach((s) => s());
+ }
+ var Vo = (s) => new Promise((l) => {
+ s.onmessage = (w) => {
+ var A = (w = w.data).Bb;
+ if (w.Gb && w.Gb != cr()) {
+ var B = wt[w.Gb];
+ B ? B.postMessage(w, w.Mb) : x(`Internal error! Worker sent a message "${A}" to target pthread ${w.Gb}, but that thread no longer exists!`);
+ } else A === "checkMailbox" ? nr() : A === "spawnThread" ? Do(w) : A === "cleanupThread" ? Uo(wt[w.hc]) : A === "loaded" ? (s.loaded = true, l(s)) : A === "alert" ? alert(`Thread ${w.ic}: ${w.text}`) : w.target === "setimmediate" ? s.postMessage(w) : A === "callHandler" ? n[w.Qb](...w.args) : A && x(`worker sent an unknown command ${A}`);
+ }, s.onerror = (w) => {
+ throw x(`worker sent an error! ${w.filename}:${w.lineno}: ${w.message}`), w;
+ };
+ var h, y = [];
+ for (h of []) n.propertyIsEnumerable(h) && y.push(h);
+ s.postMessage({ Bb: "load", Rb: y, kc: T, lc: E });
+ });
+ function Wo() {
+ var s = new Worker((() => {
+ let l = URL;
+ return import.meta.url > "file:" && import.meta.url < "file;" ? new l("ort.bundle.min.mjs", import.meta.url) : new URL(import.meta.url);
+ })(), { type: "module", workerData: "em-pthread", name: "em-pthread" });
+ ct.push(s);
+ }
+ var _c = (s) => {
+ Ce();
+ var l = V()[s + 52 >>> 2 >>> 0];
+ s = V()[s + 56 >>> 2 >>> 0], Ni(l, l - s), mr(l);
+ }, wc = (s, l) => {
+ lt = 0, s = Vi(s, l), 0 < lt ? I = s : En(s);
+ };
+ class vc {
+ constructor(l) {
+ this.Ib = l - 24;
+ }
+ }
+ function $c(s, l, h) {
+ var y = new vc(s >>>= 0);
+ throw l >>>= 0, h >>>= 0, V()[y.Ib + 16 >>> 2 >>> 0] = 0, V()[y.Ib + 4 >>> 2 >>> 0] = l, V()[y.Ib + 8 >>> 2 >>> 0] = h, s;
+ }
+ function Lo(s, l, h, y) {
+ return u ? xe(2, 1, s, l, h, y) : Go(s, l, h, y);
+ }
+ function Go(s, l, h, y) {
+ if (s >>>= 0, h >>>= 0, y >>>= 0, d === void 0) return 6;
+ var w = [];
+ return u && w.length === 0 ? Lo(s, l >>>= 0, h, y) : (s = { ec: h, Ab: s, Hb: y, Mb: w }, u ? (s.Bb = "spawnThread", postMessage(s, w), 0) : Do(s));
+ }
+ var Ho = typeof TextDecoder < "u" ? new TextDecoder() : void 0, Fo = (s, l = 0, h = NaN) => {
+ var y = (l >>>= 0) + h;
+ for (h = l; s[h] && !(h >= y); ) ++h;
+ if (16 < h - l && s.buffer && Ho) return Ho.decode(s.buffer instanceof ArrayBuffer ? s.subarray(l, h) : s.slice(l, h));
+ for (y = ""; l < h; ) {
+ var w = s[l++];
+ if (128 & w) {
+ var A = 63 & s[l++];
+ if ((224 & w) == 192) y += String.fromCharCode((31 & w) << 6 | A);
+ else {
+ var B = 63 & s[l++];
+ 65536 > (w = (240 & w) == 224 ? (15 & w) << 12 | A << 6 | B : (7 & w) << 18 | A << 12 | B << 6 | 63 & s[l++]) ? y += String.fromCharCode(w) : (w -= 65536, y += String.fromCharCode(55296 | w >> 10, 56320 | 1023 & w));
+ }
+ } else y += String.fromCharCode(w);
+ }
+ return y;
+ }, Te = (s, l) => (s >>>= 0) ? Fo(he(), s, l) : "";
+ function qo(s, l, h) {
+ return u ? xe(3, 1, s, l, h) : 0;
+ }
+ function jo(s, l) {
+ if (u) return xe(4, 1, s, l);
+ }
+ var Ko = (s) => {
+ for (var l = 0, h = 0; h < s.length; ++h) {
+ var y = s.charCodeAt(h);
+ 127 >= y ? l++ : 2047 >= y ? l += 2 : 55296 <= y && 57343 >= y ? (l += 4, ++h) : l += 3;
+ }
+ return l;
+ }, zt = (s, l, h) => {
+ var y = he();
+ if (l >>>= 0, 0 < h) {
+ var w = l;
+ h = l + h - 1;
+ for (var A = 0; A < s.length; ++A) {
+ var B = s.charCodeAt(A);
+ if (55296 <= B && 57343 >= B && (B = 65536 + ((1023 & B) << 10) | 1023 & s.charCodeAt(++A)), 127 >= B) {
+ if (l >= h) break;
+ y[l++ >>> 0] = B;
+ } else {
+ if (2047 >= B) {
+ if (l + 1 >= h) break;
+ y[l++ >>> 0] = 192 | B >> 6;
+ } else {
+ if (65535 >= B) {
+ if (l + 2 >= h) break;
+ y[l++ >>> 0] = 224 | B >> 12;
+ } else {
+ if (l + 3 >= h) break;
+ y[l++ >>> 0] = 240 | B >> 18, y[l++ >>> 0] = 128 | B >> 12 & 63;
+ }
+ y[l++ >>> 0] = 128 | B >> 6 & 63;
+ }
+ y[l++ >>> 0] = 128 | 63 & B;
+ }
+ }
+ y[l >>> 0] = 0, s = l - w;
+ } else s = 0;
+ return s;
+ };
+ function Zo(s, l) {
+ if (u) return xe(5, 1, s, l);
+ }
+ function Qo(s, l, h) {
+ if (u) return xe(6, 1, s, l, h);
+ }
+ function Yo(s, l, h) {
+ return u ? xe(7, 1, s, l, h) : 0;
+ }
+ function Xo(s, l) {
+ if (u) return xe(8, 1, s, l);
+ }
+ function Jo(s, l, h) {
+ if (u) return xe(9, 1, s, l, h);
+ }
+ function ei(s, l, h, y) {
+ if (u) return xe(10, 1, s, l, h, y);
+ }
+ function ti(s, l, h, y) {
+ if (u) return xe(11, 1, s, l, h, y);
+ }
+ function ri(s, l, h, y) {
+ if (u) return xe(12, 1, s, l, h, y);
+ }
+ function ni(s) {
+ if (u) return xe(13, 1, s);
+ }
+ function oi(s, l) {
+ if (u) return xe(14, 1, s, l);
+ }
+ function ii(s, l, h) {
+ if (u) return xe(15, 1, s, l, h);
+ }
+ var ai, pt, xc = () => dt(""), Ke = (s) => {
+ for (var l = ""; he()[s >>> 0]; ) l += ai[he()[s++ >>> 0]];
+ return l;
+ }, gn = {}, bn = {}, Sc = {};
+ function it(s, l, h = {}) {
+ return (function(y, w, A = {}) {
+ var B = w.name;
+ if (!y) throw new pt(`type "${B}" must have a positive integer typeid pointer`);
+ if (bn.hasOwnProperty(y)) {
+ if (A.Sb) return;
+ throw new pt(`Cannot register type '${B}' twice`);
+ }
+ bn[y] = w, delete Sc[y], gn.hasOwnProperty(y) && (w = gn[y], delete gn[y], w.forEach((R) => R()));
+ })(s, l, h);
+ }
+ var si = (s, l, h) => {
+ switch (l) {
+ case 1:
+ return h ? (y) => ue()[y >>> 0] : (y) => he()[y >>> 0];
+ case 2:
+ return h ? (y) => ye()[y >>> 1 >>> 0] : (y) => re()[y >>> 1 >>> 0];
+ case 4:
+ return h ? (y) => C()[y >>> 2 >>> 0] : (y) => V()[y >>> 2 >>> 0];
+ case 8:
+ return h ? (y) => Z[y >>> 3] : (y) => we[y >>> 3];
+ default:
+ throw new TypeError(`invalid integer width (${l}): ${s}`);
+ }
+ };
+ function Tc(s, l, h) {
+ h >>>= 0, it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: (y) => y, toWireType: function(y, w) {
+ if (typeof w != "bigint" && typeof w != "number") throw w = w === null ? "null" : (y = typeof w) == "object" || y === "array" || y === "function" ? w.toString() : "" + w, new TypeError(`Cannot convert "${w}" to ${this.name}`);
+ return typeof w == "number" && (w = BigInt(w)), w;
+ }, Cb: mt, readValueFromPointer: si(l, h, l.indexOf("u") == -1), Db: null });
+ }
+ var mt = 8;
+ function Ic(s, l, h, y) {
+ it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: function(w) {
+ return !!w;
+ }, toWireType: function(w, A) {
+ return A ? h : y;
+ }, Cb: mt, readValueFromPointer: function(w) {
+ return this.fromWireType(he()[w >>> 0]);
+ }, Db: null });
+ }
+ var yn = [], at = [];
+ function _n(s) {
+ 9 < (s >>>= 0) && --at[s + 1] == 0 && (at[s] = void 0, yn.push(s));
+ }
+ var De = (s) => {
+ if (!s) throw new pt("Cannot use deleted val. handle = " + s);
+ return at[s];
+ }, Ve = (s) => {
+ switch (s) {
+ case void 0:
+ return 2;
+ case null:
+ return 4;
+ case true:
+ return 6;
+ case false:
+ return 8;
+ default:
+ let l = yn.pop() || at.length;
+ return at[l] = s, at[l + 1] = 1, l;
+ }
+ };
+ function wn(s) {
+ return this.fromWireType(V()[s >>> 2 >>> 0]);
+ }
+ var Cc = { name: "emscripten::val", fromWireType: (s) => {
+ var l = De(s);
+ return _n(s), l;
+ }, toWireType: (s, l) => Ve(l), Cb: mt, readValueFromPointer: wn, Db: null };
+ function Ac(s) {
+ return it(s >>> 0, Cc);
+ }
+ var Ec = (s, l) => {
+ switch (l) {
+ case 4:
+ return function(h) {
+ return this.fromWireType(de()[h >>> 2 >>> 0]);
+ };
+ case 8:
+ return function(h) {
+ return this.fromWireType(ze()[h >>> 3 >>> 0]);
+ };
+ default:
+ throw new TypeError(`invalid float width (${l}): ${s}`);
+ }
+ };
+ function kc(s, l, h) {
+ h >>>= 0, it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: (y) => y, toWireType: (y, w) => w, Cb: mt, readValueFromPointer: Ec(l, h), Db: null });
+ }
+ function Pc(s, l, h, y, w) {
+ if (s >>>= 0, h >>>= 0, l = Ke(l >>> 0), w === -1 && (w = 4294967295), w = (R) => R, y === 0) {
+ var A = 32 - 8 * h;
+ w = (R) => R << A >>> A;
+ }
+ var B = l.includes("unsigned") ? function(R, G) {
+ return G >>> 0;
+ } : function(R, G) {
+ return G;
+ };
+ it(s, { name: l, fromWireType: w, toWireType: B, Cb: mt, readValueFromPointer: si(l, h, y !== 0), Db: null });
+ }
+ function zc(s, l, h) {
+ function y(A) {
+ var B = V()[A >>> 2 >>> 0];
+ return A = V()[A + 4 >>> 2 >>> 0], new w(ue().buffer, A, B);
+ }
+ var w = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array][l];
+ it(s >>>= 0, { name: h = Ke(h >>> 0), fromWireType: y, Cb: mt, readValueFromPointer: y }, { Sb: true });
+ }
+ function Oc(s, l) {
+ it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: function(h) {
+ for (var y, w = V()[h >>> 2 >>> 0], A = h + 4, B = A, R = 0; R <= w; ++R) {
+ var G = A + R;
+ R != w && he()[G >>> 0] != 0 || (B = Te(B, G - B), y === void 0 ? y = B : (y += "\0", y += B), B = G + 1);
+ }
+ return Qe(h), y;
+ }, toWireType: function(h, y) {
+ y instanceof ArrayBuffer && (y = new Uint8Array(y));
+ var w = typeof y == "string";
+ if (!(w || y instanceof Uint8Array || y instanceof Uint8ClampedArray || y instanceof Int8Array)) throw new pt("Cannot pass non-string to std::string");
+ var A = w ? Ko(y) : y.length, B = pr(4 + A + 1), R = B + 4;
+ if (V()[B >>> 2 >>> 0] = A, w) zt(y, R, A + 1);
+ else if (w) for (w = 0; w < A; ++w) {
+ var G = y.charCodeAt(w);
+ if (255 < G) throw Qe(B), new pt("String has UTF-16 code units that do not fit in 8 bits");
+ he()[R + w >>> 0] = G;
+ }
+ else for (w = 0; w < A; ++w) he()[R + w >>> 0] = y[w];
+ return h !== null && h.push(Qe, B), B;
+ }, Cb: mt, readValueFromPointer: wn, Db(h) {
+ Qe(h);
+ } });
+ }
+ var ui = typeof TextDecoder < "u" ? new TextDecoder("utf-16le") : void 0, Bc = (s, l) => {
+ for (var h = s >> 1, y = h + l / 2; !(h >= y) && re()[h >>> 0]; ) ++h;
+ if (32 < (h <<= 1) - s && ui) return ui.decode(he().slice(s, h));
+ for (h = "", y = 0; !(y >= l / 2); ++y) {
+ var w = ye()[s + 2 * y >>> 1 >>> 0];
+ if (w == 0) break;
+ h += String.fromCharCode(w);
+ }
+ return h;
+ }, Dc = (s, l, h) => {
+ if (h ?? (h = 2147483647), 2 > h) return 0;
+ var y = l;
+ h = (h -= 2) < 2 * s.length ? h / 2 : s.length;
+ for (var w = 0; w < h; ++w) {
+ var A = s.charCodeAt(w);
+ ye()[l >>> 1 >>> 0] = A, l += 2;
+ }
+ return ye()[l >>> 1 >>> 0] = 0, l - y;
+ }, Mc = (s) => 2 * s.length, Rc = (s, l) => {
+ for (var h = 0, y = ""; !(h >= l / 4); ) {
+ var w = C()[s + 4 * h >>> 2 >>> 0];
+ if (w == 0) break;
+ ++h, 65536 <= w ? (w -= 65536, y += String.fromCharCode(55296 | w >> 10, 56320 | 1023 & w)) : y += String.fromCharCode(w);
+ }
+ return y;
+ }, Uc = (s, l, h) => {
+ if (l >>>= 0, h ?? (h = 2147483647), 4 > h) return 0;
+ var y = l;
+ h = y + h - 4;
+ for (var w = 0; w < s.length; ++w) {
+ var A = s.charCodeAt(w);
+ if (55296 <= A && 57343 >= A && (A = 65536 + ((1023 & A) << 10) | 1023 & s.charCodeAt(++w)), C()[l >>> 2 >>> 0] = A, (l += 4) + 4 > h) break;
+ }
+ return C()[l >>> 2 >>> 0] = 0, l - y;
+ }, Nc = (s) => {
+ for (var l = 0, h = 0; h < s.length; ++h) {
+ var y = s.charCodeAt(h);
+ 55296 <= y && 57343 >= y && ++h, l += 4;
+ }
+ return l;
+ };
+ function Vc(s, l, h) {
+ if (s >>>= 0, l >>>= 0, h = Ke(h >>>= 0), l === 2) var y = Bc, w = Dc, A = Mc, B = (R) => re()[R >>> 1 >>> 0];
+ else l === 4 && (y = Rc, w = Uc, A = Nc, B = (R) => V()[R >>> 2 >>> 0]);
+ it(s, { name: h, fromWireType: (R) => {
+ for (var G, K = V()[R >>> 2 >>> 0], ae = R + 4, le = 0; le <= K; ++le) {
+ var _e = R + 4 + le * l;
+ le != K && B(_e) != 0 || (ae = y(ae, _e - ae), G === void 0 ? G = ae : (G += "\0", G += ae), ae = _e + l);
+ }
+ return Qe(R), G;
+ }, toWireType: (R, G) => {
+ if (typeof G != "string") throw new pt(`Cannot pass non-string to C++ string type ${h}`);
+ var K = A(G), ae = pr(4 + K + l);
+ return V()[ae >>> 2 >>> 0] = K / l, w(G, ae + 4, K + l), R !== null && R.push(Qe, ae), ae;
+ }, Cb: mt, readValueFromPointer: wn, Db(R) {
+ Qe(R);
+ } });
+ }
+ function Wc(s, l) {
+ it(s >>>= 0, { Tb: true, name: l = Ke(l >>> 0), Cb: 0, fromWireType: () => {
+ }, toWireType: () => {
+ } });
+ }
+ function Lc(s) {
+ An(s >>> 0, !a, 1, !i, 131072, false), No();
+ }
+ var vn = (s) => {
+ if (!te) try {
+ if (s(), !(0 < lt)) try {
+ u ? En(I) : hn(I);
+ } catch (l) {
+ l instanceof pn || l == "unwind" || g(0, l);
+ }
+ } catch (l) {
+ l instanceof pn || l == "unwind" || g(0, l);
+ }
+ };
+ function $n(s) {
+ s >>>= 0, typeof Atomics.jc == "function" && (Atomics.jc(C(), s >>> 2, s).value.then(nr), s += 128, Atomics.store(C(), s >>> 2, 1));
+ }
+ var nr = () => {
+ var s = cr();
+ s && ($n(s), vn(Ui));
+ };
+ function Gc(s, l) {
+ (s >>>= 0) == l >>> 0 ? setTimeout(nr) : u ? postMessage({ Gb: s, Bb: "checkMailbox" }) : (s = wt[s]) && s.postMessage({ Bb: "checkMailbox" });
+ }
+ var xn = [];
+ function Hc(s, l, h, y, w) {
+ for (l >>>= 0, y /= 2, xn.length = y, h = w >>> 0 >>> 3, w = 0; w < y; w++) xn[w] = Z[h + 2 * w] ? Z[h + 2 * w + 1] : ze()[h + 2 * w + 1 >>> 0];
+ return (l ? cn[l] : Mp[s])(...xn);
+ }
+ var Fc = () => {
+ lt = 0;
+ };
+ function qc(s) {
+ s >>>= 0, u ? postMessage({ Bb: "cleanupThread", hc: s }) : Uo(wt[s]);
+ }
+ function jc(s) {
+ }
+ var or = (s, l) => {
+ var h = bn[s];
+ if (h === void 0) throw s = zi(s), h = Ke(s), Qe(s), new pt(`${l} has unknown type ${h}`);
+ return h;
+ }, di = (s, l, h) => {
+ var y = [];
+ return s = s.toWireType(y, h), y.length && (V()[l >>> 2 >>> 0] = Ve(y)), s;
+ };
+ function Kc(s, l, h) {
+ return l >>>= 0, h >>>= 0, s = De(s >>> 0), l = or(l, "emval::as"), di(l, h, s);
+ }
+ function Zc(s, l) {
+ return l >>>= 0, s = De(s >>> 0), (l = or(l, "emval::as")).toWireType(null, s);
+ }
+ var ir = (s) => {
+ try {
+ s();
+ } catch (l) {
+ dt(l);
+ }
+ }, ft = 0, Ze = null, li = 0, ar = [], ci = {}, pi = {}, Qc = 0, Sn = null, Yc = [];
+ function mi(s) {
+ return (function(l) {
+ if (!te) {
+ if (ft === 0) {
+ var h = false, y = false;
+ l((w = 0) => {
+ if (!te && (li = w, h = true, y)) {
+ ft = 2, ir(() => Gi(Ze)), typeof MainLoop < "u" && MainLoop.Pb && MainLoop.resume(), w = false;
+ try {
+ var A = (function() {
+ var G = C()[Ze + 8 >>> 2 >>> 0];
+ return G = Y[pi[G]], --lt, G();
+ })();
+ } catch (G) {
+ A = G, w = true;
+ }
+ var B = false;
+ if (!Ze) {
+ var R = Sn;
+ R && (Sn = null, (w ? R.reject : R.resolve)(A), B = true);
+ }
+ if (w && !B) throw A;
+ }
+ }), y = true, h || (ft = 1, Ze = (function() {
+ var w = pr(65548), A = w + 12;
+ V()[w >>> 2 >>> 0] = A, V()[w + 4 >>> 2 >>> 0] = A + 65536, A = ar[0];
+ var B = ci[A];
+ return B === void 0 && (B = Qc++, ci[A] = B, pi[B] = A), A = B, C()[w + 8 >>> 2 >>> 0] = A, w;
+ })(), typeof MainLoop < "u" && MainLoop.Pb && MainLoop.pause(), ir(() => Wi(Ze)));
+ } else ft === 2 ? (ft = 0, ir(Hi), Qe(Ze), Ze = null, Yc.forEach(vn)) : dt(`invalid state: ${ft}`);
+ return li;
+ }
+ })((l) => {
+ s().then(l);
+ });
+ }
+ function Xc(s) {
+ return s >>>= 0, mi(async () => {
+ var l = await De(s);
+ return Ve(l);
+ });
+ }
+ var sr = [];
+ function Jc(s, l, h, y) {
+ return h >>>= 0, y >>>= 0, (s = sr[s >>> 0])(null, l = De(l >>> 0), h, y);
+ }
+ var ep = {}, ur = (s) => {
+ var l = ep[s];
+ return l === void 0 ? Ke(s) : l;
+ };
+ function tp(s, l, h, y, w) {
+ return h >>>= 0, y >>>= 0, w >>>= 0, (s = sr[s >>> 0])(l = De(l >>> 0), l[h = ur(h)], y, w);
+ }
+ var fi = () => typeof globalThis == "object" ? globalThis : Function("return this")();
+ function rp(s) {
+ return (s >>>= 0) == 0 ? Ve(fi()) : (s = ur(s), Ve(fi()[s]));
+ }
+ var np = (s) => {
+ var l = sr.length;
+ return sr.push(s), l;
+ }, op = (s, l) => {
+ for (var h = Array(s), y = 0; y < s; ++y) h[y] = or(V()[l + 4 * y >>> 2 >>> 0], "parameter " + y);
+ return h;
+ }, hi = (s, l) => Object.defineProperty(l, "name", { value: s });
+ function ip(s, l, h) {
+ var y = (l = op(s, l >>> 0)).shift();
+ s--;
+ var w = `return function (obj, func, destructorsRef, args) {
+`, A = 0, B = [];
+ h === 0 && B.push("obj");
+ for (var R = ["retType"], G = [y], K = 0; K < s; ++K) B.push("arg" + K), R.push("argType" + K), G.push(l[K]), w += ` var arg${K} = argType${K}.readValueFromPointer(args${A ? "+" + A : ""});
+`, A += l[K].Cb;
+ return w += ` var rv = ${h === 1 ? "new func" : "func.call"}(${B.join(", ")});
+`, y.Tb || (R.push("emval_returnValue"), G.push(di), w += ` return emval_returnValue(retType, destructorsRef, rv);
+`), R.push(w + `};
+`), s = (function(ae) {
+ var le = Function;
+ if (!(le instanceof Function)) throw new TypeError(`new_ called with constructor type ${typeof le} which is not a function`);
+ var _e = hi(le.name || "unknownFunctionName", function() {
+ });
+ return _e.prototype = le.prototype, _e = new _e(), (ae = le.apply(_e, ae)) instanceof Object ? ae : _e;
+ })(R)(...G), h = `methodCaller<(${l.map((ae) => ae.name).join(", ")}) => ${y.name}>`, np(hi(h, s));
+ }
+ function ap(s) {
+ return s = ur(s >>> 0), Ve(n[s]);
+ }
+ function sp(s, l) {
+ return l >>>= 0, s = De(s >>> 0), l = De(l), Ve(s[l]);
+ }
+ function up(s) {
+ 9 < (s >>>= 0) && (at[s + 1] += 1);
+ }
+ function dp() {
+ return Ve([]);
+ }
+ function lp(s) {
+ s = De(s >>> 0);
+ for (var l = Array(s.length), h = 0; h < s.length; h++) l[h] = s[h];
+ return Ve(l);
+ }
+ function cp(s) {
+ return Ve(ur(s >>> 0));
+ }
+ function pp() {
+ return Ve({});
+ }
+ function mp(s) {
+ for (var l = De(s >>>= 0); l.length; ) {
+ var h = l.pop();
+ l.pop()(h);
+ }
+ _n(s);
+ }
+ function fp(s, l, h) {
+ l >>>= 0, h >>>= 0, s = De(s >>> 0), l = De(l), h = De(h), s[l] = h;
+ }
+ function hp(s, l) {
+ return l >>>= 0, s = (s = or(s >>> 0, "_emval_take_value")).readValueFromPointer(l), Ve(s);
+ }
+ function gp(s, l) {
+ s = -9007199254740992 > s || 9007199254740992 < s ? NaN : Number(s), l >>>= 0, s = new Date(1e3 * s), C()[l >>> 2 >>> 0] = s.getUTCSeconds(), C()[l + 4 >>> 2 >>> 0] = s.getUTCMinutes(), C()[l + 8 >>> 2 >>> 0] = s.getUTCHours(), C()[l + 12 >>> 2 >>> 0] = s.getUTCDate(), C()[l + 16 >>> 2 >>> 0] = s.getUTCMonth(), C()[l + 20 >>> 2 >>> 0] = s.getUTCFullYear() - 1900, C()[l + 24 >>> 2 >>> 0] = s.getUTCDay(), s = (s.getTime() - Date.UTC(s.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, C()[l + 28 >>> 2 >>> 0] = s;
+ }
+ var gi = (s) => s % 4 == 0 && (s % 100 != 0 || s % 400 == 0), bi = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], yi = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
+ function bp(s, l) {
+ s = -9007199254740992 > s || 9007199254740992 < s ? NaN : Number(s), l >>>= 0, s = new Date(1e3 * s), C()[l >>> 2 >>> 0] = s.getSeconds(), C()[l + 4 >>> 2 >>> 0] = s.getMinutes(), C()[l + 8 >>> 2 >>> 0] = s.getHours(), C()[l + 12 >>> 2 >>> 0] = s.getDate(), C()[l + 16 >>> 2 >>> 0] = s.getMonth(), C()[l + 20 >>> 2 >>> 0] = s.getFullYear() - 1900, C()[l + 24 >>> 2 >>> 0] = s.getDay();
+ var h = (gi(s.getFullYear()) ? bi : yi)[s.getMonth()] + s.getDate() - 1 | 0;
+ C()[l + 28 >>> 2 >>> 0] = h, C()[l + 36 >>> 2 >>> 0] = -60 * s.getTimezoneOffset(), h = new Date(s.getFullYear(), 6, 1).getTimezoneOffset();
+ var y = new Date(s.getFullYear(), 0, 1).getTimezoneOffset();
+ s = 0 | (h != y && s.getTimezoneOffset() == Math.min(y, h)), C()[l + 32 >>> 2 >>> 0] = s;
+ }
+ function yp(s) {
+ s >>>= 0;
+ var l = new Date(C()[s + 20 >>> 2 >>> 0] + 1900, C()[s + 16 >>> 2 >>> 0], C()[s + 12 >>> 2 >>> 0], C()[s + 8 >>> 2 >>> 0], C()[s + 4 >>> 2 >>> 0], C()[s >>> 2 >>> 0], 0), h = C()[s + 32 >>> 2 >>> 0], y = l.getTimezoneOffset(), w = new Date(l.getFullYear(), 6, 1).getTimezoneOffset(), A = new Date(l.getFullYear(), 0, 1).getTimezoneOffset(), B = Math.min(A, w);
+ return 0 > h ? C()[s + 32 >>> 2 >>> 0] = +(w != A && B == y) : 0 < h != (B == y) && (w = Math.max(A, w), l.setTime(l.getTime() + 6e4 * ((0 < h ? B : w) - y))), C()[s + 24 >>> 2 >>> 0] = l.getDay(), h = (gi(l.getFullYear()) ? bi : yi)[l.getMonth()] + l.getDate() - 1 | 0, C()[s + 28 >>> 2 >>> 0] = h, C()[s >>> 2 >>> 0] = l.getSeconds(), C()[s + 4 >>> 2 >>> 0] = l.getMinutes(), C()[s + 8 >>> 2 >>> 0] = l.getHours(), C()[s + 12 >>> 2 >>> 0] = l.getDate(), C()[s + 16 >>> 2 >>> 0] = l.getMonth(), C()[s + 20 >>> 2 >>> 0] = l.getYear(), s = l.getTime(), BigInt(isNaN(s) ? -1 : s / 1e3);
+ }
+ function _i(s, l, h, y, w, A, B) {
+ return u ? xe(16, 1, s, l, h, y, w, A, B) : -52;
+ }
+ function wi(s, l, h, y, w, A) {
+ if (u) return xe(17, 1, s, l, h, y, w, A);
+ }
+ var Ht = {}, _p = () => performance.timeOrigin + performance.now();
+ function vi(s, l) {
+ if (u) return xe(18, 1, s, l);
+ if (Ht[s] && (clearTimeout(Ht[s].id), delete Ht[s]), !l) return 0;
+ var h = setTimeout(() => {
+ delete Ht[s], vn(() => Ri(s, performance.timeOrigin + performance.now()));
+ }, l);
+ return Ht[s] = { id: h, qc: l }, 0;
+ }
+ function wp(s, l, h, y) {
+ s >>>= 0, l >>>= 0, h >>>= 0, y >>>= 0;
+ var w = (/* @__PURE__ */ new Date()).getFullYear(), A = new Date(w, 0, 1).getTimezoneOffset();
+ w = new Date(w, 6, 1).getTimezoneOffset();
+ var B = Math.max(A, w);
+ V()[s >>> 2 >>> 0] = 60 * B, C()[l >>> 2 >>> 0] = +(A != w), s = (l = (R) => {
+ var G = Math.abs(R);
+ return `UTC${0 <= R ? "-" : "+"}${String(Math.floor(G / 60)).padStart(2, "0")}${String(G % 60).padStart(2, "0")}`;
+ })(A), l = l(w), w < A ? (zt(s, h, 17), zt(l, y, 17)) : (zt(s, y, 17), zt(l, h, 17));
+ }
+ var vp = () => Date.now(), $p = 1;
+ function xp(s, l, h) {
+ if (!(0 <= s && 3 >= s)) return 28;
+ if (s === 0) s = Date.now();
+ else {
+ if (!$p) return 52;
+ s = performance.timeOrigin + performance.now();
+ }
+ return Z[h >>> 0 >>> 3] = BigInt(Math.round(1e6 * s)), 0;
+ }
+ var Tn = [], $i = (s, l) => {
+ Tn.length = 0;
+ for (var h; h = he()[s++ >>> 0]; ) {
+ var y = h != 105;
+ l += (y &= h != 112) && l % 8 ? 4 : 0, Tn.push(h == 112 ? V()[l >>> 2 >>> 0] : h == 106 ? Z[l >>> 3] : h == 105 ? C()[l >>> 2 >>> 0] : ze()[l >>> 3 >>> 0]), l += y ? 8 : 4;
+ }
+ return Tn;
+ };
+ function Sp(s, l, h) {
+ return s >>>= 0, l = $i(l >>> 0, h >>> 0), cn[s](...l);
+ }
+ function Tp(s, l, h) {
+ return s >>>= 0, l = $i(l >>> 0, h >>> 0), cn[s](...l);
+ }
+ var Ip = () => {
+ };
+ function Cp(s, l) {
+ return x(Te(s >>> 0, l >>> 0));
+ }
+ var Ap = () => {
+ throw lt += 1, "unwind";
+ };
+ function Ep() {
+ return 4294901760;
+ }
+ var kp = () => navigator.hardwareConcurrency;
+ function Pp() {
+ return dt("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"), 0;
+ }
+ function zp(s) {
+ s >>>= 0;
+ var l = he().length;
+ if (s <= l || 4294901760 < s) return false;
+ for (var h = 1; 4 >= h; h *= 2) {
+ var y = l * (1 + 0.2 / h);
+ y = Math.min(y, s + 100663296);
+ e: {
+ y = (Math.min(4294901760, 65536 * Math.ceil(Math.max(s, y) / 65536)) - T.buffer.byteLength + 65535) / 65536 | 0;
+ try {
+ T.grow(y), Ce();
+ var w = 1;
+ break e;
+ } catch {
+ }
+ w = void 0;
+ }
+ if (w) return true;
+ }
+ return false;
+ }
+ var dr = () => (dt("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"), 0), Ot = {}, xi = (s) => {
+ s.forEach((l) => {
+ var h = dr();
+ h && (Ot[h] = l);
+ });
+ };
+ function Op() {
+ var s = Error().stack.toString().split(`
+`);
+ return s[0] == "Error" && s.shift(), xi(s), Ot.Lb = dr(), Ot.cc = s, Ot.Lb;
+ }
+ function Bp(s, l, h) {
+ if (s >>>= 0, l >>>= 0, Ot.Lb == s) var y = Ot.cc;
+ else (y = Error().stack.toString().split(`
+`))[0] == "Error" && y.shift(), xi(y);
+ for (var w = 3; y[w] && dr() != s; ) ++w;
+ for (s = 0; s < h && y[s + w]; ++s) C()[l + 4 * s >>> 2 >>> 0] = dr();
+ return s;
+ }
+ var In, Cn = {}, Si = () => {
+ if (!In) {
+ var s, l = { 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" };
+ for (s in Cn) Cn[s] === void 0 ? delete l[s] : l[s] = Cn[s];
+ var h = [];
+ for (s in l) h.push(`${s}=${l[s]}`);
+ In = h;
+ }
+ return In;
+ };
+ function Ti(s, l) {
+ if (u) return xe(19, 1, s, l);
+ s >>>= 0, l >>>= 0;
+ var h = 0;
+ return Si().forEach((y, w) => {
+ var A = l + h;
+ for (w = V()[s + 4 * w >>> 2 >>> 0] = A, A = 0; A < y.length; ++A) ue()[w++ >>> 0] = y.charCodeAt(A);
+ ue()[w >>> 0] = 0, h += y.length + 1;
+ }), 0;
+ }
+ function Ii(s, l) {
+ if (u) return xe(20, 1, s, l);
+ s >>>= 0, l >>>= 0;
+ var h = Si();
+ V()[s >>> 2 >>> 0] = h.length;
+ var y = 0;
+ return h.forEach((w) => y += w.length + 1), V()[l >>> 2 >>> 0] = y, 0;
+ }
+ function Ci(s) {
+ return u ? xe(21, 1, s) : 52;
+ }
+ function Ai(s, l, h, y) {
+ return u ? xe(22, 1, s, l, h, y) : 52;
+ }
+ function Ei(s, l, h, y) {
+ return u ? xe(23, 1, s, l, h, y) : 70;
+ }
+ var Dp = [null, [], []];
+ function ki(s, l, h, y) {
+ if (u) return xe(24, 1, s, l, h, y);
+ l >>>= 0, h >>>= 0, y >>>= 0;
+ for (var w = 0, A = 0; A < h; A++) {
+ var B = V()[l >>> 2 >>> 0], R = V()[l + 4 >>> 2 >>> 0];
+ l += 8;
+ for (var G = 0; G < R; G++) {
+ var K = he()[B + G >>> 0], ae = Dp[s];
+ K === 0 || K === 10 ? ((s === 1 ? v : x)(Fo(ae)), ae.length = 0) : ae.push(K);
+ }
+ w += R;
+ }
+ return V()[y >>> 2 >>> 0] = w, 0;
+ }
+ u || (function() {
+ for (var s = n.numThreads - 1; s--; ) Wo();
+ mn.unshift(() => {
+ Pt++, (function(l) {
+ u ? l() : Promise.all(ct.map(Vo)).then(l);
+ })(() => zo());
+ });
+ })();
+ for (var Pi = Array(256), lr = 0; 256 > lr; ++lr) Pi[lr] = String.fromCharCode(lr);
+ ai = Pi, pt = n.BindingError = class extends Error {
+ constructor(s) {
+ super(s), this.name = "BindingError";
+ }
+ }, n.InternalError = class extends Error {
+ constructor(s) {
+ super(s), this.name = "InternalError";
+ }
+ }, at.push(0, 1, void 0, 1, null, 1, true, 1, false, 1), n.count_emval_handles = () => at.length / 2 - 5 - yn.length;
+ var Y, Mp = [fn, Mo, Lo, qo, jo, Zo, Qo, Yo, Xo, Jo, ei, ti, ri, ni, oi, ii, _i, wi, vi, Ti, Ii, Ci, Ai, Ei, ki];
+ (async function() {
+ function s(y, w) {
+ return Y = y.exports, Y = (function() {
+ var A = Y, B = {};
+ for (let [R, G] of Object.entries(A)) B[R] = typeof G == "function" ? (...K) => {
+ ar.push(R);
+ try {
+ return G(...K);
+ } finally {
+ te || (ar.pop(), Ze && ft === 1 && ar.length === 0 && (ft = 0, lt += 1, ir(Li), typeof Fibers < "u" && Fibers.rc()));
+ }
+ } : G;
+ return B;
+ })(), Y = (function() {
+ var A = Y, B = (G) => (K) => G(K) >>> 0, R = (G) => () => G() >>> 0;
+ return (A = Object.assign({}, A)).Da = B(A.Da), A.fb = R(A.fb), A.hb = B(A.hb), A.tb = B(A.tb), A.ub = R(A.ub), A.__cxa_get_exception_ptr = B(A.__cxa_get_exception_ptr), A;
+ })(), Ro.push(Y.ib), E = w, zo(), Y;
+ }
+ Pt++;
+ var l = Oo();
+ if (n.instantiateWasm) return new Promise((y) => {
+ n.instantiateWasm(l, (w, A) => {
+ s(w, A), y(w.exports);
+ });
+ });
+ if (u) return new Promise((y) => {
+ ve = (w) => {
+ var A = new WebAssembly.Instance(w, Oo());
+ y(s(A, w));
+ };
+ });
+ kt ?? (kt = n.locateFile ? n.locateFile ? n.locateFile("ort-wasm-simd-threaded.jsep.wasm", _) : _ + "ort-wasm-simd-threaded.jsep.wasm" : new URL("ort-wasm-simd-threaded.jsep.wasm", import.meta.url).href);
+ try {
+ var h = await (async function(y) {
+ var w = kt;
+ if (!j && typeof WebAssembly.instantiateStreaming == "function" && !X(w)) try {
+ var A = fetch(w, { credentials: "same-origin" });
+ return await WebAssembly.instantiateStreaming(A, y);
+ } catch (B) {
+ x(`wasm streaming compile failed: ${B}`), x("falling back to ArrayBuffer instantiation");
+ }
+ return (async function(B, R) {
+ try {
+ var G = await (async function(K) {
+ if (!j) try {
+ var ae = await m(K);
+ return new Uint8Array(ae);
+ } catch {
+ }
+ if (K == kt && j) K = new Uint8Array(j);
+ else {
+ if (!f) throw "both async and sync fetching of the wasm failed";
+ K = f(K);
+ }
+ return K;
+ })(B);
+ return await WebAssembly.instantiate(G, R);
+ } catch (K) {
+ x(`failed to asynchronously prepare wasm: ${K}`), dt(K);
+ }
+ })(w, y);
+ })(l);
+ return s(h.instance, h.module);
+ } catch (y) {
+ return r(y), Promise.reject(y);
+ }
+ })();
+ var zi = (s) => (zi = Y.Da)(s), Oi = () => (Oi = Y.Ea)();
+ n._OrtInit = (s, l) => (n._OrtInit = Y.Fa)(s, l), n._OrtGetLastError = (s, l) => (n._OrtGetLastError = Y.Ga)(s, l), n._OrtCreateSessionOptions = (s, l, h, y, w, A, B, R, G, K) => (n._OrtCreateSessionOptions = Y.Ha)(s, l, h, y, w, A, B, R, G, K), n._OrtAppendExecutionProvider = (s, l, h, y, w) => (n._OrtAppendExecutionProvider = Y.Ia)(s, l, h, y, w), n._OrtAddFreeDimensionOverride = (s, l, h) => (n._OrtAddFreeDimensionOverride = Y.Ja)(s, l, h), n._OrtAddSessionConfigEntry = (s, l, h) => (n._OrtAddSessionConfigEntry = Y.Ka)(s, l, h), n._OrtReleaseSessionOptions = (s) => (n._OrtReleaseSessionOptions = Y.La)(s), n._OrtCreateSession = (s, l, h) => (n._OrtCreateSession = Y.Ma)(s, l, h), n._OrtReleaseSession = (s) => (n._OrtReleaseSession = Y.Na)(s), n._OrtGetInputOutputCount = (s, l, h) => (n._OrtGetInputOutputCount = Y.Oa)(s, l, h), n._OrtGetInputOutputMetadata = (s, l, h, y) => (n._OrtGetInputOutputMetadata = Y.Pa)(s, l, h, y), n._OrtFree = (s) => (n._OrtFree = Y.Qa)(s), n._OrtCreateTensor = (s, l, h, y, w, A) => (n._OrtCreateTensor = Y.Ra)(s, l, h, y, w, A), n._OrtGetTensorData = (s, l, h, y, w) => (n._OrtGetTensorData = Y.Sa)(s, l, h, y, w), n._OrtReleaseTensor = (s) => (n._OrtReleaseTensor = Y.Ta)(s), n._OrtCreateRunOptions = (s, l, h, y) => (n._OrtCreateRunOptions = Y.Ua)(s, l, h, y), n._OrtAddRunConfigEntry = (s, l, h) => (n._OrtAddRunConfigEntry = Y.Va)(s, l, h), n._OrtReleaseRunOptions = (s) => (n._OrtReleaseRunOptions = Y.Wa)(s), n._OrtCreateBinding = (s) => (n._OrtCreateBinding = Y.Xa)(s), n._OrtBindInput = (s, l, h) => (n._OrtBindInput = Y.Ya)(s, l, h), n._OrtBindOutput = (s, l, h, y) => (n._OrtBindOutput = Y.Za)(s, l, h, y), n._OrtClearBoundOutputs = (s) => (n._OrtClearBoundOutputs = Y._a)(s), n._OrtReleaseBinding = (s) => (n._OrtReleaseBinding = Y.$a)(s), n._OrtRunWithBinding = (s, l, h, y, w) => (n._OrtRunWithBinding = Y.ab)(s, l, h, y, w), n._OrtRun = (s, l, h, y, w, A, B, R) => (n._OrtRun = Y.bb)(s, l, h, y, w, A, B, R), n._OrtEndProfiling = (s) => (n._OrtEndProfiling = Y.cb)(s), n._JsepOutput = (s, l, h) => (n._JsepOutput = Y.db)(s, l, h), n._JsepGetNodeName = (s) => (n._JsepGetNodeName = Y.eb)(s);
+ var cr = () => (cr = Y.fb)(), Qe = n._free = (s) => (Qe = n._free = Y.gb)(s), pr = n._malloc = (s) => (pr = n._malloc = Y.hb)(s), An = (s, l, h, y, w, A) => (An = Y.kb)(s, l, h, y, w, A), Bi = () => (Bi = Y.lb)(), Di = (s, l, h, y, w) => (Di = Y.mb)(s, l, h, y, w), Mi = (s) => (Mi = Y.nb)(s), En = (s) => (En = Y.ob)(s), Ri = (s, l) => (Ri = Y.pb)(s, l), Ui = () => (Ui = Y.qb)(), Ni = (s, l) => (Ni = Y.rb)(s, l), mr = (s) => (mr = Y.sb)(s), kn = (s) => (kn = Y.tb)(s), Pn = () => (Pn = Y.ub)(), Vi = n.dynCall_ii = (s, l) => (Vi = n.dynCall_ii = Y.vb)(s, l), Wi = (s) => (Wi = Y.wb)(s), Li = () => (Li = Y.xb)(), Gi = (s) => (Gi = Y.yb)(s), Hi = () => (Hi = Y.zb)();
+ return n.stackSave = () => Pn(), n.stackRestore = (s) => mr(s), n.stackAlloc = (s) => kn(s), n.setValue = function(s, l, h = "i8") {
+ switch (h.endsWith("*") && (h = "*"), h) {
+ case "i1":
+ case "i8":
+ ue()[s >>> 0] = l;
+ break;
+ case "i16":
+ ye()[s >>> 1 >>> 0] = l;
+ break;
+ case "i32":
+ C()[s >>> 2 >>> 0] = l;
+ break;
+ case "i64":
+ Z[s >>> 3] = BigInt(l);
+ break;
+ case "float":
+ de()[s >>> 2 >>> 0] = l;
+ break;
+ case "double":
+ ze()[s >>> 3 >>> 0] = l;
+ break;
+ case "*":
+ V()[s >>> 2 >>> 0] = l;
+ break;
+ default:
+ dt(`invalid type for setValue: ${h}`);
+ }
+ }, n.getValue = function(s, l = "i8") {
+ switch (l.endsWith("*") && (l = "*"), l) {
+ case "i1":
+ case "i8":
+ return ue()[s >>> 0];
+ case "i16":
+ return ye()[s >>> 1 >>> 0];
+ case "i32":
+ return C()[s >>> 2 >>> 0];
+ case "i64":
+ return Z[s >>> 3];
+ case "float":
+ return de()[s >>> 2 >>> 0];
+ case "double":
+ return ze()[s >>> 3 >>> 0];
+ case "*":
+ return V()[s >>> 2 >>> 0];
+ default:
+ dt(`invalid type for getValue: ${l}`);
+ }
+ }, n.UTF8ToString = Te, n.stringToUTF8 = zt, n.lengthBytesUTF8 = Ko, (function s() {
+ if (0 < Pt) Lt = s;
+ else if (u) t(n), _t();
+ else {
+ for (; 0 < mn.length; ) mn.shift()(n);
+ 0 < Pt ? Lt = s : (n.calledRun = true, te || (_t(), t(n)));
+ }
+ })(), n.PTR_SIZE = 4, o;
+ }), Fp = Sa, qp = globalThis.self?.name?.startsWith("em-pthread");
+ qp && Sa();
+});
+var Ea;
+var Gn;
+var jp;
+var Ue;
+var ka;
+var Ln;
+var Kp;
+var Zp;
+var Pa;
+var Qp;
+var Ca;
+var za;
+var Aa;
+var Oa;
+var _r = U(() => {
+ "use strict";
+ yr();
+ Ea = typeof location > "u" ? void 0 : location.origin, Gn = import.meta.url > "file:" && import.meta.url < "file;", jp = () => {
+ if (true) {
+ if (Gn) {
+ let e = URL;
+ return new URL(new e("ort.bundle.min.mjs", import.meta.url).href, Ea).href;
+ }
+ return import.meta.url;
+ }
+ }, Ue = jp(), ka = () => {
+ if (Ue && !Ue.startsWith("blob:")) return Ue.substring(0, Ue.lastIndexOf("/") + 1);
+ }, Ln = (e, t) => {
+ try {
+ let r = t ?? Ue;
+ return (r ? new URL(e, r) : new URL(e)).origin === Ea;
+ } catch {
+ return false;
+ }
+ }, Kp = (e, t) => {
+ let r = t ?? Ue;
+ try {
+ return (r ? new URL(e, r) : new URL(e)).href;
+ } catch {
+ return;
+ }
+ }, Zp = (e, t) => `${t ?? "./"}${e}`, Pa = async (e) => {
+ let r = await (await fetch(e, { credentials: "same-origin" })).blob();
+ return URL.createObjectURL(r);
+ }, Qp = async (e) => (await import(
+ /*webpackIgnore:true*/
+ e
+ )).default, Ca = (xa(), Ft($a)).default, za = async () => {
+ if (!Ue) throw new Error("Failed to load proxy worker: cannot determine the script source URL.");
+ if (Ln(Ue)) return [void 0, Ca()];
+ let e = await Pa(Ue);
+ return [e, Ca(e)];
+ }, Aa = (Ia(), Ft(Ta)).default, Oa = async (e, t, r) => {
+ if (!e && !t && Aa && Ue && Ln(Ue)) return [void 0, Aa];
+ {
+ let n = "ort-wasm-simd-threaded.jsep.mjs", o = e ?? Kp(n, t), i = r && o && !Ln(o, t), a = i ? await Pa(o) : o ?? Zp(n, t);
+ return [i ? a : void 0, await Qp(a)];
+ }
+ };
+});
+var Hn;
+var Fn;
+var Ar;
+var Ba;
+var Yp;
+var Xp;
+var Jp;
+var wr;
+var fe;
+var ht = U(() => {
+ "use strict";
+ _r();
+ Fn = false, Ar = false, Ba = false, Yp = () => {
+ if (typeof SharedArrayBuffer > "u") return false;
+ 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 false;
+ }
+ }, Xp = () => {
+ 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 false;
+ }
+ }, Jp = () => {
+ try {
+ return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 19, 1, 17, 0, 65, 1, 253, 15, 65, 2, 253, 15, 65, 3, 253, 15, 253, 147, 2, 11]));
+ } catch {
+ return false;
+ }
+ }, wr = async (e) => {
+ if (Fn) return Promise.resolve();
+ if (Ar) throw new Error("multiple calls to 'initializeWebAssembly()' detected.");
+ if (Ba) throw new Error("previous call to 'initializeWebAssembly()' failed.");
+ Ar = true;
+ let t = e.initTimeout, r = e.numThreads;
+ if (e.simd !== false) {
+ if (e.simd === "relaxed") {
+ if (!Jp()) throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.");
+ } else if (!Xp()) throw new Error("WebAssembly SIMD is not supported in the current environment.");
+ }
+ let n = Yp();
+ r > 1 && !n && (typeof self < "u" && !self.crossOriginIsolated && console.warn("env.wasm.numThreads is set to " + r + ", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."), console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."), e.numThreads = r = 1);
+ let o = e.wasmPaths, i = typeof o == "string" ? o : void 0, a = o?.mjs, u = a?.href ?? a, d = o?.wasm, c = d?.href ?? d, p = e.wasmBinary, [m, f] = await Oa(u, i, r > 1), b = false, g = [];
+ if (t > 0 && g.push(new Promise((_) => {
+ setTimeout(() => {
+ b = true, _();
+ }, t);
+ })), g.push(new Promise((_, S) => {
+ let $ = { numThreads: r };
+ if (p) $.wasmBinary = p;
+ else if (c || i) $.locateFile = (v) => c ?? i + v;
+ else if (u && u.indexOf("blob:") !== 0) $.locateFile = (v) => new URL(v, u).href;
+ else if (m) {
+ let v = ka();
+ v && ($.locateFile = (x) => v + x);
+ }
+ f($).then((v) => {
+ Ar = false, Fn = true, Hn = v, _(), m && URL.revokeObjectURL(m);
+ }, (v) => {
+ Ar = false, Ba = true, S(v);
+ });
+ })), await Promise.race(g), b) throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`);
+ }, fe = () => {
+ if (Fn && Hn) return Hn;
+ throw new Error("WebAssembly is not initialized yet.");
+ };
+});
+var Ne;
+var Kt;
+var pe;
+var Er = U(() => {
+ "use strict";
+ ht();
+ Ne = (e, t) => {
+ let r = fe(), n = r.lengthBytesUTF8(e) + 1, o = r._malloc(n);
+ return r.stringToUTF8(e, o, n), t.push(o), o;
+ }, Kt = (e, t, r, n) => {
+ if (typeof e == "object" && e !== null) {
+ if (r.has(e)) throw new Error("Circular reference in options");
+ r.add(e);
+ }
+ Object.entries(e).forEach(([o, i]) => {
+ let a = t ? t + o : o;
+ if (typeof i == "object") Kt(i, a + ".", r, n);
+ else if (typeof i == "string" || typeof i == "number") n(a, i.toString());
+ else if (typeof i == "boolean") n(a, i ? "1" : "0");
+ else throw new Error(`Can't handle extra config type: ${typeof i}`);
+ });
+ }, pe = (e) => {
+ let t = fe(), r = t.stackSave();
+ try {
+ let n = t.PTR_SIZE, o = t.stackAlloc(2 * n);
+ t._OrtGetLastError(o, o + n);
+ let i = Number(t.getValue(o, n === 4 ? "i32" : "i64")), a = t.getValue(o + n, "*"), u = a ? t.UTF8ToString(a) : "";
+ throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${u}`);
+ } finally {
+ t.stackRestore(r);
+ }
+ };
+});
+var Da;
+var Ma = U(() => {
+ "use strict";
+ ht();
+ Er();
+ Da = (e) => {
+ let t = fe(), r = 0, n = [], o = e || {};
+ try {
+ if (e?.logSeverityLevel === void 0) o.logSeverityLevel = 2;
+ else if (typeof e.logSeverityLevel != "number" || !Number.isInteger(e.logSeverityLevel) || e.logSeverityLevel < 0 || e.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);
+ if (e?.logVerbosityLevel === void 0) o.logVerbosityLevel = 0;
+ else if (typeof e.logVerbosityLevel != "number" || !Number.isInteger(e.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);
+ e?.terminate === void 0 && (o.terminate = false);
+ let i = 0;
+ return e?.tag !== void 0 && (i = Ne(e.tag, n)), r = t._OrtCreateRunOptions(o.logSeverityLevel, o.logVerbosityLevel, !!o.terminate, i), r === 0 && pe("Can't create run options."), e?.extra !== void 0 && Kt(e.extra, "", /* @__PURE__ */ new WeakSet(), (a, u) => {
+ let d = Ne(a, n), c = Ne(u, n);
+ t._OrtAddRunConfigEntry(r, d, c) !== 0 && pe(`Can't set a run config entry: ${a} - ${u}.`);
+ }), [r, n];
+ } catch (i) {
+ throw r !== 0 && t._OrtReleaseRunOptions(r), n.forEach((a) => t._free(a)), i;
+ }
+ };
+});
+var em;
+var tm;
+var rm;
+var kr;
+var nm;
+var Ra;
+var Ua = U(() => {
+ "use strict";
+ ht();
+ Er();
+ em = (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}`);
+ }
+ }, tm = (e) => {
+ switch (e) {
+ case "sequential":
+ return 0;
+ case "parallel":
+ return 1;
+ default:
+ throw new Error(`unsupported execution mode: ${e}`);
+ }
+ }, rm = (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 = false);
+ }, kr = (e, t, r, n) => {
+ let o = Ne(t, n), i = Ne(r, n);
+ fe()._OrtAddSessionConfigEntry(e, o, i) !== 0 && pe(`Can't set a session config entry: ${t} - ${r}.`);
+ }, nm = async (e, t, r) => {
+ for (let n of t) {
+ let o = typeof n == "string" ? n : n.name, i = [];
+ switch (o) {
+ case "webnn":
+ if (o = "WEBNN", typeof n != "string") {
+ let m = n?.deviceType;
+ m && kr(e, "deviceType", m, r);
+ }
+ break;
+ case "webgpu":
+ if (o = "JS", typeof n != "string") {
+ let p = n;
+ if (p?.preferredLayout) {
+ if (p.preferredLayout !== "NCHW" && p.preferredLayout !== "NHWC") throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);
+ kr(e, "preferredLayout", p.preferredLayout, r);
+ }
+ }
+ break;
+ case "wasm":
+ case "cpu":
+ continue;
+ default:
+ throw new Error(`not supported execution provider: ${o}`);
+ }
+ let a = Ne(o, r), u = i.length, d = 0, c = 0;
+ if (u > 0) {
+ d = fe()._malloc(u * fe().PTR_SIZE), r.push(d), c = fe()._malloc(u * fe().PTR_SIZE), r.push(c);
+ for (let p = 0; p < u; p++) fe().setValue(d + p * fe().PTR_SIZE, i[p][0], "*"), fe().setValue(c + p * fe().PTR_SIZE, i[p][1], "*");
+ }
+ await fe()._OrtAppendExecutionProvider(e, a, d, c, u) !== 0 && pe(`Can't append execution provider: ${o}.`);
+ }
+ }, Ra = async (e) => {
+ let t = fe(), r = 0, n = [], o = e || {};
+ rm(o);
+ try {
+ let i = em(o.graphOptimizationLevel ?? "all"), a = tm(o.executionMode ?? "sequential"), u = typeof o.logId == "string" ? Ne(o.logId, n) : 0, d = o.logSeverityLevel ?? 2;
+ if (!Number.isInteger(d) || d < 0 || d > 4) throw new Error(`log serverity level is not valid: ${d}`);
+ let c = o.logVerbosityLevel ?? 0;
+ if (!Number.isInteger(c) || c < 0 || c > 4) throw new Error(`log verbosity level is not valid: ${c}`);
+ let p = typeof o.optimizedModelFilePath == "string" ? Ne(o.optimizedModelFilePath, n) : 0;
+ if (r = t._OrtCreateSessionOptions(i, !!o.enableCpuMemArena, !!o.enableMemPattern, a, !!o.enableProfiling, 0, u, d, c, p), r === 0 && pe("Can't create session options."), o.executionProviders && await nm(r, o.executionProviders, n), o.enableGraphCapture !== void 0) {
+ if (typeof o.enableGraphCapture != "boolean") throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);
+ kr(r, "enableGraphCapture", o.enableGraphCapture.toString(), n);
+ }
+ if (o.freeDimensionOverrides) for (let [m, f] of Object.entries(o.freeDimensionOverrides)) {
+ if (typeof m != "string") throw new Error(`free dimension override name must be a string: ${m}`);
+ if (typeof f != "number" || !Number.isInteger(f) || f < 0) throw new Error(`free dimension override value must be a non-negative integer: ${f}`);
+ let b = Ne(m, n);
+ t._OrtAddFreeDimensionOverride(r, b, f) !== 0 && pe(`Can't set a free dimension override: ${m} - ${f}.`);
+ }
+ return o.extra !== void 0 && Kt(o.extra, "", /* @__PURE__ */ new WeakSet(), (m, f) => {
+ kr(r, m, f, n);
+ }), [r, n];
+ } catch (i) {
+ throw r !== 0 && t._OrtReleaseSessionOptions(r) !== 0 && pe("Can't release session options."), n.forEach((a) => t._free(a)), i;
+ }
+ };
+});
+var Mt;
+var Ye;
+var gt;
+var Pr;
+var Zt;
+var zr;
+var Or;
+var qn;
+var ee = U(() => {
+ "use strict";
+ Mt = (e) => {
+ switch (e) {
+ case "int8":
+ return 3;
+ case "uint8":
+ return 2;
+ case "bool":
+ return 9;
+ case "int16":
+ return 5;
+ case "uint16":
+ return 4;
+ case "int32":
+ return 6;
+ case "uint32":
+ return 12;
+ case "float16":
+ return 10;
+ case "float32":
+ return 1;
+ case "float64":
+ return 11;
+ case "string":
+ return 8;
+ case "int64":
+ return 7;
+ case "uint64":
+ return 13;
+ case "int4":
+ return 22;
+ case "uint4":
+ return 21;
+ default:
+ throw new Error(`unsupported data type: ${e}`);
+ }
+ }, Ye = (e) => {
+ switch (e) {
+ case 3:
+ return "int8";
+ case 2:
+ return "uint8";
+ case 9:
+ return "bool";
+ case 5:
+ return "int16";
+ case 4:
+ return "uint16";
+ case 6:
+ return "int32";
+ case 12:
+ return "uint32";
+ case 10:
+ return "float16";
+ case 1:
+ return "float32";
+ case 11:
+ return "float64";
+ case 8:
+ return "string";
+ case 7:
+ return "int64";
+ case 13:
+ return "uint64";
+ case 22:
+ return "int4";
+ case 21:
+ return "uint4";
+ default:
+ throw new Error(`unsupported data type: ${e}`);
+ }
+ }, gt = (e, t) => {
+ let r = [-1, 4, 1, 1, 2, 2, 4, 8, -1, 1, 2, 8, 4, 8, -1, -1, -1, -1, -1, -1, -1, 0.5, 0.5][e], n = typeof t == "number" ? t : t.reduce((o, i) => o * i, 1);
+ return r > 0 ? Math.ceil(n * r) : void 0;
+ }, Pr = (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}`);
+ }
+ }, Zt = (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}`);
+ }
+ }, zr = (e) => e === "float32" || e === "float16" || e === "int32" || e === "int64" || e === "uint32" || e === "uint8" || e === "bool" || e === "uint4" || e === "int4", Or = (e) => e === "float32" || e === "float16" || e === "int32" || e === "int64" || e === "uint32" || e === "uint64" || e === "int8" || e === "uint8" || e === "bool" || e === "uint4" || e === "int4", qn = (e) => {
+ switch (e) {
+ case "none":
+ return 0;
+ case "cpu":
+ return 1;
+ case "cpu-pinned":
+ return 2;
+ case "texture":
+ return 3;
+ case "gpu-buffer":
+ return 4;
+ case "ml-tensor":
+ return 5;
+ default:
+ throw new Error(`unsupported data location: ${e}`);
+ }
+ };
+});
+var Qt;
+var jn = U(() => {
+ "use strict";
+ yr();
+ Qt = async (e) => {
+ if (typeof e == "string") if (false) try {
+ let { readFile: t } = On("node:fs/promises");
+ return new Uint8Array(await t(e));
+ } catch (t) {
+ if (t.code === "ERR_FS_FILE_TOO_LARGE") {
+ let { createReadStream: r } = On("node:fs"), n = r(e), o = [];
+ for await (let i of n) o.push(i);
+ 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"), n = r ? parseInt(r, 10) : 0;
+ if (n < 1073741824) return new Uint8Array(await t.arrayBuffer());
+ {
+ if (!t.body) throw new Error(`failed to load external data file: ${e}, no response body.`);
+ let o = t.body.getReader(), i;
+ try {
+ i = new ArrayBuffer(n);
+ } catch (u) {
+ if (u instanceof RangeError) {
+ let d = Math.ceil(n / 65536);
+ i = new WebAssembly.Memory({ initial: d, maximum: d }).buffer;
+ } else throw u;
+ }
+ let a = 0;
+ for (; ; ) {
+ let { done: u, value: d } = await o.read();
+ if (u) break;
+ let c = d.byteLength;
+ new Uint8Array(i, a, c).set(d), a += c;
+ }
+ return new Uint8Array(i, 0, n);
+ }
+ }
+ else return e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : e instanceof Uint8Array ? e : new Uint8Array(e);
+ };
+});
+var om;
+var im;
+var Na;
+var Va;
+var Br;
+var am;
+var se;
+var Xe = U(() => {
+ "use strict";
+ ee();
+ om = ["V", "I", "W", "E", "F"], im = (e, t) => {
+ console.log(`[${om[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`);
+ }, Br = (e, t) => {
+ Na = e, Va = t;
+ }, am = (e, t) => {
+ let r = Zt(e), n = Zt(Na);
+ r >= n && im(r, typeof t == "function" ? t() : t);
+ }, se = (...e) => {
+ Va && am(...e);
+ };
+});
+var Kn;
+var Je;
+var k;
+var Tt;
+var Dr;
+var Wa;
+var La;
+var ne = U(() => {
+ "use strict";
+ Kn = class {
+ static calcMatMulShape(t, r) {
+ return t[1] !== r[0] ? void 0 : [t[0], r[1]];
+ }
+ }, Je = class {
+ static calcShape(t, r, n = false) {
+ let o = t.length, i = r.length;
+ if (o === 0) return r;
+ if (i === 0) return t;
+ let a = Math.max(t.length, r.length), u = new Array(a);
+ if (n) {
+ if (o < 2 || i < 2) return;
+ let d = Kn.calcMatMulShape([t[o - 2], t[o - 1]], [r[i - 2], r[i - 1]]);
+ if (d === void 0) return;
+ [u[a - 2], u[a - 1]] = d;
+ }
+ for (let d = n ? 3 : 1; d <= a; d++) {
+ let c = o - d < 0 ? 1 : t[o - d], p = i - d < 0 ? 1 : r[i - d];
+ if (c !== p && c > 1 && p > 1) return;
+ let m = Math.max(c, p);
+ if (c && p) u[a - d] = Math.max(c, p);
+ else {
+ if (m > 1) return;
+ u[a - d] = 0;
+ }
+ }
+ return u;
+ }
+ static isValidBroadcast(t, r) {
+ let n = t.length, o = r.length;
+ if (n > o) return false;
+ for (let i = 1; i <= n; i++) if (t[n - i] !== 1 && t[n - i] !== r[o - i]) return false;
+ return true;
+ }
+ }, k = class e {
+ static size(t) {
+ return e.getSizeFromDimensionRange(t, 0, t.length);
+ }
+ static convertShape(t, r = 4) {
+ let n = t.length;
+ if (n === 0) return [];
+ let o = new Array(n), i = n - 1;
+ for (; i >= 0; ) {
+ if (t[i] % r === 0) {
+ o[i] = t[i] / r;
+ break;
+ }
+ if (r % t[i] !== 0) throw new Error("cannot convert shape");
+ o[i] = 1, r /= t[i], i--;
+ }
+ for (i--; i >= 0; i--) o[i] = t[i];
+ return o;
+ }
+ static sizeFromDimension(t, r) {
+ if (r < 0 || r > t.length) throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);
+ return 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, n) {
+ let o = 1;
+ for (let i = r; i < n; i++) {
+ if (t[i] < 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");
+ o *= Number(t[i]);
+ }
+ return o;
+ }
+ static computeStrides(t) {
+ let r = t.length;
+ if (r === 0) return [];
+ if (r === 1) return [1];
+ let n = new Array(r);
+ n[r - 1] = 1, n[r - 2] = t[r - 1];
+ for (let o = r - 3; o >= 0; --o) n[o] = n[o + 1] * t[o + 1];
+ return n;
+ }
+ static normalizeAxis(t, r) {
+ if (t < -r && t >= r) throw new Error("unsupported axis for this operation.");
+ return t < 0 ? t + r : t;
+ }
+ static normalizeAxes(t, r) {
+ return t.map((n) => this.normalizeAxis(n, r ?? t.length));
+ }
+ static sortBasedOnPerm(t, r) {
+ return r ? r.map((n) => t[n]) : t.slice().reverse();
+ }
+ static padShape(t, r) {
+ let n = t.length;
+ return t.map((o, i) => o + r[i] + r[i + n]);
+ }
+ static areEqual(t, r) {
+ return t.length !== r.length ? false : t.every((n, o) => n === r[o]);
+ }
+ }, Tt = class e {
+ static adjustPoolAttributes(t, r, n, o, i, a) {
+ if (!t && n.length !== r.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");
+ if (t) for (let u = 0; u < r.length - 2; u++) u >= n.length ? n.push(r[u + 2]) : n[u] = r[u + 2];
+ for (let u = 0; u < n.length; u++) if (u < o.length) {
+ if (o[u] < 0) throw new Error("strides should be greater than or equal to 1");
+ } else o.push(1);
+ for (let u = 0; u < n.length; u++) if (u < i.length) {
+ if (i[u] < 0) throw new Error("dilations should be greater than or equal to 1");
+ } else i.push(1);
+ for (let u = 0; u < n.length * 2; u++) if (u < a.length) {
+ if (a[u] < 0) throw new Error("pad should be greater than or equal to 1");
+ } else a.push(0);
+ for (let u = 0; u < n.length; u++) {
+ if (n[u] <= 0) throw new Error("kernel shapes need to be greater than 0");
+ if (a[u] >= n[u] || a[u + n.length] >= n[u]) throw new Error("pads should be smaller than kernel");
+ }
+ }
+ static adjustPadsBasedOnAutoPad(t, r, n, o, i, a, u) {
+ if (u) {
+ if (i.length !== 2 * (t.length - 2)) throw new Error("length of pads should be twice the length of data dimensions");
+ if (r.length !== t.length - 2) throw new Error("length of strides should be the length of data dimensions");
+ if (o.length !== t.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions");
+ for (let d = 0; d < t.length - 2; d++) e.adjustPadAndReturnShape(t[d + (a ? 1 : 2)], r[d], n[d], o[d], i, d, d + t.length - 2, u);
+ }
+ }
+ static computePoolOutputShape(t, r, n, o, i, a, u) {
+ if (r.length <= 0) throw new Error("input shape must be of size greater than 0");
+ let d = [r[0], r[1]];
+ return e.computeShapeHelper(t, r, d, n, o, i, a, u), d;
+ }
+ static computeConvOutputShape(t, r, n, o, i, a, u) {
+ if (t.length <= 0 || r.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims");
+ let d = [t[0], r[0]];
+ return e.computeShapeHelper(false, t, d, n, o, i, a, u), d;
+ }
+ static computeShapeHelper(t, r, n, o, i, a, u, d) {
+ if (t) for (let c = 0; c < r.length - 2; c++) n.push(1);
+ else for (let c = 0; c < r.length - 2; c++) n.push(e.adjustPadAndReturnShape(r[c + 2], o[c], i[c], a[c], u, c, c + r.length - 2, d));
+ }
+ static adjustPadAndReturnShape(t, r, n, o, i, a, u, d) {
+ let c = n * (o - 1) + 1;
+ if (d && d !== "NOTSET") switch (d) {
+ case "VALID":
+ return i[a] = 0, i[u] = 0, Math.floor((t - c) / r + 1);
+ case "SAME_LOWER":
+ case "SAME_UPPER":
+ if (n !== 1) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");
+ {
+ let m = ((t + r - 1) / r - 1) * r + o - t;
+ return i[a] = Math.floor(d === "SAME_LOWER" ? (m + 1) / 2 : m / 2), i[u] = m - i[a], Math.floor((t + m - o) / r + 1);
+ }
+ default:
+ throw new Error("Unsupported AutoPad type");
+ }
+ else return Math.floor((t + i[a] + i[u] - c) / r + 1);
+ }
+ }, Dr = class {
+ static getShapeOfGemmResult(t, r, n, o, i) {
+ if (t.length !== 2 || n.length !== 2) throw new Error("shape need to be of size 2");
+ let a, u, d;
+ r ? (a = t[1], u = t[0]) : (a = t[0], u = t[1]);
+ let c = -1;
+ if (o ? (d = n[0], c = 1) : (d = n[1], c = 0), n[c] !== u) throw new Error("dimension mismatch");
+ if (a <= 0 || d <= 0 || u <= 0) throw new Error("invalid shape specified");
+ if (i && !Je.isValidBroadcast(i, [a, d])) throw new Error("gemm: invalid bias shape for broadcast");
+ return [a, d, u];
+ }
+ }, Wa = -34028234663852886e22, La = 34028234663852886e22;
+});
+var Mr;
+var Zn = U(() => {
+ "use strict";
+ ee();
+ Mr = (e, t) => new (Pr(t))(e);
+});
+var Yn;
+var Ha;
+var sm;
+var Ga;
+var um;
+var Fa;
+var Rr;
+var Ur;
+var Qn;
+var qa;
+var ja = U(() => {
+ "use strict";
+ Xe();
+ Yn = (e, t = true) => {
+ if (e.byteLength % 8 !== 0) throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");
+ let r = e.byteLength / 8, n = new BigInt64Array(e.buffer, e.byteOffset, r), o = new Int32Array(r);
+ for (let i = 0; i < r; i++) {
+ let a = n[i];
+ if (a > 2147483647n || a < -2147483648n) throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${i}: ${a}`);
+ o[i] = Number(a);
+ }
+ return t ? new Uint8Array(o.buffer) : o;
+ }, Ha = (e, t = true) => {
+ if (e.byteLength % 4 !== 0) throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");
+ let r = e.byteLength / 4, n = new Int32Array(e.buffer, e.byteOffset, r), o = BigInt64Array.from(n, BigInt);
+ return t ? new Uint8Array(o.buffer) : o;
+ }, sm = 1, Ga = () => sm++, um = /* @__PURE__ */ new Map([["float32", 32], ["float16", 16], ["int32", 32], ["uint32", 32], ["int64", 64], ["uint64", 64], ["int8", 8], ["uint8", 8], ["int4", 4], ["uint4", 4]]), Fa = (e, t) => {
+ let r = um.get(e);
+ if (!r) throw new Error("Unsupported data type.");
+ return t.length > 0 ? Math.ceil(t.reduce((n, o) => n * o) * r / 8) : 0;
+ }, Rr = class {
+ constructor(t) {
+ this.shouldConvertInt64toInt32 = false;
+ this.isInt64ToInt32Converted = false;
+ let { sessionId: r, context: n, tensor: o, dataType: i, shape: a, shouldConvertInt64toInt32: u = false } = t;
+ this.sessionId = r, this.mlContext = n, this.mlTensor = o, this.dataType = i, this.tensorShape = a, this.shouldConvertInt64toInt32 = u;
+ }
+ get tensor() {
+ return this.mlTensor;
+ }
+ get type() {
+ return this.dataType;
+ }
+ get shape() {
+ return this.tensorShape;
+ }
+ get byteLength() {
+ return Fa(this.dataType, this.tensorShape);
+ }
+ destroy() {
+ se("verbose", () => "[WebNN] TensorWrapper.destroy"), this.mlTensor.destroy();
+ }
+ write(t) {
+ this.mlContext.writeTensor(this.mlTensor, t);
+ }
+ async read(t, r) {
+ if (t) {
+ let n = await this.mlContext.readTensor(this.mlTensor), o = Ha(new Uint8Array(n));
+ if (r) {
+ (r instanceof ArrayBuffer ? new Uint8Array(r) : new Uint8Array(r.buffer, r.byteOffset, r.byteLength)).set(o);
+ return;
+ } else return o.buffer;
+ } else return r ? this.mlContext.readTensor(this.mlTensor, r) : this.mlContext.readTensor(this.mlTensor);
+ }
+ canReuseTensor(t, r, n) {
+ return this.mlContext === t && this.dataType === r && this.tensorShape.length === n.length && this.tensorShape.every((o, i) => o === n[i]);
+ }
+ setIsInt64ToInt32Converted(t) {
+ this.isInt64ToInt32Converted = t;
+ }
+ }, Ur = class {
+ constructor(t, r) {
+ this.tensorManager = t;
+ this.wrapper = r;
+ }
+ get tensorWrapper() {
+ return this.wrapper;
+ }
+ releaseTensor() {
+ this.tensorWrapper && (this.tensorManager.releaseTensor(this.tensorWrapper), this.wrapper = void 0);
+ }
+ async ensureTensor(t, r, n, o) {
+ let i = r, a = this.tensorManager.getMLContext(t), u = i === "int64" && !a.opSupportLimits().input.dataTypes.includes("int64");
+ if (u && (i = "int32", se("verbose", () => "[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")), this.wrapper) {
+ if (this.wrapper.canReuseTensor(a, i, n)) return this.wrapper.tensor;
+ if (o) {
+ if (this.wrapper.byteLength !== Fa(i, n)) throw new Error("Unable to copy data to tensor with different size.");
+ this.activeUpload = new Uint8Array(await this.wrapper.read());
+ }
+ this.tensorManager.releaseTensor(this.wrapper);
+ }
+ let d = typeof MLTensorUsage > "u" ? void 0 : MLTensorUsage.READ | MLTensorUsage.WRITE;
+ return this.wrapper = await this.tensorManager.getCachedTensor(t, i, n, d, true, true, u), o && this.activeUpload && (this.wrapper.write(this.activeUpload), this.activeUpload = void 0), this.wrapper.tensor;
+ }
+ upload(t) {
+ let r = t;
+ if (this.wrapper) if (this.wrapper.shouldConvertInt64toInt32 && (r = Yn(t, true), this.wrapper.setIsInt64ToInt32Converted(true)), r.byteLength === this.wrapper.byteLength) {
+ this.wrapper.write(r);
+ return;
+ } else se("verbose", () => "Data size does not match tensor size. Releasing tensor."), this.releaseTensor();
+ this.activeUpload ? this.activeUpload.set(r) : this.activeUpload = new Uint8Array(r);
+ }
+ async download(t) {
+ if (this.activeUpload) {
+ let r = this.wrapper?.isInt64ToInt32Converted ? Ha(this.activeUpload) : this.activeUpload;
+ if (t) {
+ t instanceof ArrayBuffer ? new Uint8Array(t).set(r) : new Uint8Array(t.buffer, t.byteOffset, t.byteLength).set(r);
+ return;
+ } else return r.buffer;
+ }
+ if (!this.wrapper) throw new Error("Tensor has not been created.");
+ return t ? this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32, t) : this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32);
+ }
+ }, Qn = class {
+ constructor(t) {
+ this.backend = t;
+ this.tensorTrackersById = /* @__PURE__ */ new Map();
+ this.freeTensors = [];
+ this.externalTensors = /* @__PURE__ */ new Set();
+ }
+ getMLContext(t) {
+ let r = this.backend.getMLContext(t);
+ if (!r) throw new Error("MLContext not found for session.");
+ return r;
+ }
+ reserveTensorId() {
+ let t = Ga();
+ return this.tensorTrackersById.set(t, new Ur(this)), t;
+ }
+ releaseTensorId(t) {
+ let r = this.tensorTrackersById.get(t);
+ r && (this.tensorTrackersById.delete(t), r.tensorWrapper && this.releaseTensor(r.tensorWrapper));
+ }
+ async ensureTensor(t, r, n, o, i) {
+ se("verbose", () => `[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${n}, shape: ${o}, copyOld: ${i}}`);
+ let a = this.tensorTrackersById.get(r);
+ if (!a) throw new Error("Tensor not found.");
+ return a.ensureTensor(t, n, o, i);
+ }
+ upload(t, r) {
+ let n = this.tensorTrackersById.get(t);
+ if (!n) throw new Error("Tensor not found.");
+ n.upload(r);
+ }
+ async download(t, r) {
+ se("verbose", () => `[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);
+ let n = this.tensorTrackersById.get(t);
+ if (!n) throw new Error("Tensor not found.");
+ return n.download(r);
+ }
+ releaseTensorsForSession(t) {
+ for (let r of this.freeTensors) r.sessionId === t && r.destroy();
+ this.freeTensors = this.freeTensors.filter((r) => r.sessionId !== t);
+ }
+ registerTensor(t, r, n, o) {
+ let i = this.getMLContext(t), a = Ga(), u = new Rr({ sessionId: t, context: i, tensor: r, dataType: n, shape: o });
+ return this.tensorTrackersById.set(a, new Ur(this, u)), this.externalTensors.add(u), a;
+ }
+ async getCachedTensor(t, r, n, o, i, a, u = false) {
+ let d = this.getMLContext(t);
+ for (let [p, m] of this.freeTensors.entries()) if (m.canReuseTensor(d, r, n)) {
+ se("verbose", () => `[WebNN] Reusing tensor {dataType: ${r}, shape: ${n}}`);
+ let f = this.freeTensors.splice(p, 1)[0];
+ return f.sessionId = t, f;
+ }
+ se("verbose", () => `[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${n}}`);
+ let c = await d.createTensor({ dataType: r, shape: n, dimensions: n, usage: o, writable: i, readable: a });
+ return new Rr({ sessionId: t, context: d, tensor: c, dataType: r, shape: n, shouldConvertInt64toInt32: u });
+ }
+ releaseTensor(t) {
+ this.externalTensors.has(t) && this.externalTensors.delete(t), this.freeTensors.push(t);
+ }
+ }, qa = (...e) => new Qn(...e);
+});
+var Xn;
+var dm;
+var Nr;
+var Ka = U(() => {
+ "use strict";
+ ee();
+ ht();
+ Zn();
+ ja();
+ Xe();
+ Xn = /* @__PURE__ */ new Map([[1, "float32"], [10, "float16"], [6, "int32"], [12, "uint32"], [7, "int64"], [13, "uint64"], [22, "int4"], [21, "uint4"], [3, "int8"], [2, "uint8"], [9, "uint8"]]), dm = (e, t) => {
+ if (e === t) return true;
+ if (e === void 0 || t === void 0) return false;
+ let r = Object.keys(e).sort(), n = Object.keys(t).sort();
+ return r.length === n.length && r.every((o, i) => o === n[i] && e[o] === t[o]);
+ }, Nr = class {
+ constructor(t) {
+ this.tensorManager = qa(this);
+ this.mlContextBySessionId = /* @__PURE__ */ new Map();
+ this.sessionIdsByMLContext = /* @__PURE__ */ new Map();
+ this.mlContextCache = [];
+ this.sessionGraphInputs = /* @__PURE__ */ new Map();
+ this.temporaryGraphInputs = [];
+ this.temporarySessionTensorIds = /* @__PURE__ */ new Map();
+ Br(t.logLevel, !!t.debug);
+ }
+ get currentSessionId() {
+ if (this.activeSessionId === void 0) throw new Error("No active session");
+ return this.activeSessionId;
+ }
+ onRunStart(t) {
+ se("verbose", () => `[WebNN] onRunStart {sessionId: ${t}}`), this.activeSessionId = t;
+ }
+ onRunEnd(t) {
+ se("verbose", () => `[WebNN] onRunEnd {sessionId: ${t}}`);
+ let r = this.temporarySessionTensorIds.get(t);
+ if (r) {
+ for (let n of r) se("verbose", () => `[WebNN] releasing temporary tensor {tensorId: ${n}}`), this.tensorManager.releaseTensorId(n);
+ this.temporarySessionTensorIds.delete(t), this.activeSessionId = void 0;
+ }
+ }
+ async createMLContext(t) {
+ if (t instanceof GPUDevice) {
+ let n = this.mlContextCache.findIndex((o) => o.gpuDevice === t);
+ if (n !== -1) return this.mlContextCache[n].mlContext;
+ {
+ let o = await navigator.ml.createContext(t);
+ return this.mlContextCache.push({ gpuDevice: t, mlContext: o }), o;
+ }
+ } else if (t === void 0) {
+ let n = this.mlContextCache.findIndex((o) => o.options === void 0 && o.gpuDevice === void 0);
+ if (n !== -1) return this.mlContextCache[n].mlContext;
+ {
+ let o = await navigator.ml.createContext();
+ return this.mlContextCache.push({ mlContext: o }), o;
+ }
+ }
+ let r = this.mlContextCache.findIndex((n) => dm(n.options, t));
+ if (r !== -1) return this.mlContextCache[r].mlContext;
+ {
+ let n = await navigator.ml.createContext(t);
+ return this.mlContextCache.push({ options: t, mlContext: n }), n;
+ }
+ }
+ registerMLContext(t, r) {
+ this.mlContextBySessionId.set(t, r);
+ let n = this.sessionIdsByMLContext.get(r);
+ n || (n = /* @__PURE__ */ new Set(), this.sessionIdsByMLContext.set(r, n)), n.add(t), this.temporaryGraphInputs.length > 0 && (this.sessionGraphInputs.set(t, this.temporaryGraphInputs), this.temporaryGraphInputs = []);
+ }
+ onReleaseSession(t) {
+ this.sessionGraphInputs.delete(t);
+ let r = this.mlContextBySessionId.get(t);
+ if (!r) return;
+ this.tensorManager.releaseTensorsForSession(t), this.mlContextBySessionId.delete(t);
+ let n = this.sessionIdsByMLContext.get(r);
+ if (n.delete(t), n.size === 0) {
+ this.sessionIdsByMLContext.delete(r);
+ let o = this.mlContextCache.findIndex((i) => i.mlContext === r);
+ o !== -1 && this.mlContextCache.splice(o, 1);
+ }
+ }
+ getMLContext(t) {
+ return this.mlContextBySessionId.get(t);
+ }
+ reserveTensorId() {
+ return this.tensorManager.reserveTensorId();
+ }
+ releaseTensorId(t) {
+ se("verbose", () => `[WebNN] releaseTensorId {tensorId: ${t}}`), this.tensorManager.releaseTensorId(t);
+ }
+ async ensureTensor(t, r, n, o, i) {
+ let a = Xn.get(n);
+ if (!a) throw new Error(`Unsupported ONNX data type: ${n}`);
+ return this.tensorManager.ensureTensor(t ?? this.currentSessionId, r, a, o, i);
+ }
+ async createTemporaryTensor(t, r, n) {
+ se("verbose", () => `[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${n}}`);
+ let o = Xn.get(r);
+ if (!o) throw new Error(`Unsupported ONNX data type: ${r}`);
+ let i = this.tensorManager.reserveTensorId();
+ await this.tensorManager.ensureTensor(t, i, o, n, false);
+ let a = this.temporarySessionTensorIds.get(t);
+ return a ? a.push(i) : this.temporarySessionTensorIds.set(t, [i]), i;
+ }
+ uploadTensor(t, r) {
+ if (!fe().shouldTransferToMLTensor) throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");
+ se("verbose", () => `[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`), this.tensorManager.upload(t, r);
+ }
+ async downloadTensor(t, r) {
+ return this.tensorManager.download(t, r);
+ }
+ createMLTensorDownloader(t, r) {
+ return async () => {
+ let n = await this.tensorManager.download(t);
+ return Mr(n, r);
+ };
+ }
+ registerMLTensor(t, r, n, o) {
+ let i = Xn.get(n);
+ if (!i) throw new Error(`Unsupported ONNX data type: ${n}`);
+ let a = this.tensorManager.registerTensor(t, r, i, o);
+ return se("verbose", () => `[WebNN] registerMLTensor {tensor: ${r}, dataType: ${i}, dimensions: ${o}} -> {tensorId: ${a}}`), a;
+ }
+ registerMLConstant(t, r, n, o, i, a, u = false) {
+ if (!a) throw new Error("External mounted files are not available.");
+ let d = t;
+ t.startsWith("./") && (d = t.substring(2));
+ let c = a.get(d);
+ if (!c) throw new Error(`File with name ${d} not found in preloaded files.`);
+ if (r + n > c.byteLength) throw new Error("Out of bounds: data offset and length exceed the external file data size.");
+ let p = c.slice(r, r + n).buffer, m;
+ switch (i.dataType) {
+ case "float32":
+ m = new Float32Array(p);
+ break;
+ case "float16":
+ m = typeof Float16Array < "u" && Float16Array.from ? new Float16Array(p) : new Uint16Array(p);
+ break;
+ case "int32":
+ m = new Int32Array(p);
+ break;
+ case "uint32":
+ m = new Uint32Array(p);
+ break;
+ case "int64":
+ u ? (m = Yn(new Uint8Array(p), false), i.dataType = "int32") : m = new BigInt64Array(p);
+ break;
+ case "uint64":
+ m = new BigUint64Array(p);
+ break;
+ case "int8":
+ m = new Int8Array(p);
+ break;
+ case "int4":
+ case "uint4":
+ case "uint8":
+ m = new Uint8Array(p);
+ break;
+ default:
+ throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`);
+ }
+ return se("verbose", () => `[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${u ? "(Note: it was int64 data type and registered to int32 as workaround)" : ""}`), o.constant(i, m);
+ }
+ registerGraphInput(t) {
+ this.temporaryGraphInputs.push(t);
+ }
+ isGraphInput(t, r) {
+ let n = this.sessionGraphInputs.get(t);
+ return n ? n.includes(r) : false;
+ }
+ isInt64Supported(t) {
+ return !!this.mlContextBySessionId.get(t)?.opSupportLimits().input.dataTypes.includes("int64");
+ }
+ flush() {
+ }
+ };
+});
+var Vr = U(() => {
+ "use strict";
+});
+var Za;
+var Jn;
+var eo;
+var lm;
+var cm;
+var Qa;
+var ro;
+var to;
+var Xa;
+var Ja = U(() => {
+ "use strict";
+ Xe();
+ Vr();
+ Za = /* @__PURE__ */ new Map([[64, 250], [128, 200], [256, 200], [512, 200], [2048, 230], [4096, 200], [8192, 50], [16384, 50], [32768, 50], [65536, 50], [131072, 50], [262144, 50], [524288, 50], [1048576, 50], [2097152, 30], [4194304, 20], [8388608, 10], [12582912, 10], [16777216, 10], [26214400, 15], [33554432, 22], [44236800, 2], [58982400, 6], [67108864, 6], [134217728, 6], [167772160, 6]]), Jn = [], eo = (e) => Math.ceil(Number(e) / 16) * 16, lm = (e) => {
+ for (let t = 0; t < Jn.length; t++) {
+ let r = Jn[t];
+ if (e <= r) return r;
+ }
+ return Math.ceil(e / 16) * 16;
+ }, cm = 1, Qa = () => cm++, ro = async (e, t, r, n) => {
+ let o = eo(r), i = e.device.createBuffer({ size: o, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
+ try {
+ let a = e.getCommandEncoder();
+ e.endComputePass(), a.copyBufferToBuffer(t, 0, i, 0, o), e.flush(), await i.mapAsync(GPUMapMode.READ);
+ let u = i.getMappedRange();
+ if (n) {
+ let d = n();
+ return d.set(new Uint8Array(u, 0, r)), d;
+ } else return new Uint8Array(u.slice(0, r));
+ } finally {
+ i.destroy();
+ }
+ }, to = class {
+ constructor(t) {
+ this.backend = t;
+ this.storageCache = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.buffersPending = [], this.capturedPendingBuffers = /* @__PURE__ */ new Map();
+ for (let [r] of Za) Jn.push(r), this.freeBuffers.set(r, []), this.freeUniformBuffers.set(r, []);
+ this.sessionCount = 0;
+ }
+ upload(t, r) {
+ let n = r.buffer, o = r.byteOffset, i = r.byteLength, a = eo(i), u = this.storageCache.get(t);
+ if (!u) throw new Error("gpu data for uploading does not exist");
+ if (Number(u.originalSize) !== i) throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${i}`);
+ let d = this.backend.device.createBuffer({ mappedAtCreation: true, size: a, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC }), c = d.getMappedRange();
+ new Uint8Array(c).set(new Uint8Array(n, o, i)), d.unmap();
+ let p = this.backend.device.createCommandEncoder();
+ p.copyBufferToBuffer(d, 0, u.gpuData.buffer, 0, a), this.backend.device.queue.submit([p.finish()]), d.destroy(), se("verbose", () => `[WebGPU] GpuDataManager.upload(id=${t})`);
+ }
+ memcpy(t, r) {
+ let n = this.storageCache.get(t);
+ if (!n) throw new Error("source gpu data for memcpy does not exist");
+ let o = this.storageCache.get(r);
+ if (!o) throw new Error("destination gpu data for memcpy does not exist");
+ if (n.originalSize !== o.originalSize) throw new Error("inconsistent source and destination gpu data size");
+ let i = eo(n.originalSize), a = this.backend.getCommandEncoder();
+ this.backend.endComputePass(), a.copyBufferToBuffer(n.gpuData.buffer, 0, o.gpuData.buffer, 0, i);
+ }
+ registerExternalBuffer(t, r, n) {
+ let o;
+ if (n) {
+ if (o = n[0], t === n[1]) return se("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`), o;
+ if (this.backend.capturedCommandList.has(this.backend.currentSessionId)) throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
+ Please use the previous external buffer!`);
+ } else o = Qa();
+ return this.storageCache.set(o, { gpuData: { id: o, type: 0, buffer: t }, originalSize: r }), se("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`), o;
+ }
+ unregisterExternalBuffer(t) {
+ t !== void 0 && (this.storageCache.delete(t), se("verbose", () => `[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`));
+ }
+ create(t, r = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) {
+ let n = lm(t), o, i = (r & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE, a = (r & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM;
+ if (i || a) {
+ let c = (i ? this.freeBuffers : this.freeUniformBuffers).get(n);
+ c ? c.length > 0 ? o = c.pop() : o = this.backend.device.createBuffer({ size: n, usage: r }) : o = this.backend.device.createBuffer({ size: n, usage: r });
+ } else o = this.backend.device.createBuffer({ size: n, usage: r });
+ let u = { id: Qa(), type: 0, buffer: o };
+ return this.storageCache.set(u.id, { gpuData: u, originalSize: Number(t) }), se("verbose", () => `[WebGPU] GpuDataManager.create(size=${t}) => id=${u.id}`), u;
+ }
+ get(t) {
+ return this.storageCache.get(t)?.gpuData;
+ }
+ release(t) {
+ let r = typeof t == "bigint" ? Number(t) : t, n = this.storageCache.get(r);
+ if (!n) {
+ if (this.storageCache.size === 0) return 0;
+ throw new Error("releasing data does not exist");
+ }
+ return se("verbose", () => `[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`), this.storageCache.delete(r), this.buffersPending.push(n.gpuData.buffer), n.originalSize;
+ }
+ async download(t, r) {
+ let n = this.storageCache.get(Number(t));
+ if (!n) throw new Error("data does not exist");
+ await ro(this.backend, n.gpuData.buffer, n.originalSize, r);
+ }
+ refreshPendingBuffers() {
+ if (this.buffersPending.length !== 0) if (this.backend.sessionStatus === "default") {
+ for (let t of this.buffersPending) {
+ let r = Za.get(t.size);
+ if ((t.usage & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE) {
+ let n = this.freeBuffers.get(t.size) || [];
+ r === void 0 || n.length >= r ? t.destroy() : n.push(t);
+ } else if ((t.usage & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM) {
+ let n = this.freeUniformBuffers.get(t.size) || [];
+ r === void 0 || n.length >= r ? t.destroy() : n.push(t);
+ } else 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 = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.capturedPendingBuffers = /* @__PURE__ */ new Map();
+ }
+ onCreateSession() {
+ this.sessionCount += 1;
+ }
+ onReleaseSession(t) {
+ let r = this.capturedPendingBuffers.get(t);
+ r && (r.forEach((n) => {
+ n.destroy();
+ }), this.capturedPendingBuffers.delete(t)), this.sessionCount -= 1, this.sessionCount === 0 && (se("warning", () => "[WebGPU] Clearing webgpu buffer cache"), this.storageCache.forEach((n) => {
+ n.gpuData.buffer.destroy();
+ }), this.storageCache = /* @__PURE__ */ new Map());
+ }
+ }, Xa = (...e) => new to(...e);
+});
+var no;
+var J;
+var Se = U(() => {
+ "use strict";
+ no = 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;
+ }
+ }, J = (e) => new no(e);
+});
+var It;
+var io;
+var be;
+var Ae;
+var N;
+var ce;
+var ao;
+var Ct;
+var He;
+var F;
+var Wr;
+var P;
+var M;
+var es;
+var Lr;
+var oo;
+var ts;
+var ie = U(() => {
+ "use strict";
+ ee();
+ ne();
+ It = 64, io = (e, t) => {
+ if (t === 3) throw new Error("vec3 has same alignment as vec4, use vec4 instead");
+ switch (Number(e)) {
+ case 10:
+ return t > 1 ? `vec${t}` : "f16";
+ case 1:
+ return t > 1 ? `vec${t}` : "f32";
+ case 6:
+ return t > 1 ? `vec${t}` : "i32";
+ case 12:
+ return t > 1 ? `vec${t}` : "u32";
+ case 7:
+ if (t > 1) throw new Error("currently not supported vecX of uint64 yet");
+ return ["vec2", "i32"];
+ case 13:
+ if (t > 1) throw new Error("currently not supported vecX of uint64 yet");
+ return ["vec2", "u32"];
+ case 9:
+ if (t !== 4) throw new Error("bool must be vec4");
+ return ["u32", "vec4"];
+ case 22:
+ return "i32";
+ case 21:
+ return "u32";
+ default:
+ throw new Error(`Unknown data type: ${e}`);
+ }
+ }, be = (e, t = 1) => {
+ let r = io(e, t);
+ return typeof r == "string" ? r : r[0];
+ }, Ae = (e, t = 1) => {
+ let r = io(e, t);
+ return typeof r == "string" ? r : r[1];
+ }, N = (...e) => {
+ let t = [];
+ return e.forEach((r) => {
+ r.length !== 0 && t.push({ type: 12, data: r }, { type: 12, data: k.computeStrides(r) });
+ }), t;
+ }, ce = (e) => e % 4 === 0 ? 4 : e % 2 === 0 ? 2 : 1, ao = (e = "f32", t, r = "0") => !t || t === 1 ? `${e}(${r})` : `vec${t}<${e}>(${r})`, Ct = (e, t, r) => e === "f32" ? r : t === 1 ? `f32(${r})` : `vec${t}(${r})`, He = (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, F = (e, t, r, n) => e.startsWith("uniforms.") && r > 4 ? typeof t == "string" ? n === "f16" ? `${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]` : `${e}[(${t}) / 4][(${t}) % 4]` : n === "f16" ? `${e}[${Math.floor(t / 8)}][${Math.floor(t % 8 / 4)}][${t % 8 % 4}]` : `${e}[${Math.floor(t / 4)}][${t % 4}]` : r > 1 ? `${e}[${t}]` : e, Wr = (e, t, r, n, o) => {
+ let i = typeof r == "number", a = i ? r : r.length, u = [...new Array(a).keys()], d = a < 2 ? "u32" : a <= 4 ? `vec${a}` : `array`, c = io(t, o), p = typeof c == "string" ? c : c[1], m = typeof c == "string" ? c : c[0], f = { indices: d, value: p, storage: m, tensor: t }, b = (C) => typeof C == "string" ? C : `${C}u`, g = { offsetToIndices: false, indicesToOffset: false, broadcastedIndicesToOffset: false, set: false, setByIndices: false, get: false, getByIndices: false }, _ = i ? "uniforms." : "", S = `${_}${e}_shape`, $ = `${_}${e}_strides`, v = "";
+ for (let C = 0; C < a - 1; C++) v += `
+ let dim${C} = current / ${F($, C, a)};
+ let rest${C} = current % ${F($, C, a)};
+ indices[${C}] = dim${C};
+ current = rest${C};
+ `;
+ v += `indices[${a - 1}] = current;`;
+ let x = a < 2 ? "" : `
+ fn o2i_${e}(offset: u32) -> ${f.indices} {
+ var indices: ${f.indices};
+ var current = offset;
+ ${v}
+ return indices;
+ }`, T = (C) => (g.offsetToIndices = true, a < 2 ? C : `o2i_${e}(${C})`), E = [];
+ if (a >= 2) for (let C = a - 1; C >= 0; C--) E.push(`${F($, C, a)} * (indices[${C}])`);
+ let I = a < 2 ? "" : `
+ fn i2o_${e}(indices: ${f.indices}) -> u32 {
+ return ${E.join("+")};
+ }`, z = (C) => (g.indicesToOffset = true, a < 2 ? C : `i2o_${e}(${C})`), O = (...C) => a === 0 ? "0u" : `${f.indices}(${C.map(b).join(",")})`, D = (C, V) => a < 2 ? `${C}` : `${F(C, V, a)}`, L = (C, V, de) => a < 2 ? `${C}=${de};` : `${F(C, V, a)}=${de};`, q = {}, Q = (C, V) => {
+ g.broadcastedIndicesToOffset = true;
+ let de = `${V.name}broadcastedIndicesTo${e}Offset`;
+ if (de in q) return `${de}(${C})`;
+ let ze = [];
+ for (let ve = a - 1; ve >= 0; ve--) {
+ let $e = V.indicesGet("outputIndices", ve + V.rank - a);
+ ze.push(`${D($, ve)} * (${$e} % ${D(S, ve)})`);
+ }
+ return q[de] = `fn ${de}(outputIndices: ${V.type.indices}) -> u32 {
+ return ${ze.length > 0 ? ze.join("+") : "0u"};
+ }`, `${de}(${C})`;
+ }, W = (C, V) => (() => {
+ if (f.storage === f.value) return `${e}[${C}]=${V};`;
+ if (f.storage === "vec2" && f.value === "i32") return `${e}[${C}]=vec2(u32(${V}), select(0u, 0xFFFFFFFFu, ${V} < 0));`;
+ if (f.storage === "vec2" && f.value === "u32") return `${e}[${C}]=vec2(u32(${V}), 0u);`;
+ if (f.storage === "u32" && f.value === "vec4") return `${e}[${C}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${V}));`;
+ throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`);
+ })(), Z = (C) => (() => {
+ if (f.storage === f.value) return `${e}[${C}]`;
+ if (f.storage === "vec2" && f.value === "i32") return `i32(${e}[${C}].x)`;
+ if (f.storage === "vec2" && f.value === "u32") return `u32(${e}[${C}].x)`;
+ if (f.storage === "u32" && f.value === "vec4") return `vec4(bool(${e}[${C}] & 0xFFu), bool(${e}[${C}] & 0xFF00u), bool(${e}[${C}] & 0xFF0000u), bool(${e}[${C}] & 0xFF000000u))`;
+ throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`);
+ })(), we = a < 2 ? "" : `
+ fn get_${e}ByIndices(indices: ${f.indices}) -> ${p} {
+ return ${Z(`i2o_${e}(indices)`)};
+ }`, H = a < 2 ? "" : (() => {
+ let C = u.map((de) => `d${de}: u32`).join(", "), V = u.map((de) => `d${de}`).join(", ");
+ return `
+ fn get_${e}(${C}) -> ${p} {
+ return get_${e}ByIndices(${O(V)});
+ }`;
+ })(), j = (...C) => {
+ if (C.length !== a) throw new Error(`indices length must be ${a}`);
+ let V = C.map(b).join(",");
+ return a === 0 ? Z("0u") : a === 1 ? Z(V[0]) : (g.get = true, g.getByIndices = true, g.indicesToOffset = true, `get_${e}(${V})`);
+ }, te = (C) => a < 2 ? Z(C) : (g.getByIndices = true, g.indicesToOffset = true, `get_${e}ByIndices(${C})`), X = a < 2 ? "" : `
+ fn set_${e}ByIndices(indices: ${f.indices}, value: ${p}) {
+ ${W(`i2o_${e}(indices)`, "value")}
+ }`, ue = a < 2 ? "" : (() => {
+ let C = u.map((de) => `d${de}: u32`).join(", "), V = u.map((de) => `d${de}`).join(", ");
+ return `
+ fn set_${e}(${C}, value: ${p}) {
+ set_${e}ByIndices(${O(V)}, value);
+ }`;
+ })();
+ return { impl: () => {
+ let C = [], V = false;
+ return g.offsetToIndices && (C.push(x), V = true), g.indicesToOffset && (C.push(I), V = true), g.broadcastedIndicesToOffset && (Object.values(q).forEach((de) => C.push(de)), V = true), g.set && (C.push(ue), V = true), g.setByIndices && (C.push(X), V = true), g.get && (C.push(H), V = true), g.getByIndices && (C.push(we), V = true), !i && V && C.unshift(`const ${S} = ${f.indices}(${r.join(",")});`, `const ${$} = ${f.indices}(${k.computeStrides(r).join(",")});`), C.join(`
+`);
+ }, type: f, offsetToIndices: T, indicesToOffset: z, broadcastedIndicesToOffset: Q, indices: O, indicesGet: D, indicesSet: L, set: (...C) => {
+ if (C.length !== a + 1) throw new Error(`indices length must be ${a}`);
+ let V = C[a];
+ if (typeof V != "string") throw new Error("value must be string");
+ let de = C.slice(0, a).map(b).join(",");
+ return a === 0 ? W("0u", V) : a === 1 ? W(de[0], V) : (g.set = true, g.setByIndices = true, g.indicesToOffset = true, `set_${e}(${de}, ${V})`);
+ }, setByOffset: W, setByIndices: (C, V) => a < 2 ? W(C, V) : (g.setByIndices = true, g.indicesToOffset = true, `set_${e}ByIndices(${C}, ${V});`), get: j, getByOffset: Z, getByIndices: te, usage: n, name: e, strides: $, shape: S, rank: a };
+ }, P = (e, t, r, n = 1) => Wr(e, t, r, "input", n), M = (e, t, r, n = 1) => Wr(e, t, r, "output", n), es = (e, t, r) => Wr(e, t, r, "atomicOutput", 1), Lr = (e, t, r, n = 1) => Wr(e, t, r, "internal", n), oo = class {
+ constructor(t, r) {
+ this.normalizedDispatchGroup = t;
+ this.limits = r;
+ this.internalVariables = [];
+ this.variables = [];
+ this.uniforms = [];
+ this.variableIndex = 0;
+ }
+ guardAgainstOutOfBoundsWorkgroupSizes(t) {
+ return `if (global_idx >= ${typeof t == "number" ? `${t}u` : t}) { return; }`;
+ }
+ mainStart(t = It) {
+ let r = typeof t == "number" ? t : t[0], n = typeof t == "number" ? 1 : t[1], o = typeof t == "number" ? 1 : t[2];
+ if (r > this.limits.maxComputeWorkgroupSizeX || n > this.limits.maxComputeWorkgroupSizeY || o > this.limits.maxComputeWorkgroupSizeZ) throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);
+ if (r * n * o > this.limits.maxComputeInvocationsPerWorkgroup) throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);
+ let i = this.normalizedDispatchGroup[1] === 1 && this.normalizedDispatchGroup[2] === 1, a = i ? `@builtin(global_invocation_id) global_id : vec3,
+ @builtin(workgroup_id) workgroup_id : vec3,
+ @builtin(local_invocation_index) local_idx : u32,
+ @builtin(local_invocation_id) local_id : vec3` : `@builtin(global_invocation_id) global_id : vec3,
+ @builtin(local_invocation_id) local_id : vec3,
+ @builtin(local_invocation_index) local_idx : u32,
+ @builtin(workgroup_id) workgroup_id : vec3,
+ @builtin(num_workgroups) num_workgroups : vec3`, u = i ? `let global_idx = global_id.x;
+ let workgroup_index = workgroup_id.x;` : `let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +
+ workgroup_id.y * num_workgroups[0] + workgroup_id.x;
+ let global_idx = workgroup_index * ${r * n * o}u + local_idx;`;
+ return `@compute @workgroup_size(${r}, ${n}, ${o})
+ fn main(${a}) {
+ ${u}
+ `;
+ }
+ 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 n = t.usage === "input" ? "read" : "read_write", o = t.usage === "atomicOutput" ? "atomic" : t.type.storage;
+ return `@group(0) @binding(${r}) var ${t.name}: array<${o}>;`;
+ }
+ declareVariables(...t) {
+ return t.map((r) => this.declareVariable(r, this.variableIndex++)).join(`
+`);
+ }
+ 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, n = 1) {
+ return this.uniforms.push({ name: t, type: r, length: n }), 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: n, length: o } of this.uniforms) if (o && o > 4) n === "f16" ? t.push(`@align(16) ${r}:array, ${Math.ceil(o / 8)}>`) : t.push(`${r}:array, ${Math.ceil(o / 4)}>`);
+ else {
+ let i = o == null || o === 1 ? n : `vec${o}<${n}>`;
+ t.push(`${r}:${i}`);
+ }
+ return `
+ struct Uniforms { ${t.join(", ")} };
+ @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`;
+ }
+ get additionalImplementations() {
+ return this.uniformDeclaration() + this.variables.map((t) => t.impl()).join(`
+`) + this.internalVariables.map((t) => t.impl()).join(`
+`);
+ }
+ get variablesInfo() {
+ if (this.uniforms.length === 0) return;
+ let t = (r) => [12, 10, 1, 6][["u32", "f16", "f32", "i32"].indexOf(r)];
+ return this.uniforms.map((r) => [t(r.type), r.length ?? 1]);
+ }
+ }, ts = (e, t) => new oo(e, t);
+});
+var pm;
+var rs;
+var mm;
+var fm;
+var hm;
+var gm;
+var Ee;
+var ns;
+var os;
+var st = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ pm = (e, t) => {
+ if (!e || e.length !== 1) throw new Error("Transpose requires 1 input.");
+ if (t.length !== 0 && t.length !== e[0].dims.length) throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`);
+ }, rs = (e, t) => t.length !== 0 ? t : [...new Array(e).keys()].reverse(), mm = (e, t) => k.sortBasedOnPerm(e, rs(e.length, t)), fm = (e, t, r, n) => {
+ let o = `fn perm(i: ${n.type.indices}) -> ${r.type.indices} {
+ var a: ${r.type.indices};`;
+ for (let i = 0; i < t; ++i) o += `a[${e[i]}]=i[${i}];`;
+ return o += "return a;}";
+ }, hm = (e, t) => {
+ let r = [], n = [];
+ for (let o = 0; o < e.length; ++o) e[o] !== 1 && r.push(e[o]), e[t[o]] !== 1 && n.push(t[o]);
+ return { newShape: r, newPerm: n };
+ }, gm = (e, t) => {
+ let r = 0;
+ for (let n = 0; n < e.length; ++n) if (t[e[n]] !== 1) {
+ if (e[n] < r) return false;
+ r = e[n];
+ }
+ return true;
+ }, Ee = (e, t) => {
+ let r = e.dataType, n = e.dims.length, o = rs(n, t), i = mm(e.dims, o), a = e.dims, u = i, d = n < 2 || gm(o, e.dims), c;
+ if (d) return c = (_) => {
+ let S = P("input", r, a, 4), $ = M("output", r, u, 4);
+ return `
+ ${_.registerUniform("output_size", "u32").declareVariables(S, $)}
+ ${_.mainStart()}
+ ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ output[global_idx] = input[global_idx];
+ }`;
+ }, { name: "TransposeCopy", shaderCache: { inputDependencies: ["type"] }, getRunData: () => {
+ let _ = k.size(i);
+ return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(_ / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(_ / 4) }] };
+ }, getShaderSource: c };
+ let { newShape: p, newPerm: m } = hm(e.dims, o), f = k.areEqual(m, [2, 3, 1]), b = k.areEqual(m, [3, 1, 2]);
+ if (p.length === 2 || f || b) {
+ a = f ? [p[0], p[1] * p[2]] : b ? [p[0] * p[1], p[2]] : p, u = [a[1], a[0]];
+ let _ = 16;
+ return c = (S) => {
+ let $ = P("a", r, a.length), v = M("output", r, u.length);
+ return `
+ ${S.registerUniform("output_size", "u32").declareVariables($, v)}
+ var tile : array, ${_}>;
+ ${S.mainStart([_, _, 1])}
+ let stride = (uniforms.output_shape[1] - 1) / ${_} + 1;
+ let workgroup_id_x = workgroup_index % stride;
+ let workgroup_id_y = workgroup_index / stride;
+ let input_col = workgroup_id_y * ${_}u + local_id.x;
+ let input_row = workgroup_id_x * ${_}u + local_id.y;
+ if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {
+ tile[local_id.y][local_id.x] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)};
+ }
+ workgroupBarrier();
+
+ let output_col = workgroup_id_x * ${_}u + local_id.x;
+ let output_row = workgroup_id_y * ${_}u + local_id.y;
+ if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
+ ${v.setByIndices(`${v.type.indices}(output_row, output_col)`, "tile[local_id.x][local_id.y]")}
+ }
+ }`;
+ }, { name: "TransposeShared", shaderCache: { inputDependencies: ["type"] }, getRunData: () => {
+ let S = k.size(i);
+ return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(u[1] / _), y: Math.ceil(u[0] / _) }, programUniforms: [{ type: 12, data: S }, ...N(a, u)] };
+ }, getShaderSource: c };
+ }
+ return c = (_) => {
+ let S = P("a", r, a.length), $ = M("output", r, u.length);
+ return `
+ ${_.registerUniform("output_size", "u32").declareVariables(S, $)}
+
+ ${fm(o, n, S, $)}
+
+ ${_.mainStart()}
+ ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+
+ let indices = ${$.offsetToIndices("global_idx")};
+ let aIndices = perm(indices);
+
+ ${$.setByOffset("global_idx", S.getByIndices("aIndices"))}
+ }`;
+ }, { name: "Transpose", shaderCache: { hint: `${t}`, inputDependencies: ["rank"] }, getRunData: () => {
+ let _ = k.size(i);
+ return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(_ / 64) }, programUniforms: [{ type: 12, data: _ }, ...N(a, u)] };
+ }, getShaderSource: c };
+ }, ns = (e, t) => {
+ pm(e.inputs, t.perm), e.compute(Ee(e.inputs[0], t.perm));
+ }, os = (e) => J({ perm: e.perm });
+});
+var bm;
+var ym;
+var _m;
+var wm;
+var vm;
+var $m;
+var xm;
+var Sm;
+var Tm;
+var Im;
+var et;
+var is;
+var as;
+var ss;
+var us;
+var ds;
+var ls;
+var cs;
+var ps;
+var ms;
+var fs;
+var hs = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ Gr();
+ st();
+ bm = { 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" }, ym = { 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" }, _m = { max: "_A[offset]", min: "_A[offset]", mean: "0", sum: "0", prod: "1", sumSquare: "0", logSumExp: "0", l1: "0", l2: "0", logSum: "0" }, wm = { max: "bestValue", min: "bestValue", sum: "bestValue", prod: "bestValue", sumSquare: "bestValue", logSumExp: "log(bestValue)", l1: "bestValue", l2: "sqrt(bestValue)", logSum: "log(bestValue)" }, vm = (e, t) => {
+ let r = [];
+ for (let n = t - e; n < t; ++n) r.push(n);
+ return r;
+ }, $m = (e, t) => {
+ let r = [], n = e.length;
+ for (let i = 0; i < n; i++) t.indexOf(i) === -1 && r.push(e[i]);
+ let o = t.map((i) => e[i]);
+ return [r, o];
+ }, xm = (e, t) => {
+ let r = e.length + t.length, n = [], o = 0;
+ for (let i = 0; i < r; i++) t.indexOf(i) === -1 ? n.push(e[o++]) : n.push(1);
+ return n;
+ }, Sm = (e, t) => {
+ for (let r = 0; r < e.length; ++r) if (e[e.length - r - 1] !== t - 1 - r) return false;
+ return true;
+ }, Tm = (e, t) => {
+ let r = [];
+ if (!Sm(e, t)) {
+ for (let n = 0; n < t; ++n) e.indexOf(n) === -1 && r.push(n);
+ e.forEach((n) => r.push(n));
+ }
+ return r;
+ }, Im = (e, t, r, n, o, i, a) => {
+ let u = r[0].dims, d = k.size(i), c = k.size(a), p = P("_A", r[0].dataType, u), m = M("output", o, i), f = 64;
+ d === 1 && (f = 256);
+ let b = `
+ var aBestValues : array;
+ `, g = (_) => `
+ ${_.registerUniform("reduceSize", "u32").declareVariables(p, m)}
+ ${b}
+ fn DIV_CEIL(a : u32, b : u32) -> u32 {
+ return ((a - 1u) / b + 1u);
+ }
+ ${_.mainStart(f)}
+
+ let outputIndex = global_idx / ${f};
+ let offset = outputIndex * uniforms.reduceSize;
+
+ var bestValue = f32(${_m[n]});
+ let Length = uniforms.reduceSize;
+ for (var k = local_idx; k < Length; k = k + ${f}) {
+ let candidate = f32(${p.getByOffset("offset + k")});
+ bestValue = ${bm[n]};
+ }
+ aBestValues[local_idx] = bestValue;
+ workgroupBarrier();
+
+ var reduceSize = min(Length, ${f}u);
+ for (var currentSize = reduceSize / 2u; reduceSize > 1u;
+ currentSize = reduceSize / 2u) {
+ let interval = DIV_CEIL(reduceSize, 2u);
+ if (local_idx < currentSize) {
+ let candidate = aBestValues[local_idx + interval];
+ bestValue = ${ym[n]};
+ aBestValues[local_idx] = bestValue;
+ }
+ reduceSize = interval;
+ workgroupBarrier();
+ }
+
+ if (local_idx == 0u) {
+ ${m.setByOffset("outputIndex", `${n === "mean" ? `${m.type.storage}(bestValue / f32(uniforms.reduceSize))` : `${m.type.storage}(${wm[n]})`}`)};
+ }
+ }`;
+ return { name: e, shaderCache: { hint: `${t};${f}`, inputDependencies: ["type"] }, getShaderSource: g, getRunData: () => ({ outputs: [{ dims: i, dataType: o }], dispatchGroup: { x: d }, programUniforms: [{ type: 12, data: c }] }) };
+ }, et = (e, t, r, n) => {
+ let o = e.inputs.length === 1 ? r : so(e.inputs, r), i = o.axes;
+ i.length === 0 && !o.noopWithEmptyAxes && (i = e.inputs[0].dims.map((b, g) => g));
+ let a = k.normalizeAxes(i, e.inputs[0].dims.length), u = a, d = e.inputs[0], c = Tm(u, e.inputs[0].dims.length);
+ c.length > 0 && (d = e.compute(Ee(e.inputs[0], c), { inputs: [0], outputs: [-1] })[0], u = vm(u.length, d.dims.length));
+ let [p, m] = $m(d.dims, u), f = p;
+ o.keepDims && (f = xm(p, a)), e.compute(Im(t, o.cacheKey, [d], n, e.inputs[0].dataType, f, m), { inputs: [d] });
+ }, is = (e, t) => {
+ et(e, "ReduceMeanShared", t, "mean");
+ }, as = (e, t) => {
+ et(e, "ReduceL1Shared", t, "l1");
+ }, ss = (e, t) => {
+ et(e, "ReduceL2Shared", t, "l2");
+ }, us = (e, t) => {
+ et(e, "ReduceLogSumExpShared", t, "logSumExp");
+ }, ds = (e, t) => {
+ et(e, "ReduceMaxShared", t, "max");
+ }, ls = (e, t) => {
+ et(e, "ReduceMinShared", t, "min");
+ }, cs = (e, t) => {
+ et(e, "ReduceProdShared", t, "prod");
+ }, ps = (e, t) => {
+ et(e, "ReduceSumShared", t, "sum");
+ }, ms = (e, t) => {
+ et(e, "ReduceSumSquareShared", t, "sumSquare");
+ }, fs = (e, t) => {
+ et(e, "ReduceLogSumShared", t, "logSum");
+ };
+});
+var tt;
+var Cm;
+var Hr;
+var so;
+var rt;
+var Am;
+var Em;
+var km;
+var Pm;
+var zm;
+var Om;
+var Bm;
+var Dm;
+var Mm;
+var Rm;
+var nt;
+var gs;
+var bs;
+var ys;
+var _s;
+var ws;
+var vs;
+var $s;
+var xs;
+var Ss;
+var Ts;
+var Gr = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ hs();
+ tt = (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.");
+ }, Cm = (e) => ["", "", `var value = ${e.getByIndices("input_indices")};`, ""], Hr = (e, t, r, n, o, i, a = false, u = false) => {
+ let d = [], c = r[0].dims, p = c.length, m = k.normalizeAxes(o, p), f = !u && m.length === 0;
+ c.forEach((S, $) => {
+ f || m.indexOf($) >= 0 ? a && d.push(1) : d.push(S);
+ });
+ let b = d.length, g = k.size(d);
+ return { name: e, shaderCache: t, getShaderSource: (S) => {
+ let $ = [], v = P("_A", r[0].dataType, p), x = M("output", i, b), T = n(v, x, m), E = T[2];
+ for (let I = 0, z = 0; I < p; I++) f || m.indexOf(I) >= 0 ? (a && z++, E = `for(var j${I}: u32 = 0; j${I} < ${c[I]}; j${I}++) {
+ ${T[2].includes("last_index") ? `let last_index = j${I};` : ""}
+ ${v.indicesSet("input_indices", I, `j${I}`)}
+ ${E}
+ }`) : ($.push(`${v.indicesSet("input_indices", I, x.indicesGet("output_indices", z))};`), z++);
+ return `
+
+ ${S.registerUniform("output_size", "u32").declareVariables(v, x)}
+
+ ${S.mainStart()}
+ ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ var input_indices: ${v.type.indices};
+ let output_indices = ${x.offsetToIndices("global_idx")};
+
+ ${$.join(`
+`)}
+ ${T[0]} // init ops for reduce max/min
+ ${T[1]}
+ ${E}
+ ${T[3]}
+ ${T.length === 4 ? x.setByOffset("global_idx", "value") : T.slice(4).join(`
+`)}
+ }`;
+ }, getRunData: () => ({ outputs: [{ dims: d, dataType: i }], dispatchGroup: { x: Math.ceil(g / 64) }, programUniforms: [{ type: 12, data: g }, ...N(c, d)] }) };
+ }, so = (e, t) => {
+ let r = [];
+ return e[1].dims[0] > 0 && e[1].getBigInt64Array().forEach((n) => r.push(Number(n))), J({ axes: r, keepDims: t.keepDims, noopWithEmptyAxes: t.noopWithEmptyAxes });
+ }, rt = (e, t, r, n) => {
+ let o = e.inputs, i = o.length === 1 ? r : so(o, r);
+ e.compute(Hr(t, { hint: i.cacheKey, inputDependencies: ["rank"] }, [o[0]], i.noopWithEmptyAxes && i.axes.length === 0 ? Cm : n, i.axes, o[0].dataType, i.keepDims, i.noopWithEmptyAxes), { inputs: [0] });
+ }, Am = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceLogSum", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += ${n.getByIndices("input_indices")};`, "value = log(value);"]);
+ }, Em = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceL1", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += abs(${n.getByIndices("input_indices")});`, ""]);
+ }, km = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceL2", t, (n, o) => [`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`, "", `t = ${n.getByIndices("input_indices")}; value += (t * t);`, "value = sqrt(value);"]);
+ }, Pm = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceLogSumExp", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += exp(${n.getByIndices("input_indices")});`, "value = log(value);"]);
+ }, zm = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceMax", t, (n, o, i) => {
+ let a = [];
+ for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(n.indicesSet("input_indices", u, 0));
+ return [`${a.join(`
+`)}`, `var value = ${n.getByIndices("input_indices")};`, `value = max(value, ${n.getByIndices("input_indices")});`, ""];
+ });
+ }, Om = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceMean", t, (n, o, i) => {
+ let a = 1;
+ for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && (a *= e.inputs[0].dims[u]);
+ return ["var sum = f32(0);", "", `sum += f32(${n.getByIndices("input_indices")});`, `let value = ${o.type.value}(sum / ${a});`];
+ });
+ }, Bm = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceMin", t, (n, o, i) => {
+ let a = [];
+ for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(`input_indices[${u}] = 0;`);
+ return [`${a.join(`
+`)}`, `var value = ${n.getByIndices("input_indices")};`, `value = min(value, ${n.getByIndices("input_indices")});`, ""];
+ });
+ }, Dm = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceProd", t, (n, o) => [`var value = ${o.type.storage}(1);`, "", `value *= ${n.getByIndices("input_indices")};`, ""]);
+ }, Mm = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceSum", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += ${n.getByIndices("input_indices")};`, ""]);
+ }, Rm = (e, t) => {
+ tt(e.inputs), rt(e, "ReduceSumSquare", t, (n, o) => [`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`, "", `t = ${n.getByIndices("input_indices")}; value += t * t;`, ""]);
+ }, nt = (e, t, r) => {
+ if (t.length === 0) return r;
+ let n = 1, o = 1;
+ for (let i = 0; i < t.length; i++) t.indexOf(i) === -1 ? n *= e[i] : o *= e[i];
+ return o < 32 && n > 1024;
+ }, gs = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Om(e, t) : is(e, t);
+ }, bs = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Em(e, t) : as(e, t);
+ }, ys = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? km(e, t) : ss(e, t);
+ }, _s = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Pm(e, t) : us(e, t);
+ }, ws = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? zm(e, t) : ds(e, t);
+ }, vs = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Bm(e, t) : ls(e, t);
+ }, $s = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Dm(e, t) : cs(e, t);
+ }, xs = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Mm(e, t) : ps(e, t);
+ }, Ss = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Rm(e, t) : ms(e, t);
+ }, Ts = (e, t) => {
+ nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Am(e, t) : fs(e, t);
+ };
+});
+var Is;
+var Cs;
+var As;
+var uo;
+var Es = U(() => {
+ "use strict";
+ ee();
+ Se();
+ Gr();
+ Is = (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.");
+ }, Cs = (e, t) => {
+ Is(e.inputs);
+ let r = (n, o, i) => {
+ let a = [];
+ for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(`input_indices[${u}] = 0;`);
+ return [`${a.join(`
+`)}`, `var value = ${n.getByIndices("input_indices")};
+var best_index : i32 = 0;`, `if (${n.getByIndices("input_indices")} ${t.selectLastIndex > 0 ? "<=" : "<"} value) {
+ value = ${n.getByIndices("input_indices")};
+ best_index = i32(last_index);
+ }`, "", o.setByOffset("global_idx", "best_index")];
+ };
+ e.compute(Hr("ArgMin", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], r, [t.axis], 7, t.keepDims), { inputs: [0] });
+ }, As = (e, t) => {
+ Is(e.inputs);
+ let r = (n, o, i) => {
+ let a = [];
+ for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(`input_indices[${u}] = 0;`);
+ return [`${a.join(`
+`)}`, `var value = ${n.getByIndices("input_indices")};
+var best_index : i32 = 0;`, `if (${n.getByIndices("input_indices")} ${t.selectLastIndex > 0 ? ">=" : ">"} value) {
+ value = ${n.getByIndices("input_indices")};
+ best_index = i32(last_index);
+ }`, "", o.setByOffset("global_idx", "best_index")];
+ };
+ e.compute(Hr("argMax", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], r, [t.axis], 7, t.keepDims), { inputs: [0] });
+ }, uo = (e) => J(e);
+});
+var Um;
+var lo;
+var Nm;
+var Vm;
+var Wm;
+var Rt;
+var Lm;
+var ks;
+var Fr = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Vr();
+ ie();
+ Um = (e, t) => {
+ let r = e[0], n = e[1], o = e[2], i = e[3], a = e[4], u = e[5];
+ if (a && u) throw new Error("Attention cannot have both past and attention_bias");
+ if (r.dims.length !== 3) throw new Error('Input "input" must have 3 dimensions');
+ let d = r.dims[0], c = r.dims[1], p = r.dims[2];
+ if (o.dims.length !== 1) throw new Error('Input "bias" is expected to have 1 dimensions');
+ if (n.dims.length !== 2) throw new Error('Input "weights" is expected to have 2 dimensions');
+ if (n.dims[0] !== p) throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");
+ if (o.dims[0] !== n.dims[1]) throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');
+ let m = o.dims[0] / 3, f = m, b = f;
+ if (t.qkvHiddenSizes.length > 0) {
+ if (t.qkvHiddenSizes.length !== 3) throw new Error("qkv_hidden_sizes attribute should have 3 elements");
+ for (let x of t.qkvHiddenSizes) if (x % t.numHeads !== 0) throw new Error("qkv_hidden_sizes should be divisible by num_heads");
+ m = t.qkvHiddenSizes[0], f = t.qkvHiddenSizes[1], b = t.qkvHiddenSizes[2];
+ }
+ let g = c;
+ if (m !== f) throw new Error("qkv_hidden_sizes first element should be same as the second");
+ if (o.dims[0] !== m + f + b) throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');
+ let _ = 0;
+ if (a) {
+ if (f !== b) throw new Error('Input "past" expect k_hidden_size == v_hidden_size');
+ if (a.dims.length !== 5) throw new Error('Input "past" must have 5 dimensions');
+ if (a.dims[0] !== 2) throw new Error('Input "past" first dimension must be 2');
+ if (a.dims[1] !== d) throw new Error('Input "past" second dimension must be batch_size');
+ if (a.dims[2] !== t.numHeads) throw new Error('Input "past" third dimension must be num_heads');
+ if (a.dims[4] !== f / t.numHeads) throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');
+ t.pastPresentShareBuffer || (_ = a.dims[3]);
+ }
+ let S = g + _, $ = -1, v = 0;
+ if (i) throw new Error("Mask not supported");
+ if (a) throw new Error("past is not supported");
+ if (u) {
+ if (u.dims.length !== 4) throw new Error('Input "attention_bias" must have 4 dimensions');
+ if (u.dims[0] !== d || u.dims[1] !== t.numHeads || u.dims[2] !== c || u.dims[3] !== S) throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)');
+ }
+ return { batchSize: d, sequenceLength: c, pastSequenceLength: _, kvSequenceLength: g, totalSequenceLength: S, maxSequenceLength: $, inputHiddenSize: p, hiddenSize: m, vHiddenSize: b, headSize: Math.floor(m / t.numHeads), vHeadSize: Math.floor(b / t.numHeads), numHeads: t.numHeads, isUnidirectional: false, pastPresentShareBuffer: false, maskFilterValue: t.maskFilterValue, maskType: v, scale: t.scale, broadcastResPosBias: false, passPastInKv: false, qkvFormat: 1 };
+ }, lo = (e, t, r) => t && e ? `
+ let total_sequence_length_input = u32(${t.getByOffset("0")});
+ let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
+ let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
+ let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;
+ total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;
+ var past_sequence_length: u32 = 0;
+ if (is_first_prompt == false) {
+ past_sequence_length = total_sequence_length - sequence_length;
+ }
+ ` : `
+ ${r ? "let past_sequence_length = uniforms.past_sequence_length" : ""};
+ let present_sequence_length = total_sequence_length;
+ `, Nm = (e, t, r, n, o, i, a, u) => {
+ let d = ce(a ? 1 : i), c = 64, p = i / d;
+ p < c && (c = 32);
+ let m = Math.ceil(i / d / c), f = [{ type: 12, data: t }, { type: 12, data: r }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: p }, { type: 12, data: m }], b = be(e.dataType, d), g = Ae(1, d), _ = ["type"];
+ a && _.push("type"), u && _.push("type");
+ let S = ($) => {
+ let v = M("x", e.dataType, e.dims, d), x = [v], T = a ? P("seq_lens", a.dataType, a.dims) : void 0;
+ T && x.push(T);
+ let E = u ? P("total_sequence_length_input", u.dataType, u.dims) : void 0;
+ E && x.push(E);
+ let I = Ae(e.dataType), z = [{ name: "batch_size", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "past_sequence_length", type: "u32" }, { name: "sequence_length", type: "u32" }, { name: "total_sequence_length", type: "u32" }, { name: "elements_per_thread", type: "u32" }];
+ return `
+ var thread_max: array;
+ var thread_sum: array;
+ ${$.registerUniforms(z).declareVariables(...x)}
+ ${$.mainStart([c, 1, 1])}
+ let batchIdx = workgroup_id.z / uniforms.num_heads;
+ let headIdx = workgroup_id.z % uniforms.num_heads;
+ let sequence_length = uniforms.sequence_length;
+ var total_sequence_length = uniforms.total_sequence_length;
+ ${lo(T, E, false)}
+ let local_offset = local_idx * uniforms.elements_per_thread;
+ let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset;
+ let seq_causal_length = ${a ? "u32(past_sequence_length + workgroup_id.y + 1)" : "total_sequence_length"};
+ var thread_max_vector = ${g}(-3.402823e+38f);
+ for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
+ thread_max_vector = max(${g}(x[offset + i]), thread_max_vector);
+ }
+ thread_max[local_idx] = ${(() => {
+ switch (d) {
+ case 1:
+ return "thread_max_vector";
+ case 2:
+ return "max(thread_max_vector.x, thread_max_vector.y)";
+ case 4:
+ return "max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";
+ default:
+ throw new Error(`Unsupported components: ${d}`);
+ }
+ })()};
+ workgroupBarrier();
+
+ var max_value = f32(-3.402823e+38f);
+ for (var i = 0u; i < ${c}; i++) {
+ max_value = max(thread_max[i], max_value);
+ }
+
+ var sum_vector = ${g}(0);
+ for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
+ sum_vector += exp(${g}(x[offset + i]) - max_value);
+ }
+ thread_sum[local_idx] = ${(() => {
+ switch (d) {
+ case 1:
+ return "sum_vector";
+ case 2:
+ return "sum_vector.x + sum_vector.y";
+ case 4:
+ return "sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";
+ default:
+ throw new Error(`Unsupported components: ${d}`);
+ }
+ })()};
+ workgroupBarrier();
+
+ var sum: f32 = 0;
+ for (var i = 0u; i < ${c}; i++) {
+ sum += thread_sum[i];
+ }
+
+ if (sum == 0) {
+ for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
+ x[offset + i] = ${v.type.value}(${I}(1.0) / ${I}(seq_causal_length));
+ }
+ } else {
+ for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
+ var f32input = ${g}(x[offset + i]);
+ x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum);
+ }
+ }
+ ${a ? `
+ for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
+ x[offset + total_seq_id] = ${v.type.value}(${I}(0));
+ }` : ""};
+ }`;
+ };
+ return { name: "AttentionProbsSoftmax", shaderCache: { hint: `${c};${b};${d}`, inputDependencies: _ }, getShaderSource: S, getRunData: () => ({ outputs: [], dispatchGroup: { x: 1, y: o, z: t * r }, programUniforms: f }) };
+ }, Vm = (e, t, r, n, o, i, a, u, d) => {
+ let c = a + i.kvSequenceLength, p = [i.batchSize, i.numHeads, i.sequenceLength, c], m = e > 1 && n, f = i.kvNumHeads ? i.kvNumHeads : i.numHeads, b = m ? [i.batchSize, f, c, i.headSize] : void 0, g = i.nReps ? i.nReps : 1, _ = i.scale === 0 ? 1 / Math.sqrt(i.headSize) : i.scale, S = ce(i.headSize), $ = i.headSize / S, v = 12, x = { x: Math.ceil(c / v), y: Math.ceil(i.sequenceLength / v), z: i.batchSize * i.numHeads }, T = [{ type: 12, data: i.sequenceLength }, { type: 12, data: $ }, { type: 12, data: c }, { type: 12, data: i.numHeads }, { type: 12, data: i.headSize }, { type: 1, data: _ }, { type: 12, data: a }, { type: 12, data: i.kvSequenceLength }, { type: 12, data: g }], E = m && n && k.size(n.dims) > 0, I = ["type", "type"];
+ E && I.push("type"), o && I.push("type"), u && I.push("type"), d && I.push("type");
+ let z = [{ dims: p, dataType: t.dataType, gpuDataType: 0 }];
+ m && z.push({ dims: b, dataType: t.dataType, gpuDataType: 0 });
+ let O = (D) => {
+ let L = P("q", t.dataType, t.dims, S), q = P("key", r.dataType, r.dims, S), Q = [L, q];
+ if (E) {
+ let X = P("past_key", n.dataType, n.dims, S);
+ Q.push(X);
+ }
+ o && Q.push(P("attention_bias", o.dataType, o.dims));
+ let W = u ? P("seq_lens", u.dataType, u.dims) : void 0;
+ W && Q.push(W);
+ let Z = d ? P("total_sequence_length_input", d.dataType, d.dims) : void 0;
+ Z && Q.push(Z);
+ let we = M("output", t.dataType, p), H = [we];
+ m && H.push(M("present_key", t.dataType, b, S));
+ let j = Ae(1, S), te = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "alpha", type: "f32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }, { name: "n_reps", type: "u32" }];
+ return `
+ const TILE_SIZE = ${v}u;
+
+ var tileQ: array<${L.type.storage}, ${v * v}>;
+ var tileK: array<${L.type.storage}, ${v * v}>;
+ ${D.registerUniforms(te).declareVariables(...Q, ...H)}
+ ${D.mainStart([v, v, 1])}
+ // x holds the N and y holds the M
+ let headIdx = workgroup_id.z % uniforms.num_heads;
+ let kvHeadIdx = ${g === 1 ? "headIdx" : "headIdx / uniforms.n_reps"};
+ let kv_num_heads = ${g === 1 ? "uniforms.num_heads" : "uniforms.num_heads / uniforms.n_reps"};
+ let batchIdx = workgroup_id.z / uniforms.num_heads;
+ let m = workgroup_id.y * TILE_SIZE;
+ let n = workgroup_id.x * TILE_SIZE;
+ let sequence_length = uniforms.M;
+ var total_sequence_length = uniforms.N;
+ ${lo(W, Z, true)}
+ let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
+ let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
+ ${E && m ? "let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;" : ""};
+ let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
+ ${m ? "let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;" : ""}
+ var value = ${j}(0);
+ for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
+ if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {
+ tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];
+ }
+ if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {
+ var idx = TILE_SIZE * local_id.y + local_id.x;
+ ${E && m ? `
+ if (n + local_id.y < past_sequence_length) {
+ tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
+ } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
+ tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];
+ }` : `
+ if (n + local_id.y < uniforms.kv_sequence_length) {
+ tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
+ }`}
+ ${m ? `if (n + local_id.y < present_sequence_length) {
+ present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];
+ }` : ""}
+ }
+ workgroupBarrier();
+
+ for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {
+ value += ${j}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
+ }
+
+ workgroupBarrier();
+ }
+
+ if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {
+ let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
+ let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
+ var sum: f32 = ${(() => {
+ switch (S) {
+ case 1:
+ return "value";
+ case 2:
+ return "value.x + value.y";
+ case 4:
+ return "value.x + value.y + value.z + value.w";
+ default:
+ throw new Error(`Unsupported components: ${S}`);
+ }
+ })()};
+ output[outputIdx] = ${we.type.value} (sum * uniforms.alpha) + ${o ? "attention_bias[outputIdx]" : "0.0"};
+ }
+ }`;
+ };
+ return { name: "AttentionProbs", shaderCache: { hint: `${S};${o !== void 0};${n !== void 0};${e}`, inputDependencies: I }, getRunData: () => ({ outputs: z, dispatchGroup: x, programUniforms: T }), getShaderSource: O };
+ }, Wm = (e, t, r, n, o, i, a = void 0, u = void 0) => {
+ let d = i + o.kvSequenceLength, c = o.nReps ? o.nReps : 1, p = o.vHiddenSize * c, m = e > 1 && n, f = o.kvNumHeads ? o.kvNumHeads : o.numHeads, b = m ? [o.batchSize, f, d, o.headSize] : void 0, g = [o.batchSize, o.sequenceLength, p], _ = 12, S = { x: Math.ceil(o.vHeadSize / _), y: Math.ceil(o.sequenceLength / _), z: o.batchSize * o.numHeads }, $ = [{ type: 12, data: o.sequenceLength }, { type: 12, data: d }, { type: 12, data: o.vHeadSize }, { type: 12, data: o.numHeads }, { type: 12, data: o.headSize }, { type: 12, data: p }, { type: 12, data: i }, { type: 12, data: o.kvSequenceLength }, { type: 12, data: c }], v = m && n && k.size(n.dims) > 0, x = ["type", "type"];
+ v && x.push("type"), a && x.push("type"), u && x.push("type");
+ let T = [{ dims: g, dataType: t.dataType, gpuDataType: 0 }];
+ m && T.push({ dims: b, dataType: t.dataType, gpuDataType: 0 });
+ let E = (I) => {
+ let z = P("probs", t.dataType, t.dims), O = P("v", r.dataType, r.dims), D = [z, O];
+ v && D.push(P("past_value", n.dataType, n.dims));
+ let L = a ? P("seq_lens", a.dataType, a.dims) : void 0;
+ a && D.push(L);
+ let q = u ? P("total_sequence_length_input", u.dataType, u.dims) : void 0;
+ u && D.push(q);
+ let W = [M("output", t.dataType, g)];
+ m && W.push(M("present_value", t.dataType, b));
+ let Z = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "v_hidden_size", type: "u32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }, { name: "n_reps", type: "u32" }];
+ return `
+ const TILE_SIZE = ${_}u;
+ var tileQ: array<${z.type.value}, ${_ * _}>;
+ var tileV: array<${z.type.value}, ${_ * _}>;
+ ${I.registerUniforms(Z).declareVariables(...D, ...W)}
+ ${I.mainStart([_, _, 1])}
+ let headIdx = workgroup_id.z % uniforms.num_heads;
+ let batchIdx = workgroup_id.z / uniforms.num_heads;
+ let kvHeadIdx = ${c === 1 ? "headIdx" : "headIdx / uniforms.n_reps"};
+ let kv_num_heads = ${c === 1 ? "uniforms.num_heads" : "uniforms.num_heads / uniforms.n_reps"};
+ let m = global_id.y;
+ let n = global_id.x;
+ let sequence_length = uniforms.M;
+ var total_sequence_length = uniforms.K;
+ ${lo(L, q, true)}
+ let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
+ let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
+ ${v && m ? "let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;" : ""};
+ let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
+ ${m ? "let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;" : ""}
+ var value = ${z.type.storage}(0);
+ for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
+ if (m < uniforms.M && w + local_id.x < uniforms.K) {
+ tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];
+ }
+ if (n < uniforms.N && w + local_id.y < uniforms.K) {
+ var idx = TILE_SIZE * local_id.y + local_id.x;
+ ${v && m ? `
+ if (w + local_id.y < past_sequence_length) {
+ tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];
+ } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
+ tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];
+ }
+ ` : `
+ if (w + local_id.y < uniforms.kv_sequence_length) {
+ tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];
+ }`}
+ ${m ? `
+ if (w + local_id.y < present_sequence_length) {
+ present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];
+ }` : ""}
+ }
+ workgroupBarrier();
+ for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {
+ value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];
+ }
+ workgroupBarrier();
+ }
+
+ // we need to transpose output from BNSH_v to BSND_v
+ if (m < uniforms.M && n < uniforms.N) {
+ let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size
+ + headIdx * uniforms.N + n;
+ output[outputIdx] = value;
+ }
+ }`;
+ };
+ return { name: "AttentionScore", shaderCache: { hint: `${n !== void 0};${e}`, inputDependencies: x }, getRunData: () => ({ outputs: T, dispatchGroup: S, programUniforms: $ }), getShaderSource: E };
+ }, Rt = (e, t, r, n, o, i, a, u, d, c, p = void 0, m = void 0) => {
+ let f = Math.min(e.outputCount, 1 + (a ? 1 : 0) + (u ? 1 : 0)), b = f > 1 ? c.pastSequenceLength : 0, g = b + c.kvSequenceLength, _ = d && k.size(d.dims) > 0 ? d : void 0, S = [t, r];
+ f > 1 && a && k.size(a.dims) > 0 && S.push(a), _ && S.push(_), p && S.push(p), m && S.push(m);
+ let $ = e.compute(Vm(f, t, r, a, _, c, b, p, m), { inputs: S, outputs: f > 1 ? [-1, 1] : [-1] })[0];
+ e.compute(Nm($, c.batchSize, c.numHeads, b, c.sequenceLength, g, p, m), { inputs: p && m ? [$, p, m] : [$], outputs: [] });
+ let v = [$, n];
+ f > 1 && u && k.size(u.dims) > 0 && v.push(u), p && v.push(p), m && v.push(m), e.compute(Wm(f, $, n, u, c, b, p, m), { inputs: v, outputs: f > 1 ? [0, 2] : [0] });
+ }, Lm = (e, t) => {
+ let r = [t.batchSize, t.numHeads, t.sequenceLength, t.headSize], n = t.sequenceLength, o = t.inputHiddenSize, i = t.headSize, a = 12, u = { x: Math.ceil(t.headSize / a), y: Math.ceil(t.sequenceLength / a), z: t.batchSize * t.numHeads }, d = [e.inputs[0], e.inputs[1], e.inputs[2]], c = [{ type: 12, data: n }, { type: 12, data: o }, { type: 12, data: i }, { type: 12, data: t.numHeads }, { type: 12, data: t.headSize }, { type: 12, data: t.hiddenSize }, { type: 12, data: t.hiddenSize + t.hiddenSize + t.vHiddenSize }], p = (m) => {
+ let f = M("output_q", d[0].dataType, r), b = M("output_k", d[0].dataType, r), g = M("output_v", d[0].dataType, r), _ = P("input", d[0].dataType, d[0].dims), S = P("weight", d[1].dataType, d[1].dims), $ = P("bias", d[2].dataType, d[2].dims), v = _.type.storage, x = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "hidden_size", type: "u32" }, { name: "ldb", type: "u32" }];
+ return `
+ const TILE_SIZE = ${a}u;
+ var tileInput: array<${v}, ${a * a}>;
+ var tileWeightQ: array<${v}, ${a * a}>;
+ var tileWeightK: array<${v}, ${a * a}>;
+ var tileWeightV: array<${v}, ${a * a}>;
+ ${m.registerUniforms(x).declareVariables(_, S, $, f, b, g)}
+ ${m.mainStart([a, a, 1])}
+ let batchIndex = workgroup_id.z / uniforms.num_heads;
+ let headNumber = workgroup_id.z % uniforms.num_heads;
+ let m = global_id.y;
+ let n = global_id.x;
+
+ let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;
+ let biasOffsetQ = headNumber * uniforms.head_size;
+ let biasOffsetK = uniforms.hidden_size + biasOffsetQ;
+ let biasOffsetV = uniforms.hidden_size + biasOffsetK;
+
+ var valueQ = ${v}(0);
+ var valueK = ${v}(0);
+ var valueV = ${v}(0);
+ for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
+ if (m < uniforms.M && w + local_id.x < uniforms.K) {
+ tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];
+ }
+ if (n < uniforms.N && w + local_id.y < uniforms.K) {
+ let offset = n + (w + local_id.y) * uniforms.ldb;
+ tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];
+ tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];
+ tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];
+ }
+ workgroupBarrier();
+ for (var k: u32 = 0u; k ({ outputs: [{ dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }], dispatchGroup: u, programUniforms: c }), getShaderSource: p }, { inputs: d, outputs: [-1, -1, -1] });
+ }, ks = (e, t) => {
+ let r = Um(e.inputs, t), [n, o, i] = Lm(e, r);
+ return Rt(e, n, o, i, e.inputs[4], void 0, void 0, void 0, e.inputs[5], r);
+ };
+});
+var Gm;
+var Hm;
+var Fm;
+var Ps;
+var zs = U(() => {
+ "use strict";
+ We();
+ ee();
+ ne();
+ Se();
+ ie();
+ Gm = (e, t) => {
+ if (!e || e.length !== 5) throw new Error("BatchNormalization requires 5 inputs");
+ let r = (n, o, i) => {
+ let a = o.length;
+ if (a !== n.length) throw new Error(`${i}: num dimensions != ${a}`);
+ o.forEach((u, d) => {
+ if (u !== n[d]) throw new Error(`${i}: dim[${d}] do not match`);
+ });
+ };
+ if (e[0].dims.length > 1) {
+ let n = t.format === "NHWC" ? t.spatial ? e[0].dims.slice(-1) : e[0].dims.slice(-1).concat(e[0].dims.slice(1, e[0].dims.length - 1)) : e[0].dims.slice(1, t.spatial ? 2 : void 0);
+ r(e[1].dims, n, "Invalid input scale"), r(e[2].dims, n, "Invalid input B"), r(e[3].dims, n, "Invalid input mean"), r(e[4].dims, n, "Invalid input var");
+ } else r(e[1].dims, [1], "Invalid input scale"), r(e[2].dims, [1], "Invalid input B"), r(e[3].dims, [1], "Invalid input mean"), r(e[4].dims, [1], "Invalid input var");
+ }, Hm = (e, t) => {
+ let { epsilon: r, spatial: n, format: o } = t, i = e[0].dims, a = n ? ce(i[i.length - 1]) : 1, u = o === "NHWC" && i.length > 1 ? a : 1, d = k.size(i) / a, c = n, p = c ? i.length : i, m = P("x", e[0].dataType, e[0].dims, a), f = P("scale", e[1].dataType, e[1].dims, u), b = P("bias", e[2].dataType, e[2].dims, u), g = P("inputMean", e[3].dataType, e[3].dims, u), _ = P("inputVar", e[4].dataType, e[4].dims, u), S = M("y", e[0].dataType, p, a), $ = () => {
+ let x = "";
+ if (n) x = `let cOffset = ${i.length === 1 ? "0u" : o === "NHWC" ? `outputIndices[${i.length - 1}] / ${a}` : "outputIndices[1]"};`;
+ else if (o === "NCHW") x = `
+ ${S.indicesSet("outputIndices", "0", "0")}
+ let cOffset = ${S.indicesToOffset("outputIndices")};`;
+ else {
+ x = `var cIndices = ${f.type.indices}(0);
+ cIndices[0] = outputIndices[${i.length - 1}];`;
+ for (let T = 1; T < f.rank; T++) x += `cIndices[${T}] = outputIndices[${T}];`;
+ x += `let cOffset = ${f.indicesToOffset("cIndices")};`;
+ }
+ return x;
+ }, v = (x) => `
+ const epsilon = ${r};
+ ${x.registerUniform("outputSize", "u32").declareVariables(m, f, b, g, _, S)}
+ ${x.mainStart()}
+ ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+ var outputIndices = ${S.offsetToIndices(`global_idx * ${a}`)};
+ ${$()}
+ let scale = ${f.getByOffset("cOffset")};
+ let bias = ${b.getByOffset("cOffset")};
+ let inputMean = ${g.getByOffset("cOffset")};
+ let inputVar = ${_.getByOffset("cOffset")};
+ let x = ${m.getByOffset("global_idx")};
+ let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
+ ${S.setByOffset("global_idx", "value")}
+ }`;
+ return { name: "BatchNormalization", shaderCache: { hint: `${t.epsilon}_${t.format}_${n}_${a}`, inputDependencies: c ? ["rank", "type", "type", "type", "type"] : void 0 }, getShaderSource: v, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: c ? [{ type: 12, data: d }, ...N(i)] : [{ type: 12, data: d }] }) };
+ }, Fm = (e) => J(e), Ps = (e, t) => {
+ let { inputs: r, outputCount: n } = e, o = Fm({ ...t, outputCount: n });
+ if (ge.webgpu.validateInputContent && Gm(r, o), t.trainingMode) throw new Error("BatchNormalization trainingMode is not supported yet.");
+ e.compute(Hm(r, o));
+ };
+});
+var qm;
+var jm;
+var Os;
+var Bs = U(() => {
+ "use strict";
+ ne();
+ ie();
+ qm = (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");
+ }, jm = (e) => {
+ let t = e[0].dims, r = e[0].dims[2], n = k.size(t) / 4, o = e[0].dataType, i = P("input", o, t, 4), a = P("bias", o, [r], 4), u = P("residual", o, t, 4), d = M("output", o, t, 4);
+ return { name: "BiasAdd", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(n / 64) } }), getShaderSource: (p) => `
+ const channels = ${r}u / 4;
+ ${p.declareVariables(i, a, u, d)}
+
+ ${p.mainStart()}
+ ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)}
+ let value = ${i.getByOffset("global_idx")}
+ + ${a.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")};
+ ${d.setByOffset("global_idx", "value")}
+ }` };
+ }, Os = (e) => {
+ qm(e.inputs), e.compute(jm(e.inputs));
+ };
+});
+var Km;
+var me;
+var Ds;
+var Ms;
+var Rs;
+var Us;
+var Ns;
+var Vs;
+var Ws;
+var Ls;
+var Gs;
+var Zm;
+var Hs;
+var Fs;
+var qs;
+var js;
+var Yt;
+var Ks;
+var qr;
+var Zs;
+var Qs;
+var Ys;
+var Xs;
+var Js;
+var eu;
+var tu;
+var ru;
+var nu;
+var ou;
+var iu;
+var au;
+var su;
+var uu;
+var du;
+var lu;
+var cu;
+var pu;
+var co;
+var po;
+var mu;
+var fu;
+var hu;
+var Qm;
+var Ym;
+var gu;
+var jr = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ Km = (e, t, r, n, o, i, a) => {
+ let u = Math.ceil(t / 4), d = "";
+ typeof o == "string" ? d = `${o}(a)` : d = o("a");
+ let c = P("inputData", r, [u], 4), p = M("outputData", n, [u], 4), m = [{ name: "vec_size", type: "u32" }];
+ return a && m.push(...a), `
+ ${e.registerUniforms(m).declareVariables(c, p)}
+
+ ${i ?? ""}
+
+ ${e.mainStart()}
+ ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
+
+ let a = ${c.getByOffset("global_idx")};
+ ${p.setByOffset("global_idx", d)}
+ }`;
+ }, me = (e, t, r, n, o, i = e.dataType, a, u) => {
+ let d = [{ type: 12, data: Math.ceil(k.size(e.dims) / 4) }];
+ return a && d.push(...a), { name: t, shaderCache: { hint: o, inputDependencies: ["type"] }, getShaderSource: (c) => Km(c, k.size(e.dims), e.dataType, i, r, n, u), getRunData: (c) => ({ outputs: [{ dims: e.dims, dataType: i }], dispatchGroup: { x: Math.ceil(k.size(c[0].dims) / 64 / 4) }, programUniforms: d }) };
+ }, Ds = (e) => {
+ e.compute(me(e.inputs[0], "Abs", "abs"));
+ }, Ms = (e) => {
+ e.compute(me(e.inputs[0], "Acos", "acos"));
+ }, Rs = (e) => {
+ e.compute(me(e.inputs[0], "Acosh", "acosh"));
+ }, Us = (e) => {
+ e.compute(me(e.inputs[0], "Asin", "asin"));
+ }, Ns = (e) => {
+ e.compute(me(e.inputs[0], "Asinh", "asinh"));
+ }, Vs = (e) => {
+ e.compute(me(e.inputs[0], "Atan", "atan"));
+ }, Ws = (e) => {
+ e.compute(me(e.inputs[0], "Atanh", "atanh"));
+ }, Ls = (e) => J(e), Gs = (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(me(e.inputs[0], "Cast", r, void 0, t.cacheKey, t.to));
+ }, Zm = (e) => {
+ let t, r, n = e.length >= 2 && e[1].data !== 0, o = e.length >= 3 && e[2].data !== 0;
+ switch (e[0].dataType) {
+ case 1:
+ t = n ? e[1].getFloat32Array()[0] : -34028234663852886e22, r = o ? e[2].getFloat32Array()[0] : 34028234663852886e22;
+ break;
+ case 10:
+ t = n ? e[1].getUint16Array()[0] : 64511, r = o ? e[2].getUint16Array()[0] : 31743;
+ break;
+ default:
+ throw new Error("Unsupport data type");
+ }
+ return J({ min: t, max: r });
+ }, Hs = (e, t) => {
+ let r = t || Zm(e.inputs), n = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "Clip", (o) => `clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`, void 0, r.cacheKey, void 0, [{ type: e.inputs[0].dataType, data: r.min }, { type: e.inputs[0].dataType, data: r.max }], [{ name: "min", type: n }, { name: "max", type: n }]), { inputs: [0] });
+ }, Fs = (e) => {
+ e.compute(me(e.inputs[0], "Ceil", "ceil"));
+ }, qs = (e) => {
+ e.compute(me(e.inputs[0], "Cos", "cos"));
+ }, js = (e) => {
+ e.compute(me(e.inputs[0], "Cosh", "cosh"));
+ }, Yt = (e) => J(e), Ks = (e, t) => {
+ let r = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "Elu", (n) => `elu_vf32(${n})`, `
+ const elu_alpha_ = ${r}(${t.alpha});
+
+ fn elu_f32(a: ${r}) -> ${r} {
+ return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);
+ }
+
+ fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {
+ return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
+ }`, t.cacheKey));
+ }, qr = (e = "f32") => `
+const r0: ${e} = 0.3275911;
+const r1: ${e} = 0.254829592;
+const r2: ${e} = -0.284496736;
+const r3: ${e} = 1.421413741;
+const r4: ${e} = -1.453152027;
+const r5: ${e} = 1.061405429;
+
+fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
+ let absv = abs(v);
+ let x = 1.0 / (1.0 + r0 * absv);
+ return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
+}`, Zs = (e) => {
+ let t = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "Erf", (r) => `erf_vf32(${r})`, qr(t)));
+ }, Qs = (e) => {
+ e.compute(me(e.inputs[0], "Exp", "exp"));
+ }, Ys = (e) => {
+ e.compute(me(e.inputs[0], "Floor", "floor"));
+ }, Xs = (e) => {
+ let t = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "Gelu", (r) => `0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`, qr(t)));
+ }, Js = (e, t) => {
+ let r = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "LeakyRelu", (n) => `select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`, `const leaky_relu_alpha_ = ${r}(${t.alpha});`, t.cacheKey));
+ }, eu = (e) => {
+ e.compute(me(e.inputs[0], "Not", (t) => `!${t}`));
+ }, tu = (e) => {
+ e.compute(me(e.inputs[0], "Neg", (t) => `-${t}`));
+ }, ru = (e) => {
+ e.compute(me(e.inputs[0], "Reciprocal", (t) => `1.0/${t}`));
+ }, nu = (e) => {
+ let t = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "Relu", (r) => `select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`));
+ }, ou = (e) => {
+ e.compute(me(e.inputs[0], "Sigmoid", (t) => `(1.0 / (1.0 + exp(-${t})))`));
+ }, iu = (e) => J(e), au = (e, t) => {
+ let r = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "HardSigmoid", (n) => `max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`, void 0, t.cacheKey));
+ }, su = (e) => {
+ e.compute(me(e.inputs[0], "Sin", "sin"));
+ }, uu = (e) => {
+ e.compute(me(e.inputs[0], "Sinh", "sinh"));
+ }, du = (e) => {
+ e.compute(me(e.inputs[0], "Sqrt", "sqrt"));
+ }, lu = (e) => {
+ e.compute(me(e.inputs[0], "Tan", "tan"));
+ }, cu = (e) => `sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`, pu = (e) => {
+ e.compute(me(e.inputs[0], "Tanh", cu));
+ }, co = (e = "f32") => `
+const fast_gelu_a: ${e} = 0.5;
+const fast_gelu_b: ${e} = 0.7978845608028654;
+const fast_gelu_c: ${e} = 0.035677408136300125;
+
+fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
+ return ${cu("v")};
+}
+`, po = (e) => `(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`, mu = (e) => {
+ let t = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "FastGelu", po, co(t), void 0, e.inputs[0].dataType));
+ }, fu = (e, t) => {
+ let r = Ae(e.inputs[0].dataType);
+ return e.compute(me(e.inputs[0], "ThresholdedRelu", (n) => `select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`, `const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`, t.cacheKey)), 0;
+ }, hu = (e) => {
+ e.compute(me(e.inputs[0], "Log", "log"));
+ }, Qm = (e, t) => `
+const alpha = vec4<${e}>(${t});
+const one = ${e}(1.0);
+const zero = ${e}(0.0);
+
+fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
+ let v = x *alpha;
+ var x1 : vec4<${e}>;
+ for (var i = 0; i < 4; i = i + 1) {
+ if (v[i] >= zero) {
+ x1[i] = one / (one + exp(-v[i]));
+ } else {
+ x1[i] = one - one / (one + exp(v[i]));
+ }
+ }
+ return x * x1;
+}
+`, Ym = (e) => `quick_gelu_impl(${e})`, gu = (e, t) => {
+ let r = Ae(e.inputs[0].dataType);
+ e.compute(me(e.inputs[0], "QuickGelu", Ym, Qm(r, t.alpha), t.cacheKey, e.inputs[0].dataType));
+ };
+});
+var Xm;
+var Jm;
+var yu;
+var _u = U(() => {
+ "use strict";
+ ne();
+ ie();
+ jr();
+ Xm = (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");
+ }, Jm = (e) => {
+ let t = e[0].dims.slice();
+ t[2] = t[2] / 2;
+ let r = P("input", e[0].dataType, e[0].dims, 4), n = P("bias", e[0].dataType, [e[0].dims[2]], 4), o = M("output", e[0].dataType, t, 4), i = k.size(t) / 4, a = be(e[0].dataType);
+ return { name: "BiasSplitGelu", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(i / 64) } }), getShaderSource: (d) => `
+ const M_SQRT2 = sqrt(2.0);
+ const halfChannels = ${e[0].dims[2] / 4 / 2}u;
+
+ ${d.declareVariables(r, n, o)}
+
+ ${qr(a)}
+
+ ${d.mainStart()}
+ ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)}
+ let biasIdx = global_idx % halfChannels;
+ let batchIndex = global_idx / halfChannels;
+ let inputOffset = biasIdx + batchIndex * halfChannels * 2;
+ let valueLeft = input[inputOffset] + bias[biasIdx];
+ let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];
+ let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
+
+ ${o.setByOffset("global_idx", "valueLeft * geluRight")}
+ }` };
+ }, yu = (e) => {
+ Xm(e.inputs), e.compute(Jm(e.inputs));
+ };
+});
+var ef;
+var tf;
+var ot;
+var wu;
+var vu;
+var $u;
+var xu;
+var Su;
+var Tu;
+var Iu;
+var Cu;
+var Au;
+var Eu;
+var ku = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ ef = (e, t, r, n, o, i, a, u, d, c, p, m) => {
+ let f, b;
+ typeof u == "string" ? f = b = (v, x) => `${u}((${v}),(${x}))` : typeof u == "function" ? f = b = u : (f = u.scalar, b = u.vector);
+ let g = M("outputData", p, n.length, 4), _ = P("aData", d, t.length, 4), S = P("bData", c, r.length, 4), $;
+ if (o) if (i) {
+ let v = k.size(t) === 1, x = k.size(r) === 1, T = t.length > 0 && t[t.length - 1] % 4 === 0, E = r.length > 0 && r[r.length - 1] % 4 === 0;
+ v || x ? $ = g.setByOffset("global_idx", b(v ? `${_.type.value}(${_.getByOffset("0")}.x)` : _.getByOffset("global_idx"), x ? `${S.type.value}(${S.getByOffset("0")}.x)` : S.getByOffset("global_idx"))) : $ = `
+ let outputIndices = ${g.offsetToIndices("global_idx * 4u")};
+ let offsetA = ${_.broadcastedIndicesToOffset("outputIndices", g)};
+ let offsetB = ${S.broadcastedIndicesToOffset("outputIndices", g)};
+ ${g.setByOffset("global_idx", b(a || T ? _.getByOffset("offsetA / 4u") : `${_.type.value}(${_.getByOffset("offsetA / 4u")}[offsetA % 4u])`, a || E ? S.getByOffset("offsetB / 4u") : `${S.type.value}(${S.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
+ `;
+ } else $ = g.setByOffset("global_idx", b(_.getByOffset("global_idx"), S.getByOffset("global_idx")));
+ else {
+ if (!i) throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");
+ let v = (x, T, E = "") => {
+ let I = `aData[indexA${T}][componentA${T}]`, z = `bData[indexB${T}][componentB${T}]`;
+ return `
+ let outputIndices${T} = ${g.offsetToIndices(`global_idx * 4u + ${T}u`)};
+ let offsetA${T} = ${_.broadcastedIndicesToOffset(`outputIndices${T}`, g)};
+ let offsetB${T} = ${S.broadcastedIndicesToOffset(`outputIndices${T}`, g)};
+ let indexA${T} = offsetA${T} / 4u;
+ let indexB${T} = offsetB${T} / 4u;
+ let componentA${T} = offsetA${T} % 4u;
+ let componentB${T} = offsetB${T} % 4u;
+ ${x}[${T}] = ${E}(${f(I, z)});
+ `;
+ };
+ p === 9 ? $ = `
+ var data = vec4(0);
+ ${v("data", 0, "u32")}
+ ${v("data", 1, "u32")}
+ ${v("data", 2, "u32")}
+ ${v("data", 3, "u32")}
+ outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));` : $ = `
+ ${v("outputData[global_idx]", 0)}
+ ${v("outputData[global_idx]", 1)}
+ ${v("outputData[global_idx]", 2)}
+ ${v("outputData[global_idx]", 3)}
+ `;
+ }
+ return `
+ ${e.registerUniform("vec_size", "u32").declareVariables(_, S, g)}
+
+ ${m ?? ""}
+
+ ${e.mainStart()}
+ ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
+ ${$}
+ }`;
+ }, tf = (e, t, r, n, o, i, a = r.dataType) => {
+ let u = r.dims.map((_) => Number(_) ?? 1), d = n.dims.map((_) => Number(_) ?? 1), c = !k.areEqual(u, d), p = u, m = k.size(u), f = false, b = false, g = [c];
+ if (c) {
+ let _ = Je.calcShape(u, d, false);
+ if (!_) throw new Error("Can't perform binary op on the given tensors");
+ p = _.slice(), m = k.size(p);
+ let S = k.size(u) === 1, $ = k.size(d) === 1, v = u.length > 0 && u[u.length - 1] % 4 === 0, x = d.length > 0 && d[d.length - 1] % 4 === 0;
+ g.push(S), g.push($), g.push(v), g.push(x);
+ let T = 1;
+ for (let E = 1; E < p.length; E++) {
+ let I = u[u.length - E], z = d[d.length - E];
+ if (I === z) T *= I;
+ else break;
+ }
+ T % 4 === 0 ? (b = true, f = true) : (S || $ || v || x) && (f = true);
+ } else f = true;
+ return g.push(f), { name: e, shaderCache: { hint: t + g.map((_) => _.toString()).join("_"), inputDependencies: ["rank", "rank"] }, getShaderSource: (_) => ef(_, u, d, p, f, c, b, o, r.dataType, n.dataType, a, i), getRunData: () => ({ outputs: [{ dims: p, dataType: a }], dispatchGroup: { x: Math.ceil(m / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(k.size(p) / 4) }, ...N(u, d, p)] }) };
+ }, ot = (e, t, r, n, o, i) => {
+ e.compute(tf(t, o ?? "", e.inputs[0], e.inputs[1], r, n, i));
+ }, wu = (e) => {
+ ot(e, "Add", (t, r) => `${t}+${r}`);
+ }, vu = (e) => {
+ ot(e, "Div", (t, r) => `${t}/${r}`);
+ }, $u = (e) => {
+ ot(e, "Equal", { scalar: (t, r) => `u32(${t}==${r})`, vector: (t, r) => `vec4(${t}==${r})` }, void 0, void 0, 9);
+ }, xu = (e) => {
+ ot(e, "Mul", (t, r) => `${t}*${r}`);
+ }, Su = (e) => {
+ let t = P("input", e.inputs[0].dataType, e.inputs[0].dims).type.value;
+ ot(e, "Pow", { scalar: (n, o) => `pow_custom(${n},${o})`, vector: (n, o) => `pow_vector_custom(${n},${o})` }, `
+ fn pow_custom(a : ${t}, b : ${t}) -> ${t} {
+ if (b == ${t}(0.0)) {
+ return ${t}(1.0);
+ } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {
+ return ${t}(pow(f32(a), f32(b))); // NaN
+ }
+ return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t === "i32" ? "round" : ""}(pow(f32(abs(a)), f32(b))));
+ }
+ fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {
+ // TODO: implement vectorized pow
+ return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
+ }
+ `);
+ }, Tu = (e) => {
+ ot(e, "Sub", (t, r) => `${t}-${r}`);
+ }, Iu = (e) => {
+ ot(e, "Greater", { scalar: (t, r) => `u32(${t}>${r})`, vector: (t, r) => `vec4(${t}>${r})` }, void 0, void 0, 9);
+ }, Cu = (e) => {
+ ot(e, "Less", { scalar: (t, r) => `u32(${t}<${r})`, vector: (t, r) => `vec4(${t}<${r})` }, void 0, void 0, 9);
+ }, Au = (e) => {
+ ot(e, "GreaterOrEqual", { scalar: (t, r) => `u32(${t}>=${r})`, vector: (t, r) => `vec4(${t}>=${r})` }, void 0, void 0, 9);
+ }, Eu = (e) => {
+ ot(e, "LessOrEqual", { scalar: (t, r) => `u32(${t}<=${r})`, vector: (t, r) => `vec4(${t}<=${r})` }, void 0, void 0, 9);
+ };
+});
+var nf;
+var of;
+var af;
+var sf;
+var Pu;
+var zu;
+var Ou = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ nf = (e, t) => {
+ if (!e || e.length < 1) throw new Error("too few inputs");
+ let r = 0, n = e[r], o = n.dataType, i = n.dims.length;
+ e.forEach((a, u) => {
+ if (u !== r) {
+ if (a.dataType !== o) throw new Error("input tensors should be one type");
+ if (a.dims.length !== i) throw new Error("input tensors should have the same shape");
+ a.dims.forEach((d, c) => {
+ if (c !== t && d !== n.dims[c]) throw new Error("non concat dimensions must match");
+ });
+ }
+ });
+ }, of = (e, t) => `
+ fn calculateInputIndex(index: u32) -> u32 {
+ let sizeInConcatAxis = array(${t});
+ for (var i: u32 = 0u; i < ${e}; i += 1u ) {
+ if (index < sizeInConcatAxis[i]) {
+ return i;
+ }
+ }
+ return ${e}u;
+ }`, af = (e, t) => {
+ let r = e.length, n = [];
+ for (let o = 0; o < r; ++o) {
+ let i = t.setByOffset("global_idx", e[o].getByIndices("indices"));
+ r === 1 ? n.push(i) : o === 0 ? n.push(`if (inputIndex == ${o}u) { ${i} }`) : o === r - 1 ? n.push(`else { ${i} }`) : n.push(`else if (inputIndex == ${o}) { ${i} }`);
+ }
+ return n.join(`
+`);
+ }, sf = (e, t, r, n) => {
+ let o = k.size(r), i = new Array(e.length), a = new Array(e.length), u = 0, d = [], c = [], p = [{ type: 12, data: o }];
+ for (let _ = 0; _ < e.length; ++_) u += e[_].dims[t], i[_] = u, c.push(e[_].dims.length), a[_] = P(`input${_}`, n, c[_]), d.push("rank"), p.push({ type: 12, data: i[_] });
+ for (let _ = 0; _ < e.length; ++_) p.push(...N(e[_].dims));
+ p.push(...N(r));
+ let m = M("output", n, r.length), f = m.indicesGet("indices", t), b = Array.from(Array(i.length).keys()).map((_) => `uniforms.sizeInConcatAxis${_}`).join(","), g = (_) => `
+
+ ${(() => {
+ _.registerUniform("outputSize", "u32");
+ for (let S = 0; S < e.length; S++) _.registerUniform(`sizeInConcatAxis${S}`, "u32");
+ return _.declareVariables(...a, m);
+ })()}
+
+ ${of(i.length, b)}
+
+ ${_.mainStart()}
+ ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+
+ var indices = ${m.offsetToIndices("global_idx")};
+
+ let inputIndex = calculateInputIndex(${f});
+ if (inputIndex != 0u) {
+ let sizeInConcatAxis = array(${b});
+ ${f} -= sizeInConcatAxis[inputIndex - 1u];
+ }
+
+ ${af(a, m)}
+ }`;
+ return { name: "Concat", shaderCache: { hint: `${t}`, inputDependencies: d }, getRunData: () => ({ outputs: [{ dims: r, dataType: n }], dispatchGroup: { x: Math.ceil(o / 64) }, programUniforms: p }), getShaderSource: g };
+ }, Pu = (e, t) => {
+ let r = e.inputs, n = r[0].dims, o = k.normalizeAxis(t.axis, n.length);
+ nf(r, o);
+ let i = n.slice();
+ i[o] = r.reduce((u, d) => u + (d.dims.length > o ? d.dims[o] : 0), 0);
+ let a = r.filter((u) => k.size(u.dims) > 0);
+ e.compute(sf(a, o, i, r[0].dataType), { inputs: a });
+ }, zu = (e) => J({ axis: e.axis });
+});
+var Fe;
+var qe;
+var je;
+var Kr;
+var bt = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Fe = (e, t, r = "f32") => {
+ switch (e.activation) {
+ case "Relu":
+ return `value = max(value, ${t}(0.0));`;
+ case "Sigmoid":
+ return `value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;
+ case "Clip":
+ return `value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;
+ case "HardSigmoid":
+ return `value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;
+ case "LeakyRelu":
+ return `value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;
+ case "Tanh":
+ return `let e2x = exp(-2.0 * abs(value));
+ value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
+ `;
+ case "":
+ return "";
+ default:
+ throw new Error(`Unsupported activation ${e.activation}`);
+ }
+ }, qe = (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 });
+ }, je = (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" });
+ }, Kr = (e) => {
+ let t = e?.activation || "";
+ if (t === "HardSigmoid") {
+ let [r, n] = e?.activation_params || [0.2, 0.5];
+ return { activation: t, alpha: r, beta: n };
+ } else if (t === "Clip") {
+ let [r, n] = e?.activation_params || [Wa, La];
+ return { activation: t, clipMax: n, clipMin: r };
+ } else if (t === "LeakyRelu") {
+ let [r] = e?.activation_params || [0.01];
+ return { activation: t, alpha: r };
+ }
+ return { activation: t };
+ };
+});
+var Ie;
+var Bu;
+var Zr = U(() => {
+ "use strict";
+ Ie = (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.`);
+ }
+ }, Bu = (e) => `
+ ${e ? "value = value + getBiasByOutputCoords(coords);" : ""}
+ `;
+});
+var Du;
+var Mu = U(() => {
+ "use strict";
+ Du = (e) => `
+fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {
+ return dot(coords, vec4(
+ shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
+}
+fn getOutputIndexFromCoords(coords : vec4) -> i32 {
+ return dot(coords, vec4(
+ i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
+}
+`;
+});
+var Xt;
+var Qr;
+var Yr = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ bt();
+ Xt = (e, t, r, n, o) => {
+ let i = n - r;
+ return `
+ ${Array.from({ length: r }).map((a, u) => `
+ if (${F(t.shape, u, t.rank)} != 1) {
+ ${t.indicesSet(e, u, F(o, u + i, n))}
+ } else {
+ ${t.indicesSet(e, u, 0)}
+ }`).join("")}
+`;
+ }, Qr = (e, t, r, n, o = false, i) => {
+ let a = e[0].dims, u = e[1].dims, d = a[a.length - 2], c = u[u.length - 1], p = a[a.length - 1], m = ce(c), f = ce(p), b = ce(d), g = k.size(r) / m / b, _ = e.length > 2, S = n ? n.slice(0, -2) : r.slice(0, -2), v = [k.size(S), d, c], x = [{ type: 12, data: g }, { type: 12, data: d }, { type: 12, data: c }, { type: 12, data: p }];
+ qe(t, x), x.push(...N(S, a, u)), _ && x.push(...N(e[2].dims)), x.push(...N(v));
+ let T = (E) => {
+ let I = Lr("batch_dims", e[0].dataType, S.length), z = P("a", e[0].dataType, a.length, f), O = P("b", e[1].dataType, u.length, m), D = M("output", e[0].dataType, v.length, m), L = be(D.type.tensor), q = Fe(t, D.type.value, L), Q = [z, O], W = "";
+ if (_) {
+ let H = o ? m : 1;
+ Q.push(P("bias", e[2].dataType, e[2].dims.length, H)), W = `${o ? `value += bias[col / ${H}];` : `value += ${D.type.value}(bias[row + i]);`}`;
+ }
+ let Z = [{ name: "output_size", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }];
+ je(t, Z);
+ let we = () => {
+ let H = `var a_data: ${z.type.value};`;
+ for (let j = 0; j < f; j++) H += `
+ let b_data${j} = b[(b_offset + (k + ${j}) * uniforms.N + col) / ${m}];`;
+ for (let j = 0; j < b; j++) {
+ H += `a_data = a[(a_offset + (row + ${j}) * uniforms.K + k) / ${f}];`;
+ for (let te = 0; te < f; te++) H += `
+ values[${j}] = fma(${O.type.value}(a_data${f === 1 ? "" : `[${te}]`}), b_data${te}, values[${j}]);
+`;
+ }
+ return H;
+ };
+ return `
+ ${E.registerUniforms(Z).registerInternalVariables(I).declareVariables(...Q, D)}
+ ${E.mainStart()}
+ ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let col = (global_idx % (uniforms.N / ${m})) * ${m};
+ var index1 = global_idx / (uniforms.N / ${m});
+ let stride1 = uniforms.M / ${b};
+ let row = (index1 % stride1) * ${b};
+ let batch = index1 / stride1;
+
+ ${r.length === 2 ? "" : `let batch_indices = ${I.offsetToIndices("batch")};`}
+
+ var a_indices: ${z.type.indices};
+ ${Xt("a_indices", z, z.rank - 2, I.rank, "batch_indices")}
+ ${z.indicesSet("a_indices", z.rank - 2, 0)}
+ ${z.indicesSet("a_indices", z.rank - 1, 0)}
+ let a_offset = ${z.indicesToOffset("a_indices")};
+
+ var b_indices: ${O.type.indices};
+ ${Xt("b_indices", O, O.rank - 2, I.rank, "batch_indices")}
+ ${O.indicesSet("b_indices", O.rank - 2, 0)}
+ ${O.indicesSet("b_indices", O.rank - 1, 0)}
+ let b_offset = ${O.indicesToOffset("b_indices")};
+ var values: array<${D.type.value}, ${b}>;
+ for (var k: u32 = 0u; k < uniforms.K; k = k + ${f}) {
+ ${we()}
+ }
+ for (var i = 0u; i < ${b}u; i++) {
+ var value = values[i];
+ ${W}
+ ${q}
+ let cur_indices = ${D.type.indices}(batch, row + i, col);
+ let offset = ${D.indicesToOffset("cur_indices")};
+ ${D.setByOffset(`offset / ${m}`, "value")};
+ }
+ }
+ `;
+ };
+ return { name: "MatMulNaive", shaderCache: { hint: `${t.activation};${m};${f};${b};${o}`, inputDependencies: _ ? ["rank", "rank", "rank"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: i ? i(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(g / 64) }, programUniforms: x }), getShaderSource: T };
+ };
+});
+var uf;
+var df;
+var mo;
+var Ru;
+var lf;
+var fo;
+var cf;
+var Jt;
+var Xr = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ bt();
+ Yr();
+ Zr();
+ uf = (e, t) => e ? `
+ mm_Asub[inputRow][inputCol] = mm_readA(batch,
+ kStart + inputRow,
+ globalRowStart / innerElementSize + inputCol${t ? ", batchIndices" : ""});
+ ` : `
+ mm_Asub[inputRow][inputCol] = mm_readA(batch,
+ globalRow + innerRow,
+ kStart / innerElementSize + inputCol${t ? ", batchIndices" : ""});
+ `, df = (e, t) => e ? `
+ let ACached0 = mm_Asub[k * innerElementSize][localRow];
+ let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
+ let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
+ ${t === 3 ? "" : "let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}
+ for (var i = 0; i < rowPerThread; i = i + 1) {
+ acc[i] = BCached0 * ACached0[i] + acc[i];
+ acc[i] = BCached1 * ACached1[i] + acc[i];
+ acc[i] = BCached2 * ACached2[i] + acc[i];
+ ${t === 3 ? "" : "acc[i] = BCached3 * ACached3[i] + acc[i];"}
+ }` : `
+ for (var i = 0; i < rowPerThread; i = i + 1) {
+ let ACached = mm_Asub[tileRow + i][k];
+ acc[i] = BCached0 * ACached.x + acc[i];
+ acc[i] = BCached1 * ACached.y + acc[i];
+ acc[i] = BCached2 * ACached.z + acc[i];
+ ${t === 3 ? "" : "acc[i] = BCached3 * ACached.w + acc[i];"}
+ }`, mo = (e, t, r = "f32", n, o = false, i = 32, a = false, u = 32) => {
+ let d = t[1] * e[1], c = t[0] * e[0], p = o ? d : i, m = o ? i : d, f = p / t[0], b = i / t[1];
+ if (!((o && f === 4 && e[1] === 4 || !o && (f === 3 || f === 4)) && p % t[0] === 0 && i % t[1] === 0 && e[0] === 4)) throw new Error(`If transposeA ${o} is true, innerElementSize ${f} and workPerThread[1] ${e[1]} must be 4.
+ Otherwise, innerElementSize ${f} must be 3 or 4.
+ tileAWidth ${p} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);
+ return `
+var mm_Asub: array, ${p / f}>, ${m}>;
+var mm_Bsub: array, ${c / e[0]}>, ${i}>;
+
+const rowPerThread = ${e[1]};
+const colPerThread = ${e[0]};
+const innerElementSize = ${f};
+const tileInner = ${i};
+
+@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
+fn main(@builtin(local_invocation_id) localId : vec3,
+ @builtin(global_invocation_id) globalId : vec3,
+ @builtin(workgroup_id) workgroupId : vec3) {
+ let localRow = i32(localId.y);
+ let tileRow = localRow * rowPerThread;
+ let tileCol = i32(localId.x);
+
+ let globalRow =i32(globalId.y) * rowPerThread;
+ let globalCol = i32(globalId.x);
+ let batch = ${a ? "0" : "i32(globalId.z)"};
+ ${n ? `let batchIndices = ${n.offsetToIndices("u32(batch)")};` : ""}
+ let globalRowStart = i32(workgroupId.y) * ${d};
+
+ let num_tiles = ${a ? `${Math.ceil(u / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"};
+ var kStart = ${a ? `i32(globalId.z) * ${u}` : "0"};
+
+ var acc: array, rowPerThread>;
+
+ // Loop over shared dimension.
+ let tileRowB = localRow * ${b};
+ for (var t = 0; t < num_tiles; t = t + 1) {
+ // Load one tile of A into local memory.
+ for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
+ let inputRow = tileRow + innerRow;
+ let inputCol = tileCol;
+ ${uf(o, n)}
+ }
+
+ // Load one tile of B into local memory.
+ for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) {
+ let inputRow = tileRowB + innerRow;
+ let inputCol = tileCol;
+ mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n ? ", batchIndices" : ""});
+ }
+ kStart = kStart + tileInner;
+ workgroupBarrier();
+
+ // Compute acc values for a single thread.
+ for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {
+ let BCached0 = mm_Bsub[k * innerElementSize][tileCol];
+ let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];
+ let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];
+ ${f === 3 ? "" : "let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
+
+ ${df(o, f)}
+ }
+
+ workgroupBarrier();
+ }
+
+ for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
+ mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
+ }
+}`;
+ }, Ru = (e, t) => e ? `
+ mm_Asub[inputRow][inputCol] = mm_readA(batch,
+ kStart + inputRow,
+ globalRowStart + inputCol${t ? ", batchIndices" : ""});
+ ` : `
+ mm_Asub[inputRow][inputCol] = mm_readA(batch,
+ globalRowStart + inputRow,
+ kStart + inputCol${t ? ", batchIndices" : ""});
+ `, lf = (e) => e ? "let ACached = mm_Asub[k][tileRow + innerRow];" : "let ACached = mm_Asub[tileRow + innerRow][k];", fo = (e, t, r = "f32", n, o = false, i = 32, a = false, u = 32, d = false) => {
+ let c = e[1] * t[1], p = e[0] * t[0], m = o ? c : i, f = o ? i : c;
+ if (!(f % t[1] === 0 && m % t[0] === 0 && i % t[1] === 0)) throw new Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);
+ let b = f / t[1], g = m / t[0], _ = i / t[1], S = d ? `
+ let localRow = i32(localId.y);
+ let localCol = i32(localId.x);
+ let globalRowStart = i32(workgroupId.y) * ${c};
+ let globalColStart = i32(workgroupId.x) * ${p};
+
+ // Loop over shared dimension.
+ for (var t = 0; t < num_tiles; t = t + 1) {
+ // Load one tile of A into local memory.
+ for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${t[1]}) {
+ for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {
+ ${Ru(o, n)}
+ }
+ }
+ // Load one tile of B into local memory.
+ for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {
+ for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${t[0]}) {
+ mm_Bsub[inputRow][inputCol] = mm_readB(batch,
+ kStart + inputRow,
+ globalColStart + inputCol${n ? ", batchIndices" : ""});
+ }
+ }
+ kStart = kStart + tileInner;
+ workgroupBarrier();
+
+ // Compute acc values for a single thread.
+ var BCached : array<${r}, colPerThread>;
+ for (var k = 0; k < tileInner; k = k + 1) {
+ for (var inner = 0; inner < colPerThread; inner = inner + 1) {
+ BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];
+ }
+ for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
+ let ACached = ${o ? `mm_Asub[k][localRow + innerRow * ${t[1]}];` : `mm_Asub[localRow + innerRow * ${t[1]}][k];`}
+ for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
+ acc[innerRow][innerCol] = acc[innerRow][innerCol] +
+ ACached * BCached[innerCol];
+ }
+ }
+ }
+ workgroupBarrier();
+ }
+ for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
+ let gRow = globalRowStart + localRow + innerRow * ${t[1]};
+ for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
+ let gCol = globalColStart + localCol + innerCol * ${t[0]};
+ mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
+ }
+ }
+ ` : `
+let tileRow = i32(localId.y) * rowPerThread;
+let tileCol = i32(localId.x) * colPerThread;
+
+let globalRow = i32(globalId.y) * rowPerThread;
+let globalCol = i32(globalId.x) * colPerThread;
+let globalRowStart = i32(workgroupId.y) * ${c};
+
+let tileRowA = i32(localId.y) * ${b};
+let tileColA = i32(localId.x) * ${g};
+let tileRowB = i32(localId.y) * ${_};
+// Loop over shared dimension.
+for (var t = 0; t < num_tiles; t = t + 1) {
+ // Load one tile of A into local memory.
+ for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) {
+ for (var innerCol = 0; innerCol < ${g}; innerCol = innerCol + 1) {
+ let inputRow = tileRowA + innerRow;
+ let inputCol = tileColA + innerCol;
+ ${Ru(o, n)}
+ }
+ }
+
+ // Load one tile of B into local memory.
+ for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {
+ for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
+ let inputRow = tileRowB + innerRow;
+ let inputCol = tileCol + innerCol;
+ mm_Bsub[inputRow][inputCol] = mm_readB(batch,
+ kStart + inputRow,
+ globalCol + innerCol${n ? ", batchIndices" : ""});
+ }
+ }
+ kStart = kStart + tileInner;
+ workgroupBarrier();
+
+ // Compute acc values for a single thread.
+ var BCached : array<${r}, colPerThread>;
+ for (var k = 0; k < tileInner; k = k + 1) {
+ for (var inner = 0; inner < colPerThread; inner = inner + 1) {
+ BCached[inner] = mm_Bsub[k][tileCol + inner];
+ }
+
+ for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
+ ${lf(o)}
+ for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
+ acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
+ }
+ }
+ }
+
+ workgroupBarrier();
+}
+
+for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
+ for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
+ mm_write(batch, globalRow + innerRow, globalCol + innerCol,
+ acc[innerRow][innerCol]);
+ }
+}
+`;
+ return `
+ var mm_Asub : array, ${f}>;
+ var mm_Bsub : array, ${i}>;
+ const rowPerThread = ${e[1]};
+ const colPerThread = ${e[0]};
+ const tileInner = ${i};
+
+@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})
+fn main(@builtin(local_invocation_id) localId : vec3,
+ @builtin(global_invocation_id) globalId : vec3,
+ @builtin(workgroup_id) workgroupId : vec3) {
+ let batch = ${a ? "0" : "i32(globalId.z)"};
+ ${n ? `let batchIndices = ${n.offsetToIndices("u32(batch)")};` : ""}
+ let num_tiles = ${a ? `${Math.ceil(u / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"};
+ var kStart = ${a ? `i32(globalId.z) * ${u}` : "0"};
+
+ var acc : array, rowPerThread>;
+ ${S}
+ }
+`;
+ }, cf = (e, t, r, n, o = false) => {
+ let [i, a, u, d] = n, c = be(n[0].type.tensor);
+ return `
+ fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ie(e, c)} {
+ var value = ${Ie(e, c)}(0.0);
+ let col = colIn * ${e};
+ if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
+ {
+ var aIndices: ${a.type.indices};
+ ${Xt("aIndices", a, a.rank - 2, i.rank, "batchIndices")}
+ ${a.indicesSet("aIndices", a.rank - 2, "u32(row)")}
+ ${a.indicesSet("aIndices", a.rank - 1, "u32(colIn)")}
+ value = ${a.getByIndices("aIndices")};
+ }
+ return value;
+ }
+
+ fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ie(e, c)} {
+ var value = ${Ie(e, c)}(0.0);
+ let col = colIn * ${e};
+ if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
+ {
+ var bIndices: ${u.type.indices};
+ ${Xt("bIndices", u, u.rank - 2, i.rank, "batchIndices")}
+ ${u.indicesSet("bIndices", u.rank - 2, "u32(row)")}
+ ${u.indicesSet("bIndices", u.rank - 1, "u32(colIn)")}
+ value = ${u.getByIndices("bIndices")};
+ }
+ return value;
+ }
+
+ fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ie(e, c)}) {
+ let col = colIn * ${e};
+ if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
+ var value = valueIn;
+ let coords = vec3(batch, row, colIn);
+ ${t ? `value = value + ${o ? "bias[colIn]" : `${Ie(e, c)}(bias[row])`};` : ""}
+ ${r}
+ ${d.setByIndices("vec3(coords)", "value")}
+ }
+ }
+ `;
+ }, Jt = (e, t, r, n, o = false, i) => {
+ let a = e[0].dims, u = e[1].dims, d = a.slice(0, -2), c = u.slice(0, -2), p = n ? n.slice(0, -2) : r.slice(0, -2), m = k.size(p), f = a[a.length - 2], b = a[a.length - 1], g = u[u.length - 1], _ = b % 4 === 0 && g % 4 === 0, S = f <= 8 ? [4, 1, 1] : [4, 4, 1], $ = [8, 8, 1], v = [Math.ceil(g / $[0] / S[0]), Math.ceil(f / $[1] / S[1]), Math.ceil(m / $[2] / S[2])], x = _ ? 4 : 1, T = [...d, f, b / x], E = T.length, I = [...c, b, g / x], z = I.length, O = [m, f, g / x], D = [{ type: 6, data: f }, { type: 6, data: g }, { type: 6, data: b }];
+ qe(t, D), D.push(...N(p, T, I));
+ let L = ["rank", "rank"], q = e.length > 2;
+ q && (D.push(...N(e[2].dims)), L.push("rank")), D.push(...N(O));
+ let Q = (W) => {
+ let Z = p.length, we = Lr("batchDims", e[0].dataType, Z, 1), H = be(e[0].dataType), j = P("a", e[0].dataType, E, x), te = P("b", e[1].dataType, z, x), X = M("result", e[0].dataType, O.length, x), ue = [j, te];
+ if (q) {
+ let V = o ? x : 1;
+ ue.push(P("bias", e[2].dataType, e[2].dims.length, V));
+ }
+ let he = [{ name: "dim_a_outer", type: "i32" }, { name: "dim_b_outer", type: "i32" }, { name: "dim_inner", type: "i32" }];
+ je(t, he);
+ let ye = be(X.type.tensor), re = Fe(t, X.type.value, ye), C = cf(x, q, re, [we, j, te, X], o);
+ return `
+ ${W.registerUniforms(he).registerInternalVariables(we).declareVariables(...ue, X)}
+ ${C}
+ ${_ ? mo(S, $, H, we) : fo(S, $, H, we)}
+ `;
+ };
+ return { name: "MatMul", shaderCache: { hint: `${S};${t.activation};${_};${o}`, inputDependencies: L }, getRunData: () => ({ outputs: [{ dims: i ? i(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: v[0], y: v[1], z: v[2] }, programUniforms: D }), getShaderSource: Q };
+ };
+});
+var pf;
+var Uu;
+var Nu = U(() => {
+ "use strict";
+ ee();
+ Xe();
+ ie();
+ bt();
+ Zr();
+ Mu();
+ Xr();
+ pf = (e, t, r, n, o = false, i, a = 4, u = 4, d = 4, c = "f32") => {
+ let p = (L) => {
+ switch (L) {
+ case 1:
+ return "resData = x[xIndex];";
+ case 3:
+ return `resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;
+ case 4:
+ return "resData = x[xIndex / 4];";
+ default:
+ throw new Error(`innerElementSize ${L} is not supported.`);
+ }
+ }, m = (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.`);
+ }
+ }, f = e ? `
+ let coord = vec4(batch, xRow, xCol, xCh);
+ ` : `
+ let coord = vec4(batch, xCh, xRow, xCol);
+ `, b = e ? `
+ let coords = vec4(
+ batch,
+ row / outWidth,
+ row % outWidth,
+ col);
+ ` : `
+ let coords = vec4(
+ batch,
+ row,
+ col / outWidth,
+ col % outWidth);
+ `, g = e ? "i32(uniforms.x_shape[1])" : "i32(uniforms.x_shape[2])", _ = e ? "i32(uniforms.x_shape[2])" : "i32(uniforms.x_shape[3])", S = e ? "row" : "col", $ = e ? "col" : "row", v = `
+ let inChannels = i32(uniforms.w_shape[2]);
+ let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"};
+ let outRow = ${S} / outWidth;
+ let outCol = ${S} % outWidth;
+
+ let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels);
+ let WCol = ${$} / inChannels % i32(uniforms.w_shape[1]);
+ let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
+ let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
+ let xCh = ${$} % inChannels;
+ var resData = ${Ie(a, c)}(0.0);
+ // The bounds checking is always needed since we use it to pad zero for
+ // the 'same' padding type.
+ if (xRow >= 0 && xRow < ${g} && xCol >= 0 && xCol < ${_}) {
+ ${f}
+ let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));
+ ${p(a)}
+ }
+ return resData;`, x = e ? t && n ? `
+ let col = colIn * ${a};
+ ${v}` : `
+ let col = colIn * ${a};
+ if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
+ ${v}
+ }
+ return ${Ie(a, c)}(0.0);` : n && r ? `
+ let col = colIn * ${a};
+ ${v}` : `
+ let col = colIn * ${a};
+ if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
+ ${v}
+ }
+ return ${Ie(a, c)}(0.0);`, T = e ? n && r ? m(u) : `
+ let col = colIn * ${u};
+ if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
+ ${m(u)}
+ }
+ return ${Ie(u, c)}(0.0);` : `
+ let col = colIn * ${u};
+ if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
+ ${m(u)}
+ }
+ return ${Ie(u, c)}(0.0);`, E = Ie(d, c), I = e ? Ie(a, c) : Ie(u, c), z = e ? Ie(u, c) : Ie(a, c), O = Fe(i, E, c);
+ return `
+ fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${I} {
+ ${e ? x : T}
+ }
+
+ fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${z} {
+ ${e ? T : x}
+ }
+
+ fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${E}) {
+ let col = colIn * ${d};
+ if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)
+ {
+ var value = valueIn;
+ let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"};
+ ${b}
+ ${Bu(o)}
+ ${O}
+ setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
+ }
+ }`;
+ }, Uu = (e, t, r, n, o, i, a, u, d) => {
+ let c = t.format === "NHWC", p = c ? e[0].dims[3] : e[0].dims[1], m = r[0], f = c ? r[2] : r[3], b = c ? r[1] : r[2], g = c ? r[3] : r[1], _ = c && (p % 4 === 0 || p % 3 === 0) && g % 4 === 0, S = c ? g : f * b, $ = c ? f * b : g, v = [8, 8, 1], x = n <= 8 ? [4, 1, 1] : [4, 4, 1], T = [Math.ceil(S / v[0] / x[0]), Math.ceil($ / v[1] / x[1]), Math.ceil(m / v[2] / x[2])];
+ se("verbose", () => `[conv2d_mm_webgpu] dispatch = ${T}`);
+ let E = _ ? c && p % 4 !== 0 ? 3 : 4 : 1, I = v[1] * x[1], z = v[0] * x[0], O = Math.max(v[0] * E, v[1]), D = n % I === 0, L = o % z === 0, q = i % O === 0, Q = _ ? [E, 4, 4] : [1, 1, 1], W = [{ type: 6, data: n }, { type: 6, data: o }, { type: 6, data: i }, { type: 6, data: [t.pads[0], t.pads[1]] }, { type: 6, data: t.strides }, { type: 6, data: t.dilations }];
+ qe(t, W), W.push(...N(e[0].dims, e[1].dims));
+ let Z = ["rank", "rank"];
+ a && (W.push(...N(e[2].dims)), Z.push("rank")), W.push(...N(r));
+ let we = (H) => {
+ let j = [{ 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 }];
+ je(t, j);
+ let te = _ ? 4 : 1, X = be(e[0].dataType), ue = `
+ fn setOutputAtIndex(flatIndex : i32, value : ${_ ? `vec4<${X}>` : X}) {
+ result[flatIndex] = ${_ ? `vec4<${X}>` : X}(value);
+ }
+ fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${_ ? `vec4<${X}>` : X}) {
+ let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));
+ setOutputAtIndex(flatIndex ${_ ? "/ 4" : ""}, value);
+ }`, he = P("x", e[0].dataType, e[0].dims.length, E === 3 ? 1 : E), ye = P("w", e[1].dataType, e[1].dims.length, te), re = [he, ye], C = M("result", e[0].dataType, r.length, te);
+ if (a) {
+ let V = P("bias", e[2].dataType, e[2].dims.length, te);
+ re.push(V), ue += `
+ fn getBiasByOutputCoords(coords : vec4) -> ${_ ? `vec4<${X}>` : X} {
+ return bias[coords.${c ? "w" : "y"}${_ ? "/ 4" : ""}];
+ }`;
+ }
+ return `
+ ${Du("uniforms.result_strides")}
+ //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,
+ // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,
+ // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
+ ${H.registerUniforms(j).declareVariables(...re, C)}
+ ${ue}
+ ${pf(c, D, L, q, a, t, Q[0], Q[1], Q[2], X)}
+ ${_ ? mo(x, v, X, void 0, !c, O) : fo(x, v, X, void 0, !c, O, false, void 0, u)}`;
+ };
+ return { name: "Conv2DMatMul", shaderCache: { hint: `${t.cacheKey};${E};${_};${D};${L};${q};${I};${z};${O}`, inputDependencies: Z }, getRunData: () => ({ outputs: [{ dims: d ? d(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: T[0], y: T[1], z: T[2] }, programUniforms: W }), getShaderSource: we };
+ };
+});
+var mf;
+var Vu;
+var Jr;
+var ff;
+var Wu;
+var hf;
+var Lu;
+var Gu;
+var Hu = U(() => {
+ "use strict";
+ ee();
+ Xe();
+ ne();
+ ie();
+ bt();
+ Zr();
+ mf = (e) => {
+ let t = 1;
+ for (let r = 0; r < e.length; r++) t *= e[r];
+ return t;
+ }, Vu = (e) => typeof e == "number" ? [e, e, e] : e, Jr = (e, t) => t <= 1 ? e : e + (e - 1) * (t - 1), ff = (e, t, r, n = 1) => {
+ let o = Jr(t, n);
+ return Math.floor((e[0] * (r - 1) - r + o) / 2);
+ }, Wu = (e, t, r, n, o) => {
+ o == null && (o = ff(e, t[0], n[0]));
+ let i = [0, 0, 0, r];
+ for (let a = 0; a < 3; a++) e[a] + 2 * o >= t[a] && (i[a] = Math.trunc((e[a] - t[a] + 2 * o) / n[a] + 1));
+ return i;
+ }, hf = (e, t, r, n, o, i, a, u, d, c) => {
+ let p, m, f, b;
+ if (e === "VALID" && (e = 0), typeof e == "number") {
+ p = { top: e, bottom: e, left: e, right: e, front: e, back: e };
+ let g = Wu([t, r, n, 1], [u, d, c], 1, [o, i, a], e);
+ m = g[0], f = g[1], b = g[2];
+ } else if (Array.isArray(e)) {
+ if (!e.every((_, S, $) => _ === $[0])) throw Error(`Unsupported padding parameter: ${e}`);
+ p = { top: e[0], bottom: e[1], left: e[2], right: e[3], front: e[4], back: e[5] };
+ let g = Wu([t, r, n, 1], [u, d, c], 1, [o, i, a], e[0]);
+ m = g[0], f = g[1], b = g[2];
+ } else if (e === "SAME_UPPER") {
+ m = Math.ceil(t / o), f = Math.ceil(r / i), b = Math.ceil(n / a);
+ let g = (m - 1) * o + u - t, _ = (f - 1) * i + d - r, S = (b - 1) * a + c - n, $ = Math.floor(g / 2), v = g - $, x = Math.floor(_ / 2), T = _ - x, E = Math.floor(S / 2), I = S - E;
+ p = { top: x, bottom: T, left: E, right: I, front: $, back: v };
+ } else throw Error(`Unknown padding parameter: ${e}`);
+ return { padInfo: p, outDepth: m, outHeight: f, outWidth: b };
+ }, Lu = (e, t, r, n, o, i = false, a = "channelsLast") => {
+ let u, d, c, p, m;
+ if (a === "channelsLast") [u, d, c, p, m] = e;
+ else if (a === "channelsFirst") [u, m, d, c, p] = e;
+ else throw new Error(`Unknown dataFormat ${a}`);
+ let [f, , b, g, _] = t, [S, $, v] = Vu(r), [x, T, E] = Vu(n), I = Jr(b, x), z = Jr(g, T), O = Jr(_, E), { padInfo: D, outDepth: L, outHeight: q, outWidth: Q } = hf(o, d, c, p, S, $, v, I, z, O), W = i ? f * m : f, Z = [0, 0, 0, 0, 0];
+ return a === "channelsFirst" ? Z = [u, W, L, q, Q] : a === "channelsLast" && (Z = [u, L, q, Q, W]), { batchSize: u, dataFormat: a, inDepth: d, inHeight: c, inWidth: p, inChannels: m, outDepth: L, outHeight: q, outWidth: Q, outChannels: W, padInfo: D, strideDepth: S, strideHeight: $, strideWidth: v, filterDepth: b, filterHeight: g, filterWidth: _, effectiveFilterDepth: I, effectiveFilterHeight: z, effectiveFilterWidth: O, dilationDepth: x, dilationHeight: T, dilationWidth: E, inShape: e, outShape: Z, filterShape: t };
+ }, Gu = (e, t, r, n, o, i) => {
+ let a = i === "channelsLast", u = a ? e[0].dims[3] : e[0].dims[1], d = false, c = [64, 1, 1], p = { x: r.map((v, x) => x) }, m = [Math.ceil(mf(p.x.map((v) => r[v])) / c[0]), 1, 1];
+ se("verbose", () => `[conv3d_naive_webgpu] dispatch = ${m}`);
+ let f = d ? a && u % 4 !== 0 ? 3 : 4 : 1, b = k.size(r), g = [{ type: 12, data: b }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: t.strides }, { type: 12, data: t.dilations }];
+ qe(t, g), g.push(...N(e[0].dims, e[1].dims));
+ let _ = ["rank", "rank"], S = e.length === 3;
+ S && (g.push(...N(e[2].dims)), _.push("rank")), g.push(...N(r));
+ let $ = (v) => {
+ let x = [{ name: "output_size", type: "u32" }, { name: "filter_dims", type: "u32", length: n.length }, { name: "pads", type: "u32", length: o.length }, { name: "strides", type: "u32", length: t.strides.length }, { name: "dilations", type: "u32", length: t.dilations.length }];
+ je(t, x);
+ let T = d ? 4 : 1, E = be(e[0].dataType), I = P("x", e[0].dataType, e[0].dims.length, f === 3 ? 1 : f), z = P("W", e[1].dataType, e[1].dims.length, T), O = [I, z], D = M("result", e[0].dataType, r.length, T), L = "";
+ if (S) {
+ let W = P("bias", e[2].dataType, e[2].dims.length, T);
+ O.push(W), L += `
+ fn getBiasByOutputCoords(coords : array) -> ${d ? `vec4<${E}>` : E} {
+ return bias[${a ? F("coords", 4, 5) : F("coords", 1, 5)}${d ? "/ 4" : ""}];
+ }`;
+ }
+ let q = Ie(f, E), Q = Fe(t, q, E);
+ return `
+ ${L}
+ fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
+ let aIndices = array(d0, d1, d2, d3, d4);
+ return ${I.getByIndices("aIndices")};
+ }
+ fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
+ let aIndices = array(d0, d1, d2, d3, d4);
+ return ${z.getByIndices("aIndices")};
+ }
+ ${v.registerUniforms(x).declareVariables(...O, D)}
+ ${v.mainStart()}
+ ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let coords = ${D.offsetToIndices("global_idx")};
+ let batch = ${F("coords", 0, I.rank)};
+ let d2 = ${a ? F("coords", I.rank - 1, I.rank) : F("coords", 1, I.rank)};
+ let xFRCCorner = vec3(${a ? F("coords", 1, I.rank) : F("coords", 2, I.rank)},
+ ${a ? F("coords", 2, I.rank) : F("coords", 3, I.rank)},
+ ${a ? F("coords", 3, I.rank) : F("coords", 4, I.rank)}) * uniforms.strides - uniforms.pads;
+ let xFCorner = xFRCCorner.x;
+ let xRCorner = xFRCCorner.y;
+ let xCCorner = xFRCCorner.z;
+ let xShapeY = ${a ? F("uniforms.x_shape", 1, I.rank) : F("uniforms.x_shape", 2, I.rank)};
+ let xShapeZ = ${a ? F("uniforms.x_shape", 2, I.rank) : F("uniforms.x_shape", 3, I.rank)};
+ let xShapeW = ${a ? F("uniforms.x_shape", 3, I.rank) : F("uniforms.x_shape", 4, I.rank)};
+ let xShapeU = ${a ? F("uniforms.x_shape", 4, I.rank) : F("uniforms.x_shape", 1, I.rank)};
+ let inputDepthNearestVec4 = (xShapeU / 4) * 4;
+ let inputDepthVec4Remainder = xShapeU % 4;
+
+ var value = 0.0;
+ for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {
+ let xF = xFCorner + wF * uniforms.dilations[0];
+ if (xF < 0 || xF >= xShapeY) {
+ continue;
+ }
+
+ for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {
+ let xR = xRCorner + wR * uniforms.dilations[1];
+ if (xR < 0 || xR >= xShapeZ) {
+ continue;
+ }
+
+ for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {
+ let xC = xCCorner + wC * uniforms.dilations[2];
+ if (xC < 0 || xC >= xShapeW) {
+ continue;
+ }
+
+ for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {
+ ${a ? `let xValues = vec4(
+ getX(batch, xF, xR, xC, d1),
+ getX(batch, xF, xR, xC, d1 + 1),
+ getX(batch, xF, xR, xC, d1 + 2),
+ getX(batch, xF, xR, xC, d1 + 3));
+ ` : `let xValues = vec4(
+ getX(batch, d1, xF, xR, xC),
+ getX(batch, d1 + 1, xF, xR, xC),
+ getX(batch, d1 + 2, xF, xR, xC),
+ getX(batch, d1 + 3, xF, xR, xC));
+ `}
+ let wValues = vec4(
+ getW(d2, d1, wF, wR, wC),
+ getW(d2, d1 + 1, wF, wR, wC),
+ getW(d2, d1 + 2, wF, wR, wC),
+ getW(d2, d1 + 3, wF, wR, wC));
+ value += dot(xValues, wValues);
+ }
+ if (inputDepthVec4Remainder == 1) {
+ ${a ? `value += getX(batch, xF, xR, xC, inputDepthNearestVec4)
+ * getW(d2, inputDepthNearestVec4, wF, wR, wC);` : `value += getX(batch, inputDepthNearestVec4, xF, xR, xC)
+ * getW(d2, inputDepthNearestVec4, wF, wR, wC);`}
+ } else if (inputDepthVec4Remainder == 2) {
+ ${a ? `let xValues = vec2(
+ getX(batch, xF, xR, xC, inputDepthNearestVec4),
+ getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));
+ ` : `let xValues = vec2(
+ getX(batch, inputDepthNearestVec4, xF, xR, xC),
+ getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));
+ `}
+ let wValues = vec2(
+ getW(d2, inputDepthNearestVec4, wF, wR, wC),
+ getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));
+ value += dot(xValues, wValues);
+ } else if (inputDepthVec4Remainder == 3) {
+ ${a ? `let xValues = vec3(
+ getX(batch, xF, xR, xC, inputDepthNearestVec4),
+ getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
+ getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));
+ ` : `let xValues = vec3(
+ getX(batch, inputDepthNearestVec4, xF, xR, xC),
+ getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),
+ getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));
+ `}
+ let wValues = vec3(
+ getW(d2, inputDepthNearestVec4, wF, wR, wC),
+ getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),
+ getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));
+ value += dot(xValues, wValues);
+ }
+ }
+ }
+ }
+ ${S ? "value = value + getBiasByOutputCoords(coords)" : ""};
+ ${Q}
+ result[global_idx] = f32(value);
+ }`;
+ };
+ return { name: "Conv3DNaive", shaderCache: { hint: `${t.cacheKey};${a};${f};${S}`, inputDependencies: _ }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: m[0], y: m[1], z: m[2] }, programUniforms: g }), getShaderSource: $ };
+ };
+});
+var Fu;
+var qu;
+var ju = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ bt();
+ Fu = (e, t, r, n) => {
+ let o = e.length > 2, i = o ? "value += b[output_channel];" : "", a = e[0].dims, u = e[1].dims, d = t.format === "NHWC", c = d ? r[3] : r[1], p = c / t.group, m = d && p >= 4 ? ce(c) : 1, f = k.size(r) / m, b = [{ type: 12, data: f }, { 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: p }];
+ qe(t, b), b.push(...N(a, [u[0], u[1], u[2], u[3] / m]));
+ let g = o ? ["rank", "rank", "rank"] : ["rank", "rank"];
+ b.push(...N([r[0], r[1], r[2], r[3] / m]));
+ let _ = (S) => {
+ let $ = M("output", e[0].dataType, r.length, m), v = be($.type.tensor), x = Fe(t, $.type.value, v), T = P("x", e[0].dataType, a.length), E = P("w", e[1].dataType, u.length, m), I = [T, E];
+ o && I.push(P("b", e[2].dataType, e[2].dims, m));
+ let z = [{ 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" }];
+ je(t, z);
+ let O = d ? `
+ for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
+ let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
+
+ if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {
+ continue;
+ }
+
+ for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {
+ let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
+ if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {
+ continue;
+ }
+
+ for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {
+ let input_channel = in_channel_offset + wInChannel;
+ let xVal = ${T.get("batch", "xHeight", "xWidth", "input_channel")};
+ let wVal = ${E.get("wHeight", "wWidth", "wInChannel", "output_channel")};
+ value += xVal * wVal;
+ }
+ }
+ }
+ ` : `
+ for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {
+ let input_channel = in_channel_offset + wInChannel;
+ for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {
+ let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
+
+ if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {
+ continue;
+ }
+
+ for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {
+ let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
+ if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {
+ continue;
+ }
+
+ let xVal = ${T.get("batch", "input_channel", "xHeight", "xWidth")};
+ let wVal = ${E.get("output_channel", "wInChannel", "wHeight", "wWidth")};
+ value += xVal * wVal;
+ }
+ }
+ }
+ `;
+ return `
+ ${S.registerUniforms(z).declareVariables(...I, $)}
+
+ ${S.mainStart()}
+ ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+
+ let outputIndices = ${$.offsetToIndices("global_idx")};
+ let batch: u32 = outputIndices[0];
+ let output_channel: u32 = outputIndices[${d ? 3 : 1}];
+ let xRCCorner: vec2 = vec2(outputIndices[${d ? 1 : 2}], outputIndices[${d ? 2 : 3}]) * uniforms.strides - uniforms.pads;
+ let group_id: u32 = output_channel * ${m} / uniforms.output_channels_per_group;
+ var in_channel_offset = group_id * uniforms.w_shape[${d ? 2 : 1}];
+
+ var value: ${$.type.value} = ${$.type.value}(0);
+ ${O}
+ ${i}
+ ${x}
+ ${$.setByOffset("global_idx", "value")}
+ }`;
+ };
+ return { name: "GroupedConv", shaderCache: { hint: `${t.cacheKey}_${m}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: n ? n(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: b }), getShaderSource: _ };
+ }, qu = (e, t, r, n) => {
+ let o = e.length > 2, i = ce(r[3]), a = ce(r[2]), u = k.size(r) / i / a, d = [e[0].dims[0], e[0].dims[1], e[0].dims[2], e[0].dims[3] / i], c = [e[1].dims[0], e[1].dims[1], e[1].dims[2], e[1].dims[3] / i], p = [r[0], r[1], r[2], r[3] / i], m = [{ type: 12, data: u }, { type: 6, data: [t.strides[0], t.strides[1]] }, { type: 6, data: [t.pads[0], t.pads[1]] }];
+ qe(t, m), m.push(...N(d, c, p));
+ let f = (a - 1) * t.strides[1] + c[1], b = (g) => {
+ let _ = M("output", e[0].dataType, p.length, i), S = be(_.type.tensor), $ = Fe(t, _.type.value, S), v = P("x", e[0].dataType, d.length, i), x = P("w", e[1].dataType, c.length, i), T = [v, x];
+ o && T.push(P("b", e[2].dataType, e[2].dims, i));
+ let E = o ? "value += b[output_channel];" : "", I = [{ name: "output_size", type: "u32" }, { name: "strides", type: "i32", length: 2 }, { name: "pads", type: "i32", length: 2 }];
+ return je(t, I), `
+ ${g.registerUniforms(I).declareVariables(...T, _)}
+ ${g.mainStart()}
+ ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let width0 = uniforms.output_shape[3];
+ let output_channel = global_idx % width0;
+ var index1 = global_idx / width0;
+ let width1 = uniforms.output_shape[2] / ${a}u;
+ let col = (index1 % width1) * ${a}u;
+ index1 = index1 / width1;
+ let row = index1 % uniforms.output_shape[1];
+ let batch = index1 / uniforms.output_shape[1];
+
+ let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;
+
+ var x_vals: array<${v.type.value}, ${f}>;
+ var values: array<${_.type.value}, ${a}>;
+ let input_channel = output_channel;
+ // Use constant instead of uniform can give better performance for w's height/width.
+ for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) {
+ let x_height = x_corner.x + i32(w_height);
+ if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {
+ for (var i = 0; i < ${f}; i++) {
+ let x_width = x_corner.y + i;
+ if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {
+ x_vals[i] = ${v.get("batch", "u32(x_height)", "u32(x_width)", "input_channel")};
+ } else {
+ x_vals[i] = ${v.type.value}(0);
+ }
+ }
+ for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) {
+ let w_val = ${x.get("w_height", "w_width", "0", "output_channel")};
+ for (var i = 0u; i < ${a}u; i++) {
+ values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);
+ }
+ }
+ }
+ }
+
+ for (var i = 0u; i < ${a}u; i++) {
+ var value = values[i];
+ ${E}
+ ${$}
+ ${_.set("batch", "row", "col + i", "output_channel", "value")};
+ }
+ }`;
+ };
+ return { name: "GroupedConv-Vectorize", shaderCache: { hint: `${t.cacheKey};${i};${a};${f};${c[0]};${c[1]}`, inputDependencies: o ? ["rank", "rank", "type"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: n ? n(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(u / 64) }, programUniforms: m }), getShaderSource: b };
+ };
+});
+var gf;
+var ho;
+var bf;
+var go;
+var bo;
+var Ku;
+var yf;
+var _f;
+var yo;
+var Zu = U(() => {
+ "use strict";
+ ne();
+ Nu();
+ Hu();
+ Xr();
+ ju();
+ bt();
+ Yr();
+ st();
+ gf = (e, t, r, n, o, i) => {
+ let a = e[0], u = e.slice(i ? 1 : 2, i ? 3 : 4), d = u.length, c = t[0], m = t.slice(2).map((g, _) => g + (g - 1) * (r[_] - 1)), b = u.map((g, _) => g + n[_] + n[_ + d]).map((g, _) => Math.floor((g - m[_] + o[_]) / o[_]));
+ return b.splice(0, 0, a), b.splice(i ? 3 : 1, 0, c), b;
+ }, ho = [2, 3, 1, 0], bf = (e, t) => {
+ if (!e || e.length !== 2 && e.length !== 3) throw new Error("Conv requires 2 or 3 inputs");
+ if (e[0].dims.length > 5) throw new Error("greater than 5D is not supported");
+ if (e[0].dims.length !== e[1].dims.length) throw new Error("filter does not have same dimension as input");
+ let r = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[1] * t.group;
+ if (r !== n) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
+ if (e.length === 3 && (e[2].dims.length !== 1 || e[1].dims[0] !== e[2].dims[0])) throw new Error("invalid bias");
+ let o = e[0].dims.length - 2;
+ if (t.dilations.length !== o) throw new Error(`dilations should be ${o}D`);
+ if (t.strides.length !== o) throw new Error(`strides should be ${o}D`);
+ if (t.pads.length !== o * 2) throw new Error(`pads should be ${o * 2}D`);
+ if (t.kernelShape.length !== 0 && t.kernelShape.length !== e[1].dims.length - 2) throw new Error("invalid kernel shape");
+ }, go = (e, t) => {
+ let r = e.kernelShape.slice();
+ r.length < t[1].dims.length - 2 && r.push(...Array(t[1].dims.length - 2 - r.length).fill(0));
+ for (let i = 2; i < t[1].dims.length; ++i) r[i - 2] === 0 && (r[i - 2] = t[1].dims[i]);
+ let n = e.pads.slice();
+ Tt.adjustPadsBasedOnAutoPad(t[0].dims, e.strides, e.dilations, r, n, e.format === "NHWC", e.autoPad);
+ let o = Object.assign({}, e);
+ return Object.assign(o, { kernelShape: r, pads: n }), o;
+ }, bo = (e) => {
+ let t = Kr(e), r = e.format, n = ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][e.auto_pad], o = e.dilations, i = e.group, a = e.kernel_shape, u = e.pads, d = e.strides, c = e.w_is_const();
+ return { autoPad: n, format: r, dilations: o, group: i, kernelShape: a, pads: u, strides: d, wIsConst: c, ...t, cacheKey: `${e.format};${t.activation};` };
+ }, Ku = (e, t, r, n) => {
+ let o = r.format === "NHWC", i = gf(t[0].dims, t[1].dims, r.dilations, r.pads, r.strides, o);
+ if (r.group !== 1) {
+ let I = [t[0]];
+ if (o) {
+ let O = e.kernelCustomData.wT ?? e.compute(Ee(t[1], ho), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0];
+ r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = O), I.push(O);
+ } else I.push(t[1]);
+ t.length === 3 && I.push(t[2]), !e.adapterInfo.isArchitecture("ampere") && o && t[1].dims[0] === r.group && t[1].dims[1] === 1 && r.dilations[0] === 1 && r.dilations[1] === 1 ? e.compute(qu(I, r, i, n), { inputs: I }) : e.compute(Fu(I, r, i, n), { inputs: I });
+ return;
+ }
+ let a = t.length === 3, u = t[0].dims[o ? 1 : 2], d = t[0].dims[o ? 2 : 3], c = t[0].dims[o ? 3 : 1], p = t[1].dims[2], m = t[1].dims[3], f = i[o ? 1 : 2], b = i[o ? 2 : 3], g = i[o ? 3 : 1], _ = o && p === u && m === d && 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 I = i[0], z, O, D, L = [];
+ if (o) {
+ let W = e.kernelCustomData.wT ?? e.compute(Ee(t[1], ho), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0];
+ if (r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = W), _) {
+ let Z = u * d * c;
+ z = t[0].reshape([1, I, Z]), O = W.reshape([1, Z, g]), D = [1, I, g];
+ } else z = t[0].reshape([I, u * d, c]), O = W.reshape([1, c, g]), D = [I, f * b, g];
+ L.push(z), L.push(O);
+ } else z = t[0].reshape([I, c, u * d]), O = t[1].reshape([1, g, c]), D = [I, g, f * b], L.push(O), L.push(z);
+ a && L.push(t[2]);
+ let q = D[2], Q = L[0].dims[L[0].dims.length - 1];
+ q < 8 && Q < 8 ? e.compute(Qr(L, r, i, D, o, n), { inputs: L }) : e.compute(Jt(L, r, i, D, o, n), { inputs: L });
+ return;
+ }
+ let S = true, $ = e.kernelCustomData.wT ?? e.compute(Ee(t[1], ho), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0];
+ r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = $);
+ let v = [t[0], $];
+ a && v.push(t[2]);
+ let x = o ? f * b : g, T = o ? g : f * b, E = p * m * c;
+ e.compute(Uu(v, r, i, x, T, E, a, S, n), { inputs: v });
+ }, yf = (e, t) => {
+ let r = t.format === "NHWC", n = [e.inputs[0].reshape(r ? [e.inputs[0].dims[0], 1, e.inputs[0].dims[1], e.inputs[0].dims[2]] : [e.inputs[0].dims[0], e.inputs[0].dims[1], 1, e.inputs[0].dims[2]]), e.inputs[1].reshape([e.inputs[1].dims[0], e.inputs[1].dims[1], 1, e.inputs[1].dims[2]])];
+ e.inputs.length === 3 && n.push(e.inputs[2]);
+ let o = [0, t.pads[0], 0, t.pads[1]], i = [1].concat(t.strides), a = [1].concat(t.dilations), u = [1].concat(t.kernelShape), d = go({ ...t, pads: o, strides: i, dilations: a, kernelShape: u }, n);
+ Ku(e, n, d, (c) => r ? [c[0], c[2], c[3]] : [c[0], c[1], c[3]]);
+ }, _f = (e, t, r) => {
+ let n = r.format === "NHWC" ? "channelsLast" : "channelsFirst", o = go(r, t), i = r.autoPad === "NOTSET" ? r.pads : r.autoPad, a = Lu(t[0].dims, t[1].dims, r.strides, r.dilations, i, false, n);
+ e.compute(Gu(t, o, a.outShape, [a.filterDepth, a.filterHeight, a.filterWidth], [a.padInfo.front, a.padInfo.top, a.padInfo.left], n));
+ }, yo = (e, t) => {
+ if (bf(e.inputs, t), e.inputs[0].dims.length === 3) yf(e, t);
+ else if (e.inputs[0].dims.length === 5) _f(e, e.inputs, t);
+ else {
+ let r = go(t, e.inputs);
+ Ku(e, e.inputs, r);
+ }
+ };
+});
+var Qu;
+var Yu = U(() => {
+ "use strict";
+ ee();
+ Xe();
+ ne();
+ ie();
+ Qu = (e, t, r) => {
+ let n = e.length > 2, o = t.outputShape, i = t.format === "NHWC", a = t.group, u = e[1].dims, d = u[2] / a, c = u[3], p = i ? ce(d) : 1, m = i && c === 1 && d >= 4, f = m ? Math.floor(d / 4) * 4 : Math.floor(d / p) * p, b = d - f, g = i ? ce(c) : 1, _ = i ? c === 1 ? p : g : 1, S = k.size(o) / g, $ = [Math.ceil(S / 64), 1, 1];
+ se("verbose", () => `[conv2d_backprop_webgpu] dispatch = ${$}`);
+ let v = ["rank", "rank"], x = [t.strides[0], t.strides[1]], T = [t.kernelShape[i ? 1 : 2], t.kernelShape[i ? 2 : 3]], E = [t.dilations[0], t.dilations[1]], I = [T[0] + (t.dilations[0] <= 1 ? 0 : (t.kernelShape[i ? 1 : 2] - 1) * (t.dilations[0] - 1)), T[1] + (t.dilations[1] <= 1 ? 0 : (t.kernelShape[i ? 2 : 3] - 1) * (t.dilations[1] - 1))], z = [I[0] - 1 - Math.floor((t.pads[0] + t.pads[2]) / 2), I[1] - 1 - Math.floor((t.pads[1] + t.pads[3]) / 2)], O = [{ type: 12, data: S }, { type: 12, data: x }, { type: 12, data: T }, { type: 12, data: E }, { type: 12, data: I }, { type: 6, data: z }, { type: 12, data: f }, { type: 12, data: d }, { type: 12, data: c }, ...N(e[0].dims, e[1].dims)];
+ n && (O.push(...N(e[2].dims)), v.push("rank")), O.push(...N(o));
+ let D = (L) => {
+ let q = [{ name: "output_size", type: "u32" }, { name: "strides", type: "u32", length: x.length }, { name: "filter_dims", type: "u32", length: T.length }, { name: "dilations", type: "u32", length: T.length }, { name: "effective_filter_dims", type: "u32", length: I.length }, { name: "pads", type: "i32", length: z.length }, { name: "input_channels_per_group_int", type: "u32" }, { name: "input_channels_per_group", type: "u32" }, { name: "output_channels_per_group", type: "u32" }], Q = be(e[0].dataType), W = i ? 1 : 2, Z = i ? 2 : 3, we = i ? 3 : 1, H = P("W", e[1].dataType, e[1].dims.length, _), j = P("Dy", e[0].dataType, e[0].dims.length, p), te = [j, H];
+ n && te.push(P("bias", e[2].dataType, [o[we]].length, g));
+ let X = M("result", e[0].dataType, o.length, g), ue = () => {
+ let re = "";
+ if (m) p === 4 ? re += `
+ let xValue = ${j.getByOffset("x_offset")};
+ let wValue = ${H.getByOffset("w_offset")};
+ dotProd = dotProd + dot(xValue, wValue);
+ x_offset += 1u;
+ w_offset += 1u;` : p === 2 ? re += `
+ dotProd = dotProd + dot(vec4<${Q}>(${j.getByOffset("x_offset")}, ${j.getByOffset("x_offset + 1u")}), vec4<${Q}>(${H.getByOffset("w_offset")}, ${H.getByOffset("w_offset + 1u")}));
+ x_offset += 2u;
+ w_offset += 2u;` : p === 1 && (re += `
+ dotProd = dotProd + dot(vec4<${Q}>(${j.getByOffset("x_offset")}, ${j.getByOffset("x_offset + 1u")}, ${j.getByOffset("x_offset + 2u")}, ${j.getByOffset("x_offset + 3u")}), vec4<${Q}>(${H.getByOffset("w_offset")}, ${H.getByOffset("w_offset + 1u")}, ${H.getByOffset("w_offset + 2u")}, ${H.getByOffset("w_offset + 3u")}));
+ x_offset += 4u;
+ w_offset += 4u;`);
+ else if (re += `
+ let xValue = ${i ? j.getByOffset(`${j.indicesToOffset(`${j.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`) : j.get("batch", "inputChannel", "idyR", "idyC")};
+ `, p === 1) re += `
+ let w_offset = ${H.indicesToOffset(`${H.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
+ let wValue = ${H.getByOffset(`w_offset / ${_}`)};
+ dotProd = dotProd + xValue * wValue;`;
+ else for (let C = 0; C < p; C++) re += `
+ let wValue${C} = ${H.getByOffset(`${H.indicesToOffset(`${H.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${C}, wOutChannel)`)} / ${_}`)};
+ dotProd = dotProd + xValue[${C}] * wValue${C};`;
+ return re;
+ }, he = () => {
+ if (b === 0) return "";
+ if (!m) throw new Error(`packInputAs4 ${m} is not true.`);
+ let re = "";
+ if (p === 1) {
+ re += "dotProd = dotProd";
+ for (let C = 0; C < b; C++) re += `
+ + ${j.getByOffset(`x_offset + ${C}`)} * ${H.getByOffset(`w_offset + ${C}`)}`;
+ re += ";";
+ } else if (p === 2) {
+ if (b !== 2) throw new Error(`Invalid inputChannelsRemainder ${b}.`);
+ re += `
+ let xValue = ${j.getByOffset("x_offset")};
+ let wValue = ${H.getByOffset("w_offset")};
+ dotProd = dotProd + dot(xValue, wValue);`;
+ }
+ return re;
+ }, ye = `
+ let outputIndices = ${X.offsetToIndices(`global_idx * ${g}`)};
+ let batch = ${X.indicesGet("outputIndices", 0)};
+ let d1 = ${X.indicesGet("outputIndices", we)};
+ let r = ${X.indicesGet("outputIndices", W)};
+ let c = ${X.indicesGet("outputIndices", Z)};
+ let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;
+ let dyRCorner = dyCorner.x;
+ let dyCCorner = dyCorner.y;
+ let groupId = d1 / uniforms.output_channels_per_group;
+ let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;
+ // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
+ // ? = to be determined. : = across all values in that axis.
+ var dotProd = ${X.type.value}(0.0);
+ var wR: u32 = 0;
+ if (uniforms.dilations.x == 1) {
+ // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
+ wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);
+ }
+ for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {
+ if (wR % uniforms.dilations.x != 0) {
+ continue;
+ }
+ let dyR = (${Q}(dyRCorner) + ${Q}(wR)) / ${Q}(uniforms.strides[0]);
+ let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
+ if (dyR < 0.0 || dyR >= ${Q}(uniforms.Dy_shape[${W}]) || fract(dyR) > 0.0 ||
+ wRPerm < 0) {
+ continue;
+ }
+ let idyR: u32 = u32(dyR);
+ var wC: u32 = 0;
+ if (uniforms.dilations.y == 1) {
+ // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0
+ wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);
+ }
+ for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {
+ if (wC % uniforms.dilations.y != 0) {
+ continue;
+ }
+ let dyC = (${Q}(dyCCorner) + ${Q}(wC)) / ${Q}(uniforms.strides.y);
+ let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
+ if (dyC < 0.0 || dyC >= ${Q}(uniforms.Dy_shape[${Z}]) ||
+ fract(dyC) > 0.0 || wCPerm < 0) {
+ continue;
+ }
+ let idyC: u32 = u32(dyC);
+ var inputChannel = groupId * uniforms.input_channels_per_group;
+ ${m ? `
+ var x_offset = ${j.indicesToOffset(`${j.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p};
+ var w_offset = ${H.indicesToOffset(`${H.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${_};
+ ` : ""}
+ for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${m ? 4 : p}) {
+ ${ue()}
+ inputChannel = inputChannel + ${m ? 4 : p};
+ }
+ ${he()}
+ wC = wC + uniforms.strides.y - 1;
+ }
+ wR = wR + uniforms.strides[0] - 1;
+ }
+ let value = dotProd${n ? ` + bias[d1 / ${g}]` : ""};
+ ${X.setByOffset("global_idx", "value")};
+ `;
+ return `
+ ${L.registerUniforms(q).declareVariables(...te, X)}
+ ${L.mainStart()}
+ ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
+ ${ye}}`;
+ };
+ return { name: "ConvTranspose2D", shaderCache: { hint: `${t.cacheKey};${p}${_}${g}${m}${b}`, inputDependencies: v }, getRunData: () => ({ dispatchGroup: { x: $[0], y: $[1], z: $[2] }, outputs: [{ dims: r ? r(o) : o, dataType: e[0].dataType }], programUniforms: O }), getShaderSource: D };
+ };
+});
+var wf;
+var vf;
+var $f;
+var Xu;
+var Ju;
+var xf;
+var ed;
+var Sf;
+var td;
+var rd = U(() => {
+ "use strict";
+ Yu();
+ bt();
+ st();
+ wf = (e, t, r, n, o, i) => (e - 1) * t + r + (n - 1) * o + 1 - i, vf = (e, t, r, n, o) => {
+ let i = Math.floor(e / 2);
+ t === "SAME_UPPER" ? (r[n] = i, r[o] = e - i) : t === "SAME_LOWER" && (r[n] = e - i, r[o] = i);
+ }, $f = (e, t, r, n, o, i, a, u, d, c) => {
+ let p = e.length - 2, m = c.length === 0;
+ d.length < p && d.push(...Array(p - d.length).fill(0));
+ let f = e[0], b = t[u ? 3 : 1] * o;
+ for (let g = 0, _ = e.length - p - (u ? 1 : 0); g < p; ++g, ++_) {
+ let S = e[_], $ = m ? S * a[g] : c[g], v = wf(S, a[g], i[g], t[_], r[g], $);
+ vf(v, n, i, g, g + p), m && c.push(a[g] * (S - 1) + d[g] + (t[_] - 1) * r[g] + 1 - i[g] - i[g + p]);
+ }
+ c.splice(0, 0, f), c.splice(u ? 3 : 1, 0, b);
+ }, Xu = (e, t) => {
+ let r = e.kernelShape.slice();
+ if (e.kernelShape.length === 0 || e.kernelShape.reduce((m, f) => m * f, 1) === 0) {
+ r.length = 0;
+ for (let m = 2; m < t[1].dims.length; ++m) r.push(t[1].dims[m]);
+ }
+ let n = e.format === "NHWC";
+ r.splice(0, 0, t[1].dims[0]), r.splice(n ? 3 : 1, 0, t[1].dims[1]);
+ let o = e.pads.slice(), i = e.outputShape.slice(), a = e.outputPadding.slice(), u = t[0].dims, d = e.dilations.slice();
+ if (d.reduce((m, f) => m + f, 0) === 0) {
+ let m = t[0].dims.length - 2;
+ d = new Array(m).fill(1);
+ }
+ let c = e.strides.slice();
+ if (c.reduce((m, f) => m + f, 0) === 0) {
+ let m = t[0].dims.length - 2;
+ c = new Array(m).fill(1);
+ }
+ $f(u, r, d, e.autoPad, e.group, o, c, n, a, i);
+ let p = Object.assign({}, e);
+ return Object.assign(p, { kernelShape: r, pads: o, outputPadding: a, outputShape: i, dilations: d, strides: c }), p;
+ }, Ju = (e) => {
+ let t = Kr(e), r = e.format, n = ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][typeof e.autoPad > "u" ? 0 : e.autoPad], o = e.dilations, i = e.group, a = e.kernelShape, u = e.pads, d = e.strides, c = e.wIsConst(), p = e.outputPadding, m = e.outputShape;
+ return { autoPad: n, format: r, dilations: o, group: i, kernelShape: a, outputPadding: p, outputShape: m, pads: u, strides: d, wIsConst: c, ...t, cacheKey: `${e.format};${t.activation};` };
+ }, xf = (e, t) => {
+ if (!e || e.length !== 2 && e.length !== 3) throw new Error("Conv requires 2 or 3 inputs");
+ if (e[0].dims.length !== 4 && e[0].dims.length !== 3) throw new Error("currently only support 2-dimensional conv");
+ if (e[0].dims.length !== e[1].dims.length) throw new Error("filter does not have same dimension as input");
+ let r = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[0];
+ if (r !== n) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
+ let o = e[1].dims[1] * t.group;
+ if (e.length === 3 && (e[2].dims.length !== 1 || e[2].dims[0] !== o)) throw new Error("invalid bias");
+ let i = e[0].dims.length - 2;
+ if (t.dilations.reduce((p, m) => p + m, 0) > 0 && t.dilations.length !== i) throw new Error(`dilations should be ${i}D`);
+ if (t.strides.reduce((p, m) => p + m, 0) > 0 && t.strides.length !== i) throw new Error(`strides should be ${i}D`);
+ if (t.pads.reduce((p, m) => p + m, 0) > 0 && t.pads.length !== i * 2) throw new Error(`pads should be ${i * 2}D`);
+ if (t.outputPadding.length !== i && t.outputPadding.length !== 0) throw new Error(`output_padding should be ${i}D`);
+ if (t.kernelShape.reduce((p, m) => p + m, 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");
+ }, ed = (e, t, r, n) => {
+ let o = e.kernelCustomData.wT ?? e.compute(Ee(t[1], [2, 3, 0, 1]), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0];
+ r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = o);
+ let i = [t[0], o];
+ t.length === 3 && i.push(t[2]), e.compute(Qu(i, r, n), { inputs: i });
+ }, Sf = (e, t) => {
+ let r = t.format === "NHWC", n = [e.inputs[0].reshape(r ? [e.inputs[0].dims[0], 1, e.inputs[0].dims[1], e.inputs[0].dims[2]] : [e.inputs[0].dims[0], e.inputs[0].dims[1], 1, e.inputs[0].dims[2]]), e.inputs[1].reshape([e.inputs[1].dims[0], e.inputs[1].dims[1], 1, e.inputs[1].dims[2]])];
+ e.inputs.length === 3 && n.push(e.inputs[2]);
+ let o = t.kernelShape;
+ (o.length === 0 || o[0] === 0) && (o = [e.inputs[1].dims[2]]);
+ let i = t.dilations;
+ (i.length === 0 || i[0] === 0) && (i = [1]);
+ let a = t.strides;
+ (a.length === 0 || a[0] === 0) && (a = [1]);
+ let u = t.pads;
+ u.length === 0 && (u = [0, 0]), u = [0, u[0], 0, u[1]], a = [1].concat(a), i = [1].concat(i), o = [1].concat(o);
+ let d = t.outputPadding;
+ d = [0].concat(d);
+ let c = Xu({ ...t, pads: u, strides: a, dilations: i, kernelShape: o, outputPadding: d }, n);
+ ed(e, n, c, (p) => r ? [p[0], p[2], p[3]] : [p[0], p[1], p[3]]);
+ }, td = (e, t) => {
+ if (xf(e.inputs, t), e.inputs[0].dims.length === 3) Sf(e, t);
+ else {
+ let r = Xu(t, e.inputs);
+ ed(e, e.inputs, r);
+ }
+ };
+});
+var Tf;
+var nd;
+var od;
+var id = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ Tf = (e, t, r, n) => {
+ let o = k.size(t), i = t.length, a = P("input", e, i), u = M("output", e, i), d = r.dataType === 6 ? r.getInt32Array()[0] : Number(r.getBigInt64Array()[0]), c = k.normalizeAxis(d, i), p = (m) => {
+ let f = ` i32(${a.indicesGet("inputIndices", "uniforms.axis")}) `, b = F("uniforms.input_shape", "uniforms.axis", i), g = n.reverse ? f + (n.exclusive ? " + 1" : "") : "0", _ = n.reverse ? b : f + (n.exclusive ? "" : " + 1");
+ return `
+ ${m.registerUniform("outputSize", "u32").registerUniform("axis", "u32").declareVariables(a, u)}
+ ${m.mainStart()}
+ ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+ var inputIndices = ${u.offsetToIndices("global_idx")};
+ var sum = ${u.type.value}(0);
+ let first : i32 = ${g};
+ let last : i32 = ${_};
+ for (var i : i32 = first; i < last; i++) {
+ ${a.indicesSet("inputIndices", "uniforms.axis", "u32(i)")};
+ sum = sum + ${a.getByIndices("inputIndices")};
+ }
+ ${u.setByOffset("global_idx", "sum")};
+ }`;
+ };
+ return { name: "CumSum", shaderCache: { hint: n.cacheKey, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: t, dataType: e }], dispatchGroup: { x: Math.ceil(o / 64) }, programUniforms: [{ type: 12, data: o }, { type: 12, data: c }, ...N(t, t)] }), getShaderSource: p };
+ }, nd = (e, t) => {
+ let r = e.inputs[0].dims, n = e.inputs[0].dataType, o = e.inputs[1];
+ e.compute(Tf(n, r, o, t), { inputs: [0] });
+ }, od = (e) => {
+ let t = e.exclusive === 1, r = e.reverse === 1;
+ return J({ exclusive: t, reverse: r });
+ };
+});
+var If;
+var Cf;
+var Af;
+var ad;
+var sd;
+var ud = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ If = (e) => {
+ if (!e || e.length !== 1) throw new Error("DepthToSpace requires 1 input.");
+ if (e[0].dims.length !== 4) throw new Error("DepthToSpace requires 4D input.");
+ }, Cf = (e, t, r, n) => {
+ let o = [];
+ o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {
+ var a: ${r.type.indices};`);
+ for (let i = 0; i < t; ++i) o.push(r.indicesSet("a", e[i], `i[${i}]`));
+ return o.push("return a;}"), o.join(`
+`);
+ }, Af = (e, t) => {
+ let r, n, o, i, a, u, d = t.format === "NHWC", c = t.blocksize, p = t.mode === "DCR";
+ d ? ([r, n, o, i] = e.dims, a = p ? [r, n, o, c, c, i / c ** 2] : [r, n, o, i / c ** 2, c, c], u = p ? [0, 1, 3, 2, 4, 5] : [0, 1, 4, 2, 5, 3]) : ([r, n, o, i] = [e.dims[0], e.dims[2], e.dims[3], e.dims[1]], a = p ? [r, c, c, i / c ** 2, n, o] : [r, i / c ** 2, c, c, n, o], u = p ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3]);
+ let m = e.reshape(a), f = m.dims.length, b = e.dataType, g = P("a", b, f), _ = M("output", b, f), S = ($) => `
+ ${$.registerUniform("output_size", "u32").declareVariables(g, _)}
+
+ ${Cf(u, f, g, _)}
+
+ ${$.mainStart()}
+ ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+
+ let indices = ${_.offsetToIndices("global_idx")};
+ let aIndices = perm(indices);
+
+ ${_.setByOffset("global_idx", g.getByIndices("aIndices"))}
+ }`;
+ return { name: "DepthToSpace", shaderCache: { hint: `${e.dims};${t.blocksize};${t.mode}`, inputDependencies: ["rank"] }, getRunData: ($) => {
+ let v = d ? [r, n * c, o * c, i / c ** 2] : [r, i / c ** 2, n * c, o * c], x = k.size(v), T = m.dims, E = k.sortBasedOnPerm(T, u);
+ return { outputs: [{ dims: v, dataType: $[0].dataType }], dispatchGroup: { x: Math.ceil(x / 64) }, programUniforms: [{ type: 12, data: x }, ...N(T, E)] };
+ }, getShaderSource: S };
+ }, ad = (e, t) => {
+ If(e.inputs), e.compute(Af(e.inputs[0], t));
+ }, sd = (e) => J({ blocksize: e.blocksize, mode: e.mode, format: e.format });
+});
+var _o;
+var en;
+var dd;
+var Ef;
+var kf;
+var wo;
+var vo;
+var ld;
+var Pf;
+var cd;
+var pd;
+var md = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ _o = "[a-zA-Z]|\\.\\.\\.", en = "(" + _o + ")+", dd = "^" + en + "$", Ef = "(" + en + ",)*" + en, kf = "^" + Ef + "$", wo = class {
+ constructor(t = -1) {
+ this.symbolToIndices = /* @__PURE__ */ new Map(), this.inputIndex = t;
+ }
+ addSymbol(t, r) {
+ let n = this.symbolToIndices.get(t);
+ n === void 0 ? n = [r] : n.push(r), this.symbolToIndices.set(t, n);
+ }
+ }, vo = class {
+ constructor(t, r) {
+ this.equation = r;
+ this.hasEllipsis = false, this.symbolToInfo = /* @__PURE__ */ new Map(), this.lhs = new Array(), this.outputDims = [];
+ let [n, o] = r.includes("->") ? r.split("->", 2) : [r, ""];
+ if (!n.match(RegExp(kf))) throw new Error("Invalid LHS term");
+ if (n.split(",").forEach((u, d) => {
+ let c = t[d].dims.slice();
+ if (!u.match(RegExp(dd))) throw new Error("Invalid LHS term");
+ let p = this.processTerm(u, true, c, d);
+ this.lhs.push(p);
+ }), o === "") o += [...this.symbolToInfo.entries()].filter(([u, d]) => d.count === 1 || u === "...").map(([u]) => u).join("");
+ else if (!o.match(RegExp(en))) throw new Error("Invalid RHS");
+ o.match(RegExp(_o, "g"))?.forEach((u) => {
+ if (u === "...") this.outputDims = this.outputDims.concat(this.ellipsisDims);
+ else {
+ let d = this.symbolToInfo.get(u);
+ if (d === void 0) throw new Error("Invalid RHS symbol");
+ this.outputDims.push(d.dimValue);
+ }
+ }), this.rhs = this.processTerm(o, false, this.outputDims);
+ }
+ addSymbol(t, r, n) {
+ let o = this.symbolToInfo.get(t);
+ if (o !== void 0) {
+ if (o.dimValue !== r && o.count !== 1) throw new Error("Dimension mismatch");
+ o.count++, o.inputIndices.push(n);
+ } else o = { count: 1, dimValue: r, inputIndices: [n] };
+ this.symbolToInfo.set(t, o);
+ }
+ processTerm(t, r, n, o = -1) {
+ let i = n.length, a = false, u = [], d = 0;
+ if (!t.match(RegExp(dd)) && !r && t !== "") throw new Error("Invalid LHS term");
+ let c = t.match(RegExp(_o, "g")), p = new wo(o);
+ return c?.forEach((m, f) => {
+ if (m === "...") {
+ if (a) throw new Error("Only one ellipsis is allowed per input term");
+ a = true;
+ let b = i - c.length + 1;
+ if (b < 0) throw new Error("Ellipsis out of bounds");
+ if (u = n.slice(d, d + b), this.hasEllipsis) {
+ if (this.ellipsisDims.length !== u.length || this.ellipsisDims.toString() !== u.toString()) throw new Error("Ellipsis dimensions mismatch");
+ } else if (r) this.hasEllipsis = true, this.ellipsisDims = u;
+ else throw new Error("Ellipsis must be specified in the LHS");
+ for (let g = 0; g < u.length; g++) {
+ let _ = String.fromCharCode(48 + g);
+ p.addSymbol(_, f + g), this.addSymbol(_, n[d++], o);
+ }
+ } else p.addSymbol(m, f + (this.hasEllipsis ? this.ellipsisDims.length - 1 : 0)), this.addSymbol(m, n[d++], o);
+ }), p;
+ }
+ }, ld = (e) => e + "_max", Pf = (e, t, r, n) => {
+ let i = e.map((p) => p.length).map((p, m) => P(`input${m}`, t, p)), a = k.size(n), u = M("output", t, n.length), d = [...r.symbolToInfo.keys()].filter((p) => !r.rhs.symbolToIndices.has(p)), c = (p) => {
+ let m = [], f = "var prod = 1.0;", b = "var sum = 0.0;", g = "sum += prod;", _ = [], S = [], $ = [], v = [], x = r.symbolToInfo.size === r.rhs.symbolToIndices.size;
+ r.symbolToInfo.forEach((E, I) => {
+ if (r.rhs.symbolToIndices.has(I)) {
+ let z = r.rhs.symbolToIndices.get(I)?.[0];
+ z !== void 0 && r.lhs.forEach((O, D) => {
+ if (E.inputIndices.includes(D)) {
+ let L = O.symbolToIndices.get(I);
+ if (L === void 0) throw new Error("Invalid symbol error");
+ L.forEach((q) => {
+ m.push(`${i[D].indicesSet(`input${D}Indices`, q, u.indicesGet("outputIndices", z))}`);
+ });
+ }
+ });
+ } else r.lhs.forEach((z, O) => {
+ if (E.inputIndices.includes(O)) {
+ let D = z.symbolToIndices.get(I);
+ if (D === void 0) throw new Error("Invalid symbol error");
+ D.forEach((L) => {
+ _.push(`${i[O].indicesSet(`input${O}Indices`, L, `${I}`)}`);
+ }), v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`);
+ }
+ }), S.push(`for(var ${I}: u32 = 0; ${I} < uniforms.${ld(I)}; ${I}++) {`), $.push("}");
+ });
+ let T = x ? [...m, `let sum = ${i.map((E, I) => E.getByIndices(`input${I}Indices`)).join(" * ")};`] : [...m, b, ...S, ..._, f, ...v, g, ...$];
+ return `
+ ${p.registerUniforms(d.map((E) => ({ name: `${ld(E)}`, type: "u32" }))).registerUniform("outputSize", "u32").declareVariables(...i, u)}
+
+ ${p.mainStart()}
+ ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+ var outputIndices = ${u.offsetToIndices("global_idx")};
+ ${i.map((E, I) => `var input${I}Indices: ${i[I].type.indices};`).join(`
+`)}
+ ${T.join(`
+`)};
+ ${u.setByOffset("global_idx", "sum")};
+ }`;
+ };
+ return { name: "Einsum", shaderCache: { hint: r.equation, inputDependencies: e.map(() => "rank") }, getRunData: () => {
+ let p = d.filter((f) => r.symbolToInfo.has(f)).map((f) => ({ type: 12, data: r.symbolToInfo.get(f)?.dimValue || 0 }));
+ p.push({ type: 12, data: a });
+ let m = e.map((f, b) => [...N(f)]).reduce((f, b) => f.concat(b), p);
+ return m.push(...N(n)), { outputs: [{ dims: n, dataType: t }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: m };
+ }, getShaderSource: c };
+ }, cd = (e, t) => {
+ let r = new vo(e.inputs, t.equation), n = r.outputDims, o = e.inputs.map((i, a) => i.dims);
+ e.compute(Pf(o, e.inputs[0].dataType, r, n));
+ }, pd = (e) => {
+ let t = e.equation.replace(/\s+/g, "");
+ return J({ equation: t });
+ };
+});
+var zf;
+var fd;
+var Of;
+var Bf;
+var hd;
+var gd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ zf = (e) => {
+ if (!e || e.length !== 2) throw new Error("Expand requires 2 input.");
+ let t = e[0].dims, r = Array.from(e[1].getBigInt64Array(), Number), n = r.length < t.length ? 0 : r.length - t.length, o = t.length < r.length ? 0 : t.length - r.length;
+ for (; n < r.length && o < t.length; ++n, ++o) if (r[n] !== t[o] && r[n] !== 1 && t[o] !== 1) throw new Error("Expand requires shape to be broadcastable to input");
+ }, fd = (e, t) => {
+ let r = e.length - t.length, n = [];
+ for (let o = 0; o < r; ++o) n.push(e[o]);
+ for (let o = 0; o < t.length; ++o) n.push(t[o] === 1 ? e[o + r] : t[o]);
+ return n;
+ }, Of = (e, t) => e.length > t.length ? fd(e, t) : fd(t, e), Bf = (e) => {
+ let t = e[0].dims, r = Array.from(e[1].getBigInt64Array(), Number), n = Of(t, r), o = e[0].dataType, i = o === 9 || k.size(t) === 1, a = o === 9 || t.length > 0 && t[t.length - 1] % 4 === 0 ? 4 : 1, u = i || n.length > 0 && n[n.length - 1] % 4 === 0 ? 4 : 1, d = Math.ceil(k.size(n) / u), c = (m) => {
+ let f = P("input", o, t.length, a), b = M("output", o, n.length, u), g;
+ if (o === 9) {
+ let _ = (S, $, v = "") => `
+ let outputIndices${$} = ${b.offsetToIndices(`outputOffset + ${$}u`)};
+ let offset${$} = ${f.broadcastedIndicesToOffset(`outputIndices${$}`, b)};
+ let index${$} = offset${$} / 4u;
+ let component${$} = offset${$} % 4u;
+ ${S}[${$}] = ${v}(${f.getByOffset(`index${$}`)}[component${$}]);
+ `;
+ g = `
+ let outputOffset = global_idx * ${u};
+ var data = vec4(0);
+ ${_("data", 0, "u32")}
+ ${_("data", 1, "u32")}
+ ${_("data", 2, "u32")}
+ ${_("data", 3, "u32")}
+ ${b.setByOffset("global_idx", "data")}
+ }`;
+ } else g = `
+ let outputIndices = ${b.offsetToIndices(`global_idx * ${u}`)};
+ let inputOffset = ${f.broadcastedIndicesToOffset("outputIndices", b)};
+ let data = ${b.type.value}(${f.getByOffset(`inputOffset / ${a}`)});
+ ${b.setByOffset("global_idx", "data")}
+ }`;
+ return `
+ ${m.registerUniform("vec_size", "u32").declareVariables(f, b)}
+ ${m.mainStart()}
+ ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
+ ${g}`;
+ }, p = [{ type: 12, data: d }, ...N(t, n)];
+ return { name: "Expand", shaderCache: { hint: `${n.length};${a}${u}`, inputDependencies: ["rank"] }, getShaderSource: c, getRunData: () => ({ outputs: [{ dims: n, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: p }) };
+ }, hd = (e) => {
+ zf(e.inputs), e.compute(Bf(e.inputs), { inputs: [0] });
+ };
+});
+var Df;
+var bd;
+var yd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ jr();
+ Df = (e) => {
+ let t = e[0].dataType, r = k.size(e[0].dims), n = k.size(e[1].dims), o = n % 4 === 0, i = (a) => {
+ let u = P("x", t, [1], 4), d = P("bias", t, [1], 4), c = M("y", t, [1], 4), p = [{ name: "output_vec_size", type: "u32" }, { name: "bias_size", type: "u32" }], m = (b) => `
+ let bias${b}_offset: u32 = (global_idx * 4 + ${b}) % uniforms.bias_size;
+ let bias${b} = ${d.getByOffset(`bias${b}_offset / 4`)}[bias${b}_offset % 4];`, f = o ? `
+ let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};` : `${m(0)}${m(1)}${m(2)}${m(3)}
+ let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;
+ return `${a.registerUniforms(p).declareVariables(u, d, c)}
+
+ ${co(Ae(t))}
+
+ ${a.mainStart(It)}
+ ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
+
+ let x = ${u.getByOffset("global_idx")};
+ ${f}
+ let x_in = x + bias;
+ ${c.setByOffset("global_idx", po("x_in"))}
+ }`;
+ };
+ return { name: "FastGeluWithBias", shaderCache: { hint: `${o}`, inputDependencies: ["type", "type"] }, getShaderSource: i, getRunData: (a) => ({ outputs: [{ dims: a[0].dims, dataType: a[0].dataType }], programUniforms: [{ type: 12, data: Math.ceil(r / 4) }, { type: 12, data: n }], dispatchGroup: { x: Math.ceil(r / It / 4) } }) };
+ }, bd = (e) => {
+ e.inputs.length < 2 || k.size(e.inputs[1].dims) === 0 ? mu(e) : e.compute(Df(e.inputs));
+ };
+});
+var Mf;
+var Rf;
+var _d;
+var wd;
+var vd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ Mf = (e) => {
+ if (!e || e.length !== 2) throw new Error("Gather requires 2 inputs.");
+ }, Rf = (e, t) => {
+ let r = e[0].dims, n = e[1].dims, o = r.length, i = k.normalizeAxis(t.axis, o), a = r.slice(0);
+ a.splice(i, 1, ...n);
+ let u = r[i], d = e[0].dataType === 9 ? 4 : 1, c = Math.ceil(k.size(a) / d), p = [{ type: 12, data: c }, { type: 6, data: u }, { type: 12, data: i }, ...N(e[0].dims, e[1].dims, a)], m = (f) => {
+ let b = P("data", e[0].dataType, e[0].dims.length, d), g = P("inputIndices", e[1].dataType, e[1].dims.length), _ = M("output", e[0].dataType, a.length, d), S = (v) => {
+ let x = n.length, T = `var indicesIndices${v} = ${g.type.indices}(0);`;
+ for (let E = 0; E < x; E++) T += `${x > 1 ? `indicesIndices${v}[${E}]` : `indicesIndices${v}`} = ${a.length > 1 ? `outputIndices${v}[uniforms.axis + ${E}]` : `outputIndices${v}`};`;
+ T += `
+ var idx${v} = ${g.getByIndices(`indicesIndices${v}`)};
+ if (idx${v} < 0) {
+ idx${v} = idx${v} + uniforms.axisDimLimit;
+ }
+ var dataIndices${v} : ${b.type.indices};
+ `;
+ for (let E = 0, I = 0; E < o; E++) E === i ? (T += `${o > 1 ? `dataIndices${v}[${E}]` : `dataIndices${v}`} = u32(idx${v});`, I += x) : (T += `${o > 1 ? `dataIndices${v}[${E}]` : `dataIndices${v}`} = ${a.length > 1 ? `outputIndices${v}[${I}]` : `outputIndices${v}`};`, I++);
+ return T;
+ }, $;
+ if (e[0].dataType === 9) {
+ let v = (x, T, E = "") => `
+ let outputIndices${T} = ${_.offsetToIndices(`outputOffset + ${T}u`)};
+ ${S(T)};
+ let offset${T} = ${b.indicesToOffset(`dataIndices${T}`)};
+ let index${T} = offset${T} / 4u;
+ let component${T} = offset${T} % 4u;
+ ${x}[${T}] = ${E}(${b.getByOffset(`index${T}`)}[component${T}]);
+ `;
+ $ = `
+ let outputOffset = global_idx * ${d};
+ var value = vec4(0);
+ ${v("value", 0, "u32")}
+ ${v("value", 1, "u32")}
+ ${v("value", 2, "u32")}
+ ${v("value", 3, "u32")}
+ ${_.setByOffset("global_idx", "value")}
+ `;
+ } else $ = `
+ let outputIndices = ${_.offsetToIndices("global_idx")};
+ ${S("")};
+ let value = ${b.getByIndices("dataIndices")};
+ ${_.setByOffset("global_idx", "value")};
+ `;
+ return `
+ ${f.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(b, g, _)}
+ ${f.mainStart()}
+ ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+ ${$}
+ }`;
+ };
+ return { name: "Gather", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: a, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(c / 64) }, programUniforms: p }), getShaderSource: m };
+ }, _d = (e) => J({ axis: e.axis }), wd = (e, t) => {
+ let r = e.inputs;
+ Mf(r), e.compute(Rf(e.inputs, t));
+ };
+});
+var Uf;
+var $d;
+var xd;
+var Sd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ Uf = (e, t, r, n, o, i, a, u, d) => {
+ let c = [{ type: 12, data: i }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: r }, { type: 12, data: a }, { type: 12, data: u }, { type: 12, data: d }], p = [i];
+ c.push(...N(t.dims, p));
+ let m = (f) => {
+ let b = P("indices_data", t.dataType, t.dims.length), g = M("input_slice_offsets_data", 12, 1, 1), _ = [b, g], S = [{ name: "output_size", type: "u32" }, { name: "batch_dims", type: "u32" }, { name: "input_dims", type: "u32", length: o.length }, { name: "sizes_from_slice_dims_data", type: "u32", length: r.length }, { name: "num_slices_per_batch", type: "u32" }, { name: "input_batch_stride", type: "u32" }, { name: "num_slice_dims", type: "u32" }];
+ return `
+ ${f.registerUniforms(S).declareVariables(..._)}
+ ${f.mainStart()}
+ ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let batch_idx = global_idx / uniforms.num_slices_per_batch;
+ let base_offset = batch_idx * uniforms.input_batch_stride;
+
+ let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;
+ var relative_slice_offset = 0;
+ for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {
+ var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);
+ let input_dim_idx = uniforms.batch_dims + dim_idx;
+ if (index < 0) {
+ ${o.length === 1 ? "index += i32(uniforms.input_dims);" : "index += i32(uniforms.input_dims[input_dim_idx]);"}
+ }
+ ${r.length === 1 ? "relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);" : "relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}
+ }
+
+ input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
+ }`;
+ };
+ return e.compute({ name: "computeSliceOffsets", shaderCache: { hint: `${o.length}_${r.length}`, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: p, dataType: e.inputs[1].dataType }], dispatchGroup: { x: Math.ceil(i / 64) }, programUniforms: c }), getShaderSource: m }, { inputs: [t], outputs: [-1] })[0];
+ }, $d = (e, t) => {
+ let r = e.inputs, n = r[0].dims, o = r[0].dataType, i = r[1].dims, a = i[i.length - 1], u = k.sizeToDimension(i, i.length - 1), d = k.sizeFromDimension(n, t.batchDims + a), c = k.sizeToDimension(n, t.batchDims), p = k.sizeFromDimension(n, t.batchDims), m = u / c, f = new Array(a), b = d;
+ for (let T = 0; T < a; ++T) f[a - 1 - T] = b, b *= n[t.batchDims + a - 1 - T];
+ let g = Uf(e, r[1], f, t.batchDims, n, u, m, p, a), _ = t.batchDims + a;
+ if (_ > n.length) throw new Error("last dimension of indices must not be larger than rank of input tensor");
+ let S = i.slice(0, -1).concat(n.slice(_)), $ = k.size(S), v = [{ type: 12, data: $ }, { type: 12, data: d }, ...N(r[0].dims, g.dims, S)], x = (T) => {
+ let E = P("data", r[0].dataType, r[0].dims.length), I = P("slice_offsets", 12, g.dims.length), z = M("output", r[0].dataType, S.length);
+ return `
+ ${T.registerUniform("output_size", "u32").registerUniform("slice_size", "u32").declareVariables(E, I, z)}
+ ${T.mainStart()}
+ ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
+ output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
+ }`;
+ };
+ e.compute({ name: "GatherND", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: S, dataType: o }], dispatchGroup: { x: Math.ceil($ / 64) }, programUniforms: v }), getShaderSource: x }, { inputs: [r[0], g] });
+ }, xd = (e) => ({ batchDims: e.batch_dims, cacheKey: "" });
+});
+var Nf;
+var Vf;
+var Td;
+var Id;
+var Cd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ Nf = (e, t) => {
+ if (e.length < 3 || e.length > 4) throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");
+ let r = k.normalizeAxis(t.quantizeAxis, e[0].dims.length), n = t.blockSize, o = e[0], i = e[2], a = e.length === 4 ? e[3] : void 0;
+ if (i.dims.length !== o.dims.length || !o.dims.map((u, d) => d === r ? Math.ceil(u / n) === i.dims[d] : u === i.dims[d]).reduce((u, d) => u && d, true)) throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");
+ if (a) {
+ if (a.dataType !== o.dataType) throw new Error("Zero point must have the same data type as the input tensor.");
+ if (a.dims.length !== i.dims.length || !a.dims.map((u, d) => u === i.dims[d]).reduce((u, d) => u && d, true)) throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.");
+ }
+ }, Vf = (e, t) => {
+ let r = e[0].dims, n = e[1].dims, o = r.length, i = k.normalizeAxis(t.gatherAxis, o), a = k.normalizeAxis(t.quantizeAxis, o), u = r.slice(0);
+ u.splice(i, 1, ...n);
+ let d = k.size(u), c = e[2].dataType, m = e[0].dataType === 22, f = [{ type: 12, data: d }, { type: 12, data: a }, { type: 12, data: i }, { type: 12, data: t.blockSize }, ...N(...e.map((g, _) => g.dims), u)], b = (g) => {
+ let _ = P("data", e[0].dataType, e[0].dims.length), S = P("inputIndices", e[1].dataType, e[1].dims.length), $ = P("scales", e[2].dataType, e[2].dims.length), v = e.length > 3 ? P("zeroPoint", e[3].dataType, e[3].dims.length) : void 0, x = M("output", c, u.length), T = [_, S, $];
+ v && T.push(v);
+ let E = [{ name: "output_size", type: "u32" }, { name: "quantize_axis", type: "u32" }, { name: "gather_axis", type: "u32" }, { name: "block_size", type: "u32" }];
+ return `
+ ${g.registerUniforms(E).declareVariables(...T, x)}
+ ${g.mainStart()}
+ let output_indices = ${x.offsetToIndices("global_idx")};
+ var indices_indices = ${S.type.indices}(0);
+ ${n.length > 1 ? `
+ for (var i: u32 = 0; i < ${n.length}; i++) {
+ let index = ${x.indicesGet("output_indices", "uniforms.gather_axis + i")};
+ ${S.indicesSet("indices_indices", "i", "index")};
+ }` : `indices_indices = ${x.indicesGet("output_indices", "uniforms.gather_axis")};`};
+ var data_indices = ${_.type.indices}(0);
+ for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
+ let index = ${x.indicesGet("output_indices", "i")};
+ ${_.indicesSet("data_indices", "i", "index")};
+ }
+ var index_from_indices = ${S.getByIndices("indices_indices")};
+ if (index_from_indices < 0) {
+ index_from_indices += ${r[i]};
+ }
+ ${_.indicesSet("data_indices", "uniforms.gather_axis", "u32(index_from_indices)")};
+ for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) {
+ let index = ${x.indicesGet("output_indices", `i + ${n.length} - 1`)};
+ ${_.indicesSet("data_indices", "i", "index")};
+ }
+ let data_offset = ${_.indicesToOffset("data_indices")};
+ let data_index = data_offset % 8;
+ // Convert 4-bit packed data to 8-bit packed data.
+ let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")};
+ let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
+ let quantized_data_vec = ${m ? "unpack4xI8" : "unpack4xU8"}(u32(packed_8bit_quantized_data));
+ let quantized_data = quantized_data_vec[data_index / 2];
+ var scale_indices = data_indices;
+ let quantize_axis_index = ${$.indicesGet("data_indices", "uniforms.quantize_axis")} / uniforms.block_size;
+ ${$.indicesSet("scale_indices", "uniforms.quantize_axis", "quantize_axis_index")};
+ var scale = ${$.getByIndices("scale_indices")};
+ ${v ? `
+ let zero_point_indices = scale_indices;
+ let zero_point_offset = ${v.indicesToOffset("zero_point_indices")};
+ let zero_point_index = zero_point_offset % 8;
+ let packed_4bit_zero_points = ${v.getByOffset("zero_point_offset / 8")};
+ let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
+ let zero_point_vec = ${m ? "unpack4xI8" : "unpack4xU8"}(u32(packed_8bit_zero_points));
+ let zero_point = zero_point_vec[zero_point_index / 2];` : "var zero_point = 0"};
+ let dequantized_data = ${Ae(c)}(quantized_data - zero_point) * scale;
+ ${x.setByOffset("global_idx", "dequantized_data")};
+ }`;
+ };
+ return { name: "GatherBlockQuantized", shaderCache: { hint: `${t.cacheKey};${e.filter((g, _) => _ !== 1).map((g) => g.dims.join("_")).join(";")}`, inputDependencies: Array.from({ length: e.length }, (g, _) => "rank") }, getRunData: () => ({ outputs: [{ dims: u, dataType: c }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: f }), getShaderSource: b };
+ }, Td = (e, t) => {
+ let r = e.inputs;
+ Nf(r, t), e.compute(Vf(e.inputs, t));
+ }, Id = (e) => J({ blockSize: e.blockSize, gatherAxis: e.gatherAxis, quantizeAxis: e.quantizeAxis });
+});
+var Wf;
+var Lf;
+var Ad;
+var Ed;
+var kd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ Wf = (e) => {
+ if (!e || e.length !== 2) throw new Error("GatherElements requires 2 inputs.");
+ if (e[0].dims.length < 1) throw new Error("GatherElements requires that the data input be rank >= 1.");
+ if (e[0].dims.length !== e[1].dims.length) throw new Error(`GatherElements requires that the data input and
+ indices input tensors be of same rank.`);
+ }, Lf = (e, t) => {
+ let r = e[0].dims, n = e[0].dataType, o = r.length, i = e[1].dims, a = e[1].dataType, u = k.normalizeAxis(t.axis, o), d = r[u], c = i.slice(0), p = k.size(c), m = P("input", n, o), f = P("indicesInput", a, i.length), b = M("output", n, c.length), g = [{ type: 12, data: p }, { type: 6, data: d }, { type: 12, data: u }];
+ return g.push(...N(r, i, c)), { name: "GatherElements", shaderCache: { inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: c, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: g }), getShaderSource: ($) => `
+ ${$.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(m, f, b)}
+ ${$.mainStart()}
+ ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+
+ let outputIndices = ${b.offsetToIndices("global_idx")};
+
+ var idx = ${f.getByOffset("global_idx")};
+ if (idx < 0) {
+ idx = idx + uniforms.axisDimLimit;
+ }
+ var inputIndices = ${m.type.indices}(outputIndices);
+ ${m.indicesSet("inputIndices", "uniforms.axis", "u32(idx)")};
+ let value = ${m.getByIndices("inputIndices")};
+
+ ${b.setByOffset("global_idx", "value")};
+ }` };
+ }, Ad = (e) => J({ axis: e.axis }), Ed = (e, t) => {
+ let r = e.inputs;
+ Wf(r), e.compute(Lf(e.inputs, t));
+ };
+});
+var Gf;
+var Hf;
+var Pd;
+var zd;
+var Od = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ Gf = (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");
+ }, Hf = (e, t) => {
+ let r = e[0].dims.slice(), n = e[1].dims.slice(), [o, i, a] = Dr.getShapeOfGemmResult(r, t.transA, n, t.transB, e.length === 3 ? e[2].dims : void 0), u = [o, i];
+ if (!u) throw new Error("Can't use gemm on the given tensors");
+ let d = 16, c = Math.ceil(i / d), p = Math.ceil(o / d), m = true, f = k.size(u), b = [{ type: 12, data: m ? c : f }, { type: 12, data: o }, { type: 12, data: i }, { type: 12, data: a }, { type: 1, data: t.alpha }, { type: 1, data: t.beta }], g = ["type", "type"];
+ e.length === 3 && (b.push(...N(e[2].dims)), g.push("rank")), b.push(...N(u));
+ let _ = ($) => {
+ let v = "";
+ t.transA && t.transB ? v = "value += a[k * uniforms.M + m] * b[n * uniforms.K + k];" : t.transA && !t.transB ? v = "value += a[k * uniforms.M + m] * b[k * uniforms.N + n];" : !t.transA && t.transB ? v = "value += a[m * uniforms.K + k] * b[n * uniforms.K + k];" : !t.transA && !t.transB && (v = "value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");
+ let x = t.alpha === 1 ? "" : "value *= uniforms.alpha;", T = P("a", e[0].dataType, e[0].dims), E = P("b", e[1].dataType, e[1].dims), I = T.type.value, z = null, O = [T, E];
+ e.length === 3 && (z = P("c", e[2].dataType, e[2].dims.length), O.push(z));
+ let D = M("output", e[0].dataType, u.length);
+ O.push(D);
+ let L = [{ 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 `
+ ${$.registerUniforms(L).declareVariables(...O)}
+
+ ${$.mainStart()}
+ ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+
+ let m = global_idx / uniforms.N;
+ let n = global_idx % uniforms.N;
+
+ var value = ${I}(0);
+ for (var k: u32 = 0u; k < uniforms.K; k++) {
+ ${v}
+ }
+
+ ${x}
+ ${z != null ? `let cOffset = ${z.broadcastedIndicesToOffset("vec2(m, n)", D)}; value += ${I}(uniforms.beta) * ${z.getByOffset("cOffset")};` : ""}
+ output[global_idx] = value;
+ }`;
+ }, S = ($) => {
+ let v = P("a", e[0].dataType, e[0].dims), x = P("b", e[1].dataType, e[1].dims), T = null, E = [v, x];
+ e.length === 3 && (T = P("c", e[2].dataType, e[2].dims.length), E.push(T));
+ let I = M("output", e[0].dataType, u.length);
+ E.push(I);
+ let z = [{ name: "num_tile_n", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }, { name: "alpha", type: "f32" }, { name: "beta", type: "f32" }], O = "", D = "";
+ t.transA && t.transB ? (D = `
+ var col = tile_row_start + local_id.x;
+ var row = k_start + local_id.y;
+ if (col < uniforms.M && row < uniforms.K) {
+ tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
+ } else {
+ tile_a[local_id.y][local_id.x] = ${v.type.value}(0);
+ }
+
+ col = k_start + local_id.x;
+ row = tile_col_start + local_id.y;
+ if (col < uniforms.K && row < uniforms.N) {
+ tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
+ } else {
+ tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
+ }
+ `, O = "value += tile_a[k][local_id.y] * tile_b[local_id.x][k];") : t.transA && !t.transB ? (D = `
+ var col = tile_row_start + local_id.x;
+ var row = k_start + local_id.y;
+ if (col < uniforms.M && row < uniforms.K) {
+ tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
+ } else {
+ tile_a[local_id.y][local_id.x] = ${v.type.value}(0);
+ }
+
+ col = tile_col_start + local_id.x;
+ row = k_start + local_id.y;
+ if (col < uniforms.N && row < uniforms.K) {
+ tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
+ } else {
+ tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
+ }
+ `, O = "value += tile_a[k][local_id.y] * tile_b[k][local_id.x];") : !t.transA && t.transB ? (D = `
+ var col = k_start + local_id.x;
+ var row = tile_row_start + local_id.y;
+ if (col < uniforms.K && row < uniforms.M) {
+ tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
+ } else {
+ tile_a[local_id.y][local_id.x] = ${v.type.value}(0);
+ }
+
+ col = k_start + local_id.x;
+ row = tile_col_start + local_id.y;
+ if (col < uniforms.K && row < uniforms.N) {
+ tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
+ } else {
+ tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
+ }
+ `, O = "value += tile_a[local_id.y][k] * tile_b[local_id.x][k];") : !t.transA && !t.transB && (D = `
+ var col = k_start + local_id.x;
+ var row = tile_row_start + local_id.y;
+ if (col < uniforms.K && row < uniforms.M) {
+ tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
+ } else {
+ tile_a[local_id.y][local_id.x] = ${v.type.value}(0);
+ }
+
+ col = tile_col_start + local_id.x;
+ row = k_start + local_id.y;
+ if (col < uniforms.N && row < uniforms.K) {
+ tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
+ } else {
+ tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
+ }
+ `, O = "value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");
+ let L = t.alpha === 1 ? "" : "value *= uniforms.alpha;";
+ return `
+ ${$.registerUniforms(z).declareVariables(...E)}
+ var tile_a: array, ${d}>;
+ var tile_b: array, ${d}>;
+ ${$.mainStart([d, d, 1])}
+ let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d};
+ let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d};
+ let num_tiles = (uniforms.K - 1) / ${d} + 1;
+ var k_start = 0u;
+ var value = ${I.type.value}(0);
+ for (var t: u32 = 0u; t < num_tiles; t++) {
+ ${D}
+ k_start = k_start + ${d};
+ workgroupBarrier();
+
+ for (var k: u32 = 0u; k < ${d}; k++) {
+ ${O}
+ }
+ workgroupBarrier();
+ }
+
+ ${L}
+ let m = tile_row_start + local_id.y;
+ let n = tile_col_start + local_id.x;
+ ${T != null ? `let cOffset = ${T.broadcastedIndicesToOffset("vec2(m, n)", I)}; value += ${I.type.value}(uniforms.beta) * ${T.getByOffset("cOffset")};` : ""}
+ if (m < uniforms.M && n < uniforms.N) {
+ output[m * uniforms.N + n] = value;
+ }
+ }`;
+ };
+ return m ? { name: "GemmShared", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: u, dataType: e[0].dataType }], dispatchGroup: { x: c * p }, programUniforms: b }), getShaderSource: S } : { name: "Gemm", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: u, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: b }), getShaderSource: _ };
+ }, Pd = (e) => {
+ let t = e.transA, r = e.transB, n = e.alpha, o = e.beta;
+ return { transA: t, transB: r, alpha: n, beta: o, cacheKey: `${e.transA};${e.transB};${e.alpha === 1}` };
+ }, zd = (e, t) => {
+ Gf(e.inputs), e.compute(Hf(e.inputs, t));
+ };
+});
+var ut;
+var yt;
+var Ut;
+var Nt;
+var Ff;
+var qf;
+var jf;
+var Kf;
+var Zf;
+var Qf;
+var Yf;
+var Xf;
+var Bd;
+var Dd;
+var Md = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ [ut, yt, Ut, Nt] = [0, 1, 2, 3], Ff = (e) => {
+ if (e[0].dims.length !== 4) throw new Error("only 4-D tensor is supported.");
+ if (e[0].dims.length !== e[1].dims.length) throw new Error("input dimensions must be equal to grid dimensions");
+ if (e[0].dims.length - 2 !== e[1].dims[e[1].dims.length - 1]) throw new Error(`last dimension of grid must be equal to ${e[0].dims.length - 2}`);
+ if (e[0].dims[0] !== e[1].dims[0]) throw new Error("grid batch size must match input batch size");
+ }, qf = `
+ fn gs_get_cubic_coeffs(x: f32) -> vec4 {
+ let cubic_alpha = -0.75f;
+ let x_abs = abs(x);
+ var coeffs: vec4;
+ coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);
+ coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);
+ coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);
+ coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
+ return coeffs;
+ }
+`, jf = (e) => `
+ fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {
+ var v: vec4;
+ var coeffs = gs_get_cubic_coeffs(x);
+ for (var i = 0; i < 4; i++) {
+ v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];
+ }
+ coeffs = gs_get_cubic_coeffs(y);
+ let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
+ return pixel;
+ }
+`, Kf = (e) => `
+ fn gs_denormalize(n: f32, length: i32) -> f32 {
+ ${e.alignCorners === 0 ? `
+ // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
+ return ((n + 1.0) * f32(length) - 1.0) / 2.0;
+ ` : `
+ // alignCorners: true => [-1, 1] to [0, length - 1]
+ return (n + 1.0) / 2.0 * (f32(length - 1));
+ `}
+ }
+`, Zf = (e) => `
+ ${e.paddingMode === "reflection" ? `
+ fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
+ var dx = 0.0;
+ var fx = f32(x);
+ let range = x_max - x_min;
+ if (fx < x_min) {
+ dx = x_min - fx;
+ let n = u32(dx / range);
+ let r = dx - f32(n) * range;
+ if (n % 2 == 0) {
+ fx = x_min + r;
+ } else {
+ fx = x_max - r;
+ }
+ } else if (fx > x_max) {
+ dx = fx - x_max;
+ let n = u32(dx / range);
+ let r = dx - f32(n) * range;
+ if (n % 2 == 0) {
+ fx = x_max - r;
+ } else {
+ fx = x_min + r;
+ }
+ }
+ return u32(fx);
+ }` : ""}
+`, Qf = (e, t, r) => `
+ fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} {
+ var pixel = ${t}(0);
+ var indices = vec4(0);
+ indices[${ut}] = batch;
+ indices[${yt}] = channel;` + (() => {
+ switch (r.paddingMode) {
+ case "zeros":
+ return `
+ if (r >= 0 && r < H && c >=0 && c < W) {
+ indices[${Ut}] = u32(r);
+ indices[${Nt}] = u32(c);
+ } else {
+ return ${t}(0);
+ }
+ `;
+ case "border":
+ return `
+ indices[${Ut}] = u32(clamp(r, 0, H - 1));
+ indices[${Nt}] = u32(clamp(c, 0, W - 1));
+ `;
+ case "reflection":
+ return `
+ indices[${Ut}] = gs_reflect(r, border[1], border[3]);
+ indices[${Nt}] = gs_reflect(c, border[0], border[2]);
+ `;
+ default:
+ throw new Error(`padding mode ${r.paddingMode} is not supported`);
+ }
+ })() + `
+ return ${e.getByIndices("indices")};
+ }
+`, Yf = (e, t, r) => (() => {
+ switch (r.mode) {
+ case "nearest":
+ return `
+ let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ut}], indices[${yt}], border);
+ `;
+ case "bilinear":
+ return `
+ let x1 = i32(floor(x));
+ let y1 = i32(floor(y));
+ let x2 = x1 + 1;
+ let y2 = y1 + 1;
+
+ let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ut}], indices[${yt}], border);
+ let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ut}], indices[${yt}], border);
+ let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ut}], indices[${yt}], border);
+ let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ut}], indices[${yt}], border);
+
+ let dx2 = ${t}(f32(x2) - x);
+ let dx1 = ${t}(x - f32(x1));
+ let dy2 = ${t}(f32(y2) - y);
+ let dy1 = ${t}(y - f32(y1));
+ let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);
+ `;
+ case "bicubic":
+ return `
+ let x0 = i32(floor(x)) - 1;
+ let y0 = i32(floor(y)) - 1;
+ var p: mat4x4<${t}>;
+ for (var h = 0; h < 4; h++) {
+ for (var w = 0; w < 4; w++) {
+ p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ut}], indices[${yt}], border);
+ }
+ }
+
+ let dx = x - f32(x0 + 1);
+ let dy = y - f32(y0 + 1);
+ let result = gs_bicubic_interpolate(p, dx, dy);
+ `;
+ default:
+ throw new Error(`mode ${r.mode} is not supported`);
+ }
+ })() + `${e.setByOffset("global_idx", "result")}`, Xf = (e, t) => {
+ let r = P("x", e[0].dataType, e[0].dims.length), n = [e[1].dims[0], e[1].dims[1], e[1].dims[2]], o = P("grid", e[1].dataType, n.length, 2), i = [e[0].dims[0], e[0].dims[1], e[1].dims[1], e[1].dims[2]];
+ t.format === "NHWC" && (i = [e[0].dims[0], e[1].dims[1], e[1].dims[2], e[0].dims[3]], [ut, yt, Ut, Nt] = [0, 3, 1, 2]);
+ let a = M("output", e[0].dataType, i.length), u = r.type.value, d = k.size(i), c = [{ type: 12, data: d }, ...N(e[0].dims, n, i)], p = (m) => `
+ ${m.registerUniform("output_size", "u32").declareVariables(r, o, a)}
+ ${qf}
+ ${jf(u)}
+ ${Kf(t)}
+ ${Zf(t)}
+ ${Qf(r, u, t)}
+
+ ${m.mainStart()}
+ ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let H_in = i32(uniforms.x_shape[${Ut}]);
+ let W_in = i32(uniforms.x_shape[${Nt}]);
+
+ ${t.alignCorners === 0 ? `
+ let x_min = -0.5;
+ let x_max = f32(W_in) - 0.5;
+ let y_min = -0.5;
+ let y_max = f32(H_in) - 0.5;
+ ` : `
+ let x_min = 0.0;
+ let x_max = f32(W_in) - 1.0;
+ let y_min = 0.0;
+ let y_max = f32(H_in) - 1.0;
+ `};
+ let border = vec4(x_min, y_min, x_max, y_max);
+
+ let indices = ${a.offsetToIndices("global_idx")};
+ var grid_indices = vec3(indices[${ut}], indices[${Ut}], indices[${Nt}]);
+ let nxy = ${o.getByIndices("grid_indices")};
+ var x = gs_denormalize(f32(nxy[0]), W_in);
+ var y = gs_denormalize(f32(nxy[1]), H_in);
+
+ ${Yf(a, u, t)}
+ }`;
+ return { name: "GridSample", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: ["type", "type"] }, getRunData: (m) => {
+ let f = k.size(i);
+ return { outputs: [{ dims: i, dataType: m[0].dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: c };
+ }, getShaderSource: p };
+ }, Bd = (e, t) => {
+ Ff(e.inputs), e.compute(Xf(e.inputs, t));
+ }, Dd = (e) => J({ alignCorners: e.align_corners, mode: e.mode, paddingMode: e.padding_mode, format: e.format });
+});
+var Be;
+var th;
+var Ud;
+var Rd;
+var rh;
+var er;
+var Nd;
+var $o = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ Vr();
+ Fr();
+ ie();
+ st();
+ Be = (e, t) => e.length > t && e[t].dims.length > 0 ? e[t] : void 0, th = (e, t) => {
+ let r = e[0], n = Be(e, 1), o = Be(e, 2), i = Be(e, 3), a = Be(e, 4), u = Be(e, 5), d = Be(e, 6), c = Be(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 p = r.dims[0], m = r.dims[1], f = r.dims.length === 3 ? r.dims[2] : t.numHeads * r.dims[4], b = m, g = 0, _ = 0, S = Math.floor(f / t.numHeads);
+ if (d && c && k.size(d.dims) && k.size(c.dims)) {
+ if (d.dims.length !== 4) throw new Error('Input "past_key" is expected to have 4 dimensions');
+ if (d.dims[0] !== p || d.dims[1] !== t.numHeads || d.dims[3] !== S) throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');
+ if (c.dims[0] !== p || c.dims[1] !== t.numHeads || c.dims[3] !== S) throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');
+ if (d.dims[2] !== c.dims[2]) throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');
+ if (c.dims.length !== 4) throw new Error('Input "past_value" is expected to have 4 dimensions');
+ g = d.dims[2], _ = d.dims[2];
+ } else if (d && k.size(d.dims) || c && k.size(c.dims)) throw new Error('Input "past_key" and "past_value" shall be both present or both absent');
+ let $;
+ if (n && k.size(n.dims) > 0) {
+ if (r.dims.length !== 3) throw new Error('Input "query" is expected to have 3 dimensions when key is given');
+ if (n.dims.length < 3 || n.dims.length > 5) throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');
+ if (r.dims[0] !== n.dims[0]) throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');
+ if (n.dims.length === 3) {
+ if (n.dims[2] !== r.dims[2]) throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');
+ $ = 2, b = n.dims[1];
+ } else if (n.dims.length === 5) {
+ if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== S) throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');
+ if (o) throw new Error('Expect "value" be none when "key" has packed kv format.');
+ $ = 5, b = n.dims[1];
+ } else {
+ if (n.dims[1] !== t.numHeads || n.dims[3] !== S) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');
+ $ = 0, b = n.dims[2];
+ }
+ } else {
+ if (r.dims.length !== 5) throw new Error('Input "query" is expected to have 5 dimensions when key is empty');
+ if (r.dims[2] !== t.numHeads || r.dims[3] !== 3) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');
+ $ = 3;
+ }
+ if (i && k.size(i.dims) > 0) {
+ if (i.dims.length !== 1) throw new Error('Input "bias" is expected to have 1 dimension');
+ if (n && n.dims.length === 5 && n.dims[3] === 2) throw new Error("bias is not allowed for packed kv.");
+ }
+ let v = g + b, x = 0;
+ if (a && k.size(a.dims) > 0) {
+ x = 8;
+ let z = a.dims;
+ throw z.length === 1 ? z[0] === p ? x = 1 : z[0] === 3 * p + 2 && (x = 3) : z.length === 2 && z[0] === p && z[1] === v && (x = 5), x === 8 ? new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)') : new Error("Mask not supported");
+ }
+ let T = false, E = f;
+ if (o && k.size(o.dims) > 0) {
+ if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions');
+ if (r.dims[0] !== o.dims[0]) throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');
+ if (o.dims.length === 3) {
+ if (b !== o.dims[1]) throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');
+ E = o.dims[2];
+ } else {
+ if (b !== o.dims[2]) throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');
+ E = o.dims[1] * o.dims[3], T = true;
+ }
+ }
+ let I = false;
+ if (a && k.size(a.dims) > 0) throw new Error("Key padding mask is not supported");
+ if (u && k.size(u.dims) > 0) {
+ if (u.dims.length !== 4) throw new Error('Input "attention_bias" is expected to have 4 dimensions');
+ if (u.dims[0] !== p || u.dims[1] !== t.numHeads || u.dims[2] !== m || u.dims[3] !== v) throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)');
+ }
+ return { batchSize: p, sequenceLength: m, pastSequenceLength: g, kvSequenceLength: b, totalSequenceLength: v, maxSequenceLength: _, inputHiddenSize: 0, hiddenSize: f, vHiddenSize: E, headSize: S, vHeadSize: Math.floor(E / t.numHeads), numHeads: t.numHeads, isUnidirectional: false, pastPresentShareBuffer: false, maskFilterValue: t.maskFilterValue, maskType: x, scale: t.scale, broadcastResPosBias: I, passPastInKv: T, qkvFormat: $ };
+ }, Ud = (e) => J({ ...e }), Rd = J({ perm: [0, 2, 1, 3] }), rh = (e, t, r, n, o, i, a) => {
+ let u = [n, o, i], d = k.size(u), c = [{ type: 12, data: d }, { type: 12, data: a }, { type: 12, data: i }], p = (m) => {
+ let f = M("qkv_with_bias", t.dataType, u), b = P("qkv", t.dataType, u), g = P("bias", r.dataType, u), _ = [{ name: "output_size", type: "u32" }, { name: "bias_offset", type: "u32" }, { name: "hidden_size", type: "u32" }];
+ return `
+ ${m.registerUniforms(_).declareVariables(b, g, f)}
+ ${m.mainStart()}
+ ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
+
+ qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
+ }`;
+ };
+ return e.compute({ name: "MultiHeadAttentionAddBias", shaderCache: { inputDependencies: ["type", "type"] }, getRunData: () => ({ outputs: [{ dims: u, dataType: t.dataType, gpuDataType: 0 }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: c }), getShaderSource: p }, { inputs: [t, r], outputs: [-1] })[0];
+ }, er = (e, t, r, n, o, i, a, u) => {
+ let d = i;
+ if (a && k.size(a.dims) > 0) {
+ if (n === 1) throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");
+ return d = rh(e, i, a, t, n, r * o, u), d = d.reshape([t, n, r, o]), r === 1 || n === 1 ? d : e.compute(Ee(d, Rd.perm), { inputs: [d], outputs: [-1] })[0];
+ } else return i.dims.length === 3 && (d = i.reshape([t, n, r, o])), r === 1 || n === 1 ? d : e.compute(Ee(d, Rd.perm), { inputs: [d], outputs: [-1] })[0];
+ }, Nd = (e, t) => {
+ let r = th(e.inputs, t), n = e.inputs[0], o = Be(e.inputs, 1), i = Be(e.inputs, 2), a = Be(e.inputs, 3), u = Be(e.inputs, 4), d = Be(e.inputs, 5), c = Be(e.inputs, 6), p = Be(e.inputs, 7);
+ if (n.dims.length === 5) throw new Error("Packed QKV is not implemented");
+ if (o?.dims.length === 5) throw new Error("Packed KV is not implemented");
+ let m = o && i && o.dims.length === 4 && i.dims.length === 4, f = er(e, r.batchSize, r.numHeads, r.sequenceLength, r.headSize, n, a, 0);
+ if (m) return Rt(e, f, o, i, u, void 0, c, p, d, r);
+ if (!o || !i) throw new Error("key and value must be provided");
+ let b = er(e, r.batchSize, r.numHeads, r.kvSequenceLength, r.headSize, o, a, r.hiddenSize), g = er(e, r.batchSize, r.numHeads, r.kvSequenceLength, r.vHeadSize, i, a, 2 * r.hiddenSize);
+ Rt(e, f, b, g, u, void 0, c, p, d, r);
+ };
+});
+var nh;
+var oh;
+var ih;
+var ah;
+var xo;
+var Vd;
+var Wd;
+var So = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ nh = (e) => {
+ if (!e || e.length < 1) throw new Error("too few inputs");
+ }, oh = (e, t) => {
+ let r = [], n = t.numOutputs;
+ return e[1].dims[0] > 0 && (e[1].getBigInt64Array().forEach((o) => r.push(Number(o))), n = r.length), J({ numOutputs: n, axis: t.axis, splitSizes: r });
+ }, ih = (e) => `
+fn calculateOutputIndex(index: u32) -> u32 {
+ for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
+ if (index < ${F("uniforms.size_in_split_axis", "i", e)}) {
+ return i;
+ }
+ }
+ return ${e}u;
+}`, ah = (e) => {
+ let t = e.length, r = [];
+ for (let n = 0; n < t; ++n) {
+ let o = e[n].setByIndices("indices", "input[global_idx]");
+ t === 1 ? r.push(o) : n === 0 ? r.push(`if (output_number == ${n}u) { ${o} }`) : n === t - 1 ? r.push(`else { ${o} }`) : r.push(`else if (output_number == ${n}) { ${o} }`);
+ }
+ return `
+ fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {
+ ${r.join(`
+`)}
+ }`;
+ }, xo = (e, t) => {
+ let r = e[0].dims, n = k.size(r), o = e[0].dataType, i = k.normalizeAxis(t.axis, r.length), a = new Array(t.numOutputs), u = P("input", o, r.length), d = new Array(t.numOutputs), c = [], p = [], m = 0, f = [{ type: 12, data: n }];
+ for (let g = 0; g < t.numOutputs; g++) {
+ m += t.splitSizes[g], d[g] = m;
+ let _ = r.slice();
+ _[i] = t.splitSizes[g], p.push(_), a[g] = M(`output${g}`, o, _.length), c.push({ dims: p[g], dataType: e[0].dataType });
+ }
+ f.push({ type: 12, data: d }, ...N(r, ...p));
+ let b = (g) => `
+ ${g.registerUniform("input_size", "u32").registerUniform("size_in_split_axis", "u32", d.length).declareVariables(u, ...a)}
+ ${ih(d.length)}
+ ${ah(a)}
+
+ ${g.mainStart()}
+ ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
+
+ var indices = ${u.offsetToIndices("global_idx")};
+ var index = ${u.indicesGet("indices", i)};
+ let output_number = calculateOutputIndex(index);
+ if (output_number != 0) {
+ index -= ${F("uniforms.size_in_split_axis", "output_number - 1u", d.length)};
+ ${u.indicesSet("indices", i, "index")};
+ }
+ writeBufferData(output_number, indices, global_idx);
+ }`;
+ return { name: "Split", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank"] }, getShaderSource: b, getRunData: () => ({ outputs: c, dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: f }) };
+ }, Vd = (e, t) => {
+ nh(e.inputs);
+ let r = e.inputs.length === 1 ? t : oh(e.inputs, t);
+ e.compute(xo(e.inputs, r), { inputs: [0] });
+ }, Wd = (e) => {
+ let t = e.axis, r = e.splitSizes, n = e.numOutputs < 0 ? r.length : e.numOutputs;
+ if (n !== r.length) throw new Error("numOutputs and splitSizes lengh must be equal");
+ return J({ axis: t, numOutputs: n, splitSizes: r });
+ };
+});
+var sh;
+var tn;
+var Ld;
+var To = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ sh = (e, t) => {
+ let [r, n, o, i] = e, { numHeads: a, rotaryEmbeddingDim: u } = t;
+ if (r.dims.length !== 3 && r.dims.length !== 4) throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);
+ if (!k.areEqual(n.dims, []) && !k.areEqual(n.dims, [1]) && n.dims.length !== 2) throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);
+ if (o.dims.length !== 2) throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);
+ if (i.dims.length !== 2) throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);
+ if (!k.areEqual(o.dims, i.dims)) throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");
+ if (u > 0 && a === 0) throw new Error("num_heads must be provided if rotary_embedding_dim is specified");
+ let d = r.dims[0], c = r.dims[r.dims.length - 2], p = o.dims[0], m = k.sizeFromDimension(r.dims, 1) / c, f = u === 0 ? o.dims[1] * 2 : m / a;
+ if (u > f) throw new Error("rotary_embedding_dim must be less than or equal to head_size");
+ if (n.dims.length === 2) {
+ if (d !== n.dims[0]) throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);
+ if (c !== n.dims[1]) throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`);
+ }
+ if (f / 2 !== o.dims[1] && u / 2 !== o.dims[1]) throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);
+ if (c > p) throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");
+ }, tn = (e, t) => {
+ let { interleaved: r, numHeads: n, rotaryEmbeddingDim: o, scale: i } = t, a = e[0].dims[0], u = k.sizeFromDimension(e[0].dims, 1), d = e[0].dims[e[0].dims.length - 2], c = u / d, p = e[2].dims[1], m = o === 0 ? p * 2 : c / n, f = new Array(a, d, c / m, m - p), b = k.computeStrides(f), g = [{ type: 1, data: i }, { type: 12, data: f }, { type: 12, data: b }, ...e[0].dims.length === 3 ? new Array({ type: 12, data: [u, c, m, 1] }) : [], ...e[0].dims.length === 4 ? new Array({ type: 12, data: [u, m, d * m, 1] }) : [], ...N(e[0].dims, e[1].dims, e[2].dims, e[3].dims, e[0].dims)], _ = (S) => {
+ let $ = P("input", e[0].dataType, e[0].dims.length), v = P("position_ids", e[1].dataType, e[1].dims.length), x = P("cos_cache", e[2].dataType, e[2].dims.length), T = P("sin_cache", e[3].dataType, e[3].dims.length), E = M("output", e[0].dataType, e[0].dims.length);
+ return S.registerUniforms([{ name: "scale", type: "f32" }, { name: "global_shape", type: "u32", length: f.length }, { name: "global_strides", type: "u32", length: b.length }, { name: "input_output_strides", type: "u32", length: b.length }]), `
+ ${S.declareVariables($, v, x, T, E)}
+
+ ${S.mainStart(It)}
+ let half_rotary_emb_dim = uniforms.${x.name}_shape[1];
+ let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
+ let size = uniforms.global_shape[0] * uniforms.global_strides[0];
+ ${S.guardAgainstOutOfBoundsWorkgroupSizes("size")}
+
+ if (bsnh[3] < half_rotary_emb_dim) {
+ let position_ids_idx =
+ ${v.broadcastedIndicesToOffset("bsnh.xy", M("", v.type.tensor, 2))};
+ let position_id =
+ u32(${v.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
+ let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});
+ let j = i + select(half_rotary_emb_dim, 1, ${r});
+ let re = ${$.getByOffset("i")} * ${x.get("position_id", "bsnh[3]")} -
+ ${$.getByOffset("j")} * ${T.get("position_id", "bsnh[3]")};
+ ${E.setByOffset("i", "re")}
+ let im = ${$.getByOffset("i")} * ${T.get("position_id", "bsnh[3]")} +
+ ${$.getByOffset("j")} * ${x.get("position_id", "bsnh[3]")};
+ ${E.setByOffset("j", "im")}
+ } else {
+ let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
+ ${E.setByOffset("k", $.getByOffset("k"))}
+ }
+ }`;
+ };
+ return { name: "RotaryEmbedding", shaderCache: { hint: J({ interleaved: r }).cacheKey, inputDependencies: ["rank", "rank", "rank", "rank"] }, getShaderSource: _, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k.size(f) / It) }, programUniforms: g }) };
+ }, Ld = (e, t) => {
+ sh(e.inputs, t), e.compute(tn(e.inputs, t));
+ };
+});
+var uh;
+var dh;
+var Gd;
+var lh;
+var Hd;
+var Fd = U(() => {
+ "use strict";
+ Se();
+ ee();
+ Fr();
+ $o();
+ So();
+ st();
+ To();
+ ie();
+ uh = (e, t) => {
+ if (t.doRotary && e.length <= 7) throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");
+ let r = e[0], n = e[1], o = e[2], i = e[3], a = e[4];
+ if (t.doRotary !== 0 && e.length <= 7) throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");
+ if (t.localWindowSize !== -1) throw new Error("Local attention is not supported");
+ if (t.softcap !== 0) throw new Error("Softcap is not supported");
+ if (t.rotaryInterleaved !== 0) throw new Error("Rotary interleaved is not supported");
+ if (t.smoothSoftmax) throw new Error("Smooth softmax is not supported");
+ if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error("Input query is expected to have 3 or 5 dimensions");
+ let u = false, d = r.dims[0], c = r.dims[1], p = r.dims.length === 3 ? u ? r.dims[2] / 3 : r.dims[2] : t.numHeads * r.dims[4], m = c, f = 0, b = !n || n.dims.length === 0, g = Math.floor(b ? p / (t.numHeads + 2 * t.kvNumHeads) : p / t.numHeads);
+ b && (p = g * t.numHeads);
+ let _ = i && i.dims.length !== 0, S = a && a.dims.length !== 0;
+ if (_ && i.dims.length === 4 && i.dims[0] === d && i.dims[1] !== t.kvNumHeads && i.dims[2] === t.kvNumHeads && i.dims[3] === g) throw new Error("BSNH pastKey/pastValue is not supported");
+ if (_ && S) {
+ if (i.dims.length !== 4) throw new Error('Input "past_key" is expected to have 4 dimensions');
+ if (a.dims.length !== 4) throw new Error('Input "past_value" is expected to have 4 dimensions');
+ f = i.dims[2];
+ } else if (_ || S) throw new Error('Input "past_key" and "past_value" shall be both present or both absent');
+ let v = 1;
+ if (n && n.dims.length > 0) {
+ if (r.dims.length !== 3) throw new Error('Input "query" is expected to have 3 dimensions when key is given');
+ if (n.dims.length < 3 || n.dims.length > 5) throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');
+ if (r.dims[0] !== n.dims[0]) throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');
+ if (n.dims.length === 3) {
+ if (r.dims[2] % n.dims[2] !== 0) throw new Error('Dimension 2 of "query" should be a multiple of "key"');
+ m = n.dims[1];
+ } else if (n.dims.length === 5) {
+ if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== g) throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');
+ if (o) throw new Error('Expect "value" be none when "key" has packed kv format.');
+ m = n.dims[1];
+ } else {
+ if (n.dims[1] !== t.numHeads || n.dims[3] !== g) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');
+ m = n.dims[2];
+ }
+ } else {
+ if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');
+ if (r.dims.length === 5 && (r.dims[2] !== t.numHeads || r.dims[3] !== 3)) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');
+ v = 3;
+ }
+ let x = 0, T = false, E = t.kvNumHeads ? g * t.kvNumHeads : p;
+ if (o && o.dims.length > 0) {
+ if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions');
+ if (r.dims[0] !== o.dims[0]) throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');
+ if (o.dims.length === 3) {
+ if (m !== o.dims[1]) throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');
+ E = o.dims[2];
+ } else {
+ if (m !== o.dims[2]) throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');
+ E = o.dims[1] * o.dims[3], T = true;
+ }
+ }
+ let I = e.length > 4 ? e[5] : void 0;
+ if (I && I.dims.length !== 1 && I.dims[0] !== d) throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');
+ return { batchSize: d, sequenceLength: c, pastSequenceLength: f, kvSequenceLength: m, totalSequenceLength: -1, maxSequenceLength: -1, inputHiddenSize: 0, hiddenSize: p, vHiddenSize: E, headSize: g, vHeadSize: Math.floor(E / t.kvNumHeads), numHeads: t.numHeads, kvNumHeads: t.kvNumHeads, nReps: t.numHeads / t.kvNumHeads, pastPresentShareBuffer: false, maskType: x, scale: t.scale, broadcastResPosBias: false, passPastInKv: T, qkvFormat: v };
+ }, dh = J({ perm: [0, 2, 1, 3] }), Gd = (e, t, r) => {
+ let n = t, o = r.kvNumHeads;
+ return t.dims.length === 3 && r.kvSequenceLength !== 0 && (n = t.reshape([r.batchSize, r.kvSequenceLength, o, r.headSize]), n = e.compute(Ee(n, dh.perm), { inputs: [n], outputs: [-1] })[0]), n;
+ }, lh = (e, t, r, n) => {
+ let o = 7, i = ["type", "type"], a = [e * t], u = e * t, d = [{ type: 12, data: u }, { type: 12, data: t }, { type: 12, data: e }], c = (p) => {
+ let m = P("seq_lens", r.dataType, r.dims), f = P("total_seq_lens", n.dataType, n.dims), b = M("pos_ids", o, a), g = [{ name: "output_size", type: "u32" }, { name: "sequence_length", type: "u32" }, { name: "batch_size", type: "u32" }];
+ return `
+ ${p.registerUniforms(g).declareVariables(m, f, b)}
+ ${p.mainStart()}
+ ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let total_sequence_length = u32(${f.getByOffset("0")});
+ let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;
+ let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;
+ let batch_idx = global_idx / uniforms.sequence_length;
+ let sequence_idx = i32(global_idx % uniforms.sequence_length);
+ var pos_id: i32 = 0;
+ let seqlen = ${m.getByOffset("batch_idx")};
+ let total_seqlen = seqlen + 1;
+ if (is_first_prompt) {
+ if (sequence_idx < total_seqlen) {
+ pos_id = sequence_idx;
+ } else {
+ pos_id = 1;
+ }
+ ${b.setByOffset("global_idx", "pos_id")}
+ } else if (is_subsequent_prompt) {
+ let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
+ if (past_seqlen + sequence_idx < total_seqlen) {
+ pos_id = past_seqlen + sequence_idx;
+ } else {
+ pos_id = 1;
+ }
+ ${b.setByOffset("global_idx", "pos_id")}
+ } else if (global_idx < uniforms.batch_size) {
+ ${b.setByOffset("global_idx", "seqlen")}
+ };
+ }
+ `;
+ };
+ return { name: "GeneratePositionIds", shaderCache: { hint: `${e};${t}`, inputDependencies: i }, getRunData: () => ({ outputs: [{ dims: a, dataType: o }], dispatchGroup: { x: Math.ceil(u / 64) }, programUniforms: d }), getShaderSource: c };
+ }, Hd = (e, t) => {
+ let r = uh(e.inputs, t);
+ if (e.inputs[0].dims.length === 5) throw new Error("Packed QKV is not implemented");
+ if (e.inputs[1]?.dims.length === 5) throw new Error("Packed KV is not implemented");
+ let n = e.inputs[0], o = e.inputs[1] && e.inputs[1].dims.length > 0 ? e.inputs[1] : void 0, i = e.inputs[2] && e.inputs[2].dims.length > 0 ? e.inputs[2] : void 0, a = e.inputs[3] && e.inputs[3].dims.length !== 0 ? e.inputs[3] : void 0, u = e.inputs[4] && e.inputs[4].dims.length !== 0 ? e.inputs[4] : void 0, d = e.inputs.length > 4 ? e.inputs[5] : void 0, c = e.inputs.length > 5 ? e.inputs[6] : void 0, p = r.kvNumHeads ? r.kvNumHeads : r.numHeads, m = J({ axis: 2, numOutputs: 3, splitSizes: [r.numHeads * r.headSize, p * r.headSize, p * r.headSize] }), [f, b, g] = !o && !i ? e.compute(xo([n], m), { inputs: [n], outputs: [-1, -1, -1] }) : [n, o, i], _, S;
+ if (t.doRotary) {
+ let T = e.compute(lh(r.batchSize, r.sequenceLength, d, c), { inputs: [d, c], outputs: [-1] })[0], E = e.inputs[7], I = e.inputs[8], z = J({ interleaved: t.rotaryInterleaved !== 0, numHeads: r.numHeads, rotaryEmbeddingDim: 0, scale: t.scale }), O = [f, T, E, I], D = [-1];
+ _ = e.compute(tn(O, z), { inputs: O, outputs: D })[0], O.splice(0, 1, b);
+ let L = J({ interleaved: t.rotaryInterleaved !== 0, numHeads: r.kvNumHeads, rotaryEmbeddingDim: 0, scale: t.scale });
+ S = e.compute(tn(O, L), { inputs: O, outputs: D })[0];
+ }
+ let $ = er(e, r.batchSize, r.numHeads, r.sequenceLength, r.headSize, t.doRotary ? _ : f, void 0, 0), v = Gd(e, t.doRotary ? S : b, r), x = Gd(e, g, r);
+ Rt(e, $, v, x, void 0, void 0, a, u, void 0, r, d, c);
+ };
+});
+var qd;
+var ch;
+var ph;
+var jd;
+var Kd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ st();
+ ie();
+ qd = (e, t, r, n, o, i, a, u) => {
+ let d = ce(i), c = d === 1 ? "f32" : `vec${d}f`, p = d === 1 ? "vec2f" : `mat2x${d}f`, m = o * a, f = 64;
+ m === 1 && (f = 256);
+ let b = [o, a, i / d], g = [o, a, 2], _ = ["rank", "type", "type"], S = [];
+ S.push(...N(b, g));
+ let $ = (v) => {
+ let x = P("x", t.dataType, 3, d), T = P("scale", r.dataType, r.dims), E = P("bias", n.dataType, n.dims), I = M("output", 1, 3, 2), z = [x, T, E, I];
+ return `
+ var workgroup_shared : array<${p}, ${f}>;
+ const workgroup_size = ${f}u;
+ ${v.declareVariables(...z)}
+ ${v.mainStart(f)}
+ let batch = workgroup_index / uniforms.x_shape[1];
+ let channel = workgroup_index % uniforms.x_shape[1];
+ let hight = uniforms.x_shape[2];
+ // initialize workgroup memory
+ var sum = ${c}(0);
+ var squared_sum = ${c}(0);
+ for (var h = local_idx; h < hight; h += workgroup_size) {
+ let value = ${c}(${x.get("batch", "channel", "h")});
+ sum += value;
+ squared_sum += value * value;
+ }
+ workgroup_shared[local_idx] = ${p}(sum, squared_sum);
+ workgroupBarrier();
+
+ for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {
+ if (local_idx < currSize) {
+ workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];
+ }
+ workgroupBarrier();
+ }
+ if (local_idx == 0) {
+ let sum_final = ${He("workgroup_shared[0][0]", d)} / f32(hight * ${d});
+ let squared_sum_final = ${He("workgroup_shared[0][1]", d)} / f32(hight * ${d});
+
+ let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u}));
+ let channel_scale = inv_std_dev * f32(scale[channel]);
+ let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
+ output[workgroup_index] = vec2f(channel_scale, channel_shift);
+ }
+ }`;
+ };
+ return e.compute({ name: "InstanceNormComputeChannelScaleShift", shaderCache: { hint: `${d};${u};${f}`, inputDependencies: _ }, getRunData: () => ({ outputs: [{ dims: g, dataType: 1 }], dispatchGroup: { x: m }, programUniforms: S }), getShaderSource: $ }, { inputs: [t, r, n], outputs: [-1] })[0];
+ }, ch = (e, t, r) => {
+ let n = t[0].dims, o = n, i = 2, a = n[0], u = n[1], d = k.sizeFromDimension(n, i), c = ce(d), p = k.size(o) / c, m = qd(e, t[0], t[1], t[2], a, d, u, r.epsilon), f = [a, u, d / c], b = [a, u], g = ["type", "none"], _ = (S) => {
+ let $ = P("x", t[0].dataType, f.length, c), v = P("scale_shift", 1, b.length, 2), x = M("output", t[0].dataType, f.length, c), T = [$, v, x];
+ return `
+ ${S.registerUniform("output_size", "u32").declareVariables(...T)}
+ ${S.mainStart()}
+ ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let outputIndices = ${x.offsetToIndices("global_idx")};
+ let batch = outputIndices[0];
+ let channel = outputIndices[1];
+ let scale_shift = ${v.getByIndices("vec2(batch, channel)")};
+ let value = ${$.getByOffset("global_idx")} * ${x.type.value}(scale_shift.x) + ${x.type.value}(scale_shift.y);
+ ${x.setByOffset("global_idx", "value")};
+ }`;
+ };
+ e.compute({ name: "InstanceNormalization", shaderCache: { hint: `${c}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: o, dataType: t[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: [{ type: 12, data: p }, ...N(f, b, f)] }), getShaderSource: _ }, { inputs: [t[0], m] });
+ }, ph = (e, t, r) => {
+ let n = t[0].dims, o = n, i = n[0], a = n[n.length - 1], u = k.sizeFromDimension(n, 1) / a, d = ce(a), c = k.size(o) / d, p = [{ type: 12, data: u }, { type: 12, data: Math.floor(a / d) }], m = ["type", "type"], f = false, b = [0, n.length - 1];
+ for (let $ = 0; $ < n.length - 2; $++) f = f || n[$ + 1] !== 1, b.push($ + 1);
+ f = f && n[n.length - 1] !== 1;
+ let g = f ? e.compute(Ee(e.inputs[0], b), { inputs: [e.inputs[0]], outputs: [-1] })[0] : e.inputs[0].reshape(Array.from({ length: n.length }, ($, v) => n[b[v]])), _ = qd(e, g, t[1], t[2], i, u, a, r.epsilon), S = ($) => {
+ let v = be(t[0].dataType), x = d === 1 ? "vec2f" : `mat${d}x2f`, T = (z) => {
+ let O = z === 0 ? "x" : "y", D = d === 1 ? "f32" : `vec${d}f`;
+ switch (d) {
+ case 1:
+ return `${v}(${D}(scale.${O}))`;
+ case 2:
+ return `vec2<${v}>(${D}(scale[0].${O}, scale[1].${O}))`;
+ case 4:
+ return `vec4<${v}>(${D}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;
+ default:
+ throw new Error(`Not supported compoents ${d}`);
+ }
+ }, E = P("input", t[0].dataType, t[0].dims, d), I = M("output", t[0].dataType, o, d);
+ return `
+ @group(0) @binding(0) var input : array<${E.type.storage}>;
+ @group(0) @binding(1) var scale_input : array<${x}>;
+ @group(0) @binding(2) var output : array<${I.type.storage}>;
+ struct Uniforms {H: u32, C : u32};
+ @group(0) @binding(3) var uniforms: Uniforms;
+
+ ${$.mainStart()}
+ let current_image_number = global_idx / (uniforms.C * uniforms.H);
+ let current_channel_number = global_idx % uniforms.C;
+
+ let scale_offset = current_image_number * uniforms.C + current_channel_number;
+ let scale = scale_input[scale_offset];
+ output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)});
+ }`;
+ };
+ e.compute({ name: "InstanceNormalizationNHWC", shaderCache: { hint: `${d}`, inputDependencies: m }, getRunData: () => ({ outputs: [{ dims: o, dataType: t[0].dataType }], dispatchGroup: { x: Math.ceil(c / 64) }, programUniforms: p }), getShaderSource: S }, { inputs: [t[0], _] });
+ }, jd = (e, t) => {
+ t.format === "NHWC" ? ph(e, e.inputs, t) : ch(e, e.inputs, t);
+ };
+});
+var mh;
+var fh;
+var Zd;
+var Qd = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ mh = (e) => {
+ if (!e || e.length < 2) throw new Error("layerNorm requires at least 2 inputs.");
+ }, fh = (e, t, r) => {
+ let n = t.simplified, o = e[0].dims, i = e[1], a = !n && e[2], u = o, d = k.normalizeAxis(t.axis, o.length), c = k.sizeToDimension(o, d), p = k.sizeFromDimension(o, d), m = k.size(i.dims), f = a ? k.size(a.dims) : 0;
+ if (m !== p || a && f !== p) throw new Error(`Size of X.shape()[axis:] == ${p}.
+ Size of scale and bias (if provided) must match this.
+ Got scale size of ${m} and bias size of ${f}`);
+ let b = [];
+ for (let E = 0; E < o.length; ++E) E < d ? b.push(o[E]) : b.push(1);
+ let g = ce(p), _ = ["type", "type"], S = [{ type: 12, data: c }, { type: 1, data: p }, { type: 12, data: Math.floor(p / g) }, { type: 1, data: t.epsilon }];
+ a && _.push("type");
+ let $ = r > 1, v = r > 2, x = (E) => {
+ let I = be(e[0].dataType), z = [P("x", e[0].dataType, e[0].dims, g), P("scale", i.dataType, i.dims, g)];
+ a && z.push(P("bias", a.dataType, a.dims, g)), z.push(M("output", e[0].dataType, u, g)), $ && z.push(M("mean_data_output", 1, b)), v && z.push(M("inv_std_output", 1, b));
+ let O = [{ name: "norm_count", type: "u32" }, { name: "norm_size", type: "f32" }, { name: "norm_size_vectorized", type: "u32" }, { name: "epsilon", type: "f32" }];
+ return `
+ ${E.registerUniforms(O).declareVariables(...z)}
+ ${E.mainStart()}
+ ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
+ let offset = global_idx * uniforms.norm_size_vectorized;
+ var mean_vector = ${ao("f32", g)};
+ var mean_square_vector = ${ao("f32", g)};
+
+ for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
+ let value = ${Ct(I, g, "x[h + offset]")};
+ mean_vector += value;
+ mean_square_vector += value * value;
+ }
+ let mean = ${He("mean_vector", g)} / uniforms.norm_size;
+ let inv_std_dev = inverseSqrt(${He("mean_square_vector", g)} / uniforms.norm_size ${n ? "" : "- mean * mean"} + uniforms.epsilon);
+
+ for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
+ let f32input = ${Ct(I, g, "x[j + offset]")};
+ let f32scale = ${Ct(I, g, "scale[j]")};
+ output[j + offset] = ${z[0].type.value}((f32input ${n ? "" : "- mean"}) * inv_std_dev * f32scale
+ ${a ? `+ ${Ct(I, g, "bias[j]")}` : ""}
+ );
+ }
+
+ ${$ ? "mean_data_output[global_idx] = mean" : ""};
+ ${v ? "inv_std_output[global_idx] = inv_std_dev" : ""};
+ }`;
+ }, T = [{ dims: u, dataType: e[0].dataType }];
+ return $ && T.push({ dims: b, dataType: 1 }), v && T.push({ dims: b, dataType: 1 }), { name: "LayerNormalization", shaderCache: { hint: `${g};${r};${n}`, inputDependencies: _ }, getRunData: () => ({ outputs: T, dispatchGroup: { x: Math.ceil(c / 64) }, programUniforms: S }), getShaderSource: x };
+ }, Zd = (e, t) => {
+ mh(e.inputs), e.compute(fh(e.inputs, t, e.outputCount));
+ };
+});
+var hh;
+var Yd;
+var Xd = U(() => {
+ "use strict";
+ ne();
+ Yr();
+ Xr();
+ hh = (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.");
+ }, Yd = (e) => {
+ hh(e.inputs);
+ let t = Je.calcShape(e.inputs[0].dims, e.inputs[1].dims, true);
+ if (!t) throw new Error("Can't use matmul on the given tensors");
+ let r = t[t.length - 1], n = e.inputs[0].dims[e.inputs[0].dims.length - 1];
+ if (r < 8 && n < 8) e.compute(Qr(e.inputs, { activation: "" }, t));
+ else {
+ let o = t[t.length - 2], i = k.size(e.inputs[0].dims.slice(0, -2)), a = k.size(e.inputs[1].dims.slice(0, -2));
+ if (i !== 1 && o === 1 && a === 1) {
+ let u = e.inputs[0].reshape([1, i, n]), d = e.inputs[1].reshape([1, n, r]), c = [1, i, r], p = [u, d];
+ e.compute(Jt(p, { activation: "" }, t, c), { inputs: p });
+ } else e.compute(Jt(e.inputs, { activation: "" }, t));
+ }
+ };
+});
+var gh;
+var bh;
+var yh;
+var Jd;
+var el;
+var tl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ gh = (e, t) => {
+ if (e.length < 3 || e.length > 4) throw new Error("MatMulNBits requires 3 or 4 inputs");
+ let r = e[0], n = r.dims.length;
+ if (r.dims[n - 1] !== t.k) throw new Error("The last dim of input shape does not match the k value");
+ let o = Math.floor((t.k + t.blockSize - 1) / t.blockSize), i = t.blockSize / 8 * t.bits, a = e[1];
+ if (!k.areEqual(a.dims, [t.n, o, i])) throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");
+ let d = e[2].dims;
+ if (k.size(d) !== t.n * o) throw new Error("scales input size error.");
+ if (e.length === 4) {
+ let p = e[3].dims, m = t.bits > 4 ? t.n * o : t.n * Math.floor((o + 1) / 2);
+ if (k.size(p) !== m) throw new Error("zeroPoints input size error.");
+ }
+ }, bh = (e, t) => {
+ let r = e[0].dims, n = r.length, o = r[n - 2], i = t.k, a = t.n, u = r.slice(0, n - 2), d = k.size(u), p = e[1].dims[2] / 4, m = e[0].dataType, f = ce(t.k), b = ce(p), g = ce(a), _ = u.concat([o, a]), S = o > 1 && a / g % 2 === 0 ? 2 : 1, $ = k.size(_) / g / S, v = 64, x = [], T = [d, o, i / f], E = k.convertShape(e[1].dims).slice();
+ E.splice(-1, 1, p / b), x.push(...N(T)), x.push(...N(E)), x.push(...N(e[2].dims)), e.length === 4 && x.push(...N(k.convertShape(e[3].dims)));
+ let I = [d, o, a / g];
+ x.push(...N(I));
+ let z = (O) => {
+ let D = T.length, L = P("a", e[0].dataType, D, f), q = P("b", 12, E.length, b), Q = P("scales", e[2].dataType, e[2].dims.length), W = [L, q, Q], Z = e.length === 4 ? P("zero_points", 12, e[3].dims.length) : void 0;
+ Z && W.push(Z);
+ let we = I.length, H = M("output", e[0].dataType, we, g), j = be(e[0].dataType), te = (() => {
+ switch (f) {
+ case 1:
+ return `array<${j}, 8>`;
+ case 2:
+ return `mat4x2<${j}>`;
+ case 4:
+ return `mat2x4<${j}>`;
+ default:
+ throw new Error(`${f}-component is not supported.`);
+ }
+ })(), X = () => {
+ let ye = `
+ // reuse a data
+ var input_offset = ${L.indicesToOffset(`${L.type.indices}(batch, row, word_offset)`)};
+ var a_data: ${te};
+ for (var j: u32 = 0; j < ${8 / f}; j++) {
+ a_data[j] = ${L.getByOffset("input_offset")};
+ input_offset++;
+ }
+ `;
+ for (let re = 0; re < g * S; re++) ye += `
+ b_value = ${b === 1 ? `b${re}_data` : `b${re}_data[i]`};
+ b_value_lower = unpack4xU8(b_value & b_mask);
+ b_value_upper = unpack4xU8((b_value >> 4) & b_mask);
+ b_quantized_values = ${te}(${Array.from({ length: 4 }, (C, V) => `${j}(b_value_lower[${V}]), ${j}(b_value_upper[${V}])`).join(", ")});
+ b_dequantized_values = ${f === 1 ? `${te}(${Array.from({ length: 8 }, (C, V) => `(b_quantized_values[${V}] - ${Z ? `zero_point${re}` : "zero_point"}) * scale${re}`).join(", ")});` : `(b_quantized_values - ${te}(${Array(8).fill(`${Z ? `zero_point${re}` : "zero_point"}`).join(",")})) * scale${re};`};
+ workgroup_shared[local_id.x * ${S} + ${Math.floor(re / g)}]${g > 1 ? `[${re % g}]` : ""} += ${Array.from({ length: 8 / f }, (C, V) => `${f === 1 ? `a_data[${V}] * b_dequantized_values[${V}]` : `dot(a_data[${V}], b_dequantized_values[${V}])`}`).join(" + ")};
+ `;
+ return ye;
+ }, ue = () => {
+ let ye = `
+ var col_index = col * ${g};
+ ${Z ? `
+ let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;
+ var zero_point_byte_count: u32;
+ var zero_point_word_index: u32;
+ var zero_point_byte_offset: u32;
+ let zero_point_nibble_offset: u32 = block & 0x1u;
+ var zero_point_bits_offset: u32;
+ var zero_point_word: u32;` : `
+ // The default zero point is 8 for unsigned 4-bit quantization.
+ let zero_point = ${j}(8);`}
+ `;
+ for (let re = 0; re < g * S; re++) ye += `
+ let scale${re} = ${Q.getByOffset("col_index * nBlocksPerCol + block")};
+ ${Z ? `
+ zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u);
+ zero_point_word_index = zero_point_byte_count >> 0x2u;
+ zero_point_byte_offset = zero_point_byte_count & 0x3u;
+ zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
+ zero_point_word = ${Z.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
+ let zero_point${re} = ${j}((zero_point_word) & 0xFu);` : ""}
+ col_index += 1;`;
+ return ye;
+ }, he = () => {
+ let ye = `col_index = col * ${g};`;
+ for (let re = 0; re < g * S; re++) ye += `
+ let b${re}_data = ${q.getByIndices(`${q.type.indices}(col_index, block, word)`)};
+ col_index += 1;`;
+ return ye += `
+ var b_value: u32;
+ let b_mask: u32 = 0x0F0F0F0Fu;
+ var b_value_lower: vec4;
+ var b_value_upper: vec4;
+ var b_quantized_values: ${te};
+ var b_dequantized_values: ${te};`, ye;
+ };
+ return `
+ var workgroup_shared: array<${H.type.value}, ${S * v}>;
+ ${O.declareVariables(...W, H)}
+ ${O.mainStart([v, 1, 1])}
+ let output_indices = ${H.offsetToIndices(`(global_idx / ${v}) * ${S}`)};
+ let col = output_indices[2];
+ let row = output_indices[1];
+ let batch = output_indices[0];
+ let nBlocksPerCol = uniforms.b_shape[1];
+
+ for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) {
+ //process one block
+ var word_offset: u32 = block * ${t.blockSize / f};
+ ${ue()}
+ for (var word: u32 = 0; word < ${p}; word += ${b}) {
+ ${he()}
+ for (var i: u32 = 0; i < ${b}; i++) {
+ ${X()}
+ word_offset += ${8 / f};
+ }
+ }
+ }
+ workgroupBarrier();
+
+ if (local_id.x < ${S}) {
+ var output_value: ${H.type.value} = ${H.type.value}(0);
+ var workgroup_shared_offset: u32 = local_id.x;
+ for (var b: u32 = 0u; b < ${v}u; b++) {
+ output_value += workgroup_shared[workgroup_shared_offset];
+ workgroup_shared_offset += ${S};
+ }
+ ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`, "output_value")};
+ }
+ }`;
+ };
+ return { name: "MatMulNBits", shaderCache: { hint: `${t.blockSize};${t.bits};${f};${b};${g};${S};${v}`, inputDependencies: Array(e.length).fill("rank") }, getRunData: () => ({ outputs: [{ dims: _, dataType: m }], dispatchGroup: { x: $ }, programUniforms: x }), getShaderSource: z };
+ }, yh = (e, t) => {
+ let r = e[0].dims, n = r.length, o = r[n - 2], i = t.k, a = t.n, u = r.slice(0, n - 2), d = k.size(u), p = e[1].dims[2] / 4, m = e[0].dataType, f = ce(t.k), b = ce(p), g = u.concat([o, a]), _ = 128, S = a % 8 === 0 ? 8 : a % 4 === 0 ? 4 : 1, $ = _ / S, v = $ * b * 8, x = v / f, T = v / t.blockSize, E = k.size(g) / S, I = [], z = [d, o, i / f], O = k.convertShape(e[1].dims).slice();
+ O.splice(-1, 1, p / b), I.push(...N(z)), I.push(...N(O)), I.push(...N(e[2].dims)), e.length === 4 && I.push(...N(k.convertShape(e[3].dims)));
+ let D = [d, o, a];
+ I.push(...N(D));
+ let L = (q) => {
+ let Q = z.length, W = P("a", e[0].dataType, Q, f), Z = P("b", 12, O.length, b), we = P("scales", e[2].dataType, e[2].dims.length), H = [W, Z, we], j = e.length === 4 ? P("zero_points", 12, e[3].dims.length) : void 0;
+ j && H.push(j);
+ let te = D.length, X = M("output", e[0].dataType, te), ue = be(e[0].dataType), he = () => {
+ switch (f) {
+ case 1:
+ return `
+ let a_data0 = vec4<${ue}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
+ let a_data1 = vec4<${ue}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;
+ case 2:
+ return `
+ let a_data0 = vec4<${ue}>(sub_a[word_offset], sub_a[word_offset + 1]);
+ let a_data1 = vec4<${ue}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;
+ case 4:
+ return `
+ let a_data0 = sub_a[word_offset];
+ let a_data1 = sub_a[word_offset + 1];`;
+ default:
+ throw new Error(`${f}-component is not supported.`);
+ }
+ };
+ return `
+ var sub_a: array<${W.type.value}, ${x}>;
+ var inter_results: array, ${S}>;
+ ${q.declareVariables(...H, X)}
+ ${q.mainStart([$, S, 1])}
+ let output_indices = ${X.offsetToIndices(`workgroup_index * ${S}`)};
+ let col = output_indices[2];
+ let row = output_indices[1];
+ let batch = output_indices[0];
+ let n_blocks_per_col = uniforms.b_shape[1];
+ let num_tiles = (n_blocks_per_col - 1) / ${T} + 1;
+
+ // Loop over shared dimension.
+ for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
+ let a_col_start = tile * ${x};
+ // load one tile A data into shared memory.
+ for (var a_offset = local_idx; a_offset < ${x}; a_offset += ${_})
+ {
+ let a_col = a_col_start + a_offset;
+ if (a_col < uniforms.a_shape[2])
+ {
+ sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)};
+ } else {
+ sub_a[a_offset] = ${W.type.value}(0);
+ }
+ }
+ workgroupBarrier();
+
+ // each thread process one block
+ let b_row = col + local_id.y;
+ let block = tile * ${T} + local_id.x;
+ ${j ? `
+ let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;
+ let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);
+ let zero_point_word_index = zero_point_byte_count >> 0x2u;
+ let zero_point_byte_offset = zero_point_byte_count & 0x3u;
+ let zero_point_nibble_offset: u32 = block & 0x1u;
+ let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
+ let zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
+ let zero_point = ${ue}((zero_point_word) & 0xFu);` : `
+ // The default zero point is 8 for unsigned 4-bit quantization.
+ let zero_point = ${ue}(8);`}
+ let scale = ${we.getByOffset("b_row * n_blocks_per_col + block")};
+ let b_data = ${Z.getByIndices(`${Z.type.indices}(b_row, block, 0)`)};
+ var word_offset = local_id.x * ${t.blockSize / f};
+ for (var i: u32 = 0; i < ${b}; i++) {
+ ${he()}
+ let b_value = ${b === 1 ? "b_data" : "b_data[i]"};
+ let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);
+ let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);
+ let b_quantized_values = mat2x4<${ue}>(${Array.from({ length: 4 }, (ye, re) => `${ue}(b_value_lower[${re}]), ${ue}(b_value_upper[${re}])`).join(", ")});
+ let b_dequantized_values = (b_quantized_values - mat2x4<${ue}>(${Array(8).fill("zero_point").join(",")})) * scale;
+ inter_results[local_id.y][local_id.x] += ${Array.from({ length: 2 }, (ye, re) => `${`dot(a_data${re}, b_dequantized_values[${re}])`}`).join(" + ")};
+ word_offset += ${8 / f};
+ }
+ workgroupBarrier();
+ }
+
+ if (local_idx < ${S}) {
+ var output_value: ${X.type.value} = ${X.type.value}(0);
+ for (var b = 0u; b < ${$}; b++) {
+ output_value += inter_results[local_idx][b];
+ }
+ if (col + local_idx < uniforms.output_shape[2])
+ {
+ ${X.setByIndices(`${X.type.indices}(batch, row, col + local_idx)`, "output_value")}
+ }
+ }
+ }`;
+ };
+ return { name: "BlockwiseMatMulNBits32", shaderCache: { hint: `${t.blockSize};${f};${b};${$};${S}`, inputDependencies: Array(e.length).fill("rank") }, getRunData: () => ({ outputs: [{ dims: g, dataType: m }], dispatchGroup: { x: E }, programUniforms: I }), getShaderSource: L };
+ }, Jd = (e, t) => {
+ gh(e.inputs, t), t.blockSize === 32 && e.adapterInfo.isVendor("intel") && e.adapterInfo.isArchitecture("gen-12lp") ? e.compute(yh(e.inputs, t)) : e.compute(bh(e.inputs, t));
+ }, el = (e) => J(e);
+});
+var _h;
+var wh;
+var vh;
+var $h;
+var xh;
+var Sh;
+var Th;
+var Ih;
+var rl;
+var nl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ _h = (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].");
+ }
+ }, wh = (e, t, r) => {
+ let n = "";
+ for (let o = t - 1; o >= 0; --o) n += `
+ k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)};
+ if (k < 0) {
+ break;
+ }
+ if (k >= i32(${F("uniforms.x_shape", o, t)})) {
+ break;
+ }
+ offset += k * i32(${F("uniforms.x_strides", o, t)});
+ `;
+ return `
+ value = ${e.type.value}(uniforms.constant_value);
+ for (var i = 0; i < 1; i++) {
+ var offset = 0;
+ var k = 0;
+ ${n}
+ value = x[offset];
+ }
+ `;
+ }, vh = (e, t, r) => {
+ let n = "";
+ for (let o = t - 1; o >= 0; --o) n += `
+ k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)};
+ if (k < 0) {
+ k = -k;
+ }
+ {
+ let _2n_1 = 2 * (i32(${F("uniforms.x_shape", o, t)}) - 1);
+ k = k % _2n_1;
+ if(k >= i32(${F("uniforms.x_shape", o, t)})) {
+ k = _2n_1 - k;
+ }
+ }
+ offset += k * i32(${F("uniforms.x_strides", o, t)});
+ `;
+ return `
+ var offset = 0;
+ var k = 0;
+ ${n}
+ value = x[offset];
+ `;
+ }, $h = (e, t, r) => {
+ let n = "";
+ for (let o = t - 1; o >= 0; --o) n += `
+ k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)};
+ if (k < 0) {
+ k = 0;
+ }
+ if (k >= i32(${F("uniforms.x_shape", o, t)})) {
+ k = i32(${F("uniforms.x_shape", o, t)}) - 1;
+ }
+ offset += k * i32(${F("uniforms.x_strides", o, t)});
+ `;
+ return `
+ var offset = 0;
+ var k = 0;
+ ${n}
+ value = x[offset];
+ `;
+ }, xh = (e, t, r) => {
+ let n = "";
+ for (let o = t - 1; o >= 0; --o) n += `
+ k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)};
+ if (k < 0) {
+ k += i32(${F("uniforms.x_shape", o, t)}]);
+ }
+ if (k >= i32(${F("uniforms.x_shape", o, t)})) {
+ k -= i32(${F("uniforms.x_shape", o, t)});
+ }
+ offset += k * i32(${F("uniforms.x_strides", o, t)});
+ `;
+ return `
+ var offset = 0;
+ var k = 0;
+ ${n}
+ value = x[offset];
+ `;
+ }, Sh = (e, t, r) => {
+ switch (r.mode) {
+ case 0:
+ return wh(e, t, r.pads.length);
+ case 1:
+ return vh(e, t, r.pads.length);
+ case 2:
+ return $h(e, t, r.pads.length);
+ case 3:
+ return xh(e, t, r.pads.length);
+ default:
+ throw new Error("Invalid mode");
+ }
+ }, Th = (e, t) => {
+ let r = k.padShape(e[0].dims.slice(), t.pads), n = e[0].dims, o = k.size(r), i = [{ type: 12, data: o }, { type: 6, data: t.pads }], a = e.length >= 3 && e[2].data;
+ t.mode === 0 && i.push({ type: a ? e[2].dataType : 1, data: t.value }), i.push(...N(e[0].dims, r));
+ let u = ["rank"], d = (c) => {
+ let p = M("output", e[0].dataType, r.length), m = P("x", e[0].dataType, n.length), f = m.type.value, b = Sh(p, n.length, t), g = [{ name: "output_size", type: "u32" }, { name: "pads", type: "i32", length: t.pads.length }];
+ return t.mode === 0 && g.push({ name: "constant_value", type: a ? f : "f32" }), `
+ ${c.registerUniforms(g).declareVariables(m, p)}
+ ${c.mainStart()}
+ ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+
+ let indices = ${p.offsetToIndices("global_idx")};
+
+ var value = ${f}(0);
+ ${b}
+ output[global_idx] = value;
+ }`;
+ };
+ return { name: "Pad", shaderCache: { hint: `${t.mode}${a}`, inputDependencies: u }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k.size(r) / 64) }, programUniforms: i }), getShaderSource: d };
+ }, Ih = (e, t) => {
+ if (e.length > 1) {
+ let r = e[1].getBigInt64Array(), n = e.length >= 3 && e[2].data ? e[2].dataType === 10 ? e[2].getUint16Array()[0] : e[2].getFloat32Array()[0] : 0, o = e[0].dims.length, i = new Int32Array(2 * o).fill(0);
+ if (e.length >= 4) {
+ let u = e[3].getBigInt64Array();
+ for (let d = 0; d < u.length; d++) i[Number(u[d])] = Number(r[d]), i[Number(u[d]) + o] = Number(r[d + u.length]);
+ } else r.forEach((u, d) => i[Number(d)] = Number(u));
+ let a = [];
+ return i.forEach((u) => a.push(u)), { mode: t.mode, value: n, pads: a };
+ } else return t;
+ }, rl = (e, t) => {
+ _h(e.inputs);
+ let r = Ih(e.inputs, t);
+ e.compute(Th(e.inputs, r), { inputs: [0] });
+ };
+});
+var rn;
+var ol;
+var il;
+var al;
+var sl;
+var Ch;
+var Ah;
+var ul;
+var dl;
+var ll;
+var cl;
+var pl;
+var ml;
+var fl;
+var hl;
+var gl;
+var bl;
+var yl;
+var _l;
+var wl = U(() => {
+ "use strict";
+ We();
+ ee();
+ ne();
+ ie();
+ rn = (e) => {
+ if (ge.webgpu.validateInputContent && (!e || e.length !== 1)) throw new Error("Pool ops requires 1 input.");
+ }, ol = (e, t, r) => {
+ let n = t.format === "NHWC", o = e.dims.slice();
+ n && o.splice(1, 0, o.pop());
+ let i = Object.hasOwnProperty.call(t, "dilations"), a = t.kernelShape.slice(), u = t.strides.slice(), d = i ? t.dilations.slice() : [], c = t.pads.slice();
+ Tt.adjustPoolAttributes(r, o, a, u, d, c);
+ let p = Tt.computePoolOutputShape(r, o, u, d, a, c, t.autoPad), m = Object.assign({}, t);
+ i ? Object.assign(m, { kernelShape: a, strides: u, pads: c, dilations: d, cacheKey: t.cacheKey }) : Object.assign(m, { kernelShape: a, strides: u, pads: c, cacheKey: t.cacheKey });
+ let f = p.slice();
+ return f.push(f.splice(1, 1)[0]), [m, n ? f : p];
+ }, il = (e, t) => {
+ let r = t.format === "NHWC", n = k.size(e), o = k.size(t.kernelShape), i = [{ type: 12, data: n }, { type: 12, data: o }], a = [{ name: "outputSize", type: "u32" }, { name: "kernelSize", type: "u32" }];
+ if (t.kernelShape.length <= 2) {
+ let u = t.kernelShape[t.kernelShape.length - 1], d = t.strides[t.strides.length - 1], c = t.pads[t.pads.length / 2 - 1], p = t.pads[t.pads.length - 1], m = !!(c + p);
+ i.push({ type: 12, data: u }, { type: 12, data: d }, { type: 12, data: c }, { type: 12, data: p }), a.push({ name: "kw", type: "u32" }, { name: "sw", type: "u32" }, { name: "pwStart", type: "u32" }, { name: "pwEnd", type: "u32" });
+ let f = false;
+ if (t.kernelShape.length === 2) {
+ let b = t.kernelShape[t.kernelShape.length - 2], g = t.strides[t.strides.length - 2], _ = t.pads[t.pads.length / 2 - 2], S = t.pads[t.pads.length - 2];
+ f = !!(_ + S), i.push({ type: 12, data: b }, { type: 12, data: g }, { type: 12, data: _ }, { type: 12, data: S }), a.push({ name: "kh", type: "u32" }, { name: "sh", type: "u32" }, { name: "phStart", type: "u32" }, { name: "phEnd", type: "u32" });
+ }
+ return [i, a, true, m, f];
+ } else {
+ if (r) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");
+ let u = k.computeStrides(t.kernelShape);
+ i.push({ type: 12, data: u }, { type: 12, data: t.pads }, { type: 12, data: t.strides }), a.push({ name: "kernelStrides", type: "u32", length: u.length }, { name: "pads", type: "u32", length: t.pads.length }, { name: "strides", type: "u32", length: t.strides.length });
+ let d = t.pads.reduce((c, p) => c + p);
+ return [i, a, !!d, false, false];
+ }
+ }, al = (e, t, r, n, o, i, a, u, d, c, p, m) => {
+ let f = o.format === "NHWC", b = t.type.value, g = M("output", t.type.tensor, n);
+ if (o.kernelShape.length <= 2) {
+ let _ = "", S = "", $ = "", v = r - (f ? 2 : 1);
+ if (p ? _ = `
+ for (var i: u32 = 0u; i < uniforms.kw; i++) {
+ xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;
+ if (xIndices[${v}] < 0 || xIndices[${v}]
+ >= uniforms.x_shape[${v}]) {
+ pad++;
+ continue;
+ }
+ let x_val = x[${t.indicesToOffset("xIndices")}];
+ ${i}
+ }` : _ = `
+ for (var i: u32 = 0u; i < uniforms.kw; i++) {
+ xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;
+ let x_val = x[${t.indicesToOffset("xIndices")}];
+ ${i}
+ }`, o.kernelShape.length === 2) {
+ let T = r - (f ? 3 : 2);
+ m ? S = `
+ for (var j: u32 = 0u; j < uniforms.kh; j++) {
+ xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;
+ if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) {
+ pad += i32(uniforms.kw);
+ continue;
+ }
+ ` : S = `
+ for (var j: u32 = 0u; j < uniforms.kh; j++) {
+ xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;
+ `, $ = `
+ }
+ `;
+ }
+ return `
+ ${e.registerUniforms(d).declareVariables(t, g)}
+
+ ${e.mainStart()}
+ ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+
+ let indices = ${g.offsetToIndices("global_idx")};
+ var xIndices = ${g.offsetToIndices("global_idx")};
+
+ var value = ${b}(${u});
+ var pad = 0;
+ ${S}
+ ${_}
+ ${$}
+ ${a}
+
+ output[global_idx] = value;
+ }`;
+ } else {
+ if (f) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");
+ let _ = o.kernelShape.length, S = o.pads.length, $ = "";
+ return c ? $ = `
+ if (xIndices[j] >= uniforms.x_shape[j]) {
+ pad++;
+ isPad = true;
+ break;
+ }
+ }
+ if (!isPad) {
+ let x_val = x[${t.indicesToOffset("xIndices")}];
+ ${i}
+ }` : $ = `
+ }
+ let x_val = x[${t.indicesToOffset("xIndices")}];
+ ${i}
+ `, `
+ ${e.registerUniforms(d).declareVariables(t, g)}
+
+ ${e.mainStart()}
+ ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+ let indices = ${g.offsetToIndices("global_idx")};
+ var xIndices = ${g.offsetToIndices("global_idx")};
+
+ var offsets: array;
+
+ var value = ${b}(${u});
+ var pad = 0;
+ var isPad = false;
+
+ for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
+ var offset = i;
+ for (var j = 0u; j < ${_ - 1}u; j++) {
+ offsets[j] = offset / ${F("uniforms.kernelStrides", "j", _)};
+ offset -= offsets[j] * ${F("uniforms.kernelStrides", "j", _)};
+ }
+ offsets[${_ - 1}] = offset;
+
+ isPad = false;
+ for (var j = ${r - _}u; j < ${r}u; j++) {
+ xIndices[j] = indices[j] * ${F("uniforms.strides", `j - ${r - _}u`, _)}
+ + offsets[j - ${r - _}u] - ${F("uniforms.pads", "j - 2u", S)};
+ ${$}
+ }
+ ${a}
+
+ output[global_idx] = value;
+ }`;
+ }
+ }, sl = (e) => `${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`, Ch = (e) => `${sl(e)};${e.countIncludePad}`, Ah = (e) => `${sl(e)};${e.storageOrder};${e.dilations}`, ul = (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 }), dl = (e, t, r, n) => {
+ let [o, i] = ol(t, n, r), a = P("x", t.dataType, t.dims.length), u = a.type.value, d = "value += x_val;", c = "";
+ o.countIncludePad ? c += `value /= ${u}(uniforms.kernelSize);` : c += `value /= ${u}(i32(uniforms.kernelSize) - pad);`;
+ let [p, m, f, b, g] = il(i, o);
+ p.push(...N(t.dims, i));
+ let _ = ["rank"];
+ return { name: e, shaderCache: { hint: `${n.cacheKey};${f};${b};${g}`, inputDependencies: _ }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(k.size(i) / 64) }, programUniforms: p }), getShaderSource: (S) => al(S, a, t.dims.length, i.length, o, d, c, 0, m, f, b, g) };
+ }, ll = (e) => {
+ let t = e.count_include_pad !== 0, r = ul(e);
+ if (r.ceilMode !== 0) throw new Error("using ceil() in shape computation is not yet supported for AveragePool");
+ let n = { countIncludePad: t, ...r, cacheKey: "" };
+ return { ...n, cacheKey: Ch(n) };
+ }, cl = (e, t) => {
+ rn(e.inputs), e.compute(dl("AveragePool", e.inputs[0], false, t));
+ }, pl = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [] }, ml = (e) => {
+ let t = e.format;
+ return { format: t, ...pl, cacheKey: t };
+ }, fl = (e, t) => {
+ rn(e.inputs), e.compute(dl("GlobalAveragePool", e.inputs[0], true, t));
+ }, hl = (e, t, r, n) => {
+ let [o, i] = ol(t, n, r), a = `
+ value = max(x_val, value);
+ `, u = "", d = P("x", t.dataType, t.dims.length), c = ["rank"], [p, m, f, b, g] = il(i, o);
+ return p.push(...N(t.dims, i)), { name: e, shaderCache: { hint: `${n.cacheKey};${f};${b};${g}`, inputDependencies: c }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(k.size(i) / 64) }, programUniforms: p }), getShaderSource: (_) => al(_, d, t.dims.length, i.length, o, a, u, t.dataType === 10 ? -65504 : -1e5, m, f, b, g) };
+ }, gl = (e, t) => {
+ rn(e.inputs), e.compute(hl("MaxPool", e.inputs[0], false, t));
+ }, bl = (e) => {
+ let t = e.storage_order, r = e.dilations, n = ul(e);
+ if (t !== 0) throw new Error("column major storage order is not yet supported for MaxPool");
+ if (n.ceilMode !== 0) throw new Error("using ceil() in shape computation is not yet supported for MaxPool");
+ let o = { storageOrder: t, dilations: r, ...n, cacheKey: "" };
+ return { ...o, cacheKey: Ah(o) };
+ }, yl = (e) => {
+ let t = e.format;
+ return { format: t, ...pl, cacheKey: t };
+ }, _l = (e, t) => {
+ rn(e.inputs), e.compute(hl("GlobalMaxPool", e.inputs[0], true, t));
+ };
+});
+var kh;
+var Ph;
+var vl;
+var $l;
+var xl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ kh = (e, t) => {
+ if (e.length < 2 || e.length > 3) throw new Error("DequantizeLinear requires 2 or 3 inputs.");
+ if (e.length === 3 && e[1].dims === e[2].dims) throw new Error("x-scale and x-zero-point must have the same shape.");
+ if (e.length === 3 && e[0].dataType !== e[2].dataType) throw new Error("x and x-zero-point must have the same data type.");
+ if (e[0].dataType === 6 && e.length > 2) throw new Error("In the case of dequantizing int32 there is no zero point.");
+ if (e[1].dims.length !== 0 && e[1].dims.length !== 1 && e[1].dims.length !== e[0].dims.length) throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");
+ if (e.length > 2) {
+ if (e[0].dataType !== e[2].dataType) throw new Error("x and x-zero-point must have the same data type.");
+ if (e[1].dims.length !== e[2].dims.length) throw new Error("scale and zero-point inputs must have the same rank.");
+ if (!e[1].dims.map((r, n) => r === e[2].dims[n]).reduce((r, n) => r && n, true)) throw new Error("scale and zero-point inputs must have the same shape.");
+ }
+ if (t.blockSize > 0) {
+ if (e[1].dims.length === 0 || e[1].dims.length === 1 && e[1].dims[0] === 1) throw new Error("blockSize must be set only for block quantization.");
+ if (!e[1].dims.map((o, i) => i === t.axis || o === e[0].dims[i]).reduce((o, i) => o && i, true)) throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");
+ if (e[1].dims.length !== e[0].dims.length) throw new Error("For block qunatization the scale input rank must be the same as the x rank.");
+ let r = e[0].dims[t.axis], n = e[1].dims[t.axis];
+ if (t.blockSize < Math.ceil(r / n) || t.blockSize > Math.ceil(r / (n - 1) - 1)) throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].");
+ }
+ }, Ph = (e, t) => {
+ let r = k.normalizeAxis(t.axis, e[0].dims.length), n = e[0].dataType, o = n === 3, i = e[0].dims, a = e[1].dataType, u = k.size(i), d = n === 3 || n === 2, c = d ? [Math.ceil(k.size(e[0].dims) / 4)] : e[0].dims, p = e[1].dims, m = e.length > 2 ? e[2] : void 0, f = m ? d ? [Math.ceil(k.size(m.dims) / 4)] : m.dims : void 0, b = p.length === 0 || p.length === 1 && p[0] === 1, g = b === false && p.length === 1, _ = ce(u), S = b && (!d || _ === 4), $ = S ? _ : 1, v = S && !d ? _ : 1, x = P("input", d ? 12 : n, c.length, v), T = P("scale", a, p.length), E = m ? P("zero_point", d ? 12 : n, f.length) : void 0, I = M("output", a, i.length, $), z = [x, T];
+ E && z.push(E);
+ let O = [c, p];
+ m && O.push(f);
+ let D = [{ type: 12, data: u / $ }, { type: 12, data: r }, { type: 12, data: t.blockSize }, ...N(...O, i)], L = (q) => {
+ let Q = [{ name: "output_size", type: "u32" }, { name: "axis", type: "u32" }, { name: "block_size", type: "u32" }];
+ return `
+ ${q.registerUniforms(Q).declareVariables(...z, I)}
+ ${q.mainStart()}
+ ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let output_indices = ${I.offsetToIndices("global_idx")};
+
+ // Set input x
+ ${d ? `
+ let input = ${x.getByOffset("global_idx / 4")};
+ let x_vec = ${o ? "unpack4xI8(input)" : "unpack4xU8(input)"};
+ let x_value = ${$ === 1 ? "x_vec[global_idx % 4]" : "x_vec"};` : `let x_value = ${x.getByOffset("global_idx")};`};
+
+ // Set scale input
+ ${b ? `let scale_value= ${T.getByOffset("0")}` : g ? `
+ let scale_index = ${I.indicesGet("output_indices", "uniforms.axis")};
+ let scale_value= ${T.getByOffset("scale_index")};` : `
+ var scale_indices: ${T.type.indices} = output_indices;
+ let index = ${T.indicesGet("scale_indices", "uniforms.axis")} / uniforms.block_size;
+ ${T.indicesSet("scale_indices", "uniforms.axis", "index")};
+ let scale_value= ${T.getByIndices("scale_indices")};`};
+
+ // Set zero-point input
+ ${E ? b ? d ? `
+ let zero_point_input = ${E.getByOffset("0")};
+ let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"};
+ let zero_point_value= zero_point_vec[0]` : `let zero_point_value = ${E.getByOffset("0")}` : g ? d ? `
+ let zero_point_index = ${I.indicesGet("output_indices", "uniforms.axis")};
+ let zero_point_input = ${E.getByOffset("zero_point_index / 4")};
+ let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"};
+ let zero_point_value = zero_point_vec[zero_point_index % 4]` : `
+ let zero_point_index = ${I.indicesGet("output_indices", "uniforms.axis")};
+ let zero_point_value = ${E.getByOffset("zero_point_index")};` : d ? `
+ let zero_point_offset = ${T.indicesToOffset("scale_indices")};
+ let zero_point_input = ${E.getByOffset("zero_point_offset / 4")};
+ let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"};
+ let zero_point_value = zero_point_vec[zero_point_offset % 4];` : `let zero_point_value = ${E.getByIndices("scale_indices")};` : `let zero_point_value = ${d ? o ? "i32" : "u32" : x.type.value}(0);`};
+ // Compute and write output
+ ${I.setByOffset("global_idx", `${I.type.value}(x_value - zero_point_value) * scale_value`)};
+ }`;
+ };
+ return { name: "DequantizeLinear", shaderCache: { hint: t.cacheKey, inputDependencies: E ? ["rank", "rank", "rank"] : ["rank", "rank"] }, getShaderSource: L, getRunData: () => ({ outputs: [{ dims: i, dataType: a }], dispatchGroup: { x: Math.ceil(u / $ / 64), y: 1, z: 1 }, programUniforms: D }) };
+ }, vl = (e, t) => {
+ kh(e.inputs, t), e.compute(Ph(e.inputs, t));
+ }, $l = (e) => J({ axis: e.axis, blockSize: e.blockSize });
+});
+var zh;
+var Oh;
+var Sl;
+var Tl = U(() => {
+ "use strict";
+ We();
+ ee();
+ ie();
+ zh = (e, t, r) => {
+ let n = e === t, o = e < t && r < 0, i = e > t && r > 0;
+ if (n || o || i) throw new Error("Range these inputs' contents are invalid.");
+ }, Oh = (e, t, r, n) => {
+ let o = Math.abs(Math.ceil((t - e) / r)), i = [o], a = o, u = [{ type: 12, data: a }, { type: n, data: e }, { type: n, data: r }, ...N(i)], d = (c) => {
+ let p = M("output", n, i.length), m = p.type.value, f = [{ name: "outputSize", type: "u32" }, { name: "start", type: m }, { name: "delta", type: m }];
+ return `
+ ${c.registerUniforms(f).declareVariables(p)}
+ ${c.mainStart()}
+ ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+ output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta;
+ }`;
+ };
+ return { name: "Range", shaderCache: { hint: `${n}` }, getShaderSource: d, getRunData: () => ({ outputs: [{ dims: i, dataType: n }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: u }) };
+ }, Sl = (e) => {
+ let t = 0, r = 0, n = 0;
+ e.inputs[0].dataType === 6 ? (t = e.inputs[0].getInt32Array()[0], r = e.inputs[1].getInt32Array()[0], n = e.inputs[2].getInt32Array()[0]) : e.inputs[0].dataType === 1 && (t = e.inputs[0].getFloat32Array()[0], r = e.inputs[1].getFloat32Array()[0], n = e.inputs[2].getFloat32Array()[0]), ge.webgpu.validateInputContent && zh(t, r, n), e.compute(Oh(t, r, n, e.inputs[0].dataType), { inputs: [] });
+ };
+});
+var Bh;
+var Il;
+var Cl;
+var Dh;
+var Al;
+var El;
+var kl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ Bh = (e, t, r, n) => {
+ if (e !== "none" && n !== "i32" && n !== "u32" && n !== "f32") throw new Error(`Input ${n} is not supported with reduction ${e}.`);
+ let o = `{
+ var oldValue = 0;
+ loop {
+ let newValueF32 =`, i = `;
+ let newValue = bitcast(newValueF32);
+ let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);
+ if res.exchanged {
+ break;
+ }
+ oldValue = res.old_value;
+ }
+ }`;
+ switch (e) {
+ case "none":
+ return `${t}=${r};`;
+ case "add":
+ return n === "i32" || n === "u32" ? `atomicAdd(&${t}, bitcast<${n}>(${r}));` : `
+ ${o}bitcast<${n}>(oldValue) + (${r})${i}`;
+ case "max":
+ return n === "i32" || n === "u32" ? `atomicMax(&${t}, bitcast<${n}>(${r}));` : `
+ ${o}max(bitcast(oldValue), (${r}))${i}`;
+ case "min":
+ return n === "i32" || n === "u32" ? `atomicMin(&${t}, bitcast<${n}>(${r}));` : `${o}min(bitcast<${n}>(oldValue), (${r}))${i}`;
+ case "mul":
+ return `${o}(bitcast<${n}>(oldValue) * (${r}))${i}`;
+ default:
+ throw new Error(`Reduction ${e} is not supported.`);
+ }
+ }, Il = (e, t) => `${e === 1 ? `
+ let element_count_dim = uniforms.output_strides;
+ let dim_value = uniforms.output_shape;` : `
+ let element_count_dim = uniforms.output_strides[${t ? "i - indices_start" : "i"}];
+ let dim_value = uniforms.output_shape[${t ? "i - indices_start" : "i"} + uniforms.last_index_dimension];`}
+
+ if (index >= 0) {
+ if (index >= i32(dim_value)) {
+ index = i32(dim_value - 1);
+ }
+ } else {
+ if (index < -i32(dim_value)) {
+ index = 0;
+ } else {
+ index += i32(dim_value);
+ }
+ }
+ data_offset += u32((u32(index) * element_count_dim));`, Cl = (e, t, r) => `for (var i = 0u; i < uniforms.num_updates_elements; i++) {
+ let value = updates[uniforms.num_updates_elements * ${r ? "global_idx" : "idx"} + i];
+ ${Bh(e.reduction, "output[data_offset + i]", "value", t)}
+ }`, Dh = (e, t) => {
+ let r = e[0].dims, n = e[1].dims, o = r, i = 1, a = Math.ceil(k.size(n) / i), u = n[n.length - 1], d = k.sizeFromDimension(r, u), c = k.sizeFromDimension(n, 0) / u, p = [{ type: 12, data: a }, { type: 12, data: u }, { type: 12, data: d }, ...N(e[1].dims, e[2].dims, o)], m = (f) => {
+ let b = P("indices", e[1].dataType, e[1].dims.length), g = P("updates", e[2].dataType, e[2].dims.length, i), _ = t.reduction !== "none" && t.reduction !== "" ? es("output", e[0].dataType, o.length) : M("output", e[0].dataType, o.length, i);
+ return `
+ ${f.registerUniform("output_size", "u32").registerUniform("last_index_dimension", "u32").registerUniform("num_updates_elements", "u32").declareVariables(b, g, _)}
+ ${f.mainStart()}
+ ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ var hasDuplicates = false;
+ if (${t.reduction === "none"}) {
+ for (var i = 0; i < ${c}; i = i + 1) {
+ for (var j = i + 1; j < ${c}; j = j + 1) {
+ var index_i = i32(indices[i].x);
+ var index_j = i32(indices[j].x);
+ if (index_i == index_j) {
+ hasDuplicates = true;
+ break;
+ }
+ }
+ if (hasDuplicates) {
+ break;
+ }
+ }
+ }
+
+ if (${t.reduction === "none"} && hasDuplicates) {
+ if (global_idx != 0u) {
+ return;
+ }
+ // Process each index-update pair individually when duplicates exist
+ for (var idx = 0u; idx < ${c}u; idx++) {
+ var data_offset = 0u;
+ for (var i = 0u; i < uniforms.last_index_dimension; i++) {
+ var index = i32(indices[idx * uniforms.last_index_dimension + i].x);
+ ${Il(r.length, false)}
+ }
+ ${Cl(t, _.type.value, false)}
+ }
+ return;
+ }
+
+ var data_offset = 0u;
+ var indices_start = uniforms.last_index_dimension * global_idx;
+ var indices_end = indices_start + uniforms.last_index_dimension;
+ for (var i = indices_start; i < indices_end; i++) {
+ var index = i32(indices[i].x);
+ ${Il(r.length, true)}
+ }
+ ${Cl(t, _.type.value, true)}
+ }`;
+ };
+ return { name: "ScatterND", shaderCache: { hint: `${t.cacheKey}_${t.reduction}`, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: o, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: p }), getShaderSource: m };
+ }, Al = (e) => J({ reduction: e.reduction }), El = (e, t) => {
+ e.compute(Dh(e.inputs, t), { inputs: [e.inputs[1], e.inputs[2]], outputs: [] });
+ };
+});
+var Mh;
+var Rh;
+var Uh;
+var Pl;
+var Nh;
+var Vh;
+var Wh;
+var Lh;
+var Gh;
+var Hh;
+var Fh;
+var qh;
+var zl;
+var jh;
+var Kh;
+var Zh;
+var Qh;
+var Yh;
+var Ol;
+var Bl;
+var Dl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ Mh = (e, t) => {
+ if (e.every((r) => r > 0 || (() => {
+ throw new Error("Resize requires scales input values to be positive");
+ })), e.length > 0) {
+ if (t.mode === "linear") {
+ if (!(e.length === 2 || e.length === 3 || e.length === 4 && e[0] === 1 && e[1] === 1 || e.length === 4 && e[0] === 1 && e[3] === 1 || e.length === 5 && e[0] === 1 && e[1] === 1)) throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
+ one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`);
+ } else if (t.mode === "cubic" && !(e.length === 2 || e.length === 4 && e[0] === 1 && e[1] === 1 || e.length === 4 && e[0] === 1 && e[3] === 1)) throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode");
+ }
+ }, Rh = (e, t, r) => {
+ t.every((o) => o >= 0 && o < r || (() => {
+ throw new Error("Resize requires axes input values to be positive and less than rank");
+ }));
+ let n = new Array(r).fill(1);
+ return t.forEach((o, i) => n[o] = e[i]), n;
+ }, Uh = (e, t, r, n, o, i) => {
+ let [a, u, d] = r > 10 ? [1, 2, 3] : [-1, e.length > 1 ? 1 : -1, -1], c = e[0].dims.length;
+ if (a > 0 && e.length > a && e[a].dims.length > 0) e[a].getFloat32Array().forEach((p) => i.push(p));
+ else if (t.coordinateTransformMode === "tf_crop_and_resize") throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");
+ if (u > 0 && e.length > u && e[u].dims.length === 1 && e[u].dims[0] > 0) {
+ if (e[u].getFloat32Array().forEach((p) => n.push(p)), n.length !== 0 && n.length !== c && r >= 18 && n.length !== t.axes.length) throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");
+ Mh(n, t), t.axes.length > 0 && Rh(n, t.axes, c).forEach((p, m) => n[m] = p);
+ }
+ if (d > 0 && e.length > d && e[d].dims.length === 1 && e[d].dims[0] > 0 && (e[d].getBigInt64Array().forEach((p) => o.push(Number(p))), o.length !== 0 && o.length !== c && r >= 18 && o.length !== t.axes.length)) throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");
+ if (t.axes.length > 0) {
+ if (n.length !== 0 && n.length !== t.axes.length) throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');
+ if (o.length !== 0 && o.length !== t.axes.length) throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified');
+ }
+ if (typeof n < "u" && typeof o < "u" && n.length > 0 && o.length > c) throw new Error("Resize requires only of scales or sizes to be specified");
+ }, Pl = (e, t, r, n) => `
+ // The whole part and the fractional part are calculated separately due to inaccuracy of floating
+ // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
+ // offset-by-one error later in floor().
+ let big = (${e}) * (${t});
+ let whole = ${n}(big / (${r}));
+ let fract = ${n}(big % (${r})) / ${n}(${r});
+ return whole + fract;
+`, Nh = (e, t) => `fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
+ lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { ` + (() => {
+ switch (e) {
+ case "asymmetric":
+ return `
+ if (xScale < 1.0 || floor(xScale) != xScale) {
+ return ${t}(xResized) / ${t}(xScale);
+ } else {
+ ${Pl("xResized", "lengthOriginal", "lengthResized", t)}
+ }
+ `;
+ case "pytorch_half_pixel":
+ return `if (lengthResized > 1) {
+ return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;
+ } else {
+ return 0.0;
+ }`;
+ case "tf_half_pixel_for_nn":
+ return `return (${t}(xResized) + 0.5) / ${t}(xScale);`;
+ case "align_corners":
+ return `if (lengthResized == 1) {
+ return 0.0;
+ } else {
+ ${Pl("xResized", "lengthOriginal - 1", "lengthResized - 1", t)}
+ }`;
+ case "tf_crop_and_resize":
+ return `if (lengthResized > 1) {
+ return ${t}(roiStart) * ${t}(lengthOriginal - 1) +
+ (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /
+ ${t}(lengthResized - 1);
+ } else {
+ return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);
+ }`;
+ case "half_pixel_symmetric":
+ return `const outputWidth = ${t}xScale * ${t}(lengthResized);
+ const adjustment = ${t}(lengthResized) / outputWidth;
+ const center = ${t}(lengthOriginal) / 2;
+ const offset = center * (1 - adjustment);
+ return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;
+ case "half_pixel":
+ return `return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;
+ default:
+ throw new Error(`Coordinate transform mode ${e} is not supported`);
+ }
+ })() + "}", Vh = (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`);
+ }
+ })() + "}", Wh = (e, t, r) => {
+ let n = new Array(r).fill(0).concat(new Array(r).fill(1)), o = e.length === 0 ? n : e.slice();
+ return t.length > 0 ? (t.forEach((i, a) => {
+ n[i] = o[a], n[a + r] = o[t.length + a];
+ }), n) : o;
+ }, Lh = (e, t, r, n) => {
+ let o = [];
+ if (r.length > 0) if (n.length > 0) {
+ if (e.forEach((i) => o.push(i)), Math.max(...n) > e.length) throw new Error("axes is out of bound");
+ n.forEach((i, a) => o[i] = r[a]);
+ } else r.forEach((i) => o.push(i));
+ else {
+ if (t.length === 0) throw new Error("Resize requires either scales or sizes.");
+ o = e.map((i, a) => Math.round(i * t[a]));
+ }
+ return o;
+ }, Gh = (e, t, r) => {
+ let n = (() => {
+ switch (r.keepAspectRatioPolicy) {
+ case "not_larger":
+ return r.axes.length > 0 ? Math.min(...r.axes.map((i) => t[i]), Number.MAX_VALUE) : Math.min(...t, Number.MAX_VALUE);
+ case "not_smaller":
+ return r.axes.length > 0 ? Math.max(...r.axes.map((i) => t[i]), Number.MIN_VALUE) : Math.max(...t, Number.MIN_VALUE);
+ default:
+ throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`);
+ }
+ })();
+ t.fill(1, 0, t.length);
+ let o = e.slice();
+ return r.axes.length > 0 ? (r.axes.forEach((i) => t[i] = n), r.axes.forEach((i) => o[i] = Math.round(e[i] * t[i]))) : (t.fill(n, 0, t.length), o.forEach((i, a) => o[a] = Math.round(i * t[a]))), o;
+ }, Hh = (e, t, r, n, o) => `
+ fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {
+ var original_indices: array<${e.type.value}, ${r.length}>;
+ for (var i:u32 = 0; i < ${r.length}; i++) {
+ var output_index = ${e.indicesGet("output_indices", "i")};
+ var scale = ${F("uniforms.scales", "i", n)};
+ var roi_low = ${F("uniforms.roi", "i", o)};
+ var roi_hi = ${F("uniforms.roi", `i + ${t.length}`, o)};
+ if (scale == 1.0) {
+ original_indices[i] = ${e.type.value}(output_index);
+ } else {
+ var input_shape_i = ${F("uniforms.input_shape", "i", t.length)};
+ var output_shape_i = ${F("uniforms.output_shape", "i", r.length)};
+ original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
+ input_shape_i, roi_low, roi_hi);
+ }
+ }
+ return original_indices;
+ }`, Fh = (e, t, r, n, o, i, a) => `
+ fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
+ var input_indices: ${e.type.indices};
+ for (var i:u32 = 0; i < ${n.length}; i++) {
+ var output_index = ${t.indicesGet("output_indices", "i")};
+ var input_index: u32;
+ var scale = ${F("uniforms.scales", "i", o)};
+ if (scale == 1.0) {
+ input_index = output_index;
+ } else {
+ var roi_low = ${F("uniforms.roi", "i", i)};
+ var roi_hi = ${F("uniforms.roi", `i + ${r.length}`, i)};
+ var input_shape_i = ${F("uniforms.input_shape", "i", r.length)};
+ var output_shape_i = ${F("uniforms.output_shape", "i", n.length)};
+ var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
+ input_shape_i, roi_low, roi_hi);
+ if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {
+ if (original_idx < 0) {
+ input_index = 0;
+ } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {
+ input_index = input_shape_i - 1;
+ } else {
+ input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));
+ }
+ } else {
+ input_index = u32(original_idx);
+ }
+ }
+ ${e.indicesSet("input_indices", "i", "input_index")}
+ }
+ return input_indices;
+ }`, qh = (e, t) => `
+ fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {
+ for (var i:u32 = 0; i < ${t.length}; i++) {
+ var input_index = ${e.indicesGet("input_indices", "i")};
+ if (input_index < 0 || input_index >= ${F("uniforms.input_shape", "i", t.length)}) {
+ return false;
+ }
+ }
+ return true;
+ }`, zl = (e, t, r, n) => e.rank > n ? `
+ ${e.indicesSet("input_indices", t, "channel")};
+ ${e.indicesSet("input_indices", r, "batch")};
+` : "", jh = (e, t, r, n, o) => {
+ let [a, u, d, c] = r.length === 2 ? [-1, 0, 1, -1] : [0, 2, 3, 1], p = e.type.value;
+ return `
+ fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} {
+ var input_indices: ${e.type.indices};
+ ${e.indicesSet("input_indices", u, `max(0, min(row, ${r[u]} - 1))`)};
+ ${e.indicesSet("input_indices", d, `max(0, min(col, ${r[d]} - 1))`)};
+ ${zl(e, c, a, 2)}
+ return ${e.getByIndices("input_indices")};
+ }
+
+ fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} {
+ var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
+ var row:${p} = originalIndices[${u}];
+ var col:${p} = originalIndices[${d}];
+ ${n ? `if (row < 0 || row > (${r[u]} - 1) || col < 0 || col > (${r[d]} - 1)) {
+ return ${o};
+ }` : ""};
+ row = max(0, min(row, ${r[u]} - 1));
+ col = max(0, min(col, ${r[d]} - 1));
+ var row1: u32 = u32(row);
+ var col1: u32 = u32(col);
+ var row2: u32 = u32(row + 1);
+ var col2: u32 = u32(col + 1);
+ var channel: u32 = ${r.length > 2 ? `u32(originalIndices[${c}])` : "0"};
+ var batch: u32 = ${r.length > 2 ? `u32(originalIndices[${a}])` : "0"};
+ var x11: ${p} = getInputValue(batch, channel, row1, col1);
+ var x12: ${p} = getInputValue(batch, channel, row1, col2);
+ var x21: ${p} = getInputValue(batch, channel, row2, col1);
+ var x22: ${p} = getInputValue(batch, channel, row2, col2);
+ var dx1: ${p} = abs(row - ${p}(row1));
+ var dx2: ${p} = abs(${p}(row2) - row);
+ var dy1: ${p} = abs(col - ${p}(col1));
+ var dy2: ${p} = abs(${p}(col2) - col);
+ if (row1 == row2) {
+ dx1 = 0.5;
+ dx2 = 0.5;
+ }
+ if (col1 == col2) {
+ dy1 = 0.5;
+ dy2 = 0.5;
+ }
+ return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
+ }`;
+ }, Kh = (e, t, r, n, o, i, a, u, d, c) => {
+ let p = r.length === 2, m = true, [f, b] = p ? [0, 1] : m ? [2, 3] : [1, 2], g = e.type.value, _ = (S) => {
+ let $ = S === f ? "row" : "col";
+ return `
+ fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${g} {
+ var output_index = ${t.indicesGet("output_indices", S)};
+ var originalIdx: ${g} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[S]},
+ ${n[S]}, ${r[S]}, ${i[S]}, ${i[S]} + ${r.length});
+ var fractOriginalIdx: ${g} = originalIdx - floor(originalIdx);
+ var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
+
+ if (${u} && (originalIdx < 0 || originalIdx > (${r[S]} - 1))) {
+ return ${d};
+ }
+ var data: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0);
+ for (var i: i32 = -1; i < 3; i++) {
+ var ${$}: ${g} = originalIdx + ${g}(i);
+ if (${$} < 0 || ${$} >= ${r[S]}) {
+ ${c ? `coefs[i + 1] = 0.0;
+ continue;` : u ? `return ${d};` : `${$} = max(0, min(${$}, ${r[S]} - 1));`};
+ }
+ var input_indices_copy: ${e.type.indices} = input_indices;
+ ${e.indicesSet("input_indices_copy", S, `u32(${$})`)};
+ data[i + 1] = ${S === f ? e.getByIndices("input_indices_copy") : "rowCubicInterpolation(input_indices_copy, output_indices)"};
+ }
+ return cubicInterpolation1D(data, coefs);
+ }`;
+ };
+ return `
+ ${_(f)};
+ ${_(b)};
+ fn getCubicInterpolationCoefs(s: ${g}) -> array<${g}, 4> {
+ var absS = abs(s);
+ var coeffs: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0);
+ var oneMinusAbsS: ${g} = 1.0 - absS;
+ var twoMinusAbsS: ${g} = 2.0 - absS;
+ var onePlusAbsS: ${g} = 1.0 + absS;
+ coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};
+ coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;
+ coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
+ coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};
+ return coeffs;
+ }
+
+ fn cubicInterpolation1D(x: array<${g}, 4>, coefs: array<${g}, 4>) -> ${g} {
+ var coefsSum: ${g} = coefs[0] + coefs[1] + coefs[2] + coefs[3];
+ return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;
+ }
+
+ fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${g} {
+ var input_indices: ${e.type.indices} = output_indices;
+ return colCubicInterpolation(input_indices, output_indices);
+ }
+ `;
+ }, Zh = (e, t, r, n, o) => {
+ let [a, u, d, c, p] = r.length === 3 ? [-1, 0, 1, 2, -1] : [0, 2, 3, 4, 1], m = e.type.value;
+ return `
+ fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${m} {
+ var input_indices: ${e.type.indices};
+ ${e.indicesSet("input_indices", u, `max(0, min(depth, ${r[u]} - 1))`)};
+ ${e.indicesSet("input_indices", d, `max(0, min(height, ${r[d]} - 1))`)};
+ ${e.indicesSet("input_indices", c, `max(0, min(width, ${r[c]} - 1))`)};
+ ${zl(e, p, a, 3)}
+ return ${e.getByIndices("input_indices")};
+ }
+
+ fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {
+ var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
+ var depth:${m} = originalIndices[${u}];
+ var height:${m} = originalIndices[${d}];
+ var width:${m} = originalIndices[${c}];
+ ${n ? `if (depth < 0 || depth > (${r[u]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) {
+ return ${o};
+ }` : ""};
+
+ depth = max(0, min(depth, ${r[u]} - 1));
+ height = max(0, min(height, ${r[d]} - 1));
+ width = max(0, min(width, ${r[c]} - 1));
+ var depth1: u32 = u32(depth);
+ var height1: u32 = u32(height);
+ var width1: u32 = u32(width);
+ var depth2: u32 = u32(depth + 1);
+ var height2: u32 = u32(height + 1);
+ var width2: u32 = u32(width + 1);
+ var channel: u32 = ${r.length > 3 ? `u32(originalIndices[${p}])` : "0"};
+ var batch: u32 = ${r.length > 3 ? `u32(originalIndices[${a}])` : "0"};
+
+ var x111: ${m} = getInputValue(batch, channel, depth1, height1, width1);
+ var x112: ${m} = getInputValue(batch, channel, depth1, height1, width2);
+ var x121: ${m} = getInputValue(batch, channel, depth1, height2, width1);
+ var x122: ${m} = getInputValue(batch, channel, depth1, height2, width2);
+ var x211: ${m} = getInputValue(batch, channel, depth2, height1, width1);
+ var x212: ${m} = getInputValue(batch, channel, depth2, height1, width2);
+ var x221: ${m} = getInputValue(batch, channel, depth2, height2, width1);
+ var x222: ${m} = getInputValue(batch, channel, depth2, height2, width2);
+ var dx1: ${m} = abs(depth - ${m}(depth1));
+ var dx2: ${m} = abs(${m}(depth2) - depth);
+ var dy1: ${m} = abs(height - ${m}(height1));
+ var dy2: ${m} = abs(${m}(height2) - height);
+ var dz1: ${m} = abs(width - ${m}(width1));
+ var dz2: ${m} = abs(${m}(width2) - width);
+ if (depth1 == depth2) {
+ dx1 = 0.5;
+ dx2 = 0.5;
+ }
+ if (height1 == height2) {
+ dy1 = 0.5;
+ dy2 = 0.5;
+ }
+ if (width1 == width2) {
+ dz1 = 0.5;
+ dz2 = 0.5;
+ }
+ return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
+ x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
+ }`;
+ }, Qh = (e, t, r, n, o, i) => {
+ let a = e.dims, u = Wh(i, t.axes, a.length), d = Lh(a, n, o, t.axes), c = n.slice();
+ n.length === 0 && (c = a.map((v, x) => v === 0 ? 1 : d[x] / v), t.keepAspectRatioPolicy !== "stretch" && (d = Gh(a, c, t)));
+ let p = M("output", e.dataType, d.length), m = P("input", e.dataType, a.length), f = k.size(d), b = a.length === d.length && a.every((v, x) => v === d[x]), g = t.coordinateTransformMode === "tf_crop_and_resize", _ = t.extrapolationValue, S = m.type.value, $ = (v) => `
+ ${b ? "" : `
+ ${Nh(t.coordinateTransformMode, S)};
+ ${(() => {
+ switch (t.mode) {
+ case "nearest":
+ return `
+ ${qh(m, a)};
+ ${Vh(t.nearestMode, r, S)};
+ ${Fh(m, p, a, d, c.length, u.length, g)};
+ `;
+ case "linear":
+ return `
+ ${Hh(p, a, d, c.length, u.length)};
+ ${(() => {
+ if (a.length === 2 || a.length === 4) return `${jh(m, p, a, g, _)}`;
+ if (a.length === 3 || a.length === 5) return `${Zh(m, p, a, g, _)}`;
+ throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.");
+ })()};
+ `;
+ case "cubic":
+ return `
+ ${(() => {
+ if (a.length === 2 || a.length === 4) return `${Kh(m, p, a, d, c, u, t.cubicCoeffA, g, t.extrapolationValue, t.excludeOutside)}`;
+ throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.");
+ })()};
+ `;
+ default:
+ throw Error("Invalid resize mode");
+ }
+ })()};
+ `}
+ ${v.registerUniform("output_size", "u32").registerUniform("scales", "f32", c.length).registerUniform("roi", "f32", u.length).declareVariables(m, p)}
+ ${v.mainStart()}
+ ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ ${b ? "output[global_idx] = input[global_idx];" : `
+ let output_indices = ${p.offsetToIndices("global_idx")};
+ var input_indices: ${m.type.indices};
+ ${(() => {
+ switch (t.mode) {
+ case "nearest":
+ return `input_indices = calculateInputIndicesFromOutputIndices(output_indices);
+ if (checkInputIndices(input_indices)) {
+ output[global_idx] = ${m.getByIndices("input_indices")};
+ } else {
+ output[global_idx] = ${t.extrapolationValue};
+ }`;
+ case "linear":
+ return `output[global_idx] = ${a.length === 2 || a.length === 4 ? "bilinearInterpolation" : "trilinearInterpolation"}(output_indices);`;
+ case "cubic":
+ return "output[global_idx] = bicubicInterpolation(output_indices);";
+ default:
+ throw Error(`Unsupported resize mode: ${t.mode}`);
+ }
+ })()};
+`}
+ }`;
+ return { name: "Resize", shaderCache: { hint: `${t.cacheKey}|${r}|${c.length > 0 ? t.mode === "cubic" ? c : c.length : ""}|${o.length > 0 ? o : ""}|${u.length > 0 ? u : ""}|${b}|${t.mode === "nearest" ? a.length : a}`, inputDependencies: ["rank"] }, getShaderSource: $, getRunData: () => ({ outputs: [{ dims: d, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: [{ type: 12, data: f }, { type: 1, data: c }, { type: 1, data: u }, ...N(a, d)] }) };
+ }, Yh = (e) => {
+ let t = e.customDataBuffer;
+ return new Uint32Array(t, t.byteOffset, 1)[0];
+ }, Ol = (e, t) => {
+ let r = [], n = [], o = [], i = Yh(e);
+ if (t.antialias !== 0) throw Error("Only default value (0) for Antialias attribute is supported");
+ Uh(e.inputs, t, i, r, n, o), e.compute(Qh(e.inputs[0], t, i, r, n, o), { inputs: [0] });
+ }, Bl = (e) => {
+ let t = e.antialias, r = e.axes, n = e.coordinateTransformMode, o = e.cubicCoeffA, i = e.excludeOutside !== 0, a = e.extrapolationValue, u = e.keepAspectRatioPolicy, d = e.mode, c = e.nearestMode === "" ? "simple" : e.nearestMode;
+ return J({ antialias: t, axes: r, coordinateTransformMode: n, cubicCoeffA: o, excludeOutside: i, extrapolationValue: a, keepAspectRatioPolicy: u, mode: d, nearestMode: c });
+ };
+});
+var Xh;
+var Jh;
+var Ml;
+var Rl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ Xh = (e) => {
+ if (!e || e.length < 3) throw new Error("layerNorm requires at least 3 inputs.");
+ let t = e[0], r = e[1], n = e[2];
+ if (t.dataType !== r.dataType || t.dataType !== n.dataType) throw new Error("All inputs must have the same data type");
+ if (t.dims.length !== 3 && t.dims.length !== 2) throw new Error("Input must be 2D or 3D");
+ if (r.dims.length !== 3 && r.dims.length !== 2) throw new Error("Skip must be 2D or 3D");
+ let o = t.dims[t.dims.length - 1], i = t.dims[t.dims.length - 2];
+ if (r.dims[r.dims.length - 1] !== o) throw new Error("Skip must have the same hidden size as input");
+ if (r.dims[r.dims.length - 2] !== i) throw new Error("Skip must have the same sequence length as input");
+ if (n.dims.length !== 1) throw new Error("Gamma must be 1D");
+ if (n.dims[n.dims.length - 1] !== o) throw new Error("Gamma must have the same hidden size as input");
+ if (e.length > 3) {
+ let a = e[3];
+ if (a.dims.length !== 1) throw new Error("Beta must be 1D");
+ if (a.dims[a.dims.length - 1] !== o) throw new Error("Beta must have the same hidden size as input");
+ }
+ if (e.length > 4) {
+ let a = e[4];
+ if (a.dims.length !== 1) throw new Error("Bias must be 1D");
+ if (a.dims[a.dims.length - 1] !== o) throw new Error("Bias must have the same hidden size as input");
+ }
+ }, Jh = (e, t, r, n) => {
+ let o = t.simplified, i = e[0].dims, a = k.size(i), u = i, d = a, c = i.slice(-1)[0], p = n ? i.slice(0, -1).concat(1) : [], m = !o && e.length > 3, f = e.length > 4, b = n && r > 1, g = n && r > 2, _ = r > 3, S = 64, $ = ce(c), v = [{ type: 12, data: d }, { type: 12, data: $ }, { type: 12, data: c }, { type: 1, data: t.epsilon }], x = (E) => {
+ let I = [{ name: "output_size", type: "u32" }, { name: "components", type: "u32" }, { name: "hidden_size", type: "u32" }, { name: "epsilon", type: "f32" }], z = [P("x", e[0].dataType, e[0].dims, $), P("skip", e[1].dataType, e[1].dims, $), P("gamma", e[2].dataType, e[2].dims, $)];
+ m && z.push(P("beta", e[3].dataType, e[3].dims, $)), f && z.push(P("bias", e[4].dataType, e[4].dims, $)), z.push(M("output", e[0].dataType, u, $)), b && z.push(M("mean_output", 1, p)), g && z.push(M("inv_std_output", 1, p)), _ && z.push(M("input_skip_bias_sum", e[0].dataType, u, $));
+ let O = be(e[0].dataType), D = be(1, $);
+ return `
+
+ ${E.registerUniforms(I).declareVariables(...z)}
+ var sum_shared : array<${D}, ${S}>;
+ var sum_squared_shared : array<${D}, ${S}>;
+
+ ${E.mainStart([S, 1, 1])}
+ let ix = local_id.x;
+ let iy = global_id.x / ${S};
+
+ let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;
+ var stride = hidden_size_vectorized / ${S};
+ let offset = ix * stride + iy * hidden_size_vectorized;
+ let offset1d = stride * ix;
+ if (ix == ${S - 1}) {
+ stride = hidden_size_vectorized - stride * ix;
+ }
+ for (var i: u32 = 0; i < stride; i++) {
+ let skip_value = skip[offset + i];
+ let bias_value = ${f ? "bias[offset1d + i]" : O + "(0.0)"};
+ let input_value = x[offset + i];
+ let value = input_value + skip_value + bias_value;
+ ${_ ? "input_skip_bias_sum[offset + i] = value;" : ""}
+ output[offset + i] = value;
+ let f32_value = ${Ct(O, $, "value")};
+ sum_shared[ix] += f32_value;
+ sum_squared_shared[ix] += f32_value * f32_value;
+ }
+ workgroupBarrier();
+
+ var reduce_size : u32 = ${S};
+ for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {
+ reduce_size = curr_size + (reduce_size & 1);
+ if (ix < curr_size) {
+ sum_shared[ix] += sum_shared[ix + reduce_size];
+ sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];
+ }
+ workgroupBarrier();
+ }
+
+ let sum = sum_shared[0];
+ let square_sum = sum_squared_shared[0];
+ let mean = ${He("sum", $)} / f32(uniforms.hidden_size);
+ let inv_std_dev = inverseSqrt(${He("square_sum", $)} / f32(uniforms.hidden_size) ${o ? "" : "- mean * mean"} + uniforms.epsilon);
+ ${b ? "mean_output[global_idx] = mean;" : ""}
+ ${g ? "inv_std_output[global_idx] = inv_std_dev;" : ""}
+
+ for (var i: u32 = 0; i < stride; i++) {
+ output[offset + i] = (output[offset + i] ${o ? "" : `- ${O}(mean)`}) *
+ ${O}(inv_std_dev) * gamma[offset1d + i]
+ ${m ? "+ beta[offset1d + i]" : ""};
+ }
+ }`;
+ }, T = [{ dims: u, dataType: e[0].dataType }];
+ return r > 1 && T.push({ dims: p, dataType: 1 }), r > 2 && T.push({ dims: p, dataType: 1 }), r > 3 && T.push({ dims: i, dataType: e[0].dataType }), { name: "SkipLayerNormalization", shaderCache: { hint: `${$};${b};${g};${_}`, inputDependencies: e.map((E, I) => "type") }, getShaderSource: x, getRunData: () => ({ outputs: T, dispatchGroup: { x: Math.ceil(d / c) }, programUniforms: v }) };
+ }, Ml = (e, t) => {
+ Xh(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(Jh(e.inputs, t, e.outputCount, false), { outputs: n });
+ };
+});
+var eg;
+var nn;
+var tg;
+var Ul;
+var rg;
+var ng;
+var Nl;
+var Vl;
+var Wl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ ie();
+ eg = (e, t) => {
+ if (!e || e.length < 1) throw new Error("too few inputs");
+ if (t.axes.length !== 0) {
+ if (t.axes.length !== t.starts.length || t.axes.length !== t.ends.length) throw new Error("axes, starts and ends must have the same length");
+ } else if (t.starts.length !== t.ends.length) throw new Error("starts and ends must have the same length");
+ e.slice(1).forEach((r, n) => {
+ if (e[n + 1].dataType !== 6 && e[n + 1].dataType !== 7) throw new Error(`Input ${n} must be an array of int32 or int64`);
+ });
+ }, nn = (e, t) => {
+ let r = [];
+ if (e.length > t) if (e[t].dataType === 7) e[t].getBigInt64Array().forEach((n) => r.push(Number(n)));
+ else if (e[t].dataType === 6) e[t].getInt32Array().forEach((n) => r.push(Number(n)));
+ else throw new Error(`Input ${t} must be an array of int32 or int64`);
+ return r;
+ }, tg = (e, t) => {
+ if (e.length > 1) {
+ let r = nn(e, 1), n = nn(e, 2), o = nn(e, 3);
+ return o.length === 0 && (o = [...Array(e[0].dims.length).keys()]), J({ starts: r, ends: n, axes: o });
+ } else return t;
+ }, Ul = (e, t, r, n, o) => {
+ let i = e;
+ return e < 0 && (i += r[n[t]]), o[t] < 0 ? Math.max(0, Math.min(i, r[n[t]] - 1)) : Math.max(0, Math.min(i, r[n[t]]));
+ }, rg = (e, t, r) => `fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
+ var input_indices: ${e.type.indices};
+ var carry = 0u;
+ for (var i = ${r.length}; i >= 0; i--) {
+ let input_shape_i = ${F("uniforms.input_shape", "i", r.length)};
+ let steps_i = ${F("uniforms.steps", "i", r.length)};
+ let signs_i = ${F("uniforms.signs", "i", r.length)};
+ let starts_i = ${F("uniforms.starts", "i", r.length)};
+ var output_index = ${t.indicesGet("output_indices", "i")};
+ var input_index = output_index * steps_i + starts_i + carry;
+ carry = input_index / input_shape_i;
+ input_index = input_index % input_shape_i;
+ if (signs_i < 0) {
+ input_index = input_shape_i - input_index - 1u + starts_i;
+ }
+ ${e.indicesSet("input_indices", "i", "input_index")};
+ }
+ return input_indices;
+ }`, ng = (e, t) => {
+ let r = e[0].dims, n = k.size(r), o = t.axes.length > 0 ? k.normalizeAxes(t.axes, r.length) : [...Array(r.length).keys()], i = nn(e, 4);
+ i.forEach(($) => $ !== 0 || (() => {
+ throw new Error("step cannot be 0");
+ })), i.length === 0 && (i = Array(o.length).fill(1));
+ let a = t.starts.map(($, v) => Ul($, v, r, o, i)), u = t.ends.map(($, v) => Ul($, v, r, o, i));
+ if (o.length !== a.length || o.length !== u.length) throw new Error("start, ends and axes should have the same number of elements");
+ if (o.length !== r.length) for (let $ = 0; $ < r.length; ++$) o.includes($) || (a.splice($, 0, 0), u.splice($, 0, r[$]), i.splice($, 0, 1));
+ let d = i.map(($) => Math.sign($));
+ i.forEach(($, v, x) => {
+ if ($ < 0) {
+ let T = (u[v] - a[v]) / $, E = a[v], I = E + T * i[v];
+ a[v] = I, u[v] = E, x[v] = -$;
+ }
+ });
+ let c = r.slice(0);
+ o.forEach(($, v) => {
+ c[$] = Math.ceil((u[$] - a[$]) / i[$]);
+ });
+ let p = { dims: c, dataType: e[0].dataType }, m = M("output", e[0].dataType, c.length), f = P("input", e[0].dataType, e[0].dims.length), b = k.size(c), g = [{ name: "outputSize", type: "u32" }, { name: "starts", type: "u32", length: a.length }, { name: "signs", type: "i32", length: d.length }, { name: "steps", type: "u32", length: i.length }], _ = [{ type: 12, data: b }, { type: 12, data: a }, { type: 6, data: d }, { type: 12, data: i }, ...N(e[0].dims, c)], S = ($) => `
+ ${$.registerUniforms(g).declareVariables(f, m)}
+ ${rg(f, m, r)}
+ ${$.mainStart()}
+ ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
+ let output_indices = ${m.offsetToIndices("global_idx")};
+ let input_indices = calculateInputIndices(output_indices);
+ ${m.setByOffset("global_idx", f.getByIndices("input_indices"))}
+ }`;
+ return { name: "Slice", shaderCache: { hint: `${d.length}_${a.length}_${i.length}`, inputDependencies: ["rank"] }, getShaderSource: S, getRunData: () => ({ outputs: [p], dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: _ }) };
+ }, Nl = (e, t) => {
+ eg(e.inputs, t);
+ let r = tg(e.inputs, t);
+ e.compute(ng(e.inputs, r), { inputs: [0] });
+ }, Vl = (e) => {
+ let t = e.starts, r = e.ends, n = e.axes;
+ return J({ starts: t, ends: r, axes: n });
+ };
+});
+var og;
+var ig;
+var Ll;
+var Gl;
+var Hl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ Se();
+ st();
+ ie();
+ og = (e) => {
+ if (!e || e.length !== 1) throw new Error("Softmax op requires 1 input.");
+ }, ig = (e, t) => {
+ let r = e.inputs[0], n = r.dims, o = k.size(n), i = n.length, a = k.normalizeAxis(t.axis, i), u = a < n.length - 1, d, c = [];
+ u ? (c = Array.from({ length: i }, (z, O) => O), c[a] = i - 1, c[i - 1] = a, d = e.compute(Ee(r, c), { inputs: [r], outputs: [-1] })[0]) : d = r;
+ let p = d.dims, m = p[i - 1], f = o / m, b = ce(m), g = m / b, _ = 64;
+ f === 1 && (_ = 256);
+ let S = (z, O) => O === 4 ? `max(max(${z}.x, ${z}.y), max(${z}.z, ${z}.w))` : O === 2 ? `max(${z}.x, ${z}.y)` : O === 3 ? `max(max(${z}.x, ${z}.y), ${z}.z)` : z, $ = P("x", d.dataType, d.dims, b), v = M("result", d.dataType, d.dims, b), x = $.type.value, T = be(d.dataType) === "f32" ? `var threadMax = ${x}(-3.402823e+38f);` : `var threadMax = ${x}(-65504.0h);`, E = (z) => `
+ var rowMaxShared : ${x};
+ var rowSumShared : ${x};
+ var threadShared : array<${x}, ${_}>;
+
+ fn getValue(row: i32, col: i32, row_stride: i32) -> ${x} {
+ let index = row * row_stride + col;
+ return x[index];
+ }
+
+ fn setValue(row: i32, col: i32, row_stride: i32, value: ${x}) {
+ let index = row * row_stride + col;
+ result[index] = value;
+ }
+ ${z.registerUniform("packedCols", "i32").declareVariables($, v)}
+ ${z.mainStart(_)}
+ let gindex = i32(global_idx);
+ let lindex = i32(local_idx);
+ const wg = ${_};
+ let row = gindex / wg;
+ let cols = uniforms.packedCols;
+ let row_stride : i32 = uniforms.packedCols;
+
+ // find the rows max
+ ${T}
+ for (var col = lindex; col < cols; col += wg) {
+ let value = getValue(row, col, row_stride);
+ threadMax = max(threadMax, value);
+ }
+ if (lindex < cols) {
+ threadShared[lindex] = threadMax;
+ }
+ workgroupBarrier();
+
+ var reduceSize = min(cols, wg);
+ for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
+ reduceSize = currSize + (reduceSize & 1);
+ if (lindex < currSize) {
+ threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);
+ }
+ workgroupBarrier();
+ }
+ if (lindex == 0) {
+ rowMaxShared = ${x}(${S("threadShared[0]", b)});
+ }
+ workgroupBarrier();
+
+ // find the rows sum
+ var threadSum = ${x}(0.0);
+ for (var col = lindex; col < cols; col += wg) {
+ let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);
+ threadSum += subExp;
+ }
+ threadShared[lindex] = threadSum;
+ workgroupBarrier();
+
+ for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {
+ if (lindex < currSize) {
+ threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];
+ }
+ workgroupBarrier();
+ }
+ if (lindex == 0) {
+ rowSumShared = ${x}(${He("threadShared[0]", b)});
+ }
+ workgroupBarrier();
+
+ // calculate final value for each element in the row
+ for (var col = lindex; col < cols; col += wg) {
+ let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;
+ setValue(row, col, row_stride, value);
+ }
+ }`, I = e.compute({ name: "Softmax", shaderCache: { hint: `${b};${_}`, inputDependencies: ["type"] }, getRunData: () => ({ outputs: [{ dims: p, dataType: d.dataType }], dispatchGroup: { x: f }, programUniforms: [{ type: 6, data: g }] }), getShaderSource: E }, { inputs: [d], outputs: [u ? -1 : 0] })[0];
+ u && e.compute(Ee(I, c), { inputs: [I] });
+ }, Ll = (e, t) => {
+ og(e.inputs), ig(e, t);
+ }, Gl = (e) => J({ axis: e.axis });
+});
+var Fl;
+var ag;
+var sg;
+var ug;
+var ql;
+var jl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ Fl = (e) => Array.from(e.getBigInt64Array(), Number), ag = (e) => {
+ if (!e || e.length !== 2) throw new Error("Tile requires 2 inputs.");
+ if (e[0].dataType !== 1 && e[0].dataType !== 10 && e[0].dataType !== 6 && e[0].dataType !== 12) throw new Error("Tile only support float, float16, int32, and uint32 data types");
+ if (e[1].dataType !== 7) throw new Error("Tile `repeats` input should be of int64 data type");
+ if (e[1].dims.length !== 1) throw new Error("Tile `repeats` input should be 1-D");
+ if (Fl(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");
+ }, sg = (e, t) => {
+ let r = [];
+ for (let n = 0; n < e.length; ++n) r.push(e[n] * t[n]);
+ return r;
+ }, ug = (e, t) => {
+ let r = e[0].dims, n = t ?? Fl(e[1]), o = sg(r, n), i = k.size(o), a = e[0].dataType, u = P("input", a, r.length), d = M("output", a, o.length), c = (p) => `
+ const inputShape = ${u.indices(...r)};
+ ${p.registerUniform("output_size", "u32").declareVariables(u, d)}
+ ${p.mainStart()}
+ ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
+ let output_indices = ${d.offsetToIndices("global_idx")};
+ var input_indices: ${u.type.indices};
+ for (var i = 0; i < ${r.length}; i++) {
+ let input_dim_i = ${u.indicesGet("uniforms.input_shape", "i")};
+ let input_dim_value = ${d.indicesGet("output_indices", "i")} % input_dim_i;
+
+ ${u.indicesSet("input_indices", "i", "input_dim_value")}
+ }
+ ${d.setByOffset("global_idx", u.getByIndices("input_indices"))}
+ }`;
+ return { name: "Tile", shaderCache: { hint: `${n}`, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: o, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(i / 64) }, programUniforms: [{ type: 12, data: i }, ...N(e[0].dims, o)] }), getShaderSource: c };
+ }, ql = (e) => {
+ ag(e.inputs), e.compute(ug(e.inputs), { inputs: [0] });
+ };
+});
+var dg;
+var lg;
+var Kl;
+var Zl = U(() => {
+ "use strict";
+ ee();
+ ne();
+ ie();
+ dg = (e, t, r, n, o) => {
+ let i = M("output_data", o, r.length, 4), a = P("a_data", t[1].dataType, t[1].dims.length, 4), u = P("b_data", t[2].dataType, t[2].dims.length, 4), d = P("c_data", t[0].dataType, t[0].dims.length, 4), c, p = (m, f, b) => `select(${f}, ${m}, ${b})`;
+ if (!n) c = i.setByOffset("global_idx", p(a.getByOffset("global_idx"), u.getByOffset("global_idx"), d.getByOffset("global_idx")));
+ else {
+ let m = (f, b, g = "") => {
+ let _ = `a_data[index_a${b}][component_a${b}]`, S = `b_data[index_b${b}][component_b${b}]`, $ = `bool(c_data[index_c${b}] & (0xffu << (component_c${b} * 8)))`;
+ return `
+ let output_indices${b} = ${i.offsetToIndices(`global_idx * 4u + ${b}u`)};
+ let offset_a${b} = ${a.broadcastedIndicesToOffset(`output_indices${b}`, i)};
+ let offset_b${b} = ${u.broadcastedIndicesToOffset(`output_indices${b}`, i)};
+ let offset_c${b} = ${d.broadcastedIndicesToOffset(`output_indices${b}`, i)};
+ let index_a${b} = offset_a${b} / 4u;
+ let index_b${b} = offset_b${b} / 4u;
+ let index_c${b} = offset_c${b} / 4u;
+ let component_a${b} = offset_a${b} % 4u;
+ let component_b${b} = offset_b${b} % 4u;
+ let component_c${b} = offset_c${b} % 4u;
+ ${f}[${b}] = ${g}(${p(_, S, $)});
+ `;
+ };
+ o === 9 ? c = `
+ var data = vec4(0);
+ ${m("data", 0, "u32")}
+ ${m("data", 1, "u32")}
+ ${m("data", 2, "u32")}
+ ${m("data", 3, "u32")}
+ output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));` : c = `
+ ${m("output_data[global_idx]", 0)}
+ ${m("output_data[global_idx]", 1)}
+ ${m("output_data[global_idx]", 2)}
+ ${m("output_data[global_idx]", 3)}
+ `;
+ }
+ return `
+ ${e.registerUniform("vec_size", "u32").declareVariables(d, a, u, i)}
+ ${e.mainStart()}
+ ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
+ ${c}
+ }`;
+ }, lg = (e) => {
+ let t = e[1].dims, r = e[2].dims, n = e[0].dims, o = e[1].dataType, i = !(k.areEqual(t, r) && k.areEqual(r, n)), a = t, u = k.size(t);
+ if (i) {
+ let c = Je.calcShape(Je.calcShape(t, r, false), n, false);
+ if (!c) throw new Error("Can't perform where op on the given tensors");
+ a = c, u = k.size(a);
+ }
+ let d = Math.ceil(u / 4);
+ return { name: "Where", shaderCache: { inputDependencies: ["rank", "rank", "rank"] }, getShaderSource: (c) => dg(c, e, a, i, o), getRunData: () => ({ outputs: [{ dims: a, dataType: o }], dispatchGroup: { x: Math.ceil(u / 64 / 4) }, programUniforms: [{ type: 12, data: d }, ...N(n, t, r, a)] }) };
+ }, Kl = (e) => {
+ e.compute(lg(e.inputs));
+ };
+});
+var Ql;
+var Yl = U(() => {
+ "use strict";
+ Es();
+ Fr();
+ zs();
+ Bs();
+ _u();
+ ku();
+ Ou();
+ Zu();
+ rd();
+ id();
+ ud();
+ md();
+ gd();
+ yd();
+ vd();
+ Sd();
+ Cd();
+ kd();
+ Od();
+ Md();
+ Fd();
+ Kd();
+ Qd();
+ Xd();
+ tl();
+ $o();
+ nl();
+ wl();
+ xl();
+ Tl();
+ kl();
+ Gr();
+ Dl();
+ To();
+ Rl();
+ Wl();
+ Hl();
+ So();
+ jl();
+ st();
+ jr();
+ Zl();
+ Ql = /* @__PURE__ */ new Map([["Abs", [Ds]], ["Acos", [Ms]], ["Acosh", [Rs]], ["Add", [wu]], ["ArgMax", [As, uo]], ["ArgMin", [Cs, uo]], ["Asin", [Us]], ["Asinh", [Ns]], ["Atan", [Vs]], ["Atanh", [Ws]], ["Attention", [ks]], ["AveragePool", [cl, ll]], ["BatchNormalization", [Ps]], ["BiasAdd", [Os]], ["BiasSplitGelu", [yu]], ["Cast", [Gs, Ls]], ["Ceil", [Fs]], ["Clip", [Hs]], ["Concat", [Pu, zu]], ["Conv", [yo, bo]], ["ConvTranspose", [td, Ju]], ["Cos", [qs]], ["Cosh", [js]], ["CumSum", [nd, od]], ["DepthToSpace", [ad, sd]], ["DequantizeLinear", [vl, $l]], ["Div", [vu]], ["Einsum", [cd, pd]], ["Elu", [Ks, Yt]], ["Equal", [$u]], ["Erf", [Zs]], ["Exp", [Qs]], ["Expand", [hd]], ["FastGelu", [bd]], ["Floor", [Ys]], ["FusedConv", [yo, bo]], ["Gather", [wd, _d]], ["GatherElements", [Ed, Ad]], ["GatherBlockQuantized", [Td, Id]], ["GatherND", [$d, xd]], ["Gelu", [Xs]], ["Gemm", [zd, Pd]], ["GlobalAveragePool", [fl, ml]], ["GlobalMaxPool", [_l, yl]], ["Greater", [Iu]], ["GreaterOrEqual", [Au]], ["GridSample", [Bd, Dd]], ["GroupQueryAttention", [Hd]], ["HardSigmoid", [au, iu]], ["InstanceNormalization", [jd]], ["LayerNormalization", [Zd]], ["LeakyRelu", [Js, Yt]], ["Less", [Cu]], ["LessOrEqual", [Eu]], ["Log", [hu]], ["MatMul", [Yd]], ["MatMulNBits", [Jd, el]], ["MaxPool", [gl, bl]], ["Mul", [xu]], ["MultiHeadAttention", [Nd, Ud]], ["Neg", [tu]], ["Not", [eu]], ["Pad", [rl]], ["Pow", [Su]], ["QuickGelu", [gu, Yt]], ["Range", [Sl]], ["Reciprocal", [ru]], ["ReduceMin", [vs]], ["ReduceMean", [gs]], ["ReduceMax", [ws]], ["ReduceSum", [xs]], ["ReduceProd", [$s]], ["ReduceL1", [bs]], ["ReduceL2", [ys]], ["ReduceLogSum", [Ts]], ["ReduceLogSumExp", [_s]], ["ReduceSumSquare", [Ss]], ["Relu", [nu]], ["Resize", [Ol, Bl]], ["RotaryEmbedding", [Ld]], ["ScatterND", [El, Al]], ["Sigmoid", [ou]], ["Sin", [su]], ["Sinh", [uu]], ["Slice", [Nl, Vl]], ["SkipLayerNormalization", [Ml]], ["Split", [Vd, Wd]], ["Sqrt", [du]], ["Softmax", [Ll, Gl]], ["Sub", [Tu]], ["Tan", [lu]], ["Tanh", [pu]], ["ThresholdedRelu", [fu, Yt]], ["Tile", [ql]], ["Transpose", [ns, os]], ["Where", [Kl]]]);
+});
+var on;
+var Xl = U(() => {
+ "use strict";
+ We();
+ Xe();
+ ie();
+ on = class {
+ constructor(t) {
+ this.backend = t;
+ this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false;
+ }
+ getArtifact(t) {
+ return this.repo.get(t);
+ }
+ setArtifact(t, r) {
+ this.repo.set(t, r);
+ }
+ run(t, r, n, o, i) {
+ Re(t.programInfo.name);
+ let a = this.backend.device, u = this.backend.getComputePassEncoder();
+ this.backend.writeTimestamp(this.backend.pendingDispatchNumber * 2);
+ let d = [];
+ for (let p of r) d.push({ binding: d.length, resource: { buffer: p.buffer } });
+ for (let p of n) d.push({ binding: d.length, resource: { buffer: p.buffer } });
+ i && d.push({ binding: d.length, resource: i });
+ let c = a.createBindGroup({ layout: t.computePipeline.getBindGroupLayout(0), entries: d, label: t.programInfo.name });
+ if (this.backend.sessionStatus === "capturing") {
+ let p = { kernelId: this.backend.currentKernelId, computePipeline: t.computePipeline, bindGroup: c, dispatchGroup: o };
+ this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p);
+ }
+ u.setPipeline(t.computePipeline), u.setBindGroup(0, c), u.dispatchWorkgroups(...o), 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(), Oe(t.programInfo.name);
+ }
+ dispose() {
+ }
+ build(t, r) {
+ Re(t.name);
+ let n = this.backend.device, o = [];
+ [{ feature: "shader-f16", extension: "f16" }, { feature: "subgroups", extension: "subgroups" }].forEach((m) => {
+ n.features.has(m.feature) && o.push(`enable ${m.extension};`);
+ });
+ let a = ts(r, this.backend.device.limits), u = t.getShaderSource(a), d = `${o.join(`
+`)}
+${a.additionalImplementations}
+${u}`, c = n.createShaderModule({ code: d, label: t.name });
+ se("verbose", () => `[WebGPU] ${t.name} shader code: ${d}`);
+ let p = n.createComputePipeline({ compute: { module: c, entryPoint: "main" }, layout: "auto", label: t.name });
+ return Oe(t.name), { programInfo: t, computePipeline: p, uniformVariablesInfo: a.variablesInfo };
+ }
+ normalizeDispatchGroupSize(t) {
+ let r = typeof t == "number" ? t : t.x, n = typeof t == "number" ? 1 : t.y || 1, o = typeof t == "number" ? 1 : t.z || 1, i = this.backend.device.limits.maxComputeWorkgroupsPerDimension;
+ if (r <= i && n <= i && o <= i) return [r, n, o];
+ let a = r * n * o, u = Math.ceil(Math.sqrt(a));
+ if (u > i) {
+ if (u = Math.ceil(Math.cbrt(a)), u > i) throw new Error("Total dispatch size exceeds WebGPU maximum.");
+ return [u, u, u];
+ } else return [u, u, 1];
+ }
+ };
+});
+var Jl = {};
+Dt(Jl, { WebGpuBackend: () => Co });
+var cg;
+var pg;
+var Io;
+var Co;
+var ec = U(() => {
+ "use strict";
+ We();
+ ee();
+ Xe();
+ Zn();
+ Ja();
+ Yl();
+ Xl();
+ cg = (e, t) => {
+ if (t.length !== e.length) throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);
+ let r = [];
+ for (let n = 0; n < e.length; ++n) {
+ let o = e[n].dataType;
+ switch (t[n]) {
+ case "none": {
+ r.push("");
+ break;
+ }
+ case "type": {
+ r.push(`${o}`);
+ break;
+ }
+ case "rank": {
+ let i = e[n].dims.length;
+ r.push(`${o};${i}`);
+ break;
+ }
+ case "dims": {
+ let i = e[n].dims.join(",");
+ r.push(`${o};${i}`);
+ break;
+ }
+ default:
+ throw new Error(`unsupported input dependency: ${t[n]}`);
+ }
+ }
+ return r.join("|");
+ }, pg = (e, t, r) => {
+ let n = e.name;
+ return e.shaderCache?.hint && (n += "[" + e.shaderCache.hint + "]"), n += ":" + r + `:${cg(t, e.shaderCache?.inputDependencies ?? new Array(t.length).fill("dims"))}`, n;
+ }, Io = class {
+ constructor(t) {
+ t && (this.architecture = t.architecture, this.vendor = t.vendor);
+ }
+ isArchitecture(t) {
+ return this.architecture === t;
+ }
+ isVendor(t) {
+ return this.vendor === t;
+ }
+ }, Co = class {
+ constructor() {
+ this.currentSessionId = null;
+ this.currentKernelId = null;
+ this.commandEncoder = null;
+ this.computePassEncoder = null;
+ this.maxDispatchNumber = 16;
+ this.pendingDispatchNumber = 0;
+ this.pendingKernels = [];
+ this.pendingQueries = /* @__PURE__ */ new Map();
+ this.sessionStatus = "default";
+ this.capturedCommandList = /* @__PURE__ */ new Map();
+ this.capturedPendingKernels = /* @__PURE__ */ new Map();
+ this.sessionExternalDataMapping = /* @__PURE__ */ 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 n = [], o = { 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: n }, i = (a) => r.features.has(a) && n.push(a) && true;
+ i("chromium-experimental-timestamp-query-inside-passes") || i("timestamp-query"), i("shader-f16"), i("subgroups"), this.device = await r.requestDevice(o), this.adapterInfo = new Io(r.info || await r.requestAdapterInfo()), this.gpuDataManager = Xa(this), this.programManager = new on(this), this.kernels = /* @__PURE__ */ new Map(), this.kernelPersistentData = /* @__PURE__ */ new Map(), this.kernelCustomData = /* @__PURE__ */ new Map(), Br(t.logLevel, !!t.debug), this.device.onuncapturederror = (a) => {
+ a.error instanceof GPUValidationError && console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`);
+ }, Object.defineProperty(this.env.webgpu, "device", { value: this.device, writable: false, enumerable: true, configurable: false }), Object.defineProperty(this.env.webgpu, "adapter", { value: r, writable: false, enumerable: true, configurable: false }), 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;
+ Re(), 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()), n = this.pendingQueries.get(t);
+ for (let o = 0; o < r.length / 2; o++) {
+ let i = n[o], a = i.kernelId, u = this.kernels.get(a), d = u.kernelType, c = u.kernelName, p = i.programName, m = i.inputTensorViews, f = i.outputTensorViews, b = r[o * 2], g = r[o * 2 + 1];
+ typeof this.queryTimeBase > "u" && (this.queryTimeBase = b);
+ let _ = Number(b - this.queryTimeBase), S = Number(g - this.queryTimeBase);
+ if (!Number.isSafeInteger(_) || !Number.isSafeInteger(S)) throw new RangeError("incorrect timestamp range");
+ if (this.env.webgpu.profiling?.ondata) this.env.webgpu.profiling.ondata({ version: 1, inputsMetadata: m.map(($) => ({ dims: $.dims, dataType: Ye($.dataType) })), outputsMetadata: f.map(($) => ({ dims: $.dims, dataType: Ye($.dataType) })), kernelId: a, kernelType: d, kernelName: c, programName: p, startTime: _, endTime: S });
+ else {
+ let $ = "";
+ m.forEach((x, T) => {
+ $ += `input[${T}]: [${x.dims}] | ${Ye(x.dataType)}, `;
+ });
+ let v = "";
+ f.forEach((x, T) => {
+ v += `output[${T}]: [${x.dims}] | ${Ye(x.dataType)}, `;
+ }), console.log(`[profiling] kernel "${a}|${d}|${c}|${p}" ${$}${v}execution time: ${S - _} ns`);
+ }
+ gr("GPU", `${p}::${b}::${g}`);
+ }
+ t.unmap(), this.pendingQueries.delete(t);
+ }), Oe();
+ }
+ run(t, r, n, o, i, a) {
+ Re(t.name);
+ let u = [];
+ for (let x = 0; x < r.length; ++x) {
+ let T = r[x].data;
+ if (T === 0) continue;
+ let E = this.gpuDataManager.get(T);
+ if (!E) throw new Error(`no GPU data for input: ${T}`);
+ u.push(E);
+ }
+ let { outputs: d, dispatchGroup: c, programUniforms: p } = t.getRunData(r), m = n.length === 0 ? d.map((x, T) => T) : n;
+ if (m.length !== d.length) throw new Error(`Output size ${m.length} must be equal to ${d.length}.`);
+ let f = [], b = [];
+ for (let x = 0; x < d.length; ++x) {
+ if (!Number.isInteger(m[x]) || m[x] < -3 || m[x] >= a) throw new Error(`Invalid output index: ${m[x]}`);
+ if (m[x] === -3) continue;
+ let T = m[x] === -1, E = m[x] === -2, I = T || E ? i(d[x].dataType, d[x].dims) : o(m[x], d[x].dataType, d[x].dims);
+ if (f.push(I), I.data === 0) continue;
+ let z = this.gpuDataManager.get(I.data);
+ if (!z) throw new Error(`no GPU data for output: ${I.data}`);
+ if (T && this.temporaryData.push(z), E) {
+ let O = this.kernelPersistentData.get(this.currentKernelId);
+ O || (O = [], this.kernelPersistentData.set(this.currentKernelId, O)), O.push(z);
+ }
+ b.push(z);
+ }
+ if (u.length !== r.length || b.length !== f.length) {
+ if (b.length === 0) return Oe(t.name), f;
+ throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`);
+ }
+ let g;
+ if (p) {
+ let x = 0, T = [];
+ p.forEach((O) => {
+ let D = typeof O.data == "number" ? [O.data] : O.data;
+ if (D.length === 0) return;
+ let L = O.type === 10 ? 2 : 4, q, Q;
+ O.type === 10 ? (Q = D.length > 4 ? 16 : D.length > 2 ? 8 : D.length * L, q = D.length > 4 ? 16 : L * D.length) : (Q = D.length <= 2 ? D.length * L : 16, q = 16), x = Math.ceil(x / Q) * Q, T.push(x);
+ let W = O.type === 10 ? 8 : 4;
+ x += D.length > 4 ? Math.ceil(D.length / W) * q : D.length * L;
+ });
+ let E = 16;
+ x = Math.ceil(x / E) * E;
+ let I = new ArrayBuffer(x);
+ p.forEach((O, D) => {
+ let L = T[D], q = typeof O.data == "number" ? [O.data] : O.data;
+ if (O.type === 6) new Int32Array(I, L, q.length).set(q);
+ else if (O.type === 12) new Uint32Array(I, L, q.length).set(q);
+ else if (O.type === 10) new Uint16Array(I, L, q.length).set(q);
+ else if (O.type === 1) new Float32Array(I, L, q.length).set(q);
+ else throw new Error(`Unsupported uniform type: ${Ye(O.type)}`);
+ });
+ let z = this.gpuDataManager.create(x, GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM);
+ this.device.queue.writeBuffer(z.buffer, 0, I, 0, x), this.gpuDataManager.release(z.id), g = { offset: 0, size: x, buffer: z.buffer };
+ }
+ let _ = this.programManager.normalizeDispatchGroupSize(c), S = _[1] === 1 && _[2] === 1, $ = pg(t, r, S), v = this.programManager.getArtifact($);
+ if (v || (v = this.programManager.build(t, _), this.programManager.setArtifact($, v), se("info", () => `[artifact] key: ${$}, programName: ${t.name}`)), p && v.uniformVariablesInfo) {
+ if (p.length !== v.uniformVariablesInfo.length) throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${p.length} in program "${v.programInfo.name}".`);
+ for (let x = 0; x < p.length; x++) {
+ let T = p[x], E = T.type, I = typeof T.data == "number" ? 1 : T.data.length, [z, O] = v.uniformVariablesInfo[x];
+ if (E !== z || I !== O) throw new Error(`Uniform variable ${x} mismatch: expect type ${z} with size ${O}, got type ${E} with size ${I} in program "${v.programInfo.name}".`);
+ }
+ }
+ if (se("info", () => `[ProgramManager] run "${t.name}" (key=${$}) with ${_[0]}x${_[1]}x${_[2]}`), this.queryType !== "none" || this.sessionStatus === "capturing") {
+ let x = { kernelId: this.currentKernelId, programName: v.programInfo.name, inputTensorViews: r, outputTensorViews: f };
+ this.pendingKernels.push(x), this.sessionStatus === "capturing" && this.capturedPendingKernels.get(this.currentSessionId).push(x);
+ }
+ return this.programManager.run(v, u, b, _, g), Oe(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, n, o) {
+ let i = Ql.get(t);
+ if (!i) throw new Error(`kernel not implemented: ${t}`);
+ let a = { kernelType: t, kernelName: o, kernelEntry: i[0], attributes: [i[1], n] };
+ this.kernels.set(r, a);
+ }
+ releaseKernel(t) {
+ let r = this.kernelPersistentData.get(t);
+ if (r) {
+ for (let n of r) this.gpuDataManager.release(n.id);
+ this.kernelPersistentData.delete(t);
+ }
+ this.kernelCustomData.delete(t), this.kernels.delete(t);
+ }
+ computeKernel(t, r, n) {
+ let o = this.kernels.get(t);
+ if (!o) throw new Error(`kernel not created: ${t}`);
+ let i = o.kernelType, a = o.kernelName, u = o.kernelEntry, d = o.attributes;
+ if (this.currentKernelId !== null) throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);
+ this.currentKernelId = t, d[0] && (d[1] = d[0](d[1]), d[0] = void 0), se("info", () => `[WebGPU] Start to run kernel "[${i}] ${a}"...`);
+ let c = this.env.debug;
+ this.temporaryData = [];
+ try {
+ return c && this.device.pushErrorScope("validation"), u(r, d[1]), 0;
+ } catch (p) {
+ return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${p}`)), 1;
+ } finally {
+ c && n.push(this.device.popErrorScope().then((p) => p ? `GPU validation error for kernel "[${i}] ${a}": ${p.message}` : null));
+ for (let p of this.temporaryData) this.gpuDataManager.release(p.id);
+ this.temporaryData = [], this.currentKernelId = null;
+ }
+ }
+ registerBuffer(t, r, n, o) {
+ let i = this.sessionExternalDataMapping.get(t);
+ i || (i = /* @__PURE__ */ new Map(), this.sessionExternalDataMapping.set(t, i));
+ let a = i.get(r), u = this.gpuDataManager.registerExternalBuffer(n, o, a);
+ return i.set(r, [u, n]), u;
+ }
+ unregisterBuffers(t) {
+ let r = this.sessionExternalDataMapping.get(t);
+ r && (r.forEach((n) => this.gpuDataManager.unregisterExternalBuffer(n[0])), 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, n) {
+ return async () => {
+ let o = await ro(this, t, r);
+ return Mr(o.buffer, n);
+ };
+ }
+ 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() {
+ se("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() {
+ se("info", "captureEnd"), this.flush(), this.sessionStatus = "default";
+ }
+ replay() {
+ se("info", "replay"), this.sessionStatus = "replaying";
+ let t = this.capturedCommandList.get(this.currentSessionId), r = this.capturedPendingKernels.get(this.currentSessionId), n = t.length;
+ this.pendingKernels = [];
+ for (let o = 0; o < n; o++) {
+ let i = this.getComputePassEncoder(), a = t[o];
+ this.writeTimestamp(this.pendingDispatchNumber * 2), i.setPipeline(a.computePipeline), i.setBindGroup(0, a.bindGroup), i.dispatchWorkgroups(...a.dispatchGroup), this.writeTimestamp(this.pendingDispatchNumber * 2 + 1), this.pendingDispatchNumber++, this.queryType !== "none" && this.pendingKernels.push(r[o]), (this.pendingDispatchNumber >= this.maxDispatchNumber || this.queryType === "at-passes") && this.endComputePass(), this.pendingDispatchNumber >= this.maxDispatchNumber && this.flush();
+ }
+ this.flush(), this.sessionStatus = "default";
+ }
+ onCreateSession() {
+ this.gpuDataManager.onCreateSession();
+ }
+ 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 tc = {};
+Dt(tc, { init: () => mg });
+var tr;
+var Ao;
+var mg;
+var rc = U(() => {
+ "use strict";
+ ee();
+ Xe();
+ ne();
+ Ka();
+ tr = class e {
+ constructor(t, r, n, o) {
+ this.module = t;
+ this.dataType = r;
+ this.data = n;
+ this.dims = o;
+ }
+ getFloat32Array() {
+ if (this.dataType !== 1) throw new Error("Invalid data type");
+ let t = k.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 = k.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 = k.size(this.dims);
+ return t === 0 ? new Int32Array() : new Int32Array(this.module.HEAP8.buffer, this.data, t);
+ }
+ getUint16Array() {
+ if (this.dataType !== 10 && this.dataType !== 4) throw new Error("Invalid data type");
+ let t = k.size(this.dims);
+ return t === 0 ? new Uint16Array() : new Uint16Array(this.module.HEAP8.buffer, this.data, t);
+ }
+ reshape(t) {
+ if (k.size(t) !== k.size(this.dims)) throw new Error("Invalid new shape");
+ return new e(this.module, this.dataType, this.data, t);
+ }
+ }, Ao = class {
+ constructor(t, r, n) {
+ this.module = t;
+ this.backend = r;
+ this.customDataOffset = 0;
+ this.customDataSize = 0;
+ this.adapterInfo = r.adapterInfo;
+ let o = t.PTR_SIZE, i = n / t.PTR_SIZE, a = o === 4 ? "i32" : "i64";
+ this.opKernelContext = Number(t.getValue(o * i++, a));
+ let u = Number(t.getValue(o * i++, a));
+ this.outputCount = Number(t.getValue(o * i++, a)), this.customDataOffset = Number(t.getValue(o * i++, "*")), this.customDataSize = Number(t.getValue(o * i++, a));
+ let d = [];
+ for (let c = 0; c < u; c++) {
+ let p = Number(t.getValue(o * i++, a)), m = Number(t.getValue(o * i++, "*")), f = Number(t.getValue(o * i++, a)), b = [];
+ for (let g = 0; g < f; g++) b.push(Number(t.getValue(o * i++, a)));
+ d.push(new tr(t, p, m, b));
+ }
+ this.inputs = d;
+ }
+ get kernelCustomData() {
+ return this.backend.currentKernelCustomData;
+ }
+ get customDataBuffer() {
+ return this.module.HEAPU8.subarray(this.customDataOffset, this.customDataOffset + this.customDataSize);
+ }
+ compute(t, r) {
+ let n = r?.inputs?.map((u) => typeof u == "number" ? this.inputs[u] : u) ?? this.inputs, o = r?.outputs ?? [], i = (u, d, c) => new tr(this.module, d, this.output(u, c), c), a = (u, d) => {
+ let c = gt(u, d);
+ if (!c) throw new Error(`Unsupported data type: ${u}`);
+ let p = c > 0 ? this.backend.gpuDataManager.create(c).id : 0;
+ return new tr(this.module, u, p, d);
+ };
+ return this.backend.run(t, n, o, i, a, this.outputCount);
+ }
+ output(t, r) {
+ let n = this.module.stackSave();
+ try {
+ let o = this.module.PTR_SIZE, i = o === 4 ? "i32" : "i64", a = this.module.stackAlloc((1 + r.length) * o);
+ this.module.setValue(a, r.length, i);
+ for (let u = 0; u < r.length; u++) this.module.setValue(a + o * (u + 1), r[u], i);
+ return this.module._JsepOutput(this.opKernelContext, t, a);
+ } catch (o) {
+ throw new Error(`Failed to generate kernel's output[${t}] with dims [${r}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${o}`);
+ } finally {
+ this.module.stackRestore(n);
+ }
+ }
+ }, mg = async (e, t, r, n) => {
+ let o = t.jsepInit;
+ if (!o) throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");
+ if (e === "webgpu") {
+ let i = (ec(), Ft(Jl)).WebGpuBackend, a = new i();
+ await a.initialize(r, n), o("webgpu", [a, (u) => a.alloc(Number(u)), (u) => a.free(u), (u, d, c, p = false) => {
+ if (p) se("verbose", () => `[WebGPU] jsepCopyGpuToGpu: src=${Number(u)}, dst=${Number(d)}, size=${Number(c)}`), a.memcpy(Number(u), Number(d));
+ else {
+ se("verbose", () => `[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(u)}, gpuDataId=${Number(d)}, size=${Number(c)}`);
+ let m = t.HEAPU8.subarray(Number(u >>> 0), Number(u >>> 0) + Number(c));
+ a.upload(Number(d), m);
+ }
+ }, async (u, d, c) => {
+ se("verbose", () => `[WebGPU] jsepCopyGpuToCpu: gpuDataId=${u}, dataOffset=${d}, size=${c}`), await a.download(Number(u), () => t.HEAPU8.subarray(Number(d) >>> 0, Number(d + c) >>> 0));
+ }, (u, d, c) => a.createKernel(u, Number(d), c, t.UTF8ToString(t._JsepGetNodeName(Number(d)))), (u) => a.releaseKernel(u), (u, d, c, p) => {
+ se("verbose", () => `[WebGPU] jsepRun: sessionHandle=${c}, kernel=${u}, contextDataOffset=${d}`);
+ let m = new Ao(t, a, Number(d));
+ return a.computeKernel(Number(u), m, p);
+ }, () => a.captureBegin(), () => a.captureEnd(), () => a.replay()]);
+ } else {
+ let i = new Nr(r);
+ o("webnn", [i, () => i.reserveTensorId(), (a) => i.releaseTensorId(a), async (a, u, d, c, p) => i.ensureTensor(a, u, d, c, p), (a, u) => {
+ i.uploadTensor(a, u);
+ }, async (a, u) => i.downloadTensor(a, u)]);
+ }
+ };
+});
+var fg;
+var vr;
+var $r;
+var At;
+var hg;
+var nc;
+var jt;
+var xr;
+var Sr;
+var oc;
+var Tr;
+var Ir;
+var Cr;
+var Vn = U(() => {
+ "use strict";
+ Ma();
+ Ua();
+ ee();
+ ht();
+ Er();
+ jn();
+ fg = (e, t) => {
+ fe()._OrtInit(e, t) !== 0 && pe("Can't initialize onnxruntime.");
+ }, vr = async (e) => {
+ fg(e.wasm.numThreads, Zt(e.logLevel));
+ }, $r = async (e, t) => {
+ fe().asyncInit?.();
+ {
+ let r = (rc(), Ft(tc)).init;
+ if (t === "webgpu") {
+ if (typeof navigator > "u" || !navigator.gpu) throw new Error("WebGPU is not supported in current environment");
+ let n = e.webgpu.adapter;
+ if (n) {
+ if (typeof n.limits != "object" || typeof n.features != "object" || typeof n.requestDevice != "function") throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.");
+ } else {
+ let o = e.webgpu.powerPreference;
+ if (o !== void 0 && o !== "low-power" && o !== "high-performance") throw new Error(`Invalid powerPreference setting: "${o}"`);
+ let i = e.webgpu.forceFallbackAdapter;
+ if (i !== void 0 && typeof i != "boolean") throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);
+ if (n = await navigator.gpu.requestAdapter({ powerPreference: o, forceFallbackAdapter: i }), !n) throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.');
+ }
+ await r("webgpu", fe(), e, n);
+ }
+ if (t === "webnn") {
+ if (typeof navigator > "u" || !navigator.ml) throw new Error("WebNN is not supported in current environment");
+ await r("webnn", fe(), e);
+ }
+ }
+ }, At = /* @__PURE__ */ new Map(), hg = (e) => {
+ let t = fe(), r = t.stackSave();
+ try {
+ let n = t.PTR_SIZE, o = t.stackAlloc(2 * n);
+ t._OrtGetInputOutputCount(e, o, o + n) !== 0 && pe("Can't get session input/output count.");
+ let a = n === 4 ? "i32" : "i64";
+ return [Number(t.getValue(o, a)), Number(t.getValue(o + n, a))];
+ } finally {
+ t.stackRestore(r);
+ }
+ }, nc = (e, t) => {
+ let r = fe(), n = r.stackSave(), o = 0;
+ try {
+ let i = r.PTR_SIZE, a = r.stackAlloc(2 * i);
+ r._OrtGetInputOutputMetadata(e, t, a, a + i) !== 0 && pe("Can't get session input/output metadata.");
+ let d = Number(r.getValue(a, "*"));
+ o = Number(r.getValue(a + i, "*"));
+ let c = r.HEAP32[o / 4];
+ if (c === 0) return [d, 0];
+ let p = r.HEAPU32[o / 4 + 1], m = [];
+ for (let f = 0; f < p; f++) {
+ let b = Number(r.getValue(o + 8 + f * i, "*"));
+ m.push(b !== 0 ? r.UTF8ToString(b) : Number(r.getValue(o + 8 + (f + p) * i, "*")));
+ }
+ return [d, c, m];
+ } finally {
+ r.stackRestore(n), o !== 0 && r._OrtFree(o);
+ }
+ }, jt = (e) => {
+ let t = fe(), 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];
+ }, xr = async (e, t) => {
+ let r, n, o = fe();
+ Array.isArray(e) ? [r, n] = e : e.buffer === o.HEAPU8.buffer ? [r, n] = [e.byteOffset, e.byteLength] : [r, n] = jt(e);
+ let i = 0, a = 0, u = 0, d = [], c = [], p = [];
+ try {
+ if ([a, d] = await Ra(t), t?.externalData && o.mountExternalData) {
+ let T = [];
+ for (let E of t.externalData) {
+ let I = typeof E == "string" ? E : E.path;
+ T.push(Qt(typeof E == "string" ? E : E.data).then((z) => {
+ o.mountExternalData(I, z);
+ }));
+ }
+ await Promise.all(T);
+ }
+ for (let T of t?.executionProviders ?? []) if ((typeof T == "string" ? T : T.name) === "webnn") {
+ if (o.shouldTransferToMLTensor = false, typeof T != "string") {
+ let I = T, z = I?.context, O = I?.gpuDevice, D = I?.deviceType, L = I?.powerPreference;
+ z ? o.currentContext = z : O ? o.currentContext = await o.webnnCreateMLContext(O) : o.currentContext = await o.webnnCreateMLContext({ deviceType: D, powerPreference: L });
+ } else o.currentContext = await o.webnnCreateMLContext();
+ break;
+ }
+ i = await o._OrtCreateSession(r, n, a), o.webgpuOnCreateSession?.(i), i === 0 && pe("Can't create a session."), o.jsepOnCreateSession?.(), o.currentContext && (o.webnnRegisterMLContext(i, o.currentContext), o.currentContext = void 0, o.shouldTransferToMLTensor = true);
+ let [m, f] = hg(i), b = !!t?.enableGraphCapture, g = [], _ = [], S = [], $ = [], v = [];
+ for (let T = 0; T < m; T++) {
+ let [E, I, z] = nc(i, T);
+ E === 0 && pe("Can't get an input name."), c.push(E);
+ let O = o.UTF8ToString(E);
+ g.push(O), S.push(I === 0 ? { name: O, isTensor: false } : { name: O, isTensor: true, type: Ye(I), shape: z });
+ }
+ for (let T = 0; T < f; T++) {
+ let [E, I, z] = nc(i, T + m);
+ E === 0 && pe("Can't get an output name."), p.push(E);
+ let O = o.UTF8ToString(E);
+ _.push(O), $.push(I === 0 ? { name: O, isTensor: false } : { name: O, isTensor: true, type: Ye(I), shape: z });
+ {
+ if (b && t?.preferredOutputLocation === void 0) {
+ v.push("gpu-buffer");
+ continue;
+ }
+ let D = typeof t?.preferredOutputLocation == "string" ? t.preferredOutputLocation : t?.preferredOutputLocation?.[O] ?? "cpu";
+ if (D !== "cpu" && D !== "cpu-pinned" && D !== "gpu-buffer" && D !== "ml-tensor") throw new Error(`Not supported preferred output location: ${D}.`);
+ if (b && D !== "gpu-buffer") throw new Error(`Not supported preferred output location: ${D}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);
+ v.push(D);
+ }
+ }
+ let x = null;
+ return v.some((T) => T === "gpu-buffer" || T === "ml-tensor") && (u = o._OrtCreateBinding(i), u === 0 && pe("Can't create IO binding."), x = { handle: u, outputPreferredLocations: v, outputPreferredLocationsEncoded: v.map((T) => qn(T)) }), At.set(i, [i, c, p, x, b, false]), [i, g, _, S, $];
+ } catch (m) {
+ throw c.forEach((f) => o._OrtFree(f)), p.forEach((f) => o._OrtFree(f)), u !== 0 && o._OrtReleaseBinding(u) !== 0 && pe("Can't release IO binding."), i !== 0 && o._OrtReleaseSession(i) !== 0 && pe("Can't release session."), m;
+ } finally {
+ o._free(r), a !== 0 && o._OrtReleaseSessionOptions(a) !== 0 && pe("Can't release session options."), d.forEach((m) => o._free(m)), o.unmountExternalData?.();
+ }
+ }, Sr = (e) => {
+ let t = fe(), r = At.get(e);
+ if (!r) throw new Error(`cannot release session. invalid session id: ${e}`);
+ let [n, o, i, a, u] = r;
+ a && (u && t._OrtClearBoundOutputs(a.handle) !== 0 && pe("Can't clear bound outputs."), t._OrtReleaseBinding(a.handle) !== 0 && pe("Can't release IO binding.")), t.jsepOnReleaseSession?.(e), t.webnnOnReleaseSession?.(e), t.webgpuOnReleaseSession?.(e), o.forEach((d) => t._OrtFree(d)), i.forEach((d) => t._OrtFree(d)), t._OrtReleaseSession(n) !== 0 && pe("Can't release session."), At.delete(e);
+ }, oc = async (e, t, r, n, o, i, a = false) => {
+ if (!e) {
+ t.push(0);
+ return;
+ }
+ let u = fe(), d = u.PTR_SIZE, c = e[0], p = e[1], m = e[3], f = m, b, g;
+ if (c === "string" && (m === "gpu-buffer" || m === "ml-tensor")) throw new Error("String tensor is not supported on GPU.");
+ if (a && m !== "gpu-buffer") throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);
+ if (m === "gpu-buffer") {
+ let $ = e[2].gpuBuffer;
+ g = gt(Mt(c), p);
+ {
+ let v = u.jsepRegisterBuffer;
+ if (!v) throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');
+ b = v(n, i, $, g);
+ }
+ } else if (m === "ml-tensor") {
+ let $ = e[2].mlTensor;
+ g = gt(Mt(c), p);
+ let v = u.webnnRegisterMLTensor;
+ if (!v) throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');
+ b = v(n, $, Mt(c), p);
+ } else {
+ let $ = e[2];
+ if (Array.isArray($)) {
+ g = d * $.length, b = u._malloc(g), r.push(b);
+ for (let v = 0; v < $.length; v++) {
+ if (typeof $[v] != "string") throw new TypeError(`tensor data at index ${v} is not a string`);
+ u.setValue(b + v * d, Ne($[v], r), "*");
+ }
+ } else {
+ let v = u.webnnIsGraphInput;
+ if (c !== "string" && v) {
+ let x = u.UTF8ToString(o);
+ if (v(n, x)) {
+ let T = Mt(c);
+ g = gt(T, p), f = "ml-tensor";
+ let E = u.webnnCreateTemporaryTensor, I = u.webnnUploadTensor;
+ if (!E || !I) throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');
+ let z = await E(n, T, p);
+ I(z, new Uint8Array($.buffer, $.byteOffset, $.byteLength)), b = z;
+ } else g = $.byteLength, b = u._malloc(g), r.push(b), u.HEAPU8.set(new Uint8Array($.buffer, $.byteOffset, g), b);
+ } else g = $.byteLength, b = u._malloc(g), r.push(b), u.HEAPU8.set(new Uint8Array($.buffer, $.byteOffset, g), b);
+ }
+ }
+ let _ = u.stackSave(), S = u.stackAlloc(4 * p.length);
+ try {
+ p.forEach((v, x) => u.setValue(S + x * d, v, d === 4 ? "i32" : "i64"));
+ let $ = u._OrtCreateTensor(Mt(c), b, g, S, p.length, qn(f));
+ $ === 0 && pe(`Can't create tensor for input/output. session=${n}, index=${i}.`), t.push($);
+ } finally {
+ u.stackRestore(_);
+ }
+ }, Tr = async (e, t, r, n, o, i) => {
+ let a = fe(), u = a.PTR_SIZE, d = At.get(e);
+ if (!d) throw new Error(`cannot run inference. invalid session id: ${e}`);
+ let c = d[0], p = d[1], m = d[2], f = d[3], b = d[4], g = d[5], _ = t.length, S = n.length, $ = 0, v = [], x = [], T = [], E = [], I = a.stackSave(), z = a.stackAlloc(_ * u), O = a.stackAlloc(_ * u), D = a.stackAlloc(S * u), L = a.stackAlloc(S * u);
+ try {
+ [$, v] = Da(i);
+ for (let W = 0; W < _; W++) await oc(r[W], x, E, e, p[t[W]], t[W], b);
+ for (let W = 0; W < S; W++) await oc(o[W], T, E, e, m[n[W]], _ + n[W], b);
+ for (let W = 0; W < _; W++) a.setValue(z + W * u, x[W], "*"), a.setValue(O + W * u, p[t[W]], "*");
+ for (let W = 0; W < S; W++) a.setValue(D + W * u, T[W], "*"), a.setValue(L + W * u, m[n[W]], "*");
+ if (f && !g) {
+ let { handle: W, outputPreferredLocations: Z, outputPreferredLocationsEncoded: we } = f;
+ if (p.length !== _) throw new Error(`input count from feeds (${_}) is expected to be always equal to model's input count (${p.length}).`);
+ for (let H = 0; H < _; H++) {
+ let j = t[H];
+ await a._OrtBindInput(W, p[j], x[H]) !== 0 && pe(`Can't bind input[${H}] for session=${e}.`);
+ }
+ for (let H = 0; H < S; H++) {
+ let j = n[H];
+ o[H]?.[3] ? a._OrtBindOutput(W, m[j], T[H], 0) !== 0 && pe(`Can't bind pre-allocated output[${H}] for session=${e}.`) : a._OrtBindOutput(W, m[j], 0, we[j]) !== 0 && pe(`Can't bind output[${H}] to ${Z[H]} for session=${e}.`);
+ }
+ At.set(e, [c, p, m, f, b, true]);
+ }
+ a.jsepOnRunStart?.(c), a.webnnOnRunStart?.(c);
+ let q;
+ f ? q = await a._OrtRunWithBinding(c, f.handle, S, D, $) : q = await a._OrtRun(c, O, z, _, L, S, D, $), q !== 0 && pe("failed to call OrtRun().");
+ let Q = [];
+ for (let W = 0; W < S; W++) {
+ let Z = Number(a.getValue(D + W * u, "*"));
+ if (Z === T[W]) {
+ Q.push(o[W]);
+ continue;
+ }
+ let we = a.stackSave(), H = a.stackAlloc(4 * u), j = false, te, X = 0;
+ try {
+ a._OrtGetTensorData(Z, H, H + u, H + 2 * u, H + 3 * u) !== 0 && pe(`Can't access output tensor data on index ${W}.`);
+ let he = u === 4 ? "i32" : "i64", ye = Number(a.getValue(H, he));
+ X = a.getValue(H + u, "*");
+ let re = a.getValue(H + u * 2, "*"), C = Number(a.getValue(H + u * 3, he)), V = [];
+ for (let ve = 0; ve < C; ve++) V.push(Number(a.getValue(re + ve * u, he)));
+ a._OrtFree(re) !== 0 && pe("Can't free memory for tensor dims.");
+ let de = V.reduce((ve, $e) => ve * $e, 1);
+ te = Ye(ye);
+ let ze = f?.outputPreferredLocations[n[W]];
+ if (te === "string") {
+ if (ze === "gpu-buffer" || ze === "ml-tensor") throw new Error("String tensor is not supported on GPU.");
+ let ve = [];
+ for (let $e = 0; $e < de; $e++) {
+ let Ce = a.getValue(X + $e * u, "*"), _t = a.getValue(X + ($e + 1) * u, "*"), kt = $e === de - 1 ? void 0 : _t - Ce;
+ ve.push(a.UTF8ToString(Ce, kt));
+ }
+ Q.push([te, V, ve, "cpu"]);
+ } else if (ze === "gpu-buffer" && de > 0) {
+ let ve = a.jsepGetBuffer;
+ if (!ve) throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');
+ let $e = ve(X), Ce = gt(ye, de);
+ if (Ce === void 0 || !zr(te)) throw new Error(`Unsupported data type: ${te}`);
+ j = true, Q.push([te, V, { gpuBuffer: $e, download: a.jsepCreateDownloader($e, Ce, te), dispose: () => {
+ a._OrtReleaseTensor(Z) !== 0 && pe("Can't release tensor.");
+ } }, "gpu-buffer"]);
+ } else if (ze === "ml-tensor" && de > 0) {
+ let ve = a.webnnEnsureTensor, $e = a.webnnIsInt64Supported;
+ if (!ve || !$e) throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');
+ if (gt(ye, de) === void 0 || !Or(te)) throw new Error(`Unsupported data type: ${te}`);
+ if (te === "int64" && !$e(e)) throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');
+ let _t = await ve(e, X, ye, V, false);
+ j = true, Q.push([te, V, { mlTensor: _t, download: a.webnnCreateMLTensorDownloader(X, te), dispose: () => {
+ a.webnnReleaseTensorId(X), a._OrtReleaseTensor(Z);
+ } }, "ml-tensor"]);
+ } else {
+ let ve = Pr(te), $e = new ve(de);
+ new Uint8Array($e.buffer, $e.byteOffset, $e.byteLength).set(a.HEAPU8.subarray(X, X + $e.byteLength)), Q.push([te, V, $e, "cpu"]);
+ }
+ } finally {
+ a.stackRestore(we), te === "string" && X && a._free(X), j || a._OrtReleaseTensor(Z), a.webnnOnRunEnd?.(c);
+ }
+ }
+ return f && !b && (a._OrtClearBoundOutputs(f.handle) !== 0 && pe("Can't clear bound outputs."), At.set(e, [c, p, m, f, b, false])), Q;
+ } finally {
+ a.stackRestore(I), x.forEach((q) => a._OrtReleaseTensor(q)), T.forEach((q) => a._OrtReleaseTensor(q)), E.forEach((q) => a._free(q)), $ !== 0 && a._OrtReleaseRunOptions($), v.forEach((q) => a._free(q));
+ }
+ }, Ir = (e) => {
+ let t = fe(), r = At.get(e);
+ if (!r) throw new Error("invalid session id");
+ let n = r[0], o = t._OrtEndProfiling(n);
+ o === 0 && pe("Can't get an profile file name."), t._OrtFree(o);
+ }, Cr = (e) => {
+ let t = [];
+ for (let r of e) {
+ let n = r[2];
+ !Array.isArray(n) && "buffer" in n && t.push(n.buffer);
+ }
+ return t;
+ };
+});
+var Et;
+var Le;
+var rr;
+var sn;
+var un;
+var an;
+var Eo;
+var ko;
+var Vt;
+var Wt;
+var bg;
+var ic;
+var ac;
+var sc;
+var uc;
+var dc;
+var lc;
+var cc;
+var Po = U(() => {
+ "use strict";
+ We();
+ Vn();
+ ht();
+ _r();
+ Et = () => !!ge.wasm.proxy && typeof document < "u", rr = false, sn = false, un = false, ko = /* @__PURE__ */ new Map(), Vt = (e, t) => {
+ let r = ko.get(e);
+ r ? r.push(t) : ko.set(e, [t]);
+ }, Wt = () => {
+ if (rr || !sn || un || !Le) throw new Error("worker not ready");
+ }, bg = (e) => {
+ switch (e.data.type) {
+ case "init-wasm":
+ rr = false, e.data.err ? (un = true, Eo[1](e.data.err)) : (sn = true, Eo[0]()), an && (URL.revokeObjectURL(an), an = void 0);
+ break;
+ case "init-ep":
+ case "copy-from":
+ case "create":
+ case "release":
+ case "run":
+ case "end-profiling": {
+ let t = ko.get(e.data.type);
+ e.data.err ? t.shift()[1](e.data.err) : t.shift()[0](e.data.out);
+ break;
+ }
+ default:
+ }
+ }, ic = async () => {
+ if (!sn) {
+ if (rr) throw new Error("multiple calls to 'initWasm()' detected.");
+ if (un) throw new Error("previous call to 'initWasm()' failed.");
+ if (rr = true, Et()) return new Promise((e, t) => {
+ Le?.terminate(), za().then(([r, n]) => {
+ try {
+ Le = n, Le.onerror = (i) => t(i), Le.onmessage = bg, Eo = [e, t];
+ let o = { type: "init-wasm", in: ge };
+ !o.in.wasm.wasmPaths && (r || Gn) && (o.in.wasm.wasmPaths = { wasm: new URL("ort-wasm-simd-threaded.jsep.wasm", import.meta.url).href }), Le.postMessage(o), an = r;
+ } catch (o) {
+ t(o);
+ }
+ }, t);
+ });
+ try {
+ await wr(ge.wasm), await vr(ge), sn = true;
+ } catch (e) {
+ throw un = true, e;
+ } finally {
+ rr = false;
+ }
+ }
+ }, ac = async (e) => {
+ if (Et()) return Wt(), new Promise((t, r) => {
+ Vt("init-ep", [t, r]);
+ let n = { type: "init-ep", in: { epName: e, env: ge } };
+ Le.postMessage(n);
+ });
+ await $r(ge, e);
+ }, sc = async (e) => Et() ? (Wt(), new Promise((t, r) => {
+ Vt("copy-from", [t, r]);
+ let n = { type: "copy-from", in: { buffer: e } };
+ Le.postMessage(n, [e.buffer]);
+ })) : jt(e), uc = async (e, t) => {
+ if (Et()) {
+ if (t?.preferredOutputLocation) throw new Error('session option "preferredOutputLocation" is not supported for proxy.');
+ return Wt(), new Promise((r, n) => {
+ Vt("create", [r, n]);
+ let o = { type: "create", in: { model: e, options: { ...t } } }, i = [];
+ e instanceof Uint8Array && i.push(e.buffer), Le.postMessage(o, i);
+ });
+ } else return xr(e, t);
+ }, dc = async (e) => {
+ if (Et()) return Wt(), new Promise((t, r) => {
+ Vt("release", [t, r]);
+ let n = { type: "release", in: e };
+ Le.postMessage(n);
+ });
+ Sr(e);
+ }, lc = async (e, t, r, n, o, i) => {
+ if (Et()) {
+ if (r.some((a) => a[3] !== "cpu")) throw new Error("input tensor on GPU is not supported for proxy.");
+ if (o.some((a) => a)) throw new Error("pre-allocated output tensor is not supported for proxy.");
+ return Wt(), new Promise((a, u) => {
+ Vt("run", [a, u]);
+ let d = r, c = { type: "run", in: { sessionId: e, inputIndices: t, inputs: d, outputIndices: n, options: i } };
+ Le.postMessage(c, Cr(d));
+ });
+ } else return Tr(e, t, r, n, o, i);
+ }, cc = async (e) => {
+ if (Et()) return Wt(), new Promise((t, r) => {
+ Vt("end-profiling", [t, r]);
+ let n = { type: "end-profiling", in: e };
+ Le.postMessage(n);
+ });
+ Ir(e);
+ };
+});
+var pc;
+var yg;
+var dn;
+var mc = U(() => {
+ "use strict";
+ We();
+ Po();
+ ee();
+ yr();
+ jn();
+ pc = (e, t) => {
+ switch (e.location) {
+ case "cpu":
+ return [e.type, e.dims, e.data, "cpu"];
+ case "gpu-buffer":
+ return [e.type, e.dims, { gpuBuffer: e.gpuBuffer }, "gpu-buffer"];
+ case "ml-tensor":
+ return [e.type, e.dims, { mlTensor: e.mlTensor }, "ml-tensor"];
+ default:
+ throw new Error(`invalid data location: ${e.location} for ${t()}`);
+ }
+ }, yg = (e) => {
+ switch (e[3]) {
+ case "cpu":
+ return new Ge(e[0], e[2], e[1]);
+ case "gpu-buffer": {
+ let t = e[0];
+ if (!zr(t)) throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);
+ let { gpuBuffer: r, download: n, dispose: o } = e[2];
+ return Ge.fromGpuBuffer(r, { dataType: t, dims: e[1], download: n, dispose: o });
+ }
+ case "ml-tensor": {
+ let t = e[0];
+ if (!Or(t)) throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);
+ let { mlTensor: r, download: n, dispose: o } = e[2];
+ return Ge.fromMLTensor(r, { dataType: t, dims: e[1], download: n, dispose: o });
+ }
+ default:
+ throw new Error(`invalid data location: ${e[3]}`);
+ }
+ }, dn = class {
+ async fetchModelAndCopyToWasmMemory(t) {
+ return sc(await Qt(t));
+ }
+ async loadModel(t, r) {
+ Re();
+ let n;
+ typeof t == "string" ? n = await this.fetchModelAndCopyToWasmMemory(t) : n = t, [this.sessionId, this.inputNames, this.outputNames, this.inputMetadata, this.outputMetadata] = await uc(n, r), Oe();
+ }
+ async dispose() {
+ return dc(this.sessionId);
+ }
+ async run(t, r, n) {
+ Re();
+ let o = [], i = [];
+ Object.entries(t).forEach((f) => {
+ let b = f[0], g = f[1], _ = this.inputNames.indexOf(b);
+ if (_ === -1) throw new Error(`invalid input '${b}'`);
+ o.push(g), i.push(_);
+ });
+ let a = [], u = [];
+ Object.entries(r).forEach((f) => {
+ let b = f[0], g = f[1], _ = this.outputNames.indexOf(b);
+ if (_ === -1) throw new Error(`invalid output '${b}'`);
+ a.push(g), u.push(_);
+ });
+ let d = o.map((f, b) => pc(f, () => `input "${this.inputNames[i[b]]}"`)), c = a.map((f, b) => f ? pc(f, () => `output "${this.outputNames[u[b]]}"`) : null), p = await lc(this.sessionId, i, d, u, c, n), m = {};
+ for (let f = 0; f < p.length; f++) m[this.outputNames[u[f]]] = a[f] ?? yg(p[f]);
+ return Oe(), m;
+ }
+ startProfiling() {
+ }
+ endProfiling() {
+ cc(this.sessionId);
+ }
+ };
+});
+var hc = {};
+Dt(hc, { OnnxruntimeWebAssemblyBackend: () => ln, initializeFlags: () => fc, wasmBackend: () => _g });
+var fc;
+var ln;
+var _g;
+var gc = U(() => {
+ "use strict";
+ We();
+ Po();
+ mc();
+ fc = () => {
+ (typeof ge.wasm.initTimeout != "number" || ge.wasm.initTimeout < 0) && (ge.wasm.initTimeout = 0);
+ let e = ge.wasm.simd;
+ if (typeof e != "boolean" && e !== void 0 && e !== "fixed" && e !== "relaxed" && (console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`), ge.wasm.simd = false), typeof ge.wasm.proxy != "boolean" && (ge.wasm.proxy = false), typeof ge.wasm.trace != "boolean" && (ge.wasm.trace = false), typeof ge.wasm.numThreads != "number" || !Number.isInteger(ge.wasm.numThreads) || ge.wasm.numThreads <= 0) if (typeof self < "u" && !self.crossOriginIsolated) ge.wasm.numThreads = 1;
+ else {
+ let t = typeof navigator > "u" ? On("node:os").cpus().length : navigator.hardwareConcurrency;
+ ge.wasm.numThreads = Math.min(4, Math.ceil((t || 1) / 2));
+ }
+ }, ln = class {
+ async init(t) {
+ fc(), await ic(), await ac(t);
+ }
+ async createInferenceSessionHandler(t, r) {
+ let n = new dn();
+ return await n.loadModel(t, r), n;
+ }
+ }, _g = new ln();
+});
+We();
+We();
+We();
+var _a = "1.22.0-dev.20250409-89f8206ba4";
+var IS = Nn;
+{
+ let e = (gc(), Ft(hc)).wasmBackend;
+ $t("webgpu", e, 5), $t("webnn", e, 5), $t("cpu", e, 10), $t("wasm", e, 10);
+}
+Object.defineProperty(ge.versions, "web", { value: _a, enumerable: true });
+
+// node_modules/@huggingface/transformers/dist/transformers.web.js
+var __webpack_modules__ = {
+ /***/
+ "onnxruntime-common": (
+ /*!*************************************!*\
+ !*** external "onnxruntime-common" ***!
+ \*************************************/
+ /***/
+ ((module) => {
+ module.exports = esm_exports;
+ })
+ ),
+ /***/
+ "onnxruntime-web": (
+ /*!**********************************!*\
+ !*** external "onnxruntime-web" ***!
+ \**********************************/
+ /***/
+ ((module) => {
+ module.exports = ort_bundle_min_exports;
+ })
+ ),
+ /***/
+ "?2ce3": (
+ /*!**********************************!*\
+ !*** onnxruntime-node (ignored) ***!
+ \**********************************/
+ /***/
+ (() => {
+ })
+ ),
+ /***/
+ "?7992": (
+ /*!*************************!*\
+ !*** node:fs (ignored) ***!
+ \*************************/
+ /***/
+ (() => {
+ })
+ ),
+ /***/
+ "?5af5": (
+ /*!***************************!*\
+ !*** node:path (ignored) ***!
+ \***************************/
+ /***/
+ (() => {
+ })
+ ),
+ /***/
+ "?2b25": (
+ /*!***********************!*\
+ !*** sharp (ignored) ***!
+ \***********************/
+ /***/
+ (() => {
+ })
+ ),
+ /***/
+ "?db59": (
+ /*!*************************!*\
+ !*** node:fs (ignored) ***!
+ \*************************/
+ /***/
+ (() => {
+ })
+ ),
+ /***/
+ "?383f": (
+ /*!***************************!*\
+ !*** node:path (ignored) ***!
+ \***************************/
+ /***/
+ (() => {
+ })
+ ),
+ /***/
+ "?fa4b": (
+ /*!**************************!*\
+ !*** node:url (ignored) ***!
+ \**************************/
+ /***/
+ (() => {
+ })
+ ),
+ /***/
+ "./node_modules/@huggingface/jinja/dist/index.js": (
+ /*!*******************************************************!*\
+ !*** ./node_modules/@huggingface/jinja/dist/index.js ***!
+ \*******************************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ Environment: () => (
+ /* binding */
+ Environment
+ ),
+ /* harmony export */
+ Interpreter: () => (
+ /* binding */
+ Interpreter
+ ),
+ /* harmony export */
+ Template: () => (
+ /* binding */
+ Template
+ ),
+ /* harmony export */
+ parse: () => (
+ /* binding */
+ parse
+ ),
+ /* harmony export */
+ tokenize: () => (
+ /* binding */
+ tokenize
+ )
+ /* harmony export */
+ });
+ var TOKEN_TYPES = Object.freeze({
+ Text: "Text",
+ // The text between Jinja statements or expressions
+ NumericLiteral: "NumericLiteral",
+ // e.g., 123, 1.0
+ StringLiteral: "StringLiteral",
+ // 'string'
+ Identifier: "Identifier",
+ // Variables, functions, statements, booleans, etc.
+ 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",
+ // ! - +
+ Comment: "Comment"
+ // {# ... #}
+ });
+ var Token = class {
+ /**
+ * Constructs a new Token.
+ * @param {string} value The raw value as seen inside the source code.
+ * @param {TokenType} type The type of token.
+ */
+ constructor(value, type) {
+ this.value = value;
+ this.type = type;
+ }
+ };
+ function isWord(char) {
+ return /\w/.test(char);
+ }
+ function isInteger(char) {
+ return /[0-9]/.test(char);
+ }
+ function isWhitespace(char) {
+ return /\s/.test(char);
+ }
+ var ORDERED_MAPPING_TABLE = [
+ // Control sequences
+ ["{%", TOKEN_TYPES.OpenStatement],
+ ["%}", TOKEN_TYPES.CloseStatement],
+ ["{{", TOKEN_TYPES.OpenExpression],
+ ["}}", TOKEN_TYPES.CloseExpression],
+ // Single character tokens
+ ["(", TOKEN_TYPES.OpenParen],
+ [")", TOKEN_TYPES.CloseParen],
+ ["{", TOKEN_TYPES.OpenCurlyBracket],
+ ["}", TOKEN_TYPES.CloseCurlyBracket],
+ ["[", TOKEN_TYPES.OpenSquareBracket],
+ ["]", TOKEN_TYPES.CloseSquareBracket],
+ [",", TOKEN_TYPES.Comma],
+ [".", TOKEN_TYPES.Dot],
+ [":", TOKEN_TYPES.Colon],
+ ["|", TOKEN_TYPES.Pipe],
+ // Comparison operators
+ ["<=", TOKEN_TYPES.ComparisonBinaryOperator],
+ [">=", TOKEN_TYPES.ComparisonBinaryOperator],
+ ["==", TOKEN_TYPES.ComparisonBinaryOperator],
+ ["!=", TOKEN_TYPES.ComparisonBinaryOperator],
+ ["<", TOKEN_TYPES.ComparisonBinaryOperator],
+ [">", TOKEN_TYPES.ComparisonBinaryOperator],
+ // Arithmetic operators
+ ["+", TOKEN_TYPES.AdditiveBinaryOperator],
+ ["-", TOKEN_TYPES.AdditiveBinaryOperator],
+ ["~", TOKEN_TYPES.AdditiveBinaryOperator],
+ ["*", TOKEN_TYPES.MultiplicativeBinaryOperator],
+ ["/", TOKEN_TYPES.MultiplicativeBinaryOperator],
+ ["%", TOKEN_TYPES.MultiplicativeBinaryOperator],
+ // Assignment operator
+ ["=", TOKEN_TYPES.Equals]
+ ];
+ var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([
+ ["n", "\n"],
+ // New line
+ ["t", " "],
+ // Horizontal tab
+ ["r", "\r"],
+ // Carriage return
+ ["b", "\b"],
+ // Backspace
+ ["f", "\f"],
+ // Form feed
+ ["v", "\v"],
+ // Vertical tab
+ ["'", "'"],
+ // Single quote
+ ['"', '"'],
+ // Double quote
+ ["\\", "\\"]
+ // Backslash
+ ]);
+ function preprocess(template, options = {}) {
+ if (template.endsWith("\n")) {
+ template = template.slice(0, -1);
+ }
+ if (options.lstrip_blocks) {
+ template = template.replace(/^[ \t]*({[#%-])/gm, "$1");
+ }
+ if (options.trim_blocks) {
+ template = template.replace(/([#%-]})\n/g, "$1");
+ }
+ return template.replace(/{%\s*(end)?generation\s*%}/gs, "");
+ }
+ function tokenize(source, options = {}) {
+ const tokens = [];
+ const src = preprocess(source, options);
+ let cursorPosition = 0;
+ let curlyBracketDepth = 0;
+ const consumeWhile = (predicate) => {
+ let str = "";
+ while (predicate(src[cursorPosition])) {
+ if (src[cursorPosition] === "\\") {
+ ++cursorPosition;
+ if (cursorPosition >= src.length)
+ throw new SyntaxError("Unexpected end of input");
+ const escaped = src[cursorPosition++];
+ const unescaped = ESCAPE_CHARACTERS.get(escaped);
+ if (unescaped === void 0) {
+ throw new SyntaxError(`Unexpected escaped character: ${escaped}`);
+ }
+ str += unescaped;
+ continue;
+ }
+ str += src[cursorPosition++];
+ if (cursorPosition >= src.length)
+ throw new SyntaxError("Unexpected end of input");
+ }
+ return str;
+ };
+ const stripTrailingWhitespace = () => {
+ const lastToken = tokens.at(-1);
+ if (lastToken && lastToken.type === TOKEN_TYPES.Text) {
+ lastToken.value = lastToken.value.trimEnd();
+ if (lastToken.value === "") {
+ tokens.pop();
+ }
+ }
+ };
+ const skipLeadingWhitespace = () => {
+ while (cursorPosition < src.length && isWhitespace(src[cursorPosition])) {
+ ++cursorPosition;
+ }
+ };
+ main:
+ while (cursorPosition < src.length) {
+ const lastTokenType = tokens.at(-1)?.type;
+ if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression || lastTokenType === TOKEN_TYPES.Comment) {
+ let text = "";
+ while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression
+ !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{" || src[cursorPosition + 1] === "#"))) {
+ text += src[cursorPosition++];
+ }
+ if (text.length > 0) {
+ tokens.push(new Token(text, TOKEN_TYPES.Text));
+ continue;
+ }
+ }
+ if (src[cursorPosition] === "{" && src[cursorPosition + 1] === "#") {
+ cursorPosition += 2;
+ const stripBefore = src[cursorPosition] === "-";
+ if (stripBefore) {
+ ++cursorPosition;
+ }
+ let comment = "";
+ while (src[cursorPosition] !== "#" || src[cursorPosition + 1] !== "}") {
+ if (cursorPosition + 2 >= src.length) {
+ throw new SyntaxError("Missing end of comment tag");
+ }
+ comment += src[cursorPosition++];
+ }
+ const stripAfter = comment.endsWith("-");
+ if (stripAfter) {
+ comment = comment.slice(0, -1);
+ }
+ if (stripBefore) {
+ stripTrailingWhitespace();
+ }
+ tokens.push(new Token(comment, TOKEN_TYPES.Comment));
+ cursorPosition += 2;
+ if (stripAfter) {
+ skipLeadingWhitespace();
+ }
+ continue;
+ }
+ if (src.slice(cursorPosition, cursorPosition + 3) === "{%-") {
+ stripTrailingWhitespace();
+ tokens.push(new Token("{%", TOKEN_TYPES.OpenStatement));
+ cursorPosition += 3;
+ continue;
+ }
+ if (src.slice(cursorPosition, cursorPosition + 3) === "{{-") {
+ stripTrailingWhitespace();
+ tokens.push(new Token("{{", TOKEN_TYPES.OpenExpression));
+ curlyBracketDepth = 0;
+ cursorPosition += 3;
+ continue;
+ }
+ consumeWhile(isWhitespace);
+ if (src.slice(cursorPosition, cursorPosition + 3) === "-%}") {
+ tokens.push(new Token("%}", TOKEN_TYPES.CloseStatement));
+ cursorPosition += 3;
+ skipLeadingWhitespace();
+ continue;
+ }
+ if (src.slice(cursorPosition, cursorPosition + 3) === "-}}") {
+ tokens.push(new Token("}}", TOKEN_TYPES.CloseExpression));
+ cursorPosition += 3;
+ skipLeadingWhitespace();
+ continue;
+ }
+ const char = src[cursorPosition];
+ if (char === "-" || char === "+") {
+ const lastTokenType2 = tokens.at(-1)?.type;
+ if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) {
+ throw new SyntaxError(`Unexpected character: ${char}`);
+ }
+ switch (lastTokenType2) {
+ case TOKEN_TYPES.Identifier:
+ case TOKEN_TYPES.NumericLiteral:
+ case TOKEN_TYPES.StringLiteral:
+ case TOKEN_TYPES.CloseParen:
+ case TOKEN_TYPES.CloseSquareBracket:
+ break;
+ default: {
+ ++cursorPosition;
+ const num = consumeWhile(isInteger);
+ tokens.push(
+ new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)
+ );
+ continue;
+ }
+ }
+ }
+ for (const [seq, type] of ORDERED_MAPPING_TABLE) {
+ if (seq === "}}" && curlyBracketDepth > 0) {
+ continue;
+ }
+ const slice2 = src.slice(cursorPosition, cursorPosition + seq.length);
+ if (slice2 === seq) {
+ tokens.push(new Token(seq, type));
+ if (type === TOKEN_TYPES.OpenExpression) {
+ curlyBracketDepth = 0;
+ } else if (type === TOKEN_TYPES.OpenCurlyBracket) {
+ ++curlyBracketDepth;
+ } else if (type === TOKEN_TYPES.CloseCurlyBracket) {
+ --curlyBracketDepth;
+ }
+ cursorPosition += seq.length;
+ continue main;
+ }
+ }
+ if (char === "'" || char === '"') {
+ ++cursorPosition;
+ const str = consumeWhile((c) => c !== char);
+ tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));
+ ++cursorPosition;
+ continue;
+ }
+ if (isInteger(char)) {
+ let num = consumeWhile(isInteger);
+ if (src[cursorPosition] === "." && isInteger(src[cursorPosition + 1])) {
+ ++cursorPosition;
+ const frac = consumeWhile(isInteger);
+ num = `${num}.${frac}`;
+ }
+ tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));
+ continue;
+ }
+ if (isWord(char)) {
+ const word = consumeWhile(isWord);
+ tokens.push(new Token(word, TOKEN_TYPES.Identifier));
+ continue;
+ }
+ throw new SyntaxError(`Unexpected character: ${char}`);
+ }
+ return tokens;
+ }
+ var Statement = class {
+ constructor() {
+ __publicField(this, "type", "Statement");
+ }
+ };
+ var Program = class extends Statement {
+ constructor(body) {
+ super();
+ __publicField(this, "type", "Program");
+ this.body = body;
+ }
+ };
+ var If2 = class extends Statement {
+ constructor(test, body, alternate) {
+ super();
+ __publicField(this, "type", "If");
+ this.test = test;
+ this.body = body;
+ this.alternate = alternate;
+ }
+ };
+ var For = class extends Statement {
+ constructor(loopvar, iterable, body, defaultBlock) {
+ super();
+ __publicField(this, "type", "For");
+ this.loopvar = loopvar;
+ this.iterable = iterable;
+ this.body = body;
+ this.defaultBlock = defaultBlock;
+ }
+ };
+ var Break = class extends Statement {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "Break");
+ }
+ };
+ var Continue = class extends Statement {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "Continue");
+ }
+ };
+ var SetStatement = class extends Statement {
+ constructor(assignee, value, body) {
+ super();
+ __publicField(this, "type", "Set");
+ this.assignee = assignee;
+ this.value = value;
+ this.body = body;
+ }
+ };
+ var Macro = class extends Statement {
+ constructor(name, args, body) {
+ super();
+ __publicField(this, "type", "Macro");
+ this.name = name;
+ this.args = args;
+ this.body = body;
+ }
+ };
+ var Comment = class extends Statement {
+ constructor(value) {
+ super();
+ __publicField(this, "type", "Comment");
+ this.value = value;
+ }
+ };
+ var Expression = class extends Statement {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "Expression");
+ }
+ };
+ var MemberExpression = class extends Expression {
+ constructor(object, property, computed) {
+ super();
+ __publicField(this, "type", "MemberExpression");
+ this.object = object;
+ this.property = property;
+ this.computed = computed;
+ }
+ };
+ var CallExpression = class extends Expression {
+ constructor(callee, args) {
+ super();
+ __publicField(this, "type", "CallExpression");
+ this.callee = callee;
+ this.args = args;
+ }
+ };
+ var Identifier = class extends Expression {
+ /**
+ * @param {string} value The name of the identifier
+ */
+ constructor(value) {
+ super();
+ __publicField(this, "type", "Identifier");
+ this.value = value;
+ }
+ };
+ var Literal = class extends Expression {
+ constructor(value) {
+ super();
+ __publicField(this, "type", "Literal");
+ this.value = value;
+ }
+ };
+ var IntegerLiteral = class extends Literal {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "IntegerLiteral");
+ }
+ };
+ var FloatLiteral = class extends Literal {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "FloatLiteral");
+ }
+ };
+ var StringLiteral = class extends Literal {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "StringLiteral");
+ }
+ };
+ var ArrayLiteral = class extends Literal {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "ArrayLiteral");
+ }
+ };
+ var TupleLiteral = class extends Literal {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "TupleLiteral");
+ }
+ };
+ var ObjectLiteral = class extends Literal {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "ObjectLiteral");
+ }
+ };
+ var BinaryExpression = class extends Expression {
+ constructor(operator, left, right) {
+ super();
+ __publicField(this, "type", "BinaryExpression");
+ this.operator = operator;
+ this.left = left;
+ this.right = right;
+ }
+ };
+ var FilterExpression = class extends Expression {
+ constructor(operand, filter) {
+ super();
+ __publicField(this, "type", "FilterExpression");
+ this.operand = operand;
+ this.filter = filter;
+ }
+ };
+ var FilterStatement = class extends Statement {
+ constructor(filter, body) {
+ super();
+ __publicField(this, "type", "FilterStatement");
+ this.filter = filter;
+ this.body = body;
+ }
+ };
+ var SelectExpression = class extends Expression {
+ constructor(lhs, test) {
+ super();
+ __publicField(this, "type", "SelectExpression");
+ this.lhs = lhs;
+ this.test = test;
+ }
+ };
+ var TestExpression = class extends Expression {
+ constructor(operand, negate, test) {
+ super();
+ __publicField(this, "type", "TestExpression");
+ this.operand = operand;
+ this.negate = negate;
+ this.test = test;
+ }
+ };
+ var UnaryExpression = class extends Expression {
+ constructor(operator, argument) {
+ super();
+ __publicField(this, "type", "UnaryExpression");
+ this.operator = operator;
+ this.argument = argument;
+ }
+ };
+ var SliceExpression = class extends Expression {
+ constructor(start = void 0, stop = void 0, step = void 0) {
+ super();
+ __publicField(this, "type", "SliceExpression");
+ this.start = start;
+ this.stop = stop;
+ this.step = step;
+ }
+ };
+ var KeywordArgumentExpression = class extends Expression {
+ constructor(key, value) {
+ super();
+ __publicField(this, "type", "KeywordArgumentExpression");
+ this.key = key;
+ this.value = value;
+ }
+ };
+ var SpreadExpression = class extends Expression {
+ constructor(argument) {
+ super();
+ __publicField(this, "type", "SpreadExpression");
+ this.argument = argument;
+ }
+ };
+ var CallStatement = class extends Statement {
+ constructor(call, callerArgs, body) {
+ super();
+ __publicField(this, "type", "CallStatement");
+ this.call = call;
+ this.callerArgs = callerArgs;
+ this.body = body;
+ }
+ };
+ var Ternary = class extends Expression {
+ constructor(condition, trueExpr, falseExpr) {
+ super();
+ __publicField(this, "type", "Ternary");
+ this.condition = condition;
+ this.trueExpr = trueExpr;
+ this.falseExpr = falseExpr;
+ }
+ };
+ function parse(tokens) {
+ const program = new Program([]);
+ let current = 0;
+ function expect(type, error) {
+ const prev = tokens[current++];
+ if (!prev || prev.type !== type) {
+ throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);
+ }
+ return prev;
+ }
+ function expectIdentifier(name) {
+ if (!isIdentifier(name)) {
+ throw new SyntaxError(`Expected ${name}`);
+ }
+ ++current;
+ }
+ function parseAny() {
+ switch (tokens[current].type) {
+ case TOKEN_TYPES.Comment:
+ return new Comment(tokens[current++].value);
+ case TOKEN_TYPES.Text:
+ return parseText();
+ case TOKEN_TYPES.OpenStatement:
+ return parseJinjaStatement();
+ case TOKEN_TYPES.OpenExpression:
+ return parseJinjaExpression();
+ default:
+ throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);
+ }
+ }
+ function is2(...types) {
+ return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);
+ }
+ function isStatement(...names) {
+ return tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.Identifier && names.includes(tokens[current + 1]?.value);
+ }
+ function isIdentifier(...names) {
+ return current + names.length <= tokens.length && names.every((name, i) => tokens[current + i].type === "Identifier" && name === tokens[current + i].value);
+ }
+ function parseText() {
+ return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value);
+ }
+ function parseJinjaStatement() {
+ expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token");
+ if (tokens[current].type !== TOKEN_TYPES.Identifier) {
+ throw new SyntaxError(`Unknown statement, got ${tokens[current].type}`);
+ }
+ const name = tokens[current].value;
+ let result;
+ switch (name) {
+ case "set":
+ ++current;
+ result = parseSetStatement();
+ break;
+ case "if":
+ ++current;
+ result = parseIfStatement();
+ expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
+ expectIdentifier("endif");
+ expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
+ break;
+ case "macro":
+ ++current;
+ result = parseMacroStatement();
+ expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
+ expectIdentifier("endmacro");
+ expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
+ break;
+ case "for":
+ ++current;
+ result = parseForStatement();
+ expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
+ expectIdentifier("endfor");
+ expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
+ break;
+ case "call": {
+ ++current;
+ let callerArgs = null;
+ if (is2(TOKEN_TYPES.OpenParen)) {
+ callerArgs = parseArgs();
+ }
+ const callee = parsePrimaryExpression();
+ if (callee.type !== "Identifier") {
+ throw new SyntaxError(`Expected identifier following call statement`);
+ }
+ const callArgs = parseArgs();
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ const body = [];
+ while (!isStatement("endcall")) {
+ body.push(parseAny());
+ }
+ expect(TOKEN_TYPES.OpenStatement, "Expected '{%'");
+ expectIdentifier("endcall");
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ const callExpr = new CallExpression(callee, callArgs);
+ result = new CallStatement(callExpr, callerArgs, body);
+ break;
+ }
+ case "break":
+ ++current;
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ result = new Break();
+ break;
+ case "continue":
+ ++current;
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ result = new Continue();
+ break;
+ case "filter": {
+ ++current;
+ let filterNode = parsePrimaryExpression();
+ if (filterNode instanceof Identifier && is2(TOKEN_TYPES.OpenParen)) {
+ filterNode = parseCallExpression(filterNode);
+ }
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ const filterBody = [];
+ while (!isStatement("endfilter")) {
+ filterBody.push(parseAny());
+ }
+ expect(TOKEN_TYPES.OpenStatement, "Expected '{%'");
+ expectIdentifier("endfilter");
+ expect(TOKEN_TYPES.CloseStatement, "Expected '%}'");
+ result = new FilterStatement(filterNode, filterBody);
+ break;
+ }
+ default:
+ throw new SyntaxError(`Unknown statement type: ${name}`);
+ }
+ return result;
+ }
+ function parseJinjaExpression() {
+ expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token");
+ const result = parseExpression();
+ expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token");
+ return result;
+ }
+ function parseSetStatement() {
+ const left = parseExpressionSequence();
+ let value = null;
+ const body = [];
+ if (is2(TOKEN_TYPES.Equals)) {
+ ++current;
+ value = parseExpressionSequence();
+ } else {
+ expect(TOKEN_TYPES.CloseStatement, "Expected %} token");
+ while (!isStatement("endset")) {
+ body.push(parseAny());
+ }
+ expect(TOKEN_TYPES.OpenStatement, "Expected {% token");
+ expectIdentifier("endset");
+ }
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ return new SetStatement(left, value, body);
+ }
+ function parseIfStatement() {
+ const test = parseExpression();
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ const body = [];
+ const alternate = [];
+ while (!isStatement("elif", "else", "endif")) {
+ body.push(parseAny());
+ }
+ if (isStatement("elif")) {
+ ++current;
+ ++current;
+ const result = parseIfStatement();
+ alternate.push(result);
+ } else if (isStatement("else")) {
+ ++current;
+ ++current;
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ while (!isStatement("endif")) {
+ alternate.push(parseAny());
+ }
+ }
+ return new If2(test, body, alternate);
+ }
+ function parseMacroStatement() {
+ const name = parsePrimaryExpression();
+ if (name.type !== "Identifier") {
+ throw new SyntaxError(`Expected identifier following macro statement`);
+ }
+ const args = parseArgs();
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ const body = [];
+ while (!isStatement("endmacro")) {
+ body.push(parseAny());
+ }
+ return new Macro(name, args, body);
+ }
+ function parseExpressionSequence(primary = false) {
+ const fn = primary ? parsePrimaryExpression : parseExpression;
+ const expressions = [fn()];
+ const isTuple = is2(TOKEN_TYPES.Comma);
+ while (isTuple) {
+ ++current;
+ expressions.push(fn());
+ if (!is2(TOKEN_TYPES.Comma)) {
+ break;
+ }
+ }
+ return isTuple ? new TupleLiteral(expressions) : expressions[0];
+ }
+ function parseForStatement() {
+ const loopVariable = parseExpressionSequence(true);
+ if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) {
+ throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);
+ }
+ if (!isIdentifier("in")) {
+ throw new SyntaxError("Expected `in` keyword following loop variable");
+ }
+ ++current;
+ const iterable = parseExpression();
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ const body = [];
+ while (!isStatement("endfor", "else")) {
+ body.push(parseAny());
+ }
+ const alternative = [];
+ if (isStatement("else")) {
+ ++current;
+ ++current;
+ expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token");
+ while (!isStatement("endfor")) {
+ alternative.push(parseAny());
+ }
+ }
+ return new For(loopVariable, iterable, body, alternative);
+ }
+ function parseExpression() {
+ return parseIfExpression();
+ }
+ function parseIfExpression() {
+ const a = parseLogicalOrExpression();
+ if (isIdentifier("if")) {
+ ++current;
+ const test = parseLogicalOrExpression();
+ if (isIdentifier("else")) {
+ ++current;
+ const falseExpr = parseIfExpression();
+ return new Ternary(test, a, falseExpr);
+ } else {
+ return new SelectExpression(a, test);
+ }
+ }
+ return a;
+ }
+ function parseLogicalOrExpression() {
+ let left = parseLogicalAndExpression();
+ while (isIdentifier("or")) {
+ const operator = tokens[current];
+ ++current;
+ const right = parseLogicalAndExpression();
+ left = new BinaryExpression(operator, left, right);
+ }
+ return left;
+ }
+ function parseLogicalAndExpression() {
+ let left = parseLogicalNegationExpression();
+ while (isIdentifier("and")) {
+ const operator = tokens[current];
+ ++current;
+ const right = parseLogicalNegationExpression();
+ left = new BinaryExpression(operator, left, right);
+ }
+ return left;
+ }
+ function parseLogicalNegationExpression() {
+ let right;
+ while (isIdentifier("not")) {
+ const operator = tokens[current];
+ ++current;
+ const arg = parseLogicalNegationExpression();
+ right = new UnaryExpression(operator, arg);
+ }
+ return right ?? parseComparisonExpression();
+ }
+ function parseComparisonExpression() {
+ let left = parseAdditiveExpression();
+ while (true) {
+ let operator;
+ if (isIdentifier("not", "in")) {
+ operator = new Token("not in", TOKEN_TYPES.Identifier);
+ current += 2;
+ } else if (isIdentifier("in")) {
+ operator = tokens[current++];
+ } else if (is2(TOKEN_TYPES.ComparisonBinaryOperator)) {
+ operator = tokens[current++];
+ } else {
+ break;
+ }
+ const right = parseAdditiveExpression();
+ left = new BinaryExpression(operator, left, right);
+ }
+ return left;
+ }
+ function parseAdditiveExpression() {
+ let left = parseMultiplicativeExpression();
+ while (is2(TOKEN_TYPES.AdditiveBinaryOperator)) {
+ const operator = tokens[current];
+ ++current;
+ const right = parseMultiplicativeExpression();
+ left = new BinaryExpression(operator, left, right);
+ }
+ return left;
+ }
+ function parseCallMemberExpression() {
+ const member = parseMemberExpression(parsePrimaryExpression());
+ if (is2(TOKEN_TYPES.OpenParen)) {
+ return parseCallExpression(member);
+ }
+ return member;
+ }
+ function parseCallExpression(callee) {
+ let expression = new CallExpression(callee, parseArgs());
+ expression = parseMemberExpression(expression);
+ if (is2(TOKEN_TYPES.OpenParen)) {
+ expression = parseCallExpression(expression);
+ }
+ return expression;
+ }
+ function parseArgs() {
+ expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list");
+ const args = parseArgumentsList();
+ expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list");
+ return args;
+ }
+ function parseArgumentsList() {
+ const args = [];
+ while (!is2(TOKEN_TYPES.CloseParen)) {
+ let argument;
+ if (tokens[current].type === TOKEN_TYPES.MultiplicativeBinaryOperator && tokens[current].value === "*") {
+ ++current;
+ const expr = parseExpression();
+ argument = new SpreadExpression(expr);
+ } else {
+ argument = parseExpression();
+ if (is2(TOKEN_TYPES.Equals)) {
+ ++current;
+ if (!(argument instanceof Identifier)) {
+ throw new SyntaxError(`Expected identifier for keyword argument`);
+ }
+ const value = parseExpression();
+ argument = new KeywordArgumentExpression(argument, value);
+ }
+ }
+ args.push(argument);
+ if (is2(TOKEN_TYPES.Comma)) {
+ ++current;
+ }
+ }
+ return args;
+ }
+ function parseMemberExpressionArgumentsList() {
+ const slices = [];
+ let isSlice = false;
+ while (!is2(TOKEN_TYPES.CloseSquareBracket)) {
+ if (is2(TOKEN_TYPES.Colon)) {
+ slices.push(void 0);
+ ++current;
+ isSlice = true;
+ } else {
+ slices.push(parseExpression());
+ if (is2(TOKEN_TYPES.Colon)) {
+ ++current;
+ isSlice = true;
+ }
+ }
+ }
+ if (slices.length === 0) {
+ throw new SyntaxError(`Expected at least one argument for member/slice expression`);
+ }
+ if (isSlice) {
+ if (slices.length > 3) {
+ throw new SyntaxError(`Expected 0-3 arguments for slice expression`);
+ }
+ return new SliceExpression(...slices);
+ }
+ return slices[0];
+ }
+ function parseMemberExpression(object) {
+ while (is2(TOKEN_TYPES.Dot) || is2(TOKEN_TYPES.OpenSquareBracket)) {
+ const operator = tokens[current];
+ ++current;
+ let property;
+ const computed = operator.type === TOKEN_TYPES.OpenSquareBracket;
+ if (computed) {
+ property = parseMemberExpressionArgumentsList();
+ expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket");
+ } else {
+ property = parsePrimaryExpression();
+ if (property.type !== "Identifier") {
+ throw new SyntaxError(`Expected identifier following dot operator`);
+ }
+ }
+ object = new MemberExpression(object, property, computed);
+ }
+ return object;
+ }
+ function parseMultiplicativeExpression() {
+ let left = parseTestExpression();
+ while (is2(TOKEN_TYPES.MultiplicativeBinaryOperator)) {
+ const operator = tokens[current++];
+ const right = parseTestExpression();
+ left = new BinaryExpression(operator, left, right);
+ }
+ return left;
+ }
+ function parseTestExpression() {
+ let operand = parseFilterExpression();
+ while (isIdentifier("is")) {
+ ++current;
+ const negate = isIdentifier("not");
+ if (negate) {
+ ++current;
+ }
+ const filter = parsePrimaryExpression();
+ if (!(filter instanceof Identifier)) {
+ throw new SyntaxError(`Expected identifier for the test`);
+ }
+ operand = new TestExpression(operand, negate, filter);
+ }
+ return operand;
+ }
+ function parseFilterExpression() {
+ let operand = parseCallMemberExpression();
+ while (is2(TOKEN_TYPES.Pipe)) {
+ ++current;
+ let filter = parsePrimaryExpression();
+ if (!(filter instanceof Identifier)) {
+ throw new SyntaxError(`Expected identifier for the filter`);
+ }
+ if (is2(TOKEN_TYPES.OpenParen)) {
+ filter = parseCallExpression(filter);
+ }
+ operand = new FilterExpression(operand, filter);
+ }
+ return operand;
+ }
+ function parsePrimaryExpression() {
+ const token = tokens[current++];
+ switch (token.type) {
+ case TOKEN_TYPES.NumericLiteral: {
+ const num = token.value;
+ return num.includes(".") ? new FloatLiteral(Number(num)) : new IntegerLiteral(Number(num));
+ }
+ case TOKEN_TYPES.StringLiteral: {
+ let value = token.value;
+ while (is2(TOKEN_TYPES.StringLiteral)) {
+ value += tokens[current++].value;
+ }
+ return new StringLiteral(value);
+ }
+ case TOKEN_TYPES.Identifier:
+ return new Identifier(token.value);
+ case TOKEN_TYPES.OpenParen: {
+ const expression = parseExpressionSequence();
+ expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis, got ${tokens[current].type} instead.");
+ return expression;
+ }
+ case TOKEN_TYPES.OpenSquareBracket: {
+ const values = [];
+ while (!is2(TOKEN_TYPES.CloseSquareBracket)) {
+ values.push(parseExpression());
+ if (is2(TOKEN_TYPES.Comma)) {
+ ++current;
+ }
+ }
+ ++current;
+ return new ArrayLiteral(values);
+ }
+ case TOKEN_TYPES.OpenCurlyBracket: {
+ const values = /* @__PURE__ */ new Map();
+ while (!is2(TOKEN_TYPES.CloseCurlyBracket)) {
+ const key = parseExpression();
+ expect(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal");
+ const value = parseExpression();
+ values.set(key, value);
+ if (is2(TOKEN_TYPES.Comma)) {
+ ++current;
+ }
+ }
+ ++current;
+ return new ObjectLiteral(values);
+ }
+ default:
+ throw new SyntaxError(`Unexpected token: ${token.type}`);
+ }
+ }
+ while (current < tokens.length) {
+ program.body.push(parseAny());
+ }
+ return program;
+ }
+ function range(start, stop, step = 1) {
+ if (stop === void 0) {
+ stop = start;
+ start = 0;
+ }
+ const result = [];
+ for (let i = start; i < stop; i += step) {
+ result.push(i);
+ }
+ return result;
+ }
+ function slice(array, start, stop, step = 1) {
+ const direction = Math.sign(step);
+ if (direction >= 0) {
+ start = (start ?? (start = 0)) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);
+ stop = (stop ?? (stop = array.length)) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);
+ } else {
+ start = (start ?? (start = array.length - 1)) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);
+ stop = (stop ?? (stop = -1)) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);
+ }
+ const result = [];
+ for (let i = start; direction * i < direction * stop; i += step) {
+ result.push(array[i]);
+ }
+ return result;
+ }
+ function titleCase(value) {
+ return value.replace(/\b\w/g, (c) => c.toUpperCase());
+ }
+ function strftime_now(format2) {
+ return strftime(/* @__PURE__ */ new Date(), format2);
+ }
+ function strftime(date, format2) {
+ const monthFormatterLong = new Intl.DateTimeFormat(void 0, { month: "long" });
+ const monthFormatterShort = new Intl.DateTimeFormat(void 0, { month: "short" });
+ const pad2 = (n) => n < 10 ? "0" + n : n.toString();
+ return format2.replace(/%[YmdbBHM%]/g, (token) => {
+ switch (token) {
+ case "%Y":
+ return date.getFullYear().toString();
+ case "%m":
+ return pad2(date.getMonth() + 1);
+ case "%d":
+ return pad2(date.getDate());
+ case "%b":
+ return monthFormatterShort.format(date);
+ case "%B":
+ return monthFormatterLong.format(date);
+ case "%H":
+ return pad2(date.getHours());
+ case "%M":
+ return pad2(date.getMinutes());
+ case "%%":
+ return "%";
+ default:
+ return token;
+ }
+ });
+ }
+ function escapeRegExp(s) {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ }
+ function replace(str, oldvalue, newvalue, count) {
+ if (count === 0)
+ return str;
+ let remaining = count == null || count < 0 ? Infinity : count;
+ const pattern = oldvalue.length === 0 ? new RegExp("(?=)", "gu") : new RegExp(escapeRegExp(oldvalue), "gu");
+ return str.replaceAll(pattern, (match) => {
+ if (remaining > 0) {
+ --remaining;
+ return newvalue;
+ }
+ return match;
+ });
+ }
+ var BreakControl = class extends Error {
+ };
+ var ContinueControl = class extends Error {
+ };
+ var RuntimeValue = class {
+ /**
+ * Creates a new RuntimeValue.
+ */
+ constructor(value = void 0) {
+ __publicField(this, "type", "RuntimeValue");
+ __publicField(this, "value");
+ /**
+ * A collection of built-in functions for this type.
+ */
+ __publicField(this, "builtins", /* @__PURE__ */ new Map());
+ this.value = value;
+ }
+ /**
+ * Determines truthiness or falsiness of the runtime value.
+ * This function should be overridden by subclasses if it has custom truthiness criteria.
+ * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.
+ */
+ __bool__() {
+ return new BooleanValue(!!this.value);
+ }
+ toString() {
+ return String(this.value);
+ }
+ };
+ var IntegerValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "IntegerValue");
+ }
+ };
+ var FloatValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "FloatValue");
+ }
+ toString() {
+ return this.value % 1 === 0 ? this.value.toFixed(1) : this.value.toString();
+ }
+ };
+ var StringValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "StringValue");
+ __publicField(this, "builtins", /* @__PURE__ */ new Map([
+ [
+ "upper",
+ new FunctionValue(() => {
+ return new StringValue(this.value.toUpperCase());
+ })
+ ],
+ [
+ "lower",
+ new FunctionValue(() => {
+ return new StringValue(this.value.toLowerCase());
+ })
+ ],
+ [
+ "strip",
+ new FunctionValue(() => {
+ return new StringValue(this.value.trim());
+ })
+ ],
+ [
+ "title",
+ new FunctionValue(() => {
+ return new StringValue(titleCase(this.value));
+ })
+ ],
+ [
+ "capitalize",
+ new FunctionValue(() => {
+ return new StringValue(this.value.charAt(0).toUpperCase() + this.value.slice(1));
+ })
+ ],
+ ["length", new IntegerValue(this.value.length)],
+ [
+ "rstrip",
+ new FunctionValue(() => {
+ return new StringValue(this.value.trimEnd());
+ })
+ ],
+ [
+ "lstrip",
+ new FunctionValue(() => {
+ return new StringValue(this.value.trimStart());
+ })
+ ],
+ [
+ "startswith",
+ new FunctionValue((args) => {
+ if (args.length === 0) {
+ throw new Error("startswith() requires at least one argument");
+ }
+ const pattern = args[0];
+ if (pattern instanceof StringValue) {
+ return new BooleanValue(this.value.startsWith(pattern.value));
+ } else if (pattern instanceof ArrayValue) {
+ for (const item of pattern.value) {
+ if (!(item instanceof StringValue)) {
+ throw new Error("startswith() tuple elements must be strings");
+ }
+ if (this.value.startsWith(item.value)) {
+ return new BooleanValue(true);
+ }
+ }
+ return new BooleanValue(false);
+ }
+ throw new Error("startswith() argument must be a string or tuple of strings");
+ })
+ ],
+ [
+ "endswith",
+ new FunctionValue((args) => {
+ if (args.length === 0) {
+ throw new Error("endswith() requires at least one argument");
+ }
+ const pattern = args[0];
+ if (pattern instanceof StringValue) {
+ return new BooleanValue(this.value.endsWith(pattern.value));
+ } else if (pattern instanceof ArrayValue) {
+ for (const item of pattern.value) {
+ if (!(item instanceof StringValue)) {
+ throw new Error("endswith() tuple elements must be strings");
+ }
+ if (this.value.endsWith(item.value)) {
+ return new BooleanValue(true);
+ }
+ }
+ return new BooleanValue(false);
+ }
+ throw new Error("endswith() argument must be a string or tuple of strings");
+ })
+ ],
+ [
+ "split",
+ // follows Python's `str.split(sep=None, maxsplit=-1)` function behavior
+ // https://docs.python.org/3.13/library/stdtypes.html#str.split
+ new FunctionValue((args) => {
+ const sep = args[0] ?? new NullValue();
+ if (!(sep instanceof StringValue || sep instanceof NullValue)) {
+ throw new Error("sep argument must be a string or null");
+ }
+ const maxsplit = args[1] ?? new IntegerValue(-1);
+ if (!(maxsplit instanceof IntegerValue)) {
+ throw new Error("maxsplit argument must be a number");
+ }
+ let result = [];
+ if (sep instanceof NullValue) {
+ const text = this.value.trimStart();
+ for (const { 0: match, index } of text.matchAll(/\S+/g)) {
+ if (maxsplit.value !== -1 && result.length >= maxsplit.value && index !== void 0) {
+ result.push(match + text.slice(index + match.length));
+ break;
+ }
+ result.push(match);
+ }
+ } else {
+ if (sep.value === "") {
+ throw new Error("empty separator");
+ }
+ result = this.value.split(sep.value);
+ if (maxsplit.value !== -1 && result.length > maxsplit.value) {
+ result.push(result.splice(maxsplit.value).join(sep.value));
+ }
+ }
+ return new ArrayValue(result.map((part) => new StringValue(part)));
+ })
+ ],
+ [
+ "replace",
+ new FunctionValue((args) => {
+ if (args.length < 2) {
+ throw new Error("replace() requires at least two arguments");
+ }
+ const oldValue = args[0];
+ const newValue = args[1];
+ if (!(oldValue instanceof StringValue && newValue instanceof StringValue)) {
+ throw new Error("replace() arguments must be strings");
+ }
+ let count;
+ if (args.length > 2) {
+ if (args[2].type === "KeywordArgumentsValue") {
+ count = args[2].value.get("count") ?? new NullValue();
+ } else {
+ count = args[2];
+ }
+ } else {
+ count = new NullValue();
+ }
+ if (!(count instanceof IntegerValue || count instanceof NullValue)) {
+ throw new Error("replace() count argument must be a number or null");
+ }
+ return new StringValue(replace(this.value, oldValue.value, newValue.value, count.value));
+ })
+ ]
+ ]));
+ }
+ };
+ var BooleanValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "BooleanValue");
+ }
+ };
+ function toJSON(input, indent, depth, convertUndefinedToNull = true) {
+ const currentDepth = depth ?? 0;
+ switch (input.type) {
+ case "NullValue":
+ return "null";
+ case "UndefinedValue":
+ return convertUndefinedToNull ? "null" : "undefined";
+ case "IntegerValue":
+ case "FloatValue":
+ case "StringValue":
+ case "BooleanValue":
+ return JSON.stringify(input.value);
+ case "ArrayValue":
+ case "ObjectValue": {
+ const indentValue = indent ? " ".repeat(indent) : "";
+ const basePadding = "\n" + indentValue.repeat(currentDepth);
+ const childrenPadding = basePadding + indentValue;
+ if (input.type === "ArrayValue") {
+ const core = input.value.map(
+ (x) => toJSON(x, indent, currentDepth + 1, convertUndefinedToNull)
+ );
+ return indent ? `[${childrenPadding}${core.join(`,${childrenPadding}`)}${basePadding}]` : `[${core.join(", ")}]`;
+ } else {
+ const core = Array.from(input.value.entries()).map(([key, value]) => {
+ const v = `"${key}": ${toJSON(value, indent, currentDepth + 1, convertUndefinedToNull)}`;
+ return indent ? `${childrenPadding}${v}` : v;
+ });
+ return indent ? `{${core.join(",")}${basePadding}}` : `{${core.join(", ")}}`;
+ }
+ }
+ default:
+ throw new Error(`Cannot convert to JSON: ${input.type}`);
+ }
+ }
+ var ObjectValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "ObjectValue");
+ __publicField(this, "builtins", /* @__PURE__ */ new Map([
+ [
+ "get",
+ new FunctionValue(([key, defaultValue]) => {
+ if (!(key instanceof StringValue)) {
+ throw new Error(`Object key must be a string: got ${key.type}`);
+ }
+ return this.value.get(key.value) ?? defaultValue ?? new NullValue();
+ })
+ ],
+ ["items", new FunctionValue(() => this.items())],
+ ["keys", new FunctionValue(() => this.keys())],
+ ["values", new FunctionValue(() => this.values())],
+ [
+ "dictsort",
+ new FunctionValue((args) => {
+ let kwargs = /* @__PURE__ */ new Map();
+ const positionalArgs = args.filter((arg) => {
+ if (arg instanceof KeywordArgumentsValue) {
+ kwargs = arg.value;
+ return false;
+ }
+ return true;
+ });
+ const caseSensitive = positionalArgs.at(0) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false);
+ if (!(caseSensitive instanceof BooleanValue)) {
+ throw new Error("case_sensitive must be a boolean");
+ }
+ const by = positionalArgs.at(1) ?? kwargs.get("by") ?? new StringValue("key");
+ if (!(by instanceof StringValue)) {
+ throw new Error("by must be a string");
+ }
+ if (!["key", "value"].includes(by.value)) {
+ throw new Error("by must be either 'key' or 'value'");
+ }
+ const reverse = positionalArgs.at(2) ?? kwargs.get("reverse") ?? new BooleanValue(false);
+ if (!(reverse instanceof BooleanValue)) {
+ throw new Error("reverse must be a boolean");
+ }
+ const items = Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])).sort((a, b) => {
+ const index = by.value === "key" ? 0 : 1;
+ const aVal = a.value[index];
+ const bVal = b.value[index];
+ const result = compareRuntimeValues(aVal, bVal, caseSensitive.value);
+ return reverse.value ? -result : result;
+ });
+ return new ArrayValue(items);
+ })
+ ]
+ ]));
+ }
+ /**
+ * NOTE: necessary to override since all JavaScript arrays are considered truthy,
+ * while only non-empty Python arrays are consider truthy.
+ *
+ * e.g.,
+ * - JavaScript: {} && 5 -> 5
+ * - Python: {} and 5 -> {}
+ */
+ __bool__() {
+ return new BooleanValue(this.value.size > 0);
+ }
+ items() {
+ return new ArrayValue(
+ Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))
+ );
+ }
+ keys() {
+ return new ArrayValue(Array.from(this.value.keys()).map((key) => new StringValue(key)));
+ }
+ values() {
+ return new ArrayValue(Array.from(this.value.values()));
+ }
+ toString() {
+ return toJSON(this, null, 0, false);
+ }
+ };
+ var KeywordArgumentsValue = class extends ObjectValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "KeywordArgumentsValue");
+ }
+ };
+ var ArrayValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "ArrayValue");
+ __publicField(this, "builtins", /* @__PURE__ */ new Map([["length", new IntegerValue(this.value.length)]]));
+ }
+ /**
+ * NOTE: necessary to override since all JavaScript arrays are considered truthy,
+ * while only non-empty Python arrays are consider truthy.
+ *
+ * e.g.,
+ * - JavaScript: [] && 5 -> 5
+ * - Python: [] and 5 -> []
+ */
+ __bool__() {
+ return new BooleanValue(this.value.length > 0);
+ }
+ toString() {
+ return toJSON(this, null, 0, false);
+ }
+ };
+ var TupleValue = class extends ArrayValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "TupleValue");
+ }
+ };
+ var FunctionValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "FunctionValue");
+ }
+ };
+ var NullValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "NullValue");
+ }
+ };
+ var UndefinedValue = class extends RuntimeValue {
+ constructor() {
+ super(...arguments);
+ __publicField(this, "type", "UndefinedValue");
+ }
+ };
+ var Environment = class {
+ constructor(parent) {
+ /**
+ * The variables declared in this environment.
+ */
+ __publicField(this, "variables", /* @__PURE__ */ new Map([
+ [
+ "namespace",
+ new FunctionValue((args) => {
+ if (args.length === 0) {
+ return new ObjectValue(/* @__PURE__ */ new Map());
+ }
+ if (args.length !== 1 || !(args[0] instanceof ObjectValue)) {
+ throw new Error("`namespace` expects either zero arguments or a single object argument");
+ }
+ return args[0];
+ })
+ ]
+ ]));
+ /**
+ * The tests available in this environment.
+ */
+ __publicField(this, "tests", /* @__PURE__ */ new Map([
+ ["boolean", (operand) => operand.type === "BooleanValue"],
+ ["callable", (operand) => operand instanceof FunctionValue],
+ [
+ "odd",
+ (operand) => {
+ if (!(operand instanceof IntegerValue)) {
+ throw new Error(`cannot odd on ${operand.type}`);
+ }
+ return operand.value % 2 !== 0;
+ }
+ ],
+ [
+ "even",
+ (operand) => {
+ if (!(operand instanceof IntegerValue)) {
+ throw new Error(`cannot even on ${operand.type}`);
+ }
+ return operand.value % 2 === 0;
+ }
+ ],
+ ["false", (operand) => operand.type === "BooleanValue" && !operand.value],
+ ["true", (operand) => operand.type === "BooleanValue" && operand.value],
+ ["none", (operand) => operand.type === "NullValue"],
+ ["string", (operand) => operand.type === "StringValue"],
+ ["number", (operand) => operand instanceof IntegerValue || operand instanceof FloatValue],
+ ["integer", (operand) => operand instanceof IntegerValue],
+ ["iterable", (operand) => operand.type === "ArrayValue" || operand.type === "StringValue"],
+ ["mapping", (operand) => operand.type === "ObjectValue"],
+ [
+ "lower",
+ (operand) => {
+ const str = operand.value;
+ return operand.type === "StringValue" && str === str.toLowerCase();
+ }
+ ],
+ [
+ "upper",
+ (operand) => {
+ const str = operand.value;
+ return operand.type === "StringValue" && str === str.toUpperCase();
+ }
+ ],
+ ["none", (operand) => operand.type === "NullValue"],
+ ["defined", (operand) => operand.type !== "UndefinedValue"],
+ ["undefined", (operand) => operand.type === "UndefinedValue"],
+ ["equalto", (a, b) => a.value === b.value],
+ ["eq", (a, b) => a.value === b.value]
+ ]));
+ this.parent = parent;
+ }
+ /**
+ * Set the value of a variable in the current environment.
+ */
+ set(name, value) {
+ return this.declareVariable(name, convertToRuntimeValues(value));
+ }
+ declareVariable(name, value) {
+ if (this.variables.has(name)) {
+ throw new SyntaxError(`Variable already declared: ${name}`);
+ }
+ this.variables.set(name, value);
+ return value;
+ }
+ // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {
+ // const env = this.resolve(name);
+ // env.variables.set(name, value);
+ // return value;
+ // }
+ /**
+ * Set variable in the current scope.
+ * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.
+ */
+ setVariable(name, value) {
+ this.variables.set(name, value);
+ return value;
+ }
+ /**
+ * Resolve the environment in which the variable is declared.
+ * @param {string} name The name of the variable.
+ * @returns {Environment} The environment in which the variable is declared.
+ */
+ resolve(name) {
+ if (this.variables.has(name)) {
+ return this;
+ }
+ if (this.parent) {
+ return this.parent.resolve(name);
+ }
+ throw new Error(`Unknown variable: ${name}`);
+ }
+ lookupVariable(name) {
+ try {
+ return this.resolve(name).variables.get(name) ?? new UndefinedValue();
+ } catch {
+ return new UndefinedValue();
+ }
+ }
+ };
+ function setupGlobals(env3) {
+ env3.set("false", false);
+ env3.set("true", true);
+ env3.set("none", null);
+ env3.set("raise_exception", (args) => {
+ throw new Error(args);
+ });
+ env3.set("range", range);
+ env3.set("strftime_now", strftime_now);
+ env3.set("True", true);
+ env3.set("False", false);
+ env3.set("None", null);
+ }
+ function getAttributeValue(item, attributePath) {
+ const parts = attributePath.split(".");
+ let value = item;
+ for (const part of parts) {
+ if (value instanceof ObjectValue) {
+ value = value.value.get(part) ?? new UndefinedValue();
+ } else if (value instanceof ArrayValue) {
+ const index = parseInt(part, 10);
+ if (!isNaN(index) && index >= 0 && index < value.value.length) {
+ value = value.value[index];
+ } else {
+ return new UndefinedValue();
+ }
+ } else {
+ return new UndefinedValue();
+ }
+ }
+ return value;
+ }
+ function compareRuntimeValues(a, b, caseSensitive = false) {
+ if (a instanceof NullValue && b instanceof NullValue) {
+ return 0;
+ }
+ if (a instanceof NullValue || b instanceof NullValue) {
+ throw new Error(`Cannot compare ${a.type} with ${b.type}`);
+ }
+ if (a instanceof UndefinedValue && b instanceof UndefinedValue) {
+ return 0;
+ }
+ if (a instanceof UndefinedValue || b instanceof UndefinedValue) {
+ throw new Error(`Cannot compare ${a.type} with ${b.type}`);
+ }
+ const isNumericLike = (v) => v instanceof IntegerValue || v instanceof FloatValue || v instanceof BooleanValue;
+ const getNumericValue = (v) => {
+ if (v instanceof BooleanValue) {
+ return v.value ? 1 : 0;
+ }
+ return v.value;
+ };
+ if (isNumericLike(a) && isNumericLike(b)) {
+ const aNum = getNumericValue(a);
+ const bNum = getNumericValue(b);
+ return aNum < bNum ? -1 : aNum > bNum ? 1 : 0;
+ }
+ if (a.type !== b.type) {
+ throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);
+ }
+ switch (a.type) {
+ case "StringValue": {
+ let aStr = a.value;
+ let bStr = b.value;
+ if (!caseSensitive) {
+ aStr = aStr.toLowerCase();
+ bStr = bStr.toLowerCase();
+ }
+ return aStr < bStr ? -1 : aStr > bStr ? 1 : 0;
+ }
+ default:
+ throw new Error(`Cannot compare type: ${a.type}`);
+ }
+ }
+ var Interpreter = class {
+ constructor(env3) {
+ __publicField(this, "global");
+ this.global = env3 ?? new Environment();
+ }
+ /**
+ * Run the program.
+ */
+ run(program) {
+ return this.evaluate(program, this.global);
+ }
+ /**
+ * Evaluates expressions following the binary operation type.
+ */
+ evaluateBinaryExpression(node, environment) {
+ const left = this.evaluate(node.left, environment);
+ switch (node.operator.value) {
+ case "and":
+ return left.__bool__().value ? this.evaluate(node.right, environment) : left;
+ case "or":
+ return left.__bool__().value ? left : this.evaluate(node.right, environment);
+ }
+ const right = this.evaluate(node.right, environment);
+ switch (node.operator.value) {
+ case "==":
+ return new BooleanValue(left.value == right.value);
+ case "!=":
+ return new BooleanValue(left.value != right.value);
+ }
+ if (left instanceof UndefinedValue || right instanceof UndefinedValue) {
+ if (right instanceof UndefinedValue && ["in", "not in"].includes(node.operator.value)) {
+ return new BooleanValue(node.operator.value === "not in");
+ }
+ throw new Error(`Cannot perform operation ${node.operator.value} on undefined values`);
+ } else if (left instanceof NullValue || right instanceof NullValue) {
+ throw new Error("Cannot perform operation on null values");
+ } else if (node.operator.value === "~") {
+ return new StringValue(left.value.toString() + right.value.toString());
+ } else if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue)) {
+ const a = left.value, b = right.value;
+ switch (node.operator.value) {
+ case "+":
+ case "-":
+ case "*": {
+ const res = node.operator.value === "+" ? a + b : node.operator.value === "-" ? a - b : a * b;
+ const isFloat = left instanceof FloatValue || right instanceof FloatValue;
+ return isFloat ? new FloatValue(res) : new IntegerValue(res);
+ }
+ case "/":
+ return new FloatValue(a / b);
+ case "%": {
+ const rem = a % b;
+ const isFloat = left instanceof FloatValue || right instanceof FloatValue;
+ return isFloat ? new FloatValue(rem) : new IntegerValue(rem);
+ }
+ case "<":
+ return new BooleanValue(a < b);
+ case ">":
+ return new BooleanValue(a > b);
+ case ">=":
+ return new BooleanValue(a >= b);
+ case "<=":
+ return new BooleanValue(a <= b);
+ }
+ } else if (left instanceof ArrayValue && right instanceof ArrayValue) {
+ switch (node.operator.value) {
+ case "+":
+ return new ArrayValue(left.value.concat(right.value));
+ }
+ } else if (right instanceof ArrayValue) {
+ const member = right.value.find((x) => x.value === left.value) !== void 0;
+ switch (node.operator.value) {
+ case "in":
+ return new BooleanValue(member);
+ case "not in":
+ return new BooleanValue(!member);
+ }
+ }
+ if (left instanceof StringValue || right instanceof StringValue) {
+ switch (node.operator.value) {
+ case "+":
+ return new StringValue(left.value.toString() + right.value.toString());
+ }
+ }
+ if (left instanceof StringValue && right instanceof StringValue) {
+ switch (node.operator.value) {
+ case "in":
+ return new BooleanValue(right.value.includes(left.value));
+ case "not in":
+ return new BooleanValue(!right.value.includes(left.value));
+ }
+ }
+ if (left instanceof StringValue && right instanceof ObjectValue) {
+ switch (node.operator.value) {
+ case "in":
+ return new BooleanValue(right.value.has(left.value));
+ case "not in":
+ return new BooleanValue(!right.value.has(left.value));
+ }
+ }
+ throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`);
+ }
+ evaluateArguments(args, environment) {
+ const positionalArguments = [];
+ const keywordArguments = /* @__PURE__ */ new Map();
+ for (const argument of args) {
+ if (argument.type === "SpreadExpression") {
+ const spreadNode = argument;
+ const val = this.evaluate(spreadNode.argument, environment);
+ if (!(val instanceof ArrayValue)) {
+ throw new Error(`Cannot unpack non-iterable type: ${val.type}`);
+ }
+ for (const item of val.value) {
+ positionalArguments.push(item);
+ }
+ } else if (argument.type === "KeywordArgumentExpression") {
+ const kwarg = argument;
+ keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));
+ } else {
+ if (keywordArguments.size > 0) {
+ throw new Error("Positional arguments must come before keyword arguments");
+ }
+ positionalArguments.push(this.evaluate(argument, environment));
+ }
+ }
+ return [positionalArguments, keywordArguments];
+ }
+ applyFilter(operand, filterNode, environment) {
+ if (filterNode.type === "Identifier") {
+ const filter = filterNode;
+ if (filter.value === "tojson") {
+ return new StringValue(toJSON(operand));
+ }
+ if (operand instanceof ArrayValue) {
+ switch (filter.value) {
+ case "list":
+ return operand;
+ case "first":
+ return operand.value[0];
+ case "last":
+ return operand.value[operand.value.length - 1];
+ case "length":
+ return new IntegerValue(operand.value.length);
+ case "reverse":
+ return new ArrayValue(operand.value.slice().reverse());
+ case "sort": {
+ return new ArrayValue(operand.value.slice().sort((a, b) => compareRuntimeValues(a, b, false)));
+ }
+ case "join":
+ return new StringValue(operand.value.map((x) => x.value).join(""));
+ case "string":
+ return new StringValue(toJSON(operand, null, 0, false));
+ case "unique": {
+ const seen = /* @__PURE__ */ new Set();
+ const output = [];
+ for (const item of operand.value) {
+ if (!seen.has(item.value)) {
+ seen.add(item.value);
+ output.push(item);
+ }
+ }
+ return new ArrayValue(output);
+ }
+ default:
+ throw new Error(`Unknown ArrayValue filter: ${filter.value}`);
+ }
+ } else if (operand instanceof StringValue) {
+ switch (filter.value) {
+ case "length":
+ case "upper":
+ case "lower":
+ case "title":
+ case "capitalize": {
+ const builtin = operand.builtins.get(filter.value);
+ if (builtin instanceof FunctionValue) {
+ return builtin.value(
+ /* no arguments */
+ [],
+ environment
+ );
+ } else if (builtin instanceof IntegerValue) {
+ return builtin;
+ } else {
+ throw new Error(`Unknown StringValue filter: ${filter.value}`);
+ }
+ }
+ case "trim":
+ return new StringValue(operand.value.trim());
+ case "indent":
+ return new StringValue(
+ operand.value.split("\n").map(
+ (x, i) => (
+ // By default, don't indent the first line or empty lines
+ i === 0 || x.length === 0 ? x : " " + x
+ )
+ ).join("\n")
+ );
+ case "join":
+ case "string":
+ return operand;
+ case "int": {
+ const val = parseInt(operand.value, 10);
+ return new IntegerValue(isNaN(val) ? 0 : val);
+ }
+ case "float": {
+ const val = parseFloat(operand.value);
+ return new FloatValue(isNaN(val) ? 0 : val);
+ }
+ default:
+ throw new Error(`Unknown StringValue filter: ${filter.value}`);
+ }
+ } else if (operand instanceof IntegerValue || operand instanceof FloatValue) {
+ switch (filter.value) {
+ case "abs":
+ return operand instanceof IntegerValue ? new IntegerValue(Math.abs(operand.value)) : new FloatValue(Math.abs(operand.value));
+ case "int":
+ return new IntegerValue(Math.floor(operand.value));
+ case "float":
+ return new FloatValue(operand.value);
+ default:
+ throw new Error(`Unknown NumericValue filter: ${filter.value}`);
+ }
+ } else if (operand instanceof ObjectValue) {
+ switch (filter.value) {
+ case "items":
+ return new ArrayValue(
+ Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))
+ );
+ case "length":
+ return new IntegerValue(operand.value.size);
+ default: {
+ const builtin = operand.builtins.get(filter.value);
+ if (builtin) {
+ if (builtin instanceof FunctionValue) {
+ return builtin.value([], environment);
+ }
+ return builtin;
+ }
+ throw new Error(`Unknown ObjectValue filter: ${filter.value}`);
+ }
+ }
+ } else if (operand instanceof BooleanValue) {
+ switch (filter.value) {
+ case "bool":
+ return new BooleanValue(operand.value);
+ case "int":
+ return new IntegerValue(operand.value ? 1 : 0);
+ case "float":
+ return new FloatValue(operand.value ? 1 : 0);
+ case "string":
+ return new StringValue(operand.value ? "true" : "false");
+ default:
+ throw new Error(`Unknown BooleanValue filter: ${filter.value}`);
+ }
+ }
+ throw new Error(`Cannot apply filter "${filter.value}" to type: ${operand.type}`);
+ } else if (filterNode.type === "CallExpression") {
+ const filter = filterNode;
+ if (filter.callee.type !== "Identifier") {
+ throw new Error(`Unknown filter: ${filter.callee.type}`);
+ }
+ const filterName = filter.callee.value;
+ if (filterName === "tojson") {
+ const [, kwargs] = this.evaluateArguments(filter.args, environment);
+ const indent = kwargs.get("indent") ?? new NullValue();
+ if (!(indent instanceof IntegerValue || indent instanceof NullValue)) {
+ throw new Error("If set, indent must be a number");
+ }
+ return new StringValue(toJSON(operand, indent.value));
+ } else if (filterName === "join") {
+ let value;
+ if (operand instanceof StringValue) {
+ value = Array.from(operand.value);
+ } else if (operand instanceof ArrayValue) {
+ value = operand.value.map((x) => x.value);
+ } else {
+ throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
+ }
+ const [args, kwargs] = this.evaluateArguments(filter.args, environment);
+ const separator = args.at(0) ?? kwargs.get("separator") ?? new StringValue("");
+ if (!(separator instanceof StringValue)) {
+ throw new Error("separator must be a string");
+ }
+ return new StringValue(value.join(separator.value));
+ } else if (filterName === "int" || filterName === "float") {
+ const [args, kwargs] = this.evaluateArguments(filter.args, environment);
+ const defaultValue = args.at(0) ?? kwargs.get("default") ?? (filterName === "int" ? new IntegerValue(0) : new FloatValue(0));
+ if (operand instanceof StringValue) {
+ const val = filterName === "int" ? parseInt(operand.value, 10) : parseFloat(operand.value);
+ return isNaN(val) ? defaultValue : filterName === "int" ? new IntegerValue(val) : new FloatValue(val);
+ } else if (operand instanceof IntegerValue || operand instanceof FloatValue) {
+ return operand;
+ } else if (operand instanceof BooleanValue) {
+ return filterName === "int" ? new IntegerValue(operand.value ? 1 : 0) : new FloatValue(operand.value ? 1 : 0);
+ } else {
+ throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
+ }
+ } else if (filterName === "default") {
+ const [args, kwargs] = this.evaluateArguments(filter.args, environment);
+ const defaultValue = args[0] ?? new StringValue("");
+ const booleanValue = args[1] ?? kwargs.get("boolean") ?? new BooleanValue(false);
+ if (!(booleanValue instanceof BooleanValue)) {
+ throw new Error("`default` filter flag must be a boolean");
+ }
+ if (operand instanceof UndefinedValue || booleanValue.value && !operand.__bool__().value) {
+ return defaultValue;
+ }
+ return operand;
+ }
+ if (operand instanceof ArrayValue) {
+ switch (filterName) {
+ case "sort": {
+ const [args, kwargs] = this.evaluateArguments(filter.args, environment);
+ const reverse = args.at(0) ?? kwargs.get("reverse") ?? new BooleanValue(false);
+ if (!(reverse instanceof BooleanValue)) {
+ throw new Error("reverse must be a boolean");
+ }
+ const caseSensitive = args.at(1) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false);
+ if (!(caseSensitive instanceof BooleanValue)) {
+ throw new Error("case_sensitive must be a boolean");
+ }
+ const attribute = args.at(2) ?? kwargs.get("attribute") ?? new NullValue();
+ if (!(attribute instanceof StringValue || attribute instanceof IntegerValue || attribute instanceof NullValue)) {
+ throw new Error("attribute must be a string, integer, or null");
+ }
+ const getSortValue = (item) => {
+ if (attribute instanceof NullValue) {
+ return item;
+ }
+ const attrPath = attribute instanceof IntegerValue ? String(attribute.value) : attribute.value;
+ return getAttributeValue(item, attrPath);
+ };
+ return new ArrayValue(
+ operand.value.slice().sort((a, b) => {
+ const aVal = getSortValue(a);
+ const bVal = getSortValue(b);
+ const result = compareRuntimeValues(aVal, bVal, caseSensitive.value);
+ return reverse.value ? -result : result;
+ })
+ );
+ }
+ case "selectattr":
+ case "rejectattr": {
+ const select = filterName === "selectattr";
+ if (operand.value.some((x) => !(x instanceof ObjectValue))) {
+ throw new Error(`\`${filterName}\` can only be applied to array of objects`);
+ }
+ if (filter.args.some((x) => x.type !== "StringLiteral")) {
+ throw new Error(`arguments of \`${filterName}\` must be strings`);
+ }
+ const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));
+ let testFunction;
+ if (testName) {
+ const test = environment.tests.get(testName.value);
+ if (!test) {
+ throw new Error(`Unknown test: ${testName.value}`);
+ }
+ testFunction = test;
+ } else {
+ testFunction = (...x) => x[0].__bool__().value;
+ }
+ const filtered = operand.value.filter((item) => {
+ const a = item.value.get(attr.value);
+ const result = a ? testFunction(a, value) : false;
+ return select ? result : !result;
+ });
+ return new ArrayValue(filtered);
+ }
+ case "map": {
+ const [, kwargs] = this.evaluateArguments(filter.args, environment);
+ if (kwargs.has("attribute")) {
+ const attr = kwargs.get("attribute");
+ if (!(attr instanceof StringValue)) {
+ throw new Error("attribute must be a string");
+ }
+ const defaultValue = kwargs.get("default");
+ const mapped = operand.value.map((item) => {
+ if (!(item instanceof ObjectValue)) {
+ throw new Error("items in map must be an object");
+ }
+ const value = getAttributeValue(item, attr.value);
+ return value instanceof UndefinedValue ? defaultValue ?? new UndefinedValue() : value;
+ });
+ return new ArrayValue(mapped);
+ } else {
+ throw new Error("`map` expressions without `attribute` set are not currently supported.");
+ }
+ }
+ }
+ throw new Error(`Unknown ArrayValue filter: ${filterName}`);
+ } else if (operand instanceof StringValue) {
+ switch (filterName) {
+ case "indent": {
+ const [args, kwargs] = this.evaluateArguments(filter.args, environment);
+ const width = args.at(0) ?? kwargs.get("width") ?? new IntegerValue(4);
+ if (!(width instanceof IntegerValue)) {
+ throw new Error("width must be a number");
+ }
+ const first = args.at(1) ?? kwargs.get("first") ?? new BooleanValue(false);
+ const blank = args.at(2) ?? kwargs.get("blank") ?? new BooleanValue(false);
+ const lines = operand.value.split("\n");
+ const indent = " ".repeat(width.value);
+ const indented = lines.map(
+ (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x
+ );
+ return new StringValue(indented.join("\n"));
+ }
+ case "replace": {
+ const replaceFn = operand.builtins.get("replace");
+ if (!(replaceFn instanceof FunctionValue)) {
+ throw new Error("replace filter not available");
+ }
+ const [args, kwargs] = this.evaluateArguments(filter.args, environment);
+ return replaceFn.value([...args, new KeywordArgumentsValue(kwargs)], environment);
+ }
+ }
+ throw new Error(`Unknown StringValue filter: ${filterName}`);
+ } else if (operand instanceof ObjectValue) {
+ const builtin = operand.builtins.get(filterName);
+ if (builtin && builtin instanceof FunctionValue) {
+ const [args, kwargs] = this.evaluateArguments(filter.args, environment);
+ if (kwargs.size > 0) {
+ args.push(new KeywordArgumentsValue(kwargs));
+ }
+ return builtin.value(args, environment);
+ }
+ throw new Error(`Unknown ObjectValue filter: ${filterName}`);
+ } else {
+ throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`);
+ }
+ }
+ throw new Error(`Unknown filter: ${filterNode.type}`);
+ }
+ /**
+ * Evaluates expressions following the filter operation type.
+ */
+ evaluateFilterExpression(node, environment) {
+ const operand = this.evaluate(node.operand, environment);
+ return this.applyFilter(operand, node.filter, environment);
+ }
+ /**
+ * Evaluates expressions following the test operation type.
+ */
+ evaluateTestExpression(node, environment) {
+ const operand = this.evaluate(node.operand, environment);
+ const test = environment.tests.get(node.test.value);
+ if (!test) {
+ throw new Error(`Unknown test: ${node.test.value}`);
+ }
+ const result = test(operand);
+ return new BooleanValue(node.negate ? !result : result);
+ }
+ /**
+ * Evaluates expressions following the select operation type.
+ */
+ evaluateSelectExpression(node, environment) {
+ const predicate = this.evaluate(node.test, environment);
+ if (!predicate.__bool__().value) {
+ return new UndefinedValue();
+ }
+ return this.evaluate(node.lhs, environment);
+ }
+ /**
+ * Evaluates expressions following the unary operation type.
+ */
+ evaluateUnaryExpression(node, environment) {
+ const argument = this.evaluate(node.argument, environment);
+ switch (node.operator.value) {
+ case "not":
+ return new BooleanValue(!argument.value);
+ default:
+ throw new SyntaxError(`Unknown operator: ${node.operator.value}`);
+ }
+ }
+ evaluateTernaryExpression(node, environment) {
+ const cond = this.evaluate(node.condition, environment);
+ return cond.__bool__().value ? this.evaluate(node.trueExpr, environment) : this.evaluate(node.falseExpr, environment);
+ }
+ evalProgram(program, environment) {
+ return this.evaluateBlock(program.body, environment);
+ }
+ evaluateBlock(statements, environment) {
+ let result = "";
+ for (const statement of statements) {
+ const lastEvaluated = this.evaluate(statement, environment);
+ if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") {
+ result += lastEvaluated.toString();
+ }
+ }
+ return new StringValue(result);
+ }
+ evaluateIdentifier(node, environment) {
+ return environment.lookupVariable(node.value);
+ }
+ evaluateCallExpression(expr, environment) {
+ const [args, kwargs] = this.evaluateArguments(expr.args, environment);
+ if (kwargs.size > 0) {
+ args.push(new KeywordArgumentsValue(kwargs));
+ }
+ const fn = this.evaluate(expr.callee, environment);
+ if (fn.type !== "FunctionValue") {
+ throw new Error(`Cannot call something that is not a function: got ${fn.type}`);
+ }
+ return fn.value(args, environment);
+ }
+ evaluateSliceExpression(object, expr, environment) {
+ if (!(object instanceof ArrayValue || object instanceof StringValue)) {
+ throw new Error("Slice object must be an array or string");
+ }
+ const start = this.evaluate(expr.start, environment);
+ const stop = this.evaluate(expr.stop, environment);
+ const step = this.evaluate(expr.step, environment);
+ if (!(start instanceof IntegerValue || start instanceof UndefinedValue)) {
+ throw new Error("Slice start must be numeric or undefined");
+ }
+ if (!(stop instanceof IntegerValue || stop instanceof UndefinedValue)) {
+ throw new Error("Slice stop must be numeric or undefined");
+ }
+ if (!(step instanceof IntegerValue || step instanceof UndefinedValue)) {
+ throw new Error("Slice step must be numeric or undefined");
+ }
+ if (object instanceof ArrayValue) {
+ return new ArrayValue(slice(object.value, start.value, stop.value, step.value));
+ } else {
+ return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(""));
+ }
+ }
+ evaluateMemberExpression(expr, environment) {
+ const object = this.evaluate(expr.object, environment);
+ let property;
+ if (expr.computed) {
+ if (expr.property.type === "SliceExpression") {
+ return this.evaluateSliceExpression(object, expr.property, environment);
+ } else {
+ property = this.evaluate(expr.property, environment);
+ }
+ } else {
+ property = new StringValue(expr.property.value);
+ }
+ let value;
+ if (object instanceof ObjectValue) {
+ if (!(property instanceof StringValue)) {
+ throw new Error(`Cannot access property with non-string: got ${property.type}`);
+ }
+ value = object.value.get(property.value) ?? object.builtins.get(property.value);
+ } else if (object instanceof ArrayValue || object instanceof StringValue) {
+ if (property instanceof IntegerValue) {
+ value = object.value.at(property.value);
+ if (object instanceof StringValue) {
+ value = new StringValue(object.value.at(property.value));
+ }
+ } else if (property instanceof StringValue) {
+ value = object.builtins.get(property.value);
+ } else {
+ throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);
+ }
+ } else {
+ if (!(property instanceof StringValue)) {
+ throw new Error(`Cannot access property with non-string: got ${property.type}`);
+ }
+ value = object.builtins.get(property.value);
+ }
+ return value instanceof RuntimeValue ? value : new UndefinedValue();
+ }
+ evaluateSet(node, environment) {
+ const rhs = node.value ? this.evaluate(node.value, environment) : this.evaluateBlock(node.body, environment);
+ if (node.assignee.type === "Identifier") {
+ const variableName = node.assignee.value;
+ environment.setVariable(variableName, rhs);
+ } else if (node.assignee.type === "TupleLiteral") {
+ const tuple = node.assignee;
+ if (!(rhs instanceof ArrayValue)) {
+ throw new Error(`Cannot unpack non-iterable type in set: ${rhs.type}`);
+ }
+ const arr = rhs.value;
+ if (arr.length !== tuple.value.length) {
+ throw new Error(`Too ${tuple.value.length > arr.length ? "few" : "many"} items to unpack in set`);
+ }
+ for (let i = 0; i < tuple.value.length; ++i) {
+ const elem = tuple.value[i];
+ if (elem.type !== "Identifier") {
+ throw new Error(`Cannot unpack to non-identifier in set: ${elem.type}`);
+ }
+ environment.setVariable(elem.value, arr[i]);
+ }
+ } else if (node.assignee.type === "MemberExpression") {
+ const member = node.assignee;
+ const object = this.evaluate(member.object, environment);
+ if (!(object instanceof ObjectValue)) {
+ throw new Error("Cannot assign to member of non-object");
+ }
+ if (member.property.type !== "Identifier") {
+ throw new Error("Cannot assign to member with non-identifier property");
+ }
+ object.value.set(member.property.value, rhs);
+ } else {
+ throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);
+ }
+ return new NullValue();
+ }
+ evaluateIf(node, environment) {
+ const test = this.evaluate(node.test, environment);
+ return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);
+ }
+ evaluateFor(node, environment) {
+ const scope = new Environment(environment);
+ let test, iterable;
+ if (node.iterable.type === "SelectExpression") {
+ const select = node.iterable;
+ iterable = this.evaluate(select.lhs, scope);
+ test = select.test;
+ } else {
+ iterable = this.evaluate(node.iterable, scope);
+ }
+ if (!(iterable instanceof ArrayValue || iterable instanceof ObjectValue)) {
+ throw new Error(`Expected iterable or object type in for loop: got ${iterable.type}`);
+ }
+ if (iterable instanceof ObjectValue) {
+ iterable = iterable.keys();
+ }
+ const items = [];
+ const scopeUpdateFunctions = [];
+ for (let i = 0; i < iterable.value.length; ++i) {
+ const loopScope = new Environment(scope);
+ const current = iterable.value[i];
+ let scopeUpdateFunction;
+ if (node.loopvar.type === "Identifier") {
+ scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);
+ } else if (node.loopvar.type === "TupleLiteral") {
+ const loopvar = node.loopvar;
+ if (current.type !== "ArrayValue") {
+ throw new Error(`Cannot unpack non-iterable type: ${current.type}`);
+ }
+ const c = current;
+ if (loopvar.value.length !== c.value.length) {
+ throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`);
+ }
+ scopeUpdateFunction = (scope2) => {
+ for (let j = 0; j < loopvar.value.length; ++j) {
+ if (loopvar.value[j].type !== "Identifier") {
+ throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);
+ }
+ scope2.setVariable(loopvar.value[j].value, c.value[j]);
+ }
+ };
+ } else {
+ throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);
+ }
+ if (test) {
+ scopeUpdateFunction(loopScope);
+ const testValue = this.evaluate(test, loopScope);
+ if (!testValue.__bool__().value) {
+ continue;
+ }
+ }
+ items.push(current);
+ scopeUpdateFunctions.push(scopeUpdateFunction);
+ }
+ let result = "";
+ let noIteration = true;
+ for (let i = 0; i < items.length; ++i) {
+ const loop = /* @__PURE__ */ new Map([
+ ["index", new IntegerValue(i + 1)],
+ ["index0", new IntegerValue(i)],
+ ["revindex", new IntegerValue(items.length - i)],
+ ["revindex0", new IntegerValue(items.length - i - 1)],
+ ["first", new BooleanValue(i === 0)],
+ ["last", new BooleanValue(i === items.length - 1)],
+ ["length", new IntegerValue(items.length)],
+ ["previtem", i > 0 ? items[i - 1] : new UndefinedValue()],
+ ["nextitem", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]
+ ]);
+ scope.setVariable("loop", new ObjectValue(loop));
+ scopeUpdateFunctions[i](scope);
+ try {
+ const evaluated = this.evaluateBlock(node.body, scope);
+ result += evaluated.value;
+ } catch (err) {
+ if (err instanceof ContinueControl) {
+ continue;
+ }
+ if (err instanceof BreakControl) {
+ break;
+ }
+ throw err;
+ }
+ noIteration = false;
+ }
+ if (noIteration) {
+ const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);
+ result += defaultEvaluated.value;
+ }
+ return new StringValue(result);
+ }
+ /**
+ * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.
+ */
+ evaluateMacro(node, environment) {
+ environment.setVariable(
+ node.name.value,
+ new FunctionValue((args, scope) => {
+ const macroScope = new Environment(scope);
+ args = args.slice();
+ let kwargs;
+ if (args.at(-1)?.type === "KeywordArgumentsValue") {
+ kwargs = args.pop();
+ }
+ for (let i = 0; i < node.args.length; ++i) {
+ const nodeArg = node.args[i];
+ const passedArg = args[i];
+ if (nodeArg.type === "Identifier") {
+ const identifier = nodeArg;
+ if (!passedArg) {
+ throw new Error(`Missing positional argument: ${identifier.value}`);
+ }
+ macroScope.setVariable(identifier.value, passedArg);
+ } else if (nodeArg.type === "KeywordArgumentExpression") {
+ const kwarg = nodeArg;
+ const value = passedArg ?? // Try positional arguments first
+ kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs
+ this.evaluate(kwarg.value, macroScope);
+ macroScope.setVariable(kwarg.key.value, value);
+ } else {
+ throw new Error(`Unknown argument type: ${nodeArg.type}`);
+ }
+ }
+ return this.evaluateBlock(node.body, macroScope);
+ })
+ );
+ return new NullValue();
+ }
+ evaluateCallStatement(node, environment) {
+ const callerFn = new FunctionValue((callerArgs, callerEnv) => {
+ const callBlockEnv = new Environment(callerEnv);
+ if (node.callerArgs) {
+ for (let i = 0; i < node.callerArgs.length; ++i) {
+ const param = node.callerArgs[i];
+ if (param.type !== "Identifier") {
+ throw new Error(`Caller parameter must be an identifier, got ${param.type}`);
+ }
+ callBlockEnv.setVariable(param.value, callerArgs[i] ?? new UndefinedValue());
+ }
+ }
+ return this.evaluateBlock(node.body, callBlockEnv);
+ });
+ const [macroArgs, macroKwargs] = this.evaluateArguments(node.call.args, environment);
+ macroArgs.push(new KeywordArgumentsValue(macroKwargs));
+ const fn = this.evaluate(node.call.callee, environment);
+ if (fn.type !== "FunctionValue") {
+ throw new Error(`Cannot call something that is not a function: got ${fn.type}`);
+ }
+ const newEnv = new Environment(environment);
+ newEnv.setVariable("caller", callerFn);
+ return fn.value(macroArgs, newEnv);
+ }
+ evaluateFilterStatement(node, environment) {
+ const rendered = this.evaluateBlock(node.body, environment);
+ return this.applyFilter(rendered, node.filter, environment);
+ }
+ evaluate(statement, environment) {
+ if (!statement)
+ return new UndefinedValue();
+ switch (statement.type) {
+ case "Program":
+ return this.evalProgram(statement, environment);
+ case "Set":
+ return this.evaluateSet(statement, environment);
+ case "If":
+ return this.evaluateIf(statement, environment);
+ case "For":
+ return this.evaluateFor(statement, environment);
+ case "Macro":
+ return this.evaluateMacro(statement, environment);
+ case "CallStatement":
+ return this.evaluateCallStatement(statement, environment);
+ case "Break":
+ throw new BreakControl();
+ case "Continue":
+ throw new ContinueControl();
+ case "IntegerLiteral":
+ return new IntegerValue(statement.value);
+ case "FloatLiteral":
+ return new FloatValue(statement.value);
+ case "StringLiteral":
+ return new StringValue(statement.value);
+ case "ArrayLiteral":
+ return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));
+ case "TupleLiteral":
+ return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));
+ case "ObjectLiteral": {
+ const mapping = /* @__PURE__ */ new Map();
+ for (const [key, value] of statement.value) {
+ const evaluatedKey = this.evaluate(key, environment);
+ if (!(evaluatedKey instanceof StringValue)) {
+ throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);
+ }
+ mapping.set(evaluatedKey.value, this.evaluate(value, environment));
+ }
+ return new ObjectValue(mapping);
+ }
+ case "Identifier":
+ return this.evaluateIdentifier(statement, environment);
+ case "CallExpression":
+ return this.evaluateCallExpression(statement, environment);
+ case "MemberExpression":
+ return this.evaluateMemberExpression(statement, environment);
+ case "UnaryExpression":
+ return this.evaluateUnaryExpression(statement, environment);
+ case "BinaryExpression":
+ return this.evaluateBinaryExpression(statement, environment);
+ case "FilterExpression":
+ return this.evaluateFilterExpression(statement, environment);
+ case "FilterStatement":
+ return this.evaluateFilterStatement(statement, environment);
+ case "TestExpression":
+ return this.evaluateTestExpression(statement, environment);
+ case "SelectExpression":
+ return this.evaluateSelectExpression(statement, environment);
+ case "Ternary":
+ return this.evaluateTernaryExpression(statement, environment);
+ case "Comment":
+ return new NullValue();
+ default:
+ throw new SyntaxError(`Unknown node type: ${statement.type}`);
+ }
+ }
+ };
+ function convertToRuntimeValues(input) {
+ switch (typeof input) {
+ case "number":
+ return Number.isInteger(input) ? new IntegerValue(input) : new FloatValue(input);
+ case "string":
+ return new StringValue(input);
+ case "boolean":
+ return new BooleanValue(input);
+ case "undefined":
+ return new UndefinedValue();
+ case "object":
+ if (input === null) {
+ return new NullValue();
+ } else if (Array.isArray(input)) {
+ return new ArrayValue(input.map(convertToRuntimeValues));
+ } else {
+ return new ObjectValue(
+ new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)]))
+ );
+ }
+ case "function":
+ return new FunctionValue((args, _scope) => {
+ const result = input(...args.map((x) => x.value)) ?? null;
+ return convertToRuntimeValues(result);
+ });
+ default:
+ throw new Error(`Cannot convert to runtime value: ${input}`);
+ }
+ }
+ var NEWLINE = "\n";
+ var OPEN_STATEMENT = "{%- ";
+ var CLOSE_STATEMENT = " -%}";
+ function getBinaryOperatorPrecedence(expr) {
+ switch (expr.operator.type) {
+ case "MultiplicativeBinaryOperator":
+ return 4;
+ case "AdditiveBinaryOperator":
+ return 3;
+ case "ComparisonBinaryOperator":
+ return 2;
+ case "Identifier":
+ if (expr.operator.value === "and")
+ return 1;
+ if (expr.operator.value === "in" || expr.operator.value === "not in")
+ return 2;
+ return 0;
+ }
+ return 0;
+ }
+ function format(program, indent = " ") {
+ const indentStr = typeof indent === "number" ? " ".repeat(indent) : indent;
+ const body = formatStatements(program.body, 0, indentStr);
+ return body.replace(/\n$/, "");
+ }
+ function createStatement(...text) {
+ return OPEN_STATEMENT + text.join(" ") + CLOSE_STATEMENT;
+ }
+ function formatStatements(stmts, depth, indentStr) {
+ return stmts.map((stmt) => formatStatement(stmt, depth, indentStr)).join(NEWLINE);
+ }
+ function formatStatement(node, depth, indentStr) {
+ const pad = indentStr.repeat(depth);
+ switch (node.type) {
+ case "Program":
+ return formatStatements(node.body, depth, indentStr);
+ case "If":
+ return formatIf(node, depth, indentStr);
+ case "For":
+ return formatFor(node, depth, indentStr);
+ case "Set":
+ return formatSet(node, depth, indentStr);
+ case "Macro":
+ return formatMacro(node, depth, indentStr);
+ case "Break":
+ return pad + createStatement("break");
+ case "Continue":
+ return pad + createStatement("continue");
+ case "CallStatement":
+ return formatCallStatement(node, depth, indentStr);
+ case "FilterStatement":
+ return formatFilterStatement(node, depth, indentStr);
+ case "Comment":
+ return pad + "{# " + node.value + " #}";
+ default:
+ return pad + "{{- " + formatExpression(node) + " -}}";
+ }
+ }
+ function formatIf(node, depth, indentStr) {
+ const pad = indentStr.repeat(depth);
+ const clauses = [];
+ let current = node;
+ while (current) {
+ clauses.push({ test: current.test, body: current.body });
+ if (current.alternate.length === 1 && current.alternate[0].type === "If") {
+ current = current.alternate[0];
+ } else {
+ break;
+ }
+ }
+ let out = pad + createStatement("if", formatExpression(clauses[0].test)) + NEWLINE + formatStatements(clauses[0].body, depth + 1, indentStr);
+ for (let i = 1; i < clauses.length; ++i) {
+ out += NEWLINE + pad + createStatement("elif", formatExpression(clauses[i].test)) + NEWLINE + formatStatements(clauses[i].body, depth + 1, indentStr);
+ }
+ if (current && current.alternate.length > 0) {
+ out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(current.alternate, depth + 1, indentStr);
+ }
+ out += NEWLINE + pad + createStatement("endif");
+ return out;
+ }
+ function formatFor(node, depth, indentStr) {
+ const pad = indentStr.repeat(depth);
+ let formattedIterable = "";
+ if (node.iterable.type === "SelectExpression") {
+ const n = node.iterable;
+ formattedIterable = `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`;
+ } else {
+ formattedIterable = formatExpression(node.iterable);
+ }
+ let out = pad + createStatement("for", formatExpression(node.loopvar), "in", formattedIterable) + NEWLINE + formatStatements(node.body, depth + 1, indentStr);
+ if (node.defaultBlock.length > 0) {
+ out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(node.defaultBlock, depth + 1, indentStr);
+ }
+ out += NEWLINE + pad + createStatement("endfor");
+ return out;
+ }
+ function formatSet(node, depth, indentStr) {
+ const pad = indentStr.repeat(depth);
+ const left = formatExpression(node.assignee);
+ const right = node.value ? formatExpression(node.value) : "";
+ const value = pad + createStatement("set", `${left}${node.value ? " = " + right : ""}`);
+ if (node.body.length === 0) {
+ return value;
+ }
+ return value + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endset");
+ }
+ function formatMacro(node, depth, indentStr) {
+ const pad = indentStr.repeat(depth);
+ const args = node.args.map(formatExpression).join(", ");
+ return pad + createStatement("macro", `${node.name.value}(${args})`) + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endmacro");
+ }
+ function formatCallStatement(node, depth, indentStr) {
+ const pad = indentStr.repeat(depth);
+ const params = node.callerArgs && node.callerArgs.length > 0 ? `(${node.callerArgs.map(formatExpression).join(", ")})` : "";
+ const callExpr = formatExpression(node.call);
+ let out = pad + createStatement(`call${params}`, callExpr) + NEWLINE;
+ out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE;
+ out += pad + createStatement("endcall");
+ return out;
+ }
+ function formatFilterStatement(node, depth, indentStr) {
+ const pad = indentStr.repeat(depth);
+ const spec = node.filter.type === "Identifier" ? node.filter.value : formatExpression(node.filter);
+ let out = pad + createStatement("filter", spec) + NEWLINE;
+ out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE;
+ out += pad + createStatement("endfilter");
+ return out;
+ }
+ function formatExpression(node, parentPrec = -1) {
+ switch (node.type) {
+ case "SpreadExpression": {
+ const n = node;
+ return `*${formatExpression(n.argument)}`;
+ }
+ case "Identifier":
+ return node.value;
+ case "IntegerLiteral":
+ return `${node.value}`;
+ case "FloatLiteral":
+ return `${node.value}`;
+ case "StringLiteral":
+ return JSON.stringify(node.value);
+ case "BinaryExpression": {
+ const n = node;
+ const thisPrecedence = getBinaryOperatorPrecedence(n);
+ const left = formatExpression(n.left, thisPrecedence);
+ const right = formatExpression(n.right, thisPrecedence + 1);
+ const expr = `${left} ${n.operator.value} ${right}`;
+ return thisPrecedence < parentPrec ? `(${expr})` : expr;
+ }
+ case "UnaryExpression": {
+ const n = node;
+ const val = n.operator.value + (n.operator.value === "not" ? " " : "") + formatExpression(n.argument, Infinity);
+ return val;
+ }
+ case "CallExpression": {
+ const n = node;
+ const args = n.args.map(formatExpression).join(", ");
+ return `${formatExpression(n.callee)}(${args})`;
+ }
+ case "MemberExpression": {
+ const n = node;
+ let obj = formatExpression(n.object);
+ if (![
+ "Identifier",
+ "MemberExpression",
+ "CallExpression",
+ "StringLiteral",
+ "IntegerLiteral",
+ "FloatLiteral",
+ "ArrayLiteral",
+ "TupleLiteral",
+ "ObjectLiteral"
+ ].includes(n.object.type)) {
+ obj = `(${obj})`;
+ }
+ let prop = formatExpression(n.property);
+ if (!n.computed && n.property.type !== "Identifier") {
+ prop = `(${prop})`;
+ }
+ return n.computed ? `${obj}[${prop}]` : `${obj}.${prop}`;
+ }
+ case "FilterExpression": {
+ const n = node;
+ const operand = formatExpression(n.operand, Infinity);
+ if (n.filter.type === "CallExpression") {
+ return `${operand} | ${formatExpression(n.filter)}`;
+ }
+ return `${operand} | ${n.filter.value}`;
+ }
+ case "SelectExpression": {
+ const n = node;
+ return `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`;
+ }
+ case "TestExpression": {
+ const n = node;
+ return `${formatExpression(n.operand)} is${n.negate ? " not" : ""} ${n.test.value}`;
+ }
+ case "ArrayLiteral":
+ case "TupleLiteral": {
+ const elems = node.value.map(formatExpression);
+ const brackets = node.type === "ArrayLiteral" ? "[]" : "()";
+ return `${brackets[0]}${elems.join(", ")}${brackets[1]}`;
+ }
+ case "ObjectLiteral": {
+ const entries = Array.from(node.value.entries()).map(
+ ([k2, v]) => `${formatExpression(k2)}: ${formatExpression(v)}`
+ );
+ return `{${entries.join(", ")}}`;
+ }
+ case "SliceExpression": {
+ const n = node;
+ const s = n.start ? formatExpression(n.start) : "";
+ const t = n.stop ? formatExpression(n.stop) : "";
+ const st2 = n.step ? `:${formatExpression(n.step)}` : "";
+ return `${s}:${t}${st2}`;
+ }
+ case "KeywordArgumentExpression": {
+ const n = node;
+ return `${n.key.value}=${formatExpression(n.value)}`;
+ }
+ case "Ternary": {
+ const n = node;
+ const expr = `${formatExpression(n.trueExpr)} if ${formatExpression(n.condition, 0)} else ${formatExpression(
+ n.falseExpr
+ )}`;
+ return parentPrec > -1 ? `(${expr})` : expr;
+ }
+ default:
+ throw new Error(`Unknown expression type: ${node.type}`);
+ }
+ }
+ var Template = class {
+ /**
+ * @param {string} template The template string
+ */
+ constructor(template) {
+ __publicField(this, "parsed");
+ const tokens = tokenize(template, {
+ lstrip_blocks: true,
+ trim_blocks: true
+ });
+ this.parsed = parse(tokens);
+ }
+ render(items) {
+ const env3 = new Environment();
+ setupGlobals(env3);
+ if (items) {
+ for (const [key, value] of Object.entries(items)) {
+ env3.set(key, value);
+ }
+ }
+ const interpreter = new Interpreter(env3);
+ const result = interpreter.run(this.parsed);
+ return result.value;
+ }
+ format(options) {
+ return format(this.parsed, options?.indent || " ");
+ }
+ };
+ })
+ ),
+ /***/
+ "./src/backends/onnx.js": (
+ /*!******************************!*\
+ !*** ./src/backends/onnx.js ***!
+ \******************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ var onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache;
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ Tensor: () => (
+ /* reexport safe */
+ onnxruntime_common__WEBPACK_IMPORTED_MODULE_3__.Tensor
+ ),
+ /* harmony export */
+ createInferenceSession: () => (
+ /* binding */
+ createInferenceSession
+ ),
+ /* harmony export */
+ deviceToExecutionProviders: () => (
+ /* binding */
+ deviceToExecutionProviders
+ ),
+ /* harmony export */
+ isONNXProxy: () => (
+ /* binding */
+ isONNXProxy
+ ),
+ /* harmony export */
+ isONNXTensor: () => (
+ /* binding */
+ isONNXTensor
+ ),
+ /* harmony export */
+ runInferenceSession: () => (
+ /* binding */
+ runInferenceSession
+ )
+ /* harmony export */
+ });
+ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../env.js */
+ "./src/env.js"
+ );
+ var onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! onnxruntime-node */
+ "?2ce3"
+ );
+ var onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! onnxruntime-web */
+ "onnxruntime-web"
+ );
+ var onnxruntime_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2(
+ /*! onnxruntime-common */
+ "onnxruntime-common"
+ );
+ const DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({
+ auto: null,
+ // Auto-detect based on device and environment
+ gpu: null,
+ // Auto-detect GPU
+ cpu: "cpu",
+ // CPU
+ wasm: "wasm",
+ // WebAssembly
+ webgpu: "webgpu",
+ // WebGPU
+ cuda: "cuda",
+ // CUDA
+ dml: "dml",
+ // DirectML
+ webnn: { name: "webnn", deviceType: "cpu" },
+ // WebNN (default)
+ "webnn-npu": { name: "webnn", deviceType: "npu" },
+ // WebNN NPU
+ "webnn-gpu": { name: "webnn", deviceType: "gpu" },
+ // WebNN GPU
+ "webnn-cpu": { name: "webnn", deviceType: "cpu" }
+ // WebNN CPU
+ });
+ const supportedDevices = [];
+ let defaultDevices;
+ let ONNX;
+ const ORT_SYMBOL = /* @__PURE__ */ Symbol.for("onnxruntime");
+ if (ORT_SYMBOL in globalThis) {
+ ONNX = globalThis[ORT_SYMBOL];
+ } else if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_NODE_ENV) {
+ ONNX = onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__ ?? (onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache || (onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache = __webpack_require__2.t(onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__, 2)));
+ switch (process.platform) {
+ case "win32":
+ supportedDevices.push("dml");
+ break;
+ case "linux":
+ if (process.arch === "x64") {
+ supportedDevices.push("cuda");
+ }
+ break;
+ case "darwin":
+ break;
+ }
+ supportedDevices.push("cpu");
+ defaultDevices = ["cpu"];
+ } else {
+ ONNX = onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__;
+ if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBNN_AVAILABLE) {
+ supportedDevices.push("webnn-npu", "webnn-gpu", "webnn-cpu", "webnn");
+ }
+ if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBGPU_AVAILABLE) {
+ supportedDevices.push("webgpu");
+ }
+ supportedDevices.push("wasm");
+ defaultDevices = ["wasm"];
+ }
+ const InferenceSession3 = ONNX.InferenceSession;
+ function deviceToExecutionProviders(device = null) {
+ if (!device) return defaultDevices;
+ switch (device) {
+ case "auto":
+ return supportedDevices;
+ case "gpu":
+ return supportedDevices.filter(
+ (x) => ["webgpu", "cuda", "dml", "webnn-gpu"].includes(x)
+ );
+ }
+ if (supportedDevices.includes(device)) {
+ return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device];
+ }
+ throw new Error(`Unsupported device: "${device}". Should be one of: ${supportedDevices.join(", ")}.`);
+ }
+ let wasmInitPromise = null;
+ async function createInferenceSession(buffer_or_path, session_options, session_config) {
+ if (wasmInitPromise) {
+ await wasmInitPromise;
+ }
+ const sessionPromise = InferenceSession3.create(buffer_or_path, session_options);
+ wasmInitPromise ?? (wasmInitPromise = sessionPromise);
+ const session = await sessionPromise;
+ session.config = session_config;
+ return session;
+ }
+ let webInferenceChain = Promise.resolve();
+ const IS_WEB_ENV = _env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_BROWSER_ENV || _env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBWORKER_ENV;
+ async function runInferenceSession(session, ortFeed) {
+ const run = () => session.run(ortFeed);
+ const output = await (IS_WEB_ENV ? webInferenceChain = webInferenceChain.then(run) : run());
+ return output;
+ }
+ function isONNXTensor(x) {
+ return x instanceof ONNX.Tensor;
+ }
+ const ONNX_ENV = ONNX?.env;
+ if (ONNX_ENV?.wasm) {
+ if (
+ // @ts-ignore Cannot find name 'ServiceWorkerGlobalScope'.ts(2304)
+ !(typeof ServiceWorkerGlobalScope !== "undefined" && self instanceof ServiceWorkerGlobalScope) && !ONNX_ENV.wasm.wasmPaths
+ ) {
+ ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${_env_js__WEBPACK_IMPORTED_MODULE_0__.env.version}/dist/`;
+ }
+ ONNX_ENV.wasm.proxy = false;
+ }
+ if (ONNX_ENV?.webgpu) {
+ ONNX_ENV.webgpu.powerPreference = "high-performance";
+ }
+ function isONNXProxy() {
+ return ONNX_ENV?.wasm?.proxy;
+ }
+ _env_js__WEBPACK_IMPORTED_MODULE_0__.env.backends.onnx = ONNX_ENV;
+ })
+ ),
+ /***/
+ "./src/base/feature_extraction_utils.js": (
+ /*!**********************************************!*\
+ !*** ./src/base/feature_extraction_utils.js ***!
+ \**********************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ FeatureExtractor: () => (
+ /* binding */
+ FeatureExtractor
+ ),
+ /* harmony export */
+ validate_audio_inputs: () => (
+ /* binding */
+ validate_audio_inputs
+ )
+ /* harmony export */
+ });
+ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/constants.js */
+ "./src/utils/constants.js"
+ );
+ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ../utils/generic.js */
+ "./src/utils/generic.js"
+ );
+ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! ../utils/hub.js */
+ "./src/utils/hub.js"
+ );
+ class FeatureExtractor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__.Callable {
+ /**
+ * Constructs a new FeatureExtractor instance.
+ *
+ * @param {Object} config The configuration for the feature extractor.
+ */
+ constructor(config) {
+ super();
+ this.config = config;
+ }
+ /**
+ * Instantiate one of the feature extractor classes of the library from a pretrained model.
+ *
+ * The feature extractor class to instantiate is selected based on the `feature_extractor_type` property of
+ * the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
+ *
+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
+ * - A string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co.
+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
+ * user or organization name, like `dbmdz/bert-base-german-cased`.
+ * - A path to a *directory* containing feature_extractor files, e.g., `./my_model_directory/`.
+ * @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the feature_extractor.
+ *
+ * @returns {Promise} A new instance of the Feature Extractor class.
+ */
+ static async from_pretrained(pretrained_model_name_or_path, options = {}) {
+ const config = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.FEATURE_EXTRACTOR_NAME, true, options);
+ return new this(config);
+ }
+ }
+ function validate_audio_inputs(audio, feature_extractor) {
+ if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {
+ throw new Error(
+ `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`
+ );
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/base/image_processors_utils.js": (
+ /*!********************************************!*\
+ !*** ./src/base/image_processors_utils.js ***!
+ \********************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ ImageProcessor: () => (
+ /* binding */
+ ImageProcessor
+ ),
+ /* harmony export */
+ center_to_corners_format: () => (
+ /* binding */
+ center_to_corners_format
+ ),
+ /* harmony export */
+ post_process_instance_segmentation: () => (
+ /* binding */
+ post_process_instance_segmentation
+ ),
+ /* harmony export */
+ post_process_object_detection: () => (
+ /* binding */
+ post_process_object_detection
+ ),
+ /* harmony export */
+ post_process_panoptic_segmentation: () => (
+ /* binding */
+ post_process_panoptic_segmentation
+ ),
+ /* harmony export */
+ post_process_semantic_segmentation: () => (
+ /* binding */
+ post_process_semantic_segmentation
+ )
+ /* harmony export */
+ });
+ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/generic.js */
+ "./src/utils/generic.js"
+ );
+ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ../utils/tensor.js */
+ "./src/utils/tensor.js"
+ );
+ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! ../utils/maths.js */
+ "./src/utils/maths.js"
+ );
+ var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2(
+ /*! ../utils/image.js */
+ "./src/utils/image.js"
+ );
+ var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2(
+ /*! ../utils/core.js */
+ "./src/utils/core.js"
+ );
+ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2(
+ /*! ../utils/hub.js */
+ "./src/utils/hub.js"
+ );
+ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2(
+ /*! ../utils/constants.js */
+ "./src/utils/constants.js"
+ );
+ function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {
+ const a = val / multiple;
+ let x = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.bankers_round)(a) * multiple;
+ if (maxVal !== null && x > maxVal) {
+ x = Math.floor(a) * multiple;
+ }
+ if (x < minVal) {
+ x = Math.ceil(a) * multiple;
+ }
+ return x;
+ }
+ function enforce_size_divisibility([width, height], divisor) {
+ return [
+ Math.max(Math.floor(width / divisor), 1) * divisor,
+ Math.max(Math.floor(height / divisor), 1) * divisor
+ ];
+ }
+ function center_to_corners_format([centerX, centerY, width, height]) {
+ return [
+ centerX - width / 2,
+ centerY - height / 2,
+ centerX + width / 2,
+ centerY + height / 2
+ ];
+ }
+ function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {
+ const out_logits = outputs.logits;
+ const out_bbox = outputs.pred_boxes;
+ const [batch_size, num_boxes, num_classes] = out_logits.dims;
+ if (target_sizes !== null && target_sizes.length !== batch_size) {
+ throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");
+ }
+ let toReturn = [];
+ for (let i = 0; i < batch_size; ++i) {
+ let target_size = target_sizes !== null ? target_sizes[i] : null;
+ let info = {
+ boxes: [],
+ classes: [],
+ scores: []
+ };
+ let logits = out_logits[i];
+ let bbox = out_bbox[i];
+ for (let j = 0; j < num_boxes; ++j) {
+ let logit = logits[j];
+ let indices = [];
+ let probs;
+ if (is_zero_shot) {
+ probs = logit.sigmoid().data;
+ for (let k2 = 0; k2 < probs.length; ++k2) {
+ if (probs[k2] > threshold) {
+ indices.push(k2);
+ }
+ }
+ } else {
+ let maxIndex = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logit.data)[1];
+ if (maxIndex === num_classes - 1) {
+ continue;
+ }
+ probs = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(logit.data);
+ if (probs[maxIndex] < threshold) {
+ continue;
+ }
+ indices.push(maxIndex);
+ }
+ for (const index of indices) {
+ let box = bbox[j].data;
+ box = center_to_corners_format(box);
+ if (target_size !== null) {
+ box = box.map((x, i2) => x * target_size[(i2 + 1) % 2]);
+ }
+ info.boxes.push(box);
+ info.classes.push(index);
+ info.scores.push(probs[index]);
+ }
+ }
+ toReturn.push(info);
+ }
+ return toReturn;
+ }
+ function post_process_semantic_segmentation(outputs, target_sizes = null) {
+ const logits = outputs.logits;
+ const batch_size = logits.dims[0];
+ if (target_sizes !== null && target_sizes.length !== batch_size) {
+ throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");
+ }
+ const toReturn = [];
+ for (let i = 0; i < batch_size; ++i) {
+ const target_size = target_sizes !== null ? target_sizes[i] : null;
+ let data = logits[i];
+ if (target_size !== null) {
+ data = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate)(data, target_size, "bilinear", false);
+ }
+ const [height, width] = target_size ?? data.dims.slice(-2);
+ const segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(
+ "int32",
+ new Int32Array(height * width),
+ [height, width]
+ );
+ const buffer = data[0].data;
+ const segmentation_data = segmentation.data;
+ for (let j = 1; j < data.dims[0]; ++j) {
+ const row = data[j].data;
+ for (let k2 = 0; k2 < row.length; ++k2) {
+ if (row[k2] > buffer[k2]) {
+ buffer[k2] = row[k2];
+ segmentation_data[k2] = j;
+ }
+ }
+ }
+ const hasLabel = new Array(data.dims[0]);
+ for (let j = 0; j < segmentation_data.length; ++j) {
+ const index = segmentation_data[j];
+ hasLabel[index] = index;
+ }
+ const labels = hasLabel.filter((x) => x !== void 0);
+ toReturn.push({ segmentation, labels });
+ }
+ return toReturn;
+ }
+ function remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {
+ const mask_probs_item = [];
+ const pred_scores_item = [];
+ const pred_labels_item = [];
+ for (let j = 0; j < class_logits.dims[0]; ++j) {
+ const cls = class_logits[j];
+ const mask = mask_logits[j];
+ const pred_label = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(cls.data)[1];
+ if (pred_label === num_labels) {
+ continue;
+ }
+ const scores = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(cls.data);
+ const pred_score = scores[pred_label];
+ if (pred_score > object_mask_threshold) {
+ mask_probs_item.push(mask);
+ pred_scores_item.push(pred_score);
+ pred_labels_item.push(pred_label);
+ }
+ }
+ return [mask_probs_item, pred_scores_item, pred_labels_item];
+ }
+ function check_segment_validity(mask_labels, mask_probs, k2, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8) {
+ const mask_k = [];
+ let mask_k_area = 0;
+ let original_area = 0;
+ const mask_probs_k_data = mask_probs[k2].data;
+ for (let i = 0; i < mask_labels.length; ++i) {
+ if (mask_labels[i] === k2) {
+ mask_k.push(i);
+ ++mask_k_area;
+ }
+ if (mask_probs_k_data[i] >= mask_threshold) {
+ ++original_area;
+ }
+ }
+ let mask_exists = mask_k_area > 0 && original_area > 0;
+ if (mask_exists) {
+ let area_ratio = mask_k_area / original_area;
+ mask_exists = area_ratio > overlap_mask_area_threshold;
+ }
+ return [mask_exists, mask_k];
+ }
+ function compute_segments(mask_probs, pred_scores, pred_labels, mask_threshold, overlap_mask_area_threshold, label_ids_to_fuse = null, target_size = null) {
+ const [height, width] = target_size ?? mask_probs[0].dims;
+ const segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(
+ "int32",
+ new Int32Array(height * width),
+ [height, width]
+ );
+ const segments = [];
+ if (target_size !== null) {
+ for (let i = 0; i < mask_probs.length; ++i) {
+ mask_probs[i] = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate)(mask_probs[i], target_size, "bilinear", false);
+ }
+ }
+ const mask_labels = new Int32Array(mask_probs[0].data.length);
+ const bestScores = new Float32Array(mask_probs[0].data.length);
+ for (let i = 0; i < mask_probs.length; ++i) {
+ let score = pred_scores[i];
+ const mask_probs_i_data = mask_probs[i].data;
+ for (let j = 0; j < mask_probs_i_data.length; ++j) {
+ mask_probs_i_data[j] *= score;
+ if (mask_probs_i_data[j] > bestScores[j]) {
+ mask_labels[j] = i;
+ bestScores[j] = mask_probs_i_data[j];
+ }
+ }
+ }
+ let current_segment_id = 0;
+ const segmentation_data = segmentation.data;
+ for (let k2 = 0; k2 < pred_labels.length; ++k2) {
+ const pred_class = pred_labels[k2];
+ const [mask_exists, mask_k] = check_segment_validity(
+ mask_labels,
+ mask_probs,
+ k2,
+ mask_threshold,
+ overlap_mask_area_threshold
+ );
+ if (!mask_exists) {
+ continue;
+ }
+ ++current_segment_id;
+ for (const index of mask_k) {
+ segmentation_data[index] = current_segment_id;
+ }
+ segments.push({
+ id: current_segment_id,
+ label_id: pred_class,
+ // was_fused: should_fuse, TODO
+ score: pred_scores[k2]
+ });
+ }
+ return [segmentation, segments];
+ }
+ function smart_resize(height, width, factor = 28, min_pixels = 56 * 56, max_pixels = 14 * 14 * 4 * 1280) {
+ if (height < factor || width < factor) {
+ throw new Error(`height:${height} or width:${width} must be larger than factor:${factor}`);
+ } else if (Math.max(height, width) / Math.min(height, width) > 200) {
+ throw new Error(
+ `absolute aspect ratio must be smaller than 200, got ${Math.max(height, width) / Math.min(height, width)}`
+ );
+ }
+ let h_bar = Math.round(height / factor) * factor;
+ let w_bar = Math.round(width / factor) * factor;
+ if (h_bar * w_bar > max_pixels) {
+ const beta = Math.sqrt(height * width / max_pixels);
+ h_bar = Math.floor(height / beta / factor) * factor;
+ w_bar = Math.floor(width / beta / factor) * factor;
+ } else if (h_bar * w_bar < min_pixels) {
+ const beta = Math.sqrt(min_pixels / (height * width));
+ h_bar = Math.ceil(height * beta / factor) * factor;
+ w_bar = Math.ceil(width * beta / factor) * factor;
+ }
+ return [h_bar, w_bar];
+ }
+ function post_process_panoptic_segmentation(outputs, threshold = 0.5, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8, label_ids_to_fuse = null, target_sizes = null) {
+ if (label_ids_to_fuse === null) {
+ console.warn("`label_ids_to_fuse` unset. No instance will be fused.");
+ label_ids_to_fuse = /* @__PURE__ */ new Set();
+ }
+ const class_queries_logits = outputs.class_queries_logits ?? outputs.logits;
+ const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks;
+ const mask_probs = masks_queries_logits.sigmoid();
+ let [batch_size, num_queries, num_labels] = class_queries_logits.dims;
+ num_labels -= 1;
+ if (target_sizes !== null && target_sizes.length !== batch_size) {
+ throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");
+ }
+ let toReturn = [];
+ for (let i = 0; i < batch_size; ++i) {
+ let target_size = target_sizes !== null ? target_sizes[i] : null;
+ let class_logits = class_queries_logits[i];
+ let mask_logits = mask_probs[i];
+ let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);
+ if (pred_labels_item.length === 0) {
+ let [height, width] = target_size ?? mask_logits.dims.slice(-2);
+ let segmentation2 = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(
+ "int32",
+ new Int32Array(height * width).fill(-1),
+ [height, width]
+ );
+ toReturn.push({
+ segmentation: segmentation2,
+ segments_info: []
+ });
+ continue;
+ }
+ let [segmentation, segments] = compute_segments(
+ mask_probs_item,
+ pred_scores_item,
+ pred_labels_item,
+ mask_threshold,
+ overlap_mask_area_threshold,
+ label_ids_to_fuse,
+ target_size
+ );
+ toReturn.push({
+ segmentation,
+ segments_info: segments
+ });
+ }
+ return toReturn;
+ }
+ function post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) {
+ throw new Error("`post_process_instance_segmentation` is not yet implemented.");
+ }
+ class ImageProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
+ /**
+ * Constructs a new `ImageProcessor`.
+ * @param {ImageProcessorConfig} config The configuration object.
+ */
+ constructor(config) {
+ super();
+ this.image_mean = config.image_mean ?? config.mean;
+ this.image_std = config.image_std ?? config.std;
+ this.resample = config.resample ?? 2;
+ this.do_rescale = config.do_rescale ?? true;
+ this.rescale_factor = config.rescale_factor ?? 1 / 255;
+ this.do_normalize = config.do_normalize;
+ this.do_thumbnail = config.do_thumbnail;
+ this.size = config.size ?? config.image_size;
+ this.do_resize = config.do_resize ?? this.size !== void 0;
+ this.size_divisibility = config.size_divisibility ?? config.size_divisor;
+ this.do_center_crop = config.do_center_crop;
+ this.crop_size = config.crop_size;
+ this.do_convert_rgb = config.do_convert_rgb ?? true;
+ this.do_crop_margin = config.do_crop_margin;
+ this.pad_size = config.pad_size;
+ this.do_pad = config.do_pad;
+ this.min_pixels = config.min_pixels;
+ this.max_pixels = config.max_pixels;
+ if (this.do_pad && !this.pad_size && this.size && this.size.width !== void 0 && this.size.height !== void 0) {
+ this.pad_size = this.size;
+ }
+ this.do_flip_channel_order = config.do_flip_channel_order ?? false;
+ this.config = config;
+ }
+ /**
+ * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
+ * corresponding dimension of the specified size.
+ * @param {RawImage} image The image to be resized.
+ * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
+ * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
+ * @returns {Promise} The resized image.
+ */
+ async thumbnail(image, size, resample = 2) {
+ const input_height = image.height;
+ const input_width = image.width;
+ const output_height = size.height;
+ const output_width = size.width;
+ let height = Math.min(input_height, output_height);
+ let width = Math.min(input_width, output_width);
+ if (height === input_height && width === input_width) {
+ return image;
+ }
+ if (input_height > input_width) {
+ width = Math.floor(input_width * height / input_height);
+ } else if (input_width > input_height) {
+ height = Math.floor(input_height * width / input_width);
+ }
+ return await image.resize(width, height, { resample });
+ }
+ /**
+ * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
+ * @param {RawImage} image The image to be cropped.
+ * @param {number} gray_threshold Value below which pixels are considered to be gray.
+ * @returns {Promise} The cropped image.
+ */
+ async crop_margin(image, gray_threshold = 200) {
+ const gray_image = image.clone().grayscale();
+ const minValue = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.min)(gray_image.data)[0];
+ const maxValue = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(gray_image.data)[0];
+ const diff = maxValue - minValue;
+ if (diff === 0) {
+ return image;
+ }
+ const threshold = gray_threshold / 255;
+ let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;
+ const gray_image_data = gray_image.data;
+ for (let j = 0; j < gray_image.height; ++j) {
+ const row = j * gray_image.width;
+ for (let i = 0; i < gray_image.width; ++i) {
+ if ((gray_image_data[row + i] - minValue) / diff < threshold) {
+ x_min = Math.min(x_min, i);
+ y_min = Math.min(y_min, j);
+ x_max = Math.max(x_max, i);
+ y_max = Math.max(y_max, j);
+ }
+ }
+ }
+ image = await image.crop([x_min, y_min, x_max, y_max]);
+ return image;
+ }
+ /**
+ * Pad the image by a certain amount.
+ * @param {Float32Array} pixelData The pixel data to pad.
+ * @param {number[]} imgDims The dimensions of the image (height, width, channels).
+ * @param {{width:number; height:number}|number|'square'} padSize The dimensions of the padded image.
+ * @param {Object} options The options for padding.
+ * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
+ * @param {boolean} [options.center=false] Whether to center the image.
+ * @param {number|number[]} [options.constant_values=0] The constant value to use for padding.
+ * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
+ */
+ pad_image(pixelData, imgDims, padSize, {
+ mode = "constant",
+ center = false,
+ constant_values = 0
+ } = {}) {
+ const [imageHeight, imageWidth, imageChannels] = imgDims;
+ let paddedImageWidth, paddedImageHeight;
+ if (typeof padSize === "number") {
+ paddedImageWidth = padSize;
+ paddedImageHeight = padSize;
+ } else if (padSize === "square") {
+ paddedImageWidth = paddedImageHeight = Math.max(imageHeight, imageWidth);
+ } else {
+ paddedImageWidth = padSize.width;
+ paddedImageHeight = padSize.height;
+ }
+ if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {
+ const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);
+ if (Array.isArray(constant_values)) {
+ for (let i = 0; i < paddedPixelData.length; ++i) {
+ paddedPixelData[i] = constant_values[i % imageChannels];
+ }
+ } else if (constant_values !== 0) {
+ paddedPixelData.fill(constant_values);
+ }
+ const [left, top] = center ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)] : [0, 0];
+ for (let i = 0; i < imageHeight; ++i) {
+ const a = (i + top) * paddedImageWidth;
+ const b = i * imageWidth;
+ for (let j = 0; j < imageWidth; ++j) {
+ const c = (a + j + left) * imageChannels;
+ const d = (b + j) * imageChannels;
+ for (let k2 = 0; k2 < imageChannels; ++k2) {
+ paddedPixelData[c + k2] = pixelData[d + k2];
+ }
+ }
+ }
+ if (mode === "symmetric") {
+ if (center) {
+ throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");
+ }
+ const h1 = imageHeight - 1;
+ const w1 = imageWidth - 1;
+ for (let i = 0; i < paddedImageHeight; ++i) {
+ const a = i * paddedImageWidth;
+ const b = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.calculateReflectOffset)(i, h1) * imageWidth;
+ for (let j = 0; j < paddedImageWidth; ++j) {
+ if (i < imageHeight && j < imageWidth) continue;
+ const c = (a + j) * imageChannels;
+ const d = (b + (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.calculateReflectOffset)(j, w1)) * imageChannels;
+ for (let k2 = 0; k2 < imageChannels; ++k2) {
+ paddedPixelData[c + k2] = pixelData[d + k2];
+ }
+ }
+ }
+ }
+ pixelData = paddedPixelData;
+ imgDims = [paddedImageHeight, paddedImageWidth, imageChannels];
+ }
+ return [pixelData, imgDims];
+ }
+ /**
+ * Rescale the image' pixel values by `this.rescale_factor`.
+ * @param {Float32Array} pixelData The pixel data to rescale.
+ * @returns {void}
+ */
+ rescale(pixelData) {
+ for (let i = 0; i < pixelData.length; ++i) {
+ pixelData[i] = this.rescale_factor * pixelData[i];
+ }
+ }
+ /**
+ * Find the target (width, height) dimension of the output image after
+ * resizing given the input image and the desired size.
+ * @param {RawImage} image The image to resize.
+ * @param {any} size The size to use for resizing the image.
+ * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
+ */
+ get_resize_output_image_size(image, size) {
+ const [srcWidth, srcHeight] = image.size;
+ let shortest_edge;
+ let longest_edge;
+ if (this.do_thumbnail) {
+ const { height, width } = size;
+ shortest_edge = Math.min(height, width);
+ } else if (Number.isInteger(size)) {
+ shortest_edge = size;
+ longest_edge = this.config.max_size ?? shortest_edge;
+ } else if (size !== void 0) {
+ shortest_edge = size.shortest_edge;
+ longest_edge = size.longest_edge;
+ }
+ if (shortest_edge !== void 0 || longest_edge !== void 0) {
+ const shortResizeFactor = shortest_edge === void 0 ? 1 : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);
+ const newWidth = srcWidth * shortResizeFactor;
+ const newHeight = srcHeight * shortResizeFactor;
+ const longResizeFactor = longest_edge === void 0 ? 1 : Math.min(longest_edge / newWidth, longest_edge / newHeight);
+ let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));
+ let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));
+ if (this.size_divisibility !== void 0) {
+ [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility);
+ }
+ return [finalWidth, finalHeight];
+ } else if (size !== void 0 && size.width !== void 0 && size.height !== void 0) {
+ let newWidth = size.width;
+ let newHeight = size.height;
+ if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {
+ let scale_height = newHeight / srcHeight;
+ let scale_width = newWidth / srcWidth;
+ if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {
+ scale_height = scale_width;
+ } else {
+ scale_width = scale_height;
+ }
+ newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);
+ newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);
+ }
+ return [newWidth, newHeight];
+ } else if (this.size_divisibility !== void 0) {
+ return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);
+ } else if (this.min_pixels !== void 0 && this.max_pixels !== void 0) {
+ const factor = this.config.patch_size * this.config.merge_size;
+ return smart_resize(srcHeight, srcWidth, factor, this.min_pixels, this.max_pixels);
+ } else {
+ throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`);
+ }
+ }
+ /**
+ * Resizes the image.
+ * @param {RawImage} image The image to resize.
+ * @returns {Promise} The resized image.
+ */
+ async resize(image) {
+ const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);
+ return await image.resize(newWidth, newHeight, {
+ // @ts-expect-error TS2322
+ resample: this.resample
+ });
+ }
+ /**
+ * @typedef {object} PreprocessedImage
+ * @property {HeightWidth} original_size The original size of the image.
+ * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
+ * @property {Tensor} pixel_values The pixel values of the preprocessed image.
+ */
+ /**
+ * Preprocesses the given image.
+ *
+ * @param {RawImage} image The image to preprocess.
+ * @param {Object} overrides The overrides for the preprocessing options.
+ * @returns {Promise} The preprocessed image.
+ */
+ async preprocess(image, {
+ do_normalize = null,
+ do_pad = null,
+ do_convert_rgb = null,
+ do_convert_grayscale = null,
+ do_flip_channel_order = null
+ } = {}) {
+ if (this.do_crop_margin) {
+ image = await this.crop_margin(image);
+ }
+ const [srcWidth, srcHeight] = image.size;
+ if (do_convert_rgb ?? this.do_convert_rgb) {
+ image = image.rgb();
+ } else if (do_convert_grayscale) {
+ image = image.grayscale();
+ }
+ if (this.do_resize) {
+ image = await this.resize(image);
+ }
+ if (this.do_thumbnail) {
+ image = await this.thumbnail(image, this.size, this.resample);
+ }
+ if (this.do_center_crop) {
+ let crop_width;
+ let crop_height;
+ if (Number.isInteger(this.crop_size)) {
+ crop_width = this.crop_size;
+ crop_height = this.crop_size;
+ } else {
+ crop_width = this.crop_size.width;
+ crop_height = this.crop_size.height;
+ }
+ image = await image.center_crop(crop_width, crop_height);
+ }
+ const reshaped_input_size = [image.height, image.width];
+ let pixelData = Float32Array.from(image.data);
+ let imgDims = [image.height, image.width, image.channels];
+ if (this.do_rescale) {
+ this.rescale(pixelData);
+ }
+ if (do_normalize ?? this.do_normalize) {
+ let image_mean = this.image_mean;
+ if (!Array.isArray(this.image_mean)) {
+ image_mean = new Array(image.channels).fill(image_mean);
+ }
+ let image_std = this.image_std;
+ if (!Array.isArray(this.image_std)) {
+ image_std = new Array(image.channels).fill(image_std);
+ }
+ if (image_mean.length !== image.channels || image_std.length !== image.channels) {
+ throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);
+ }
+ for (let i = 0; i < pixelData.length; i += image.channels) {
+ for (let j = 0; j < image.channels; ++j) {
+ pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];
+ }
+ }
+ }
+ if (do_pad ?? this.do_pad) {
+ if (this.pad_size) {
+ const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);
+ [pixelData, imgDims] = padded;
+ } else if (this.size_divisibility) {
+ const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);
+ [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });
+ }
+ }
+ if (do_flip_channel_order ?? this.do_flip_channel_order) {
+ if (imgDims[2] !== 3) {
+ throw new Error("Flipping channel order is only supported for RGB images.");
+ }
+ for (let i = 0; i < pixelData.length; i += 3) {
+ const temp = pixelData[i];
+ pixelData[i] = pixelData[i + 2];
+ pixelData[i + 2] = temp;
+ }
+ }
+ const pixel_values = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("float32", pixelData, imgDims).permute(2, 0, 1);
+ return {
+ original_size: [srcHeight, srcWidth],
+ reshaped_input_size,
+ pixel_values
+ };
+ }
+ /**
+ * Calls the feature extraction process on an array of images,
+ * preprocesses each image, and concatenates the resulting
+ * features into a single Tensor.
+ * @param {RawImage[]} images The image(s) to extract features from.
+ * @param {...any} args Additional arguments.
+ * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
+ */
+ async _call(images, ...args) {
+ if (!Array.isArray(images)) {
+ images = [images];
+ }
+ const imageData = await Promise.all(images.map((x) => this.preprocess(x)));
+ const pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(imageData.map((x) => x.pixel_values), 0);
+ return {
+ pixel_values,
+ // Original sizes of images
+ original_sizes: imageData.map((x) => x.original_size),
+ // Reshaped sizes of images, before padding or cropping
+ reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size)
+ };
+ }
+ /**
+ * Instantiate one of the processor classes of the library from a pretrained model.
+ *
+ * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy)
+ * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
+ *
+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
+ * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
+ * user or organization name, like `dbmdz/bert-base-german-cased`.
+ * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
+ * @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
+ *
+ * @returns {Promise} A new instance of the Processor class.
+ */
+ static async from_pretrained(pretrained_model_name_or_path, options = {}) {
+ const preprocessorConfig = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__.IMAGE_PROCESSOR_NAME, true, options);
+ return new this(preprocessorConfig);
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/base/processing_utils.js": (
+ /*!**************************************!*\
+ !*** ./src/base/processing_utils.js ***!
+ \**************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ Processor: () => (
+ /* binding */
+ Processor
+ )
+ /* harmony export */
+ });
+ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/constants.js */
+ "./src/utils/constants.js"
+ );
+ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ../utils/generic.js */
+ "./src/utils/generic.js"
+ );
+ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! ../utils/hub.js */
+ "./src/utils/hub.js"
+ );
+ class Processor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__.Callable {
+ /**
+ * Creates a new Processor with the given components
+ * @param {Object} config
+ * @param {Record} components
+ * @param {string} chat_template
+ */
+ constructor(config, components, chat_template) {
+ super();
+ this.config = config;
+ this.components = components;
+ this.chat_template = chat_template;
+ }
+ /**
+ * @returns {import('./image_processors_utils.js').ImageProcessor|undefined} The image processor of the processor, if it exists.
+ */
+ get image_processor() {
+ return this.components.image_processor;
+ }
+ /**
+ * @returns {PreTrainedTokenizer|undefined} The tokenizer of the processor, if it exists.
+ */
+ get tokenizer() {
+ return this.components.tokenizer;
+ }
+ /**
+ * @returns {import('./feature_extraction_utils.js').FeatureExtractor|undefined} The feature extractor of the processor, if it exists.
+ */
+ get feature_extractor() {
+ return this.components.feature_extractor;
+ }
+ /**
+ * @param {Parameters[0]} messages
+ * @param {Parameters[1]} options
+ * @returns {ReturnType}
+ */
+ apply_chat_template(messages, options = {}) {
+ if (!this.tokenizer) {
+ throw new Error("Unable to apply chat template without a tokenizer.");
+ }
+ return this.tokenizer.apply_chat_template(messages, {
+ tokenize: false,
+ // default to false
+ chat_template: this.chat_template ?? void 0,
+ ...options
+ });
+ }
+ /**
+ * @param {Parameters} args
+ * @returns {ReturnType}
+ */
+ batch_decode(...args) {
+ if (!this.tokenizer) {
+ throw new Error("Unable to decode without a tokenizer.");
+ }
+ return this.tokenizer.batch_decode(...args);
+ }
+ /**
+ * @param {Parameters} args
+ * @returns {ReturnType}
+ */
+ decode(...args) {
+ if (!this.tokenizer) {
+ throw new Error("Unable to decode without a tokenizer.");
+ }
+ return this.tokenizer.decode(...args);
+ }
+ /**
+ * Calls the feature_extractor function with the given input.
+ * @param {any} input The input to extract features from.
+ * @param {...any} args Additional arguments.
+ * @returns {Promise} A Promise that resolves with the extracted features.
+ */
+ async _call(input, ...args) {
+ for (const item of [this.image_processor, this.feature_extractor, this.tokenizer]) {
+ if (item) {
+ return item(input, ...args);
+ }
+ }
+ throw new Error("No image processor, feature extractor, or tokenizer found.");
+ }
+ /**
+ * Instantiate one of the processor classes of the library from a pretrained model.
+ *
+ * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy)
+ * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
+ *
+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
+ * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
+ * user or organization name, like `dbmdz/bert-base-german-cased`.
+ * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
+ * @param {PretrainedProcessorOptions} options Additional options for loading the processor.
+ *
+ * @returns {Promise} A new instance of the Processor class.
+ */
+ static async from_pretrained(pretrained_model_name_or_path, options = {}) {
+ const [config, components, chat_template] = await Promise.all([
+ // TODO:
+ this.uses_processor_config ? (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.PROCESSOR_NAME, true, options) : {},
+ Promise.all(
+ this.classes.filter((cls) => cls in this).map(async (cls) => {
+ const component = await this[cls].from_pretrained(pretrained_model_name_or_path, options);
+ return [cls.replace(/_class$/, ""), component];
+ })
+ ).then(Object.fromEntries),
+ this.uses_chat_template_file ? (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelText)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.CHAT_TEMPLATE_NAME, true, options) : null
+ ]);
+ return new this(config, components, chat_template);
+ }
+ }
+ __publicField(Processor, "classes", [
+ "image_processor_class",
+ "tokenizer_class",
+ "feature_extractor_class"
+ ]);
+ __publicField(Processor, "uses_processor_config", false);
+ __publicField(Processor, "uses_chat_template_file", false);
+ })
+ ),
+ /***/
+ "./src/configs.js": (
+ /*!************************!*\
+ !*** ./src/configs.js ***!
+ \************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ AutoConfig: () => (
+ /* binding */
+ AutoConfig
+ ),
+ /* harmony export */
+ PretrainedConfig: () => (
+ /* binding */
+ PretrainedConfig
+ ),
+ /* harmony export */
+ getCacheShapes: () => (
+ /* binding */
+ getCacheShapes
+ )
+ /* harmony export */
+ });
+ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ./utils/core.js */
+ "./src/utils/core.js"
+ );
+ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ./utils/hub.js */
+ "./src/utils/hub.js"
+ );
+ async function loadConfig(pretrained_model_name_or_path, options) {
+ return await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, "config.json", true, options);
+ }
+ function getNormalizedConfig(config) {
+ const mapping = {};
+ let init_normalized_config = {};
+ switch (config.model_type) {
+ // Sub-configs
+ case "llava":
+ case "paligemma":
+ case "gemma3":
+ case "florence2":
+ case "llava_onevision":
+ case "idefics3":
+ case "ultravox":
+ case "voxtral":
+ case "smolvlm":
+ case "gemma3n":
+ case "mistral3":
+ init_normalized_config = getNormalizedConfig(config.text_config);
+ break;
+ case "moondream1":
+ init_normalized_config = getNormalizedConfig(config.phi_config);
+ break;
+ case "musicgen":
+ init_normalized_config = getNormalizedConfig(config.decoder);
+ break;
+ case "multi_modality":
+ init_normalized_config = getNormalizedConfig(config.language_config);
+ break;
+ // Decoder-only models
+ case "gpt2":
+ case "gptj":
+ case "jais":
+ case "codegen":
+ case "gpt_bigcode":
+ mapping["num_heads"] = "n_head";
+ mapping["num_layers"] = "n_layer";
+ mapping["hidden_size"] = "n_embd";
+ break;
+ case "gpt_neox":
+ case "stablelm":
+ case "opt":
+ case "falcon":
+ case "modernbert-decoder":
+ mapping["num_heads"] = "num_attention_heads";
+ mapping["num_layers"] = "num_hidden_layers";
+ mapping["hidden_size"] = "hidden_size";
+ break;
+ case "llama":
+ case "llama4_text":
+ case "nanochat":
+ case "arcee":
+ case "lfm2":
+ case "smollm3":
+ case "olmo":
+ case "olmo2":
+ case "mobilellm":
+ case "granite":
+ case "granitemoehybrid":
+ case "cohere":
+ case "mistral":
+ case "starcoder2":
+ case "qwen2":
+ case "qwen2_vl":
+ case "phi":
+ case "phi3":
+ case "phi3_v":
+ case "llava_qwen2":
+ mapping["num_heads"] = "num_key_value_heads";
+ mapping["num_layers"] = "num_hidden_layers";
+ mapping["hidden_size"] = "hidden_size";
+ mapping["num_attention_heads"] = "num_attention_heads";
+ mapping["dim_kv"] = "head_dim";
+ break;
+ case "qwen3":
+ case "gemma":
+ case "gemma2":
+ case "vaultgemma":
+ case "gemma3_text":
+ case "gemma3n_text":
+ case "glm":
+ case "helium":
+ case "ernie4_5":
+ case "ministral":
+ case "ministral3":
+ mapping["num_heads"] = "num_key_value_heads";
+ mapping["num_layers"] = "num_hidden_layers";
+ mapping["dim_kv"] = "head_dim";
+ break;
+ case "openelm":
+ mapping["num_heads"] = "num_kv_heads";
+ mapping["num_layers"] = "num_transformer_layers";
+ mapping["dim_kv"] = "head_dim";
+ break;
+ case "gpt_neo":
+ case "donut-swin":
+ mapping["num_heads"] = "num_heads";
+ mapping["num_layers"] = "num_layers";
+ mapping["hidden_size"] = "hidden_size";
+ break;
+ case "bloom":
+ mapping["num_heads"] = "n_head";
+ mapping["num_layers"] = "n_layer";
+ mapping["hidden_size"] = "hidden_size";
+ break;
+ case "mpt":
+ mapping["num_heads"] = "n_heads";
+ mapping["num_layers"] = "n_layers";
+ mapping["hidden_size"] = "d_model";
+ break;
+ case "exaone":
+ mapping["num_heads"] = "num_key_value_heads";
+ mapping["num_layers"] = "num_layers";
+ mapping["dim_kv"] = "head_dim";
+ mapping["num_attention_heads"] = "num_attention_heads";
+ break;
+ // Encoder-decoder models
+ case "t5":
+ case "mt5":
+ case "longt5":
+ mapping["num_decoder_layers"] = "num_decoder_layers";
+ mapping["num_decoder_heads"] = "num_heads";
+ mapping["decoder_dim_kv"] = "d_kv";
+ mapping["num_encoder_layers"] = "num_layers";
+ mapping["num_encoder_heads"] = "num_heads";
+ mapping["encoder_dim_kv"] = "d_kv";
+ break;
+ case "bart":
+ case "mbart":
+ case "marian":
+ case "whisper":
+ case "lite-whisper":
+ case "m2m_100":
+ case "blenderbot":
+ case "blenderbot-small":
+ case "florence2_language":
+ mapping["num_decoder_layers"] = "decoder_layers";
+ mapping["num_decoder_heads"] = "decoder_attention_heads";
+ mapping["decoder_hidden_size"] = "d_model";
+ mapping["num_encoder_layers"] = "encoder_layers";
+ mapping["num_encoder_heads"] = "encoder_attention_heads";
+ mapping["encoder_hidden_size"] = "d_model";
+ break;
+ case "speecht5":
+ mapping["num_decoder_layers"] = "decoder_layers";
+ mapping["num_decoder_heads"] = "decoder_attention_heads";
+ mapping["decoder_hidden_size"] = "hidden_size";
+ mapping["num_encoder_layers"] = "encoder_layers";
+ mapping["num_encoder_heads"] = "encoder_attention_heads";
+ mapping["encoder_hidden_size"] = "hidden_size";
+ break;
+ case "trocr":
+ mapping["num_encoder_layers"] = mapping["num_decoder_layers"] = "decoder_layers";
+ mapping["num_encoder_heads"] = mapping["num_decoder_heads"] = "decoder_attention_heads";
+ mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "d_model";
+ break;
+ case "musicgen_decoder":
+ mapping["num_encoder_layers"] = mapping["num_decoder_layers"] = "num_hidden_layers";
+ mapping["num_encoder_heads"] = mapping["num_decoder_heads"] = "num_attention_heads";
+ mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "hidden_size";
+ break;
+ case "moonshine":
+ mapping["num_decoder_layers"] = "decoder_num_hidden_layers";
+ mapping["num_decoder_heads"] = "decoder_num_key_value_heads";
+ mapping["num_encoder_layers"] = "encoder_num_hidden_layers";
+ mapping["num_encoder_heads"] = "encoder_num_key_value_heads";
+ mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "hidden_size";
+ break;
+ case "vision-encoder-decoder":
+ const decoderConfig = getNormalizedConfig(config.decoder);
+ const add_encoder_pkv = "num_decoder_layers" in decoderConfig;
+ const result = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, ["model_type", "is_encoder_decoder"]);
+ if (add_encoder_pkv) {
+ result.num_decoder_layers = decoderConfig.num_decoder_layers;
+ result.num_decoder_heads = decoderConfig.num_decoder_heads;
+ result.decoder_hidden_size = decoderConfig.decoder_hidden_size;
+ result.num_encoder_layers = decoderConfig.num_encoder_layers;
+ result.num_encoder_heads = decoderConfig.num_encoder_heads;
+ result.encoder_hidden_size = decoderConfig.encoder_hidden_size;
+ } else {
+ result.num_layers = decoderConfig.num_layers;
+ result.num_heads = decoderConfig.num_heads;
+ result.hidden_size = decoderConfig.hidden_size;
+ }
+ return result;
+ }
+ const normalized_config = {
+ ...init_normalized_config,
+ ...(0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, ["model_type", "multi_query", "is_encoder_decoder"])
+ };
+ for (const key in mapping) {
+ normalized_config[key] = config[mapping[key]];
+ }
+ return normalized_config;
+ }
+ function getCacheShapes(config, options) {
+ if (config.model_type === "lfm2") {
+ const pkv_prefix = options?.prefix ?? "past_key_values";
+ const conv_prefix = pkv_prefix === "present" ? "present" : "past";
+ const cache_values = {};
+ const { layer_types, num_attention_heads, num_key_value_heads, hidden_size, conv_L_cache } = config;
+ const head_dim = hidden_size / num_attention_heads;
+ const batch_size = options?.batch_size ?? 1;
+ for (let i = 0; i < layer_types.length; ++i) {
+ if (layer_types[i] === "full_attention") {
+ for (const kv of ["key", "value"]) {
+ cache_values[`${pkv_prefix}.${i}.${kv}`] = [batch_size, num_key_value_heads, 0, head_dim];
+ }
+ } else if (layer_types[i] === "conv") {
+ cache_values[`${conv_prefix}_conv.${i}`] = [batch_size, hidden_size, conv_L_cache];
+ } else {
+ throw new Error(`Unsupported layer type: ${layer_types[i]}`);
+ }
+ }
+ return cache_values;
+ }
+ return getKeyValueShapes(config, options);
+ }
+ function getKeyValueShapes(config, {
+ prefix = "past_key_values",
+ batch_size = 1
+ } = {}) {
+ const decoderFeeds = {};
+ const normalized_config = config.normalized_config;
+ if (normalized_config.is_encoder_decoder && ("num_encoder_heads" in normalized_config && "num_decoder_heads" in normalized_config)) {
+ const encoder_dim_kv = normalized_config.encoder_dim_kv ?? normalized_config.encoder_hidden_size / normalized_config.num_encoder_heads;
+ const decoder_dim_kv = normalized_config.decoder_dim_kv ?? normalized_config.decoder_hidden_size / normalized_config.num_decoder_heads;
+ const encoder_dims = [batch_size, normalized_config.num_encoder_heads, 0, encoder_dim_kv];
+ const decoder_dims = [batch_size, normalized_config.num_decoder_heads, 0, decoder_dim_kv];
+ for (let i = 0; i < normalized_config.num_decoder_layers; ++i) {
+ decoderFeeds[`${prefix}.${i}.encoder.key`] = encoder_dims;
+ decoderFeeds[`${prefix}.${i}.encoder.value`] = encoder_dims;
+ decoderFeeds[`${prefix}.${i}.decoder.key`] = decoder_dims;
+ decoderFeeds[`${prefix}.${i}.decoder.value`] = decoder_dims;
+ }
+ } else {
+ const num_heads = normalized_config.num_heads;
+ const num_layers = normalized_config.num_layers;
+ const dim_kv = normalized_config.dim_kv ?? normalized_config.hidden_size / (normalized_config.num_attention_heads ?? num_heads);
+ if (normalized_config.model_type === "falcon") {
+ const dims = [batch_size * num_heads, 0, dim_kv];
+ for (let i = 0; i < num_layers; ++i) {
+ decoderFeeds[`${prefix}.${i}.key`] = dims;
+ decoderFeeds[`${prefix}.${i}.value`] = dims;
+ }
+ } else if (normalized_config.multi_query) {
+ const dims = [batch_size * num_heads, 0, 2 * dim_kv];
+ for (let i = 0; i < num_layers; ++i) {
+ decoderFeeds[`${prefix}.${i}.key_value`] = dims;
+ }
+ } else if (normalized_config.model_type === "bloom") {
+ const keyDims = [batch_size * num_heads, dim_kv, 0];
+ const valueDims = [batch_size * num_heads, 0, dim_kv];
+ for (let i = 0; i < num_layers; ++i) {
+ decoderFeeds[`${prefix}.${i}.key`] = keyDims;
+ decoderFeeds[`${prefix}.${i}.value`] = valueDims;
+ }
+ } else if (normalized_config.model_type === "openelm") {
+ for (let i = 0; i < num_layers; ++i) {
+ const dims = [batch_size, num_heads[i], 0, dim_kv];
+ decoderFeeds[`${prefix}.${i}.key`] = dims;
+ decoderFeeds[`${prefix}.${i}.value`] = dims;
+ }
+ } else {
+ const dims = [batch_size, num_heads, 0, dim_kv];
+ for (let i = 0; i < num_layers; ++i) {
+ decoderFeeds[`${prefix}.${i}.key`] = dims;
+ decoderFeeds[`${prefix}.${i}.value`] = dims;
+ }
+ }
+ }
+ return decoderFeeds;
+ }
+ class PretrainedConfig {
+ /**
+ * Create a new PreTrainedTokenizer instance.
+ * @param {Object} configJSON The JSON of the config.
+ */
+ constructor(configJSON) {
+ // NOTE: Typo in original
+ /** @type {string|null} */
+ __publicField(this, "model_type", null);
+ /** @type {boolean} */
+ __publicField(this, "is_encoder_decoder", false);
+ /** @type {number} */
+ __publicField(this, "max_position_embeddings");
+ /** @type {TransformersJSConfig} */
+ __publicField(this, "transformers.js_config");
+ Object.assign(this, configJSON);
+ this.normalized_config = getNormalizedConfig(this);
+ }
+ /**
+ * Loads a pre-trained config from the given `pretrained_model_name_or_path`.
+ *
+ * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
+ * @param {PretrainedOptions} options Additional options for loading the config.
+ * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
+ *
+ * @returns {Promise} A new instance of the `PretrainedConfig` class.
+ */
+ static async from_pretrained(pretrained_model_name_or_path, {
+ progress_callback = null,
+ config = null,
+ cache_dir = null,
+ local_files_only = false,
+ revision = "main"
+ } = {}) {
+ if (config && !(config instanceof PretrainedConfig)) {
+ config = new PretrainedConfig(config);
+ }
+ const data = config ?? await loadConfig(pretrained_model_name_or_path, {
+ progress_callback,
+ config,
+ cache_dir,
+ local_files_only,
+ revision
+ });
+ return new this(data);
+ }
+ }
+ class AutoConfig {
+ /** @type {typeof PretrainedConfig.from_pretrained} */
+ static async from_pretrained(...args) {
+ return PretrainedConfig.from_pretrained(...args);
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/env.js": (
+ /*!********************!*\
+ !*** ./src/env.js ***!
+ \********************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ apis: () => (
+ /* binding */
+ apis
+ ),
+ /* harmony export */
+ env: () => (
+ /* binding */
+ env3
+ )
+ /* harmony export */
+ });
+ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! node:fs */
+ "?db59"
+ );
+ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! node:path */
+ "?383f"
+ );
+ var node_url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! node:url */
+ "?fa4b"
+ );
+ const VERSION = "3.8.1";
+ const IS_BROWSER_ENV = typeof window !== "undefined" && typeof window.document !== "undefined";
+ const IS_WEBWORKER_ENV = typeof self !== "undefined" && ["DedicatedWorkerGlobalScope", "ServiceWorkerGlobalScope", "SharedWorkerGlobalScope"].includes(self.constructor?.name);
+ const IS_WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self;
+ const IS_WEBGPU_AVAILABLE = typeof navigator !== "undefined" && "gpu" in navigator;
+ const IS_WEBNN_AVAILABLE = typeof navigator !== "undefined" && "ml" in navigator;
+ const IS_PROCESS_AVAILABLE = typeof process !== "undefined";
+ const IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === "node";
+ const IS_FS_AVAILABLE = !isEmpty(node_fs__WEBPACK_IMPORTED_MODULE_0__);
+ const IS_PATH_AVAILABLE = !isEmpty(node_path__WEBPACK_IMPORTED_MODULE_1__);
+ const IS_DENO_RUNTIME = typeof globalThis.Deno !== "undefined";
+ const IS_BUN_RUNTIME = typeof globalThis.Bun !== "undefined";
+ const apis = Object.freeze({
+ /** Whether we are running in a browser environment (and not a web worker) */
+ IS_BROWSER_ENV,
+ /** Whether we are running in a web worker environment */
+ IS_WEBWORKER_ENV,
+ /** Whether the Cache API is available */
+ IS_WEB_CACHE_AVAILABLE,
+ /** Whether the WebGPU API is available */
+ IS_WEBGPU_AVAILABLE,
+ /** Whether the WebNN API is available */
+ IS_WEBNN_AVAILABLE,
+ /** Whether the Node.js process API is available */
+ IS_PROCESS_AVAILABLE,
+ /** Whether we are running in a Node.js-like environment (node, deno, bun) */
+ IS_NODE_ENV,
+ /** Whether the filesystem API is available */
+ IS_FS_AVAILABLE,
+ /** Whether the path API is available */
+ IS_PATH_AVAILABLE
+ });
+ const RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE;
+ let dirname__ = "./";
+ if (RUNNING_LOCALLY) {
+ const _import_meta_url = Object(import.meta).url;
+ if (_import_meta_url) {
+ dirname__ = node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(node_url__WEBPACK_IMPORTED_MODULE_2__.fileURLToPath(_import_meta_url)));
+ } else if (typeof __dirname !== "undefined") {
+ dirname__ = node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(__dirname);
+ }
+ }
+ const DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? node_path__WEBPACK_IMPORTED_MODULE_1__.join(dirname__, "/.cache/") : null;
+ const DEFAULT_LOCAL_MODEL_PATH = "/models/";
+ const localModelPath = RUNNING_LOCALLY ? node_path__WEBPACK_IMPORTED_MODULE_1__.join(dirname__, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH;
+ const env3 = {
+ version: VERSION,
+ /////////////////// Backends settings ///////////////////
+ // NOTE: These will be populated later by the backends themselves.
+ backends: {
+ // onnxruntime-web/onnxruntime-node
+ onnx: {}
+ },
+ /////////////////// Model settings ///////////////////
+ allowRemoteModels: true,
+ remoteHost: "https://huggingface.co/",
+ remotePathTemplate: "{model}/resolve/{revision}/",
+ allowLocalModels: !(IS_BROWSER_ENV || IS_WEBWORKER_ENV),
+ localModelPath,
+ useFS: IS_FS_AVAILABLE,
+ /////////////////// Cache settings ///////////////////
+ useBrowserCache: IS_WEB_CACHE_AVAILABLE && !IS_DENO_RUNTIME,
+ useFSCache: IS_FS_AVAILABLE,
+ cacheDir: DEFAULT_CACHE_DIR,
+ useCustomCache: false,
+ customCache: null
+ //////////////////////////////////////////////////////
+ };
+ function isEmpty(obj) {
+ return Object.keys(obj).length === 0;
+ }
+ })
+ ),
+ /***/
+ "./src/generation/configuration_utils.js": (
+ /*!***********************************************!*\
+ !*** ./src/generation/configuration_utils.js ***!
+ \***********************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ GenerationConfig: () => (
+ /* binding */
+ GenerationConfig
+ )
+ /* harmony export */
+ });
+ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/core.js */
+ "./src/utils/core.js"
+ );
+ class GenerationConfig {
+ /**
+ *
+ * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config
+ */
+ constructor(config) {
+ // Parameters that control the length of the output
+ /**
+ * The maximum length the generated tokens can have.
+ * Corresponds to the length of the input prompt + `max_new_tokens`.
+ * Its effect is overridden by `max_new_tokens`, if also set.
+ * @type {number}
+ * @default 20
+ */
+ __publicField(this, "max_length", 20);
+ /**
+ * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "max_new_tokens", null);
+ /**
+ * The minimum length of the sequence to be generated.
+ * Corresponds to the length of the input prompt + `min_new_tokens`.
+ * Its effect is overridden by `min_new_tokens`, if also set.
+ * @type {number}
+ * @default 0
+ */
+ __publicField(this, "min_length", 0);
+ /**
+ * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "min_new_tokens", null);
+ /**
+ * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
+ * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;
+ * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;
+ * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
+ * @type {boolean|"never"}
+ * @default false
+ */
+ __publicField(this, "early_stopping", false);
+ /**
+ * The maximum amount of time you allow the computation to run for in seconds.
+ * Generation will still finish the current pass after allocated time has been passed.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "max_time", null);
+ // Parameters that control the generation strategy used
+ /**
+ * Whether or not to use sampling; use greedy decoding otherwise.
+ * @type {boolean}
+ * @default false
+ */
+ __publicField(this, "do_sample", false);
+ /**
+ * Number of beams for beam search. 1 means no beam search.
+ * @type {number}
+ * @default 1
+ */
+ __publicField(this, "num_beams", 1);
+ /**
+ * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
+ * See [this paper](https://huggingface.co/papers/1610.02424) for more details.
+ * @type {number}
+ * @default 1
+ */
+ __publicField(this, "num_beam_groups", 1);
+ /**
+ * The values balance the model confidence and the degeneration penalty in contrastive search decoding.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "penalty_alpha", null);
+ /**
+ * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
+ * @type {boolean}
+ * @default true
+ */
+ __publicField(this, "use_cache", true);
+ // Parameters for manipulation of the model output logits
+ /**
+ * The value used to modulate the next token probabilities.
+ * @type {number}
+ * @default 1.0
+ */
+ __publicField(this, "temperature", 1);
+ /**
+ * The number of highest probability vocabulary tokens to keep for top-k-filtering.
+ * @type {number}
+ * @default 50
+ */
+ __publicField(this, "top_k", 50);
+ /**
+ * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
+ * @type {number}
+ * @default 1.0
+ */
+ __publicField(this, "top_p", 1);
+ /**
+ * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated.
+ * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation.
+ * See [this paper](https://huggingface.co/papers/2202.00666) for more details.
+ * @type {number}
+ * @default 1.0
+ */
+ __publicField(this, "typical_p", 1);
+ /**
+ * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled.
+ * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model.
+ * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details.
+ * @type {number}
+ * @default 0.0
+ */
+ __publicField(this, "epsilon_cutoff", 0);
+ /**
+ * Eta sampling is a hybrid of locally typical sampling and epsilon sampling.
+ * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`.
+ * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
+ * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details.
+ * @type {number}
+ * @default 0.0
+ */
+ __publicField(this, "eta_cutoff", 0);
+ /**
+ * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time.
+ * Note that `diversity_penalty` is only effective if `group beam search` is enabled.
+ * @type {number}
+ * @default 0.0
+ */
+ __publicField(this, "diversity_penalty", 0);
+ /**
+ * The parameter for repetition penalty. 1.0 means no penalty.
+ * See [this paper](https://huggingface.co/papers/1909.05858) for more details.
+ * @type {number}
+ * @default 1.0
+ */
+ __publicField(this, "repetition_penalty", 1);
+ /**
+ * The paramater for encoder_repetition_penalty.
+ * An exponential penalty on sequences that are not in the original input.
+ * 1.0 means no penalty.
+ * @type {number}
+ * @default 1.0
+ */
+ __publicField(this, "encoder_repetition_penalty", 1);
+ /**
+ * Exponential penalty to the length that is used with beam-based generation.
+ * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence.
+ * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
+ * @type {number}
+ * @default 1.0
+ */
+ __publicField(this, "length_penalty", 1);
+ /**
+ * If set to int > 0, all ngrams of that size can only occur once.
+ * @type {number}
+ * @default 0
+ */
+ __publicField(this, "no_repeat_ngram_size", 0);
+ /**
+ * List of token ids that are not allowed to be generated.
+ * In order to get the token ids of the words that should not appear in the generated text, use
+ * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`.
+ * @type {number[][]}
+ * @default null
+ */
+ __publicField(this, "bad_words_ids", null);
+ /**
+ * List of token ids that must be generated.
+ * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`.
+ * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
+ * @type {number[][]|number[][][]}
+ * @default null
+ */
+ __publicField(this, "force_words_ids", null);
+ /**
+ * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones).
+ * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
+ * @type {boolean}
+ * @default false
+ */
+ __publicField(this, "renormalize_logits", false);
+ /**
+ * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
+ * @type {Object[]}
+ * @default null
+ */
+ __publicField(this, "constraints", null);
+ /**
+ * The id of the token to force as the first generated token after the `decoder_start_token_id`.
+ * Useful for multilingual models like mBART where the first generated token needs to be the target language token.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "forced_bos_token_id", null);
+ /**
+ * The id of the token to force as the last generated token when `max_length` is reached.
+ * Optionally, use a list to set multiple *end-of-sequence* tokens.
+ * @type {number|number[]}
+ * @default null
+ */
+ __publicField(this, "forced_eos_token_id", null);
+ /**
+ * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
+ * @type {boolean}
+ */
+ __publicField(this, "remove_invalid_values", false);
+ /**
+ * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated.
+ * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.
+ * @type {[number, number]}
+ * @default null
+ */
+ __publicField(this, "exponential_decay_length_penalty", null);
+ /**
+ * A list of tokens that will be suppressed at generation.
+ * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
+ * @type {number[]}
+ * @default null
+ */
+ __publicField(this, "suppress_tokens", null);
+ /**
+ * A streamer that will be used to stream the generation.
+ * @type {import('./streamers.js').TextStreamer}
+ * @default null
+ */
+ __publicField(this, "streamer", null);
+ /**
+ * A list of tokens that will be suppressed at the beginning of the generation.
+ * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
+ * @type {number[]}
+ * @default null
+ */
+ __publicField(this, "begin_suppress_tokens", null);
+ /**
+ * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling.
+ * For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
+ * @type {[number, number][]}
+ * @default null
+ */
+ __publicField(this, "forced_decoder_ids", null);
+ /**
+ * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
+ * Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ * prompt, usually at the expense of poorer quality.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "guidance_scale", null);
+ // Parameters that define the output variables of `generate`
+ /**
+ * The number of independently computed returned sequences for each element in the batch.
+ * @type {number}
+ * @default 1
+ */
+ __publicField(this, "num_return_sequences", 1);
+ /**
+ * Whether or not to return the attentions tensors of all attention layers.
+ * See `attentions` under returned tensors for more details.
+ * @type {boolean}
+ * @default false
+ */
+ __publicField(this, "output_attentions", false);
+ /**
+ * Whether or not to return the hidden states of all layers.
+ * See `hidden_states` under returned tensors for more details.
+ * @type {boolean}
+ * @default false
+ */
+ __publicField(this, "output_hidden_states", false);
+ /**
+ * Whether or not to return the prediction scores.
+ * See `scores` under returned tensors for more details.
+ * @type {boolean}
+ * @default false
+ */
+ __publicField(this, "output_scores", false);
+ /**
+ * Whether or not to return a `ModelOutput` instead of a plain tuple.
+ * @type {boolean}
+ * @default false
+ */
+ __publicField(this, "return_dict_in_generate", false);
+ // Special tokens that can be used at generation time
+ /**
+ * The id of the *padding* token.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "pad_token_id", null);
+ /**
+ * The id of the *beginning-of-sequence* token.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "bos_token_id", null);
+ /**
+ * The id of the *end-of-sequence* token.
+ * Optionally, use a list to set multiple *end-of-sequence* tokens.
+ * @type {number|number[]}
+ * @default null
+ */
+ __publicField(this, "eos_token_id", null);
+ // Generation parameters exclusive to encoder-decoder models
+ /**
+ * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
+ * @type {number}
+ * @default 0
+ */
+ __publicField(this, "encoder_no_repeat_ngram_size", 0);
+ /**
+ * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
+ * @type {number}
+ * @default null
+ */
+ __publicField(this, "decoder_start_token_id", null);
+ // Wild card
+ /**
+ * Additional generation kwargs will be forwarded to the `generate` function of the model.
+ * Kwargs that are not present in `generate`'s signature will be used in the model forward pass.
+ * @type {Object}
+ * @default {}
+ */
+ __publicField(this, "generation_kwargs", {});
+ Object.assign(this, (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, Object.getOwnPropertyNames(this)));
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/generation/logits_process.js": (
+ /*!******************************************!*\
+ !*** ./src/generation/logits_process.js ***!
+ \******************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ ClassifierFreeGuidanceLogitsProcessor: () => (
+ /* binding */
+ ClassifierFreeGuidanceLogitsProcessor
+ ),
+ /* harmony export */
+ ForcedBOSTokenLogitsProcessor: () => (
+ /* binding */
+ ForcedBOSTokenLogitsProcessor
+ ),
+ /* harmony export */
+ ForcedEOSTokenLogitsProcessor: () => (
+ /* binding */
+ ForcedEOSTokenLogitsProcessor
+ ),
+ /* harmony export */
+ LogitsProcessor: () => (
+ /* binding */
+ LogitsProcessor
+ ),
+ /* harmony export */
+ LogitsProcessorList: () => (
+ /* binding */
+ LogitsProcessorList
+ ),
+ /* harmony export */
+ LogitsWarper: () => (
+ /* binding */
+ LogitsWarper
+ ),
+ /* harmony export */
+ MinLengthLogitsProcessor: () => (
+ /* binding */
+ MinLengthLogitsProcessor
+ ),
+ /* harmony export */
+ MinNewTokensLengthLogitsProcessor: () => (
+ /* binding */
+ MinNewTokensLengthLogitsProcessor
+ ),
+ /* harmony export */
+ NoBadWordsLogitsProcessor: () => (
+ /* binding */
+ NoBadWordsLogitsProcessor
+ ),
+ /* harmony export */
+ NoRepeatNGramLogitsProcessor: () => (
+ /* binding */
+ NoRepeatNGramLogitsProcessor
+ ),
+ /* harmony export */
+ RepetitionPenaltyLogitsProcessor: () => (
+ /* binding */
+ RepetitionPenaltyLogitsProcessor
+ ),
+ /* harmony export */
+ SuppressTokensAtBeginLogitsProcessor: () => (
+ /* binding */
+ SuppressTokensAtBeginLogitsProcessor
+ ),
+ /* harmony export */
+ TemperatureLogitsWarper: () => (
+ /* binding */
+ TemperatureLogitsWarper
+ ),
+ /* harmony export */
+ TopKLogitsWarper: () => (
+ /* binding */
+ TopKLogitsWarper
+ ),
+ /* harmony export */
+ TopPLogitsWarper: () => (
+ /* binding */
+ TopPLogitsWarper
+ ),
+ /* harmony export */
+ WhisperTimeStampLogitsProcessor: () => (
+ /* binding */
+ WhisperTimeStampLogitsProcessor
+ )
+ /* harmony export */
+ });
+ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/generic.js */
+ "./src/utils/generic.js"
+ );
+ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ../utils/tensor.js */
+ "./src/utils/tensor.js"
+ );
+ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! ../utils/maths.js */
+ "./src/utils/maths.js"
+ );
+ class LogitsProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
+ /**
+ * Apply the processor to the input logits.
+ *
+ * @abstract
+ * @param {bigint[][]} input_ids The input ids.
+ * @param {Tensor} logits The logits to process.
+ * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
+ */
+ _call(input_ids, logits) {
+ throw Error("`_call` should be implemented in a subclass");
+ }
+ }
+ class LogitsWarper extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
+ /**
+ * Apply the processor to the input logits.
+ *
+ * @abstract
+ * @param {bigint[][]} input_ids The input ids.
+ * @param {Tensor} logits The logits to process.
+ * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
+ */
+ _call(input_ids, logits) {
+ throw Error("`_call` should be implemented in a subclass");
+ }
+ }
+ class LogitsProcessorList extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
+ /**
+ * Constructs a new instance of `LogitsProcessorList`.
+ */
+ constructor() {
+ super();
+ this.processors = [];
+ }
+ /**
+ * Adds a new logits processor to the list.
+ *
+ * @param {LogitsProcessor} item The logits processor function to add.
+ */
+ push(item) {
+ this.processors.push(item);
+ }
+ /**
+ * Adds multiple logits processors to the list.
+ *
+ * @param {LogitsProcessor[]} items The logits processor functions to add.
+ */
+ extend(items) {
+ this.processors.push(...items);
+ }
+ /**
+ * Applies all logits processors in the list to a batch of logits, modifying them in-place.
+ *
+ * @param {bigint[][]} input_ids The input IDs for the language model.
+ * @param {Tensor} logits
+ */
+ _call(input_ids, logits) {
+ let toReturn = logits;
+ for (const processor of this.processors) {
+ toReturn = processor(input_ids, toReturn);
+ }
+ return toReturn;
+ }
+ [Symbol.iterator]() {
+ return this.processors.values();
+ }
+ }
+ class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a ForcedBOSTokenLogitsProcessor.
+ * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
+ */
+ constructor(bos_token_id) {
+ super();
+ this.bos_token_id = bos_token_id;
+ }
+ /**
+ * Apply the BOS token forcing to the logits.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The logits with BOS token forcing.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ if (input_ids[i].length === 1) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ batch_logits_data.fill(-Infinity);
+ batch_logits_data[this.bos_token_id] = 0;
+ }
+ }
+ return logits;
+ }
+ }
+ class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a ForcedEOSTokenLogitsProcessor.
+ * @param {number} max_length The maximum length of the sequence to be generated.
+ * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token.
+ */
+ constructor(max_length, eos_token_id) {
+ super();
+ this.max_length = max_length;
+ this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
+ }
+ /**
+ * Apply the processor to input_ids and logits.
+ *
+ * @param {bigint[][]} input_ids The input ids.
+ * @param {Tensor} logits The logits tensor.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ if (input_ids[i].length === this.max_length - 1) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ batch_logits_data.fill(-Infinity);
+ for (const eos_token of this.eos_token_id) {
+ batch_logits_data[eos_token] = 0;
+ }
+ }
+ }
+ return logits;
+ }
+ }
+ class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a SuppressTokensAtBeginLogitsProcessor.
+ * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
+ * @param {number} begin_index The number of tokens to generate before suppressing tokens.
+ */
+ constructor(begin_suppress_tokens, begin_index) {
+ super();
+ this.begin_suppress_tokens = begin_suppress_tokens;
+ this.begin_index = begin_index;
+ }
+ /**
+ * Apply the BOS token forcing to the logits.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The logits with BOS token forcing.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ if (input_ids[i].length === this.begin_index) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ for (const token_id of this.begin_suppress_tokens) {
+ batch_logits_data[token_id] = -Infinity;
+ }
+ }
+ }
+ return logits;
+ }
+ }
+ class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
+ /**
+ * Constructs a new WhisperTimeStampLogitsProcessor.
+ * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model.
+ * @param {number[]} init_tokens The initial tokens of the input sequence.
+ */
+ constructor(generate_config, init_tokens) {
+ super();
+ this.eos_token_id = Array.isArray(generate_config.eos_token_id) ? generate_config.eos_token_id[0] : generate_config.eos_token_id;
+ this.no_timestamps_token_id = generate_config.no_timestamps_token_id;
+ this.timestamp_begin = this.no_timestamps_token_id + 1;
+ this.begin_index = init_tokens.length;
+ if (init_tokens.at(-1) === this.no_timestamps_token_id) {
+ this.begin_index -= 1;
+ }
+ this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;
+ }
+ /**
+ * Modify the logits to handle timestamp tokens.
+ * @param {bigint[][]} input_ids The input sequence of tokens.
+ * @param {Tensor} logits The logits output by the model.
+ * @returns {Tensor} The modified logits.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ batch_logits_data[this.no_timestamps_token_id] = -Infinity;
+ if (input_ids[i].length === this.begin_index - 1) {
+ batch_logits_data.fill(-Infinity);
+ batch_logits_data[this.timestamp_begin] = 0;
+ continue;
+ }
+ const seq = input_ids[i].slice(this.begin_index);
+ const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;
+ const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;
+ if (last_was_timestamp) {
+ if (penultimate_was_timestamp) {
+ batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity);
+ } else {
+ batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity);
+ }
+ }
+ if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) {
+ const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;
+ batch_logits_data.subarray(last_allowed + 1).fill(-Infinity);
+ }
+ const logprobs = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.log_softmax)(batch_logits_data);
+ const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));
+ const max_text_token_logprob = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logprobs.subarray(0, this.timestamp_begin))[0];
+ if (timestamp_logprob > max_text_token_logprob) {
+ batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity);
+ }
+ }
+ return logits;
+ }
+ }
+ class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a NoRepeatNGramLogitsProcessor.
+ * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
+ */
+ constructor(no_repeat_ngram_size) {
+ super();
+ this.no_repeat_ngram_size = no_repeat_ngram_size;
+ }
+ /**
+ * Generate n-grams from a sequence of token ids.
+ * @param {bigint[]} prevInputIds List of previous input ids
+ * @returns {Map} Map of generated n-grams
+ */
+ getNgrams(prevInputIds) {
+ const curLen = prevInputIds.length;
+ const ngrams = [];
+ for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {
+ const ngram = [];
+ for (let k2 = 0; k2 < this.no_repeat_ngram_size; ++k2) {
+ ngram.push(prevInputIds[j + k2]);
+ }
+ ngrams.push(ngram.map(Number));
+ }
+ const generatedNgram = /* @__PURE__ */ new Map();
+ for (const ngram of ngrams) {
+ const prevNgram = ngram.slice(0, ngram.length - 1);
+ const prevNgramKey = JSON.stringify(prevNgram);
+ const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];
+ prevNgramValue.push(ngram[ngram.length - 1]);
+ generatedNgram.set(prevNgramKey, prevNgramValue);
+ }
+ return generatedNgram;
+ }
+ /**
+ * Generate n-grams from a sequence of token ids.
+ * @param {Map} bannedNgrams Map of banned n-grams
+ * @param {bigint[]} prevInputIds List of previous input ids
+ * @returns {number[]} Map of generated n-grams
+ */
+ getGeneratedNgrams(bannedNgrams, prevInputIds) {
+ const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);
+ const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? [];
+ return banned;
+ }
+ /**
+ * Calculate banned n-gram tokens
+ * @param {bigint[]} prevInputIds List of previous input ids
+ * @returns {number[]} Map of generated n-grams
+ */
+ calcBannedNgramTokens(prevInputIds) {
+ const bannedTokens = [];
+ if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {
+ return bannedTokens;
+ } else {
+ const generatedNgrams = this.getNgrams(prevInputIds);
+ const bannedTokens2 = this.getGeneratedNgrams(generatedNgrams, prevInputIds);
+ return bannedTokens2;
+ }
+ }
+ /**
+ * Apply the no-repeat-ngram processor to the logits.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The logits with no-repeat-ngram processing.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ const bannedTokens = this.calcBannedNgramTokens(input_ids[i]);
+ for (const token of bannedTokens) {
+ batch_logits_data[token] = -Infinity;
+ }
+ }
+ return logits;
+ }
+ }
+ class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a RepetitionPenaltyLogitsProcessor.
+ * @param {number} penalty The parameter for repetition penalty.
+ * - 1.0 means no penalty. Above 1.0 penalizes previously generated tokens.
+ * - Between 0.0 and 1.0 rewards previously generated tokens.
+ */
+ constructor(penalty) {
+ super();
+ this.penalty = penalty;
+ }
+ /**
+ * Apply the repetition penalty to the logits.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The logits with repetition penalty processing.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ for (const input_id of new Set(input_ids[i])) {
+ const token = Number(input_id);
+ if (batch_logits_data[token] < 0) {
+ batch_logits_data[token] *= this.penalty;
+ } else {
+ batch_logits_data[token] /= this.penalty;
+ }
+ }
+ }
+ return logits;
+ }
+ }
+ class MinLengthLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a MinLengthLogitsProcessor.
+ * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
+ * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
+ */
+ constructor(min_length, eos_token_id) {
+ super();
+ this.min_length = min_length;
+ this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
+ }
+ /**
+ * Apply logit processor.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The processed logits.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ if (input_ids[i].length < this.min_length) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ for (const eos_token of this.eos_token_id) {
+ batch_logits_data[eos_token] = -Infinity;
+ }
+ }
+ }
+ return logits;
+ }
+ }
+ class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a MinNewTokensLengthLogitsProcessor.
+ * @param {number} prompt_length_to_skip The input tokens length.
+ * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
+ * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
+ */
+ constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {
+ super();
+ this.prompt_length_to_skip = prompt_length_to_skip;
+ this.min_new_tokens = min_new_tokens;
+ this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
+ }
+ /**
+ * Apply logit processor.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The processed logits.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip;
+ if (new_tokens_length < this.min_new_tokens) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ for (const eos_token of this.eos_token_id) {
+ batch_logits_data[eos_token] = -Infinity;
+ }
+ }
+ }
+ return logits;
+ }
+ }
+ class NoBadWordsLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a `NoBadWordsLogitsProcessor`.
+ * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
+ * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ */
+ constructor(bad_words_ids, eos_token_id) {
+ super();
+ this.bad_words_ids = bad_words_ids;
+ this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
+ }
+ /**
+ * Apply logit processor.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The processed logits.
+ */
+ _call(input_ids, logits) {
+ for (let i = 0; i < input_ids.length; ++i) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits[i].data
+ );
+ const ids = input_ids[i];
+ for (const bad_word_ids of this.bad_words_ids) {
+ if (ids.length < bad_word_ids.length - 1) continue;
+ let mark = true;
+ for (let j = 1; j <= bad_word_ids.length - 1; ++j) {
+ if (bad_word_ids.at(-j - 1) != ids.at(-j)) {
+ mark = false;
+ break;
+ }
+ }
+ if (mark) {
+ batch_logits_data[bad_word_ids.at(-1)] = -Infinity;
+ }
+ }
+ }
+ return logits;
+ }
+ }
+ class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor {
+ /**
+ * Create a `ClassifierFreeGuidanceLogitsProcessor`.
+ * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
+ * Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ * prompt, usually at the expense of poorer quality.
+ */
+ constructor(guidance_scale) {
+ super();
+ if (guidance_scale <= 1) {
+ throw new Error(
+ `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.`
+ );
+ }
+ this.guidance_scale = guidance_scale;
+ }
+ /**
+ * Apply logit processor.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The processed logits.
+ */
+ _call(input_ids, logits) {
+ if (logits.dims[0] !== 2 * input_ids.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 ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.`
+ );
+ }
+ const unguided_bsz = input_ids.length;
+ const cond_logits = logits.slice([0, unguided_bsz], null);
+ const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null);
+ for (let i = 0; i < uncond_logits.data.length; ++i) {
+ uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale;
+ }
+ return uncond_logits;
+ }
+ }
+ class TemperatureLogitsWarper extends LogitsWarper {
+ /**
+ * Create a `TemperatureLogitsWarper`.
+ * @param {number} temperature Strictly positive float value used to modulate the logits distribution.
+ * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting
+ * all probability mass to the most likely token.
+ */
+ constructor(temperature) {
+ super();
+ if (typeof temperature !== "number" || temperature <= 0) {
+ let errorMessage = `\`temperature\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`;
+ if (temperature === 0) {
+ errorMessage += " If you're looking for greedy decoding strategies, set `do_sample=false`.";
+ }
+ }
+ this.temperature = temperature;
+ }
+ /**
+ * Apply logit warper.
+ * @param {bigint[][]} input_ids The input IDs.
+ * @param {Tensor} logits The logits.
+ * @returns {Tensor} The processed logits.
+ */
+ _call(input_ids, logits) {
+ const batch_logits_data = (
+ /** @type {Float32Array} */
+ logits.data
+ );
+ for (let i = 0; i < batch_logits_data.length; ++i) {
+ batch_logits_data[i] /= this.temperature;
+ }
+ return logits;
+ }
+ }
+ class TopPLogitsWarper extends LogitsWarper {
+ /**
+ * Create a `TopPLogitsWarper`.
+ * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with
+ * probabilities that add up to `top_p` or higher are kept for generation.
+ * @param {Object} options Additional options for the top-p sampling.
+ * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.
+ * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.
+ */
+ constructor(top_p, {
+ filter_value = -Infinity,
+ min_tokens_to_keep = 1
+ } = {}) {
+ super();
+ if (top_p < 0 || top_p > 1) {
+ throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${top_p}`);
+ }
+ if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) {
+ throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${min_tokens_to_keep}`);
+ }
+ this.top_p = top_p;
+ this.filter_value = filter_value;
+ this.min_tokens_to_keep = min_tokens_to_keep;
+ }
+ }
+ class TopKLogitsWarper extends LogitsWarper {
+ /**
+ * Create a `TopKLogitsWarper`.
+ * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation.
+ * @param {Object} options Additional options for the top-k sampling.
+ * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.
+ * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.
+ */
+ constructor(top_k, {
+ filter_value = -Infinity,
+ min_tokens_to_keep = 1
+ } = {}) {
+ super();
+ if (!Number.isInteger(top_k) || top_k < 0) {
+ throw new Error(`\`top_k\` must be a positive integer, but is ${top_k}`);
+ }
+ this.top_k = Math.max(top_k, min_tokens_to_keep);
+ this.filter_value = filter_value;
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/generation/logits_sampler.js": (
+ /*!******************************************!*\
+ !*** ./src/generation/logits_sampler.js ***!
+ \******************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ LogitsSampler: () => (
+ /* binding */
+ LogitsSampler
+ )
+ /* harmony export */
+ });
+ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/generic.js */
+ "./src/utils/generic.js"
+ );
+ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ../utils/tensor.js */
+ "./src/utils/tensor.js"
+ );
+ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! ../utils/maths.js */
+ "./src/utils/maths.js"
+ );
+ var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2(
+ /*! ../generation/configuration_utils.js */
+ "./src/generation/configuration_utils.js"
+ );
+ class LogitsSampler extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
+ /**
+ * Creates a new Sampler object with the specified generation config.
+ * @param {GenerationConfig} generation_config The generation config.
+ */
+ constructor(generation_config) {
+ super();
+ this.generation_config = generation_config;
+ }
+ /**
+ * Executes the sampler, using the specified logits.
+ * @param {Tensor} logits
+ * @returns {Promise<[bigint, number][]>}
+ */
+ async _call(logits) {
+ return this.sample(logits);
+ }
+ /**
+ * Abstract method for sampling the logits.
+ * @param {Tensor} logits
+ * @throws {Error} If not implemented in subclass.
+ * @returns {Promise<[bigint, number][]>}
+ */
+ async sample(logits) {
+ throw Error("sample should be implemented in subclasses.");
+ }
+ /**
+ * Returns the specified logits as an array, with temperature applied.
+ * @param {Tensor} logits
+ * @param {number} index
+ * @returns {Float32Array}
+ */
+ getLogits(logits, index) {
+ let vocabSize = logits.dims.at(-1);
+ let logs = (
+ /** @type {Float32Array} */
+ logits.data
+ );
+ if (index === -1) {
+ logs = logs.slice(-vocabSize);
+ } else {
+ let startIndex = index * vocabSize;
+ logs = logs.slice(startIndex, startIndex + vocabSize);
+ }
+ return logs;
+ }
+ /**
+ * Selects an item randomly based on the specified probabilities.
+ * @param {import("../transformers.js").DataArray} probabilities An array of probabilities to use for selection.
+ * @returns {number} The index of the selected item.
+ */
+ randomSelect(probabilities) {
+ let sumProbabilities = 0;
+ for (let i = 0; i < probabilities.length; ++i) {
+ sumProbabilities += probabilities[i];
+ }
+ let r = Math.random() * sumProbabilities;
+ for (let i = 0; i < probabilities.length; ++i) {
+ r -= probabilities[i];
+ if (r <= 0) {
+ return i;
+ }
+ }
+ return 0;
+ }
+ /**
+ * Returns a Sampler object based on the specified options.
+ * @param {GenerationConfig} generation_config An object containing options for the sampler.
+ * @returns {LogitsSampler} A Sampler object.
+ */
+ static getSampler(generation_config) {
+ if (generation_config.do_sample) {
+ return new MultinomialSampler(generation_config);
+ } else if (generation_config.num_beams > 1) {
+ return new BeamSearchSampler(generation_config);
+ } else {
+ if (generation_config.num_return_sequences > 1) {
+ throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`);
+ }
+ return new GreedySampler(generation_config);
+ }
+ }
+ }
+ class GreedySampler extends LogitsSampler {
+ /**
+ * Sample the maximum probability of a given logits tensor.
+ * @param {Tensor} logits
+ * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).
+ */
+ async sample(logits) {
+ const argmax = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logits.data)[1];
+ return [
+ [BigInt(argmax), 0]
+ ];
+ }
+ }
+ class MultinomialSampler extends LogitsSampler {
+ /**
+ * Sample from the logits.
+ * @param {Tensor} logits
+ * @returns {Promise<[bigint, number][]>}
+ */
+ async sample(logits) {
+ let k2 = logits.dims.at(-1);
+ if (this.generation_config.top_k > 0) {
+ k2 = Math.min(this.generation_config.top_k, k2);
+ }
+ const [v, i] = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.topk)(logits, k2);
+ const probabilities = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(
+ /** @type {Float32Array} */
+ v.data
+ );
+ return Array.from({ length: this.generation_config.num_beams }, () => {
+ const sampledIndex = this.randomSelect(probabilities);
+ return [
+ i.data[sampledIndex],
+ // token id
+ Math.log(probabilities[sampledIndex])
+ // score
+ ];
+ });
+ }
+ }
+ class BeamSearchSampler extends LogitsSampler {
+ /**
+ * Sample from the logits.
+ * @param {Tensor} logits
+ * @returns {Promise<[bigint, number][]>}
+ */
+ async sample(logits) {
+ let k2 = logits.dims.at(-1);
+ if (this.generation_config.top_k > 0) {
+ k2 = Math.min(this.generation_config.top_k, k2);
+ }
+ const [v, i] = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.topk)(logits, k2);
+ const probabilities = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(
+ /** @type {Float32Array} */
+ v.data
+ );
+ return Array.from({ length: this.generation_config.num_beams }, (_, x) => {
+ return [
+ i.data[x],
+ // token id
+ Math.log(probabilities[x])
+ // score
+ ];
+ });
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/generation/stopping_criteria.js": (
+ /*!*********************************************!*\
+ !*** ./src/generation/stopping_criteria.js ***!
+ \*********************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ EosTokenCriteria: () => (
+ /* binding */
+ EosTokenCriteria
+ ),
+ /* harmony export */
+ InterruptableStoppingCriteria: () => (
+ /* binding */
+ InterruptableStoppingCriteria
+ ),
+ /* harmony export */
+ MaxLengthCriteria: () => (
+ /* binding */
+ MaxLengthCriteria
+ ),
+ /* harmony export */
+ StoppingCriteria: () => (
+ /* binding */
+ StoppingCriteria
+ ),
+ /* harmony export */
+ StoppingCriteriaList: () => (
+ /* binding */
+ StoppingCriteriaList
+ )
+ /* harmony export */
+ });
+ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/generic.js */
+ "./src/utils/generic.js"
+ );
+ class StoppingCriteria extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
+ /**
+ *
+ * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`):
+ * Indices of input sequence tokens in the vocabulary.
+ * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`):
+ * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
+ * or scores for each vocabulary token after SoftMax.
+ * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped.
+ */
+ _call(input_ids, scores) {
+ throw Error("StoppingCriteria needs to be subclassed");
+ }
+ }
+ class StoppingCriteriaList extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable {
+ /**
+ * Constructs a new instance of `StoppingCriteriaList`.
+ */
+ constructor() {
+ super();
+ this.criteria = [];
+ }
+ /**
+ * Adds a new stopping criterion to the list.
+ *
+ * @param {StoppingCriteria} item The stopping criterion to add.
+ */
+ push(item) {
+ this.criteria.push(item);
+ }
+ /**
+ * Adds multiple stopping criteria to the list.
+ *
+ * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add.
+ */
+ extend(items) {
+ if (items instanceof StoppingCriteriaList) {
+ items = items.criteria;
+ } else if (items instanceof StoppingCriteria) {
+ items = [items];
+ }
+ this.criteria.push(...items);
+ }
+ _call(input_ids, scores) {
+ const is_done = new Array(input_ids.length).fill(false);
+ for (const criterion of this.criteria) {
+ const criterion_done = criterion(input_ids, scores);
+ for (let i = 0; i < is_done.length; ++i) {
+ is_done[i] || (is_done[i] = criterion_done[i]);
+ }
+ }
+ return is_done;
+ }
+ [Symbol.iterator]() {
+ return this.criteria.values();
+ }
+ }
+ class MaxLengthCriteria extends StoppingCriteria {
+ /**
+ *
+ * @param {number} max_length The maximum length that the output sequence can have in number of tokens.
+ * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.
+ */
+ constructor(max_length, max_position_embeddings = null) {
+ super();
+ this.max_length = max_length;
+ this.max_position_embeddings = max_position_embeddings;
+ }
+ _call(input_ids) {
+ return input_ids.map((ids) => ids.length >= this.max_length);
+ }
+ }
+ class EosTokenCriteria extends StoppingCriteria {
+ /**
+ *
+ * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token.
+ * Optionally, use a list to set multiple *end-of-sequence* tokens.
+ */
+ constructor(eos_token_id) {
+ super();
+ if (!Array.isArray(eos_token_id)) {
+ eos_token_id = [eos_token_id];
+ }
+ this.eos_token_id = eos_token_id;
+ }
+ /**
+ *
+ * @param {number[][]} input_ids
+ * @param {number[][]} scores
+ * @returns {boolean[]}
+ */
+ _call(input_ids, scores) {
+ return input_ids.map((ids) => {
+ const last = ids.at(-1);
+ return this.eos_token_id.some((eos_id) => last == eos_id);
+ });
+ }
+ }
+ class InterruptableStoppingCriteria extends StoppingCriteria {
+ constructor() {
+ super();
+ this.interrupted = false;
+ }
+ interrupt() {
+ this.interrupted = true;
+ }
+ reset() {
+ this.interrupted = false;
+ }
+ _call(input_ids, scores) {
+ return new Array(input_ids.length).fill(this.interrupted);
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/generation/streamers.js": (
+ /*!*************************************!*\
+ !*** ./src/generation/streamers.js ***!
+ \*************************************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ BaseStreamer: () => (
+ /* binding */
+ BaseStreamer
+ ),
+ /* harmony export */
+ TextStreamer: () => (
+ /* binding */
+ TextStreamer
+ ),
+ /* harmony export */
+ WhisperTextStreamer: () => (
+ /* binding */
+ WhisperTextStreamer
+ )
+ /* harmony export */
+ });
+ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ../utils/core.js */
+ "./src/utils/core.js"
+ );
+ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ../tokenizers.js */
+ "./src/tokenizers.js"
+ );
+ var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! ../env.js */
+ "./src/env.js"
+ );
+ class BaseStreamer {
+ /**
+ * Function that is called by `.generate()` to push new tokens
+ * @param {bigint[][]} value
+ */
+ put(value) {
+ throw Error("Not implemented");
+ }
+ /**
+ * Function that is called by `.generate()` to signal the end of generation
+ */
+ end() {
+ throw Error("Not implemented");
+ }
+ }
+ const stdout_write = _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_PROCESS_AVAILABLE ? (x) => process.stdout.write(x) : (x) => console.log(x);
+ class TextStreamer extends BaseStreamer {
+ /**
+ *
+ * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer
+ * @param {Object} options
+ * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens
+ * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding
+ * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display
+ * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated
+ * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method
+ */
+ constructor(tokenizer, {
+ skip_prompt = false,
+ callback_function = null,
+ token_callback_function = null,
+ skip_special_tokens = true,
+ decode_kwargs = {},
+ ...kwargs
+ } = {}) {
+ super();
+ this.tokenizer = tokenizer;
+ this.skip_prompt = skip_prompt;
+ this.callback_function = callback_function ?? stdout_write;
+ this.token_callback_function = token_callback_function;
+ this.decode_kwargs = { skip_special_tokens, ...decode_kwargs, ...kwargs };
+ this.token_cache = [];
+ this.print_len = 0;
+ this.next_tokens_are_prompt = true;
+ }
+ /**
+ * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.
+ * @param {bigint[][]} value
+ */
+ put(value) {
+ if (value.length > 1) {
+ throw Error("TextStreamer only supports batch size of 1");
+ }
+ const is_prompt = this.next_tokens_are_prompt;
+ if (is_prompt) {
+ this.next_tokens_are_prompt = false;
+ if (this.skip_prompt) return;
+ }
+ const tokens = value[0];
+ this.token_callback_function?.(tokens);
+ this.token_cache = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(this.token_cache, tokens);
+ const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);
+ let printable_text;
+ if (is_prompt || text.endsWith("\n")) {
+ printable_text = text.slice(this.print_len);
+ this.token_cache = [];
+ this.print_len = 0;
+ } else if (text.length > 0 && (0, _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.is_chinese_char)(text.charCodeAt(text.length - 1))) {
+ printable_text = text.slice(this.print_len);
+ this.print_len += printable_text.length;
+ } else {
+ printable_text = text.slice(this.print_len, text.lastIndexOf(" ") + 1);
+ this.print_len += printable_text.length;
+ }
+ this.on_finalized_text(printable_text, false);
+ }
+ /**
+ * Flushes any remaining cache and prints a newline to stdout.
+ */
+ end() {
+ let printable_text;
+ if (this.token_cache.length > 0) {
+ const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);
+ printable_text = text.slice(this.print_len);
+ this.token_cache = [];
+ this.print_len = 0;
+ } else {
+ printable_text = "";
+ }
+ this.next_tokens_are_prompt = true;
+ this.on_finalized_text(printable_text, true);
+ }
+ /**
+ * Prints the new text to stdout. If the stream is ending, also prints a newline.
+ * @param {string} text
+ * @param {boolean} stream_end
+ */
+ on_finalized_text(text, stream_end) {
+ if (text.length > 0) {
+ this.callback_function?.(text);
+ }
+ if (stream_end && this.callback_function === stdout_write && _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_PROCESS_AVAILABLE) {
+ this.callback_function?.("\n");
+ }
+ }
+ }
+ class WhisperTextStreamer extends TextStreamer {
+ /**
+ * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer
+ * @param {Object} options
+ * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens
+ * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display
+ * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated
+ * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts
+ * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends
+ * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized
+ * @param {number} [options.time_precision=0.02] Precision of the timestamps
+ * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding
+ * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method
+ */
+ constructor(tokenizer, {
+ skip_prompt = false,
+ callback_function = null,
+ token_callback_function = null,
+ on_chunk_start = null,
+ on_chunk_end = null,
+ on_finalize = null,
+ time_precision = 0.02,
+ skip_special_tokens = true,
+ decode_kwargs = {}
+ } = {}) {
+ super(tokenizer, {
+ skip_prompt,
+ skip_special_tokens,
+ callback_function,
+ token_callback_function,
+ decode_kwargs
+ });
+ this.timestamp_begin = tokenizer.timestamp_begin;
+ this.on_chunk_start = on_chunk_start;
+ this.on_chunk_end = on_chunk_end;
+ this.on_finalize = on_finalize;
+ this.time_precision = time_precision;
+ this.waiting_for_timestamp = false;
+ }
+ /**
+ * @param {bigint[][]} value
+ */
+ put(value) {
+ if (value.length > 1) {
+ throw Error("WhisperTextStreamer only supports batch size of 1");
+ }
+ const tokens = value[0];
+ if (tokens.length === 1) {
+ const offset = Number(tokens[0]) - this.timestamp_begin;
+ if (offset >= 0) {
+ const time = offset * this.time_precision;
+ if (this.waiting_for_timestamp) {
+ this.on_chunk_end?.(time);
+ } else {
+ this.on_chunk_start?.(time);
+ }
+ this.waiting_for_timestamp = !this.waiting_for_timestamp;
+ this.token_callback_function?.(tokens);
+ return;
+ }
+ }
+ return super.put(value);
+ }
+ end() {
+ super.end();
+ this.on_finalize?.();
+ }
+ }
+ })
+ ),
+ /***/
+ "./src/models.js": (
+ /*!***********************!*\
+ !*** ./src/models.js ***!
+ \***********************/
+ /***/
+ ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => {
+ __webpack_require__2.r(__webpack_exports__2);
+ __webpack_require__2.d(__webpack_exports__2, {
+ /* harmony export */
+ ASTForAudioClassification: () => (
+ /* binding */
+ ASTForAudioClassification
+ ),
+ /* harmony export */
+ ASTModel: () => (
+ /* binding */
+ ASTModel
+ ),
+ /* harmony export */
+ ASTPreTrainedModel: () => (
+ /* binding */
+ ASTPreTrainedModel
+ ),
+ /* harmony export */
+ AlbertForMaskedLM: () => (
+ /* binding */
+ AlbertForMaskedLM
+ ),
+ /* harmony export */
+ AlbertForQuestionAnswering: () => (
+ /* binding */
+ AlbertForQuestionAnswering
+ ),
+ /* harmony export */
+ AlbertForSequenceClassification: () => (
+ /* binding */
+ AlbertForSequenceClassification
+ ),
+ /* harmony export */
+ AlbertModel: () => (
+ /* binding */
+ AlbertModel
+ ),
+ /* harmony export */
+ AlbertPreTrainedModel: () => (
+ /* binding */
+ AlbertPreTrainedModel
+ ),
+ /* harmony export */
+ ArceeForCausalLM: () => (
+ /* binding */
+ ArceeForCausalLM
+ ),
+ /* harmony export */
+ ArceeModel: () => (
+ /* binding */
+ ArceeModel
+ ),
+ /* harmony export */
+ ArceePreTrainedModel: () => (
+ /* binding */
+ ArceePreTrainedModel
+ ),
+ /* harmony export */
+ AutoModel: () => (
+ /* binding */
+ AutoModel
+ ),
+ /* harmony export */
+ AutoModelForAudioClassification: () => (
+ /* binding */
+ AutoModelForAudioClassification
+ ),
+ /* harmony export */
+ AutoModelForAudioFrameClassification: () => (
+ /* binding */
+ AutoModelForAudioFrameClassification
+ ),
+ /* harmony export */
+ AutoModelForAudioTextToText: () => (
+ /* binding */
+ AutoModelForAudioTextToText
+ ),
+ /* harmony export */
+ AutoModelForCTC: () => (
+ /* binding */
+ AutoModelForCTC
+ ),
+ /* harmony export */
+ AutoModelForCausalLM: () => (
+ /* binding */
+ AutoModelForCausalLM
+ ),
+ /* harmony export */
+ AutoModelForDepthEstimation: () => (
+ /* binding */
+ AutoModelForDepthEstimation
+ ),
+ /* harmony export */
+ AutoModelForDocumentQuestionAnswering: () => (
+ /* binding */
+ AutoModelForDocumentQuestionAnswering
+ ),
+ /* harmony export */
+ AutoModelForImageClassification: () => (
+ /* binding */
+ AutoModelForImageClassification
+ ),
+ /* harmony export */
+ AutoModelForImageFeatureExtraction: () => (
+ /* binding */
+ AutoModelForImageFeatureExtraction
+ ),
+ /* harmony export */
+ AutoModelForImageMatting: () => (
+ /* binding */
+ AutoModelForImageMatting
+ ),
+ /* harmony export */
+ AutoModelForImageSegmentation: () => (
+ /* binding */
+ AutoModelForImageSegmentation
+ ),
+ /* harmony export */
+ AutoModelForImageTextToText: () => (
+ /* binding */
+ AutoModelForImageTextToText
+ ),
+ /* harmony export */
+ AutoModelForImageToImage: () => (
+ /* binding */
+ AutoModelForImageToImage
+ ),
+ /* harmony export */
+ AutoModelForMaskGeneration: () => (
+ /* binding */
+ AutoModelForMaskGeneration
+ ),
+ /* harmony export */
+ AutoModelForMaskedLM: () => (
+ /* binding */
+ AutoModelForMaskedLM
+ ),
+ /* harmony export */
+ AutoModelForNormalEstimation: () => (
+ /* binding */
+ AutoModelForNormalEstimation
+ ),
+ /* harmony export */
+ AutoModelForObjectDetection: () => (
+ /* binding */
+ AutoModelForObjectDetection
+ ),
+ /* harmony export */
+ AutoModelForPoseEstimation: () => (
+ /* binding */
+ AutoModelForPoseEstimation
+ ),
+ /* harmony export */
+ AutoModelForQuestionAnswering: () => (
+ /* binding */
+ AutoModelForQuestionAnswering
+ ),
+ /* harmony export */
+ AutoModelForSemanticSegmentation: () => (
+ /* binding */
+ AutoModelForSemanticSegmentation
+ ),
+ /* harmony export */
+ AutoModelForSeq2SeqLM: () => (
+ /* binding */
+ AutoModelForSeq2SeqLM
+ ),
+ /* harmony export */
+ AutoModelForSequenceClassification: () => (
+ /* binding */
+ AutoModelForSequenceClassification
+ ),
+ /* harmony export */
+ AutoModelForSpeechSeq2Seq: () => (
+ /* binding */
+ AutoModelForSpeechSeq2Seq
+ ),
+ /* harmony export */
+ AutoModelForTextToSpectrogram: () => (
+ /* binding */
+ AutoModelForTextToSpectrogram
+ ),
+ /* harmony export */
+ AutoModelForTextToWaveform: () => (
+ /* binding */
+ AutoModelForTextToWaveform
+ ),
+ /* harmony export */
+ AutoModelForTokenClassification: () => (
+ /* binding */
+ AutoModelForTokenClassification
+ ),
+ /* harmony export */
+ AutoModelForUniversalSegmentation: () => (
+ /* binding */
+ AutoModelForUniversalSegmentation
+ ),
+ /* harmony export */
+ AutoModelForVision2Seq: () => (
+ /* binding */
+ AutoModelForVision2Seq
+ ),
+ /* harmony export */
+ AutoModelForXVector: () => (
+ /* binding */
+ AutoModelForXVector
+ ),
+ /* harmony export */
+ AutoModelForZeroShotObjectDetection: () => (
+ /* binding */
+ AutoModelForZeroShotObjectDetection
+ ),
+ /* harmony export */
+ BartForConditionalGeneration: () => (
+ /* binding */
+ BartForConditionalGeneration
+ ),
+ /* harmony export */
+ BartForSequenceClassification: () => (
+ /* binding */
+ BartForSequenceClassification
+ ),
+ /* harmony export */
+ BartModel: () => (
+ /* binding */
+ BartModel
+ ),
+ /* harmony export */
+ BartPretrainedModel: () => (
+ /* binding */
+ BartPretrainedModel
+ ),
+ /* harmony export */
+ BaseModelOutput: () => (
+ /* binding */
+ BaseModelOutput
+ ),
+ /* harmony export */
+ BeitForImageClassification: () => (
+ /* binding */
+ BeitForImageClassification
+ ),
+ /* harmony export */
+ BeitModel: () => (
+ /* binding */
+ BeitModel
+ ),
+ /* harmony export */
+ BeitPreTrainedModel: () => (
+ /* binding */
+ BeitPreTrainedModel
+ ),
+ /* harmony export */
+ BertForMaskedLM: () => (
+ /* binding */
+ BertForMaskedLM
+ ),
+ /* harmony export */
+ BertForQuestionAnswering: () => (
+ /* binding */
+ BertForQuestionAnswering
+ ),
+ /* harmony export */
+ BertForSequenceClassification: () => (
+ /* binding */
+ BertForSequenceClassification
+ ),
+ /* harmony export */
+ BertForTokenClassification: () => (
+ /* binding */
+ BertForTokenClassification
+ ),
+ /* harmony export */
+ BertModel: () => (
+ /* binding */
+ BertModel
+ ),
+ /* harmony export */
+ BertPreTrainedModel: () => (
+ /* binding */
+ BertPreTrainedModel
+ ),
+ /* harmony export */
+ BlenderbotForConditionalGeneration: () => (
+ /* binding */
+ BlenderbotForConditionalGeneration
+ ),
+ /* harmony export */
+ BlenderbotModel: () => (
+ /* binding */
+ BlenderbotModel
+ ),
+ /* harmony export */
+ BlenderbotPreTrainedModel: () => (
+ /* binding */
+ BlenderbotPreTrainedModel
+ ),
+ /* harmony export */
+ BlenderbotSmallForConditionalGeneration: () => (
+ /* binding */
+ BlenderbotSmallForConditionalGeneration
+ ),
+ /* harmony export */
+ BlenderbotSmallModel: () => (
+ /* binding */
+ BlenderbotSmallModel
+ ),
+ /* harmony export */
+ BlenderbotSmallPreTrainedModel: () => (
+ /* binding */
+ BlenderbotSmallPreTrainedModel
+ ),
+ /* harmony export */
+ BloomForCausalLM: () => (
+ /* binding */
+ BloomForCausalLM
+ ),
+ /* harmony export */
+ BloomModel: () => (
+ /* binding */
+ BloomModel
+ ),
+ /* harmony export */
+ BloomPreTrainedModel: () => (
+ /* binding */
+ BloomPreTrainedModel
+ ),
+ /* harmony export */
+ CLIPModel: () => (
+ /* binding */
+ CLIPModel
+ ),
+ /* harmony export */
+ CLIPPreTrainedModel: () => (
+ /* binding */
+ CLIPPreTrainedModel
+ ),
+ /* harmony export */
+ CLIPSegForImageSegmentation: () => (
+ /* binding */
+ CLIPSegForImageSegmentation
+ ),
+ /* harmony export */
+ CLIPSegModel: () => (
+ /* binding */
+ CLIPSegModel
+ ),
+ /* harmony export */
+ CLIPSegPreTrainedModel: () => (
+ /* binding */
+ CLIPSegPreTrainedModel
+ ),
+ /* harmony export */
+ CLIPTextModel: () => (
+ /* binding */
+ CLIPTextModel
+ ),
+ /* harmony export */
+ CLIPTextModelWithProjection: () => (
+ /* binding */
+ CLIPTextModelWithProjection
+ ),
+ /* harmony export */
+ CLIPVisionModel: () => (
+ /* binding */
+ CLIPVisionModel
+ ),
+ /* harmony export */
+ CLIPVisionModelWithProjection: () => (
+ /* binding */
+ CLIPVisionModelWithProjection
+ ),
+ /* harmony export */
+ CamembertForMaskedLM: () => (
+ /* binding */
+ CamembertForMaskedLM
+ ),
+ /* harmony export */
+ CamembertForQuestionAnswering: () => (
+ /* binding */
+ CamembertForQuestionAnswering
+ ),
+ /* harmony export */
+ CamembertForSequenceClassification: () => (
+ /* binding */
+ CamembertForSequenceClassification
+ ),
+ /* harmony export */
+ CamembertForTokenClassification: () => (
+ /* binding */
+ CamembertForTokenClassification
+ ),
+ /* harmony export */
+ CamembertModel: () => (
+ /* binding */
+ CamembertModel
+ ),
+ /* harmony export */
+ CamembertPreTrainedModel: () => (
+ /* binding */
+ CamembertPreTrainedModel
+ ),
+ /* harmony export */
+ CausalLMOutput: () => (
+ /* binding */
+ CausalLMOutput
+ ),
+ /* harmony export */
+ CausalLMOutputWithPast: () => (
+ /* binding */
+ CausalLMOutputWithPast
+ ),
+ /* harmony export */
+ ChineseCLIPModel: () => (
+ /* binding */
+ ChineseCLIPModel
+ ),
+ /* harmony export */
+ ChineseCLIPPreTrainedModel: () => (
+ /* binding */
+ ChineseCLIPPreTrainedModel
+ ),
+ /* harmony export */
+ ClapAudioModelWithProjection: () => (
+ /* binding */
+ ClapAudioModelWithProjection
+ ),
+ /* harmony export */
+ ClapModel: () => (
+ /* binding */
+ ClapModel
+ ),
+ /* harmony export */
+ ClapPreTrainedModel: () => (
+ /* binding */
+ ClapPreTrainedModel
+ ),
+ /* harmony export */
+ ClapTextModelWithProjection: () => (
+ /* binding */
+ ClapTextModelWithProjection
+ ),
+ /* harmony export */
+ CodeGenForCausalLM: () => (
+ /* binding */
+ CodeGenForCausalLM
+ ),
+ /* harmony export */
+ CodeGenModel: () => (
+ /* binding */
+ CodeGenModel
+ ),
+ /* harmony export */
+ CodeGenPreTrainedModel: () => (
+ /* binding */
+ CodeGenPreTrainedModel
+ ),
+ /* harmony export */
+ CohereForCausalLM: () => (
+ /* binding */
+ CohereForCausalLM
+ ),
+ /* harmony export */
+ CohereModel: () => (
+ /* binding */
+ CohereModel
+ ),
+ /* harmony export */
+ CoherePreTrainedModel: () => (
+ /* binding */
+ CoherePreTrainedModel
+ ),
+ /* harmony export */
+ ConvBertForMaskedLM: () => (
+ /* binding */
+ ConvBertForMaskedLM
+ ),
+ /* harmony export */
+ ConvBertForQuestionAnswering: () => (
+ /* binding */
+ ConvBertForQuestionAnswering
+ ),
+ /* harmony export */
+ ConvBertForSequenceClassification: () => (
+ /* binding */
+ ConvBertForSequenceClassification
+ ),
+ /* harmony export */
+ ConvBertForTokenClassification: () => (
+ /* binding */
+ ConvBertForTokenClassification
+ ),
+ /* harmony export */
+ ConvBertModel: () => (
+ /* binding */
+ ConvBertModel
+ ),
+ /* harmony export */
+ ConvBertPreTrainedModel: () => (
+ /* binding */
+ ConvBertPreTrainedModel
+ ),
+ /* harmony export */
+ ConvNextForImageClassification: () => (
+ /* binding */
+ ConvNextForImageClassification
+ ),
+ /* harmony export */
+ ConvNextModel: () => (
+ /* binding */
+ ConvNextModel
+ ),
+ /* harmony export */
+ ConvNextPreTrainedModel: () => (
+ /* binding */
+ ConvNextPreTrainedModel
+ ),
+ /* harmony export */
+ ConvNextV2ForImageClassification: () => (
+ /* binding */
+ ConvNextV2ForImageClassification
+ ),
+ /* harmony export */
+ ConvNextV2Model: () => (
+ /* binding */
+ ConvNextV2Model
+ ),
+ /* harmony export */
+ ConvNextV2PreTrainedModel: () => (
+ /* binding */
+ ConvNextV2PreTrainedModel
+ ),
+ /* harmony export */
+ DFineForObjectDetection: () => (
+ /* binding */
+ DFineForObjectDetection
+ ),
+ /* harmony export */
+ DFineModel: () => (
+ /* binding */
+ DFineModel
+ ),
+ /* harmony export */
+ DFinePreTrainedModel: () => (
+ /* binding */
+ DFinePreTrainedModel
+ ),
+ /* harmony export */
+ DINOv3ConvNextModel: () => (
+ /* binding */
+ DINOv3ConvNextModel
+ ),
+ /* harmony export */
+ DINOv3ConvNextPreTrainedModel: () => (
+ /* binding */
+ DINOv3ConvNextPreTrainedModel
+ ),
+ /* harmony export */
+ DINOv3ViTModel: () => (
+ /* binding */
+ DINOv3ViTModel
+ ),
+ /* harmony export */
+ DINOv3ViTPreTrainedModel: () => (
+ /* binding */
+ DINOv3ViTPreTrainedModel
+ ),
+ /* harmony export */
+ DPTForDepthEstimation: () => (
+ /* binding */
+ DPTForDepthEstimation
+ ),
+ /* harmony export */
+ DPTModel: () => (
+ /* binding */
+ DPTModel
+ ),
+ /* harmony export */
+ DPTPreTrainedModel: () => (
+ /* binding */
+ DPTPreTrainedModel
+ ),
+ /* harmony export */
+ DacDecoderModel: () => (
+ /* binding */
+ DacDecoderModel
+ ),
+ /* harmony export */
+ DacDecoderOutput: () => (
+ /* binding */
+ DacDecoderOutput
+ ),
+ /* harmony export */
+ DacEncoderModel: () => (
+ /* binding */
+ DacEncoderModel
+ ),
+ /* harmony export */
+ DacEncoderOutput: () => (
+ /* binding */
+ DacEncoderOutput
+ ),
+ /* harmony export */
+ DacModel: () => (
+ /* binding */
+ DacModel
+ ),
+ /* harmony export */
+ DacPreTrainedModel: () => (
+ /* binding */
+ DacPreTrainedModel
+ ),
+ /* harmony export */
+ DebertaForMaskedLM: () => (
+ /* binding */
+ DebertaForMaskedLM
+ ),
+ /* harmony export */
+ DebertaForQuestionAnswering: () => (
+ /* binding */
+ DebertaForQuestionAnswering
+ ),
+ /* harmony export */
+ DebertaForSequenceClassification: () => (
+ /* binding */
+ DebertaForSequenceClassification
+ ),
+ /* harmony export */
+ DebertaForTokenClassification: () => (
+ /* binding */
+ DebertaForTokenClassification
+ ),
+ /* harmony export */
+ DebertaModel: () => (
+ /* binding */
+ DebertaModel
+ ),
+ /* harmony export */
+ DebertaPreTrainedModel: () => (
+ /* binding */
+ DebertaPreTrainedModel
+ ),
+ /* harmony export */
+ DebertaV2ForMaskedLM: () => (
+ /* binding */
+ DebertaV2ForMaskedLM
+ ),
+ /* harmony export */
+ DebertaV2ForQuestionAnswering: () => (
+ /* binding */
+ DebertaV2ForQuestionAnswering
+ ),
+ /* harmony export */
+ DebertaV2ForSequenceClassification: () => (
+ /* binding */
+ DebertaV2ForSequenceClassification
+ ),
+ /* harmony export */
+ DebertaV2ForTokenClassification: () => (
+ /* binding */
+ DebertaV2ForTokenClassification
+ ),
+ /* harmony export */
+ DebertaV2Model: () => (
+ /* binding */
+ DebertaV2Model
+ ),
+ /* harmony export */
+ DebertaV2PreTrainedModel: () => (
+ /* binding */
+ DebertaV2PreTrainedModel
+ ),
+ /* harmony export */
+ DecisionTransformerModel: () => (
+ /* binding */
+ DecisionTransformerModel
+ ),
+ /* harmony export */
+ DecisionTransformerPreTrainedModel: () => (
+ /* binding */
+ DecisionTransformerPreTrainedModel
+ ),
+ /* harmony export */
+ DeiTForImageClassification: () => (
+ /* binding */
+ DeiTForImageClassification
+ ),
+ /* harmony export */
+ DeiTModel: () => (
+ /* binding */
+ DeiTModel
+ ),
+ /* harmony export */
+ DeiTPreTrainedModel: () => (
+ /* binding */
+ DeiTPreTrainedModel
+ ),
+ /* harmony export */
+ DepthAnythingForDepthEstimation: () => (
+ /* binding */
+ DepthAnythingForDepthEstimation
+ ),
+ /* harmony export */
+ DepthAnythingPreTrainedModel: () => (
+ /* binding */
+ DepthAnythingPreTrainedModel
+ ),
+ /* harmony export */
+ DepthProForDepthEstimation: () => (
+ /* binding */
+ DepthProForDepthEstimation
+ ),
+ /* harmony export */
+ DepthProPreTrainedModel: () => (
+ /* binding */
+ DepthProPreTrainedModel
+ ),
+ /* harmony export */
+ DetrForObjectDetection: () => (
+ /* binding */
+ DetrForObjectDetection
+ ),
+ /* harmony export */
+ DetrForSegmentation: () => (
+ /* binding */
+ DetrForSegmentation
+ ),
+ /* harmony export */
+ DetrModel: () => (
+ /* binding */
+ DetrModel
+ ),
+ /* harmony export */
+ DetrObjectDetectionOutput: () => (
+ /* binding */
+ DetrObjectDetectionOutput
+ ),
+ /* harmony export */
+ DetrPreTrainedModel: () => (
+ /* binding */
+ DetrPreTrainedModel
+ ),
+ /* harmony export */
+ DetrSegmentationOutput: () => (
+ /* binding */
+ DetrSegmentationOutput
+ ),
+ /* harmony export */
+ Dinov2ForImageClassification: () => (
+ /* binding */
+ Dinov2ForImageClassification
+ ),
+ /* harmony export */
+ Dinov2Model: () => (
+ /* binding */
+ Dinov2Model
+ ),
+ /* harmony export */
+ Dinov2PreTrainedModel: () => (
+ /* binding */
+ Dinov2PreTrainedModel
+ ),
+ /* harmony export */
+ Dinov2WithRegistersForImageClassification: () => (
+ /* binding */
+ Dinov2WithRegistersForImageClassification
+ ),
+ /* harmony export */
+ Dinov2WithRegistersModel: () => (
+ /* binding */
+ Dinov2WithRegistersModel
+ ),
+ /* harmony export */
+ Dinov2WithRegistersPreTrainedModel: () => (
+ /* binding */
+ Dinov2WithRegistersPreTrainedModel
+ ),
+ /* harmony export */
+ DistilBertForMaskedLM: () => (
+ /* binding */
+ DistilBertForMaskedLM
+ ),
+ /* harmony export */
+ DistilBertForQuestionAnswering: () => (
+ /* binding */
+ DistilBertForQuestionAnswering
+ ),
+ /* harmony export */
+ DistilBertForSequenceClassification: () => (
+ /* binding */
+ DistilBertForSequenceClassification
+ ),
+ /* harmony export */
+ DistilBertForTokenClassification: () => (
+ /* binding */
+ DistilBertForTokenClassification
+ ),
+ /* harmony export */
+ DistilBertModel: () => (
+ /* binding */
+ DistilBertModel
+ ),
+ /* harmony export */
+ DistilBertPreTrainedModel: () => (
+ /* binding */
+ DistilBertPreTrainedModel
+ ),
+ /* harmony export */
+ DonutSwinModel: () => (
+ /* binding */
+ DonutSwinModel
+ ),
+ /* harmony export */
+ DonutSwinPreTrainedModel: () => (
+ /* binding */
+ DonutSwinPreTrainedModel
+ ),
+ /* harmony export */
+ EdgeTamModel: () => (
+ /* binding */
+ EdgeTamModel
+ ),
+ /* harmony export */
+ EfficientNetForImageClassification: () => (
+ /* binding */
+ EfficientNetForImageClassification
+ ),
+ /* harmony export */
+ EfficientNetModel: () => (
+ /* binding */
+ EfficientNetModel
+ ),
+ /* harmony export */
+ EfficientNetPreTrainedModel: () => (
+ /* binding */
+ EfficientNetPreTrainedModel
+ ),
+ /* harmony export */
+ ElectraForMaskedLM: () => (
+ /* binding */
+ ElectraForMaskedLM
+ ),
+ /* harmony export */
+ ElectraForQuestionAnswering: () => (
+ /* binding */
+ ElectraForQuestionAnswering
+ ),
+ /* harmony export */
+ ElectraForSequenceClassification: () => (
+ /* binding */
+ ElectraForSequenceClassification
+ ),
+ /* harmony export */
+ ElectraForTokenClassification: () => (
+ /* binding */
+ ElectraForTokenClassification
+ ),
+ /* harmony export */
+ ElectraModel: () => (
+ /* binding */
+ ElectraModel
+ ),
+ /* harmony export */
+ ElectraPreTrainedModel: () => (
+ /* binding */
+ ElectraPreTrainedModel
+ ),
+ /* harmony export */
+ Ernie4_5ForCausalLM: () => (
+ /* binding */
+ Ernie4_5ForCausalLM
+ ),
+ /* harmony export */
+ Ernie4_5Model: () => (
+ /* binding */
+ Ernie4_5Model
+ ),
+ /* harmony export */
+ Ernie4_5PreTrainedModel: () => (
+ /* binding */
+ Ernie4_5PreTrainedModel
+ ),
+ /* harmony export */
+ EsmForMaskedLM: () => (
+ /* binding */
+ EsmForMaskedLM
+ ),
+ /* harmony export */
+ EsmForSequenceClassification: () => (
+ /* binding */
+ EsmForSequenceClassification
+ ),
+ /* harmony export */
+ EsmForTokenClassification: () => (
+ /* binding */
+ EsmForTokenClassification
+ ),
+ /* harmony export */
+ EsmModel: () => (
+ /* binding */
+ EsmModel
+ ),
+ /* harmony export */
+ EsmPreTrainedModel: () => (
+ /* binding */
+ EsmPreTrainedModel
+ ),
+ /* harmony export */
+ ExaoneForCausalLM: () => (
+ /* binding */
+ ExaoneForCausalLM
+ ),
+ /* harmony export */
+ ExaoneModel: () => (
+ /* binding */
+ ExaoneModel
+ ),
+ /* harmony export */
+ ExaonePreTrainedModel: () => (
+ /* binding */
+ ExaonePreTrainedModel
+ ),
+ /* harmony export */
+ FalconForCausalLM: () => (
+ /* binding */
+ FalconForCausalLM
+ ),
+ /* harmony export */
+ FalconModel: () => (
+ /* binding */
+ FalconModel
+ ),
+ /* harmony export */
+ FalconPreTrainedModel: () => (
+ /* binding */
+ FalconPreTrainedModel
+ ),
+ /* harmony export */
+ FastViTForImageClassification: () => (
+ /* binding */
+ FastViTForImageClassification
+ ),
+ /* harmony export */
+ FastViTModel: () => (
+ /* binding */
+ FastViTModel
+ ),
+ /* harmony export */
+ FastViTPreTrainedModel: () => (
+ /* binding */
+ FastViTPreTrainedModel
+ ),
+ /* harmony export */
+ Florence2ForConditionalGeneration: () => (
+ /* binding */
+ Florence2ForConditionalGeneration
+ ),
+ /* harmony export */
+ Florence2PreTrainedModel: () => (
+ /* binding */
+ Florence2PreTrainedModel
+ ),
+ /* harmony export */
+ GLPNForDepthEstimation: () => (
+ /* binding */
+ GLPNForDepthEstimation
+ ),
+ /* harmony export */
+ GLPNModel: () => (
+ /* binding */
+ GLPNModel
+ ),
+ /* harmony export */
+ GLPNPreTrainedModel: () => (
+ /* binding */
+ GLPNPreTrainedModel
+ ),
+ /* harmony export */
+ GPT2LMHeadModel: () => (
+ /* binding */
+ GPT2LMHeadModel
+ ),
+ /* harmony export */
+ GPT2Model: () => (
+ /* binding */
+ GPT2Model
+ ),
+ /* harmony export */
+ GPT2PreTrainedModel: () => (
+ /* binding */
+ GPT2PreTrainedModel
+ ),
+ /* harmony export */
+ GPTBigCodeForCausalLM: () => (
+ /* binding */
+ GPTBigCodeForCausalLM
+ ),
+ /* harmony export */
+ GPTBigCodeModel: () => (
+ /* binding */
+ GPTBigCodeModel
+ ),
+ /* harmony export */
+ GPTBigCodePreTrainedModel: () => (
+ /* binding */
+ GPTBigCodePreTrainedModel
+ ),
+ /* harmony export */
+ GPTJForCausalLM: () => (
+ /* binding */
+ GPTJForCausalLM
+ ),
+ /* harmony export */
+ GPTJModel: () => (
+ /* binding */
+ GPTJModel
+ ),
+ /* harmony export */
+ GPTJPreTrainedModel: () => (
+ /* binding */
+ GPTJPreTrainedModel
+ ),
+ /* harmony export */
+ GPTNeoForCausalLM: () => (
+ /* binding */
+ GPTNeoForCausalLM
+ ),
+ /* harmony export */
+ GPTNeoModel: () => (
+ /* binding */
+ GPTNeoModel
+ ),
+ /* harmony export */
+ GPTNeoPreTrainedModel: () => (
+ /* binding */
+ GPTNeoPreTrainedModel
+ ),
+ /* harmony export */
+ GPTNeoXForCausalLM: () => (
+ /* binding */
+ GPTNeoXForCausalLM
+ ),
+ /* harmony export */
+ GPTNeoXModel: () => (
+ /* binding */
+ GPTNeoXModel
+ ),
+ /* harmony export */
+ GPTNeoXPreTrainedModel: () => (
+ /* binding */
+ GPTNeoXPreTrainedModel
+ ),
+ /* harmony export */
+ Gemma2ForCausalLM: () => (
+ /* binding */
+ Gemma2ForCausalLM
+ ),
+ /* harmony export */
+ Gemma2Model: () => (
+ /* binding */
+ Gemma2Model
+ ),
+ /* harmony export */
+ Gemma2PreTrainedModel: () => (
+ /* binding */
+ Gemma2PreTrainedModel
+ ),
+ /* harmony export */
+ Gemma3ForCausalLM: () => (
+ /* binding */
+ Gemma3ForCausalLM
+ ),
+ /* harmony export */
+ Gemma3Model: () => (
+ /* binding */
+ Gemma3Model
+ ),
+ /* harmony export */
+ Gemma3PreTrainedModel: () => (
+ /* binding */
+ Gemma3PreTrainedModel
+ ),
+ /* harmony export */
+ Gemma3nForConditionalGeneration: () => (
+ /* binding */
+ Gemma3nForConditionalGeneration
+ ),
+ /* harmony export */
+ Gemma3nPreTrainedModel: () => (
+ /* binding */
+ Gemma3nPreTrainedModel
+ ),
+ /* harmony export */
+ GemmaForCausalLM: () => (
+ /* binding */
+ GemmaForCausalLM
+ ),
+ /* harmony export */
+ GemmaModel: () => (
+ /* binding */
+ GemmaModel
+ ),
+ /* harmony export */
+ GemmaPreTrainedModel: () => (
+ /* binding */
+ GemmaPreTrainedModel
+ ),
+ /* harmony export */
+ GlmForCausalLM: () => (
+ /* binding */
+ GlmForCausalLM
+ ),
+ /* harmony export */
+ GlmModel: () => (
+ /* binding */
+ GlmModel
+ ),
+ /* harmony export */
+ GlmPreTrainedModel: () => (
+ /* binding */
+ GlmPreTrainedModel
+ ),
+ /* harmony export */
+ GraniteForCausalLM: () => (
+ /* binding */
+ GraniteForCausalLM
+ ),
+ /* harmony export */
+ GraniteModel: () => (
+ /* binding */
+ GraniteModel
+ ),
+ /* harmony export */
+ GraniteMoeHybridForCausalLM: () => (
+ /* binding */
+ GraniteMoeHybridForCausalLM
+ ),
+ /* harmony export */
+ GraniteMoeHybridModel: () => (
+ /* binding */
+ GraniteMoeHybridModel
+ ),
+ /* harmony export */
+ GraniteMoeHybridPreTrainedModel: () => (
+ /* binding */
+ GraniteMoeHybridPreTrainedModel
+ ),
+ /* harmony export */
+ GranitePreTrainedModel: () => (
+ /* binding */
+ GranitePreTrainedModel
+ ),
+ /* harmony export */
+ GroundingDinoForObjectDetection: () => (
+ /* binding */
+ GroundingDinoForObjectDetection
+ ),
+ /* harmony export */
+ GroundingDinoPreTrainedModel: () => (
+ /* binding */
+ GroundingDinoPreTrainedModel
+ ),
+ /* harmony export */
+ GroupViTModel: () => (
+ /* binding */
+ GroupViTModel
+ ),
+ /* harmony export */
+ GroupViTPreTrainedModel: () => (
+ /* binding */
+ GroupViTPreTrainedModel
+ ),
+ /* harmony export */
+ HeliumForCausalLM: () => (
+ /* binding */
+ HeliumForCausalLM
+ ),
+ /* harmony export */
+ HeliumModel: () => (
+ /* binding */
+ HeliumModel
+ ),
+ /* harmony export */
+ HeliumPreTrainedModel: () => (
+ /* binding */
+ HeliumPreTrainedModel
+ ),
+ /* harmony export */
+ HieraForImageClassification: () => (
+ /* binding */
+ HieraForImageClassification
+ ),
+ /* harmony export */
+ HieraModel: () => (
+ /* binding */
+ HieraModel
+ ),
+ /* harmony export */
+ HieraPreTrainedModel: () => (
+ /* binding */
+ HieraPreTrainedModel
+ ),
+ /* harmony export */
+ HubertForCTC: () => (
+ /* binding */
+ HubertForCTC
+ ),
+ /* harmony export */
+ HubertForSequenceClassification: () => (
+ /* binding */
+ HubertForSequenceClassification
+ ),
+ /* harmony export */
+ HubertModel: () => (
+ /* binding */
+ HubertModel
+ ),
+ /* harmony export */
+ HubertPreTrainedModel: () => (
+ /* binding */
+ HubertPreTrainedModel
+ ),
+ /* harmony export */
+ IJepaForImageClassification: () => (
+ /* binding */
+ IJepaForImageClassification
+ ),
+ /* harmony export */
+ IJepaModel: () => (
+ /* binding */
+ IJepaModel
+ ),
+ /* harmony export */
+ IJepaPreTrainedModel: () => (
+ /* binding */
+ IJepaPreTrainedModel
+ ),
+ /* harmony export */
+ Idefics3ForConditionalGeneration: () => (
+ /* binding */
+ Idefics3ForConditionalGeneration
+ ),
+ /* harmony export */
+ Idefics3PreTrainedModel: () => (
+ /* binding */
+ Idefics3PreTrainedModel
+ ),
+ /* harmony export */
+ ImageMattingOutput: () => (
+ /* binding */
+ ImageMattingOutput
+ ),
+ /* harmony export */
+ JAISLMHeadModel: () => (
+ /* binding */
+ JAISLMHeadModel
+ ),
+ /* harmony export */
+ JAISModel: () => (
+ /* binding */
+ JAISModel
+ ),
+ /* harmony export */
+ JAISPreTrainedModel: () => (
+ /* binding */
+ JAISPreTrainedModel
+ ),
+ /* harmony export */
+ JinaCLIPModel: () => (
+ /* binding */
+ JinaCLIPModel
+ ),
+ /* harmony export */
+ JinaCLIPPreTrainedModel: () => (
+ /* binding */
+ JinaCLIPPreTrainedModel
+ ),
+ /* harmony export */
+ JinaCLIPTextModel: () => (
+ /* binding */
+ JinaCLIPTextModel
+ ),
+ /* harmony export */
+ JinaCLIPVisionModel: () => (
+ /* binding */
+ JinaCLIPVisionModel
+ ),
+ /* harmony export */
+ Lfm2ForCausalLM: () => (
+ /* binding */
+ Lfm2ForCausalLM
+ ),
+ /* harmony export */
+ Lfm2Model: () => (
+ /* binding */
+ Lfm2Model
+ ),
+ /* harmony export */
+ Lfm2PreTrainedModel: () => (
+ /* binding */
+ Lfm2PreTrainedModel
+ ),
+ /* harmony export */
+ LiteWhisperForConditionalGeneration: () => (
+ /* binding */
+ LiteWhisperForConditionalGeneration
+ ),
+ /* harmony export */
+ Llama4ForCausalLM: () => (
+ /* binding */
+ Llama4ForCausalLM
+ ),
+ /* harmony export */
+ Llama4PreTrainedModel: () => (
+ /* binding */
+ Llama4PreTrainedModel
+ ),
+ /* harmony export */
+ LlamaForCausalLM: () => (
+ /* binding */
+ LlamaForCausalLM
+ ),
+ /* harmony export */
+ LlamaModel: () => (
+ /* binding */
+ LlamaModel
+ ),
+ /* harmony export */
+ LlamaPreTrainedModel: () => (
+ /* binding */
+ LlamaPreTrainedModel
+ ),
+ /* harmony export */
+ LlavaForConditionalGeneration: () => (
+ /* binding */
+ LlavaForConditionalGeneration
+ ),
+ /* harmony export */
+ LlavaOnevisionForConditionalGeneration: () => (
+ /* binding */
+ LlavaOnevisionForConditionalGeneration
+ ),
+ /* harmony export */
+ LlavaPreTrainedModel: () => (
+ /* binding */
+ LlavaPreTrainedModel
+ ),
+ /* harmony export */
+ LlavaQwen2ForCausalLM: () => (
+ /* binding */
+ LlavaQwen2ForCausalLM
+ ),
+ /* harmony export */
+ LongT5ForConditionalGeneration: () => (
+ /* binding */
+ LongT5ForConditionalGeneration
+ ),
+ /* harmony export */
+ LongT5Model: () => (
+ /* binding */
+ LongT5Model
+ ),
+ /* harmony export */
+ LongT5PreTrainedModel: () => (
+ /* binding */
+ LongT5PreTrainedModel
+ ),
+ /* harmony export */
+ M2M100ForConditionalGeneration: () => (
+ /* binding */
+ M2M100ForConditionalGeneration
+ ),
+ /* harmony export */
+ M2M100Model: () => (
+ /* binding */
+ M2M100Model
+ ),
+ /* harmony export */
+ M2M100PreTrainedModel: () => (
+ /* binding */
+ M2M100PreTrainedModel
+ ),
+ /* harmony export */
+ MBartForCausalLM: () => (
+ /* binding */
+ MBartForCausalLM
+ ),
+ /* harmony export */
+ MBartForConditionalGeneration: () => (
+ /* binding */
+ MBartForConditionalGeneration
+ ),
+ /* harmony export */
+ MBartForSequenceClassification: () => (
+ /* binding */
+ MBartForSequenceClassification
+ ),
+ /* harmony export */
+ MBartModel: () => (
+ /* binding */
+ MBartModel
+ ),
+ /* harmony export */
+ MBartPreTrainedModel: () => (
+ /* binding */
+ MBartPreTrainedModel
+ ),
+ /* harmony export */
+ MPNetForMaskedLM: () => (
+ /* binding */
+ MPNetForMaskedLM
+ ),
+ /* harmony export */
+ MPNetForQuestionAnswering: () => (
+ /* binding */
+ MPNetForQuestionAnswering
+ ),
+ /* harmony export */
+ MPNetForSequenceClassification: () => (
+ /* binding */
+ MPNetForSequenceClassification
+ ),
+ /* harmony export */
+ MPNetForTokenClassification: () => (
+ /* binding */
+ MPNetForTokenClassification
+ ),
+ /* harmony export */
+ MPNetModel: () => (
+ /* binding */
+ MPNetModel
+ ),
+ /* harmony export */
+ MPNetPreTrainedModel: () => (
+ /* binding */
+ MPNetPreTrainedModel
+ ),
+ /* harmony export */
+ MT5ForConditionalGeneration: () => (
+ /* binding */
+ MT5ForConditionalGeneration
+ ),
+ /* harmony export */
+ MT5Model: () => (
+ /* binding */
+ MT5Model
+ ),
+ /* harmony export */
+ MT5PreTrainedModel: () => (
+ /* binding */
+ MT5PreTrainedModel
+ ),
+ /* harmony export */
+ MarianMTModel: () => (
+ /* binding */
+ MarianMTModel
+ ),
+ /* harmony export */
+ MarianModel: () => (
+ /* binding */
+ MarianModel
+ ),
+ /* harmony export */
+ MarianPreTrainedModel: () => (
+ /* binding */
+ MarianPreTrainedModel
+ ),
+ /* harmony export */
+ MaskFormerForInstanceSegmentation: () => (
+ /* binding */
+ MaskFormerForInstanceSegmentation
+ ),
+ /* harmony export */
+ MaskFormerModel: () => (
+ /* binding */
+ MaskFormerModel
+ ),
+ /* harmony export */
+ MaskFormerPreTrainedModel: () => (
+ /* binding */
+ MaskFormerPreTrainedModel
+ ),
+ /* harmony export */
+ MaskedLMOutput: () => (
+ /* binding */
+ MaskedLMOutput
+ ),
+ /* harmony export */
+ Metric3DForDepthEstimation: () => (
+ /* binding */
+ Metric3DForDepthEstimation
+ ),
+ /* harmony export */
+ Metric3DPreTrainedModel: () => (
+ /* binding */
+ Metric3DPreTrainedModel
+ ),
+ /* harmony export */
+ Metric3Dv2ForDepthEstimation: () => (
+ /* binding */
+ Metric3Dv2ForDepthEstimation
+ ),
+ /* harmony export */
+ Metric3Dv2PreTrainedModel: () => (
+ /* binding */
+ Metric3Dv2PreTrainedModel
+ ),
+ /* harmony export */
+ MgpstrForSceneTextRecognition: () => (
+ /* binding */
+ MgpstrForSceneTextRecognition
+ ),
+ /* harmony export */
+ MgpstrModelOutput: () => (
+ /* binding */
+ MgpstrModelOutput
+ ),
+ /* harmony export */
+ MgpstrPreTrainedModel: () => (
+ /* binding */
+ MgpstrPreTrainedModel
+ ),
+ /* harmony export */
+ MimiDecoderModel: () => (
+ /* binding */
+ MimiDecoderModel
+ ),
+ /* harmony export */
+ MimiDecoderOutput: () => (
+ /* binding */
+ MimiDecoderOutput
+ ),
+ /* harmony export */
+ MimiEncoderModel: () => (
+ /* binding */
+ MimiEncoderModel
+ ),
+ /* harmony export */
+ MimiEncoderOutput: () => (
+ /* binding */
+ MimiEncoderOutput
+ ),
+ /* harmony export */
+ MimiModel: () => (
+ /* binding */
+ MimiModel
+ ),
+ /* harmony export */
+ MimiPreTrainedModel: () => (
+ /* binding */
+ MimiPreTrainedModel
+ ),
+ /* harmony export */
+ Ministral3ForCausalLM: () => (
+ /* binding */
+ Ministral3ForCausalLM
+ ),
+ /* harmony export */
+ Ministral3Model: () => (
+ /* binding */
+ Ministral3Model
+ ),
+ /* harmony export */
+ Ministral3PreTrainedModel: () => (
+ /* binding */
+ Ministral3PreTrainedModel
+ ),
+ /* harmony export */
+ MinistralForCausalLM: () => (
+ /* binding */
+ MinistralForCausalLM
+ ),
+ /* harmony export */
+ MinistralModel: () => (
+ /* binding */
+ MinistralModel
+ ),
+ /* harmony export */
+ MinistralPreTrainedModel: () => (
+ /* binding */
+ MinistralPreTrainedModel
+ ),
+ /* harmony export */
+ Mistral3ForConditionalGeneration: () => (
+ /* binding */
+ Mistral3ForConditionalGeneration
+ ),
+ /* harmony export */
+ MistralForCausalLM: () => (
+ /* binding */
+ MistralForCausalLM
+ ),
+ /* harmony export */
+ MistralModel: () => (
+ /* binding */
+ MistralModel
+ ),
+ /* harmony export */
+ MistralPreTrainedModel: () => (
+ /* binding */
+ MistralPreTrainedModel
+ ),
+ /* harmony export */
+ MobileBertForMaskedLM: () => (
+ /* binding */
+ MobileBertForMaskedLM
+ ),
+ /* harmony export */
+ MobileBertForQuestionAnswering: () => (
+ /* binding */
+ MobileBertForQuestionAnswering
+ ),
+ /* harmony export */
+ MobileBertForSequenceClassification: () => (
+ /* binding */
+ MobileBertForSequenceClassification
+ ),
+ /* harmony export */
+ MobileBertModel: () => (
+ /* binding */
+ MobileBertModel
+ ),
+ /* harmony export */
+ MobileBertPreTrainedModel: () => (
+ /* binding */
+ MobileBertPreTrainedModel
+ ),
+ /* harmony export */
+ MobileLLMForCausalLM: () => (
+ /* binding */
+ MobileLLMForCausalLM
+ ),
+ /* harmony export */
+ MobileLLMModel: () => (
+ /* binding */
+ MobileLLMModel
+ ),
+ /* harmony export */
+ MobileLLMPreTrainedModel: () => (
+ /* binding */
+ MobileLLMPreTrainedModel
+ ),
+ /* harmony export */
+ MobileNetV1ForImageClassification: () => (
+ /* binding */
+ MobileNetV1ForImageClassification
+ ),
+ /* harmony export */
+ MobileNetV1ForSemanticSegmentation: () => (
+ /* binding */
+ MobileNetV1ForSemanticSegmentation
+ ),
+ /* harmony export */
+ MobileNetV1Model: () => (
+ /* binding */
+ MobileNetV1Model
+ ),
+ /* harmony export */
+ MobileNetV1PreTrainedModel: () => (
+ /* binding */
+ MobileNetV1PreTrainedModel
+ ),
+ /* harmony export */
+ MobileNetV2ForImageClassification: () => (
+ /* binding */
+ MobileNetV2ForImageClassification
+ ),
+ /* harmony export */
+ MobileNetV2ForSemanticSegmentation: () => (
+ /* binding */
+ MobileNetV2ForSemanticSegmentation
+ ),
+ /* harmony export */
+ MobileNetV2Model: () => (
+ /* binding */
+ MobileNetV2Model
+ ),
+ /* harmony export */
+ MobileNetV2PreTrainedModel: () => (
+ /* binding */
+ MobileNetV2PreTrainedModel
+ ),
+ /* harmony export */
+ MobileNetV3ForImageClassification: () => (
+ /* binding */
+ MobileNetV3ForImageClassification
+ ),
+ /* harmony export */
+ MobileNetV3ForSemanticSegmentation: () => (
+ /* binding */
+ MobileNetV3ForSemanticSegmentation
+ ),
+ /* harmony export */
+ MobileNetV3Model: () => (
+ /* binding */
+ MobileNetV3Model
+ ),
+ /* harmony export */
+ MobileNetV3PreTrainedModel: () => (
+ /* binding */
+ MobileNetV3PreTrainedModel
+ ),
+ /* harmony export */
+ MobileNetV4ForImageClassification: () => (
+ /* binding */
+ MobileNetV4ForImageClassification
+ ),
+ /* harmony export */
+ MobileNetV4ForSemanticSegmentation: () => (
+ /* binding */
+ MobileNetV4ForSemanticSegmentation
+ ),
+ /* harmony export */
+ MobileNetV4Model: () => (
+ /* binding */
+ MobileNetV4Model
+ ),
+ /* harmony export */
+ MobileNetV4PreTrainedModel: () => (
+ /* binding */
+ MobileNetV4PreTrainedModel
+ ),
+ /* harmony export */
+ MobileViTForImageClassification: () => (
+ /* binding */
+ MobileViTForImageClassification
+ ),
+ /* harmony export */
+ MobileViTModel: () => (
+ /* binding */
+ MobileViTModel
+ ),
+ /* harmony export */
+ MobileViTPreTrainedModel: () => (
+ /* binding */
+ MobileViTPreTrainedModel
+ ),
+ /* harmony export */
+ MobileViTV2ForImageClassification: () => (
+ /* binding */
+ MobileViTV2ForImageClassification
+ ),
+ /* harmony export */
+ MobileViTV2Model: () => (
+ /* binding */
+ MobileViTV2Model
+ ),
+ /* harmony export */
+ MobileViTV2PreTrainedModel: () => (
+ /* binding */
+ MobileViTV2PreTrainedModel
+ ),
+ /* harmony export */
+ ModelOutput: () => (
+ /* binding */
+ ModelOutput
+ ),
+ /* harmony export */
+ ModernBertDecoderForCausalLM: () => (
+ /* binding */
+ ModernBertDecoderForCausalLM
+ ),
+ /* harmony export */
+ ModernBertDecoderModel: () => (
+ /* binding */
+ ModernBertDecoderModel
+ ),
+ /* harmony export */
+ ModernBertDecoderPreTrainedModel: () => (
+ /* binding */
+ ModernBertDecoderPreTrainedModel
+ ),
+ /* harmony export */
+ ModernBertForMaskedLM: () => (
+ /* binding */
+ ModernBertForMaskedLM
+ ),
+ /* harmony export */
+ ModernBertForSequenceClassification: () => (
+ /* binding */
+ ModernBertForSequenceClassification
+ ),
+ /* harmony export */
+ ModernBertForTokenClassification: () => (
+ /* binding */
+ ModernBertForTokenClassification
+ ),
+ /* harmony export */
+ ModernBertModel: () => (
+ /* binding */
+ ModernBertModel
+ ),
+ /* harmony export */
+ ModernBertPreTrainedModel: () => (
+ /* binding */
+ ModernBertPreTrainedModel
+ ),
+ /* harmony export */
+ Moondream1ForConditionalGeneration: () => (
+ /* binding */
+ Moondream1ForConditionalGeneration
+ ),
+ /* harmony export */
+ MoonshineForConditionalGeneration: () => (
+ /* binding */
+ MoonshineForConditionalGeneration
+ ),
+ /* harmony export */
+ MoonshineModel: () => (
+ /* binding */
+ MoonshineModel
+ ),
+ /* harmony export */
+ MoonshinePreTrainedModel: () => (
+ /* binding */
+ MoonshinePreTrainedModel
+ ),
+ /* harmony export */
+ MptForCausalLM: () => (
+ /* binding */
+ MptForCausalLM
+ ),
+ /* harmony export */
+ MptModel: () => (
+ /* binding */
+ MptModel
+ ),
+ /* harmony export */
+ MptPreTrainedModel: () => (
+ /* binding */
+ MptPreTrainedModel
+ ),
+ /* harmony export */
+ MultiModalityCausalLM: () => (
+ /* binding */
+ MultiModalityCausalLM
+ ),
+ /* harmony export */
+ MultiModalityPreTrainedModel: () => (
+ /* binding */
+ MultiModalityPreTrainedModel
+ ),
+ /* harmony export */
+ MusicgenForCausalLM: () => (
+ /* binding */
+ MusicgenForCausalLM
+ ),
+ /* harmony export */
+ MusicgenForConditionalGeneration: () => (
+ /* binding */
+ MusicgenForConditionalGeneration
+ ),
+ /* harmony export */
+ MusicgenModel: () => (
+ /* binding */
+ MusicgenModel
+ ),
+ /* harmony export */
+ MusicgenPreTrainedModel: () => (
+ /* binding */
+ MusicgenPreTrainedModel
+ ),
+ /* harmony export */
+ NanoChatForCausalLM: () => (
+ /* binding */
+ NanoChatForCausalLM
+ ),
+ /* harmony export */
+ NanoChatModel: () => (
+ /* binding */
+ NanoChatModel
+ ),
+ /* harmony export */
+ NanoChatPreTrainedModel: () => (
+ /* binding */
+ NanoChatPreTrainedModel
+ ),
+ /* harmony export */
+ NeoBertForMaskedLM: () => (
+ /* binding */
+ NeoBertForMaskedLM
+ ),
+ /* harmony export */
+ NeoBertForQuestionAnswering: () => (
+ /* binding */
+ NeoBertForQuestionAnswering
+ ),
+ /* harmony export */
+ NeoBertForSequenceClassification: () => (
+ /* binding */
+ NeoBertForSequenceClassification
+ ),
+ /* harmony export */
+ NeoBertForTokenClassification: () => (
+ /* binding */
+ NeoBertForTokenClassification
+ ),
+ /* harmony export */
+ NeoBertModel: () => (
+ /* binding */
+ NeoBertModel
+ ),
+ /* harmony export */
+ NeoBertPreTrainedModel: () => (
+ /* binding */
+ NeoBertPreTrainedModel
+ ),
+ /* harmony export */
+ NomicBertModel: () => (
+ /* binding */
+ NomicBertModel
+ ),
+ /* harmony export */
+ NomicBertPreTrainedModel: () => (
+ /* binding */
+ NomicBertPreTrainedModel
+ ),
+ /* harmony export */
+ OPTForCausalLM: () => (
+ /* binding */
+ OPTForCausalLM
+ ),
+ /* harmony export */
+ OPTModel: () => (
+ /* binding */
+ OPTModel
+ ),
+ /* harmony export */
+ OPTPreTrainedModel: () => (
+ /* binding */
+ OPTPreTrainedModel
+ ),
+ /* harmony export */
+ Olmo2ForCausalLM: () => (
+ /* binding */
+ Olmo2ForCausalLM
+ ),
+ /* harmony export */
+ Olmo2Model: () => (
+ /* binding */
+ Olmo2Model
+ ),
+ /* harmony export */
+ Olmo2PreTrainedModel: () => (
+ /* binding */
+ Olmo2PreTrainedModel
+ ),
+ /* harmony export */
+ OlmoForCausalLM: () => (
+ /* binding */
+ OlmoForCausalLM
+ ),
+ /* harmony export */
+ OlmoModel: () => (
+ /* binding */
+ OlmoModel
+ ),
+ /* harmony export */
+ OlmoPreTrainedModel: () => (
+ /* binding */
+ OlmoPreTrainedModel
+ ),
+ /* harmony export */
+ OpenELMForCausalLM: () => (
+ /* binding */
+ OpenELMForCausalLM
+ ),
+ /* harmony export */
+ OpenELMModel: () => (
+ /* binding */
+ OpenELMModel
+ ),
+ /* harmony export */
+ OpenELMPreTrainedModel: () => (
+ /* binding */
+ OpenELMPreTrainedModel
+ ),
+ /* harmony export */
+ OwlViTForObjectDetection: () => (
+ /* binding */
+ OwlViTForObjectDetection
+ ),
+ /* harmony export */
+ OwlViTModel: () => (
+ /* binding */
+ OwlViTModel
+ ),
+ /* harmony export */
+ OwlViTPreTrainedModel: () => (
+ /* binding */
+ OwlViTPreTrainedModel
+ ),
+ /* harmony export */
+ Owlv2ForObjectDetection: () => (
+ /* binding */
+ Owlv2ForObjectDetection
+ ),
+ /* harmony export */
+ Owlv2Model: () => (
+ /* binding */
+ Owlv2Model
+ ),
+ /* harmony export */
+ Owlv2PreTrainedModel: () => (
+ /* binding */
+ Owlv2PreTrainedModel
+ ),
+ /* harmony export */
+ PaliGemmaForConditionalGeneration: () => (
+ /* binding */
+ PaliGemmaForConditionalGeneration
+ ),
+ /* harmony export */
+ PaliGemmaPreTrainedModel: () => (
+ /* binding */
+ PaliGemmaPreTrainedModel
+ ),
+ /* harmony export */
+ ParakeetForCTC: () => (
+ /* binding */
+ ParakeetForCTC
+ ),
+ /* harmony export */
+ ParakeetPreTrainedModel: () => (
+ /* binding */
+ ParakeetPreTrainedModel
+ ),
+ /* harmony export */
+ PatchTSMixerForPrediction: () => (
+ /* binding */
+ PatchTSMixerForPrediction
+ ),
+ /* harmony export */
+ PatchTSMixerModel: () => (
+ /* binding */
+ PatchTSMixerModel
+ ),
+ /* harmony export */
+ PatchTSMixerPreTrainedModel: () => (
+ /* binding */
+ PatchTSMixerPreTrainedModel
+ ),
+ /* harmony export */
+ PatchTSTForPrediction: () => (
+ /* binding */
+ PatchTSTForPrediction
+ ),
+ /* harmony export */
+ PatchTSTModel: () => (
+ /* binding */
+ PatchTSTModel
+ ),
+ /* harmony export */
+ PatchTSTPreTrainedModel: () => (
+ /* binding */
+ PatchTSTPreTrainedModel
+ ),
+ /* harmony export */
+ Phi3ForCausalLM: () => (
+ /* binding */
+ Phi3ForCausalLM
+ ),
+ /* harmony export */
+ Phi3Model: () => (
+ /* binding */
+ Phi3Model
+ ),
+ /* harmony export */
+ Phi3PreTrainedModel: () => (
+ /* binding */
+ Phi3PreTrainedModel
+ ),
+ /* harmony export */
+ Phi3VForCausalLM: () => (
+ /* binding */
+ Phi3VForCausalLM
+ ),
+ /* harmony export */
+ Phi3VPreTrainedModel: () => (
+ /* binding */
+ Phi3VPreTrainedModel
+ ),
+ /* harmony export */
+ PhiForCausalLM: () => (
+ /* binding */
+ PhiForCausalLM
+ ),
+ /* harmony export */
+ PhiModel: () => (
+ /* binding */
+ PhiModel
+ ),
+ /* harmony export */
+ PhiPreTrainedModel: () => (
+ /* binding */
+ PhiPreTrainedModel
+ ),
+ /* harmony export */
+ PreTrainedModel: () => (
+ /* binding */
+ PreTrainedModel
+ ),
+ /* harmony export */
+ PretrainedMixin: () => (
+ /* binding */
+ PretrainedMixin
+ ),
+ /* harmony export */
+ PvtForImageClassification: () => (
+ /* binding */
+ PvtForImageClassification
+ ),
+ /* harmony export */
+ PvtModel: () => (
+ /* binding */
+ PvtModel
+ ),
+ /* harmony export */
+ PvtPreTrainedModel: () => (
+ /* binding */
+ PvtPreTrainedModel
+ ),
+ /* harmony export */
+ PyAnnoteForAudioFrameClassification: () => (
+ /* binding */
+ PyAnnoteForAudioFrameClassification
+ ),
+ /* harmony export */
+ PyAnnoteModel: () => (
+ /* binding */
+ PyAnnoteModel
+ ),
+ /* harmony export */
+ PyAnnotePreTrainedModel: () => (
+ /* binding */
+ PyAnnotePreTrainedModel
+ ),
+ /* harmony export */
+ QuestionAnsweringModelOutput: () => (
+ /* binding */
+ QuestionAnsweringModelOutput
+ ),
+ /* harmony export */
+ Qwen2ForCausalLM: () => (
+ /* binding */
+ Qwen2ForCausalLM
+ ),
+ /* harmony export */
+ Qwen2Model: () => (
+ /* binding */
+ Qwen2Model
+ ),
+ /* harmony export */
+ Qwen2PreTrainedModel: () => (
+ /* binding */
+ Qwen2PreTrainedModel
+ ),
+ /* harmony export */
+ Qwen2VLForConditionalGeneration: () => (
+ /* binding */
+ Qwen2VLForConditionalGeneration
+ ),
+ /* harmony export */
+ Qwen2VLPreTrainedModel: () => (
+ /* binding */
+ Qwen2VLPreTrainedModel
+ ),
+ /* harmony export */
+ Qwen3ForCausalLM: () => (
+ /* binding */
+ Qwen3ForCausalLM
+ ),
+ /* harmony export */
+ Qwen3Model: () => (
+ /* binding */
+ Qwen3Model
+ ),
+ /* harmony export */
+ Qwen3PreTrainedModel: () => (
+ /* binding */
+ Qwen3PreTrainedModel
+ ),
+ /* harmony export */
+ RFDetrForObjectDetection: () => (
+ /* binding */
+ RFDetrForObjectDetection
+ ),
+ /* harmony export */
+ RFDetrModel: () => (
+ /* binding */
+ RFDetrModel
+ ),
+ /* harmony export */
+ RFDetrObjectDetectionOutput: () => (
+ /* binding */
+ RFDetrObjectDetectionOutput
+ ),
+ /* harmony export */
+ RFDetrPreTrainedModel: () => (
+ /* binding */
+ RFDetrPreTrainedModel
+ ),
+ /* harmony export */
+ RTDetrForObjectDetection: () => (
+ /* binding */
+ RTDetrForObjectDetection
+ ),
+ /* harmony export */
+ RTDetrModel: () => (
+ /* binding */
+ RTDetrModel
+ ),
+ /* harmony export */
+ RTDetrObjectDetectionOutput: () => (
+ /* binding */
+ RTDetrObjectDetectionOutput
+ ),
+ /* harmony export */
+ RTDetrPreTrainedModel: () => (
+ /* binding */
+ RTDetrPreTrainedModel
+ ),
+ /* harmony export */
+ RTDetrV2ForObjectDetection: () => (
+ /* binding */
+ RTDetrV2ForObjectDetection
+ ),
+ /* harmony export */
+ RTDetrV2Model: () => (
+ /* binding */
+ RTDetrV2Model
+ ),
+ /* harmony export */
+ RTDetrV2ObjectDetectionOutput: () => (
+ /* binding */
+ RTDetrV2ObjectDetectionOutput
+ ),
+ /* harmony export */
+ RTDetrV2PreTrainedModel: () => (
+ /* binding */
+ RTDetrV2PreTrainedModel
+ ),
+ /* harmony export */
+ ResNetForImageClassification: () => (
+ /* binding */
+ ResNetForImageClassification
+ ),
+ /* harmony export */
+ ResNetModel: () => (
+ /* binding */
+ ResNetModel
+ ),
+ /* harmony export */
+ ResNetPreTrainedModel: () => (
+ /* binding */
+ ResNetPreTrainedModel
+ ),
+ /* harmony export */
+ RoFormerForMaskedLM: () => (
+ /* binding */
+ RoFormerForMaskedLM
+ ),
+ /* harmony export */
+ RoFormerForQuestionAnswering: () => (
+ /* binding */
+ RoFormerForQuestionAnswering
+ ),
+ /* harmony export */
+ RoFormerForSequenceClassification: () => (
+ /* binding */
+ RoFormerForSequenceClassification
+ ),
+ /* harmony export */
+ RoFormerForTokenClassification: () => (
+ /* binding */
+ RoFormerForTokenClassification
+ ),
+ /* harmony export */
+ RoFormerModel: () => (
+ /* binding */
+ RoFormerModel
+ ),
+ /* harmony export */
+ RoFormerPreTrainedModel: () => (
+ /* binding */
+ RoFormerPreTrainedModel
+ ),
+ /* harmony export */
+ RobertaForMaskedLM: () => (
+ /* binding */
+ RobertaForMaskedLM
+ ),
+ /* harmony export */
+ RobertaForQuestionAnswering: () => (
+ /* binding */
+ RobertaForQuestionAnswering
+ ),
+ /* harmony export */
+ RobertaForSequenceClassification: () => (
+ /* binding */
+ RobertaForSequenceClassification
+ ),
+ /* harmony export */
+ RobertaForTokenClassification: () => (
+ /* binding */
+ RobertaForTokenClassification
+ ),
+ /* harmony export */
+ RobertaModel: () => (
+ /* binding */
+ RobertaModel
+ ),
+ /* harmony export */
+ RobertaPreTrainedModel: () => (
+ /* binding */
+ RobertaPreTrainedModel
+ ),
+ /* harmony export */
+ Sam2ImageSegmentationOutput: () => (
+ /* binding */
+ Sam2ImageSegmentationOutput
+ ),
+ /* harmony export */
+ Sam2Model: () => (
+ /* binding */
+ Sam2Model
+ ),
+ /* harmony export */
+ Sam2PreTrainedModel: () => (
+ /* binding */
+ Sam2PreTrainedModel
+ ),
+ /* harmony export */
+ Sam3TrackerModel: () => (
+ /* binding */
+ Sam3TrackerModel
+ ),
+ /* harmony export */
+ SamImageSegmentationOutput: () => (
+ /* binding */
+ SamImageSegmentationOutput
+ ),
+ /* harmony export */
+ SamModel: () => (
+ /* binding */
+ SamModel
+ ),
+ /* harmony export */
+ SamPreTrainedModel: () => (
+ /* binding */
+ SamPreTrainedModel
+ ),
+ /* harmony export */
+ SapiensForDepthEstimation: () => (
+ /* binding */
+ SapiensForDepthEstimation
+ ),
+ /* harmony export */
+ SapiensForNormalEstimation: () => (
+ /* binding */
+ SapiensForNormalEstimation
+ ),
+ /* harmony export */
+ SapiensForSemanticSegmentation: () => (
+ /* binding */
+ SapiensForSemanticSegmentation
+ ),
+ /* harmony export */
+ SapiensPreTrainedModel: () => (
+ /* binding */
+ SapiensPreTrainedModel
+ ),
+ /* harmony export */
+ SegformerForImageClassification: () => (
+ /* binding */
+ SegformerForImageClassification
+ ),
+ /* harmony export */
+ SegformerForSemanticSegmentation: () => (
+ /* binding */
+ SegformerForSemanticSegmentation
+ ),
+ /* harmony export */
+ SegformerModel: () => (
+ /* binding */
+ SegformerModel
+ ),
+ /* harmony export */
+ SegformerPreTrainedModel: () => (
+ /* binding */
+ SegformerPreTrainedModel
+ ),
+ /* harmony export */
+ Seq2SeqLMOutput: () => (
+ /* binding */
+ Seq2SeqLMOutput
+ ),
+ /* harmony export */
+ SequenceClassifierOutput: () => (
+ /* binding */
+ SequenceClassifierOutput
+ ),
+ /* harmony export */
+ SiglipModel: () => (
+ /* binding */
+ SiglipModel
+ ),
+ /* harmony export */
+ SiglipPreTrainedModel: () => (
+ /* binding */
+ SiglipPreTrainedModel
+ ),
+ /* harmony export */
+ SiglipTextModel: () => (
+ /* binding */
+ SiglipTextModel
+ ),
+ /* harmony export */
+ SiglipVisionModel: () => (
+ /* binding */
+ SiglipVisionModel
+ ),
+ /* harmony export */
+ SmolLM3ForCausalLM: () => (
+ /* binding */
+ SmolLM3ForCausalLM
+ ),
+ /* harmony export */
+ SmolLM3Model: () => (
+ /* binding */
+ SmolLM3Model
+ ),
+ /* harmony export */
+ SmolLM3PreTrainedModel: () => (
+ /* binding */
+ SmolLM3PreTrainedModel
+ ),
+ /* harmony export */
+ SmolVLMForConditionalGeneration: () => (
+ /* binding */
+ SmolVLMForConditionalGeneration
+ ),
+ /* harmony export */
+ SnacDecoderModel: () => (
+ /* binding */
+ SnacDecoderModel
+ ),
+ /* harmony export */
+ SnacEncoderModel: () => (
+ /* binding */
+ SnacEncoderModel
+ ),
+ /* harmony export */
+ SnacModel: () => (
+ /* binding */
+ SnacModel
+ ),
+ /* harmony export */
+ SnacPreTrainedModel: () => (
+ /* binding */
+ SnacPreTrainedModel
+ ),
+ /* harmony export */
+ SpeechT5ForSpeechToText: () => (
+ /* binding */
+ SpeechT5ForSpeechToText
+ ),
+ /* harmony export */
+ SpeechT5ForTextToSpeech: () => (
+ /* binding */
+ SpeechT5ForTextToSpeech
+ ),
+ /* harmony export */
+ SpeechT5HifiGan: () => (
+ /* binding */
+ SpeechT5HifiGan
+ ),
+ /* harmony export */
+ SpeechT5Model: () => (
+ /* binding */
+ SpeechT5Model
+ ),
+ /* harmony export */
+ SpeechT5PreTrainedModel: () => (
+ /* binding */
+ SpeechT5PreTrainedModel
+ ),
+ /* harmony export */
+ SqueezeBertForMaskedLM: () => (
+ /* binding */
+ SqueezeBertForMaskedLM
+ ),
+ /* harmony export */
+ SqueezeBertForQuestionAnswering: () => (
+ /* binding */
+ SqueezeBertForQuestionAnswering
+ ),
+ /* harmony export */
+ SqueezeBertForSequenceClassification: () => (
+ /* binding */
+ SqueezeBertForSequenceClassification
+ ),
+ /* harmony export */
+ SqueezeBertModel: () => (
+ /* binding */
+ SqueezeBertModel
+ ),
+ /* harmony export */
+ SqueezeBertPreTrainedModel: () => (
+ /* binding */
+ SqueezeBertPreTrainedModel
+ ),
+ /* harmony export */
+ StableLmForCausalLM: () => (
+ /* binding */
+ StableLmForCausalLM
+ ),
+ /* harmony export */
+ StableLmModel: () => (
+ /* binding */
+ StableLmModel
+ ),
+ /* harmony export */
+ StableLmPreTrainedModel: () => (
+ /* binding */
+ StableLmPreTrainedModel
+ ),
+ /* harmony export */
+ Starcoder2ForCausalLM: () => (
+ /* binding */
+ Starcoder2ForCausalLM
+ ),
+ /* harmony export */
+ Starcoder2Model: () => (
+ /* binding */
+ Starcoder2Model
+ ),
+ /* harmony export */
+ Starcoder2PreTrainedModel: () => (
+ /* binding */
+ Starcoder2PreTrainedModel
+ ),
+ /* harmony export */
+ StyleTextToSpeech2Model: () => (
+ /* binding */
+ StyleTextToSpeech2Model
+ ),
+ /* harmony export */
+ StyleTextToSpeech2PreTrainedModel: () => (
+ /* binding */
+ StyleTextToSpeech2PreTrainedModel
+ ),
+ /* harmony export */
+ SupertonicForConditionalGeneration: () => (
+ /* binding */
+ SupertonicForConditionalGeneration
+ ),
+ /* harmony export */
+ SupertonicPreTrainedModel: () => (
+ /* binding */
+ SupertonicPreTrainedModel
+ ),
+ /* harmony export */
+ Swin2SRForImageSuperResolution: () => (
+ /* binding */
+ Swin2SRForImageSuperResolution
+ ),
+ /* harmony export */
+ Swin2SRModel: () => (
+ /* binding */
+ Swin2SRModel
+ ),
+ /* harmony export */
+ Swin2SRPreTrainedModel: () => (
+ /* binding */
+ Swin2SRPreTrainedModel
+ ),
+ /* harmony export */
+ SwinForImageClassification: () => (
+ /* binding */
+ SwinForImageClassification
+ ),
+ /* harmony export */
+ SwinForSemanticSegmentation: () => (
+ /* binding */
+ SwinForSemanticSegmentation
+ ),
+ /* harmony export */
+ SwinModel: () => (
+ /* binding */
+ SwinModel
+ ),
+ /* harmony export */
+ SwinPreTrainedModel: () => (
+ /* binding */
+ SwinPreTrainedModel
+ ),
+ /* harmony export */
+ T5ForConditionalGeneration: () => (
+ /* binding */
+ T5ForConditionalGeneration
+ ),
+ /* harmony export */
+ T5Model: () => (
+ /* binding */
+ T5Model
+ ),
+ /* harmony export */
+ T5PreTrainedModel: () => (
+ /* binding */
+ T5PreTrainedModel
+ ),
+ /* harmony export */
+ TableTransformerForObjectDetection: () => (
+ /* binding */
+ TableTransformerForObjectDetection
+ ),
+ /* harmony export */
+ TableTransformerModel: () => (
+ /* binding */
+ TableTransformerModel
+ ),
+ /* harmony export */
+ TableTransformerObjectDetectionOutput: () => (
+ /* binding */
+ TableTransformerObjectDetectionOutput
+ ),
+ /* harmony export */
+ TableTransformerPreTrainedModel: () => (
+ /* binding */
+ TableTransformerPreTrainedModel
+ ),
+ /* harmony export */
+ TokenClassifierOutput: () => (
+ /* binding */
+ TokenClassifierOutput
+ ),
+ /* harmony export */
+ TrOCRForCausalLM: () => (
+ /* binding */
+ TrOCRForCausalLM
+ ),
+ /* harmony export */
+ TrOCRPreTrainedModel: () => (
+ /* binding */
+ TrOCRPreTrainedModel
+ ),
+ /* harmony export */
+ UltravoxModel: () => (
+ /* binding */
+ UltravoxModel
+ ),
+ /* harmony export */
+ UltravoxPreTrainedModel: () => (
+ /* binding */
+ UltravoxPreTrainedModel
+ ),
+ /* harmony export */
+ UniSpeechForCTC: () => (
+ /* binding */
+ UniSpeechForCTC
+ ),
+ /* harmony export */
+ UniSpeechForSequenceClassification: () => (
+ /* binding */
+ UniSpeechForSequenceClassification
+ ),
+ /* harmony export */
+ UniSpeechModel: () => (
+ /* binding */
+ UniSpeechModel
+ ),
+ /* harmony export */
+ UniSpeechPreTrainedModel: () => (
+ /* binding */
+ UniSpeechPreTrainedModel
+ ),
+ /* harmony export */
+ UniSpeechSatForAudioFrameClassification: () => (
+ /* binding */
+ UniSpeechSatForAudioFrameClassification
+ ),
+ /* harmony export */
+ UniSpeechSatForCTC: () => (
+ /* binding */
+ UniSpeechSatForCTC
+ ),
+ /* harmony export */
+ UniSpeechSatForSequenceClassification: () => (
+ /* binding */
+ UniSpeechSatForSequenceClassification
+ ),
+ /* harmony export */
+ UniSpeechSatModel: () => (
+ /* binding */
+ UniSpeechSatModel
+ ),
+ /* harmony export */
+ UniSpeechSatPreTrainedModel: () => (
+ /* binding */
+ UniSpeechSatPreTrainedModel
+ ),
+ /* harmony export */
+ VaultGemmaForCausalLM: () => (
+ /* binding */
+ VaultGemmaForCausalLM
+ ),
+ /* harmony export */
+ VaultGemmaModel: () => (
+ /* binding */
+ VaultGemmaModel
+ ),
+ /* harmony export */
+ VaultGemmaPreTrainedModel: () => (
+ /* binding */
+ VaultGemmaPreTrainedModel
+ ),
+ /* harmony export */
+ ViTForImageClassification: () => (
+ /* binding */
+ ViTForImageClassification
+ ),
+ /* harmony export */
+ ViTMAEModel: () => (
+ /* binding */
+ ViTMAEModel
+ ),
+ /* harmony export */
+ ViTMAEPreTrainedModel: () => (
+ /* binding */
+ ViTMAEPreTrainedModel
+ ),
+ /* harmony export */
+ ViTMSNForImageClassification: () => (
+ /* binding */
+ ViTMSNForImageClassification
+ ),
+ /* harmony export */
+ ViTMSNModel: () => (
+ /* binding */
+ ViTMSNModel
+ ),
+ /* harmony export */
+ ViTMSNPreTrainedModel: () => (
+ /* binding */
+ ViTMSNPreTrainedModel
+ ),
+ /* harmony export */
+ ViTModel: () => (
+ /* binding */
+ ViTModel
+ ),
+ /* harmony export */
+ ViTPreTrainedModel: () => (
+ /* binding */
+ ViTPreTrainedModel
+ ),
+ /* harmony export */
+ VisionEncoderDecoderModel: () => (
+ /* binding */
+ VisionEncoderDecoderModel
+ ),
+ /* harmony export */
+ VitMatteForImageMatting: () => (
+ /* binding */
+ VitMatteForImageMatting
+ ),
+ /* harmony export */
+ VitMattePreTrainedModel: () => (
+ /* binding */
+ VitMattePreTrainedModel
+ ),
+ /* harmony export */
+ VitPoseForPoseEstimation: () => (
+ /* binding */
+ VitPoseForPoseEstimation
+ ),
+ /* harmony export */
+ VitPosePreTrainedModel: () => (
+ /* binding */
+ VitPosePreTrainedModel
+ ),
+ /* harmony export */
+ VitsModel: () => (
+ /* binding */
+ VitsModel
+ ),
+ /* harmony export */
+ VitsModelOutput: () => (
+ /* binding */
+ VitsModelOutput
+ ),
+ /* harmony export */
+ VitsPreTrainedModel: () => (
+ /* binding */
+ VitsPreTrainedModel
+ ),
+ /* harmony export */
+ VoxtralForConditionalGeneration: () => (
+ /* binding */
+ VoxtralForConditionalGeneration
+ ),
+ /* harmony export */
+ Wav2Vec2BertForCTC: () => (
+ /* binding */
+ Wav2Vec2BertForCTC
+ ),
+ /* harmony export */
+ Wav2Vec2BertForSequenceClassification: () => (
+ /* binding */
+ Wav2Vec2BertForSequenceClassification
+ ),
+ /* harmony export */
+ Wav2Vec2BertModel: () => (
+ /* binding */
+ Wav2Vec2BertModel
+ ),
+ /* harmony export */
+ Wav2Vec2BertPreTrainedModel: () => (
+ /* binding */
+ Wav2Vec2BertPreTrainedModel
+ ),
+ /* harmony export */
+ Wav2Vec2ForAudioFrameClassification: () => (
+ /* binding */
+ Wav2Vec2ForAudioFrameClassification
+ ),
+ /* harmony export */
+ Wav2Vec2ForCTC: () => (
+ /* binding */
+ Wav2Vec2ForCTC
+ ),
+ /* harmony export */
+ Wav2Vec2ForSequenceClassification: () => (
+ /* binding */
+ Wav2Vec2ForSequenceClassification
+ ),
+ /* harmony export */
+ Wav2Vec2Model: () => (
+ /* binding */
+ Wav2Vec2Model
+ ),
+ /* harmony export */
+ Wav2Vec2PreTrainedModel: () => (
+ /* binding */
+ Wav2Vec2PreTrainedModel
+ ),
+ /* harmony export */
+ WavLMForAudioFrameClassification: () => (
+ /* binding */
+ WavLMForAudioFrameClassification
+ ),
+ /* harmony export */
+ WavLMForCTC: () => (
+ /* binding */
+ WavLMForCTC
+ ),
+ /* harmony export */
+ WavLMForSequenceClassification: () => (
+ /* binding */
+ WavLMForSequenceClassification
+ ),
+ /* harmony export */
+ WavLMForXVector: () => (
+ /* binding */
+ WavLMForXVector
+ ),
+ /* harmony export */
+ WavLMModel: () => (
+ /* binding */
+ WavLMModel
+ ),
+ /* harmony export */
+ WavLMPreTrainedModel: () => (
+ /* binding */
+ WavLMPreTrainedModel
+ ),
+ /* harmony export */
+ WeSpeakerResNetModel: () => (
+ /* binding */
+ WeSpeakerResNetModel
+ ),
+ /* harmony export */
+ WeSpeakerResNetPreTrainedModel: () => (
+ /* binding */
+ WeSpeakerResNetPreTrainedModel
+ ),
+ /* harmony export */
+ WhisperForConditionalGeneration: () => (
+ /* binding */
+ WhisperForConditionalGeneration
+ ),
+ /* harmony export */
+ WhisperModel: () => (
+ /* binding */
+ WhisperModel
+ ),
+ /* harmony export */
+ WhisperPreTrainedModel: () => (
+ /* binding */
+ WhisperPreTrainedModel
+ ),
+ /* harmony export */
+ XLMForQuestionAnswering: () => (
+ /* binding */
+ XLMForQuestionAnswering
+ ),
+ /* harmony export */
+ XLMForSequenceClassification: () => (
+ /* binding */
+ XLMForSequenceClassification
+ ),
+ /* harmony export */
+ XLMForTokenClassification: () => (
+ /* binding */
+ XLMForTokenClassification
+ ),
+ /* harmony export */
+ XLMModel: () => (
+ /* binding */
+ XLMModel
+ ),
+ /* harmony export */
+ XLMPreTrainedModel: () => (
+ /* binding */
+ XLMPreTrainedModel
+ ),
+ /* harmony export */
+ XLMRobertaForMaskedLM: () => (
+ /* binding */
+ XLMRobertaForMaskedLM
+ ),
+ /* harmony export */
+ XLMRobertaForQuestionAnswering: () => (
+ /* binding */
+ XLMRobertaForQuestionAnswering
+ ),
+ /* harmony export */
+ XLMRobertaForSequenceClassification: () => (
+ /* binding */
+ XLMRobertaForSequenceClassification
+ ),
+ /* harmony export */
+ XLMRobertaForTokenClassification: () => (
+ /* binding */
+ XLMRobertaForTokenClassification
+ ),
+ /* harmony export */
+ XLMRobertaModel: () => (
+ /* binding */
+ XLMRobertaModel
+ ),
+ /* harmony export */
+ XLMRobertaPreTrainedModel: () => (
+ /* binding */
+ XLMRobertaPreTrainedModel
+ ),
+ /* harmony export */
+ XLMWithLMHeadModel: () => (
+ /* binding */
+ XLMWithLMHeadModel
+ ),
+ /* harmony export */
+ XVectorOutput: () => (
+ /* binding */
+ XVectorOutput
+ ),
+ /* harmony export */
+ YolosForObjectDetection: () => (
+ /* binding */
+ YolosForObjectDetection
+ ),
+ /* harmony export */
+ YolosModel: () => (
+ /* binding */
+ YolosModel
+ ),
+ /* harmony export */
+ YolosObjectDetectionOutput: () => (
+ /* binding */
+ YolosObjectDetectionOutput
+ ),
+ /* harmony export */
+ YolosPreTrainedModel: () => (
+ /* binding */
+ YolosPreTrainedModel
+ )
+ /* harmony export */
+ });
+ var _configs_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2(
+ /*! ./configs.js */
+ "./src/configs.js"
+ );
+ var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2(
+ /*! ./backends/onnx.js */
+ "./src/backends/onnx.js"
+ );
+ var _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2(
+ /*! ./utils/dtypes.js */
+ "./src/utils/dtypes.js"
+ );
+ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2(
+ /*! ./utils/generic.js */
+ "./src/utils/generic.js"
+ );
+ var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2(
+ /*! ./utils/core.js */
+ "./src/utils/core.js"
+ );
+ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2(
+ /*! ./utils/hub.js */
+ "./src/utils/hub.js"
+ );
+ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2(
+ /*! ./utils/constants.js */
+ "./src/utils/constants.js"
+ );
+ var _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__2(
+ /*! ./generation/logits_process.js */
+ "./src/generation/logits_process.js"
+ );
+ var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__2(
+ /*! ./generation/configuration_utils.js */
+ "./src/generation/configuration_utils.js"
+ );
+ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__2(
+ /*! ./utils/tensor.js */
+ "./src/utils/tensor.js"
+ );
+ var _utils_image_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__2(
+ /*! ./utils/image.js */
+ "./src/utils/image.js"
+ );
+ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__2(
+ /*! ./utils/maths.js */
+ "./src/utils/maths.js"
+ );
+ var _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__2(
+ /*! ./generation/stopping_criteria.js */
+ "./src/generation/stopping_criteria.js"
+ );
+ var _generation_logits_sampler_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__2(
+ /*! ./generation/logits_sampler.js */
+ "./src/generation/logits_sampler.js"
+ );
+ var _env_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__2(
+ /*! ./env.js */
+ "./src/env.js"
+ );
+ var _models_whisper_generation_whisper_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__2(
+ /*! ./models/whisper/generation_whisper.js */
+ "./src/models/whisper/generation_whisper.js"
+ );
+ var _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__2(
+ /*! ./models/whisper/common_whisper.js */
+ "./src/models/whisper/common_whisper.js"
+ );
+ const MODEL_TYPES = {
+ EncoderOnly: 0,
+ EncoderDecoder: 1,
+ Seq2Seq: 2,
+ Vision2Seq: 3,
+ DecoderOnly: 4,
+ MaskGeneration: 5,
+ ImageTextToText: 6,
+ Musicgen: 7,
+ MultiModality: 8,
+ Phi3V: 9,
+ AudioTextToText: 10,
+ AutoEncoder: 11,
+ ImageAudioTextToText: 12,
+ Supertonic: 13
+ };
+ const MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map();
+ const MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map();
+ const MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map();
+ async function getSession(pretrained_model_name_or_path, fileName, options) {
+ let custom_config = options.config?.["transformers.js_config"] ?? {};
+ let device = options.device ?? custom_config.device;
+ if (device && typeof device !== "string") {
+ if (device.hasOwnProperty(fileName)) {
+ device = device[fileName];
+ } else {
+ console.warn(`device not specified for "${fileName}". Using the default device.`);
+ device = null;
+ }
+ }
+ const selectedDevice = (
+ /** @type {import("./utils/devices.js").DeviceType} */
+ device ?? (_env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV ? "cpu" : "wasm")
+ );
+ const executionProviders = (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.deviceToExecutionProviders)(selectedDevice);
+ const device_config = custom_config.device_config ?? {};
+ if (device_config.hasOwnProperty(selectedDevice)) {
+ custom_config = {
+ ...custom_config,
+ ...device_config[selectedDevice]
+ };
+ }
+ let dtype = options.dtype ?? custom_config.dtype;
+ if (typeof dtype !== "string") {
+ if (dtype && dtype.hasOwnProperty(fileName)) {
+ dtype = dtype[fileName];
+ } else {
+ dtype = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp32;
+ console.warn(`dtype not specified for "${fileName}". Using the default dtype (${dtype}) for this device (${selectedDevice}).`);
+ }
+ }
+ if (dtype === _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.auto) {
+ let config_dtype = custom_config.dtype;
+ if (typeof config_dtype !== "string") {
+ config_dtype = config_dtype?.[fileName];
+ }
+ if (config_dtype && config_dtype !== _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.auto && _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.hasOwnProperty(config_dtype)) {
+ dtype = config_dtype;
+ } else {
+ dtype = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp32;
+ }
+ }
+ const selectedDtype = (
+ /** @type {import("./utils/dtypes.js").DataType} */
+ dtype
+ );
+ if (!_utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) {
+ throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(_utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES).join(", ")}`);
+ } else if (selectedDtype === _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp16 && selectedDevice === "webgpu" && !await (0, _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.isWebGpuFp16Supported)()) {
+ throw new Error(`The device (${selectedDevice}) does not support fp16.`);
+ }
+ const kv_cache_dtype_config = custom_config.kv_cache_dtype;
+ const kv_cache_dtype = kv_cache_dtype_config ? typeof kv_cache_dtype_config === "string" ? kv_cache_dtype_config : kv_cache_dtype_config[selectedDtype] ?? "float32" : void 0;
+ if (kv_cache_dtype && !["float32", "float16"].includes(kv_cache_dtype)) {
+ throw new Error(`Invalid kv_cache_dtype: ${kv_cache_dtype}. Should be one of: float32, float16`);
+ }
+ const session_config = {
+ dtype: selectedDtype,
+ kv_cache_dtype,
+ device: selectedDevice
+ };
+ const suffix = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype];
+ const baseName = `${fileName}${suffix}.onnx`;
+ const modelFileName = `${options.subfolder ?? ""}/${baseName}`;
+ const session_options = { ...options.session_options };
+ session_options.executionProviders ?? (session_options.executionProviders = executionProviders);
+ const free_dimension_overrides = custom_config.free_dimension_overrides;
+ if (free_dimension_overrides) {
+ session_options.freeDimensionOverrides ?? (session_options.freeDimensionOverrides = free_dimension_overrides);
+ } else if (selectedDevice.startsWith("webnn") && !session_options.freeDimensionOverrides) {
+ console.warn(
+ `WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${selectedDevice}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`
+ );
+ }
+ const return_path = _env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV && _env_js__WEBPACK_IMPORTED_MODULE_14__.env.useFSCache;
+ const bufferOrPathPromise = (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, modelFileName, true, options, return_path);
+ const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format;
+ let externalDataPromises = [];
+ if (use_external_data_format) {
+ let external_data_format;
+ if (typeof use_external_data_format === "object") {
+ if (use_external_data_format.hasOwnProperty(baseName)) {
+ external_data_format = use_external_data_format[baseName];
+ } else if (use_external_data_format.hasOwnProperty(fileName)) {
+ external_data_format = use_external_data_format[fileName];
+ } else {
+ external_data_format = false;
+ }
+ } else {
+ external_data_format = use_external_data_format;
+ }
+ const num_chunks = +external_data_format;
+ if (num_chunks > _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS) {
+ throw new Error(`The number of external data chunks (${num_chunks}) exceeds the maximum allowed value (${_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS}).`);
+ }
+ for (let i = 0; i < num_chunks; ++i) {
+ const path = `${baseName}_data${i === 0 ? "" : "_" + i}`;
+ const fullPath = `${options.subfolder ?? ""}/${path}`;
+ externalDataPromises.push(new Promise(async (resolve, reject) => {
+ const data = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, fullPath, true, options, return_path);
+ resolve(data instanceof Uint8Array ? { path, data } : path);
+ }));
+ }
+ } else if (session_options.externalData !== void 0) {
+ externalDataPromises = session_options.externalData.map(async (ext) => {
+ if (typeof ext.data === "string") {
+ const ext_buffer = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, ext.data, true, options);
+ return { ...ext, data: ext_buffer };
+ }
+ return ext;
+ });
+ }
+ if (externalDataPromises.length > 0) {
+ const externalData = await Promise.all(externalDataPromises);
+ if (!_env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV) {
+ session_options.externalData = externalData;
+ }
+ }
+ if (selectedDevice === "webgpu") {
+ const shapes = (0, _configs_js__WEBPACK_IMPORTED_MODULE_0__.getCacheShapes)(options.config, {
+ prefix: "present"
+ });
+ if (Object.keys(shapes).length > 0 && !(0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXProxy)()) {
+ const preferredOutputLocation = {};
+ for (const key in shapes) {
+ preferredOutputLocation[key] = "gpu-buffer";
+ }
+ session_options.preferredOutputLocation = preferredOutputLocation;
+ }
+ }
+ const buffer_or_path = await bufferOrPathPromise;
+ return { buffer_or_path, session_options, session_config };
+ }
+ async function constructSessions(pretrained_model_name_or_path, names, options) {
+ return Object.fromEntries(await Promise.all(
+ Object.keys(names).map(async (name) => {
+ const { buffer_or_path, session_options, session_config } = await getSession(pretrained_model_name_or_path, names[name], options);
+ const session = await (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.createInferenceSession)(buffer_or_path, session_options, session_config);
+ return [name, session];
+ })
+ ));
+ }
+ async function getOptionalConfigs(pretrained_model_name_or_path, names, options) {
+ return Object.fromEntries(await Promise.all(
+ Object.keys(names).map(async (name) => {
+ const config = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelJSON)(pretrained_model_name_or_path, names[name], false, options);
+ return [name, config];
+ })
+ ));
+ }
+ function validateInputs(session, inputs) {
+ const checkedInputs = /* @__PURE__ */ Object.create(null);
+ const missingInputs = [];
+ for (const inputName of session.inputNames) {
+ const tensor = inputs[inputName];
+ if (!(tensor instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor)) {
+ missingInputs.push(inputName);
+ continue;
+ }
+ checkedInputs[inputName] = (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXProxy)() ? tensor.clone() : tensor;
+ }
+ if (missingInputs.length > 0) {
+ throw new Error(
+ `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(", ")}.`
+ );
+ }
+ const numInputsProvided = Object.keys(inputs).length;
+ const numInputsNeeded = session.inputNames.length;
+ if (numInputsProvided > numInputsNeeded) {
+ let ignored = Object.keys(inputs).filter((inputName) => !session.inputNames.includes(inputName));
+ console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(", ")}".`);
+ }
+ return checkedInputs;
+ }
+ async function sessionRun(session, inputs) {
+ const checkedInputs = validateInputs(session, inputs);
+ try {
+ const ortFeed = Object.fromEntries(Object.entries(checkedInputs).map(([k2, v]) => [k2, v.ort_tensor]));
+ const output = await (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.runInferenceSession)(session, ortFeed);
+ return replaceTensors(output);
+ } catch (e) {
+ const formatted = Object.fromEntries(Object.entries(checkedInputs).map(([k2, tensor]) => {
+ const unpacked = {
+ type: tensor.type,
+ dims: tensor.dims,
+ location: tensor.location
+ };
+ if (unpacked.location !== "gpu-buffer") {
+ unpacked.data = tensor.data;
+ }
+ return [k2, unpacked];
+ }));
+ console.error(`An error occurred during model execution: "${e}".`);
+ console.error("Inputs given to model:", formatted);
+ throw e;
+ }
+ }
+ function replaceTensors(obj) {
+ for (let prop in obj) {
+ if ((0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXTensor)(obj[prop])) {
+ obj[prop] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(obj[prop]);
+ } else if (typeof obj[prop] === "object") {
+ replaceTensors(obj[prop]);
+ }
+ }
+ return obj;
+ }
+ function toI64Tensor(items) {
+ if (items instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor) {
+ return items;
+ }
+ if (items.length === 0) {
+ throw Error("items must be non-empty");
+ }
+ if (Array.isArray(items[0])) {
+ if (items.some((x) => x.length !== items[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 _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(
+ "int64",
+ BigInt64Array.from(items.flat().map((x) => BigInt(x))),
+ [items.length, items[0].length]
+ );
+ } else {
+ return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(
+ "int64",
+ BigInt64Array.from(items.map((x) => BigInt(x))),
+ [1, items.length]
+ );
+ }
+ }
+ function boolTensor(value) {
+ return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("bool", [value], [1]);
+ }
+ async function seq2seqForward(self2, model_inputs) {
+ let { encoder_outputs, input_ids, decoder_input_ids, ...other_decoder_inputs } = model_inputs;
+ if (!encoder_outputs) {
+ const encoder_inputs = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, self2.sessions["model"].inputNames);
+ encoder_outputs = (await encoderForward(self2, encoder_inputs)).last_hidden_state;
+ }
+ other_decoder_inputs.input_ids = decoder_input_ids;
+ other_decoder_inputs.encoder_hidden_states = encoder_outputs;
+ if (self2.sessions["decoder_model_merged"].inputNames.includes("encoder_attention_mask")) {
+ other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask;
+ }
+ const decoderResults = await decoderForward(self2, other_decoder_inputs, true);
+ return decoderResults;
+ }
+ async function encoderForward(self2, model_inputs) {
+ const session = self2.sessions["model"];
+ const encoderFeeds = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, session.inputNames);
+ if (session.inputNames.includes("inputs_embeds") && !encoderFeeds.inputs_embeds) {
+ if (!model_inputs.input_ids) {
+ throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");
+ }
+ encoderFeeds.inputs_embeds = await self2.encode_text({ input_ids: model_inputs.input_ids });
+ }
+ if (session.inputNames.includes("token_type_ids") && !encoderFeeds.token_type_ids) {
+ if (!encoderFeeds.input_ids) {
+ throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");
+ }
+ encoderFeeds.token_type_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.zeros_like)(encoderFeeds.input_ids);
+ }
+ if (session.inputNames.includes("pixel_mask") && !encoderFeeds.pixel_mask) {
+ if (!encoderFeeds.pixel_values) {
+ throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");
+ }
+ const dims = encoderFeeds.pixel_values.dims;
+ encoderFeeds.pixel_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([dims[0], dims[2], dims[3]]);
+ }
+ return await sessionRun(session, encoderFeeds);
+ }
+ async function autoEncoderForward(self2, model_inputs) {
+ const encoded = await self2.encode(model_inputs);
+ const decoded = await self2.decode(encoded);
+ return decoded;
+ }
+ async function decoderForward(self2, model_inputs, is_encoder_decoder = false) {
+ const session = self2.sessions[is_encoder_decoder ? "decoder_model_merged" : "model"];
+ const { past_key_values, ...new_model_inputs } = model_inputs;
+ if (session.inputNames.includes("use_cache_branch")) {
+ new_model_inputs.use_cache_branch = boolTensor(!!past_key_values);
+ }
+ if (session.inputNames.includes("position_ids") && new_model_inputs.attention_mask && !new_model_inputs.position_ids) {
+ const start_index = ["paligemma", "gemma3_text", "gemma3"].includes(self2.config.model_type) ? 1 : 0;
+ new_model_inputs.position_ids = createPositionIds(new_model_inputs, past_key_values, start_index);
+ }
+ self2.addPastKeyValues(new_model_inputs, past_key_values);
+ const fixed = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(new_model_inputs, session.inputNames);
+ return await sessionRun(session, fixed);
+ }
+ function default_merge_input_ids_with_features({
+ modality_token_id,
+ inputs_embeds,
+ modality_features,
+ input_ids,
+ attention_mask
+ }) {
+ const token_positions = input_ids.tolist().map(
+ (ids) => ids.reduce((acc, x, idx) => {
+ if (x == modality_token_id) acc.push(idx);
+ return acc;
+ }, [])
+ );
+ const n_tokens = token_positions.reduce((acc, x) => acc + x.length, 0);
+ const n_features = modality_features.dims[0];
+ if (n_tokens !== n_features) {
+ throw new Error(`Number of tokens and features do not match: tokens: ${n_tokens}, features ${n_features}`);
+ }
+ let img = 0;
+ for (let i = 0; i < token_positions.length; ++i) {
+ const tokens = token_positions[i];
+ const embeds = inputs_embeds[i];
+ for (let j = 0; j < tokens.length; ++j) {
+ embeds[tokens[j]].data.set(modality_features[img++].data);
+ }
+ }
+ return { inputs_embeds, attention_mask };
+ }
+ function default_merge_input_ids_with_image_features({
+ image_token_id,
+ inputs_embeds,
+ image_features,
+ input_ids,
+ attention_mask
+ }) {
+ return default_merge_input_ids_with_features({
+ modality_token_id: image_token_id,
+ inputs_embeds,
+ modality_features: image_features,
+ input_ids,
+ attention_mask
+ });
+ }
+ function default_merge_input_ids_with_audio_features({
+ audio_token_id,
+ inputs_embeds,
+ audio_features,
+ input_ids,
+ attention_mask
+ }) {
+ return default_merge_input_ids_with_features({
+ modality_token_id: audio_token_id,
+ inputs_embeds,
+ modality_features: audio_features,
+ input_ids,
+ attention_mask
+ });
+ }
+ async function genericTextToTextForward(self2, {
+ // Generic parameters:
+ encode_function,
+ merge_function,
+ modality_input_name,
+ modality_output_name,
+ // Produced by the tokenizer/processor:
+ input_ids = null,
+ attention_mask = null,
+ // Used during generation:
+ position_ids = null,
+ inputs_embeds = null,
+ past_key_values = null,
+ // Generic generation parameters
+ generation_config = null,
+ logits_processor = null,
+ // Additional parameters
+ ...kwargs
+ }) {
+ const modality_values = kwargs[modality_input_name];
+ if (!inputs_embeds) {
+ inputs_embeds = await self2.encode_text({ input_ids, ...kwargs });
+ if (modality_values && input_ids.dims[1] !== 1) {
+ const modality_features = await encode_function({
+ // Pass the modality values under its expected key.
+ // The caller knows whether this is audio or image.
+ [modality_input_name]: modality_values,
+ ...kwargs
+ });
+ ({ inputs_embeds, attention_mask } = merge_function({
+ [modality_output_name]: modality_features,
+ inputs_embeds,
+ input_ids,
+ attention_mask
+ }));
+ } else if (past_key_values && modality_values && input_ids.dims[1] === 1) {
+ const target_length = input_ids.dims[1];
+ const past_length = Object.values(past_key_values)[0].dims.at(-2);
+ attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([
+ (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([input_ids.dims[0], past_length]),
+ attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]])
+ ], 1);
+ }
+ }
+ if (!position_ids) {
+ if (self2.config.model_type === "qwen2_vl") {
+ const { image_grid_thw, video_grid_thw } = kwargs;
+ [position_ids] = self2.get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask);
+ }
+ }
+ const outputs = await decoderForward(self2, {
+ inputs_embeds,
+ past_key_values,
+ attention_mask,
+ position_ids,
+ generation_config,
+ logits_processor
+ }, true);
+ return outputs;
+ }
+ async function audioTextToTextForward(self2, params) {
+ return await genericTextToTextForward(self2, {
+ ...params,
+ modality_input_name: "audio_values",
+ modality_output_name: "audio_features",
+ encode_function: self2.encode_audio.bind(self2),
+ merge_function: self2._merge_input_ids_with_audio_features.bind(self2)
+ });
+ }
+ async function imageTextToTextForward(self2, params) {
+ return await genericTextToTextForward(self2, {
+ ...params,
+ modality_input_name: "pixel_values",
+ modality_output_name: "image_features",
+ encode_function: self2.encode_image.bind(self2),
+ merge_function: self2._merge_input_ids_with_image_features.bind(self2)
+ });
+ }
+ function cumsum_masked_fill(attention_mask, start_index = 0) {
+ const [bz, seq_len] = attention_mask.dims;
+ const attn_mask_data = attention_mask.data;
+ const data = new BigInt64Array(attn_mask_data.length);
+ for (let i = 0; i < bz; ++i) {
+ const start = i * seq_len;
+ let sum = BigInt(start_index);
+ for (let j = 0; j < seq_len; ++j) {
+ const index = start + j;
+ if (attn_mask_data[index] === 0n) {
+ data[index] = BigInt(1);
+ } else {
+ data[index] = sum;
+ sum += attn_mask_data[index];
+ }
+ }
+ }
+ return { data, dims: attention_mask.dims };
+ }
+ function createPositionIds(model_inputs, past_key_values = null, start_index = 0) {
+ const { input_ids, inputs_embeds, attention_mask } = model_inputs;
+ const { data, dims } = cumsum_masked_fill(attention_mask, start_index);
+ let position_ids = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", data, dims);
+ if (past_key_values) {
+ const offset = -(input_ids ?? inputs_embeds).dims.at(1);
+ position_ids = position_ids.slice(null, [offset, null]);
+ }
+ return position_ids;
+ }
+ function decoder_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) {
+ const past_length = model_inputs.past_key_values ? Object.values(model_inputs.past_key_values)[0].dims.at(-2) : 0;
+ if (!model_inputs.attention_mask) {
+ let dims;
+ for (const key of ["input_ids", "inputs_embeds", "position_ids"]) {
+ if (model_inputs[key]) {
+ dims = model_inputs[key].dims;
+ break;
+ }
+ }
+ if (!dims) {
+ throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");
+ }
+ model_inputs.attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([dims[0], past_length + dims[1]]);
+ }
+ if (model_inputs.past_key_values) {
+ const { input_ids: input_ids2, attention_mask } = model_inputs;
+ if (attention_mask && attention_mask.dims[1] > input_ids2.dims[1]) {
+ } else if (past_length < input_ids2.dims[1]) {
+ model_inputs.input_ids = input_ids2.slice(null, [past_length, null]);
+ } else {
+ }
+ }
+ return model_inputs;
+ }
+ function encoder_decoder_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) {
+ if (model_inputs.past_key_values) {
+ input_ids = input_ids.map((x) => [x.at(-1)]);
+ }
+ return {
+ ...model_inputs,
+ decoder_input_ids: toI64Tensor(input_ids)
+ };
+ }
+ function multimodal_text_to_text_prepare_inputs_for_generation(self2, ...args) {
+ if (self2.config.is_encoder_decoder) {
+ return encoder_decoder_prepare_inputs_for_generation(self2, ...args);
+ } else {
+ return decoder_prepare_inputs_for_generation(self2, ...args);
+ }
+ }
+ function multimodality_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) {
+ const has_past_key_values = !!model_inputs.past_key_values;
+ if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {
+ if (has_past_key_values) {
+ model_inputs.input_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([
+ model_inputs.input_ids,
+ model_inputs.input_ids
+ ], 0);
+ } else {
+ model_inputs.input_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([
+ model_inputs.input_ids,
+ (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(model_inputs.input_ids, BigInt(generation_config.pad_token_id))
+ ], 0);
+ model_inputs.attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([
+ model_inputs.attention_mask,
+ (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(model_inputs.attention_mask, 0n)
+ ], 0);
+ }
+ }
+ if (has_past_key_values || !model_inputs.pixel_values) {
+ model_inputs.pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([0, 0, 3, 384, 384], 1);
+ }
+ if (has_past_key_values) {
+ const num_img_tokens = 0;
+ const num_text_tokens = 1;
+ const has_image = num_img_tokens > 0 ? 1 : 0;
+ const batch_size = 1;
+ model_inputs.images_seq_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(
+ "bool",
+ new Array(num_img_tokens + num_text_tokens).fill(true).fill(false, 0, num_text_tokens),
+ [batch_size, num_img_tokens + num_text_tokens]
+ );
+ model_inputs.images_emb_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(
+ "bool",
+ new Array(num_img_tokens).fill(!!has_image),
+ [batch_size, 1, num_img_tokens]
+ );
+ }
+ return model_inputs;
+ }
+ class PreTrainedModel extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_3__.Callable {
+ /**
+ * Creates a new instance of the `PreTrainedModel` class.
+ * @param {import('./configs.js').PretrainedConfig} config The model configuration.
+ * @param {Record} sessions The inference sessions for the model.
+ * @param {Record} configs Additional configuration files (e.g., generation_config.json).
+ */
+ constructor(config, sessions, configs) {
+ super();
+ __publicField(this, "main_input_name", "input_ids");
+ __publicField(this, "forward_params", ["input_ids", "attention_mask"]);
+ this.config = config;
+ this.sessions = sessions;
+ this.configs = configs;
+ const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
+ const modelType = MODEL_TYPE_MAPPING.get(modelName);
+ this.can_generate = false;
+ this._forward = null;
+ this._prepare_inputs_for_generation = null;
+ switch (modelType) {
+ case MODEL_TYPES.DecoderOnly:
+ this.can_generate = true;
+ this._forward = decoderForward;
+ this._prepare_inputs_for_generation = decoder_prepare_inputs_for_generation;
+ break;
+ case MODEL_TYPES.Seq2Seq:
+ case MODEL_TYPES.Vision2Seq:
+ case MODEL_TYPES.Musicgen:
+ this.can_generate = true;
+ this._forward = seq2seqForward;
+ this._prepare_inputs_for_generation = encoder_decoder_prepare_inputs_for_generation;
+ break;
+ case MODEL_TYPES.EncoderDecoder:
+ this._forward = seq2seqForward;
+ break;
+ case MODEL_TYPES.ImageTextToText:
+ this.can_generate = true;
+ this._forward = imageTextToTextForward;
+ this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation;
+ break;
+ case MODEL_TYPES.AudioTextToText:
+ this.can_generate = true;
+ this._forward = audioTextToTextForward;
+ this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation;
+ break;
+ case MODEL_TYPES.Phi3V:
+ case MODEL_TYPES.ImageAudioTextToText:
+ this.can_generate = true;
+ this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation;
+ break;
+ case MODEL_TYPES.MultiModality:
+ this.can_generate = true;
+ this._prepare_inputs_for_generation = multimodality_prepare_inputs_for_generation;
+ break;
+ case MODEL_TYPES.AutoEncoder:
+ this._forward = autoEncoderForward;
+ break;
+ default:
+ this._forward = encoderForward;
+ break;
+ }
+ if (this.can_generate) {
+ this.forward_params.push("past_key_values");
+ }
+ this.custom_config = this.config["transformers.js_config"] ?? {};
+ }
+ /**
+ * Disposes of all the ONNX sessions that were created during inference.
+ * @returns {Promise} An array of promises, one for each ONNX session that is being disposed.
+ * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
+ */
+ async dispose() {
+ const promises = [];
+ for (const session of Object.values(this.sessions)) {
+ if (session?.handler?.dispose) {
+ promises.push(session.handler.dispose());
+ }
+ }
+ return await Promise.all(promises);
+ }
+ /**
+ * Instantiate one of the model classes of the library from a pretrained model.
+ *
+ * The model class to instantiate is selected based on the `model_type` property of the config object
+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
+ *
+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
+ * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
+ * user or organization name, like `dbmdz/bert-base-german-cased`.
+ * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
+ * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.
+ *
+ * @returns {Promise} A new instance of the `PreTrainedModel` class.
+ */
+ static async from_pretrained(pretrained_model_name_or_path, {
+ progress_callback = null,
+ config = null,
+ cache_dir = null,
+ local_files_only = false,
+ revision = "main",
+ model_file_name = null,
+ subfolder = "onnx",
+ device = null,
+ dtype = null,
+ use_external_data_format = null,
+ session_options = {}
+ } = {}) {
+ let options = {
+ progress_callback,
+ config,
+ cache_dir,
+ local_files_only,
+ revision,
+ model_file_name,
+ subfolder,
+ device,
+ dtype,
+ use_external_data_format,
+ session_options
+ };
+ const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);
+ const modelType = MODEL_TYPE_MAPPING.get(modelName);
+ config = options.config = await _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options);
+ let info;
+ if (modelType === MODEL_TYPES.DecoderOnly) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ model: options.model_file_name ?? "model"
+ }, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ model: "encoder_model",
+ decoder_model_merged: "decoder_model_merged"
+ }, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.MaskGeneration) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ model: "vision_encoder",
+ prompt_encoder_mask_decoder: "prompt_encoder_mask_decoder"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.EncoderDecoder) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ model: "encoder_model",
+ decoder_model_merged: "decoder_model_merged"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.ImageTextToText) {
+ const sessions = {
+ embed_tokens: "embed_tokens",
+ vision_encoder: "vision_encoder",
+ decoder_model_merged: "decoder_model_merged"
+ };
+ if (config.is_encoder_decoder) {
+ sessions["model"] = "encoder_model";
+ }
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, sessions, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.AudioTextToText) {
+ const sessions = {
+ embed_tokens: "embed_tokens",
+ audio_encoder: "audio_encoder",
+ decoder_model_merged: "decoder_model_merged"
+ };
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, sessions, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.ImageAudioTextToText) {
+ const sessions = {
+ embed_tokens: "embed_tokens",
+ audio_encoder: "audio_encoder",
+ vision_encoder: "vision_encoder",
+ decoder_model_merged: "decoder_model_merged"
+ };
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, sessions, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.Musicgen) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ model: "text_encoder",
+ decoder_model_merged: "decoder_model_merged",
+ encodec_decode: "encodec_decode"
+ }, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.MultiModality) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ prepare_inputs_embeds: "prepare_inputs_embeds",
+ model: "language_model",
+ lm_head: "lm_head",
+ gen_head: "gen_head",
+ gen_img_embeds: "gen_img_embeds",
+ image_decode: "image_decode"
+ }, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.Phi3V) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ prepare_inputs_embeds: "prepare_inputs_embeds",
+ model: "model",
+ vision_encoder: "vision_encoder"
+ }, options),
+ getOptionalConfigs(pretrained_model_name_or_path, {
+ generation_config: "generation_config.json"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.AutoEncoder) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ encoder_model: "encoder_model",
+ decoder_model: "decoder_model"
+ }, options)
+ ]);
+ } else if (modelType === MODEL_TYPES.Supertonic) {
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ text_encoder: "text_encoder",
+ latent_denoiser: "latent_denoiser",
+ voice_decoder: "voice_decoder"
+ }, options)
+ ]);
+ } else {
+ if (modelType !== MODEL_TYPES.EncoderOnly) {
+ const type = modelName ?? config?.model_type;
+ if (type !== "custom") {
+ console.warn(`Model type for '${type}' not found, assuming encoder-only architecture. Please report this at ${_utils_constants_js__WEBPACK_IMPORTED_MODULE_6__.GITHUB_ISSUE_URL}.`);
+ }
+ }
+ info = await Promise.all([
+ constructSessions(pretrained_model_name_or_path, {
+ model: options.model_file_name ?? "model"
+ }, options)
+ ]);
+ }
+ return new this(config, ...info);
+ }
+ /**
+ * Runs the model with the provided inputs
+ * @param {Object} model_inputs Object containing input tensors
+ * @returns {Promise