diff --git "a/assets/worker-B81g4upz.js" "b/assets/worker-B81g4upz.js" new file mode 100644--- /dev/null +++ "b/assets/worker-B81g4upz.js" @@ -0,0 +1,2269 @@ +(function(){"use strict";var He={},lm=Object.freeze({__proto__:null,default:He});const um="3.0.0-alpha.0",Ln=typeof self<"u",dm=Ln&&self.constructor.name==="DedicatedWorkerGlobalScope",zs=Ln&&"caches"in self,cm=typeof navigator<"u"&&"gpu"in navigator,pm=typeof process<"u"&&process?.release?.name==="node",Un=!Ds(He),Rs=!Ds(He),Lr=Object.freeze({IS_BROWSER_ENV:Ln,IS_WEBWORKER_ENV:dm,IS_WEB_CACHE_AVAILABLE:zs,IS_WEBGPU_AVAILABLE:cm,IS_NODE_ENV:pm,IS_FS_AVAILABLE:Un,IS_PATH_AVAILABLE:Rs}),Ha=Un&&Rs,Ps=Ha?He.dirname(He.dirname(He.fileURLToPath(self.location.href))):"./",hm=Ha?He.join(Ps,"/.cache/"):null,Bs="/models/",fm=Ha?He.join(Ps,Bs):Bs,dt={version:um,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ln,localModelPath:fm,useFS:Un,useBrowserCache:zs,useFSCache:Un,cacheDir:hm,useCustomCache:!1,customCache:null};function Ds(t){return Object.keys(t).length===0}const Dt=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function Ur(t,e){t&&t(e)}function mm(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e]))}function Ns(t){const e=[];let r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function gm(...t){return Array.prototype.concat.apply([],t)}function Fn(t,e){return Math.abs((t+e)%(2*e)-e)}function $r(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}var qa={};class Wn{_CONTENT_TYPE_MAP={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=He.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=He.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let n=this;this.body=new ReadableStream({start(a){n.arrayBuffer().then(i=>{a.enqueue(new Uint8Array(i)),a.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new Wn(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await He.promises.readFile(this.filePath)).buffer}async blob(){const e=await He.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await He.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function ja(t,e=null){let r;try{r=new URL(t)}catch{return!1}return e&&!e.includes(r.hostname)?!1:r.protocol==="http:"||r.protocol==="https:"}async function Ka(t){if(dt.useFS&&!ja(t))return new Wn(t);if(typeof process<"u"&&process?.release?.name==="node"){const e=!!qa?.TESTING_REMOTELY,r=dt.version,n=new Headers;if(n.set("User-Agent",`transformers.js/${r}; is_ci/${e};`),ja(t,["huggingface.co","hf.co"])){const i=qa?.HF_TOKEN??qa?.HF_ACCESS_TOKEN;i&&n.set("Authorization",`Bearer ${i}`)}return fetch(t,{headers:n})}else return fetch(t)}const _m={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function ym(t,e,r){if(!r)return null;const n=_m[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${n}: "${e}".`)}class Ls{constructor(e){this.path=e}async match(e){let r=He.join(this.path,e),n=new Wn(r);if(n.exists)return n}async put(e,r){const n=Buffer.from(await r.arrayBuffer());let a=He.join(this.path,e);try{await He.promises.mkdir(He.dirname(a),{recursive:!0}),await He.promises.writeFile(a,n)}catch(i){console.warn("An error occurred while writing the file to cache:",i)}}}async function wm(t,...e){for(let r of e)try{let n=await t.match(r);if(n)return n}catch{continue}}async function Ya(t,e,r=!0,n={}){if(!dt.allowLocalModels&&n.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");Ur(n.progress_callback,{status:"initiate",name:t,file:e});let a;if(!a&&dt.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{a=await caches.open("transformers-cache")}catch(x){console.warn("An error occurred while opening the browser cache:",x)}}if(!a&&dt.useFSCache&&(a=new Ls(n.cache_dir??dt.cacheDir)),!a&&dt.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const i=n.revision??"main";let s=Gn(t,e),o=Gn(dt.localModelPath,s),l=Gn(dt.remoteHost,dt.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(i)),e),d=i==="main"?s:Gn(t,i,e),p,u=a instanceof Ls?d:l,h=!1,m;a&&(m=await wm(a,o,u));const _=m!==void 0;if(m===void 0){if(dt.allowLocalModels)if(ja(s)){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else try{m=await Ka(o),p=o}catch(w){console.warn(`Unable to load from local path "${o}": "${w}"`)}if(m===void 0||m.status===404){if(n.local_files_only||!dt.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${o}".`);return null}if(m=await Ka(l),m.status!==200)return ym(m.status,l,r);p=u}h=a&&typeof Response<"u"&&m instanceof Response&&m.status===200}Ur(n.progress_callback,{status:"download",name:t,file:e});const y={status:"progress",name:t,file:e};let v;return n.progress_callback?_&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(v=new Uint8Array(await m.arrayBuffer()),Ur(n.progress_callback,{...y,progress:100,loaded:v.length,total:v.length})):v=await bm(m,x=>{Ur(n.progress_callback,{...y,...x})}):v=new Uint8Array(await m.arrayBuffer()),h&&p&&await a.match(p)===void 0&&await a.put(p,new Response(v,{headers:m.headers})).catch(x=>{console.warn(`Unable to add response to browser cache: ${x}.`)}),Ur(n.progress_callback,{status:"done",name:t,file:e}),v}async function xr(t,e,r=!0,n={}){let a=await Ya(t,e,r,n);if(a===null)return{};let s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}async function bm(t,e){const r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let n=parseInt(r??"0"),a=new Uint8Array(n),i=0;const s=t.body.getReader();async function o(){const{done:l,value:d}=await s.read();if(l)return;let p=i+d.length;if(p>n){n=p;let h=new Uint8Array(n);h.set(a),a=h}a.set(d,i),i=p;const u=i/n*100;return e({progress:u,loaded:i,total:n}),o()}return await o(),a}function Gn(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function vm(t,[e,r,n],[a,i],s="bilinear",o=!1){const l=i/n,d=a/r,p=new t.constructor(a*i*e),u=r*n,h=a*i;for(let m=0;m=0;--o)a[o]=l,n[o]=e[r[o]],l*=n[o];const i=r.map((o,l)=>a[r.indexOf(l)]),s=new t.constructor(t.length);for(let o=0;o=0;--d)l+=p%e[d]*i[d],p=Math.floor(p/e[d]);s[l]=t[o]}return[s,n]}function Vn(t){const e=er(t)[0],r=t.map(i=>Math.exp(i-e)),n=r.reduce((i,s)=>i+s,0);return r.map(i=>i/n)}function Us(t,e=0){return t=Array.from(t).map((r,n)=>[n,r]).sort((r,n)=>n[1]-r[1]),e!==null&&e>0&&(t=t.slice(0,e)),t}function xm(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let n=1;ne&&(e=t[n],r=n);return[Number(e),r]}function Fs(t){return t>0&&(t&t-1)===0}class Ws{constructor(e){if(this.size=e|0,this.size<=1||!Fs(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let n=0;nn;n<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>a&3)<>>1);for(let a=0;a>>1]=e[a];return n}toComplexArray(e,r){const n=r||this.createComplexArray();for(let a=0;a>>1],n[a+1]=0;return n}completeSpectrum(e){const r=this._csize,n=r>>>1;for(let a=2;a>=2;s>=2;s>>=2){o=a/s<<1;const u=o>>>2;for(l=0;l>>1,s>>>1)}else for(l=0,d=0;l>>1,s>>>1,n)}for(s>>=2;s>=2;s>>=2){o=a/s<<1;const u=o>>>2;for(l=0;l>1;++p){const u=(p+1-e)**2/2,h=Math.sqrt(l**2+d**2)**u,m=u*Math.atan2(d,l),_=2*p;i[_]=h*Math.cos(m),i[_+1]=h*Math.sin(m),s[_]=i[_],s[_+1]=-i[_+1]}this._slicedChirpBuffer=i.subarray(r,n),this._f=new Ws(a>>1),this._f.transform(this._chirpBuffer,s)}_transform(e,r,n){const a=this._buffer1,i=this._buffer2,s=this._outBuffer1,o=this._outBuffer2,l=this._chirpBuffer,d=this._slicedChirpBuffer,p=this._a;if(n)for(let u=0;u>1,_=r[m];a[u]=_*d[u],a[h]=_*d[h]}else for(let u=0;u=t.length&&(l=2*(t.length-1)-l),n[s++]=t[l]}n.sort(),r[i]=n[a]}return r}function Im(t){const e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}/*! + * ONNX Runtime Web v1.17.3 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var Xa=Object.defineProperty,km=Object.getOwnPropertyDescriptor,Tm=Object.getOwnPropertyNames,Am=Object.prototype.hasOwnProperty,V=(t,e)=>()=>(t&&(e=t(t=0)),e),Sr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Er=(t,e)=>{for(var r in e)Xa(t,r,{get:e[r],enumerable:!0})},Mm=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Tm(e))!Am.call(t,a)&&a!==r&&Xa(t,a,{get:()=>e[a],enumerable:!(n=km(e,a))||n.enumerable});return t},tr=t=>Mm(Xa({},"__esModule",{value:!0}),t),Fr,Gt,rr,Gs,Qa,Za=V(()=>{Fr=new Map,Gt=[],rr=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let n=Fr.get(t);if(n===void 0)Fr.set(t,{backend:e,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let a=Gt.indexOf(t);a!==-1&&Gt.splice(a,1);for(let i=0;i{let e=Fr.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(n){return r||(e.error=`${n}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Qa=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),n=r.length===0?Gt:r,a,i=[],s=new Set;for(let l of n){let d=await Gs(l);typeof d=="string"?i.push({name:l,err:d}):(a||(a=d),a===d&&s.add(l))}if(!a)throw new Error(`no available backend found. ERR: ${i.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:d}of i)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${d}`);let o=e.filter(l=>s.has(typeof l=="string"?l:l.name));return[a,new Proxy(t,{get:(l,d)=>d==="executionProviders"?o:Reflect.get(l,d)})]}}),Om=V(()=>{Za()}),Vs,zm=V(()=>{Vs="1.17.3"}),Ja,ht,Hs=V(()=>{zm(),Ja="warning",ht={wasm:{},webgl:{},webgpu:{},versions:{common:Vs},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Ja=t}},get logLevel(){return Ja}},Object.defineProperty(ht,"logLevel",{enumerable:!0})}),Oe,Rm=V(()=>{Hs(),Oe=ht}),qs,js,Pm=V(()=>{qs=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let n=r.getContext("2d");if(n!=null){let a,i;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],i=t.dims[3]):(a=t.dims[3],i=t.dims[2]);let s=e?.format!==void 0?e.format:"RGB",o=e?.norm,l,d;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?d=[0,0,0,0]:typeof o.bias=="number"?d=[o.bias,o.bias,o.bias,o.bias]:(d=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(d[3]=o.bias[3]));let p=i*a,u=0,h=p,m=p*2,_=-1;s==="RGBA"?(u=0,h=p,m=p*2,_=p*3):s==="RGB"?(u=0,h=p,m=p*2):s==="RBG"&&(u=0,m=p,h=p*2);for(let y=0;y{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let a,i,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],i=t.dims[1],s=t.dims[3]):(a=t.dims[3],i=t.dims[2],s=t.dims[1]);let o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let u=i*a;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,m=0,_=1,y=2,v=3,x=0,w=u,E=u*2,I=-1;o==="RGBA"?(x=0,w=u,E=u*2,I=u*3):o==="RGB"?(x=0,w=u,E=u*2):o==="RBG"&&(x=0,E=u,w=u*2),n=r.createImageData(a,i);for(let k=0;k{ti(),Hn=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=e,a=e.norm??{mean:255,bias:0},i,s;typeof a.mean=="number"?i=[a.mean,a.mean,a.mean,a.mean]:i=[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],typeof a.bias=="number"?s=[a.bias,a.bias,a.bias,a.bias]:s=[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];let o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",d=r*n,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),u=4,h=0,m=1,_=2,y=3,v=0,x=d,w=d*2,E=-1;o==="RGB"&&(u=3,h=0,m=1,_=2,y=-1),l==="RGBA"?E=d*3:l==="RBG"?(v=0,w=d,x=d*2):l==="BGR"&&(w=0,x=d,v=d*2);for(let I=0;I{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,n=typeof ImageData<"u"&&t instanceof ImageData,a=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,i=typeof t=="string",s,o=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let u=d(p);if(u!=null){let h=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(o=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=h,o.width=m}else o.tensorFormat="RGBA",o.height=h,o.width=m;u.drawImage(t,0,0),s=u.getImageData(0,0,m,h).data}else throw new Error("Can not access image data")}else if(n){let p,u;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,u=e.resizedWidth):(p=t.height,u=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=p,o.width=u,e!==void 0){let h=l();h.width=u,h.height=p;let m=d(h);if(m!=null)m.putImageData(t,0,0),s=m.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else s=t.data}else if(a){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let u=d(p);if(u!=null){let h=t.height,m=t.width;return u.drawImage(t,0,0,m,h),s=u.getImageData(0,0,m,h).data,o.height=h,o.width=m,Hn(s,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((p,u)=>{let h=l(),m=d(h);if(!t||!m)return u();let _=new Image;_.crossOrigin="Anonymous",_.src=t,_.onload=()=>{h.width=_.width,h.height=_.height,m.drawImage(_,0,0,h.width,h.height);let y=m.getImageData(0,0,h.width,h.height);o.height=h.height,o.width=h.width,p(Hn(y.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return Hn(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},Ys=(t,e)=>{let{width:r,height:n,download:a,dispose:i}=e,s=[1,n,r,4];return new vt({location:"texture",type:"float32",texture:t,dims:s,download:a,dispose:i})},Xs=(t,e)=>{let{dataType:r,dims:n,download:a,dispose:i}=e;return new vt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:i})},Qs=(t,e,r)=>new vt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),nr,Wr,ei,Zs,Dm=V(()=>{nr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Wr=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ei=!1,Zs=()=>{if(!ei){ei=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;t&&(nr.set("int64",BigInt64Array),Wr.set(BigInt64Array,"int64")),e&&(nr.set("uint64",BigUint64Array),Wr.set(BigUint64Array,"uint64")),r?(nr.set("float16",Float16Array),Wr.set(Float16Array,"float16")):nr.set("float16",Uint16Array)}}}),Js,eo,Nm=V(()=>{ti(),Js=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new vt(t.type,t.data,e);case"cpu-pinned":return new vt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new vt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new vt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),vt,ti=V(()=>{Pm(),Bm(),Dm(),Nm(),vt=class{constructor(t,e,r){Zs();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case"cpu-pinned":{let s=nr.get(n);if(!s)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof s))throw new TypeError(`buffer should be of type ${s.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,o;if(typeof t=="string")if(n=t,o=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");s=e}else{let l=nr.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");t==="uint64"||t==="int64"?s=l.from(e,BigInt):s=l.from(e)}else if(e instanceof l)s=e;else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(o=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")n="string",s=t;else if(l==="boolean")n="bool",s=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else{let l=Wr.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=l,s=t}if(o===void 0)o=[s.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");a=o,this.cpuData=s,this.dataLocation="cpu"}let i=Js(a);if(this.cpuData&&i!==this.cpuData.length)throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=i}static async fromImage(t,e){return Ks(t,e)}static fromTexture(t,e){return Ys(t,e)}static fromGpuBuffer(t,e){return Xs(t,e)}static fromPinnedBuffer(t,e,r){return Qs(t,e,r)}toDataURL(t){return qs(this,t)}toImageData(t){return js(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}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(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 eo(this,t)}}}),st,ri=V(()=>{ti(),st=vt}),Gr,ni,$t,ft,to=V(()=>{Hs(),Gr=(t,e)=>{(typeof ht.trace>"u"?!ht.wasm.trace:!ht.trace)||console.timeStamp(`${t}::ORT::${e}`)},ni=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let a=0;a{(typeof ht.trace>"u"?!ht.wasm.trace:!ht.trace)||ni("BEGIN",t)},ft=t=>{(typeof ht.trace>"u"?!ht.wasm.trace:!ht.trace)||ni("END",t)}}),ro,Lm=V(()=>{Za(),ri(),to(),ro=class im{constructor(e){this.handler=e}async run(e,r,n){$t();let a={},i={};if(typeof e!="object"||e===null||e instanceof st||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof st)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.");s=!1;for(let d of r){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);a[d]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,p=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(p.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof st)&&(d=!0,s=!1,a[u]=h)}if(d){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 d of this.inputNames)if(typeof e[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(s)for(let d of this.outputNames)a[d]=null;let o=await this.handler.run(e,a,i),l={};for(let d in o)if(Object.hasOwnProperty.call(o,d)){let p=o[d];p instanceof st?l[d]=p:l[d]=new st(p.type,p.data,p.dims)}return ft(),l}async release(){return this.handler.dispose()}static async create(e,r,n,a){$t();let i,s={};if(typeof e=="string"){if(i=e,typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(i=e,typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,u=0,h=e.byteLength;if(typeof r=="object"&&r!==null)s=r;else if(typeof r=="number"){if(u=r,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=e.byteLength-u,typeof n=="number"){if(h=n,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof a=="object"&&a!==null)s=a;else if(typeof a<"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,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await Qa(s),d=await o.createInferenceSessionHandler(i,l);return ft(),new im(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ai,Um=V(()=>{Lm(),ai=ro}),Fm=V(()=>{}),Wm=V(()=>{}),Gm=V(()=>{}),Vm=V(()=>{}),no,ao,Hm=V(()=>{Za(),ri(),no="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",ao=class sm{constructor(e,r,n){this.handler=e,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,r){let n=e.evalModel||"",a=e.optimizerModel||"",i=r||{},[s,o]=await Qa(i);if(s.createTrainingSessionHandler){let l=await s.createTrainingSessionHandler(e.checkpointState,e.trainModel,n,a,o);return new sm(l,!!e.optimizerModel,!!e.evalModel)}else throw new Error(no)}typeNarrowingForRunStep(e,r,n,a,i){let s={},o={};if(typeof n!="object"||n===null||n instanceof st||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof a=="object"){if(a===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(a instanceof st)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(a)){if(a.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(let d of a){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);s[d]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,p=Object.getOwnPropertyNames(a);for(let u of r)if(p.indexOf(u)!==-1){let h=a[u];(h===null||h instanceof st)&&(d=!0,l=!1,s[u]=h)}if(d){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=a}}else if(typeof a<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let d of e)if(typeof n[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(l)for(let d of r)s[d]=null;return[s,o]}convertHandlerReturnTypeToMapOfTensors(e){let r={};for(let n in e)if(Object.hasOwnProperty.call(e,n)){let a=e[n];a instanceof st?r[n]=a:r[n]=new st(a.type,a.data,a.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,r,n){let[a,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,r,n),s=await this.handler.runTrainStep(e,a,i);return this.convertHandlerReturnTypeToMapOfTensors(s)}async runOptimizerStep(e){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(e||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(e,r,n){if(this.hasEvalModel){let[a,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,r,n),s=await this.handler.runEvalStep(e,a,i);return this.convertHandlerReturnTypeToMapOfTensors(s)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,r=!0){let n=await this.getParametersSize(r);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,r)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}}),ii,qm=V(()=>{Hm(),ii=ao}),io={};Er(io,{InferenceSession:()=>ai,TRACE:()=>Gr,TRACE_FUNC_BEGIN:()=>$t,TRACE_FUNC_END:()=>ft,Tensor:()=>st,TrainingSession:()=>ii,env:()=>Oe,registerBackend:()=>rr});var xt=V(()=>{Om(),Rm(),Um(),ri(),Fm(),Wm(),to(),Gm(),Vm(),qm()}),si={};Er(si,{createReadStream:()=>lo,readFile:()=>so,readFileSync:()=>oo});var so,oo,lo,uo=V(()=>{so=void 0,oo=void 0,lo=void 0}),oi={};Er(oi,{join:()=>co});var co,po=V(()=>{co=void 0}),jm=Sr((t,e)=>{var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(a={}){var i=a,s,o;i.ready=new Promise((f,b)=>{s=f,o=b}),i.mountExternalData=(f,b)=>{(i.Fa||(i.Fa=new Map)).set(f,b)},i.unmountExternalData=()=>{delete i.Fa};let l=()=>{let f=(S,T,O)=>(...U)=>{let X=pt,se=T?.();U=S(...U);let _e=T?.();return se!==_e&&(S=_e,O(se),T=O=null),pt!=X?za():U},b=S=>async(...T)=>{try{if(i.Ea)throw Error("Session already started");let O=i.Ea={Za:T[0],errors:[]},U=await S(...T);if(i.Ea!==O)throw Error("Session mismatch");i.La?.flush();let X=O.errors;if(0_e),0i._OrtCreateSession,S=>i._OrtCreateSession=S),i._OrtRun=b(f(i._OrtRun,()=>i._OrtRun,S=>i._OrtRun=S)),i._OrtRunWithBinding=b(f(i._OrtRunWithBinding,()=>i._OrtRunWithBinding,S=>i._OrtRunWithBinding=S)),i._OrtBindInput=f(i._OrtBindInput,()=>i._OrtBindInput,S=>i._OrtBindInput=S),l=void 0};i.jsepInit=(f,b)=>{if(l?.(),f==="webgpu"){[i.La,i.Ra,i.Va,i.Ma,i.Ua,i.sa,i.Wa,i.Ya,i.Sa,i.Ta,i.Xa]=b;let S=i.La;i.jsepRegisterBuffer=(T,O,U,X)=>S.registerBuffer(T,O,U,X),i.jsepGetBuffer=T=>S.getBuffer(T),i.jsepCreateDownloader=(T,O,U)=>S.createDownloader(T,O,U),i.jsepOnReleaseSession=T=>{S.onReleaseSession(T)},i.jsepOnRunStart=T=>S.onRunStart(T)}};var d=Object.assign({},i),p="./this.program",u=(f,b)=>{throw b},h=typeof window=="object",m=typeof importScripts=="function",_=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",y="",v,x,w;if(_){var E=(uo(),tr(si)),I=(po(),tr(oi));y=m?I.dirname(y)+"/":__dirname+"/",v=(f,b)=>(f=ze(f)?new URL(f):I.normalize(f),E.readFileSync(f,b?void 0:"utf8")),w=f=>(f=v(f,!0),f.buffer||(f=new Uint8Array(f)),f),x=(f,b,S,T=!0)=>{f=ze(f)?new URL(f):I.normalize(f),E.readFile(f,T?void 0:"utf8",(O,U)=>{O?S(O):b(T?U.buffer:U)})},!i.thisProgram&&1{throw process.exitCode=f,b},i.inspect=()=>"[Emscripten Module object]"}else(h||m)&&(m?y=self.location.href:typeof document<"u"&&document.currentScript&&(y=document.currentScript.src),n&&(y=n),y.indexOf("blob:")!==0?y=y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):y="",v=f=>{var b=new XMLHttpRequest;return b.open("GET",f,!1),b.send(null),b.responseText},m&&(w=f=>{var b=new XMLHttpRequest;return b.open("GET",f,!1),b.responseType="arraybuffer",b.send(null),new Uint8Array(b.response)}),x=(f,b,S)=>{var T=new XMLHttpRequest;T.open("GET",f,!0),T.responseType="arraybuffer",T.onload=()=>{T.status==200||T.status==0&&T.response?b(T.response):S()},T.onerror=S,T.send(null)});var k=console.log.bind(console),A=console.error.bind(console);Object.assign(i,d),d=null,typeof WebAssembly!="object"&&Q("no native wasm support detected");var D,L=!1,Y,H,re,N,ee,oe,Ae;function q(){var f=D.buffer;i.HEAP8=H=new Int8Array(f),i.HEAP16=new Int16Array(f),i.HEAPU8=re=new Uint8Array(f),i.HEAPU16=new Uint16Array(f),i.HEAP32=N=new Int32Array(f),i.HEAPU32=ee=new Uint32Array(f),i.HEAPF32=oe=new Float32Array(f),i.HEAPF64=Ae=new Float64Array(f)}var J=[],ae=[],W=[],te=0,B=null;function Q(f){throw f="Aborted("+f+")",A(f),L=!0,Y=1,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),o(f),f}var he=f=>f.startsWith("data:application/octet-stream;base64,"),ze=f=>f.startsWith("file://"),Re;if(Re="ort-wasm-simd.wasm",!he(Re)){var Je=Re;Re=i.locateFile?i.locateFile(Je,y):y+Je}function Ve(f){if(w)return w(f);throw"both async and sync fetching of the wasm failed"}function at(f){if(h||m){if(typeof fetch=="function"&&!ze(f))return fetch(f,{credentials:"same-origin"}).then(b=>{if(!b.ok)throw"failed to load wasm binary file at '"+f+"'";return b.arrayBuffer()}).catch(()=>Ve(f));if(x)return new Promise((b,S)=>{x(f,T=>b(new Uint8Array(T)),S)})}return Promise.resolve().then(()=>Ve(f))}function ut(f,b,S){return at(f).then(T=>WebAssembly.instantiate(T,b)).then(T=>T).then(S,T=>{A(`failed to asynchronously prepare wasm: ${T}`),Q(T)})}function Le(f,b){var S=Re;return typeof WebAssembly.instantiateStreaming!="function"||he(S)||ze(S)||_||typeof fetch!="function"?ut(S,f,b):fetch(S,{credentials:"same-origin"}).then(T=>WebAssembly.instantiateStreaming(T,f).then(b,function(O){return A(`wasm streaming compile failed: ${O}`),A("falling back to ArrayBuffer instantiation"),ut(S,f,b)}))}var qe,it={931760:(f,b,S,T)=>{if(typeof i>"u"||!i.Fa)return 1;if(f=Ye(f>>>0),f.startsWith("./")&&(f=f.substring(2)),f=i.Fa.get(f),!f)return 2;if(b>>>=0,S>>>=0,b+S>f.byteLength)return 3;try{return re.set(f.subarray(b,b+S),T>>>0>>>0),0}catch{return 4}},932261:()=>{i.Sa()},932292:()=>{i.Ta()},932321:()=>{i.Xa()},932346:f=>i.Ra(f),932379:f=>i.Va(f),932411:(f,b,S)=>{i.Ma(f,b,S,!0)},932450:(f,b,S)=>{i.Ma(f,b,S)},932483:f=>{i.sa("Abs",f,void 0)},932534:f=>{i.sa("Neg",f,void 0)},932585:f=>{i.sa("Floor",f,void 0)},932638:f=>{i.sa("Ceil",f,void 0)},932690:f=>{i.sa("Reciprocal",f,void 0)},932748:f=>{i.sa("Sqrt",f,void 0)},932800:f=>{i.sa("Exp",f,void 0)},932851:f=>{i.sa("Erf",f,void 0)},932902:f=>{i.sa("Sigmoid",f,void 0)},932957:(f,b,S)=>{i.sa("HardSigmoid",f,{alpha:b,beta:S})},933036:f=>{i.sa("Log",f,void 0)},933087:f=>{i.sa("Sin",f,void 0)},933138:f=>{i.sa("Cos",f,void 0)},933189:f=>{i.sa("Tan",f,void 0)},933240:f=>{i.sa("Asin",f,void 0)},933292:f=>{i.sa("Acos",f,void 0)},933344:f=>{i.sa("Atan",f,void 0)},933396:f=>{i.sa("Sinh",f,void 0)},933448:f=>{i.sa("Cosh",f,void 0)},933500:f=>{i.sa("Asinh",f,void 0)},933553:f=>{i.sa("Acosh",f,void 0)},933606:f=>{i.sa("Atanh",f,void 0)},933659:f=>{i.sa("Tanh",f,void 0)},933711:f=>{i.sa("Not",f,void 0)},933762:(f,b,S)=>{i.sa("Clip",f,{min:b,max:S})},933831:f=>{i.sa("Clip",f,void 0)},933883:(f,b)=>{i.sa("Elu",f,{alpha:b})},933941:f=>{i.sa("Relu",f,void 0)},933993:(f,b)=>{i.sa("LeakyRelu",f,{alpha:b})},934057:(f,b)=>{i.sa("ThresholdedRelu",f,{alpha:b})},934127:(f,b)=>{i.sa("Cast",f,{to:b})},934185:f=>{i.sa("Add",f,void 0)},934236:f=>{i.sa("Sub",f,void 0)},934287:f=>{i.sa("Mul",f,void 0)},934338:f=>{i.sa("Div",f,void 0)},934389:f=>{i.sa("Pow",f,void 0)},934440:f=>{i.sa("Equal",f,void 0)},934493:f=>{i.sa("Greater",f,void 0)},934548:f=>{i.sa("GreaterOrEqual",f,void 0)},934610:f=>{i.sa("Less",f,void 0)},934662:f=>{i.sa("LessOrEqual",f,void 0)},934721:(f,b,S,T,O)=>{i.sa("ReduceMean",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},934880:(f,b,S,T,O)=>{i.sa("ReduceMax",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},935038:(f,b,S,T,O)=>{i.sa("ReduceMin",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},935196:(f,b,S,T,O)=>{i.sa("ReduceProd",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},935355:(f,b,S,T,O)=>{i.sa("ReduceSum",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},935513:(f,b,S,T,O)=>{i.sa("ReduceL1",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},935670:(f,b,S,T,O)=>{i.sa("ReduceL2",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},935827:(f,b,S,T,O)=>{i.sa("ReduceLogSum",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},935988:(f,b,S,T,O)=>{i.sa("ReduceSumSquare",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},936152:(f,b,S,T,O)=>{i.sa("ReduceLogSumExp",f,{keepDims:!!b,noopWithEmptyAxes:!!S,axes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},936316:f=>{i.sa("Where",f,void 0)},936369:(f,b,S)=>{i.sa("Transpose",f,{perm:b?Array.from(N.subarray(b>>>0,S>>>0)):[]})},936477:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z,fe)=>{i.sa("ConvTranspose",f,{format:_e?"NHWC":"NCHW",autoPad:b,dilations:[S],group:T,kernel_shape:[O],pads:[U,X],strides:[se],wIsConst:()=>!!H[ye>>>0],outputPadding:$e?Array.from(N.subarray($e>>>0,Pe>>>0)):[],outputShape:Be?Array.from(N.subarray(Be>>>0,z>>>0)):[],activation:Ye(fe)})},936879:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z)=>{i.sa("ConvTranspose",f,{format:se?"NHWC":"NCHW",autoPad:b,dilations:Array.from(N.subarray(S>>>0,(S>>>0)+2>>>0)),group:T,kernelShape:Array.from(N.subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(N.subarray(U>>>0,(U>>>0)+4>>>0)),strides:Array.from(N.subarray(X>>>0,(X>>>0)+2>>>0)),wIsConst:()=>!!H[_e>>>0],outputPadding:ye?Array.from(N.subarray(ye>>>0,$e>>>0)):[],outputShape:Pe?Array.from(N.subarray(Pe>>>0,Be>>>0)):[],activation:Ye(z)})},937444:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z,fe)=>{i.sa("ConvTranspose",f,{format:_e?"NHWC":"NCHW",autoPad:b,dilations:[S],group:T,kernel_shape:[O],pads:[U,X],strides:[se],wIsConst:()=>!!H[ye>>>0],outputPadding:$e?Array.from(N.subarray($e>>>0,Pe>>>0)):[],outputShape:Be?Array.from(N.subarray(Be>>>0,z>>>0)):[],activation:Ye(fe)})},937846:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z)=>{i.sa("ConvTranspose",f,{format:se?"NHWC":"NCHW",autoPad:b,dilations:Array.from(N.subarray(S>>>0,(S>>>0)+2>>>0)),group:T,kernelShape:Array.from(N.subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(N.subarray(U>>>0,(U>>>0)+4>>>0)),strides:Array.from(N.subarray(X>>>0,(X>>>0)+2>>>0)),wIsConst:()=>!!H[_e>>>0],outputPadding:ye?Array.from(N.subarray(ye>>>0,$e>>>0)):[],outputShape:Pe?Array.from(N.subarray(Pe>>>0,Be>>>0)):[],activation:Ye(z)})},938411:(f,b)=>{i.sa("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},938502:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z,fe,Ie)=>{i.sa("AveragePool",f,{format:Ie?"NHWC":"NCHW",auto_pad:b,ceil_mode:S,count_include_pad:T,storage_order:O,dilations:[U,X],kernel_shape:[se,_e],pads:[ye,$e,Pe,Be],strides:[z,fe]})},938786:(f,b)=>{i.sa("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},938877:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z,fe,Ie)=>{i.sa("AveragePool",f,{format:Ie?"NHWC":"NCHW",auto_pad:b,ceil_mode:S,count_include_pad:T,storage_order:O,dilations:[U,X],kernel_shape:[se,_e],pads:[ye,$e,Pe,Be],strides:[z,fe]})},939161:(f,b)=>{i.sa("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},939248:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z,fe,Ie)=>{i.sa("MaxPool",f,{format:Ie?"NHWC":"NCHW",auto_pad:b,ceil_mode:S,count_include_pad:T,storage_order:O,dilations:[U,X],kernel_shape:[se,_e],pads:[ye,$e,Pe,Be],strides:[z,fe]})},939528:(f,b)=>{i.sa("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},939615:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z,fe,Ie)=>{i.sa("MaxPool",f,{format:Ie?"NHWC":"NCHW",auto_pad:b,ceil_mode:S,count_include_pad:T,storage_order:O,dilations:[U,X],kernel_shape:[se,_e],pads:[ye,$e,Pe,Be],strides:[z,fe]})},939895:(f,b,S,T,O)=>{i.sa("Gemm",f,{alpha:b,beta:S,transA:T,transB:O})},939999:f=>{i.sa("MatMul",f,void 0)},940053:(f,b,S,T)=>{i.sa("ArgMax",f,{keepDims:!!b,selectLastIndex:!!S,axis:T})},940161:(f,b,S,T)=>{i.sa("ArgMin",f,{keepDims:!!b,selectLastIndex:!!S,axis:T})},940269:(f,b)=>{i.sa("Softmax",f,{axis:b})},940332:(f,b)=>{i.sa("Concat",f,{axis:b})},940392:(f,b,S,T,O)=>{i.sa("Split",f,{axis:b,numOutputs:S,splitSizes:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},940532:f=>{i.sa("Expand",f,void 0)},940586:(f,b)=>{i.sa("Gather",f,{axis:Number(b)})},940657:(f,b)=>{i.sa("GatherElements",f,{axis:Number(b)})},940736:(f,b,S,T,O,U,X,se,_e,ye,$e)=>{i.sa("Resize",f,{antialias:b,axes:S?Array.from(N.subarray(S>>>0,T>>>0)):[],coordinateTransformMode:Ye(O),cubicCoeffA:U,excludeOutside:X,extrapolationValue:se,keepAspectRatioPolicy:Ye(_e),mode:Ye(ye),nearestMode:Ye($e)})},941082:(f,b,S,T,O,U,X)=>{i.sa("Slice",f,{starts:b?Array.from(N.subarray(b>>>0,S>>>0)):[],ends:T?Array.from(N.subarray(T>>>0,O>>>0)):[],axes:U?Array.from(N.subarray(U>>>0,X>>>0)):[]})},941298:f=>{i.sa("Tile",f,void 0)},941350:(f,b,S)=>{i.sa("LayerNormalization",f,{axis:Number(b),epsilon:Number(S)})},941457:(f,b,S)=>{i.sa("InstanceNormalization",f,{epsilon:b,format:S?"NHWC":"NCHW"})},941571:(f,b,S)=>{i.sa("InstanceNormalization",f,{epsilon:b,format:S?"NHWC":"NCHW"})},941685:f=>{i.sa("Range",f,void 0)},941738:(f,b)=>{i.sa("Einsum",f,{equation:Ye(b)})},941819:(f,b,S,T,O)=>{i.sa("Pad",f,{mode:b,value:S,pads:T?Array.from(N.subarray(T>>>0,O>>>0)):[]})},941946:(f,b,S,T,O,U)=>{i.sa("BatchNormalization",f,{epsilon:b,momentum:S,spatial:!!O,trainingMode:!!T,format:U?"NHWC":"NCHW"})},942115:(f,b,S,T,O,U)=>{i.sa("BatchNormalization",f,{epsilon:b,momentum:S,spatial:!!O,trainingMode:!!T,format:U?"NHWC":"NCHW"})},942284:(f,b,S)=>{i.sa("CumSum",f,{exclusive:Number(b),reverse:Number(S)})},942381:(f,b,S,T,O,U,X,se,_e)=>{i.sa("Attention",f,{numHeads:b,isUnidirectional:S,maskFilterValue:T,scale:O,doRotary:U,qkvHiddenSizes:X?Array.from(N.subarray(Number(se)>>>0,Number(se)+X>>>0)):[],pastPresentShareBuffer:!!_e})},942653:f=>{i.sa("BiasAdd",f,void 0)},942708:f=>{i.sa("BiasSplitGelu",f,void 0)},942769:f=>{i.sa("FastGelu",f,void 0)},942825:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be)=>{i.sa("Conv",f,{format:_e?"NHWC":"NCHW",auto_pad:b,dilations:[S],group:T,kernel_shape:[O],pads:U?Array.from(N.subarray(U>>>0,X>>>0)):[],strides:[se],w_is_const:()=>!!H[ye>>>0],activation:Ye($e),activation_params:Pe?Array.from(oe.subarray(Pe>>>0,Be>>>0)):[]})},943195:(f,b,S,T,O,U,X,se,_e,ye,$e,Pe,Be,z,fe,Ie)=>{i.sa("Conv",f,{format:Pe?"NHWC":"NCHW",auto_pad:b,dilations:[S,T],group:O,kernel_shape:[U,X],pads:se?Array.from(N.subarray(se>>>0,_e>>>0)):[],strides:[ye,$e],w_is_const:()=>!!H[Be>>>0],activation:Ye(z),activation_params:fe?Array.from(oe.subarray(fe>>>0,Ie>>>0)):[]})},943586:f=>{i.sa("Gelu",f,void 0)},943638:(f,b,S,T,O,U)=>{i.sa("MatMulNBits",f,{k:b,n:S,accuracyLevel:T,bits:O,blockSize:U})},943765:(f,b,S,T,O,U)=>{i.sa("MultiHeadAttention",f,{numHeads:b,isUnidirectional:S,maskFilterValue:T,scale:O,doRotary:U})},943924:(f,b)=>{i.sa("SkipLayerNormalization",f,{epsilon:b})},944005:f=>{i.Wa(f)},944039:(f,b)=>i.Ya(f,b,i.Ea.Za,i.Ea.errors)};function bt(f){this.name="ExitStatus",this.message=`Program terminated with exit(${f})`,this.status=f}function Mr(f){this.Ja=f-24,this.Pa=function(b){ee[this.Ja+4>>>2>>>0]=b},this.Oa=function(b){ee[this.Ja+8>>>2>>>0]=b},this.eb=function(b,S){this.Na(),this.Pa(b),this.Oa(S)},this.Na=function(){ee[this.Ja+16>>>2>>>0]=0}}var Xt=0,$n=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,_r=(f,b,S)=>{b>>>=0;var T=b+S;for(S=b;f[S]&&!(S>=T);)++S;if(16O?T+=String.fromCharCode(O):(O-=65536,T+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else T+=String.fromCharCode(O)}return T},Ye=(f,b)=>(f>>>=0)?_r(re,f,b):"",Or=f=>{for(var b=0,S=0;S=T?b++:2047>=T?b+=2:55296<=T&&57343>=T?(b+=4,++S):b+=3}return b},xn=(f,b,S,T)=>{if(S>>>=0,!(0=X){var se=f.charCodeAt(++U);X=65536+((X&1023)<<10)|se&1023}if(127>=X){if(S>=T)break;b[S++>>>0]=X}else{if(2047>=X){if(S+1>=T)break;b[S++>>>0]=192|X>>6}else{if(65535>=X){if(S+2>=T)break;b[S++>>>0]=224|X>>12}else{if(S+3>=T)break;b[S++>>>0]=240|X>>18,b[S++>>>0]=128|X>>12&63}b[S++>>>0]=128|X>>6&63}b[S++>>>0]=128|X&63}}return b[S>>>0]=0,S-O},Ft=f=>f%4===0&&(f%100!==0||f%400===0),ka=[0,31,60,91,121,152,182,213,244,274,305,335],Wt=[0,31,59,90,120,151,181,212,243,273,304,334],zr=f=>{var b=Or(f)+1,S=Nr(b);return S&&xn(f,re,S,b),S},yr=[],Rr=(f,b)=>{yr.length=0;for(var S;S=re[f++>>>0];){var T=S!=105;T&=S!=112,b+=T&&b%8?4:0,yr.push(S==112?ee[b>>>2>>>0]:S==105?N[b>>>2>>>0]:Ae[b>>>3>>>0]),b+=T?8:4}return yr},Pr={},zt=()=>{if(!Br){var f={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",_:p||"./this.program"},b;for(b in Pr)Pr[b]===void 0?delete f[b]:f[b]=Pr[b];var S=[];for(b in f)S.push(`${b}=${f[b]}`);Br=S}return Br},Br,Ta=[null,[],[]],et=[31,29,31,30,31,30,31,31,30,31,30,31],Aa=[31,28,31,30,31,30,31,31,30,31,30,31];function De(f){var b=Array(Or(f)+1);return xn(f,b,0,b.length),b}function Sn(f,b,S,T){function O(z,fe,Ie){for(z=typeof z=="number"?z.toString():z||"";z.lengthNa?-1:0Pt-z.getDate())fe-=Pt-z.getDate()+1,z.setDate(1),11>Ie?z.setMonth(Ie+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1));else{z.setDate(z.getDate()+fe);break}}return Ie=new Date(z.getFullYear()+1,0,4),fe=se(new Date(z.getFullYear(),0,4)),Ie=se(Ie),0>=X(fe,z)?0>=X(Ie,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}f>>>=0,b>>>=0,S>>>=0,T>>>=0;var ye=ee[T+40>>>2>>>0];T={bb:N[T>>>2>>>0],ab:N[T+4>>>2>>>0],Ga:N[T+8>>>2>>>0],Ka:N[T+12>>>2>>>0],Ha:N[T+16>>>2>>>0],Da:N[T+20>>>2>>>0],xa:N[T+24>>>2>>>0],Ca:N[T+28>>>2>>>0],fb:N[T+32>>>2>>>0],$a:N[T+36>>>2>>>0],cb:ye?Ye(ye):""},S=Ye(S),ye={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var $e in ye)S=S.replace(new RegExp($e,"g"),ye[$e]);var Pe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Be="January February March April May June July August September October November December".split(" ");ye={"%a":z=>Pe[z.xa].substring(0,3),"%A":z=>Pe[z.xa],"%b":z=>Be[z.Ha].substring(0,3),"%B":z=>Be[z.Ha],"%C":z=>U((z.Da+1900)/100|0,2),"%d":z=>U(z.Ka,2),"%e":z=>O(z.Ka,2," "),"%g":z=>_e(z).toString().substring(2),"%G":z=>_e(z),"%H":z=>U(z.Ga,2),"%I":z=>(z=z.Ga,z==0?z=12:12{for(var fe=0,Ie=0;Ie<=z.Ha-1;fe+=(Ft(z.Da+1900)?et:Aa)[Ie++]);return U(z.Ka+fe,3)},"%m":z=>U(z.Ha+1,2),"%M":z=>U(z.ab,2),"%n":()=>` +`,"%p":z=>0<=z.Ga&&12>z.Ga?"AM":"PM","%S":z=>U(z.bb,2),"%t":()=>" ","%u":z=>z.xa||7,"%U":z=>U(Math.floor((z.Ca+7-z.xa)/7),2),"%V":z=>{var fe=Math.floor((z.Ca+7-(z.xa+6)%7)/7);if(2>=(z.xa+371-z.Ca-2)%7&&fe++,fe)fe==53&&(Ie=(z.xa+371-z.Ca)%7,Ie==4||Ie==3&&Ft(z.Da)||(fe=1));else{fe=52;var Ie=(z.xa+7-z.Ca-1)%7;(Ie==4||Ie==5&&Ft(z.Da%400-1))&&fe++}return U(fe,2)},"%w":z=>z.xa,"%W":z=>U(Math.floor((z.Ca+7-(z.xa+6)%7)/7),2),"%y":z=>(z.Da+1900).toString().substring(2),"%Y":z=>z.Da+1900,"%z":z=>{z=z.$a;var fe=0<=z;return z=Math.abs(z)/60,(fe?"+":"-")+("0000"+(z/60*100+z%60)).slice(-4)},"%Z":z=>z.cb,"%%":()=>"%"},S=S.replace(/%%/g,"\0\0");for($e in ye)S.includes($e)&&(S=S.replace(new RegExp($e,"g"),ye[$e](T)));return S=S.replace(/\0\0/g,"%"),$e=De(S),$e.length>b?0:(H.set($e,f>>>0),$e.length-1)}var Qt=f=>{try{f()}catch(b){Q(b)}};function En(){var f=le,b={};for(let[S,T]of Object.entries(f))b[S]=typeof T=="function"?function(){ue.push(S);try{return T.apply(null,arguments)}finally{L||(ue.pop(),pt&&Rt===1&&ue.length===0&&(Rt=0,Qt(Pn),typeof Fibers<"u"&&Fibers.gb()))}}:T;return b}var Rt=0,pt=null,Ma=0,ue=[],wr={},Cn={},Cs=0,Dr=null,Oa=[];function za(){return new Promise((f,b)=>{Dr={resolve:f,reject:b}})}function Ra(){var f=Nr(65548),b=f+12;ee[f>>>2>>>0]=b,ee[f+4>>>2>>>0]=b+65536,b=ue[0];var S=wr[b];return S===void 0&&(S=Cs++,wr[b]=S,Cn[S]=b),N[f+8>>>2>>>0]=S,f}function Pa(f){if(!L){if(Rt===0){var b=!1,S=!1;f((T=0)=>{if(!L&&(Ma=T,b=!0,S)){Rt=2,Qt(()=>Bn(pt)),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.resume(),T=!1;try{var O=(0,le[Cn[N[pt+8>>>2>>>0]]])()}catch(se){O=se,T=!0}var U=!1;if(!pt){var X=Dr;X&&(Dr=null,(T?X.reject:X.resolve)(O),U=!0)}if(T&&!U)throw O}}),S=!0,b||(Rt=1,pt=Ra(),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.pause(),Qt(()=>Rn(pt)))}else Rt===2?(Rt=0,Qt(Dn),Tn(pt),pt=null,Oa.forEach(T=>{if(!L)try{T();try{Y=Y=T=Y,i.onExit?.(T),L=!0,u(T,new bt(T))}catch(O){O instanceof bt||O=="unwind"||u(1,O)}}catch(O){O instanceof bt||O=="unwind"||u(1,O)}})):Q(`invalid state: ${Rt}`);return Ma}}function In(f){return Pa(b=>{f().then(b)})}var Ba={n:function(f,b,S){return In(async()=>{await i.Ua(f,b,S)})},a:function(f,b,S){throw f>>>=0,new Mr(f).eb(b>>>0,S>>>0),Xt=f,Xt},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(f,b,S){f=b+2097152>>>0<4194305-!!f?(f>>>0)+4294967296*b:NaN,S>>>=0,f=new Date(1e3*f),N[S>>>2>>>0]=f.getUTCSeconds(),N[S+4>>>2>>>0]=f.getUTCMinutes(),N[S+8>>>2>>>0]=f.getUTCHours(),N[S+12>>>2>>>0]=f.getUTCDate(),N[S+16>>>2>>>0]=f.getUTCMonth(),N[S+20>>>2>>>0]=f.getUTCFullYear()-1900,N[S+24>>>2>>>0]=f.getUTCDay(),N[S+28>>>2>>>0]=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(f,b,S){f=b+2097152>>>0<4194305-!!f?(f>>>0)+4294967296*b:NaN,S>>>=0,f=new Date(1e3*f),N[S>>>2>>>0]=f.getSeconds(),N[S+4>>>2>>>0]=f.getMinutes(),N[S+8>>>2>>>0]=f.getHours(),N[S+12>>>2>>>0]=f.getDate(),N[S+16>>>2>>>0]=f.getMonth(),N[S+20>>>2>>>0]=f.getFullYear()-1900,N[S+24>>>2>>>0]=f.getDay(),N[S+28>>>2>>>0]=(Ft(f.getFullYear())?ka:Wt)[f.getMonth()]+f.getDate()-1|0,N[S+36>>>2>>>0]=-(60*f.getTimezoneOffset()),b=new Date(f.getFullYear(),6,1).getTimezoneOffset();var T=new Date(f.getFullYear(),0,1).getTimezoneOffset();N[S+32>>>2>>>0]=(b!=T&&f.getTimezoneOffset()==Math.min(T,b))|0},s:function(f){f>>>=0;var b=new Date(N[f+20>>>2>>>0]+1900,N[f+16>>>2>>>0],N[f+12>>>2>>>0],N[f+8>>>2>>>0],N[f+4>>>2>>>0],N[f>>>2>>>0],0),S=N[f+32>>>2>>>0],T=b.getTimezoneOffset(),O=new Date(b.getFullYear(),6,1).getTimezoneOffset(),U=new Date(b.getFullYear(),0,1).getTimezoneOffset(),X=Math.min(U,O);return 0>S?N[f+32>>>2>>>0]=+(O!=U&&X==T):0>>2>>>0]=b.getDay(),N[f+28>>>2>>>0]=(Ft(b.getFullYear())?ka:Wt)[b.getMonth()]+b.getDate()-1|0,N[f>>>2>>>0]=b.getSeconds(),N[f+4>>>2>>>0]=b.getMinutes(),N[f+8>>>2>>>0]=b.getHours(),N[f+12>>>2>>>0]=b.getDate(),N[f+16>>>2>>>0]=b.getMonth(),N[f+20>>>2>>>0]=b.getYear(),f=b.getTime(),isNaN(f)?(N[kn()>>>2>>>0]=61,f=-1):f/=1e3,An((qe=f,1<=+Math.abs(qe)?0>>0:~~+Math.ceil((qe-+(~~qe>>>0))/4294967296)>>>0:0)),f>>>0},o:function(){return-52},p:function(){},w:function(f,b,S){function T(_e){return(_e=_e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?_e[1]:"GMT"}S>>>=0;var O=new Date().getFullYear(),U=new Date(O,0,1),X=new Date(O,6,1);O=U.getTimezoneOffset();var se=X.getTimezoneOffset();ee[f>>>0>>>2>>>0]=60*Math.max(O,se),N[b>>>0>>>2>>>0]=+(O!=se),f=T(U),b=T(X),f=zr(f),b=zr(b),se>>2>>>0]=f,ee[S+4>>>2>>>0]=b):(ee[S>>>2>>>0]=b,ee[S+4>>>2>>>0]=f)},e:()=>{Q("")},b:function(f,b,S){return f>>>=0,b=Rr(b>>>0,S>>>0),it[f].apply(null,b)},i:function(f,b,S){return f>>>=0,b=Rr(b>>>0,S>>>0),it[f].apply(null,b)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(f,b,S){return b>>>=0,re.copyWithin(f>>>0>>>0,b>>>0,b+(S>>>0)>>>0)},u:function(f){f>>>=0;var b=re.length;if(4294901760=S;S*=2){var T=b*(1+.2/S);T=Math.min(T,f+100663296);var O=Math;T=Math.max(f,T);e:{O=(O.min.call(O,4294901760,T+(65536-T%65536)%65536)-D.buffer.byteLength+65535)/65536;try{D.grow(O),q();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1},E:function(f,b){f>>>=0,b>>>=0;var S=0;return zt().forEach((T,O)=>{var U=b+S;for(O=ee[f+4*O>>>2>>>0]=U,U=0;U>>0>>>0]=T.charCodeAt(U);H[O>>>0>>>0]=0,S+=T.length+1}),0},F:function(f,b){f>>>=0,b>>>=0;var S=zt();ee[f>>>2>>>0]=S.length;var T=0;return S.forEach(O=>T+=O.length+1),ee[b>>>2>>>0]=T,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(f,b,S,T){b>>>=0,S>>>=0,T>>>=0;for(var O=0,U=0;U>>2>>>0],se=ee[b+4>>>2>>>0];b+=8;for(var _e=0;_e>>0],$e=Ta[f];ye===0||ye===10?((f===1?k:A)(_r($e,0)),$e.length=0):$e.push(ye)}O+=se}return ee[T>>>2>>>0]=O,0},v:Sn,d:function(f,b,S,T){return Sn(f>>>0,b>>>0,S>>>0,T>>>0)}},le=function(){function f(S){return le=S.exports,le=En(),le=Da(),D=le.M,q(),ae.unshift(le.N),te--,te==0&&B&&(S=B,B=null,S()),le}var b={a:Ba};if(te++,i.instantiateWasm)try{return i.instantiateWasm(b,f)}catch(S){A(`Module.instantiateWasm callback failed with error: ${S}`),o(S)}return Le(b,function(S){f(S.instance)}).catch(o),{}}();i._OrtInit=(f,b)=>(i._OrtInit=le.O)(f,b),i._OrtGetLastError=(f,b)=>(i._OrtGetLastError=le.P)(f,b),i._OrtCreateSessionOptions=(f,b,S,T,O,U,X,se,_e,ye)=>(i._OrtCreateSessionOptions=le.Q)(f,b,S,T,O,U,X,se,_e,ye),i._OrtAppendExecutionProvider=(f,b)=>(i._OrtAppendExecutionProvider=le.R)(f,b),i._OrtAddFreeDimensionOverride=(f,b,S)=>(i._OrtAddFreeDimensionOverride=le.S)(f,b,S),i._OrtAddSessionConfigEntry=(f,b,S)=>(i._OrtAddSessionConfigEntry=le.T)(f,b,S),i._OrtReleaseSessionOptions=f=>(i._OrtReleaseSessionOptions=le.U)(f),i._OrtCreateSession=(f,b,S)=>(i._OrtCreateSession=le.V)(f,b,S),i._OrtReleaseSession=f=>(i._OrtReleaseSession=le.W)(f),i._OrtGetInputOutputCount=(f,b,S)=>(i._OrtGetInputOutputCount=le.X)(f,b,S),i._OrtGetInputName=(f,b)=>(i._OrtGetInputName=le.Y)(f,b),i._OrtGetOutputName=(f,b)=>(i._OrtGetOutputName=le.Z)(f,b),i._OrtFree=f=>(i._OrtFree=le._)(f),i._OrtCreateTensor=(f,b,S,T,O,U)=>(i._OrtCreateTensor=le.$)(f,b,S,T,O,U),i._OrtGetTensorData=(f,b,S,T,O)=>(i._OrtGetTensorData=le.aa)(f,b,S,T,O),i._OrtReleaseTensor=f=>(i._OrtReleaseTensor=le.ba)(f),i._OrtCreateRunOptions=(f,b,S,T)=>(i._OrtCreateRunOptions=le.ca)(f,b,S,T),i._OrtAddRunConfigEntry=(f,b,S)=>(i._OrtAddRunConfigEntry=le.da)(f,b,S),i._OrtReleaseRunOptions=f=>(i._OrtReleaseRunOptions=le.ea)(f),i._OrtCreateBinding=f=>(i._OrtCreateBinding=le.fa)(f),i._OrtBindInput=(f,b,S)=>(i._OrtBindInput=le.ga)(f,b,S),i._OrtBindOutput=(f,b,S,T)=>(i._OrtBindOutput=le.ha)(f,b,S,T),i._OrtClearBoundOutputs=f=>(i._OrtClearBoundOutputs=le.ia)(f),i._OrtReleaseBinding=f=>(i._OrtReleaseBinding=le.ja)(f),i._OrtRunWithBinding=(f,b,S,T,O)=>(i._OrtRunWithBinding=le.ka)(f,b,S,T,O),i._OrtRun=(f,b,S,T,O,U,X,se)=>(i._OrtRun=le.la)(f,b,S,T,O,U,X,se),i._OrtEndProfiling=f=>(i._OrtEndProfiling=le.ma)(f),i._JsepOutput=(f,b,S)=>(i._JsepOutput=le.na)(f,b,S),i._JsepGetNodeName=f=>(i._JsepGetNodeName=le.oa)(f);var kn=()=>(kn=le.pa)(),Nr=i._malloc=f=>(Nr=i._malloc=le.qa)(f),Tn=i._free=f=>(Tn=i._free=le.ra)(f),An=f=>(An=le.ta)(f),Mn=()=>(Mn=le.ua)(),On=f=>(On=le.va)(f),zn=f=>(zn=le.wa)(f),Rn=f=>(Rn=le.ya)(f),Pn=()=>(Pn=le.za)(),Bn=f=>(Bn=le.Aa)(f),Dn=()=>(Dn=le.Ba)();i.___start_em_js=944151,i.___stop_em_js=944312;function Da(){var f=le;f=Object.assign({},f);var b=T=>()=>T()>>>0,S=T=>O=>T(O)>>>0;return f.pa=b(f.pa),f.qa=S(f.qa),f.ua=b(f.ua),f.wa=S(f.wa),f}i.stackAlloc=zn,i.stackSave=Mn,i.stackRestore=On,i.UTF8ToString=Ye,i.stringToUTF8=(f,b,S)=>xn(f,re,b,S),i.lengthBytesUTF8=Or;var Zt;B=function f(){Zt||br(),Zt||(B=f)};function br(){if(!(0r)}),Km=Sr(()=>{}),Ym=Sr(()=>{}),ho={};Er(ho,{cpus:()=>fo});var fo,Xm=V(()=>{fo=void 0}),Qm=Sr((t,e)=>{var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(a={}){function i(){return J.buffer!=B.buffer&&Ve(),B}function s(){return J.buffer!=B.buffer&&Ve(),Q}function o(){return J.buffer!=B.buffer&&Ve(),he}function l(){return J.buffer!=B.buffer&&Ve(),ze}function d(){return J.buffer!=B.buffer&&Ve(),Re}function p(){return J.buffer!=B.buffer&&Ve(),Je}var u=a,h,m;u.ready=new Promise((c,g)=>{h=c,m=g}),u.mountExternalData=(c,g)=>{(u.cb||(u.cb=new Map)).set(c,g)},u.unmountExternalData=()=>{delete u.cb};let _=()=>{let c=($,C,M)=>(...R)=>{let F=Bt,ie=C?.();R=$(...R);let xe=C?.();return ie!==xe&&($=xe,M(ie),C=M=null),Bt!=F?k2():R},g=$=>async(...C)=>{try{if(u.bb)throw Error("Session already started");let M=u.bb={Gb:C[0],errors:[]},R=await $(...C);if(u.bb!==M)throw Error("Session mismatch");u.kb?.flush();let F=M.errors;if(0xe),0u._OrtCreateSession,$=>u._OrtCreateSession=$),u._OrtRun=g(c(u._OrtRun,()=>u._OrtRun,$=>u._OrtRun=$)),u._OrtRunWithBinding=g(c(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,$=>u._OrtRunWithBinding=$)),u._OrtBindInput=c(u._OrtBindInput,()=>u._OrtBindInput,$=>u._OrtBindInput=$),_=void 0};u.jsepInit=(c,g)=>{if(_?.(),c==="webgpu"){[u.kb,u.xb,u.Bb,u.lb,u.Ab,u.Ea,u.Cb,u.Eb,u.yb,u.zb,u.Db]=g;let $=u.kb;u.jsepRegisterBuffer=(C,M,R,F)=>$.registerBuffer(C,M,R,F),u.jsepGetBuffer=C=>$.getBuffer(C),u.jsepCreateDownloader=(C,M,R)=>$.createDownloader(C,M,R),u.jsepOnReleaseSession=C=>{$.onReleaseSession(C)},u.jsepOnRunStart=C=>$.onRunStart(C)}};var y=Object.assign({},u),v="./this.program",x=(c,g)=>{throw g},w=typeof window=="object",E=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",k=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function D(c){return u.locateFile?u.locateFile(c,A):A+c}var L,Y,H;if(I){var re=(uo(),tr(si)),N=(po(),tr(oi));A=E?N.dirname(A)+"/":__dirname+"/",L=(g,$)=>(g=_r(g)?new URL(g):N.normalize(g),re.readFileSync(g,$?void 0:"utf8")),H=g=>(g=L(g,!0),g.buffer||(g=new Uint8Array(g)),g),Y=(g,$,C,M=!0)=>{g=_r(g)?new URL(g):N.normalize(g),re.readFile(g,M?void 0:"utf8",(R,F)=>{R?C(R):$(M?F.buffer:F)})},!u.thisProgram&&1{throw process.exitCode=g,$},u.inspect=()=>"[Emscripten Module object]";let c;try{c=Km()}catch(g){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),g}global.Worker=c.Worker}else(w||E)&&(E?A=self.location.href:typeof document<"u"&&document.currentScript&&(A=document.currentScript.src),typeof n<"u"&&n&&(A=n),A.indexOf("blob:")!==0?A=A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):A="",I||(L=c=>{var g=new XMLHttpRequest;return g.open("GET",c,!1),g.send(null),g.responseText},E&&(H=c=>{var g=new XMLHttpRequest;return g.open("GET",c,!1),g.responseType="arraybuffer",g.send(null),new Uint8Array(g.response)}),Y=(c,g,$)=>{var C=new XMLHttpRequest;C.open("GET",c,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?g(C.response):$()},C.onerror=$,C.send(null)}));I&&typeof performance>"u"&&(global.performance=Ym().performance);var ee=console.log.bind(console),oe=console.error.bind(console);I&&(ee=(...c)=>re.writeSync(1,c.join(" ")+` +`),oe=(...c)=>re.writeSync(2,c.join(" ")+` +`));var Ae=ee,q=oe;Object.assign(u,y),y=null,typeof WebAssembly!="object"&&Xt("no native wasm support detected");var J,ae,W=!1,te,B,Q,he,ze,Re,Je;function Ve(){var c=J.buffer;u.HEAP8=B=new Int8Array(c),u.HEAP16=new Int16Array(c),u.HEAPU8=Q=new Uint8Array(c),u.HEAPU16=new Uint16Array(c),u.HEAP32=he=new Int32Array(c),u.HEAPU32=ze=new Uint32Array(c),u.HEAPF32=Re=new Float32Array(c),u.HEAPF64=Je=new Float64Array(c)}var at=16777216;if(k)J=u.wasmMemory;else if(u.wasmMemory)J=u.wasmMemory;else if(J=new WebAssembly.Memory({initial:at/65536,maximum:65536,shared:!0}),!(J.buffer instanceof SharedArrayBuffer))throw q("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),I&&q("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ve(),at=J.buffer.byteLength;var ut=[],Le=[],qe=[],it=0,bt=null;function Mr(){if(it--,it==0&&bt){var c=bt;bt=null,c()}}function Xt(c){throw c="Aborted("+c+")",q(c),W=!0,te=1,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),m(c),c}var $n=c=>c.startsWith("data:application/octet-stream;base64,"),_r=c=>c.startsWith("file://"),Ye;Ye="ort-wasm-simd-threaded.wasm",$n(Ye)||(Ye=D(Ye));function Or(c){if(H)return H(c);throw"both async and sync fetching of the wasm failed"}function xn(c){if(w||E){if(typeof fetch=="function"&&!_r(c))return fetch(c,{credentials:"same-origin"}).then(g=>{if(!g.ok)throw"failed to load wasm binary file at '"+c+"'";return g.arrayBuffer()}).catch(()=>Or(c));if(Y)return new Promise((g,$)=>{Y(c,C=>g(new Uint8Array(C)),$)})}return Promise.resolve().then(()=>Or(c))}function Ft(c,g,$){return xn(c).then(C=>WebAssembly.instantiate(C,g)).then(C=>C).then($,C=>{q(`failed to asynchronously prepare wasm: ${C}`),Xt(C)})}function ka(c,g){var $=Ye;return typeof WebAssembly.instantiateStreaming!="function"||$n($)||_r($)||I||typeof fetch!="function"?Ft($,c,g):fetch($,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,c).then(g,function(M){return q(`wasm streaming compile failed: ${M}`),q("falling back to ArrayBuffer instantiation"),Ft($,c,g)}))}var Wt,zr={933148:(c,g,$,C)=>{if(typeof u>"u"||!u.cb)return 1;if(c=et(c>>>0),c.startsWith("./")&&(c=c.substring(2)),c=u.cb.get(c),!c)return 2;if(g>>>=0,$>>>=0,C>>>=0,g+$>c.byteLength)return 3;try{return s().set(c.subarray(g,g+$),C>>>0),0}catch{return 4}},933649:()=>{u.yb()},933680:()=>{u.zb()},933709:()=>{u.Db()},933734:c=>u.xb(c),933767:c=>u.Bb(c),933799:(c,g,$)=>{u.lb(c,g,$,!0)},933838:(c,g,$)=>{u.lb(c,g,$)},933871:c=>{u.Ea("Abs",c,void 0)},933922:c=>{u.Ea("Neg",c,void 0)},933973:c=>{u.Ea("Floor",c,void 0)},934026:c=>{u.Ea("Ceil",c,void 0)},934078:c=>{u.Ea("Reciprocal",c,void 0)},934136:c=>{u.Ea("Sqrt",c,void 0)},934188:c=>{u.Ea("Exp",c,void 0)},934239:c=>{u.Ea("Erf",c,void 0)},934290:c=>{u.Ea("Sigmoid",c,void 0)},934345:(c,g,$)=>{u.Ea("HardSigmoid",c,{alpha:g,beta:$})},934424:c=>{u.Ea("Log",c,void 0)},934475:c=>{u.Ea("Sin",c,void 0)},934526:c=>{u.Ea("Cos",c,void 0)},934577:c=>{u.Ea("Tan",c,void 0)},934628:c=>{u.Ea("Asin",c,void 0)},934680:c=>{u.Ea("Acos",c,void 0)},934732:c=>{u.Ea("Atan",c,void 0)},934784:c=>{u.Ea("Sinh",c,void 0)},934836:c=>{u.Ea("Cosh",c,void 0)},934888:c=>{u.Ea("Asinh",c,void 0)},934941:c=>{u.Ea("Acosh",c,void 0)},934994:c=>{u.Ea("Atanh",c,void 0)},935047:c=>{u.Ea("Tanh",c,void 0)},935099:c=>{u.Ea("Not",c,void 0)},935150:(c,g,$)=>{u.Ea("Clip",c,{min:g,max:$})},935219:c=>{u.Ea("Clip",c,void 0)},935271:(c,g)=>{u.Ea("Elu",c,{alpha:g})},935329:c=>{u.Ea("Relu",c,void 0)},935381:(c,g)=>{u.Ea("LeakyRelu",c,{alpha:g})},935445:(c,g)=>{u.Ea("ThresholdedRelu",c,{alpha:g})},935515:(c,g)=>{u.Ea("Cast",c,{to:g})},935573:c=>{u.Ea("Add",c,void 0)},935624:c=>{u.Ea("Sub",c,void 0)},935675:c=>{u.Ea("Mul",c,void 0)},935726:c=>{u.Ea("Div",c,void 0)},935777:c=>{u.Ea("Pow",c,void 0)},935828:c=>{u.Ea("Equal",c,void 0)},935881:c=>{u.Ea("Greater",c,void 0)},935936:c=>{u.Ea("GreaterOrEqual",c,void 0)},935998:c=>{u.Ea("Less",c,void 0)},936050:c=>{u.Ea("LessOrEqual",c,void 0)},936109:(c,g,$,C,M)=>{u.Ea("ReduceMean",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936268:(c,g,$,C,M)=>{u.Ea("ReduceMax",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936426:(c,g,$,C,M)=>{u.Ea("ReduceMin",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936584:(c,g,$,C,M)=>{u.Ea("ReduceProd",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936743:(c,g,$,C,M)=>{u.Ea("ReduceSum",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936901:(c,g,$,C,M)=>{u.Ea("ReduceL1",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937058:(c,g,$,C,M)=>{u.Ea("ReduceL2",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937215:(c,g,$,C,M)=>{u.Ea("ReduceLogSum",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937376:(c,g,$,C,M)=>{u.Ea("ReduceSumSquare",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937540:(c,g,$,C,M)=>{u.Ea("ReduceLogSumExp",c,{keepDims:!!g,noopWithEmptyAxes:!!$,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937704:c=>{u.Ea("Where",c,void 0)},937757:(c,g,$)=>{u.Ea("Transpose",c,{perm:g?Array.from(o().subarray(g>>>0,$>>>0)):[]})},937865:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P,be)=>{u.Ea("ConvTranspose",c,{format:xe?"NHWC":"NCHW",autoPad:g,dilations:[$],group:C,kernel_shape:[M],pads:[R,F],strides:[ie],wIsConst:()=>!!i()[we>>>0],outputPadding:Ee?Array.from(o().subarray(Ee>>>0,Ue>>>0)):[],outputShape:Fe?Array.from(o().subarray(Fe>>>0,P>>>0)):[],activation:et(be)})},938267:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P)=>{u.Ea("ConvTranspose",c,{format:ie?"NHWC":"NCHW",autoPad:g,dilations:Array.from(o().subarray($>>>0,($>>>0)+2>>>0)),group:C,kernelShape:Array.from(o().subarray(M>>>0,(M>>>0)+2>>>0)),pads:Array.from(o().subarray(R>>>0,(R>>>0)+4>>>0)),strides:Array.from(o().subarray(F>>>0,(F>>>0)+2>>>0)),wIsConst:()=>!!i()[xe>>>0],outputPadding:we?Array.from(o().subarray(we>>>0,Ee>>>0)):[],outputShape:Ue?Array.from(o().subarray(Ue>>>0,Fe>>>0)):[],activation:et(P)})},938832:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P,be)=>{u.Ea("ConvTranspose",c,{format:xe?"NHWC":"NCHW",autoPad:g,dilations:[$],group:C,kernel_shape:[M],pads:[R,F],strides:[ie],wIsConst:()=>!!i()[we>>>0],outputPadding:Ee?Array.from(o().subarray(Ee>>>0,Ue>>>0)):[],outputShape:Fe?Array.from(o().subarray(Fe>>>0,P>>>0)):[],activation:et(be)})},939234:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P)=>{u.Ea("ConvTranspose",c,{format:ie?"NHWC":"NCHW",autoPad:g,dilations:Array.from(o().subarray($>>>0,($>>>0)+2>>>0)),group:C,kernelShape:Array.from(o().subarray(M>>>0,(M>>>0)+2>>>0)),pads:Array.from(o().subarray(R>>>0,(R>>>0)+4>>>0)),strides:Array.from(o().subarray(F>>>0,(F>>>0)+2>>>0)),wIsConst:()=>!!i()[xe>>>0],outputPadding:we?Array.from(o().subarray(we>>>0,Ee>>>0)):[],outputShape:Ue?Array.from(o().subarray(Ue>>>0,Fe>>>0)):[],activation:et(P)})},939799:(c,g)=>{u.Ea("GlobalAveragePool",c,{format:g?"NHWC":"NCHW"})},939890:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P,be,Me)=>{u.Ea("AveragePool",c,{format:Me?"NHWC":"NCHW",auto_pad:g,ceil_mode:$,count_include_pad:C,storage_order:M,dilations:[R,F],kernel_shape:[ie,xe],pads:[we,Ee,Ue,Fe],strides:[P,be]})},940174:(c,g)=>{u.Ea("GlobalAveragePool",c,{format:g?"NHWC":"NCHW"})},940265:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P,be,Me)=>{u.Ea("AveragePool",c,{format:Me?"NHWC":"NCHW",auto_pad:g,ceil_mode:$,count_include_pad:C,storage_order:M,dilations:[R,F],kernel_shape:[ie,xe],pads:[we,Ee,Ue,Fe],strides:[P,be]})},940549:(c,g)=>{u.Ea("GlobalMaxPool",c,{format:g?"NHWC":"NCHW"})},940636:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P,be,Me)=>{u.Ea("MaxPool",c,{format:Me?"NHWC":"NCHW",auto_pad:g,ceil_mode:$,count_include_pad:C,storage_order:M,dilations:[R,F],kernel_shape:[ie,xe],pads:[we,Ee,Ue,Fe],strides:[P,be]})},940916:(c,g)=>{u.Ea("GlobalMaxPool",c,{format:g?"NHWC":"NCHW"})},941003:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P,be,Me)=>{u.Ea("MaxPool",c,{format:Me?"NHWC":"NCHW",auto_pad:g,ceil_mode:$,count_include_pad:C,storage_order:M,dilations:[R,F],kernel_shape:[ie,xe],pads:[we,Ee,Ue,Fe],strides:[P,be]})},941283:(c,g,$,C,M)=>{u.Ea("Gemm",c,{alpha:g,beta:$,transA:C,transB:M})},941387:c=>{u.Ea("MatMul",c,void 0)},941441:(c,g,$,C)=>{u.Ea("ArgMax",c,{keepDims:!!g,selectLastIndex:!!$,axis:C})},941549:(c,g,$,C)=>{u.Ea("ArgMin",c,{keepDims:!!g,selectLastIndex:!!$,axis:C})},941657:(c,g)=>{u.Ea("Softmax",c,{axis:g})},941720:(c,g)=>{u.Ea("Concat",c,{axis:g})},941780:(c,g,$,C,M)=>{u.Ea("Split",c,{axis:g,numOutputs:$,splitSizes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},941920:c=>{u.Ea("Expand",c,void 0)},941974:(c,g)=>{u.Ea("Gather",c,{axis:Number(g)})},942045:(c,g)=>{u.Ea("GatherElements",c,{axis:Number(g)})},942124:(c,g,$,C,M,R,F,ie,xe,we,Ee)=>{u.Ea("Resize",c,{antialias:g,axes:$?Array.from(o().subarray($>>>0,C>>>0)):[],coordinateTransformMode:et(M),cubicCoeffA:R,excludeOutside:F,extrapolationValue:ie,keepAspectRatioPolicy:et(xe),mode:et(we),nearestMode:et(Ee)})},942470:(c,g,$,C,M,R,F)=>{u.Ea("Slice",c,{starts:g?Array.from(o().subarray(g>>>0,$>>>0)):[],ends:C?Array.from(o().subarray(C>>>0,M>>>0)):[],axes:R?Array.from(o().subarray(R>>>0,F>>>0)):[]})},942686:c=>{u.Ea("Tile",c,void 0)},942738:(c,g,$)=>{u.Ea("LayerNormalization",c,{axis:Number(g),epsilon:Number($)})},942845:(c,g,$)=>{u.Ea("InstanceNormalization",c,{epsilon:g,format:$?"NHWC":"NCHW"})},942959:(c,g,$)=>{u.Ea("InstanceNormalization",c,{epsilon:g,format:$?"NHWC":"NCHW"})},943073:c=>{u.Ea("Range",c,void 0)},943126:(c,g)=>{u.Ea("Einsum",c,{equation:et(g)})},943207:(c,g,$,C,M)=>{u.Ea("Pad",c,{mode:g,value:$,pads:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},943334:(c,g,$,C,M,R)=>{u.Ea("BatchNormalization",c,{epsilon:g,momentum:$,spatial:!!M,trainingMode:!!C,format:R?"NHWC":"NCHW"})},943503:(c,g,$,C,M,R)=>{u.Ea("BatchNormalization",c,{epsilon:g,momentum:$,spatial:!!M,trainingMode:!!C,format:R?"NHWC":"NCHW"})},943672:(c,g,$)=>{u.Ea("CumSum",c,{exclusive:Number(g),reverse:Number($)})},943769:(c,g,$,C,M,R,F,ie,xe)=>{u.Ea("Attention",c,{numHeads:g,isUnidirectional:$,maskFilterValue:C,scale:M,doRotary:R,qkvHiddenSizes:F?Array.from(o().subarray(Number(ie)>>>0,Number(ie)+F>>>0)):[],pastPresentShareBuffer:!!xe})},944041:c=>{u.Ea("BiasAdd",c,void 0)},944096:c=>{u.Ea("BiasSplitGelu",c,void 0)},944157:c=>{u.Ea("FastGelu",c,void 0)},944213:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe)=>{u.Ea("Conv",c,{format:xe?"NHWC":"NCHW",auto_pad:g,dilations:[$],group:C,kernel_shape:[M],pads:R?Array.from(o().subarray(R>>>0,F>>>0)):[],strides:[ie],w_is_const:()=>!!i()[we>>>0],activation:et(Ee),activation_params:Ue?Array.from(d().subarray(Ue>>>0,Fe>>>0)):[]})},944583:(c,g,$,C,M,R,F,ie,xe,we,Ee,Ue,Fe,P,be,Me)=>{u.Ea("Conv",c,{format:Ue?"NHWC":"NCHW",auto_pad:g,dilations:[$,C],group:M,kernel_shape:[R,F],pads:ie?Array.from(o().subarray(ie>>>0,xe>>>0)):[],strides:[we,Ee],w_is_const:()=>!!i()[Fe>>>0],activation:et(P),activation_params:be?Array.from(d().subarray(be>>>0,Me>>>0)):[]})},944974:c=>{u.Ea("Gelu",c,void 0)},945026:(c,g,$,C,M,R)=>{u.Ea("MatMulNBits",c,{k:g,n:$,accuracyLevel:C,bits:M,blockSize:R})},945153:(c,g,$,C,M,R)=>{u.Ea("MultiHeadAttention",c,{numHeads:g,isUnidirectional:$,maskFilterValue:C,scale:M,doRotary:R})},945312:(c,g)=>{u.Ea("SkipLayerNormalization",c,{epsilon:g})},945393:c=>{u.Cb(c)},945427:(c,g)=>u.Eb(c,g,u.bb.Gb,u.bb.errors)};function yr(c){this.name="ExitStatus",this.message=`Program terminated with exit(${c})`,this.status=c}var Rr=c=>{c.terminate(),c.onmessage=()=>{}},Pr=c=>{ue.Ya.length==0&&(pt(),ue.mb(ue.Ya[0]));var g=ue.Ya.pop();if(!g)return 6;ue.Za.push(g),ue.Qa[c.Xa]=g,g.Xa=c.Xa;var $={cmd:"run",start_routine:c.Hb,arg:c.ub,pthread_ptr:c.Xa};return I&&g.unref(),g.postMessage($,c.Nb),0},zt=0,Br=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ta=(c,g,$)=>{g>>>=0;var C=g+$;for($=g;c[$]&&!($>=C);)++$;if(16<$-g&&c.buffer&&Br)return Br.decode(c.buffer instanceof SharedArrayBuffer?c.slice(g,$):c.subarray(g,$));for(C="";g<$;){var M=c[g++];if(M&128){var R=c[g++]&63;if((M&224)==192)C+=String.fromCharCode((M&31)<<6|R);else{var F=c[g++]&63;M=(M&240)==224?(M&15)<<12|R<<6|F:(M&7)<<18|R<<12|F<<6|c[g++]&63,65536>M?C+=String.fromCharCode(M):(M-=65536,C+=String.fromCharCode(55296|M>>10,56320|M&1023))}}else C+=String.fromCharCode(M)}return C},et=(c,g)=>(c>>>=0)?Ta(s(),c,g):"",Aa=c=>{var g=Ms();return c=c(),Wa(g),c};function De(c,g){var $=arguments.length-2,C=arguments;return Aa(()=>{for(var M=Os(8*$),R=M>>>3,F=0;F<$;F++){var ie=C[2+F];p()[R+F>>>0]=ie}return Kf(c,$,M,g)})}function Sn(c){if(k)return De(0,1,c);te=c,0{if(te=c,k)throw Cn(c),"unwind";Sn(c)},En=c=>{c instanceof yr||c=="unwind"||x(1,c)};function Rt(){for(var c=u.numThreads;c--;)pt();ut.unshift(()=>{it++,Ma(()=>Mr())})}function pt(){var c=D("ort-wasm-simd-threaded.worker.js");c=new Worker(c),ue.Ya.push(c)}function Ma(c){k?c():Promise.all(ue.Ya.map(ue.mb)).then(c)}var ue={Ya:[],Za:[],qb:[],Qa:{},hb(){k?(ue.receiveObjectTransfer=ue.Fb,ue.threadInitTLS=ue.pb,ue.setExitStatus=ue.ob):Rt()},ob:c=>te=c,Qb:["$terminateWorker"],Ib:()=>{for(var c of ue.Za)Rr(c);for(c of ue.Ya)Rr(c);ue.Ya=[],ue.Za=[],ue.Qa=[]},nb:c=>{var g=c.Xa;delete ue.Qa[g],ue.Ya.push(c),ue.Za.splice(ue.Za.indexOf(c),1),c.Xa=0,Ts(g)},Fb(){},pb(){ue.qb.forEach(c=>c())},mb:c=>new Promise(g=>{c.onmessage=R=>{R=R.data;var F=R.cmd;if(R.targetThread&&R.targetThread!=Fa()){var ie=ue.Qa[R.targetThread];ie?ie.postMessage(R,R.transferList):q(`Internal error! Worker sent a message "${F}" to target pthread ${R.targetThread}, but that thread no longer exists!`)}else F==="checkMailbox"?br():F==="spawnThread"?Pr(R):F==="cleanupThread"?ue.nb(ue.Qa[R.thread]):F==="killThread"?(R=R.thread,F=ue.Qa[R],delete ue.Qa[R],Rr(F),Ts(R),ue.Za.splice(ue.Za.indexOf(F),1),F.Xa=0):F==="cancelThread"?ue.Qa[R.thread].postMessage({cmd:"cancel"}):F==="loaded"?(c.loaded=!0,I&&!c.Xa&&c.unref(),g(c)):F==="alert"?alert(`Thread ${R.threadId}: ${R.text}`):R.target==="setimmediate"?c.postMessage(R):F==="callHandler"?u[R.handler](...R.args):F&&q(`worker sent an unknown command ${F}`)},c.onerror=R=>{throw q(`worker sent an error! ${R.filename}:${R.lineno}: ${R.message}`),R},I&&(c.on("message",R=>c.onmessage({data:R})),c.on("error",R=>c.onerror(R)));var $=[],C=["onExit"],M;for(M of C)u.hasOwnProperty(M)&&$.push(M);c.postMessage({cmd:"load",handlers:$,urlOrBlob:u.mainScriptUrlOrBlob||n,wasmMemory:J,wasmModule:ae})})};u.PThread=ue;var wr=c=>{for(;0{var c=Fa(),g=l()[c+52>>>2>>>0];c=l()[c+56>>>2>>>0],Qf(g,g-c),Wa(g)};function Cn(c){if(k)return De(1,0,c);Qt(c)}u.invokeEntryPoint=(c,g)=>{c=Zf.apply(null,[c,g]),0>>2>>>0]=g},this.sb=function(g){l()[this.gb+8>>>2>>>0]=g},this.hb=function(g,$){this.rb(),this.tb(g),this.sb($)},this.rb=function(){l()[this.gb+16>>>2>>>0]=0}}var Dr=0;function Oa(c,g,$,C){return k?De(2,1,c,g,$,C):za(c,g,$,C)}function za(c,g,$,C){if(c>>>=0,g>>>=0,$>>>=0,C>>>=0,typeof SharedArrayBuffer>"u")return q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var M=[];return k&&M.length===0?Oa(c,g,$,C):(c={Hb:$,Xa:c,ub:C,Nb:M},k?(c.Pb="spawnThread",postMessage(c,M),0):Pr(c))}function Ra(c,g,$){return k?De(3,1,c,g,$):0}function Pa(c,g){if(k)return De(4,1,c,g)}var In=c=>{for(var g=0,$=0;$=C?g++:2047>=C?g+=2:55296<=C&&57343>=C?(g+=4,++$):g+=3}return g},Ba=(c,g,$,C)=>{if($>>>=0,!(0=F){var ie=c.charCodeAt(++R);F=65536+((F&1023)<<10)|ie&1023}if(127>=F){if($>=C)break;g[$++>>>0]=F}else{if(2047>=F){if($+1>=C)break;g[$++>>>0]=192|F>>6}else{if(65535>=F){if($+2>=C)break;g[$++>>>0]=224|F>>12}else{if($+3>=C)break;g[$++>>>0]=240|F>>18,g[$++>>>0]=128|F>>12&63}g[$++>>>0]=128|F>>6&63}g[$++>>>0]=128|F&63}}return g[$>>>0]=0,$-M},le=(c,g,$)=>Ba(c,s(),g,$);function kn(c,g){if(k)return De(5,1,c,g)}function Nr(c,g,$){if(k)return De(6,1,c,g,$)}function Tn(c,g,$){return k?De(7,1,c,g,$):0}function An(c,g){if(k)return De(8,1,c,g)}function Mn(c,g,$){if(k)return De(9,1,c,g,$)}function On(c,g,$,C){if(k)return De(10,1,c,g,$,C)}function zn(c,g,$,C){if(k)return De(11,1,c,g,$,C)}function Rn(c,g,$,C){if(k)return De(12,1,c,g,$,C)}function Pn(c){if(k)return De(13,1,c)}function Bn(c,g){if(k)return De(14,1,c,g)}function Dn(c,g,$){if(k)return De(15,1,c,g,$)}var Da=()=>{if(!(0>>=0,typeof Atomics.Ob=="function"&&(Atomics.Ob(o(),c>>>2,c).value.then(br),c+=128,Atomics.store(o(),c>>>2,1))}u.__emscripten_thread_mailbox_await=Zt;var br=()=>{var c=Fa();if(c&&(Zt(c),!W))try{Yf(),Da()}catch(g){En(g)}};u.checkMailbox=br;var f=[],b=c=>c%4===0&&(c%100!==0||c%400===0),S=[0,31,60,91,121,152,182,213,244,274,305,335],T=[0,31,59,90,120,151,181,212,243,273,304,334];function O(c,g,$,C,M,R,F,ie){return k?De(16,1,c,g,$,C,M,R,F,ie):-52}function U(c,g,$,C,M,R,F){if(k)return De(17,1,c,g,$,C,M,R,F)}var X=c=>{var g=In(c)+1,$=ks(g);return $&&le(c,$,g),$},se=[],_e=(c,g)=>{se.length=0;for(var $;$=s()[c++>>>0];){var C=$!=105;C&=$!=112,g+=C&&g%8?4:0,se.push($==112?l()[g>>>2>>>0]:$==105?o()[g>>>2>>>0]:p()[g>>>3>>>0]),g+=C?8:4}return se},ye={},$e=()=>{if(!Pe){var c={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",_:v||"./this.program"},g;for(g in ye)ye[g]===void 0?delete c[g]:c[g]=ye[g];var $=[];for(g in c)$.push(`${g}=${c[g]}`);Pe=$}return Pe},Pe;function Be(c,g){if(k)return De(18,1,c,g);c>>>=0,g>>>=0;var $=0;return $e().forEach((C,M)=>{var R=g+$;for(M=l()[c+4*M>>>2>>>0]=R,R=0;R>>0>>>0]=C.charCodeAt(R);i()[M>>>0>>>0]=0,$+=C.length+1}),0}function z(c,g){if(k)return De(19,1,c,g);c>>>=0,g>>>=0;var $=$e();l()[c>>>2>>>0]=$.length;var C=0;return $.forEach(M=>C+=M.length+1),l()[g>>>2>>>0]=C,0}function fe(c){return k?De(20,1,c):52}function Ie(c,g,$,C){return k?De(21,1,c,g,$,C):52}function Pt(c,g,$,C,M){return k?De(22,1,c,g,$,C,M):70}var Na=[null,[],[]];function Nf(c,g,$,C){if(k)return De(23,1,c,g,$,C);g>>>=0,$>>>=0,C>>>=0;for(var M=0,R=0;R<$;R++){var F=l()[g>>>2>>>0],ie=l()[g+4>>>2>>>0];g+=8;for(var xe=0;xe>>0],Ee=Na[c];we===0||we===10?((c===1?Ae:q)(Ta(Ee,0)),Ee.length=0):Ee.push(we)}M+=ie}return l()[C>>>2>>>0]=M,0}var Lf=[31,29,31,30,31,30,31,31,30,31,30,31],Uf=[31,28,31,30,31,30,31,31,30,31,30,31];function x2(c){var g=Array(In(c)+1);return Ba(c,g,0,g.length),g}var S2=(c,g)=>{i().set(c,g>>>0)};function Ff(c,g,$,C){function M(P,be,Me){for(P=typeof P=="number"?P.toString():P||"";P.lengtham?-1:0vr-P.getDate())be-=vr-P.getDate()+1,P.setDate(1),11>Me?P.setMonth(Me+1):(P.setMonth(0),P.setFullYear(P.getFullYear()+1));else{P.setDate(P.getDate()+be);break}}return Me=new Date(P.getFullYear()+1,0,4),be=ie(new Date(P.getFullYear(),0,4)),Me=ie(Me),0>=F(be,P)?0>=F(Me,P)?P.getFullYear()+1:P.getFullYear():P.getFullYear()-1}c>>>=0,g>>>=0,$>>>=0,C>>>=0;var we=l()[C+40>>>2>>>0];C={Lb:o()[C>>>2>>>0],Kb:o()[C+4>>>2>>>0],eb:o()[C+8>>>2>>>0],jb:o()[C+12>>>2>>>0],fb:o()[C+16>>>2>>>0],ab:o()[C+20>>>2>>>0],Wa:o()[C+24>>>2>>>0],$a:o()[C+28>>>2>>>0],Rb:o()[C+32>>>2>>>0],Jb:o()[C+36>>>2>>>0],Mb:we?et(we):""},$=et($),we={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var Ee in we)$=$.replace(new RegExp(Ee,"g"),we[Ee]);var Ue="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Fe="January February March April May June July August September October November December".split(" ");we={"%a":P=>Ue[P.Wa].substring(0,3),"%A":P=>Ue[P.Wa],"%b":P=>Fe[P.fb].substring(0,3),"%B":P=>Fe[P.fb],"%C":P=>R((P.ab+1900)/100|0,2),"%d":P=>R(P.jb,2),"%e":P=>M(P.jb,2," "),"%g":P=>xe(P).toString().substring(2),"%G":P=>xe(P),"%H":P=>R(P.eb,2),"%I":P=>(P=P.eb,P==0?P=12:12{for(var be=0,Me=0;Me<=P.fb-1;be+=(b(P.ab+1900)?Lf:Uf)[Me++]);return R(P.jb+be,3)},"%m":P=>R(P.fb+1,2),"%M":P=>R(P.Kb,2),"%n":()=>` +`,"%p":P=>0<=P.eb&&12>P.eb?"AM":"PM","%S":P=>R(P.Lb,2),"%t":()=>" ","%u":P=>P.Wa||7,"%U":P=>R(Math.floor((P.$a+7-P.Wa)/7),2),"%V":P=>{var be=Math.floor((P.$a+7-(P.Wa+6)%7)/7);if(2>=(P.Wa+371-P.$a-2)%7&&be++,be)be==53&&(Me=(P.Wa+371-P.$a)%7,Me==4||Me==3&&b(P.ab)||(be=1));else{be=52;var Me=(P.Wa+7-P.$a-1)%7;(Me==4||Me==5&&b(P.ab%400-1))&&be++}return R(be,2)},"%w":P=>P.Wa,"%W":P=>R(Math.floor((P.$a+7-(P.Wa+6)%7)/7),2),"%y":P=>(P.ab+1900).toString().substring(2),"%Y":P=>P.ab+1900,"%z":P=>{P=P.Jb;var be=0<=P;return P=Math.abs(P)/60,(be?"+":"-")+("0000"+(P/60*100+P%60)).slice(-4)},"%Z":P=>P.Mb,"%%":()=>"%"},$=$.replace(/%%/g,"\0\0");for(Ee in we)$.includes(Ee)&&($=$.replace(new RegExp(Ee,"g"),we[Ee](C)));return $=$.replace(/\0\0/g,"%"),Ee=x2($),Ee.length>g?0:(S2(Ee,c),Ee.length-1)}var La=c=>{try{c()}catch(g){Xt(g)}};function E2(){var c=ne,g={};for(let[$,C]of Object.entries(c))g[$]=typeof C=="function"?function(){Ua.push($);try{return C.apply(null,arguments)}finally{W||(Ua.pop(),Bt&&Jt===1&&Ua.length===0&&(Jt=0,zt+=1,La(em),typeof Fibers<"u"&&Fibers.Sb()))}}:C;return g}var Jt=0,Bt=null,Wf=0,Ua=[],Gf={},Vf={},C2=0,Is=null,I2=[];function k2(){return new Promise((c,g)=>{Is={resolve:c,reject:g}})}function T2(){var c=ks(65548),g=c+12;l()[c>>>2>>>0]=g,l()[c+4>>>2>>>0]=g+65536,g=Ua[0];var $=Gf[g];return $===void 0&&($=C2++,Gf[g]=$,Vf[$]=g),g=$,o()[c+8>>>2>>>0]=g,c}function A2(){var c=o()[Bt+8>>>2>>>0];return c=ne[Vf[c]],--zt,c()}function M2(c){if(!W){if(Jt===0){var g=!1,$=!1;c((C=0)=>{if(!W&&(Wf=C,g=!0,$)){Jt=2,La(()=>tm(Bt)),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.resume(),C=!1;try{var M=A2()}catch(ie){M=ie,C=!0}var R=!1;if(!Bt){var F=Is;F&&(Is=null,(C?F.reject:F.resolve)(M),R=!0)}if(C&&!R)throw M}}),$=!0,g||(Jt=1,Bt=T2(),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.pause(),La(()=>Jf(Bt)))}else Jt===2?(Jt=0,La(rm),qf(Bt),Bt=null,I2.forEach(C=>{if(!W)try{C(),Da()}catch(M){En(M)}})):Xt(`invalid state: ${Jt}`);return Wf}}function O2(c){return M2(g=>{c().then(g)})}ue.hb();var z2=[Sn,Cn,Oa,Ra,Pa,kn,Nr,Tn,An,Mn,On,zn,Rn,Pn,Bn,Dn,O,U,Be,z,fe,Ie,Pt,Nf],R2={r:function(c,g,$){return O2(async()=>{await u.Ab(c,g,$)})},b:function(c,g,$){throw c>>>=0,new Cs(c).hb(g>>>0,$>>>0),Dr=c,Dr},N:function(c){jf(c>>>0,!E,1,!w,131072,!1),ue.pb()},l:function(c){c>>>=0,k?postMessage({cmd:"cleanupThread",thread:c}):ue.nb(ue.Qa[c])},J:za,i:Ra,T:Pa,F:kn,H:Nr,U:Tn,R:An,L:Mn,Q:On,p:zn,G:Rn,D:Pn,S:Bn,E:Dn,q:()=>1,B:function(c,g){c>>>=0,c==g>>>0?setTimeout(()=>br()):k?postMessage({targetThread:c,cmd:"checkMailbox"}):(c=ue.Qa[c])&&c.postMessage({cmd:"checkMailbox"})},K:function(c,g,$,C){g>>>=0,f.length=$,C=C>>>0>>>3;for(var M=0;M<$;M++)f[M]=p()[C+M>>>0];return c=0>c?zr[-c-1]:z2[c],ue.vb=g,g=c.apply(null,f),ue.vb=0,g},M:Zt,W:function(c){I&&ue.Qa[c>>>0].ref()},u:function(c,g,$){c=g+2097152>>>0<4194305-!!c?(c>>>0)+4294967296*g:NaN,$>>>=0,c=new Date(1e3*c),o()[$>>>2>>>0]=c.getUTCSeconds(),o()[$+4>>>2>>>0]=c.getUTCMinutes(),o()[$+8>>>2>>>0]=c.getUTCHours(),o()[$+12>>>2>>>0]=c.getUTCDate(),o()[$+16>>>2>>>0]=c.getUTCMonth(),o()[$+20>>>2>>>0]=c.getUTCFullYear()-1900,o()[$+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[$+28>>>2>>>0]=c},v:function(c,g,$){c=g+2097152>>>0<4194305-!!c?(c>>>0)+4294967296*g:NaN,$>>>=0,c=new Date(1e3*c),o()[$>>>2>>>0]=c.getSeconds(),o()[$+4>>>2>>>0]=c.getMinutes(),o()[$+8>>>2>>>0]=c.getHours(),o()[$+12>>>2>>>0]=c.getDate(),o()[$+16>>>2>>>0]=c.getMonth(),o()[$+20>>>2>>>0]=c.getFullYear()-1900,o()[$+24>>>2>>>0]=c.getDay(),g=(b(c.getFullYear())?S:T)[c.getMonth()]+c.getDate()-1|0,o()[$+28>>>2>>>0]=g,o()[$+36>>>2>>>0]=-(60*c.getTimezoneOffset()),g=new Date(c.getFullYear(),6,1).getTimezoneOffset();var C=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=(g!=C&&c.getTimezoneOffset()==Math.min(C,g))|0,o()[$+32>>>2>>>0]=c},w:function(c){c>>>=0;var g=new Date(o()[c+20>>>2>>>0]+1900,o()[c+16>>>2>>>0],o()[c+12>>>2>>>0],o()[c+8>>>2>>>0],o()[c+4>>>2>>>0],o()[c>>>2>>>0],0),$=o()[c+32>>>2>>>0],C=g.getTimezoneOffset(),M=new Date(g.getFullYear(),6,1).getTimezoneOffset(),R=new Date(g.getFullYear(),0,1).getTimezoneOffset(),F=Math.min(R,M);return 0>$?o()[c+32>>>2>>>0]=+(M!=R&&F==C):0<$!=(F==C)&&(M=Math.max(R,M),g.setTime(g.getTime()+6e4*((0<$?F:M)-C))),o()[c+24>>>2>>>0]=g.getDay(),$=(b(g.getFullYear())?S:T)[g.getMonth()]+g.getDate()-1|0,o()[c+28>>>2>>>0]=$,o()[c>>>2>>>0]=g.getSeconds(),o()[c+4>>>2>>>0]=g.getMinutes(),o()[c+8>>>2>>>0]=g.getHours(),o()[c+12>>>2>>>0]=g.getDate(),o()[c+16>>>2>>>0]=g.getMonth(),o()[c+20>>>2>>>0]=g.getYear(),c=g.getTime(),isNaN(c)?(o()[Hf()>>>2>>>0]=61,c=-1):c/=1e3,Xf((Wt=c,1<=+Math.abs(Wt)?0>>0:~~+Math.ceil((Wt-+(~~Wt>>>0))/4294967296)>>>0:0)),c>>>0},s:O,t:U,A:function(c,g,$){function C(we){return(we=we.toTimeString().match(/\(([A-Za-z ]+)\)$/))?we[1]:"GMT"}c>>>=0,g>>>=0,$>>>=0;var M=new Date().getFullYear(),R=new Date(M,0,1),F=new Date(M,6,1);M=R.getTimezoneOffset();var ie=F.getTimezoneOffset(),xe=Math.max(M,ie);l()[c>>>2>>>0]=60*xe,o()[g>>>2>>>0]=+(M!=ie),c=C(R),g=C(F),c=X(c),g=X(g),ie>>2>>>0]=c,l()[$+4>>>2>>>0]=g):(l()[$>>>2>>>0]=g,l()[$+4>>>2>>>0]=c)},d:()=>{Xt("")},c:function(c,g,$){return c>>>=0,g=_e(g>>>0,$>>>0),zr[c].apply(null,g)},k:function(c,g,$){return c>>>=0,g=_e(g>>>0,$>>>0),zr[c].apply(null,g)},m:()=>{},j:()=>Date.now(),V:()=>{throw zt+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>I?(Xm(),tr(ho)).cpus().length:navigator.hardwareConcurrency,y:function(c){c>>>=0;var g=s().length;if(c<=g||4294901760=$;$*=2){var C=g*(1+.2/$);C=Math.min(C,c+100663296);var M=Math;C=Math.max(c,C);e:{M=(M.min.call(M,4294901760,C+(65536-C%65536)%65536)-J.buffer.byteLength+65535)/65536;try{J.grow(M),Ve();var R=1;break e}catch{}R=void 0}if(R)return!0}return!1},O:Be,P:z,I:Qt,h:fe,o:Ie,x:Pt,n:Nf,a:J||u.wasmMemory,z:Ff,e:function(c,g,$,C){return Ff(c>>>0,g>>>0,$>>>0,C>>>0)}},ne=function(){function c($,C){return ne=$.exports,ne=E2(),ne=P2(),ue.qb.push(ne.Da),Le.unshift(ne.X),ae=C,Mr(),ne}var g={a:R2};if(it++,u.instantiateWasm)try{return u.instantiateWasm(g,c)}catch($){q(`Module.instantiateWasm callback failed with error: ${$}`),m($)}return ka(g,function($){c($.instance,$.module)}).catch(m),{}}();u._OrtInit=(c,g)=>(u._OrtInit=ne.Y)(c,g),u._OrtGetLastError=(c,g)=>(u._OrtGetLastError=ne.Z)(c,g),u._OrtCreateSessionOptions=(c,g,$,C,M,R,F,ie,xe,we)=>(u._OrtCreateSessionOptions=ne._)(c,g,$,C,M,R,F,ie,xe,we),u._OrtAppendExecutionProvider=(c,g)=>(u._OrtAppendExecutionProvider=ne.$)(c,g),u._OrtAddFreeDimensionOverride=(c,g,$)=>(u._OrtAddFreeDimensionOverride=ne.aa)(c,g,$),u._OrtAddSessionConfigEntry=(c,g,$)=>(u._OrtAddSessionConfigEntry=ne.ba)(c,g,$),u._OrtReleaseSessionOptions=c=>(u._OrtReleaseSessionOptions=ne.ca)(c),u._OrtCreateSession=(c,g,$)=>(u._OrtCreateSession=ne.da)(c,g,$),u._OrtReleaseSession=c=>(u._OrtReleaseSession=ne.ea)(c),u._OrtGetInputOutputCount=(c,g,$)=>(u._OrtGetInputOutputCount=ne.fa)(c,g,$),u._OrtGetInputName=(c,g)=>(u._OrtGetInputName=ne.ga)(c,g),u._OrtGetOutputName=(c,g)=>(u._OrtGetOutputName=ne.ha)(c,g),u._OrtFree=c=>(u._OrtFree=ne.ia)(c),u._OrtCreateTensor=(c,g,$,C,M,R)=>(u._OrtCreateTensor=ne.ja)(c,g,$,C,M,R),u._OrtGetTensorData=(c,g,$,C,M)=>(u._OrtGetTensorData=ne.ka)(c,g,$,C,M),u._OrtReleaseTensor=c=>(u._OrtReleaseTensor=ne.la)(c),u._OrtCreateRunOptions=(c,g,$,C)=>(u._OrtCreateRunOptions=ne.ma)(c,g,$,C),u._OrtAddRunConfigEntry=(c,g,$)=>(u._OrtAddRunConfigEntry=ne.na)(c,g,$),u._OrtReleaseRunOptions=c=>(u._OrtReleaseRunOptions=ne.oa)(c),u._OrtCreateBinding=c=>(u._OrtCreateBinding=ne.pa)(c),u._OrtBindInput=(c,g,$)=>(u._OrtBindInput=ne.qa)(c,g,$),u._OrtBindOutput=(c,g,$,C)=>(u._OrtBindOutput=ne.ra)(c,g,$,C),u._OrtClearBoundOutputs=c=>(u._OrtClearBoundOutputs=ne.sa)(c),u._OrtReleaseBinding=c=>(u._OrtReleaseBinding=ne.ta)(c),u._OrtRunWithBinding=(c,g,$,C,M)=>(u._OrtRunWithBinding=ne.ua)(c,g,$,C,M),u._OrtRun=(c,g,$,C,M,R,F,ie)=>(u._OrtRun=ne.va)(c,g,$,C,M,R,F,ie),u._OrtEndProfiling=c=>(u._OrtEndProfiling=ne.wa)(c),u._JsepOutput=(c,g,$)=>(u._JsepOutput=ne.xa)(c,g,$),u._JsepGetNodeName=c=>(u._JsepGetNodeName=ne.ya)(c);var Hf=()=>(Hf=ne.za)(),Fa=u._pthread_self=()=>(Fa=u._pthread_self=ne.Aa)(),ks=u._malloc=c=>(ks=u._malloc=ne.Ba)(c),qf=u._free=c=>(qf=u._free=ne.Ca)(c);u.__emscripten_tls_init=()=>(u.__emscripten_tls_init=ne.Da)();var jf=u.__emscripten_thread_init=(c,g,$,C,M,R)=>(jf=u.__emscripten_thread_init=ne.Fa)(c,g,$,C,M,R);u.__emscripten_thread_crashed=()=>(u.__emscripten_thread_crashed=ne.Ga)();var Kf=(c,g,$,C)=>(Kf=ne.Ha)(c,g,$,C),Ts=c=>(Ts=ne.Ia)(c),As=u.__emscripten_thread_exit=c=>(As=u.__emscripten_thread_exit=ne.Ja)(c),Yf=()=>(Yf=ne.Ka)(),Xf=c=>(Xf=ne.La)(c),Qf=(c,g)=>(Qf=ne.Ma)(c,g),Ms=()=>(Ms=ne.Na)(),Wa=c=>(Wa=ne.Oa)(c),Os=c=>(Os=ne.Pa)(c),Zf=u.dynCall_ii=(c,g)=>(Zf=u.dynCall_ii=ne.Ra)(c,g),Jf=c=>(Jf=ne.Sa)(c),em=()=>(em=ne.Ta)(),tm=c=>(tm=ne.Ua)(c),rm=()=>(rm=ne.Va)();u.___start_em_js=945539,u.___stop_em_js=945700;function P2(){var c=ne;c=Object.assign({},c);var g=C=>()=>C()>>>0,$=C=>M=>C(M)>>>0;return c.za=g(c.za),c.Aa=g(c.Aa),c.Ba=$(c.Ba),c.emscripten_main_runtime_thread_id=g(c.emscripten_main_runtime_thread_id),c.Na=g(c.Na),c.Pa=$(c.Pa),c}u.wasmMemory=J,u.stackAlloc=Os,u.stackSave=Ms,u.stackRestore=Wa,u.keepRuntimeAlive=()=>0r)}),Zm=Sr((t,e)=>{e.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\n'}),mo,go,li,qn,Vr,ui,_o,yo,wo,bo,Xe,Hr=V(()=>{mo=jm(),go=Qm(),qn=!1,Vr=!1,ui=!1,_o=t=>{if(t===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+t+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},yo=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},wo=(t,e)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",bo=async t=>{if(qn)return Promise.resolve();if(Vr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ui)throw new Error("previous call to 'initializeWebAssembly()' failed.");Vr=!0;let e=t.initTimeout,r=t.numThreads,n=t.simd,a=_o(r),i=n&&yo(),s=t.wasmPaths,o=typeof s=="string"?s:void 0,l=wo(i,a),d=typeof s=="object"?s[l]:void 0,p=!1,u=[];if(e>0&&u.push(new Promise(h=>{setTimeout(()=>{p=!0,h()},e)})),u.push(new Promise((h,m)=>{let _=a?go:mo,y={locateFile:(v,x)=>{if(a&&v.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Zm()],{type:"text/javascript"}));if(v.endsWith(".wasm")){if(d)return d;let w=o??x;return l==="ort-wasm-simd.wasm"?w+"ort-wasm-simd.jsep.wasm":l==="ort-wasm-simd-threaded.wasm"?w+"ort-wasm-simd-threaded.jsep.wasm":w+l}return x+v}};if(a)if(y.numThreads=r,typeof Blob>"u")y.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let v=`var ortWasmThreaded=${_.toString()};`;y.mainScriptUrlOrBlob=new Blob([v],{type:"text/javascript"})}_(y).then(v=>{Vr=!1,qn=!0,li=v,h()},v=>{Vr=!1,ui=!0,m(v)})})),await Promise.race(u),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Xe=()=>{if(qn&&li)return li;throw new Error("WebAssembly is not initialized yet.")}}),je,jn,Ne,di=V(()=>{Hr(),je=(t,e)=>{let r=Xe(),n=r.lengthBytesUTF8(t)+1,a=r._malloc(n);return r.stringToUTF8(t,a,n),e.push(a),a},jn=(t,e,r,n)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([a,i])=>{let s=e?e+a:a;if(typeof i=="object")jn(i,s+".",r,n);else if(typeof i=="string"||typeof i=="number")n(s,i.toString());else if(typeof i=="boolean")n(s,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},Ne=t=>{let e=Xe(),r=e.stackSave();try{let n=e.stackAlloc(8);e._OrtGetLastError(n,n+4);let a=e.HEAP32[n/4],i=e.HEAPU32[n/4+1],s=i?e.UTF8ToString(i):"";throw new Error(`${t} ERROR_CODE: ${a}, ERROR_MESSAGE: ${s}`)}finally{e.stackRestore(r)}}}),vo,Jm=V(()=>{Hr(),di(),vo=t=>{let e=Xe(),r=0,n=[],a=t||{};try{if(t?.logSeverityLevel===void 0)a.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)a.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(a.terminate=!1);let i=0;return t?.tag!==void 0&&(i=je(t.tag,n)),r=e._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,i),r===0&&Ne("Can't create run options."),t?.extra!==void 0&&jn(t.extra,"",new WeakSet,(s,o)=>{let l=je(s,n),d=je(o,n);e._OrtAddRunConfigEntry(r,l,d)!==0&&Ne(`Can't set a run config entry: ${s} - ${o}.`)}),[r,n]}catch(i){throw r!==0&&e._OrtReleaseRunOptions(r),n.forEach(s=>e._free(s)),i}}}),$o,xo,So,Eo,Co,eg=V(()=>{Hr(),di(),$o=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},xo=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},So=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},Eo=(t,e,r)=>{for(let n of e){let a=typeof n=="string"?n:n.name;switch(a){case"webnn":if(a="WEBNN",typeof n!="string"){let s=n;if(s?.deviceType){let o=je("deviceType",r),l=je(s.deviceType,r);Xe()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ne(`Can't set a session config entry: 'deviceType' - ${s.deviceType}.`)}if(s?.numThreads){let o=s.numThreads;(typeof o!="number"||!Number.isInteger(o)||o<0)&&(o=0);let l=je("numThreads",r),d=je(o.toString(),r);Xe()._OrtAddSessionConfigEntry(t,l,d)!==0&&Ne(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s?.powerPreference){let o=je("powerPreference",r),l=je(s.powerPreference,r);Xe()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ne(`Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.`)}}break;case"webgpu":if(a="JS",typeof n!="string"){let s=n;if(s?.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let o=je("preferredLayout",r),l=je(s.preferredLayout,r);Xe()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ne(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=je(a,r);Xe()._OrtAppendExecutionProvider(t,i)!==0&&Ne(`Can't append execution provider: ${a}.`)}},Co=t=>{let e=Xe(),r=0,n=[],a=t||{};So(a);try{let i=$o(a.graphOptimizationLevel??"all"),s=xo(a.executionMode??"sequential"),o=typeof a.logId=="string"?je(a.logId,n):0,l=a.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let d=a.logVerbosityLevel??0;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log verbosity level is not valid: ${d}`);let p=typeof a.optimizedModelFilePath=="string"?je(a.optimizedModelFilePath,n):0;if(r=e._OrtCreateSessionOptions(i,!!a.enableCpuMemArena,!!a.enableMemPattern,s,!!a.enableProfiling,0,o,l,d,p),r===0&&Ne("Can't create session options."),a.executionProviders&&Eo(r,a.executionProviders,n),a.enableGraphCapture!==void 0){if(typeof a.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${a.enableGraphCapture}`);let u=je("enableGraphCapture",n),h=je(a.enableGraphCapture.toString(),n);e._OrtAddSessionConfigEntry(r,u,h)!==0&&Ne(`Can't set a session config entry: 'enableGraphCapture' - ${a.enableGraphCapture}.`)}if(a.freeDimensionOverrides)for(let[u,h]of Object.entries(a.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let m=je(u,n);e._OrtAddFreeDimensionOverride(r,m,h)!==0&&Ne(`Can't set a free dimension override: ${u} - ${h}.`)}return a.extra!==void 0&&jn(a.extra,"",new WeakSet,(u,h)=>{let m=je(u,n),_=je(h,n);e._OrtAddSessionConfigEntry(r,m,_)!==0&&Ne(`Can't set a session config entry: ${u} - ${h}.`)}),[r,n]}catch(i){throw r!==0&&e._OrtReleaseSessionOptions(r),n.forEach(s=>e._free(s)),i}}}),ci,ar,Kn,pi,Yn,hi,fi,me=V(()=>{ci=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},ar=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},Kn=t=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][t],pi=t=>{switch(t){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: ${t}`)}},Yn=t=>{switch(t){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: ${t}`)}},hi=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool",fi=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${t}`)}}}),Xn,Io=V(()=>{Xn=async t=>{if(typeof t=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(t),n=[];for await(let a of r)n.push(a);return new Uint8Array(Buffer.concat(n))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let a=e.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(o){if(o instanceof RangeError){let l=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw o}let s=0;for(;;){let{done:o,value:l}=await a.read();if(o)break;let d=l.byteLength;new Uint8Array(i,s,d).set(l),s+=d}return new Uint8Array(i,0,n)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),ko,To,Ao,Mo,Oo,zo,Ke,ir=V(()=>{me(),ko=["V","I","W","E","F"],To=(t,e)=>{console.log(`[${ko[t]},${new Date().toISOString()}]${e}`)},Oo=(t,e)=>{Ao=t,Mo=e},zo=(t,e)=>{let r=Yn(t),n=Yn(Ao);r>=n&&To(r,typeof e=="function"?e():e)},Ke=(...t)=>{Mo&&zo(...t)}}),Ro,tg=V(()=>{me(),Ro=(t,e)=>new(pi(e))(t)}),mi=V(()=>{}),qr,Po,gi,_i,Bo,Do,rg=V(()=>{ir(),mi(),qr=t=>Math.ceil(t/16)*16,Po=1,gi=()=>Po++,_i=async(t,e,r,n)=>{let a=qr(r),i=t.device.createBuffer({size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=t.getCommandEncoder();t.endComputePass(),s.copyBufferToBuffer(e,0,i,0,a),t.flush(),await i.mapAsync(GPUMapMode.READ);let o=i.getMappedRange();if(n){let l=n();return l.set(new Uint8Array(o,0,r)),l}else return new Uint8Array(o.slice(0,r))}finally{i.destroy()}},Bo=class{constructor(t){this.backend=t,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map}upload(t,e){let r=e.buffer,n=e.byteOffset,a=e.byteLength,i=qr(a),s=this.storageCache.get(t);if(!s)throw new Error("gpu data for uploading does not exist");if(s.originalSize!==a)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${a}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=o.getMappedRange();new Uint8Array(l).set(new Uint8Array(r,n,a)),o.unmap();let d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(o,0,s.gpuData.buffer,0,i),Ke("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(o)}memcpy(t,e){let r=this.storageCache.get(t);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(e);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let a=qr(r.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,a)}registerExternalBuffer(t,e,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(t===r)return Ke("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`);this.externalBuffers.delete(r)}else n=gi();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:e}),this.externalBuffers.set(t,n),Ke("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${n}, registered.`),n}unregisterExternalBuffer(t){let e=this.externalBuffers.get(t);e!==void 0&&(this.storageCache.delete(e),this.externalBuffers.delete(t),Ke("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(t,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=qr(t),n,a=(e&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(e&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(a||i){let o=a?this.freeBuffers:this.freeUniformBuffers,l=o.get(r);l||(l=[],o.set(r,l)),l.length>0?n=l.pop():n=this.backend.device.createBuffer({size:r,usage:e})}else n=this.backend.device.createBuffer({size:r,usage:e});let s={id:gi(),type:0,buffer:n};return this.storageCache.set(s.id,{gpuData:s,originalSize:t}),Ke("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${s.id}`),s}get(t){return this.storageCache.get(t)?.gpuData}release(t){let e=this.storageCache.get(t);if(!e)throw new Error("releasing data does not exist");return Ke("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${e.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(e.gpuData.buffer),e.originalSize}async download(t,e){let r=this.storageCache.get(t);if(!r)throw new Error("data does not exist");await _i(this.backend,r.gpuData.buffer,r.originalSize,e)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending)(t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(t.size).push(t):(t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(t.size).push(t):t.destroy();this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let e of this.buffersPending)t.push(e);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let e=this.capturedPendingBuffers.get(t);e&&(e.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(t))}},Do=(...t)=>new Bo(...t)}),No,We,tt=V(()=>{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}},We=t=>new No(t)}),Lo,Cr,j,Qn,Uo,yi,wi,Ce=V(()=>{Lo=class{static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}},Cr=class{static calcShape(t,e,r=!1){let n=t.length,a=e.length;if(n===0)return e;if(a===0)return t;let i=Math.max(t.length,e.length),s=new Array(i);if(r){if(n<2||a<2)return;let o=Lo.calcMatMulShape([t[n-2],t[n-1]],[e[a-2],e[a-1]]);if(o===void 0)return;[s[i-2],s[i-1]]=o}for(let o=r?3:1;o<=i;o++){let l=n-o<0?1:t[n-o],d=a-o<0?1:e[a-o];if(l!==d&&l>1&&d>1)return;let p=Math.max(l,d);if(l&&d)s[i-o]=Math.max(l,d);else{if(p>1)return;s[i-o]=0}}return s}static isValidBroadcast(t,e){let r=t.length,n=e.length;if(r>n)return!1;for(let a=1;a<=r;a++)if(t[r-a]!==1&&t[r-a]!==e[n-a])return!1;return!0}},j=class Va{static size(e){return Va.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,r=4){let n=e.length;if(n===0)return[];let a=new Array(n),i=n-1;for(;i>=0;){if(e[i]%r===0){a[i]=e[i]/r;break}if(r%e[i]!==0)throw new Error("cannot convert shape");a[i]=1,r/=e[i],i--}for(i--;i>=0;i--)a[i]=e[i];return a}static sizeFromDimension(e,r){if(r<0||r>e.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return Va.getSizeFromDimensionRange(e,r,e.length)}static sizeToDimension(e,r){if(r<0||r>e.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${e.length} dimensions.`);return Va.getSizeFromDimensionRange(e,0,r)}static getSizeFromDimensionRange(e,r,n){let a=1;for(let i=r;i=0;--a)n[a]=n[a+1]*e[a+1];return n}static normalizeAxis(e,r){if(e<-r&&e>=r)throw new Error("unsupported axis for this operation.");return e<0?e+r:e}static normalizeAxes(e,r){return e.map(n=>this.normalizeAxis(n,r??e.length))}static sortBasedOnPerm(e,r){return r?r.map(n=>e[n]):e.slice().reverse()}static padShape(e,r){let n=e.length;return e.map((a,i)=>a+r[i]+r[i+n])}static areEqual(e,r){return e.length!==r.length?!1:e.every((n,a)=>n===r[a])}},Qn=class Nn{static adjustPoolAttributes(e,r,n,a,i,s){if(!e&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let o=0;o=n.length?n.push(r[o+2]):n[o]=r[o+2];for(let o=0;o=n[o]||s[o+n.length]>=n[o])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,r,n,a,i,s,o){if(o){if(i.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(a.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{me(),Ce(),Zn=64,Jn=(t,e)=>{if(e===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(t){case 10:return e>1?`vec${e}`:"f16";case 1:return e>1?`vec${e}`:"f32";case 6:return e>1?`vec${e}`:"i32";case 12:return e>1?`vec${e}`:"u32";case 7:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(e!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${t}`)}},Ze=(t,e=1)=>{let r=Jn(t,e);return typeof r=="string"?r:r[0]},mt=(t,e=1)=>{let r=Jn(t,e);return typeof r=="string"?r:r[1]},ce=(...t)=>{let e=[];return t.forEach(r=>{r.length!==0&&e.push({type:12,data:r},{type:12,data:j.computeStrides(r)})}),e},Qe=t=>t%4===0?4:t%2===0?2:1,ct=(t="f32",e,r="0")=>!e||e===1?`${t}(${r})`:`vec${e}<${t}>(${r})`,Nt=(t,e,r)=>t==="f32"?r:e===1?`f32(${r})`:`vec${e}f(${r})`,At=(t,e)=>e===4?`(${t}.x + ${t}.y + ${t}.z + ${t}.w)`:e===2?`(${t}.x + ${t}.y)`:e===3?`(${t}.x + ${t}.y + ${t}.z)`:t,ge=(t,e,r,n)=>t.startsWith("uniforms.")&&r>4?typeof e=="string"?n==="f16"?`${t}[(${e}) / 8][(${e}) % 8 / 4][(${e}) % 8 % 4]`:`${t}[(${e}) / 4][(${e}) % 4]`:n==="f16"?`${t}[${Math.floor(e/8)}][${Math.floor(e%8/4)}][${e%8%4}]`:`${t}[${Math.floor(e/4)}][${e%4}]`:r>1?`${t}[${e}]`:t,ea=(t,e,r,n,a)=>{let i=typeof r=="number",s=i?r:r.length,o=[...new Array(s).keys()],l=s<2?"u32":s<=4?`vec${s}`:`array`,d=Jn(e,a),p=typeof d=="string"?d:d[1],u=typeof d=="string"?d:d[0],h={indices:l,value:p,storage:u,tensor:e},m=B=>typeof B=="string"?B:`${B}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},y=i?"uniforms.":"",v=`${y}${t}_shape`,x=`${y}${t}_strides`,w="";for(let B=0;B ${h.indices} { + var indices: ${h.indices}; + var current = offset; + ${w} + return indices; + }`,I=B=>(_.offsetToIndices=!0,s<2?B:`o2i_${t}(${B})`),k=[];if(s>=2)for(let B=s-1;B>=0;B--)k.push(`${ge(x,B,s)} * (indices[${B}])`);let A=s<2?"":` + fn i2o_${t}(indices: ${h.indices}) -> u32 { + return ${k.join("+")}; + }`,D=B=>(_.indicesToOffset=!0,s<2?B:`i2o_${t}(${B})`),L=(...B)=>s===0?"0u":`${h.indices}(${B.map(m).join(",")})`,Y=(B,Q)=>s<2?`${B}`:`${ge(B,Q,s)}`,H=(B,Q,he)=>s<2?`${B}=${he};`:`${ge(B,Q,s)}=${he};`,re={},N=(B,Q)=>{_.broadcastedIndicesToOffset=!0;let he=`${Q.name}broadcastedIndicesTo${t}Offset`;if(he in re)return`${he}(${B})`;let ze=[];for(let Re=s-1;Re>=0;Re--){let Je=Q.indicesGet("outputIndices",Re+Q.rank-s);ze.push(`${Y(x,Re)} * (${Je} % ${Y(v,Re)})`)}return re[he]=`fn ${he}(outputIndices: ${Q.type.indices}) -> u32 { + return ${ze.length>0?ze.join("+"):"0u"}; + }`,`${he}(${B})`},ee=(B,Q)=>(()=>{if(h.storage===h.value)return`${t}[${B}]=${Q};`;if(h.storage==="vec2"&&h.value==="i32")return`${t}[${B}]=vec2(u32(${Q}), select(0u, 0xFFFFFFFFu, ${Q} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${t}[${B}]=vec2(u32(${Q}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${t}[${B}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Q}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),oe=B=>(()=>{if(h.storage===h.value)return`${t}[${B}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${t}[${B}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${t}[${B}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${t}[${B}] & 0xFFu), bool(${t}[${B}] & 0xFF00u), bool(${t}[${B}] & 0xFF0000u), bool(${t}[${B}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Ae=s<2?"":` + fn get_${t}ByIndices(indices: ${h.indices}) -> ${p} { + return ${oe(`i2o_${t}(indices)`)}; + }`,q=s<2?"":(()=>{let B=o.map(he=>`d${he}: u32`).join(", "),Q=o.map(he=>`d${he}`).join(", ");return` + fn get_${t}(${B}) -> ${p} { + return get_${t}ByIndices(${L(Q)}); + }`})(),J=(...B)=>{if(B.length!==s)throw new Error(`indices length must be ${s}`);let Q=B.map(m).join(",");return s===0?oe("0u"):s===1?oe(Q[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${t}(${Q})`)},ae=B=>s<2?oe(B):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${t}ByIndices(${B})`),W=s<2?"":` + fn set_${t}ByIndices(indices: ${h.indices}, value: ${p}) { + ${ee(`i2o_${t}(indices)`,"value")} + }`,te=s<2?"":(()=>{let B=o.map(he=>`d${he}: u32`).join(", "),Q=o.map(he=>`d${he}`).join(", ");return` + fn set_${t}(${B}, value: ${p}) { + set_${t}ByIndices(${L(Q)}, value); + }`})();return{impl:()=>{let B=[],Q=!1;return _.offsetToIndices&&(B.push(E),Q=!0),_.indicesToOffset&&(B.push(A),Q=!0),_.broadcastedIndicesToOffset&&(Object.values(re).forEach(he=>B.push(he)),Q=!0),_.set&&(B.push(te),Q=!0),_.setByIndices&&(B.push(W),Q=!0),_.get&&(B.push(q),Q=!0),_.getByIndices&&(B.push(Ae),Q=!0),!i&&Q&&B.unshift(`const ${v} = ${h.indices}(${r.join(",")});`,`const ${x} = ${h.indices}(${j.computeStrides(r).join(",")});`),B.join(` +`)},type:h,offsetToIndices:I,indicesToOffset:D,broadcastedIndicesToOffset:N,indices:L,indicesGet:Y,indicesSet:H,set:(...B)=>{if(B.length!==s+1)throw new Error(`indices length must be ${s}`);let Q=B[s];if(typeof Q!="string")throw new Error("value must be string");let he=B.slice(0,s).map(m).join(",");return s===0?ee("0u",Q):s===1?ee(he[0],Q):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${t}(${he}, ${Q})`)},setByOffset:ee,setByIndices:(B,Q)=>s<2?ee(B,Q):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${t}ByIndices(${B}, ${Q});`),get:J,getByOffset:oe,getByIndices:ae,usage:n,name:t,strides:x,shape:v,rank:s}},G=(t,e,r,n=1)=>ea(t,e,r,"input",n),de=(t,e,r,n=1)=>ea(t,e,r,"output",n),bi=(t,e,r,n=1)=>ea(t,e,r,"internal",n),Fo=class{constructor(t){this.normalizedDispatchGroup=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=Zn){let e=typeof t=="number"?t:t[0],r=typeof t=="number"?1:t[1],n=typeof t=="number"?1:t[2],a=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,i=a?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_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`,s=a?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${e*r*n}u + local_idx;`;return`@compute @workgroup_size(${e}, ${r}, ${n}) + fn main(${i}) { + ${s} + `}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,e){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let r=t.usage==="input"?"read":"read_write",n=t.type.storage;return`@group(0) @binding(${e}) var ${t.name}: array<${n}>;`}declareVariables(...t){return t.map(e=>this.declareVariable(e,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(e=>this.registerInternalVariable(e)),this}registerUniform(t,e,r=1){return this.uniforms.push({name:t,type:e,length:r}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:e,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?t.push(`@align(16) ${e}:array, ${Math.ceil(n/8)}>`):t.push(`${e}:array, ${Math.ceil(n/4)}>`);else{let a=n==null||n===1?r:`vec${n}<${r}>`;t.push(`${e}:${a}`)}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(` +`)}},Wo=t=>new Fo(t),jr=(t,e)=>{let r=t.length,n=[];for(let a=0;a1&&s===1&&n.unshift(i)}return n}}),Go,vi,Vo,Ho,Lt,qo,jo,Kr=V(()=>{me(),Ce(),tt(),Se(),Go=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},vi=(t,e)=>e&&e.length!==t?[...new Array(t).keys()].reverse():e,Vo=(t,e)=>j.sortBasedOnPerm(t,vi(t.length,e)),Ho=(t,e,r,n)=>{let a=[];a.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let i=0;i{let r=t.dataType,n=t.dims.length,a=vi(n,e),i=Vo(t.dims,a),s=de("output",r,i.length),o=G("a",r,n),l=d=>` + ${d.registerUniform("output_size","u32").declareVariables(o,s)} + + ${Ho(a,n,o,s)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${s.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${s.setByOffset("global_idx",o.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:["rank"]},getRunData:d=>{let p=j.size(i);return{outputs:[{dims:i,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ce(d[0].dims,i)]}},getShaderSource:l}},qo=(t,e)=>{Go(t.inputs),t.compute(Lt(t.inputs[0],e.perm))},jo=t=>We({perm:t.perm})}),Ko,Yo,Xo,Qo,Zo,Jo,el,tl,rl,nl,St,al,il,sl,ol,ll,ul,dl,cl,pl,hl,ng=V(()=>{me(),Ce(),Se(),xi(),Kr(),Ko={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"},Yo={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"},Xo={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Qo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Zo=(t,e)=>{let r=[];for(let n=e-t;n{let r=[],n=t.length;for(let i=0;it[i]);return[r,a]},el=(t,e)=>{let r=t.length+e.length,n=[],a=0;for(let i=0;i{for(let r=0;r{let r=[];if(!tl(t,e)){for(let n=0;nr.push(n))}return r},nl=(t,e,r,n,a,i,s)=>{let o=r[0].dims,l=j.size(i),d=j.size(s),p=G("_A",r[0].dataType,o),u=de("output",a,i),h=32,m=` + var aBestValues : array; + `;return{name:t,shaderCache:e,getShaderSource:_=>` + ${_.registerUniform("reduceSize","u32").declareVariables(p,u)} + ${m} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${_.mainStart(h)} + + let outputIndex = global_idx / ${h}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Xo[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${h}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${Ko[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${h}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 = ${Yo[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${u.setByOffset("outputIndex",`${n==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${Qo[n]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:l},programUniforms:[{type:12,data:d}]})}},St=(t,e,r,n)=>{let a=t.inputs.length===1?r:$i(t.inputs,r),i=a.axes;i.length===0&&!a.noopWithEmptyAxes&&(i=t.inputs[0].dims.map((m,_)=>_));let s=j.normalizeAxes(i,t.inputs[0].dims.length),o=s,l=t.inputs[0],d=rl(o,t.inputs[0].dims.length);d.length>0&&(l=t.compute(Lt(t.inputs[0],d),{inputs:[0],outputs:[-1]})[0],o=Zo(o.length,l.dims.length));let[p,u]=Jo(l.dims,o),h=p;a.keepDims&&(h=el(p,s)),t.compute(nl(e,{hint:a.cacheKey,inputDependencies:["type"]},[l],n,t.inputs[0].dataType,h,u),{inputs:[l]})},al=(t,e)=>{St(t,"ReduceMeanShared",e,"mean")},il=(t,e)=>{St(t,"ReduceL1Shared",e,"l1")},sl=(t,e)=>{St(t,"ReduceL2Shared",e,"l2")},ol=(t,e)=>{St(t,"ReduceLogSumExpShared",e,"logSumExp")},ll=(t,e)=>{St(t,"ReduceMaxShared",e,"max")},ul=(t,e)=>{St(t,"ReduceMinShared",e,"min")},dl=(t,e)=>{St(t,"ReduceProdShared",e,"prod")},cl=(t,e)=>{St(t,"ReduceSumShared",e,"sum")},pl=(t,e)=>{St(t,"ReduceSumSquareShared",e,"sumSquare")},hl=(t,e)=>{St(t,"ReduceLogSumShared",e,"logSum")}}),Et,fl,ta,$i,Ct,ml,gl,_l,yl,wl,bl,vl,$l,xl,Sl,It,El,Cl,Il,kl,Tl,Al,Ml,Ol,zl,Rl,xi=V(()=>{me(),Ce(),tt(),Se(),ng(),Et=t=>{if(!t||t.length===0||t.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(t.length===2&&t[1].dims.length!==1)throw new Error("Invalid axes input dims.")},fl=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],ta=(t,e,r,n,a,i,s=!1,o=!1)=>{let l=[],d=r[0].dims,p=d.length,u=j.normalizeAxes(a,p),h=!o&&u.length===0;d.forEach((y,v)=>{h||u.indexOf(v)>=0?s&&l.push(1):l.push(y)});let m=l.length,_=j.size(l);return{name:t,shaderCache:e,getShaderSource:y=>{let v=[],x=G("_A",r[0].dataType,p),w=de("output",i,m),E=n(x,w,u),I=E[2];for(let k=0,A=0;k=0?(s&&A++,I=`for(var j${k}: u32 = 0; j${k} < ${d[k]}; j${k}++) { + ${E[2].includes("last_index")?`let last_index = j${k};`:""} + ${x.indicesSet("input_indices",k,`j${k}`)} + ${I} + }`):(v.push(`${x.indicesSet("input_indices",k,w.indicesGet("output_indices",A))};`),A++);return` + + ${y.registerUniform("output_size","u32").declareVariables(x,w)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${x.type.indices}; + let output_indices = ${w.offsetToIndices("global_idx")}; + + ${v.join(` +`)} + ${E[0]} // init ops for reduce max/min + ${E[1]} + ${I} + ${E[3]} + ${E.length===4?w.setByOffset("global_idx","value"):E.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ce(d,l)]})}},$i=(t,e)=>{let r=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(n=>r.push(Number(n))),We({axes:r,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},Ct=(t,e,r,n)=>{let a=t.inputs,i=a.length===1?r:$i(a,r);t.compute(ta(e,{hint:i.cacheKey,inputDependencies:["rank"]},[a[0]],i.noopWithEmptyAxes&&i.axes.length===0?fl:n,i.axes,a[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},ml=(t,e)=>{Et(t.inputs),Ct(t,"ReduceLogSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},gl=(t,e)=>{Et(t.inputs),Ct(t,"ReduceL1",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},_l=(t,e)=>{Et(t.inputs),Ct(t,"ReduceL2",e,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},yl=(t,e)=>{Et(t.inputs),Ct(t,"ReduceLogSumExp",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},wl=(t,e)=>{Et(t.inputs),Ct(t,"ReduceMax",e,(r,n,a)=>{let i=[];for(let s=0;s=0||a.length===0)&&i.push(r.indicesSet("input_indices",s,0));return[`${i.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},bl=(t,e)=>{Et(t.inputs),Ct(t,"ReduceMean",e,(r,n,a)=>{let i=1;for(let s=0;s=0||a.length===0)&&(i*=t.inputs[0].dims[s]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${i});`]})},vl=(t,e)=>{Et(t.inputs),Ct(t,"ReduceMin",e,(r,n,a)=>{let i=[];for(let s=0;s=0||a.length===0)&&i.push(`input_indices[${s}] = 0;`);return[`${i.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},$l=(t,e)=>{Et(t.inputs),Ct(t,"ReduceProd",e,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},xl=(t,e)=>{Et(t.inputs),Ct(t,"ReduceSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Sl=(t,e)=>{Et(t.inputs),Ct(t,"ReduceSumSquare",e,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},It=(t,e,r)=>{if(e.length===0)return r;let n=1,a=1;for(let i=0;i1024},El=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?bl(t,e):al(t,e)},Cl=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?gl(t,e):il(t,e)},Il=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?_l(t,e):sl(t,e)},kl=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?yl(t,e):ol(t,e)},Tl=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?wl(t,e):ll(t,e)},Al=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?vl(t,e):ul(t,e)},Ml=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?$l(t,e):dl(t,e)},Ol=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?xl(t,e):cl(t,e)},zl=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Sl(t,e):pl(t,e)},Rl=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?ml(t,e):hl(t,e)}}),Si,Pl,Bl,Ei,ag=V(()=>{me(),tt(),xi(),Si=t=>{if(!t||t.length===0||t.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(t[0].dataType!==1)throw new Error("Invalid input type.")},Pl=(t,e)=>{Si(t.inputs);let r=(n,a,i)=>{let s=[];for(let o=0;o=0||i.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${e.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",a.setByOffset("global_idx","best_index")]};t.compute(ta("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},Bl=(t,e)=>{Si(t.inputs);let r=(n,a,i)=>{let s=[];for(let o=0;o=0||i.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${e.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",a.setByOffset("global_idx","best_index")]};t.compute(ta("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},Ei=t=>We(t)}),Dl,Nl,Ll,Ul,ra,Fl,Wl,Gl=V(()=>{me(),mi(),Se(),Dl=(t,e)=>{let r=t[0],n=t[1],a=t[2],i=t[3],s=t[4],o=t[5];if(s&&o)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=r.dims[0],d=r.dims[1],p=r.dims[2];if(a.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(a.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=a.dims[0]/3,h=u,m=h;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let E of e.qkvHiddenSizes)if(E%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=e.qkvHiddenSizes[0],h=e.qkvHiddenSizes[1],m=e.qkvHiddenSizes[2]}let _=d;if(u!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(a.dims[0]!==u+h+m)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let y=0;if(s){if(h!==m)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(s.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(s.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==e.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==h/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(y=s.dims[3])}let v=_+y,x=-1,w=0;if(i)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");if(o)throw new Error("relativePositionBias is not supported");return{batchSize:l,sequenceLength:d,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:v,maxSequenceLength:x,inputHiddenSize:p,hiddenSize:u,vHiddenSize:m,headSize:Math.floor(u/e.numHeads),vHeadSize:Math.floor(m/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:w,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Nl=(t,e,r,n)=>{let a=Qe(n),i=64,s=n/a;s{let h=de("x",e.dataType,e.dims,a),m="thread_max_vector";a===2?m="max(thread_max_vector.x, thread_max_vector.y)":a===4&&(m="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let _=mt(e.dataType),y=[{name:"d_inv",type:_},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return` + var wgMax: array; + var wgSum: array; + ${u.registerUniforms(y).declareVariables(h)} + ${u.mainStart([i,1,1])} + let localOffset = local_idx * uniforms.elements_per_wg; + let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset; + + var thread_max_vector = ${ct("f32",a,"-3.402823e+38f")}; + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + thread_max_vector = max(${Nt(_,a,"x[offset + i]")}, thread_max_vector); + } + wgMax[local_idx] = ${m}; + workgroupBarrier(); + + var maxValue = -3.402823e+38f; + for (var i = 0u; i < ${i}; i++) { + maxValue = max(wgMax[i], maxValue); + } + + var sumVector = ${ct("f32",a,"0")}; + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + sumVector += exp(${Nt(_,a,"x[offset + i]")} - maxValue); + } + wgSum[local_idx] = ${At("sumVector",a)}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${i}; i++) { + sum += wgSum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + x[offset + i] = ${ct(_,a,"uniforms.d_inv")}; + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + let f32input = ${Nt(_,a,"x[offset + i]")}; + x[offset + i] = ${h.type.value}(exp(f32input - maxValue) / sum); + } + } + }`};t.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${i};${d};${a}`},getShaderSource:p,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:l})},{inputs:[e],outputs:[]})},Ll=(t,e,r,n,a,i)=>{let s=[a.batchSize,a.numHeads,a.sequenceLength,a.kvSequenceLength+a.pastSequenceLength],o=i.scale===0?1/Math.sqrt(a.headSize):i.scale,l=Qe(a.headSize),d=a.headSize/l,p=12,u={x:Math.ceil(a.totalSequenceLength/p),y:Math.ceil(a.sequenceLength/p),z:a.batchSize*a.numHeads},h=[{type:12,data:a.sequenceLength},{type:12,data:d},{type:12,data:a.totalSequenceLength},{type:12,data:a.kvSequenceLength},{type:e.dataType,data:o}],m=[e,r],_=v=>{let x=G("q",e.dataType,e.dims,l),w=G("key",r.dataType,r.dims,l),E=de("output",e.dataType,s),I=Ze(e.dataType),k=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:I}];return` + const beta: ${I} = 1.0; + const TILE_SIZE = ${p}u; + + var tileQ: array<${x.type.storage}, ${p*p}>; + var tileK: array<${x.type.storage}, ${p*p}>; + ${v.registerUniforms(k).declareVariables(x,w,E)} + ${v.mainStart([p,p,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let lm = m + local_id.y; + let ln = n + local_id.x; + + let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K; + + var value = ${ct(I,l)}; + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m + local_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) { + tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x]; + } + workgroupBarrier(); + + for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:e.dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:_},{inputs:m,outputs:[-1]})[0];return Nl(t,y,a.batchSize*a.numHeads*a.sequenceLength,a.totalSequenceLength),y},Ul=(t,e,r,n)=>{let a=[n.batchSize,n.sequenceLength,n.vHiddenSize],i=12,s={x:Math.ceil(n.vHeadSize/i),y:Math.ceil(n.sequenceLength/i),z:n.batchSize*n.numHeads},o=[{type:12,data:n.sequenceLength},{type:12,data:n.totalSequenceLength},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.vHiddenSize}],l=d=>{let p=G("probs",e.dataType,e.dims),u=G("v",r.dataType,r.dims),h=de("output",e.dataType,a),m=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileQ: array<${p.type.value}, ${i*i}>; + var tileK: array<${p.type.value}, ${i*i}>; + ${d.registerUniforms(m).declareVariables(p,u,h)} + ${d.mainStart([i,i,1])} + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE + local_id.y; + let n = workgroup_id.x * TILE_SIZE + local_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + let offsetB = headIdx * (uniforms.N * uniforms.K) + n; + + var value = ${p.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) { + tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:a,dataType:e.dataType,gpuDataType:0}],dispatchGroup:s,programUniforms:o}),getShaderSource:l},{inputs:[e,r],outputs:[0]})[0]},ra=(t,e,r,n,a,i,s,o,l,d,p)=>{let u=Ll(t,e,r,l,d,p);Ul(t,u,n,d)},Fl=(t,e)=>{let r=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],n=e.sequenceLength,a=e.inputHiddenSize,i=e.headSize,s=12,o={x:Math.ceil(e.headSize/s),y:Math.ceil(e.sequenceLength/s),z:e.batchSize*e.numHeads},l=[t.inputs[0],t.inputs[1],t.inputs[2]],d=[{type:12,data:n},{type:12,data:a},{type:12,data:i},{type:12,data:e.numHeads},{type:12,data:e.headSize},{type:12,data:e.hiddenSize},{type:12,data:e.hiddenSize+e.hiddenSize+e.vHiddenSize}],p=u=>{let h=de("output_q",l[0].dataType,r),m=de("output_k",l[0].dataType,r),_=de("output_v",l[0].dataType,r),y=G("input",l[0].dataType,l[0].dims),v=G("weight",l[1].dataType,l[1].dims),x=G("bias",l[2].dataType,l[2].dims),w=y.type.storage,E=[{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 = ${s}u; + var tileInput: array<${w}, ${s*s}>; + var tileWeightQ: array<${w}, ${s*s}>; + var tileWeightK: array<${w}, ${s*s}>; + var tileWeightV: array<${w}, ${s*s}>; + ${u.registerUniforms(E).declareVariables(y,v,x,h,m,_)} + ${u.mainStart([s,s,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE + local_id.y; + let n = workgroup_id.x * TILE_SIZE + local_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${w}(0); + var valueK = ${w}(0); + var valueV = ${w}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:d}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Wl=(t,e)=>{let r=Dl(t.inputs,e),[n,a,i]=Fl(t,r);return ra(t,n,a,i,t.inputs[4],void 0,void 0,void 0,t.inputs[5],r,e)}}),Vl,Hl,ql,jl,ig=V(()=>{xt(),me(),Ce(),tt(),Se(),Vl=(t,e)=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,a,i)=>{let s=a.length;if(s!==n.length)throw new Error(`${i}: num dimensions != ${s}`);a.forEach((o,l)=>{if(o!==n[l])throw new Error(`${i}: dim[${l}] do not match`)})};if(t[0].dims.length>1){let n=e.format==="NHWC"?e.spatial?t[0].dims.slice(-1):t[0].dims.slice(-1).concat(t[0].dims.slice(1,t[0].dims.length-1)):t[0].dims.slice(1,e.spatial?2:void 0);r(t[1].dims,n,"Invalid input scale"),r(t[2].dims,n,"Invalid input B"),r(t[3].dims,n,"Invalid input mean"),r(t[4].dims,n,"Invalid input var")}else r(t[1].dims,[1],"Invalid input scale"),r(t[2].dims,[1],"Invalid input B"),r(t[3].dims,[1],"Invalid input mean"),r(t[4].dims,[1],"Invalid input var")},Hl=(t,e)=>{let{epsilon:r,spatial:n,format:a}=e,i=t[0].dims,s=n?Qe(i[i.length-1]):1,o=a==="NHWC"&&i.length>1?s:1,l=j.size(i)/s,d=n,p=d?i.length:i,u=G("x",t[0].dataType,t[0].dims,s),h=G("scale",t[1].dataType,t[1].dims,o),m=G("bias",t[2].dataType,t[2].dims,o),_=G("inputMean",t[3].dataType,t[3].dims,o),y=G("inputVar",t[4].dataType,t[4].dims,o),v=de("y",t[0].dataType,p,s),x=()=>{let E="";if(n)E=`let cOffset = ${i.length===1?"0u":a==="NHWC"?`outputIndices[${i.length-1}] / ${s}`:"outputIndices[1]"};`;else if(a==="NCHW")E=` + ${v.indicesSet("outputIndices","0","0")} + let cOffset = ${v.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${h.type.indices}(0); + cIndices[0] = outputIndices[${i.length-1}];`;for(let I=1;I` + const epsilon = ${r}; + ${E.registerUniform("outputSize","u32").declareVariables(u,h,m,_,y,v)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${v.offsetToIndices(`global_idx * ${s}`)}; + ${x()} + let scale = ${h.getByOffset("cOffset")}; + let bias = ${m.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${y.getByOffset("cOffset")}; + let x = ${u.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${v.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${e.epsilon}_${e.format}_${n}_${s}`,inputDependencies:d?["rank","type","type","type","type"]:void 0},getShaderSource:w,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d?[{type:12,data:l},...ce(i)]:[{type:12,data:l}]})}},ql=t=>We(t),jl=(t,e)=>{let{inputs:r,outputCount:n}=t,a=ql({...e,outputCount:n});if(Oe.webgpu.validateInputContent&&Vl(r,a),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(Hl(r,a))}}),Kl,Yl,Xl,sg=V(()=>{Ce(),Se(),Kl=t=>{if(t[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(t[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(t[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(t[0].dims[2]!==t[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Yl=t=>{let e=t[0].dims,r=t[0].dims[2],n=j.size(e)/4,a=t[0].dataType,i=G("input",a,e,4),s=G("bias",a,[r],4),o=G("residual",a,e,4),l=de("output",a,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:d=>` + const channels = ${r}u / 4; + ${d.declareVariables(i,s,o,l)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${i.getByOffset("global_idx")} + + ${s.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},Xl=t=>{Kl(t.inputs),t.compute(Yl(t.inputs))}}),Ql,Te,Zl,Jl,eu,tu,ru,nu,au,iu,su,ou,lu,uu,du,cu,na,pu,aa,hu,fu,mu,gu,_u,yu,wu,bu,vu,$u,xu,Su,Eu,Cu,Iu,ku,Ci,Tu,Ii,ki,Au,Mu,Ou,Ti=V(()=>{me(),Ce(),tt(),Se(),Ql=(t,e,r,n,a,i)=>{let s=Math.ceil(e/4),o="";typeof a=="string"?o=`${a}(a)`:o=a("a");let l=G("inputData",r,[s],4),d=de("outputData",n,[s],4);return` + ${t.registerUniform("vec_size","u32").declareVariables(l,d)} + + ${i??""} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${l.getByOffset("global_idx")}; + ${d.setByOffset("global_idx",o)} + }`},Te=(t,e,r,n,a,i=t.dataType)=>({name:e,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:s=>Ql(s,j.size(t.dims),t.dataType,i,r,n),getRunData:s=>({outputs:[{dims:t.dims,dataType:i}],dispatchGroup:{x:Math.ceil(j.size(s[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(j.size(t.dims)/4)}]})}),Zl=t=>{t.compute(Te(t.inputs[0],"Abs","abs"))},Jl=t=>{t.compute(Te(t.inputs[0],"Acos","acos"))},eu=t=>{t.compute(Te(t.inputs[0],"Acosh","acosh"))},tu=t=>{t.compute(Te(t.inputs[0],"Asin","asin"))},ru=t=>{t.compute(Te(t.inputs[0],"Asinh","asinh"))},nu=t=>{t.compute(Te(t.inputs[0],"Atan","atan"))},au=t=>{t.compute(Te(t.inputs[0],"Atanh","atanh"))},iu=t=>We(t),su=(t,e)=>{let r;switch(e.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): ${e.to}`)}t.compute(Te(t.inputs[0],"Cast",r,void 0,e.cacheKey,e.to))},ou=t=>{let e=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:yi,r=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:wi;return We({min:e,max:r})},lu=(t,e)=>{let r=t.inputs.length===1?e:ou(t.inputs),n=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"Clip",a=>`clamp(${a}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); + const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); +`,r.cacheKey),{inputs:[0]})},uu=t=>{t.compute(Te(t.inputs[0],"Ceil","ceil"))},du=t=>{t.compute(Te(t.inputs[0],"Cos","cos"))},cu=t=>{t.compute(Te(t.inputs[0],"Cosh","cosh"))},na=t=>We(t),pu=(t,e)=>{let r=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${r}(${e.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)); + }`,e.cacheKey))},aa=(t="f32")=>` +const r0: ${t} = 0.3275911; +const r1: ${t} = 0.254829592; +const r2: ${t} = -0.284496736; +const r3: ${t} = 1.421413741; +const r4: ${t} = -1.453152027; +const r5: ${t} = 1.061405429; + +fn erf_vf32(v: vec4<${t}>) -> vec4<${t}> { + 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)); +}`,hu=t=>{let e=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"Erf",r=>`erf_vf32(${r})`,aa(e)))},fu=t=>{t.compute(Te(t.inputs[0],"Exp","exp"))},mu=t=>{t.compute(Te(t.inputs[0],"Floor","floor"))},gu=t=>{let e=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,aa(e)))},_u=(t,e)=>{let r=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${e.alpha});`,e.cacheKey))},yu=t=>{t.compute(Te(t.inputs[0],"Not",e=>`!${e}`))},wu=t=>{t.compute(Te(t.inputs[0],"Neg",e=>`-${e}`))},bu=t=>{t.compute(Te(t.inputs[0],"Reciprocal",e=>`1.0/${e}`))},vu=t=>{let e=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"Relu",r=>`select(vec4<${e}>(0.0), ${r}, ${r} > vec4<${e}>(0.0))`))},$u=t=>{t.compute(Te(t.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},xu=t=>We(t),Su=(t,e)=>{let r=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${e.alpha} * ${n} + vec4<${r}>(${e.beta})))`,void 0,e.cacheKey))},Eu=t=>{t.compute(Te(t.inputs[0],"Sin","sin"))},Cu=t=>{t.compute(Te(t.inputs[0],"Sinh","sinh"))},Iu=t=>{t.compute(Te(t.inputs[0],"Sqrt","sqrt"))},ku=t=>{t.compute(Te(t.inputs[0],"Tan","tan"))},Ci=t=>`sign(${t}) * (1 - exp(-2 * abs(${t}))) / (1 + exp(-2 * abs(${t})))`,Tu=t=>{t.compute(Te(t.inputs[0],"Tanh",Ci))},Ii=(t="f32")=>` +const fast_gelu_a: ${t} = 0.5; +const fast_gelu_b: ${t} = 0.7978845608028654; +const fast_gelu_c: ${t} = 0.035677408136300125; + +fn tanh_v(v: vec4<${t}>) -> vec4<${t}> { + return ${Ci("v")}; +} +`,ki=t=>`(fast_gelu_a + fast_gelu_a * tanh_v(${t} * (fast_gelu_c * ${t} * ${t} + fast_gelu_b))) * ${t}`,Au=t=>{let e=mt(t.inputs[0].dataType);t.compute(Te(t.inputs[0],"FastGelu",ki,Ii(e),void 0,t.inputs[0].dataType))},Mu=(t,e)=>{let r=mt(t.inputs[0].dataType);return t.compute(Te(t.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${e.alpha});`,e.cacheKey)),0},Ou=t=>{t.compute(Te(t.inputs[0],"Log","log"))}}),zu,Ru,Pu,og=V(()=>{Ce(),Se(),Ti(),zu=t=>{if(t[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(t[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(t[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(t[0].dims[2]!==t[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Ru=t=>{let e=t[0].dims.slice();e[2]=e[2]/2;let r=G("input",t[0].dataType,t[0].dims,4),n=G("bias",t[0].dataType,[t[0].dims[2]],4),a=de("output",t[0].dataType,e,4),i=j.size(e)/4,s=Ze(t[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:o=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${t[0].dims[2]/4/2}u; + + ${o.declareVariables(r,n,a)} + + ${aa(s)} + + ${o.mainStart()} + ${o.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); + + ${a.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Pu=t=>{zu(t.inputs),t.compute(Ru(t.inputs))}}),Bu,Du,kt,Nu,Lu,Uu,Fu,Wu,Gu,Vu,Hu,qu,ju,lg=V(()=>{me(),Ce(),Se(),Bu=(t,e,r,n,a,i,s,o,l,d,p,u)=>{let h,m;typeof o=="string"?h=m=(w,E)=>`${o}((${w}),(${E}))`:typeof o=="function"?h=m=o:(h=o.scalar,m=o.vector);let _=de("outputData",p,n.length,4),y=G("aData",l,e.length,4),v=G("bData",d,r.length,4),x;if(a)if(i){let w=j.size(e)===1,E=j.size(r)===1,I=e.length>0&&e[e.length-1]%4===0,k=r.length>0&&r[r.length-1]%4===0;w||E?x=_.setByOffset("global_idx",m(w?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"),E?`${v.type.value}(${v.getByOffset("0")}.x)`:v.getByOffset("global_idx"))):x=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${y.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${v.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",m(s||I?y.getByOffset("offsetA / 4u"):`${y.type.value}(${y.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||k?v.getByOffset("offsetB / 4u"):`${v.type.value}(${v.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else x=_.setByOffset("global_idx",m(y.getByOffset("global_idx"),v.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let w=(E,I,k="")=>{let A=`aData[indexA${I}][componentA${I}]`,D=`bData[indexB${I}][componentB${I}]`;return` + let outputIndices${I} = ${_.offsetToIndices(`global_idx * 4u + ${I}u`)}; + let offsetA${I} = ${y.broadcastedIndicesToOffset(`outputIndices${I}`,_)}; + let offsetB${I} = ${v.broadcastedIndicesToOffset(`outputIndices${I}`,_)}; + let indexA${I} = offsetA${I} / 4u; + let indexB${I} = offsetB${I} / 4u; + let componentA${I} = offsetA${I} % 4u; + let componentB${I} = offsetB${I} % 4u; + ${E}[${I}] = ${k}(${h(A,D)}); + `};p===9?x=` + var data = vec4(0); + ${w("data",0,"u32")} + ${w("data",1,"u32")} + ${w("data",2,"u32")} + ${w("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:x=` + ${w("outputData[global_idx]",0)} + ${w("outputData[global_idx]",1)} + ${w("outputData[global_idx]",2)} + ${w("outputData[global_idx]",3)} + `}return` + ${t.registerUniform("vec_size","u32").declareVariables(y,v,_)} + + ${u??""} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${x} + }`},Du=(t,e,r,n,a,i,s=r.dataType)=>{let o=!j.areEqual(r.dims,n.dims),l=r.dims,d=j.size(r.dims),p=!1,u=!1,h=[o];if(o){let m=Cr.calcShape(r.dims,n.dims,!1);if(!m)throw new Error("Can't perform binary op on the given tensors");l=m,d=j.size(l);let _=j.size(r.dims)===1,y=j.size(n.dims)===1,v=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,x=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;h.push(_),h.push(y),h.push(v),h.push(x);let w=1;for(let E=1;Em.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:m=>Bu(m,r.dims,n.dims,l,p,o,u,a,r.dataType,n.dataType,s,i),getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(j.size(l)/4)},...ce(r.dims,n.dims,l)]})}},kt=(t,e,r,n,a,i)=>{t.compute(Du(e,a??"",t.inputs[0],t.inputs[1],r,n,i))},Nu=t=>{kt(t,"Add",(e,r)=>`${e}+${r}`)},Lu=t=>{kt(t,"Div",(e,r)=>`${e}/${r}`)},Uu=t=>{kt(t,"Equal",{scalar:(e,r)=>`u32(${e}==${r})`,vector:(e,r)=>`vec4(${e}==${r})`},void 0,void 0,9)},Fu=t=>{kt(t,"Mul",(e,r)=>`${e}*${r}`)},Wu=t=>{let e=G("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;kt(t,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` + fn pow_custom(a : ${e}, b : ${e}) -> ${e} { + if (b == ${e}(0.0)) { + return ${e}(1.0); + } else if (a < ${e}(0.0) && f32(b) != floor(f32(b))) { + return ${e}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${e}(1.0), round(f32(abs(b) % ${e}(2.0))) != 1.0) * ${e}(${e==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${e}>, b : vec4<${e}>) -> vec4<${e}> { + // TODO: implement vectorized pow + return vec4<${e}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Gu=t=>{kt(t,"Sub",(e,r)=>`${e}-${r}`)},Vu=t=>{kt(t,"Greater",{scalar:(e,r)=>`u32(${e}>${r})`,vector:(e,r)=>`vec4(${e}>${r})`},void 0,void 0,9)},Hu=t=>{kt(t,"Less",{scalar:(e,r)=>`u32(${e}<${r})`,vector:(e,r)=>`vec4(${e}<${r})`},void 0,void 0,9)},qu=t=>{kt(t,"GreaterOrEqual",{scalar:(e,r)=>`u32(${e}>=${r})`,vector:(e,r)=>`vec4(${e}>=${r})`},void 0,void 0,9)},ju=t=>{kt(t,"LessOrEqual",{scalar:(e,r)=>`u32(${e}<=${r})`,vector:(e,r)=>`vec4(${e}<=${r})`},void 0,void 0,9)}}),Ku,Yu,Xu,Qu,Zu,Ju,ug=V(()=>{me(),Ce(),tt(),Se(),Ku=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");let r=0,n=t[r],a=n.dataType,i=n.dims.length;t.forEach((s,o)=>{if(o!==r){if(s.dataType!==a)throw new Error("input tensors should be one type");if(s.dims.length!==i)throw new Error("input tensors should have the same shape");s.dims.forEach((l,d)=>{if(d!==e&&l!==n.dims[d])throw new Error("non concat dimensions must match")})}})},Yu=(t,e)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${e}); + for (var i: u32 = 0u; i < ${t}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${t}u; + }`,Xu=(t,e)=>{let r=t.length,n=[];for(let a=0;a{let a=j.size(r),i=new Array(t.length),s=new Array(t.length),o=0,l=[],d=[],p=[{type:12,data:a}];for(let y=0;y`uniforms.sizeInConcatAxis${y}`).join(","),_=y=>` + + ${(()=>{y.registerUniform("outputSize","u32");for(let v=0;v(${m}); + ${h} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Xu(s,u)} + }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:_}},Zu=(t,e)=>{let r=t.inputs,n=r[0].dims,a=j.normalizeAxis(e.axis,n.length);Ku(r,a);let i=n.slice();i[a]=r.reduce((o,l)=>o+(l.dims.length>a?l.dims[a]:0),0);let s=r.filter(o=>j.size(o.dims)>0);t.compute(Qu(s,a,i,r[0].dataType),{inputs:s})},Ju=t=>We({axis:t.axis})}),sr,or,lr,Ai,ur=V(()=>{me(),Ce(),sr=(t,e,r="f32")=>{switch(t.activation){case"Relu":return`value = max(value, ${e}(0.0));`;case"Sigmoid":return`value = (${e}(1.0) / (${e}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${e}(${r}(uniforms.clip_min)), ${e}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${e}(0.0), min(${e}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${e}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${t.activation}`)}},or=(t,e)=>{t.activation==="Clip"?e.push({type:1,data:t.clipMax},{type:1,data:t.clipMin}):t.activation==="HardSigmoid"?e.push({type:1,data:t.alpha},{type:1,data:t.beta}):t.activation==="LeakyRelu"&&e.push({type:1,data:t.alpha})},lr=(t,e)=>{t.activation==="Clip"?e.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):t.activation==="HardSigmoid"?e.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):t.activation==="LeakyRelu"&&e.push({name:"alpha",type:"f32"})},Ai=t=>{let e=t?.activation||"";if(e==="HardSigmoid"){let[r,n]=t?.activation_params||[.2,.5];return{activation:e,alpha:r,beta:n}}else if(e==="Clip"){let[r,n]=t?.activation_params||[yi,wi];return{activation:e,clipMax:n,clipMin:r}}else if(e==="LeakyRelu"){let[r]=t?.activation_params||[.01];return{activation:e,alpha:r}}return{activation:e}}}),ot,Mi,Oi=V(()=>{ot=(t,e)=>{switch(t){case 1:return e;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${t}-component is not supported.`)}},Mi=t=>` + ${t?"value = value + getBiasByOutputCoords(coords);":""} + `}),zi,ed=V(()=>{zi=t=>` +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(${t}.x), i32(${t}.y), i32(${t}.z), 1)); +} +`}),td,rd,ia,Ri,nd,sa,ad,Pi,oa=V(()=>{me(),Ce(),Se(),ur(),Oi(),td=(t,e)=>t?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${e?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${e?", batchIndices":""}); + `,rd=(t,e)=>t?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${e===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]; + ${e===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]; + ${e===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,ia=(t,e,r="f32",n,a=!1,i=32,s=!1,o=32)=>{let l=e[1]*t[1],d=e[0]*t[0],p=a?l:i,u=a?i:l,h=p/e[0],m=i/e[1];if(!((a&&h===4&&t[1]===4||!a&&(h===3||h===4))&&p%e[0]===0&&i%e[1]===0&&t[0]===4))throw new Error(`If transposeA ${a} is true, innerElementSize ${h} and workPerThread[1] ${t[1]} must be 4. + Otherwise, innerElementSize ${h} must be 3 or 4. + tileAWidth ${p} must be divisible by workgroupSize[0]${e[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${t[0]} must be 4.`);return` +var mm_Asub: array, ${p/h}>, ${u}>; +var mm_Bsub: array, ${d/t[0]}>, ${i}>; + +const rowPerThread = ${t[1]}; +const colPerThread = ${t[0]}; +const innerElementSize = ${h}; +const tileInner = ${i}; + +@compute @workgroup_size(${e[0]}, ${e[1]}, ${e[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 = ${s?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${s?`${Math.ceil(o/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${s?`i32(globalId.z) * ${o}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${m}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${td(a,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${m}; 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]; + ${h===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${rd(a,h)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Ri=(t,e)=>t?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${e?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${e?", batchIndices":""}); + `,nd=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",sa=(t,e,r="f32",n,a=!1,i=32,s=!1,o=32,l=!1)=>{let d=t[1]*e[1],p=t[0]*e[0],u=a?d:i,h=a?i:d;if(!(h%e[1]===0&&u%e[0]===0&&i%e[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${e[0]}, tileInner ${i} must be divisible by workgroupSize[1]${e[1]}`);let m=h/e[1],_=u/e[0],y=i/e[1],v=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${d}; + 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 < ${h}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${e[0]}) { + ${Ri(a,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${e[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 * ${e[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${a?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[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 * ${e[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${e[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) * ${d}; + +let tileRowA = i32(localId.y) * ${m}; +let tileColA = i32(localId.x) * ${_}; +let tileRowB = i32(localId.y) * ${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 < ${m}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Ri(a,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${y}; 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) { + ${nd(a)} + 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, ${h}>; + var mm_Bsub : array, ${i}>; + const rowPerThread = ${t[1]}; + const colPerThread = ${t[0]}; + const tileInner = ${i}; + +@compute @workgroup_size(${e[0]}, ${e[1]}, ${e[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${s?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${s?`${Math.ceil(o/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${s?`i32(globalId.z) * ${o}`:"0"}; + + var acc : array, rowPerThread>; + + // Without this initialization strange values show up in acc. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = 0.0; + } + } + ${v} + } +`},ad=(t,e,r,n,a,i=!1)=>{let[s,o,l]=a,[d,p,u,h]=n,m=jr(s,l),_=jr(o,l),y=Ze(n[0].type.tensor),v=()=>{let w=p.rank,E=d.rank,I=`var aIndices: ${p.type.indices};`;for(let k=w-2-1,A=E-1;k>=0;k--,A--)I+=` +aIndices[${k}] = ${E>1?`batchIndices[${A}]`:"batchIndices"};`;return m.forEach(k=>{I+=` +aIndices[${k}] = 0;`}),I+=` +aIndices[${w-2}] = u32(row); + aIndices[${w-1}] = u32(colIn);`,I},x=()=>{let w=u.rank,E=d.rank,I=`var bIndices: ${u.type.indices};`;for(let k=w-2-1,A=E-1;k>=0;k--,A--)I+=` +bIndices[${k}] = ${E>1?`batchIndices[${A}]`:"batchIndices"};`;return _.forEach(k=>{I+=` +bIndices[${k}] = 0;`}),I+=` +bIndices[${w-2}] = u32(row); + bIndices[${w-1}] = u32(colIn);`,I};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${ot(t,y)} { + var value = ${ot(t,y)}(0.0); + let col = colIn * ${t}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${v()} + value = ${p.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${ot(t,y)} { + var value = ${ot(t,y)}(0.0); + let col = colIn * ${t}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${x()} + value = ${u.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ot(t,y)}) { + let col = colIn * ${t}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${e?`value = value + ${i?"bias[colIn]":`${ot(t,y)}(bias[row])`};`:""} + ${r} + ${h.setByIndices("vec3(coords)","value")} + } + } + `},Pi=(t,e,r,n,a=!1)=>{let i=t[0].dims,s=t[1].dims,o=i.slice(0,-2),l=s.slice(0,-2),d=n?n.slice(0,-2):r.slice(0,-2),p=j.size(d),u=i[i.length-2],h=i[i.length-1],m=s[s.length-1],_=h%4===0&&m%4===0,y=u<=8?[4,1,1]:[4,4,1],v=[8,8,1],x=[Math.ceil(m/v[0]/y[0]),Math.ceil(u/v[1]/y[1]),Math.ceil(p/v[2]/y[2])],w=_?4:1,E=[...o,u,h/w],I=E.length,k=[...l,h,m/w],A=k.length,D=[p,u,m/w],L=[{type:6,data:u},{type:6,data:m},{type:6,data:h}];or(e,L),L.push(...ce(d,E,k));let Y=["rank","rank"],H=t.length>2;H&&(L.push(...ce(t[2].dims)),Y.push("rank")),L.push(...ce(D));let re=N=>{let ee=d.length,oe=bi("batchDims",t[0].dataType,ee,1),Ae=Ze(t[0].dataType),q=G("a",t[0].dataType,I,w),J=G("b",t[1].dataType,A,w),ae=de("result",t[0].dataType,D.length,w),W=[q,J];if(H){let ze=a?w:1;W.push(G("bias",t[2].dataType,t[2].dims.length,ze))}let te=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];lr(e,te);let B=Ze(ae.type.tensor),Q=sr(e,ae.type.value,B),he=ad(w,H,Q,[oe,q,J,ae],[o,l,d],a);return` + ${N.registerUniforms(te).registerInternalVariables(oe).declareVariables(...W,ae)} + ${he} + ${_?ia(y,v,Ae,oe):sa(y,v,Ae,oe)} + `};return{name:"MatMul",shaderCache:{hint:`${y};${e.activation};${_};${a}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:x[0],y:x[1],z:x[2]},programUniforms:L}),getShaderSource:re}}}),id,sd,dg=V(()=>{me(),ir(),Se(),ur(),Oi(),ed(),oa(),id=(t,e,r,n,a=!1,i,s=4,o=4,l=4,d="f32")=>{let p=Y=>{switch(Y){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${d}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Y} is not supported.`)}},u=Y=>{switch(Y){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 ${Y} is not supported.`)}},h=t?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,m=t?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,_=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",y=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",v=t?"row":"col",x=t?"col":"row",w=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${v} / outWidth; + let outCol = ${v} % outWidth; + + let WRow = ${x} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${x} / 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 = ${x} % inChannels; + var resData = ${ot(s,d)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${y}) { + ${h} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(s)} + } + return resData;`,E=t?e&&n?` + let col = colIn * ${s}; + ${w}`:` + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${w} + } + return ${ot(s,d)}(0.0);`:n&&r?` + let col = colIn * ${s}; + ${w}`:` + let col = colIn * ${s}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${w} + } + return ${ot(s,d)}(0.0);`,I=`${u(o)}`,k=ot(l,d),A=ot(t?s:o,d),D=ot(t?o:s,d),L=sr(i,k,d);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} { + ${t?E:I} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${D} { + ${t?I:E} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${k}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${m} + ${Mi(a)} + ${L} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},sd=(t,e,r,n,a,i,s,o)=>{let l=e.format==="NHWC",d=l?t[0].dims[3]:t[0].dims[1],p=r[0],u=l?r[2]:r[3],h=l?r[1]:r[2],m=l?r[3]:r[1],_=l&&(d%4===0||d%3===0)&&m%4===0,y=l?m:u*h,v=l?u*h:m,x=[8,8,1],w=n<=8?[4,1,1]:[4,4,1],E=[Math.ceil(y/x[0]/w[0]),Math.ceil(v/x[1]/w[1]),Math.ceil(p/x[2]/w[2])];Ke("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let I=_?l&&d%4!==0?3:4:1,k=x[1]*w[1],A=x[0]*w[0],D=Math.max(x[0]*I,x[1]),L=n%k===0,Y=a%A===0,H=i%D===0,re=_?[I,4,4]:[1,1,1],N=[{type:6,data:n},{type:6,data:a},{type:6,data:i},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];or(e,N),N.push(...ce(t[0].dims,t[1].dims));let ee=["rank","rank"];s&&(N.push(...ce(t[2].dims)),ee.push("rank")),N.push(...ce(r));let oe=Ae=>{let q=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];lr(e,q);let J=_?4:1,ae=Ze(t[0].dataType),W=` + fn setOutputAtIndex(flatIndex : i32, value : ${_?`vec4<${ae}>`:ae}) { + result[flatIndex] = ${_?`vec4<${ae}>`:ae}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${_?`vec4<${ae}>`:ae}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${_?"/ 4":""}, value); + }`,te=G("x",t[0].dataType,t[0].dims.length,I===3?1:I),B=G("w",t[1].dataType,t[1].dims.length,J),Q=[te,B],he=de("result",t[0].dataType,r.length,J);if(s){let ze=G("bias",t[2].dataType,t[2].dims.length,J);Q.push(ze),W+=` + fn getBiasByOutputCoords(coords : vec4) -> ${_?`vec4<${ae}>`:ae} { + return bias[coords.${l?"w":"y"}${_?"/ 4":""}]; + }`}return` + ${zi("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 }; + ${Ae.registerUniforms(q).declareVariables(...Q,he)} + ${W} + ${id(l,L,Y,H,s,e,re[0],re[1],re[2],ae)} + ${_?ia(w,x,ae,void 0,!l,D):sa(w,x,ae,void 0,!l,D,!1,void 0,o)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${I};${_};${L};${Y};${H};${k};${A};${D}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:N}),getShaderSource:oe}}}),Bi,od,cg=V(()=>{me(),Ce(),Se(),fd(),ur(),Bi=(t,e,r)=>{let n=t.length>2,a=n?"value += b[output_channel];":"",i=t[0].dims,s=t[1].dims,o=s[0]/e.group,l=e.format==="NHWC",d=la(i,s,e.dilations,e.pads,e.strides,l),p=j.size(d),u=[{type:12,data:p},{type:12,data:e.dilations},{type:12,data:[e.strides[0],e.strides[1]]},{type:12,data:[e.pads[0],e.pads[1]]},{type:12,data:o}];or(e,u),u.push(...ce(i,s,d));let h=["rank","rank"];n&&(u.push(...ce(t[2].dims)),h.push("rank")),u.push(...ce(d));let m=_=>{let y=de("output",t[0].dataType,d.length),v=Ze(y.type.tensor),x=sr(e,y.type.value,v),w=G("x",t[0].dataType,i.length),E=G("w",t[1].dataType,s.length),I=[w,E];n&&I.push(G("b",t[2].dataType,t[2].dims));let k=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:e.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return lr(e,k),` + ${_.registerUniforms(k).declareVariables(...I,y)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${y.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${l?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${y.type.value} = ${y.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = group_id * uniforms.w_shape[1] + 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[${l?1: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[${l?2:3}]) { + continue; + } + + let xVal = ${l?w.get("batch","xHeight","xWidth","input_channel"):w.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${E.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${a} + ${x} + ${y.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:e.cacheKey,inputDependencies:h},getRunData:()=>({outputs:[{dims:r?r(d):d,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:u}),getShaderSource:m}},od=(t,e,r)=>{let n=t.length>2,a=Qe(r[3]),i=Qe(r[2]),s=j.size(r)/a/i,o=[t[0].dims[0],t[0].dims[1],t[0].dims[2],t[0].dims[3]/a],l=[t[1].dims[0],t[1].dims[1],t[1].dims[2],t[1].dims[3]/a],d=[r[0],r[1],r[2],r[3]/a],p=[{type:12,data:s},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];or(e,p),p.push(...ce(o,l,d));let u=(i-1)*e.strides[1]+l[1],h=m=>{let _=de("output",t[0].dataType,d.length,a),y=Ze(_.type.tensor),v=sr(e,_.type.value,y),x=G("x",t[0].dataType,o.length,a),w=G("w",t[1].dataType,l.length,a),E=[x,w];n&&E.push(G("b",t[2].dataType,t[2].dims,a));let I=n?"value += b[output_channel];":"",k=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return lr(e,k),` + ${m.registerUniforms(k).declareVariables(...E,_)} + ${m.mainStart()} + ${m.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] / ${i}u; + let col = (index1 % width1) * ${i}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<${x.type.value}, ${u}>; + var values: array<${_.type.value}, ${i}>; + 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 < ${l[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 < ${u}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${x.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${x.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) { + let w_val = ${w.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${I} + ${v} + ${_.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${a};${i};${u};${l[0]};${l[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:p}),getShaderSource:h}}}),Di,ld,ud,dd=V(()=>{me(),Ce(),oa(),Se(),ur(),Di=(t,e,r,n,a=!1)=>{let i=t[0].dims,s=t[1].dims,o=i[i.length-2],l=s[s.length-1],d=i[i.length-1],p=Qe(l),u=Qe(d),h=Qe(o),m=j.size(r)/p/h,_=t.length>2,y=n?n.slice(0,-2):r.slice(0,-2),v=[j.size(y),o,l],x=[{type:12,data:m},{type:12,data:o},{type:12,data:l},{type:12,data:d}];or(e,x),x.push(...ce(y,i,s)),_&&x.push(...ce(t[2].dims)),x.push(...ce(v));let w=E=>{let I=bi("batch_dims",t[0].dataType,y.length),k=G("a",t[0].dataType,i.length,u),A=G("b",t[1].dataType,s.length,p),D=de("output",t[0].dataType,v.length,p),L=Ze(D.type.tensor),Y=sr(e,D.type.value,L),H=[k,A],re="";if(_){let W=a?p:1;H.push(G("bias",t[2].dataType,t[2].dims.length,W)),re=`${a?`value += bias[col / ${W}];`:`value += ${D.type.value}(bias[row + i]);`}`}let N=i.slice(0,-2),ee=s.slice(0,-2),oe=jr(N,y),Ae=jr(ee,y),q=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];lr(e,q);let J=(W,te)=>{let B=W.rank,Q=W.name;if(B===2)return`var ${Q}_indices = ${W.type.indices}(0u, 0u);`;let he=I.rank,ze=`var ${Q}_indices: ${W.type.indices};`;for(let Re=B-2-1,Je=he-1;Re>=0;Re--,Je--)ze+=` +${Q}_indices[${Re}] = ${he>1?`batch_indices[${Je}]`:"batch_indices"};`;return te.forEach(Re=>{ze+=` +${Q}_indices[${Re}] = 0;`}),ze+=`${Q}_indices[${B-2}] = 0u; + ${Q}_indices[${B-1}] = 0u;`,ze},ae=()=>{let W=`var a_data: ${k.type.value};`;for(let te=0;te; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { + ${ae()} + } + for (var i = 0u; i < ${h}u; i++) { + var value = values[i]; + ${re} + ${Y} + let cur_indices = ${D.type.indices}(batch, row + i, col); + let offset = ${D.indicesToOffset("cur_indices")}; + ${D.setByOffset(`offset / ${p}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${p};${u};${h};${a}`,inputDependencies:_?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:x}),getShaderSource:w}},ld=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.")},ud=t=>{ld(t.inputs);let e=Cr.calcShape(t.inputs[0].dims,t.inputs[1].dims,!0);if(!e)throw new Error("Can't use matmul on the given tensors");let r=e[e.length-1],n=t.inputs[0].dims[t.inputs[0].dims.length-1];r<8&&n<8?t.compute(Di(t.inputs,{activation:""},e)):t.compute(Pi(t.inputs,{activation:""},e))}}),la,ua,cd,Ni,Li,pd,hd,Ui,fd=V(()=>{Ce(),dg(),oa(),cg(),ur(),dd(),Kr(),la=(t,e,r,n,a,i)=>{let s=t[0],o=t.slice(i?1:2,i?3:4),l=o.length,d=e[0],p=e.slice(2).map((h,m)=>h+(h-1)*(r[m]-1)),u=o.map((h,m)=>h+n[m]+n[m+l]).map((h,m)=>Math.floor((h-p[m]+a[m])/a[m]));return u.splice(0,0,s),u.splice(i?3:1,0,d),u},ua=[2,3,1,0],cd=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4&&t[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let r=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],n=t[1].dims[1]*e.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(t.length===3&&(t[2].dims.length!==1||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");let a=t[0].dims.length-2;if(e.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(e.strides.length!==a)throw new Error(`strides should be ${a}D`);if(e.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape")},Ni=(t,e)=>{let r=t.kernelShape.slice();for(let i=2;i{let e=Ai(t),r=t.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],a=t.dilations,i=t.group,s=t.kernel_shape,o=t.pads,l=t.strides,d=t.w_is_const();return{autoPad:n,format:r,dilations:a,group:i,kernelShape:s,pads:o,strides:l,wIsConst:d,...e,cacheKey:`${t.format};${e.activation};`}},pd=(t,e,r)=>{let n=Ni(r,e),a=r.format==="NHWC";if(r.group!==1){if(!t.adapterInfo.isArchitecture("ampere")&&a&&e[1].dims[0]===r.group&&e[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let A=la(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),D=t.kernelCustomData.wT??t.compute(Lt(e[1],ua),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=D);let L=[e[0],D];e.length===3&&L.push(e[2]),t.compute(od(L,n,A),{inputs:L})}else t.compute(Bi(e,n));return}let i=e.length===3,s=e[0].dims[a?1:2],o=e[0].dims[a?2:3],l=e[0].dims[a?3:1],d=e[1].dims[2],p=e[1].dims[3],u=la(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),h=u[a?1:2],m=u[a?2:3],_=u[a?3:1],y=a&&d===s&&p===o&&r.pads[0]===0&&r.pads[1]===0;if(y||d===1&&p===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 A=u[0],D,L,Y,H=[];if(a){let ee=t.kernelCustomData.wT??t.compute(Lt(e[1],ua),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=ee),y){let oe=s*o*l;D=e[0].reshape([1,A,oe]),L=ee.reshape([1,oe,_]),Y=[1,A,_]}else D=e[0].reshape([A,s*o,l]),L=ee.reshape([1,l,_]),Y=[A,h*m,_];H.push(D),H.push(L)}else D=e[0].reshape([A,l,s*o]),L=e[1].reshape([1,_,l]),Y=[A,_,h*m],H.push(L),H.push(D);i&&H.push(e[2]);let re=Y[2],N=H[0].dims[H[0].dims.length-1];re<8&&N<8?t.compute(Di(H,n,u,Y,a),{inputs:H}):t.compute(Pi(H,n,u,Y,a),{inputs:H});return}let v=!0,x=t.kernelCustomData.wT??t.compute(Lt(e[1],ua),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=x);let w=[e[0],x];i&&w.push(e[2]);let E=a?h*m:_,I=a?_:h*m,k=d*p*l;t.compute(sd(w,n,u,E,I,k,i,v),{inputs:w})},hd=(t,e)=>{let r=e.format==="NHWC",n=[t.inputs[0].reshape(r?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];t.inputs.length===3&&n.push(t.inputs[2]);let a=[0,e.pads[0],0,e.pads[1]],i=[1].concat(e.strides),s=[1].concat(e.dilations),o=[1].concat(e.kernelShape),l=Ni({...e,pads:a,strides:i,dilations:s,kernelShape:o},n);t.compute(Bi(n,l,d=>r?[d[0],d[2],d[3]]:[]))},Ui=(t,e)=>{cd(t.inputs,e),t.inputs[0].dims.length===3?hd(t,e):pd(t,t.inputs,e)}}),md,gd,pg=V(()=>{me(),ir(),Se(),ur(),Oi(),ed(),oa(),md=(t,e=!1,r,n,a=4)=>{let i=v=>{switch(v){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` + let coord1 = vec4(coordX, coordY, col + 1, rowInner); + let coord2 = vec4(coordX, coordY, col + 2, rowInner); + let coord3 = vec4(coordX, coordY, col + 3, rowInner); + let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; + let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; + let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; + let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; + return ${n}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${v} is not supported.`)}},s=t?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,o=t?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,l=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",d=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",p=t?"row":"col",u=t?"col":"row",h=` + let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${p} / outWidth; + let outCol = ${p} % outWidth; + + let WRow = ${u} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${u} / inChannels % uniforms.filter_dims[1]; + let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(${l}) || fract(xR) > 0.0) { + return ${n}(0.0); + } + if (xC < 0.0 || xC >= f32(${d}) || fract(xC) > 0.0) { + return ${n}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${u} % inChannels; + ${s} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${a}];`,m=t?` + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${h} + } + return ${n}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${h} + } + return ${n}(0.0);`,_=` + let col = colIn * ${a}; + let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); + let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; + if (${t?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4(coordX, coordY, col, rowInner); + ${i(a)} + } + return ${n}(0.0); + `,y=sr(r,n);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { + ${t?m:_} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { + ${t?_:m} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${o} + ${Mi(e)} + ${y} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${a}] = value; + } + }`},gd=(t,e,r,n,a,i,s,o)=>{let l=e.format==="NHWC",d=l?t[0].dims[3]:t[0].dims[1],p=r[0],u=l?r[2]:r[3],h=l?r[1]:r[2],m=l?r[3]:r[1],_=l?d%4===0&&m%4===0:u%4===0&&m%4===0,y=l?m:u*h,v=l?u*h:m,x=_?[8,8,1]:[y<=4||v<=4?4:16,y>4&&v<=4?4:16,1],w=_?[4,4,1]:[y<=4?1:4,y>4&&v<=4?1:4,1],E=[Math.ceil(y/x[0]/w[0]),Math.ceil(v/x[1]/w[1]),Math.ceil(p/x[2]/w[2])];Ke("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let I=_?4:1,k=Math.max(x[0]*I,x[1]),A=_?4:1,D=[e.kernelShape[l?1:2],e.kernelShape[l?2:3]],L=[D[0]+(e.dilations[0]<=1?0:(D[0]-1)*(e.dilations[0]-1)),D[1]+(e.dilations[1]<=1?0:(D[1]-1)*(e.dilations[1]-1))],Y=[L[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),L[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],H=[{type:6,data:n},{type:6,data:a},{type:6,data:i},{type:6,data:e.strides},{type:6,data:e.dilations},{type:6,data:D},{type:6,data:Y}];or(e,H),H.push(...ce(t[0].dims,t[1].dims));let re=["rank","rank"];s&&(H.push(...ce(t[2].dims)),re.push("rank")),H.push(...ce(r));let N=ee=>{let oe=G("x",t[0].dataType,t[0].dims.length,A),Ae=G("w",t[1].dataType,t[1].dims.length,1),q=de("result",t[0].dataType,r.length,A),J=[oe,Ae],ae="";if(s){let B=G("bias",t[2].dataType,t[2].dims.length,A);J.push(B),ae+=` + fn getBiasByOutputCoords(coords : vec4) -> ${B.type.value} { + return bias[coords.${l?"w":"y"}${_?"/ 4":""}]; + }`}let W=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:D.length},{name:"pads",type:"i32",length:Y.length}];lr(e,W);let te=Ze(t[0].dataType,1);if(te!=="f16"&&te!=="f32")throw new Error(`elemType ${te} is not supported.`);return` + ${zi("uniforms.result_strides")} + ${ee.registerUniforms(W).declareVariables(...J,q)}; + ${ae} + ${md(l,s,e,oe.type.value,I)} + ${_?ia(w,x,te,void 0,!l,k):sa(w,x,te,void 0,!l,k,!1,void 0,o)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${e.cacheKey};${w};${x};${_}`,inputDependencies:re},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:H}),getShaderSource:N}}}),_d,Fi,hg=V(()=>{me(),ir(),Ce(),Se(),_d=(t,e,r,n,a,i=!1,s,o,l=!1)=>{let d=l?1:2,p=l?2:3,u=l?3:1,h=i?2:1,m=` + fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${s}>`:s}) { + result[flatIndex] = ${i?`vec4<${s}>`:s}(value); + }`;n&&(m+=` + fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${s}>`:s} { + return bias[coords.${l?"w":"y"}${i?"/ 4":""}]; + }`);let _=i?4:1,y=G("W",e[1].dataType,e[1].dims.length,_),v=G("Dy",e[0].dataType,e[0].dims.length,_),x=[v,y];n&&x.push(G("bias",e[2].dataType,[r[u]].length,_));let w=de("result",e[0].dataType,r.length,_),E=`{ + let batch: u32 = ${a?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${a?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${a?"global_id.y":"workgroup_id.y"} * ${h}; + let d1: u32 = ${a?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${h}>; + for (var i = 0; i < ${h}; i++) { + dotProd[i] = vec4<${s}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${s}(dyCorner.x) + ${s}(wR)) / ${s}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { + let dyC = (${s}(dyCorner.y) + ${s}(wC)) / ${s}(uniforms.strides.y); + let dyC2 = (${s}(dyCorner.y) + 1.0 + ${s}(wC)) / ${s}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${s}(uniforms.Dy_shape[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${v.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${s}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${v.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${s}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${u}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${v.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${s}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${y.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${v.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${s}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${h}; i = i + 1) { + let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${s}>(0.0)`}; + ${w.set("batch","r","c + i","d1","value")}; + } + }`,I=` + let outputIndices = ${w.offsetToIndices("global_idx")}; + let batch = ${w.indicesGet("outputIndices",0)}; + let d1 = ${w.indicesGet("outputIndices",u)}; + let r = ${w.indicesGet("outputIndices",d)}; + let c = ${w.indicesGet("outputIndices",p)}; + 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 = ${s}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${d}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${p}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { + let xValue = ${l?v.get("batch","idyR","idyC","inputChannel"):v.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${y.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${n?"bias[d1]":`${s}(0.0)`}; + ${w.setByOffset("global_idx","value")}; + `;return` + ${t.registerUniforms(o).declareVariables(...x,w)} + ${m} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${i?E:I}}`},Fi=(t,e,r)=>{let n=t.length>2,a=e.outputShape,i=j.size(a),s=[Math.ceil(i/64),1,1];Ke("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let o=e.format==="NHWC",l=["rank","rank"],d=[e.strides[0],e.strides[1]],p=[e.kernelShape[o?1:2],e.kernelShape[o?2:3]],u=[e.dilations[0],e.dilations[1]],h=[p[0]+(e.dilations[0]<=1?0:(e.kernelShape[o?1:2]-1)*(e.dilations[0]-1)),p[1]+(e.dilations[1]<=1?0:(e.kernelShape[o?2:3]-1)*(e.dilations[1]-1))],m=[h[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),h[1]-1-Math.floor(e.pads[1]+e.pads[3])/2],_=!1,y=e.group,v=t[1].dims,x=v[0]/y,w=v[1],E=[{type:6,data:i},{type:12,data:d},{type:12,data:p},{type:12,data:u},{type:12,data:h},{type:6,data:m},{type:12,data:x},{type:12,data:w},...ce(t[0].dims,t[1].dims)];n&&(E.push(...ce(t[2].dims)),l.push("rank")),E.push(...ce(a));let I=s[1]===1&&s[2]===1,k=A=>{let D=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:d.length},{name:"filter_dims",type:"u32",length:p.length},{name:"dilations",type:"u32",length:p.length},{name:"effective_filter_dims",type:"u32",length:h.length},{name:"pads",type:"i32",length:m.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],L=Ze(t[0].dataType);return`${_d(A,t,a,n,I,_,L,D,o)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:r?r(a):a,dataType:t[0].dataType}],programUniforms:E}),getShaderSource:k}}}),yd,wd,bd,Wi,vd,$d,xd,Sd,Ed,Cd,fg=V(()=>{pg(),hg(),ur(),Kr(),yd=(t,e,r,n,a,i)=>(t-1)*e+r+(n-1)*a+1-i,wd=(t,e,r,n,a)=>{let i=Math.floor(t/2);e==="SAME_UPPER"?(r[n]=i,r[a]=t-i):e==="SAME_LOWER"&&(r[n]=t-i,r[a]=i)},bd=(t,e,r,n,a,i,s,o,l,d)=>{let p=t.length-2,u=d.length===0;if(l.length===0)for(let _=0;_{let r=t.kernelShape.slice();if(t.kernelShape.length===0||t.kernelShape.reduce((u,h)=>u*h,1)===0){r.length=0;for(let u=2;uu+h,0)===0){let u=e[0].dims.length-2;l=new Array(u).fill(1)}let d=t.strides.slice();if(d.reduce((u,h)=>u+h,0)===0){let u=e[0].dims.length-2;d=new Array(u).fill(1)}bd(o,r,l,t.autoPad,t.group,a,d,n,s,i);let p=Object.assign({},t);return Object.assign(p,{kernelShape:r,pads:a,outputPadding:s,outputShape:i,dilations:l,strides:d}),p},vd=t=>{let e=Ai(t),r=t.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof t.autoPad>"u"?0:t.autoPad],a=t.dilations,i=t.group,s=t.kernelShape,o=t.pads,l=t.strides,d=t.wIsConst(),p=t.outputPadding,u=t.outputShape;return{autoPad:n,format:r,dilations:a,group:i,kernelShape:s,outputPadding:p,outputShape:u,pads:o,strides:l,wIsConst:d,...e,cacheKey:`${t.format};${e.activation};`}},$d=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4&&t[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let r=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],n=t[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let a=t[1].dims[1]*e.group;if(t.length===3&&(t[2].dims.length!==1||t[2].dims[0]!==a))throw new Error("invalid bias");let i=t[0].dims.length-2;if(e.dilations.reduce((s,o)=>s+o,0)>0&&e.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(e.strides.reduce((s,o)=>s+o,0)>0&&e.strides.length!==i)throw new Error(`strides should be ${i}D`);if(e.pads.reduce((s,o)=>s+o,0)>0&&e.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(e.outputPadding.length!==i&&e.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(e.kernelShape.reduce((s,o)=>s+o,0)>0&&e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(e.outputShape.length!==0&&e.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape")},xd=[2,3,1,0],Sd=(t,e,r)=>{let n=Wi(r,e),a=r.format==="NHWC",i=n.outputShape,s=i[a?3:1],o=e[0].dims[a?3:1];if(n.group!==1||s===1&&o===1){t.compute(Fi(e,n));return}let l=i[a?1:2],d=i[a?2:3],p=e[1].dims[2],u=e[1].dims[3],h=a?l*d:s,m=a?s:l*d,_=p*u*o,y=!0,v=t.kernelCustomData.wT??t.compute(Lt(e[1],xd),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=v);let x=[e[0],v],w=e.length===3;w&&(!a&&e[2].dims.length===1?x.push(e[2].reshape([e[2].dims[0],1,1])):x.push(e[2])),t.compute(gd(x,n,i,h,m,_,w,y),{inputs:x})},Ed=(t,e)=>{let r=e.format==="NHWC",n=[t.inputs[0].reshape(r?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];n.length===3&&n.push(t.inputs[2]);let a=e.kernelShape;(a.length===0||a[0]===0)&&(a=[t.inputs[1].dims[2]]);let i=e.dilations;(i.length===0||i[0]===0)&&(i=[1]);let s=e.strides;(s.length===0||s[0]===0)&&(s=[1]);let o=e.pads;o.length===0&&(o=[0,0]),o=[0,o[0],0,o[1]],s=[1].concat(s),i=[1].concat(i),a=[1].concat(a);let l=Wi({...e,pads:o,strides:s,dilations:i,kernelShape:a},n);t.compute(Fi(n,l,d=>r?[d[0],d[2],d[3]]:[d[0],d[1],d[3]]))},Cd=(t,e)=>{$d(t.inputs,e),t.inputs[0].dims.length===3?Ed(t,e):Sd(t,t.inputs,e)}}),Id,kd,Td,mg=V(()=>{me(),Ce(),tt(),Se(),Id=(t,e,r,n)=>{let a=j.size(e),i=e.length,s=G("input",t,i),o=de("output",t,i),l=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),d=j.normalizeAxis(l,i),p=u=>{let h=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,m=ge("uniforms.input_shape","uniforms.axis",i),_=n.reverse?h+(n.exclusive?" + 1":""):"0",y=n.reverse?m:h+(n.exclusive?"":" + 1");return` + ${u.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,o)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${o.offsetToIndices("global_idx")}; + var sum = ${o.type.value}(0); + let first : i32 = ${_}; + let last : i32 = ${y}; + for (var i : i32 = first; i < last; i++) { + ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${s.getByIndices("inputIndices")}; + } + ${o.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:e,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},{type:6,data:d},...ce(e,e)]}),getShaderSource:p}},kd=(t,e)=>{let r=t.inputs[0].dims,n=t.inputs[0].dataType,a=t.inputs[1];t.compute(Id(n,r,a,e),{inputs:[0]})},Td=t=>{let e=t.exclusive===1,r=t.reverse===1;return We({exclusive:e,reverse:r})}}),da,Yr,Gi,Ad,Md,Od,zd,Vi,Rd,Pd,Bd,gg=V(()=>{me(),Ce(),tt(),Se(),da="[a-zA-Z]|\\.\\.\\.",Yr="("+da+")+",Gi="^"+Yr+"$",Ad="("+Yr+",)*"+Yr,Md="^"+Ad+"$",Od=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,e){let r=this.symbolToIndices.get(t);r===void 0?r=[e]:r.push(e),this.symbolToIndices.set(t,r)}},zd=class{constructor(t,e){this.equation=e,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=e.includes("->")?e.split("->",2):[e,""];if(!r.match(RegExp(Md)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let s=t[i].dims.slice();if(!a.match(RegExp(Gi)))throw new Error("Invalid LHS term");let o=this.processTerm(a,!0,s,i);this.lhs.push(o)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Yr)))throw new Error("Invalid RHS");n.match(RegExp(da,"g"))?.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(t,e,r){let n=this.symbolToInfo.get(t);if(n!==void 0){if(n.dimValue!==e&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:e,inputIndices:[r]};this.symbolToInfo.set(t,n)}processTerm(t,e,r,n=-1){let a=r.length,i=!1,s=[],o=0;if(!t.match(RegExp(Gi))&&!e&&t!=="")throw new Error("Invalid LHS term");let l=t.match(RegExp(da,"g")),d=new Od(n);return l?.forEach((p,u)=>{if(p==="..."){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let h=a-l.length+1;if(h<0)throw new Error("Ellipsis out of bounds");if(s=r.slice(o,o+h),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else if(e)this.hasEllipsis=!0,this.ellipsisDims=s;else throw new Error("Ellipsis must be specified in the LHS");for(let m=0;mt+"_max",Rd=(t,e,r,n)=>{let a=t.map(d=>d.length).map((d,p)=>G(`input${p}`,e,d)),i=j.size(n),s=de("output",e,n.length),o=[...r.symbolToInfo.keys()].filter(d=>!r.rhs.symbolToIndices.has(d)),l=d=>{let p=[],u="var prod = 1.0;",h="var sum = 0.0;",m="sum += prod;",_=[],y=[],v=[],x=[],w=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((I,k)=>{if(r.rhs.symbolToIndices.has(k)){let A=r.rhs.symbolToIndices.get(k)?.[0];A!==void 0&&r.lhs.forEach((D,L)=>{if(I.inputIndices.includes(L)){let Y=D.symbolToIndices.get(k);if(Y===void 0)throw new Error("Invalid symbol error");Y.forEach(H=>{p.push(`${a[L].indicesSet(`input${L}Indices`,H,s.indicesGet("outputIndices",A))}`)})}})}else r.lhs.forEach((A,D)=>{if(I.inputIndices.includes(D)){let L=A.symbolToIndices.get(k);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(Y=>{_.push(`${a[D].indicesSet(`input${D}Indices`,Y,`${k}`)}`)}),x.push(`prod *= ${a[D].getByIndices(`input${D}Indices`)};`)}}),y.push(`for(var ${k}: u32 = 0; ${k} < uniforms.${Vi(k)}; ${k}++) {`),v.push("}")});let E=w?[...p,`let sum = ${a.map((I,k)=>I.getByIndices(`input${k}Indices`)).join(" * ")};`]:[...p,h,...y,..._,u,...x,m,...v];return` + ${d.registerUniforms(o.map(I=>({name:`${Vi(I)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...a,s)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${s.offsetToIndices("global_idx")}; + ${a.map((I,k)=>`var input${k}Indices: ${a[k].type.indices};`).join(` +`)} + ${E.join(` +`)}; + ${s.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:t.map(()=>"rank")},getRunData:()=>{let d=o.filter(u=>r.symbolToInfo.has(u)).map(u=>({type:12,data:r.symbolToInfo.get(u)?.dimValue||0}));d.push({type:12,data:i});let p=t.map((u,h)=>[...ce(u)]).reduce((u,h)=>u.concat(h),d);return p.push(...ce(n)),{outputs:[{dims:n,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}},getShaderSource:l}},Pd=(t,e)=>{let r=new zd(t.inputs,e.equation),n=r.outputDims,a=t.inputs.map((i,s)=>i.dims);t.compute(Rd(a,t.inputs[0].dataType,r,n))},Bd=t=>{let e=t.equation.replace(/\s+/g,"");return We({equation:e})}}),Dd,Hi,Nd,Ld,Ud,_g=V(()=>{me(),Ce(),Se(),Dd=t=>{if(!t||t.length!==2)throw new Error("Expand requires 2 input.");let e=t[0].dims,r=Array.from(t[1].getBigInt64Array(),Number),n=r.length{let r=t.length-e.length,n=[];for(let a=0;at.length>e.length?Hi(t,e):Hi(e,t),Ld=t=>{let e=t[0].dims,r=Array.from(t[1].getBigInt64Array(),Number),n=Nd(e,r),a=t[0].dataType,i=a===9?4:1,s=Math.ceil(j.size(n)/i),o=d=>{let p=G("input",a,e.length,i),u=de("output",a,n.length,i),h;if(a===9){let m=(_,y,v="")=>` + let outputIndices${y} = ${u.offsetToIndices(`outputOffset + ${y}u`)}; + let offset${y} = ${p.broadcastedIndicesToOffset(`outputIndices${y}`,u)}; + let index${y} = offset${y} / 4u; + let component${y} = offset${y} % 4u; + ${_}[${y}] = ${v}(${p.getByOffset(`index${y}`)}[component${y}]); + `;h=` + let outputOffset = global_idx * ${i}; + var data = vec4(0); + ${m("data",0,"u32")} + ${m("data",1,"u32")} + ${m("data",2,"u32")} + ${m("data",3,"u32")} + ${u.setByOffset("global_idx","data")} + }`}else h=` + let outputIndices = ${u.offsetToIndices("global_idx")}; + let inputOffset = ${p.broadcastedIndicesToOffset("outputIndices",u)}; + ${u.setByOffset("global_idx",p.getByOffset("inputOffset"))} + }`;return` + ${d.registerUniform("vec_size","u32").declareVariables(p,u)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h}`},l=[{type:12,data:s},...ce(e,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:o,getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l})}},Ud=t=>{Dd(t.inputs),t.compute(Ld(t.inputs),{inputs:[0]})}}),Fd,Wd,yg=V(()=>{me(),Ce(),Se(),Ti(),Fd=t=>{let e=t[0].dataType,r=j.size(t[0].dims),n=j.size(t[1].dims),a=n%4===0,i=s=>{let o=G("x",e,[1],4),l=G("bias",e,[1],4),d=de("y",e,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=m=>` + let bias${m}_offset: u32 = (global_idx * 4 + ${m}) % uniforms.bias_size; + let bias${m} = ${l.getByOffset(`bias${m}_offset / 4`)}[bias${m}_offset % 4];`,h=a?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${u(0)}${u(1)}${u(2)}${u(3)} + let bias = ${o.type.value}(bias0, bias1, bias2, bias3);`;return`${s.registerUniforms(p).declareVariables(o,l,d)} + + ${Ii(mt(e))} + + ${s.mainStart(Zn)} + ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${o.getByOffset("global_idx")}; + ${h} + let x_in = x + bias; + ${d.setByOffset("global_idx",ki("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${a}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:s=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Zn/4)}})}},Wd=t=>{t.inputs.length<2||j.size(t.inputs[1].dims)===0?Au(t):t.compute(Fd(t.inputs))}}),Gd,Vd,Hd,qd,wg=V(()=>{me(),Ce(),tt(),Se(),Gd=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},Vd=(t,e)=>{let r=t[0].dims,n=t[1].dims,a=r.length,i=j.normalizeAxis(e.axis,a),s=r.slice(0);s.splice(i,1,...n);let o=r[i],l=t[0].dataType===9?4:1,d=Math.ceil(j.size(s)/l),p=[{type:12,data:d},{type:6,data:o},{type:12,data:i},...ce(t[0].dims,t[1].dims,s)],u=h=>{let m=G("data",t[0].dataType,t[0].dims.length,l),_=G("inputIndices",t[1].dataType,t[1].dims.length),y=de("output",t[0].dataType,s.length,l),v=w=>{let E=n.length,I=`var indicesIndices${w} = ${_.type.indices}(0);`;for(let k=0;k1?`indicesIndices${w}[${k}]`:`indicesIndices${w}`} = ${s.length>1?`outputIndices${w}[uniforms.axis + ${k}]`:`outputIndices${w}`};`;I+=` + var idx${w} = ${_.getByIndices(`indicesIndices${w}`)}; + if (idx${w} < 0) { + idx${w} = idx${w} + uniforms.axisDimLimit; + } + var dataIndices${w} : ${m.type.indices}; + `;for(let k=0,A=0;k1?`dataIndices${w}[${k}]`:`dataIndices${w}`} = u32(idx${w});`,A+=E):(I+=`${a>1?`dataIndices${w}[${k}]`:`dataIndices${w}`} = ${s.length>1?`outputIndices${w}[${A}]`:`outputIndices${w}`};`,A++);return I},x;if(t[0].dataType===9){let w=(E,I,k="")=>` + let outputIndices${I} = ${y.offsetToIndices(`outputOffset + ${I}u`)}; + ${v(I)}; + let offset${I} = ${m.indicesToOffset(`dataIndices${I}`)}; + let index${I} = offset${I} / 4u; + let component${I} = offset${I} % 4u; + ${E}[${I}] = ${k}(${m.getByOffset(`index${I}`)}[component${I}]); + `;x=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${w("value",0,"u32")} + ${w("value",1,"u32")} + ${w("value",2,"u32")} + ${w("value",3,"u32")} + ${y.setByOffset("global_idx","value")} + `}else x=` + let outputIndices = ${y.offsetToIndices("global_idx")}; + ${v("")}; + let value = ${m.getByIndices("dataIndices")}; + ${y.setByOffset("global_idx","value")}; + `;return` + ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,_,y)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${x} + }`};return{name:"Gather",shaderCache:{hint:e.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:u}},Hd=t=>We({axis:t.axis}),qd=(t,e)=>{let r=t.inputs;Gd(r),t.compute(Vd(t.inputs,e))}}),jd,Kd,Yd,Xd,bg=V(()=>{me(),Ce(),tt(),Se(),jd=t=>{if(!t||t.length!==2)throw new Error("GatherElements requires 2 inputs.");if(t[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(t[0].dims.length!==t[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Kd=(t,e)=>{let r=t[0].dims,n=t[0].dataType,a=r.length,i=t[1].dims,s=t[1].dataType,o=j.normalizeAxis(e.axis,a),l=r[o],d=i.slice(0),p=j.size(d),u=G("input",n,a),h=G("indicesInput",s,i.length),m=de("output",n,d.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:o}];return _.push(...ce(r,i,d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:y=>` + ${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,h,m)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${m.offsetToIndices("global_idx")}; + + var idx = ${h.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${u.type.indices}(outputIndices); + ${u.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${u.getByIndices("inputIndices")}; + + ${m.setByOffset("global_idx","value")}; + }`}},Yd=t=>We({axis:t.axis}),Xd=(t,e)=>{let r=t.inputs;jd(r),t.compute(Kd(t.inputs,e))}}),Qd,Zd,Jd,ec,vg=V(()=>{me(),Ce(),Se(),Qd=t=>{if(!t)throw new Error("Input is missing");if(t.length<2||t.length>3)throw new Error("Invaid input number.");if(t.length===3&&t[2].dims.length>2)throw new Error("Invalid input shape of C");if(t[0].dataType!==t[1].dataType||t.length===3&&t[0].dataType!==t[2].dataType)throw new Error("Input types are mismatched")},Zd=(t,e)=>{let r=t[0].dims.slice(),n=t[1].dims.slice(),[a,i,s]=Uo.getShapeOfGemmResult(r,e.transA,n,e.transB,t.length===3?t[2].dims:void 0),o=[a,i];if(!o)throw new Error("Can't use gemm on the given tensors");let l=j.size(o),d=[{type:12,data:l},{type:12,data:a},{type:12,data:i},{type:12,data:s},{type:1,data:e.alpha},{type:1,data:e.beta}],p=["type","type"];t.length===3&&(d.push(...ce(t[2].dims)),p.push("rank")),d.push(...ce(o));let u=h=>{let m="";e.transA&&e.transB?m="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":e.transA&&!e.transB?m="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!e.transA&&e.transB?m="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!e.transA&&!e.transB&&(m="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let _=e.alpha===1?"":"value *= uniforms.alpha;",y=G("a",t[0].dataType,t[0].dims),v=G("b",t[1].dataType,t[1].dims),x=y.type.value,w=null,E=[y,v];t.length===3&&(w=G("c",t[2].dataType,t[2].dims.length),E.push(w));let I=de("output",t[0].dataType,o.length);E.push(I);let k=[{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` + ${h.registerUniforms(k).declareVariables(...E)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${x}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${m} + } + + ${_} + ${w!=null?`let cOffset = ${w.broadcastedIndicesToOffset("vec2(m, n)",I)}; value += ${x}(uniforms.beta) * ${w.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},Jd=t=>{let e=t.transA,r=t.transB,n=t.alpha,a=t.beta;return{transA:e,transB:r,alpha:n,beta:a,cacheKey:`${t.transA};${t.transB};${t.alpha===1}`}},ec=(t,e)=>{Qd(t.inputs),t.compute(Zd(t.inputs,e))}}),tc,rc,nc,ac,$g=V(()=>{me(),Ce(),Se(),tc=(t,e)=>{let r=t[0].dims,n=r,a=2,i=j.sizeToDimension(r,a),s=j.sizeFromDimension(r,a),o=Qe(s),l=s/o,d=[r[0],r[1],l],p=["rank","type","type"],u=[{type:12,data:s},{type:12,data:l}];u.push(...ce(d,d));let h=m=>{let _=G("x",t[0].dataType,d.length,o),y=G("scale",t[1].dataType,t[1].dims),v=G("bias",t[2].dataType,t[2].dims),x=de("output",t[0].dataType,d.length,o),w=[_,y,v,x],E=_.type.value,I=o===1?"f32":`vec${o}`,k=64,A=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${I}, ${k}>; + const workgroupSize = ${k}u; + ${m.registerUniforms(A).declareVariables(...w)} + ${m.mainStart(k)} + let norm = global_idx / workgroupSize; + let batch = norm / uniforms.x_shape[1]; + let channel = norm % uniforms.x_shape[1]; + let localIndex = local_id.x; + + // initialize workgroup memory + var initial = ${I}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${I}(${_.get("batch","channel","h")}); + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the mean of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + meanShared = ${At("workgroupShared[0]",o)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${I}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${I}(${_.get("batch","channel","h")}) - ${I}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${At("workgroupShared[0]",o)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); + let channelScale = invStdDev * f32(${y.getByOffset("channel")}); + let channelShift = f32(${v.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${_.get("batch","channel","h")} * ${E}(${I}(channelScale)) + ${E}(${I}(channelShift)); + ${x.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${e.epsilon};${o}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:i},programUniforms:u}),getShaderSource:h}},rc=(t,e,r,n,a,i,s,o)=>{let l=Qe(s),d=64,p=l===1?"vec2f":`mat2x${l}f`,u=l===1?"f32":`vec${l}f`,h=(A,D)=>`${p}(${A}, ${D})`,m=a*s/l,_=Math.ceil(i/d),y=["type"],v=[{type:12,data:_},{type:12,data:i},{type:12,data:Math.floor(s/l)},{type:12,data:Math.floor(i*s/l)}],x=A=>{let D=G("input",e.dataType,e.dims,l);return` + ${A.declareVariables(D)} + @group(0) @binding(1) var output : array<${p}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${A.mainStart(d)} + let currentImageNumber = global_idx / ${d} / uniforms.C; + let currentChannelNumber = (global_idx / ${d}) % uniforms.C; + let wgId = global_idx % ${d}; + let wgOffset = wgId * uniforms.wg_size; + if (wgOffset >= uniforms.H) { + return; + } + let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); + + let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; + var sum = ${ct("f32",l)}; + var squaredSum = ${ct("f32",l)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${u}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${h("sum","squaredSum")}; + }`},w=t.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:[a,s,d,2],dataType:1}],dispatchGroup:{x:a*s/l},programUniforms:v}),getShaderSource:x},{inputs:[e],outputs:[-1]})[0],E=[{type:12,data:m},{type:12,data:i},{type:12,data:Math.floor(s/l)},{type:12,data:Math.floor(d*s/l)}],I=["type","type","type"],k=A=>{let D=G("scale",r.dataType,r.dims,l),L=G("bias",n.dataType,n.dims,l);return` + @group(0) @binding(0) var input : array<${p}>; + @group(0) @binding(1) var scale : array<${D.type.storage}>; + @group(0) @binding(2) var bias : array<${L.type.storage}>; + @group(0) @binding(3) var output : array<${p}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} + let currentImageNumber = global_idx / uniforms.C; + let currentChannelNumber = global_idx % uniforms.C; + + let offset = currentImageNumber * uniforms.image_size; + var sum = ${ct("f32",l)}; + var squaredSum = ${ct("f32",l)}; + for (var i: u32 = 0; i < min(${d}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${d}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${o})); + let channelScale = invStdDev * ${u}(scale[currentChannelNumber]); + let channelShift = ${u}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${h("channelScale","channelShift")}; + }`};return t.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:[a,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:E}),getShaderSource:k},{inputs:[w,r,n],outputs:[-1]})[0]},nc=(t,e,r)=>{let n=e[0].dims,a=n,i=n[0],s=n[n.length-1],o=j.sizeFromDimension(n,1)/s,l=Qe(s),d=j.size(a)/l,p=[{type:12,data:o},{type:12,data:Math.floor(s/l)}],u=["type","type"],h=rc(t,e[0],e[1],e[2],i,o,s,r.epsilon),m=_=>{let y=Ze(e[0].dataType),v=l===1?"vec2f":`mat2x${l}f`,x=l===1?y:`vec${l}<${y}>`,w=G("input",e[0].dataType,e[0].dims,l),E=de("output",e[0].dataType,a,l);return` + @group(0) @binding(0) var input : array<${w.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${v}>; + @group(0) @binding(2) var output : array<${E.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${_.mainStart()} + let currentImageNumber = global_idx / (uniforms.C * uniforms.H); + let currentChannelNumber = global_idx % uniforms.C; + + let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; + let scale = scaleInput[scaleOffset]; + output[global_idx] = fma(input[global_idx], ${x}(scale[0]), ${x}(scale[1])); + }`};t.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:m},{inputs:[e[0],h]})},ac=(t,e)=>{e.format==="NHWC"?nc(t,t.inputs,e):t.compute(tc(t.inputs,e))}}),ic,sc,oc,xg=V(()=>{me(),Ce(),Se(),ic=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},sc=(t,e,r)=>{let n=t[0].dims,a=t[1],i=t[2],s=n,o=j.normalizeAxis(e.axis,n.length),l=j.sizeToDimension(n,o),d=j.sizeFromDimension(n,o),p=j.size(a.dims),u=i?j.size(i.dims):0;if(p!==d||i&&u!==d)throw new Error(`Size of X.shape()[axis:] == ${d}. + Size of scale and bias (if provided) must match this. + Got scale size of ${p} and bias size of ${u}`);let h=[];for(let I=0;I1,x=r>2,w=I=>{let k=Ze(t[0].dataType),A=[G("x",t[0].dataType,t[0].dims,m),G("scale",a.dataType,a.dims,m)];i&&A.push(G("bias",i.dataType,i.dims,m)),A.push(de("output",t[0].dataType,s,m)),v&&A.push(de("mean_data_output",1,h)),x&&A.push(de("inv_std_output",1,h));let D=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${I.registerUniforms(D).declareVariables(...A)} + ${I.mainStart()} + ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${ct("f32",m)}; + var mean_square_vector = ${ct("f32",m)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Nt(k,m,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${At("mean_vector",m)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${At("mean_square_vector",m)} / uniforms.norm_size - mean * mean + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Nt(k,m,"x[j + offset]")}; + let f32scale = ${Nt(k,m,"scale[j]")}; + output[j + offset] = ${A[0].type.value}((f32input - mean) * inv_std_dev * f32scale + ${i?`+ ${Nt(k,m,"bias[j]")}`:""} + ); + } + + ${v?"mean_data_output[global_idx] = mean":""}; + ${x?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},E=[{dims:s,dataType:t[0].dataType}];return v&&E.push({dims:h,dataType:1}),x&&E.push({dims:h,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${m};${r}`,inputDependencies:_},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:y}),getShaderSource:w}},oc=(t,e)=>{ic(t.inputs),t.compute(sc(t.inputs,e,t.outputCount))}}),lc,uc,dc,cc,Sg=V(()=>{me(),Ce(),tt(),Se(),lc=(t,e)=>{if(t.length<3||t.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=t[0],n=r.dims.length;if(r.dims[n-1]!==e.k)throw new Error("The last dim of input shape does not match the k value");let a=Math.floor((e.k+e.blockSize-1)/e.blockSize),i=e.blockSize/8*e.bits,s=t[1];if(!j.areEqual(s.dims,[e.n,a,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=t[2].dims;if(j.size(o)!==e.n*a)throw new Error("scales input size error.");if(t.length===4){let l=t[3].dims,d=e.bits>4?e.n*a:e.n*Math.floor((a+1)/2);if(j.size(l)!==d)throw new Error("zeroPoints input size error.")}},uc=(t,e)=>{let r=t[0].dims,n=r.length,a=r.slice(0,n-1).concat(e.n),i=r[n-2],s=e.blockSize/8*e.bits/4,o=Qe(i),l=Qe(e.n),d=Qe(e.k),p=Qe(s),u=j.size(a)/l/o,h=[{type:12,data:u},{type:12,data:e.k},{type:12,data:e.n},{type:12,data:e.accuracyLevel},{type:12,data:e.bits},{type:12,data:e.blockSize}],m=r.slice();m.splice(-1,1,e.k/d);let _=j.convertShape(t[1].dims).slice();_.splice(-1,1,s/p),h.push(...ce(m)),h.push(...ce(_)),h.push(...ce(t[2].dims)),t.length===4&&h.push(...ce(j.convertShape(t[3].dims)));let y=a.slice();y.splice(-1,1,e.n/l),h.push(...ce(y));let v=x=>{let w=G("a",t[0].dataType,m.length,d),E=G("b",12,_.length,p),I=G("scales",t[2].dataType,t[2].dims.length),k=[w,E,I],A=t.length===4?G("zero_points",12,t[3].dims.length):void 0;A&&k.push(A);let D=de("output",t[0].dataType,a.length,l),L=[{name:"output_size",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"accuracy_level",type:"u32"},{name:"bits",type:"u32"},{name:"block_size",type:"u32"}],Y=Math.floor((e.k+e.blockSize-1)/e.blockSize),H=Ze(t[0].dataType),re=(()=>{switch(d){case 1:return`array<${H}, 8>`;case 2:return`mat4x2<${H}>`;case 4:return`mat2x4<${H}>`;default:throw new Error(`${d}-component is not supported.`)}})(),N=` + fn dequantize(quantized: ${re}, zero_point: ${H}, scale: ${H}) -> ${re} { + ${d===1?`var dequantized = ${re}(${Array.from({length:8},(Ae,q)=>`(quantized[${q}] - zero_point) * scale`).join(", ")}); + return dequantized;`:`var zero_points: ${re} = ${re}(${Array(8).fill("zero_point").join(",")}); + return (quantized - zero_points) * scale;`} + }`,ee=` + fn ortUnpack8x4snorm(value: u32) -> ${re} { + var quantized: ${re}; + var offset: u32 = 0; + let count: u32 = 4; + for (var i: u32 = 0; i < 8u; i++) { + var result = ${H}(extractBits(value, offset, count)); + ${(()=>{switch(d){case 1:return"quantized[i] = result;";case 2:return"quantized[i / 2][i % 2] = result;";case 4:return"quantized[i / 4][i % 4] = result;";default:throw new Error(`${d}-component is not supported.`)}})()} + offset += count; + } + return quantized; + }`,oe=A?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${A.getByOffset("zero_point_index")}; + }`:"";return` + ${N}; + ${ee}; + ${x.registerUniforms(L).declareVariables(...k,D)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${D.type.value}, ${o}>; + var output_indices = ${D.offsetToIndices("global_idx")}; + var n = ${D.indicesGet("output_indices",n-1)}; + var m = ${D.indicesGet("output_indices",n-2)}; + var a_indices: ${w.type.indices} = output_indices; + // Two zero points are packed into one byte because uniforms.bits <= 4. + // zero_point_offset is either 0 or 4. It is bit offset within one byte. + // TODO support zero_point_offset for bits > 4 + ${A?` + var zero_point_index: u32 = n * ${l} * ((${Y} + 1) / 2) / 4; + var zero_point_word: u32 = ${A.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = 0;`:""} + var scale_index = n * ${Y*l}; + var b_indices: ${E.type.indices}; + for (var c: u32 = 0; c < ${l}; c++) { + ${E.indicesSet("b_indices","0",`n * ${l} + c`)}; + var block_offset: u32 = 0; + for (var block: u32 = 0; block < ${Y}; block++) { + // The scale and zero points are computed per block. + let scale = ${I.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${H}(${A?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${E.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + for (var word: u32 = 0; word < ${s}; word += ${p}) { + ${E.indicesSet("b_indices","2","word")}; + let b_data = ${E.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${p}; i++) { + let b_value = ${p===1?"b_data":"b_data[word + i]"}; + let b_quantized_values: ${re} = ortUnpack8x4snorm(b_value); + let b_dequantized_values = dequantize(b_quantized_values, zero_point, scale); + // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 + var offset: u32 = word_offset; + for (var j: u32 = 0; j < 8/${d}; j++) { + ${w.indicesSet("a_indices",n-1,`offset/${d}`)}; + for (var k: u32 = 0; k < ${o}u; k++) { + ${w.indicesSet("a_indices",n-2,`m * ${o} + k`)}; + let a_data = ${w.getByIndices("a_indices")}; + output_values[k]${l>1?"[c]":""} += ${d===1?"a_data * b_dequantized_values[j]":"dot(a_data, b_dequantized_values[j])"}; + } + offset += ${d}; + } + word_offset += 8; + } + } + scale_index++; + ${oe} + block_offset += uniforms.block_size; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${A?`if (zero_point_offset % 8 > 0) { + ${oe} + }`:""} + } + for (var k: u32 = 0u; k < ${o}u; k++) { + ${D.indicesSet("output_indices",n-2,`${o+" * m + k"}`)}; + ${D.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${e.cacheKey};${t.length}`,inputDependencies:Array(t.length).fill("rank")},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h}),getShaderSource:v}},dc=(t,e)=>{lc(t.inputs,e),t.compute(uc(t.inputs,e))},cc=t=>We(t)}),pc,hc,qi,fc,ca,mc,Eg=V(()=>{me(),Ce(),tt(),mi(),Gl(),Se(),Kr(),pc=(t,e)=>{let r=t[0],n=t[1],a=t[2],i=t[3],s=t[4],o=t[5],l=t[6],d=t[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=!1,u=r.dims[0],h=r.dims[1],m=r.dims.length===3?p?r.dims[2]/3:r.dims[2]:e.numHeads*r.dims[4],_=h,y=0,v=0,x=Math.floor(m/e.numHeads);if(l&&d){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');y=l.dims[2],v=l.dims[2]}else if(l||d)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(n){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)');w=2,_=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==e.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,_=n.dims[1]}else{if(n.dims[1]!==e.numHeads||n.dims[3]!==x)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,_=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]!==e.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(i){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(a&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let E=0;if(s){E=8;let L=s.dims;throw L.length===1?L[0]===u?E=1:L[0]===3*u+2&&(E=3):L.length===2&&L[0]===u&&L[1]===_&&(E=5),E===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let I=!1,k=m;if(a){if(a.dims.length!==3&&a.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(a.dims.length===3){if(_!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');k=a.dims[2]}else{if(_!==a.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');k=a.dims[1]*a.dims[3],I=!0}}let A=y+_,D=!1;if(s)throw new Error("Key padding mask is not supported");if(o)throw new Error("extraAddQk is not supported");if(l)throw new Error("pastKey is not supported");if(d)throw new Error("pastValue is not supported");return{batchSize:u,sequenceLength:h,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:A,maxSequenceLength:v,inputHiddenSize:0,hiddenSize:m,vHiddenSize:k,headSize:x,vHeadSize:Math.floor(k/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:E,scale:e.scale,broadcastResPosBias:D,passPastInKv:I,qkvFormat:w}},hc=t=>We({...t}),qi=We({perm:[0,2,1,3]}),fc=(t,e,r,n,a,i,s)=>{let o=[n,a,i],l=j.size(o),d=[{type:12,data:l},{type:12,data:s},{type:12,data:i}],p=u=>{let h=de("qkv_with_bias",e.dataType,o),m=G("qkv",e.dataType,o),_=G("bias",r.dataType,o),y=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${u.registerUniforms(y).declareVariables(m,_,h)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return t.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:p},{inputs:[e,r],outputs:[-1]})[0]},ca=(t,e,r,n,a,i,s,o)=>{let l=i;if(s){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=fc(t,i,s,e,n,r*a,o),l=l.reshape([e,n,r,a]),t.compute(Lt(l,qi.perm),{inputs:[l],outputs:[-1]})[0]}else return i.dims.length===3&&(l=i.reshape([e,n,r,a])),t.compute(Lt(l,qi.perm),{inputs:[l],outputs:[-1]})[0]},mc=(t,e)=>{let r=pc(t.inputs,e);if(t.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(t.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let n=t.inputs[1]&&t.inputs[2]&&t.inputs[1].dims.length===4&&t.inputs[2].dims.length===4,a=ca(t,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,t.inputs[0],t.inputs[3],0);if(n)return ra(t,a,t.inputs[1],t.inputs[2],t.inputs[4],void 0,void 0,void 0,t.inputs[5],r,e);let i=ca(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,t.inputs[1],t.inputs[3],r.hiddenSize),s=ca(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,t.inputs[2],t.inputs[3],2*r.hiddenSize);ra(t,a,i,s,t.inputs[4],void 0,t.inputs[6],t.inputs[7],t.inputs[5],r,e)}}),gc,_c,yc,wc,bc,vc,$c,xc,Sc,Cg=V(()=>{me(),Ce(),Se(),gc=t=>{if(!t||t.length<1)throw new Error("Too few inputs");if(t[0].dataType!==1&&t[0].dataType!==10)throw new Error("Input type must be float or float16.");if(t.length>=2){let e=t[0].dims.length*2===t[1].dims[0];if(t.length===4&&(e=t[3].dims[0]*2===t[1].dims[0]),!e)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},_c=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` + k = i32(${t.indicesGet("indices",a)}) - ${ge("uniforms.pads",a,r)}; + if (k < 0) { + break; + } + if (k >= i32(${ge("uniforms.x_shape",a,e)})) { + break; + } + offset += k * i32(${ge("uniforms.x_strides",a,e)}); + `;return` + value = ${t.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},yc=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` + k = i32(${t.indicesGet("indices",a)}) - ${ge("uniforms.pads",a,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${ge("uniforms.x_shape",a,e)}) - 1); + k = k % _2n_1; + if(k >= i32(${ge("uniforms.x_shape",a,e)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${ge("uniforms.x_strides",a,e)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},wc=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` + k = i32(${t.indicesGet("indices",a)}) - ${ge("uniforms.pads",a,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${ge("uniforms.x_shape",a,e)})) { + k = i32(${ge("uniforms.x_shape",a,e)}) - 1; + } + offset += k * i32(${ge("uniforms.x_strides",a,e)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},bc=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` + k = i32(${t.indicesGet("indices",a)}) - ${ge("uniforms.pads",a,r)}; + if (k < 0) { + k += i32(${ge("uniforms.x_shape",a,e)}]); + } + if (k >= i32(${ge("uniforms.x_shape",a,e)})) { + k -= i32(${ge("uniforms.x_shape",a,e)}); + } + offset += k * i32(${ge("uniforms.x_strides",a,e)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},vc=(t,e,r)=>{switch(r.mode){case 0:return _c(t,e,r.pads.length);case 1:return yc(t,e,r.pads.length);case 2:return wc(t,e,r.pads.length);case 3:return bc(t,e,r.pads.length);default:throw new Error("Invalid mode")}},$c=(t,e)=>{let r=j.padShape(t[0].dims.slice(),e.pads),n=t[0].dims,a=j.size(r),i=[{type:12,data:a},{type:12,data:e.pads}];e.mode===0&&i.push({type:t[0].dataType,data:e.value}),i.push(...ce(t[0].dims,r));let s=["rank"],o=l=>{let d=de("output",t[0].dataType,r.length),p=G("x",t[0].dataType,n.length),u=p.type.value,h=vc(d,n.length,e),m=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&m.push({name:"constant_value",type:u}),` + ${l.registerUniforms(m).declareVariables(p,d)} + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + + var value = ${u}(0); + ${h} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${e.mode}`,inputDependencies:s},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(j.size(r)/64)},programUniforms:i}),getShaderSource:o}},xc=(t,e)=>{if(t.length>1){let r=t[1].getBigInt64Array(),n=t.length>=3&&t[2].data?t[2].getFloat32Array()[0]:0,a=t[0].dims.length,i=new Int32Array(2*a).fill(0);if(t.length>=4){let o=t[3].getBigInt64Array();for(let l=0;li[Number(l)]=Number(o));let s=[];return i.forEach(o=>s.push(o)),{mode:e.mode,value:n,pads:s}}else return e},Sc=(t,e)=>{gc(t.inputs);let r=xc(t.inputs,e);t.compute($c(t.inputs,r),{inputs:[0]})}}),Xr,ji,Ki,Yi,Xi,Ec,Cc,Qi,Zi,Ic,kc,Ji,Tc,Ac,es,Mc,Oc,zc,Rc,Ig=V(()=>{xt(),me(),Ce(),Se(),Xr=t=>{if(Oe.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},ji=(t,e,r)=>{let n=e.format==="NHWC",a=t.dims.slice();n&&a.splice(1,0,a.pop());let i=Object.hasOwnProperty.call(e,"dilations"),s=e.kernelShape.slice(),o=e.strides.slice(),l=i?e.dilations.slice():[],d=e.pads.slice();Qn.adjustPoolAttributes(r,a,s,o,l,d);let p=Qn.computePoolOutputShape(r,a,o,l,s,d,e.autoPad),u=Object.assign({},e);i?Object.assign(u,{kernelShape:s,strides:o,pads:d,dilations:l,cacheKey:e.cacheKey}):Object.assign(u,{kernelShape:s,strides:o,pads:d,cacheKey:e.cacheKey});let h=p.slice();return h.push(h.splice(1,1)[0]),[u,n?h:p]},Ki=(t,e)=>{let r=e.format==="NHWC",n=j.size(t),a=j.size(e.kernelShape),i=[{type:12,data:n},{type:12,data:a}],s=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(e.kernelShape.length<=2){let o=e.kernelShape[e.kernelShape.length-1],l=e.strides[e.strides.length-1],d=e.pads[e.pads.length/2-1],p=e.pads[e.pads.length-1],u=!!(d+p);i.push({type:12,data:o},{type:12,data:l},{type:12,data:d},{type:12,data:p}),s.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(e.kernelShape.length===2){let m=e.kernelShape[e.kernelShape.length-2],_=e.strides[e.strides.length-2],y=e.pads[e.pads.length/2-2],v=e.pads[e.pads.length-2];h=!!(y+v),i.push({type:12,data:m},{type:12,data:_},{type:12,data:y},{type:12,data:v}),s.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,s,!0,u,h]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let o=j.computeStrides(e.kernelShape);i.push({type:12,data:o},{type:12,data:e.pads},{type:12,data:e.strides}),s.push({name:"kernelStrides",type:"u32",length:o.length},{name:"pads",type:"u32",length:e.pads.length},{name:"strides",type:"u32",length:e.strides.length});let l=e.pads.reduce((d,p)=>d+p);return[i,s,!!l,!1,!1]}},Yi=(t,e,r,n,a,i,s,o,l,d,p,u)=>{let h=a.format==="NHWC",m=e.type.value,_=de("output",e.type.tensor,n);if(a.kernelShape.length<=2){let y="",v="",x="",w=r-(h?2:1);if(p?y=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${w}] = indices[${w}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${w}] < 0 || xIndices[${w}] + >= uniforms.x_shape[${w}]) { + pad++; + continue; + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + }`:y=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${w}] = indices[${w}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + }`,a.kernelShape.length===2){let E=r-(h?3:2);u?v=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${E}] = indices[${E}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${E}] < 0 || xIndices[${E}] >= uniforms.x_shape[${E}]) { + pad += i32(uniforms.kw); + continue; + } + `:v=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${E}] = indices[${E}] * uniforms.sh - uniforms.phStart + j; + `,x=` + } + `}return` + ${t.registerUniforms(l).declareVariables(e,_)} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var value = ${m}(${o}); + var pad = 0; + ${v} + ${y} + ${x} + ${s} + + output[global_idx] = value; + }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let y=a.kernelShape.length,v=a.pads.length,x="";return d?x=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + }`:x=` + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + `,` + ${t.registerUniforms(l).declareVariables(e,_)} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${m}(${o}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${y-1}u; j++) { + offsets[j] = offset / ${ge("uniforms.kernelStrides","j",y)}; + offset -= offsets[j] * ${ge("uniforms.kernelStrides","j",y)}; + } + offsets[${y-1}] = offset; + + isPad = false; + for (var j = ${r-y}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${ge("uniforms.strides",`j - ${r-y}u`,y)} + + offsets[j - ${r-y}u] - ${ge("uniforms.pads","j - 2u",v)}; + ${x} + } + ${s} + + output[global_idx] = value; + }`}},Xi=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,Ec=t=>`${Xi(t)};${t.countIncludePad}`,Cc=t=>`${Xi(t)};${t.storageOrder};${t.dilations}`,Qi=t=>({format:t.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],ceilMode:t.ceil_mode,kernelShape:t.kernel_shape,strides:t.strides,pads:t.pads}),Zi=(t,e,r,n)=>{let[a,i]=ji(e,n,r),s=G("x",e.dataType,e.dims.length),o=s.type.value,l="value += x_val;",d="";a.countIncludePad?d+=`value /= ${o}(uniforms.kernelSize);`:d+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[p,u,h,m,_]=Ki(i,a);p.push(...ce(e.dims,i));let y=["rank"];return{name:t,shaderCache:{hint:`${n.cacheKey};${h};${m};${_}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(j.size(i)/64)},programUniforms:p}),getShaderSource:v=>Yi(v,s,e.dims.length,i.length,a,l,d,0,u,h,m,_)}},Ic=t=>{let e=t.count_include_pad!==0,r=Qi(t);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:e,...r,cacheKey:""};return{...n,cacheKey:Ec(n)}},kc=(t,e)=>{Xr(t.inputs),t.compute(Zi("AveragePool",t.inputs[0],!1,e))},Ji={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Tc=t=>{let e=t.format;return{format:e,...Ji,cacheKey:e}},Ac=(t,e)=>{Xr(t.inputs),t.compute(Zi("GlobalAveragePool",t.inputs[0],!0,e))},es=(t,e,r,n)=>{let[a,i]=ji(e,n,r),s=` + value = max(x_val, value); + `,o="",l=G("x",e.dataType,e.dims.length),d=["rank"],[p,u,h,m,_]=Ki(i,a);return p.push(...ce(e.dims,i)),{name:t,shaderCache:{hint:`${n.cacheKey};${h};${m};${_}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(j.size(i)/64)},programUniforms:p}),getShaderSource:y=>Yi(y,l,e.dims.length,i.length,a,s,o,e.dataType===10?-65504:-1e5,u,h,m,_)}},Mc=(t,e)=>{Xr(t.inputs),t.compute(es("MaxPool",t.inputs[0],!1,e))},Oc=t=>{let e=t.storage_order,r=t.dilations,n=Qi(t);if(e!==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 a={storageOrder:e,dilations:r,...n,cacheKey:""};return{...a,cacheKey:Cc(a)}},zc=t=>{let e=t.format;return{format:e,...Ji,cacheKey:e}},Rc=(t,e)=>{Xr(t.inputs),t.compute(es("GlobalMaxPool",t.inputs[0],!0,e))}}),Pc,Bc,Dc,kg=V(()=>{xt(),me(),Se(),Pc=(t,e,r)=>{let n=t===e,a=te&&r>0;if(n||a||i)throw new Error("Range these inputs' contents are invalid.")},Bc=(t,e,r,n)=>{let a=Math.abs(Math.ceil((e-t)/r)),i=[a],s=a,o=[{type:12,data:s},{type:n,data:t},{type:n,data:r},...ce(i)],l=d=>{let p=de("output",n,i.length),u=p.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` + ${d.registerUniforms(h).declareVariables(p)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},Dc=t=>{let e=0,r=0,n=0;t.inputs[0].dataType===6?(e=t.inputs[0].getInt32Array()[0],r=t.inputs[1].getInt32Array()[0],n=t.inputs[2].getInt32Array()[0]):t.inputs[0].dataType===1&&(e=t.inputs[0].getFloat32Array()[0],r=t.inputs[1].getFloat32Array()[0],n=t.inputs[2].getFloat32Array()[0]),Oe.webgpu.validateInputContent&&Pc(e,r,n),t.compute(Bc(e,r,n,t.inputs[0].dataType),{inputs:[]})}}),Nc,Lc,Uc,Fc,Wc,Gc,Vc,Hc,qc,jc,Kc,ts,Yc,Xc,Qc,Zc,Jc,ep,tp,Tg=V(()=>{me(),Ce(),tt(),Se(),Nc=(t,e)=>{if(t.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),t.length>0){if(e.mode==="linear"){if(!(t.length===2||t.length===3||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1||t.length===5&&t[0]===1&&t[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(e.mode==="cubic"&&!(t.length===2||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Lc=(t,e,r)=>{e.every(a=>a>=0&&a{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return e.forEach((a,i)=>n[a]=t[i]),n},Uc=(t,e,r,n,a,i)=>{let[s,o,l]=r>10?[1,2,3]:[-1,t.length>1?1:-1,-1],d=t[0].dims.length;if(s>0&&t.length>s&&t[s].dims.length>0)t[s].getFloat32Array().forEach(p=>i.push(p));else if(e.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&t.length>o&&t[o].dims.length>0){if(t[o].getFloat32Array().forEach(p=>n.push(p)),n.length!==0&&n.length!==d&&r>=18&&n.length!==e.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Nc(n,e),e.axes.length>0&&Lc(n,e.axes,d).forEach((p,u)=>n[u]=p)}if(l>0&&t.length>l&&(t[l].getBigInt64Array().forEach(p=>a.push(Number(p))),a.length!==d||r>=18&&a.length===e.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(e.axes.length>0){if(n.length!==e.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(a.length!==e.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 a<"u"&&n.length>0&&a.length>d)throw new Error("Resize requires only of scales or sizes to be specified")},Fc=(t,e)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${e} { `+(()=>{switch(t){case"asymmetric":return`return ${e}(xResized) / ${e}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${e}(xResized) + 0.5) / ${e}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${e}(xResized) + 0.5) / ${e}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let whole = ${e}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); + let fract = + ${e}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${e}(lengthResized - 1); + return whole + fract; + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${e}(roiStart) * ${e}(lengthOriginal - 1) + + (${e}(xResized) * ${e}(roiEnd - roiStart) * ${e}(lengthOriginal - 1)) / + ${e}(lengthResized - 1); + } else { + return 0.5 * ${e}(roiStart + roiEnd) * ${e}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${e}xScale * ${e}(lengthResized); + const adjustment = ${e}(lengthResized) / outputWidth; + const center = ${e}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;case"half_pixel":return`return ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${t} is not supported`)}})()+"}",Wc=(t,e,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(t){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(e<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${t} is not supported`)}})()+"}",Gc=(t,e,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),a=t.length===0?n:t.slice();return e.length>0?(e.forEach((i,s)=>{n[i]=a[s],n[s+r]=a[e.length+s]}),n):a},Vc=(t,e,r,n)=>{let a=[];if(r.length>0)if(n.length>0){if(t.forEach(i=>a.push(i)),Math.max(...n)>t.length)throw new Error("axes is out of bound");n.forEach((i,s)=>a[i]=r[s])}else r.forEach(i=>a.push(i));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");a=t.map((i,s)=>Math.round(i*e[s]))}return a},Hc=(t,e,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>e[i]),Number.MAX_VALUE):Math.min(...e,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>e[i]),Number.MIN_VALUE):Math.max(...e,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();e.fill(1,0,e.length);let a=t.slice();return r.axes.length>0?(r.axes.forEach(i=>e[i]=n),r.axes.forEach(i=>a[i]=Math.round(t[i]*e[i]))):(e.fill(n,0,e.length),a.forEach((i,s)=>a[s]=Math.round(i*e[s]))),a},qc=(t,e,r,n,a)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> array<${t.type.value}, ${r.length}> { + var original_indices: array<${t.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var scale = ${ge("uniforms.scales","i",n)}; + var roi_low = ${ge("uniforms.roi","i",a)}; + var roi_hi = ${ge("uniforms.roi",`i + ${e.length}`,a)}; + if (scale == 1.0) { + original_indices[i] = ${t.type.value}(output_index); + } else { + var input_shape_i = ${ge("uniforms.input_shape","i",e.length)}; + var output_shape_i = ${ge("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; + }`,jc=(t,e,r,n,a,i,s)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> ${t.type.indices} { + var input_indices: ${t.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${ge("uniforms.scales","i",a)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${ge("uniforms.roi","i",i)}; + var roi_hi = ${ge("uniforms.roi",`i + ${r.length}`,i)}; + var input_shape_i = ${ge("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${ge("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${s} || (original_idx >= 0 && original_idx < ${e.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${e.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); + } + } + ${t.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,Kc=(t,e)=>` + fn checkInputIndices(input_indices: ${t.type.indices}) -> bool { + for (var i:u32 = 0; i < ${e.length}; i++) { + var input_index = ${t.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${ge("uniforms.input_shape","i",e.length)}) { + return false; + } + } + return true; + }`,ts=(t,e,r,n)=>t.rank>n?` + ${t.indicesSet("input_indices",e,"channel")}; + ${t.indicesSet("input_indices",r,"batch")}; +`:"",Yc=(t,e,r,n,a)=>{let[i,s,o,l]=r.length===2?[-1,0,1,-1]:[0,2,3,1],d=t.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${d} { + var input_indices: ${t.type.indices}; + ${t.indicesSet("input_indices",s,`max(0, min(row, ${r[s]} - 1))`)}; + ${t.indicesSet("input_indices",o,`max(0, min(col, ${r[o]} - 1))`)}; + ${ts(t,l,i,2)} + return ${t.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${e.type.indices}) -> ${d} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${d} = originalIndices[${s}]; + var col:${d} = originalIndices[${o}]; + ${n?`if (row < 0 || row > (${r[s]} - 1) || col < 0 || col > (${r[o]} - 1)) { + return ${a}; + }`:""}; + row = max(0, min(row, ${r[s]} - 1)); + col = max(0, min(col, ${r[o]} - 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[${l}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${i}])`:"0"}; + var x11: ${d} = getInputValue(batch, channel, row1, col1); + var x12: ${d} = getInputValue(batch, channel, row1, col2); + var x21: ${d} = getInputValue(batch, channel, row2, col1); + var x22: ${d} = getInputValue(batch, channel, row2, col2); + var dx1: ${d} = abs(row - ${d}(row1)); + var dx2: ${d} = abs(${d}(row2) - row); + var dy1: ${d} = abs(col - ${d}(col1)); + var dy2: ${d} = abs(${d}(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); + }`},Xc=(t,e,r,n,a,i,s,o,l,d)=>{let p=r.length===2,[u,h]=p?[0,1]:[2,3],m=t.type.value,_=y=>{let v=y===u?"row":"col";return` + fn ${v}CubicInterpolation(input_indices: ${t.type.indices}, output_indices: ${e.type.indices}) -> ${m} { + var output_index = ${e.indicesGet("output_indices",y)}; + var originalIdx: ${m} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[y]}, + ${n[y]}, ${r[y]}, ${i[y]}, ${i[y]} + ${r.length}); + var fractOriginalIdx: ${m} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${o} && (originalIdx < 0 || originalIdx > (${r[y]} - 1))) { + return ${l}; + } + var data: array<${m}, 4> = array<${m}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${v}: ${m} = originalIdx + ${m}(i); + if (${v} < 0 || ${v} >= ${r[y]}) { + ${d?`coefs[i + 1] = 0.0; + continue;`:o?`return ${l};`:`${v} = max(0, min(${v}, ${r[y]} - 1));`}; + } + var input_indices_copy: ${t.type.indices} = input_indices; + ${t.indicesSet("input_indices_copy",y,`u32(${v})`)}; + data[i + 1] = ${y===u?t.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${_(u)}; + ${_(h)}; + fn getCubicInterpolationCoefs(s: ${m}) -> array<${m}, 4> { + var absS = abs(s); + var coeffs: array<${m}, 4> = array<${m}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${m} = 1.0 - absS; + var twoMinusAbsS: ${m} = 2.0 - absS; + var onePlusAbsS: ${m} = 1.0 + absS; + coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s}; + coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1; + coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${m}, 4>, coefs: array<${m}, 4>) -> ${m} { + var coefsSum: ${m} = 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: ${e.type.indices}) -> ${m} { + var input_indices: ${t.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Qc=(t,e,r,n,a)=>{let[i,s,o,l,d]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=t.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { + var input_indices: ${t.type.indices}; + ${t.indicesSet("input_indices",s,`max(0, min(depth, ${r[s]} - 1))`)}; + ${t.indicesSet("input_indices",o,`max(0, min(height, ${r[o]} - 1))`)}; + ${t.indicesSet("input_indices",l,`max(0, min(width, ${r[l]} - 1))`)}; + ${ts(t,d,i,3)} + return ${t.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${s}]; + var height:${p} = originalIndices[${o}]; + var width:${p} = originalIndices[${l}]; + ${n?`if (depth < 0 || depth > (${r[s]} - 1) || height < 0 || height > (${r[o]} - 1) || width < 0 || (width > ${r[l]} - 1)) { + return ${a}; + }`:""}; + + depth = max(0, min(depth, ${r[s]} - 1)); + height = max(0, min(height, ${r[o]} - 1)); + width = max(0, min(width, ${r[l]} - 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[${d}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${i}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(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); + }`},Zc=(t,e,r,n,a,i)=>{let s=t.dims,o=Gc(i,e.axes,s.length),l=Vc(s,n,a,e.axes),d=n.slice();n.length===0&&(d=s.map((w,E)=>w===0?1:l[E]/w),e.keepAspectRatioPolicy!=="stretch"&&(l=Hc(s,d,e)));let p=de("output",t.dataType,l.length),u=G("input",t.dataType,s.length),h=j.size(l),m=s.length===l.length&&s.every((w,E)=>w===l[E]),_=e.coordinateTransformMode==="tf_crop_and_resize",y=e.extrapolationValue,v=u.type.value,x=w=>` + ${m?"":` + ${Fc(e.coordinateTransformMode,v)}; + ${(()=>{switch(e.mode){case"nearest":return` + ${Kc(u,s)}; + ${Wc(e.nearestMode,r,v)}; + ${jc(u,p,s,l,d.length,o.length,_)}; + `;case"linear":return` + ${qc(p,s,l,d.length,o.length)}; + ${(()=>{if(s.length===2||s.length===4)return`${Yc(u,p,s,_,y)}`;if(s.length===3||s.length===5)return`${Qc(u,p,s,_,y)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(s.length===2||s.length===4)return`${Xc(u,p,s,l,d,o,e.cubicCoeffA,_,e.extrapolationValue,e.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${w.registerUniform("output_size","u32").registerUniform("scales","f32",d.length).registerUniform("roi","f32",o.length).declareVariables(u,p)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${m?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + ${(()=>{switch(e.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${u.getByIndices("input_indices")}; + } else { + output[global_idx] = ${e.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${s.length===2||s.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${e.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${e.cacheKey}|${r}|${d.length>0?d:""}|${a.length>0?a:""}|${o.length>0?o:""}|${m}|${s}`,inputDependencies:["rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:d},{type:1,data:o},...ce(s,l)]})}},Jc=t=>{let e=t.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},ep=(t,e)=>{let r=[],n=[],a=[],i=Jc(t);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Uc(t.inputs,e,i,r,n,a),t.compute(Zc(t.inputs[0],e,i,r,n,a),{inputs:[0]})},tp=t=>{let e=t.antialias,r=t.axes,n=t.coordinateTransformMode,a=t.cubicCoeffA,i=t.excludeOutside!==0,s=t.extrapolationValue,o=t.keepAspectRatioPolicy,l=t.mode,d=t.nearestMode===""?"simple":t.nearestMode;return We({antialias:e,axes:r,coordinateTransformMode:n,cubicCoeffA:a,excludeOutside:i,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:d})}}),rp,np,ap,Ag=V(()=>{me(),Ce(),Se(),rp=t=>{if(!t||t.length<3)throw new Error("layerNorm requires at least 3 inputs.");let e=t[0],r=t[1],n=t[2];if(e.dataType!==r.dataType||e.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(e.dims.length!==3&&e.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 a=e.dims[e.dims.length-1],i=e.dims[e.dims.length-2];if(r.dims[r.dims.length-1]!==a)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]!==a)throw new Error("Gamma must have the same hidden size as input");if(t.length>3){let s=t[3];if(s.dims.length!==1)throw new Error("Beta must be 1D");if(s.dims[s.dims.length-1]!==a)throw new Error("Beta must have the same hidden size as input")}if(t.length>4){let s=t[4];if(s.dims.length!==1)throw new Error("Bias must be 1D");if(s.dims[s.dims.length-1]!==a)throw new Error("Bias must have the same hidden size as input")}},np=(t,e,r,n)=>{let a=t[0].dims,i=j.size(a),s=a,o=i,l=a.slice(-1)[0],d=n?a.slice(0,-1).concat(1):[],p=t.length>3,u=t.length>4,h=n&&r>1,m=n&&r>2,_=r>3,y=Qe(l),v=[{type:12,data:o},{type:12,data:y},{type:12,data:l},{type:1,data:e.epsilon}],x=E=>{let I=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],k=[G("x",t[0].dataType,t[0].dims,y),G("skip",t[1].dataType,t[1].dims,y),G("gamma",t[2].dataType,t[2].dims,y)];p&&k.push(G("beta",t[3].dataType,t[3].dims,y)),u&&k.push(G("bias",t[4].dataType,t[4].dims,y)),k.push(de("output",t[0].dataType,s,y)),h&&k.push(de("mean_output",1,d)),m&&k.push(de("inv_std_output",1,d)),_&&k.push(de("input_skip_bias_sum",t[0].dataType,s,y));let A=Ze(t[0].dataType);return` + + ${E.registerUniforms(I).declareVariables(...k)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")} + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + let offset = global_idx * hidden_size_vectorized; + var sum = ${ct("f32",y)}; + var squareSum = ${ct("f32",y)}; + for (var i: u32 = 0; i < hidden_size_vectorized; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${u?"bias[i]":"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 = ${Nt(A,y,"value")}; + sum += f32_value; + squareSum += f32_value * f32_value; + } + let mean = ${At("sum",y)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${At("squareSum",y)} / f32(uniforms.hidden_size) - mean * mean + uniforms.epsilon); + ${h?"mean_output[global_idx] = mean;":""} + ${m?"inv_std_output[global_idx] = inv_std_dev;":""} + for (var i: u32 = 0; i < hidden_size_vectorized; i++) { + output[offset + i] = (output[offset + i] - ${A}(mean)) * ${A}(inv_std_dev) * gamma[i] + ${p?"beta[i]":"0.0"}; + } + }`},w=[{dims:s,dataType:t[0].dataType}];return r>1&&w.push({dims:d,dataType:1}),r>2&&w.push({dims:d,dataType:1}),r>3&&w.push({dims:a,dataType:t[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${y};${h};${m};${_}`,inputDependencies:t.map((E,I)=>"type")},getShaderSource:x,getRunData:()=>({outputs:w,dispatchGroup:{x:Math.ceil(o/l/64)},programUniforms:v})}},ap=(t,e)=>{rp(t.inputs);let r=[0];t.outputCount>1&&r.push(-3),t.outputCount>2&&r.push(-3),t.outputCount>3&&r.push(3),t.compute(np(t.inputs,e,t.outputCount,!1),{outputs:r})}}),ip,Qr,sp,rs,op,lp,up,dp,Mg=V(()=>{me(),Ce(),tt(),Se(),ip=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");if(e.axes.length!==0){if(e.axes.length!==e.starts.length||e.axes.length!==e.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(e.starts.length!==e.ends.length)throw new Error("starts and ends must have the same length");t.slice(1).forEach((r,n)=>{if(t[n+1].dataType!==6&&t[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Qr=(t,e)=>{let r=[];if(t.length>e)if(t[e].dataType===7)t[e].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(t[e].dataType===6)t[e].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${e} must be an array of int32 or int64`);return r},sp=(t,e)=>{if(t.length>1){let r=Qr(t,1),n=Qr(t,2),a=Qr(t,3);return a.length===0&&(a=[...Array(t[0].dims.length).keys()]),We({starts:r,ends:n,axes:a})}else return e},rs=(t,e,r,n,a)=>{let i=t;return t<0&&(i+=r[n[e]]),a[e]<0?Math.max(0,Math.min(i,r[n[e]]-1)):Math.max(0,Math.min(i,r[n[e]]))},op=(t,e,r)=>`fn calculateInputIndices(output_indices: ${e.type.indices}) -> ${t.type.indices} { + var input_indices: ${t.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${ge("uniforms.input_shape","i",r.length)}; + let steps_i = ${ge("uniforms.steps","i",r.length)}; + let signs_i = ${ge("uniforms.signs","i",r.length)}; + let starts_i = ${ge("uniforms.starts","i",r.length)}; + var output_index = ${e.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; + } + ${t.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,lp=(t,e)=>{let r=t[0].dims,n=j.size(r),a=e.axes.length>0?j.normalizeAxes(e.axes,r.length):[...Array(r.length).keys()],i=Qr(t,4);i.forEach(x=>x!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(a.length).fill(1));let s=e.starts.map((x,w)=>rs(x,w,r,a,i)),o=e.ends.map((x,w)=>rs(x,w,r,a,i));if(a.length!==s.length||a.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(a.length!==r.length)for(let x=0;xMath.sign(x));i.forEach((x,w,E)=>{if(x<0){let I=(o[w]-s[w])/x,k=s[w],A=k+I*i[w];s[w]=A,o[w]=k,E[w]=-x}});let d=r.slice(0);a.forEach((x,w)=>{d[x]=Math.ceil((o[x]-s[x])/i[x])});let p={dims:d,dataType:t[0].dataType},u=de("output",t[0].dataType,d.length),h=G("input",t[0].dataType,t[0].dims.length),m=j.size(d),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:i.length}],y=[{type:12,data:m},{type:12,data:s},{type:6,data:l},{type:12,data:i},...ce(t[0].dims,d)],v=x=>` + ${x.registerUniforms(_).declareVariables(h,u)} + ${op(h,u,r)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${u.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${u.setByOffset("global_idx",h.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${s.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:y})}},up=(t,e)=>{ip(t.inputs,e);let r=sp(t.inputs,e);t.compute(lp(t.inputs,r),{inputs:[0]})},dp=t=>{let e=t.starts,r=t.ends,n=t.axes;return We({starts:e,ends:r,axes:n})}}),cp,pp,hp,fp,Og=V(()=>{me(),Ce(),tt(),Se(),cp=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},pp=(t,e)=>{let r=t.dims,n=j.size(r),a=64,i=e.axis;if(i<0&&(i=r.length+i),ix===4?`max(max(${v}.x, ${v}.y), max(${v}.z, ${v}.w))`:x===2?`max(${v}.x, ${v}.y)`:x===3?`max(max(${v}.x, ${v}.y), ${v}.z)`:v,u=G("x",t.dataType,t.dims,l),h=de("result",t.dataType,t.dims,l),m=u.type.value,_=Ze(t.dataType)==="f32"?`var threadMax = ${m}(-3.402823e+38f);`:`var threadMax = ${m}(-65504.0h);`,y=v=>` + var rowMaxShared : ${m}; + var rowSumShared : ${m}; + var threadShared : array<${m}, ${a}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${m} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${m}) { + let index = row * row_stride + col; + result[index] = value; + } + ${v.registerUniform("packedCols","i32").declareVariables(u,h)} + ${v.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${a}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${_} + 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 = ${m}(${p("threadShared[0]",l)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${m}(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 = ${m}(${At("threadShared[0]",l)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`;return{name:"Softmax",shaderCache:{hint:`${l}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:t.dataType}],dispatchGroup:{x:o},programUniforms:[{type:12,data:d}]}),getShaderSource:y}},hp=(t,e)=>{cp(t.inputs),t.compute(pp(t.inputs[0],e))},fp=t=>We({axis:t.axis})}),mp,gp,_p,yp,wp,bp,vp,zg=V(()=>{me(),Ce(),tt(),Se(),mp=t=>{if(!t||t.length<1)throw new Error("too few inputs")},gp=(t,e)=>{let r=[],n=e.numOutputs;return t[1].dims[0]>0&&(t[1].getBigInt64Array().forEach(a=>r.push(Number(a))),n=r.length),We({numOutputs:n,axis:e.axis,splitSizes:r})},_p=t=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${t}u; i += 1u ) { + if (index < ${ge("uniforms.size_in_split_axis","i",t)}) { + return i; + } + } + return ${t}u; +}`,yp=t=>{let e=t.length,r=[];for(let n=0;n{let r=t[0].dims,n=j.size(r),a=t[0].dataType,i=j.normalizeAxis(e.axis,r.length),s=new Array(e.numOutputs),o=G("input",a,r.length),l=new Array(e.numOutputs),d=[],p=[],u=0,h=[{type:12,data:n}];for(let _=0;_` + ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)} + ${_p(l.length)} + ${yp(s)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${o.offsetToIndices("global_idx")}; + var index = ${o.indicesGet("indices",i)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${ge("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${o.indicesSet("indices",i,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:e.cacheKey,inputDependencies:["rank"]},getShaderSource:m,getRunData:()=>({outputs:d,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:h})}},bp=(t,e)=>{mp(t.inputs);let r=t.inputs.length===1?e:gp(t.inputs,e);t.compute(wp(t.inputs,r),{inputs:[0]})},vp=t=>{let e=t.axis,r=t.splitSizes,n=t.numOutputs<0?r.length:t.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return We({axis:e,numOutputs:n,splitSizes:r})}}),ns,$p,xp,Sp,Ep,Rg=V(()=>{me(),Ce(),Se(),ns=t=>Array.from(t.getBigInt64Array(),Number),$p=t=>{if(!t||t.length!==2)throw new Error("Tile requires 2 inputs.");if(t[0].dataType!==1&&t[0].dataType!==6&&t[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(t[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(t[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(ns(t[1]).length!==t[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},xp=(t,e)=>{let r=[];for(let n=0;n{let e=t[0].dims,r=ns(t[1]),n=xp(e,r),a=j.size(n),i=t[0].dataType,s=G("input",i,e.length),o=de("output",i,n.length),l=d=>` + const inputShape = ${s.indices(...e)}; + ${d.registerUniform("output_size","u32").declareVariables(s,o)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${o.offsetToIndices("global_idx")}; + var input_indices: ${s.type.indices}; + for (var i = 0; i < ${e.length}; i++) { + let input_dim_i = ${s.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${o.indicesGet("output_indices","i")} % input_dim_i; + + ${s.indicesSet("input_indices","i","input_dim_value")} + } + ${o.setByOffset("global_idx",s.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...ce(t[0].dims,n)]}),getShaderSource:l}},Ep=t=>{$p(t.inputs),t.compute(Sp(t.inputs),{inputs:[0]})}}),Cp,Ip,kp,Pg=V(()=>{me(),Ce(),Se(),Cp=(t,e,r,n,a)=>{let i=de("output_data",a,r.length,4),s=G("a_data",e[1].dataType,e[1].dims.length,4),o=G("b_data",e[2].dataType,e[2].dims.length,4),l=G("c_data",e[0].dataType,e[0].dims.length,4),d,p=(u,h,m)=>`select(${h}, ${u}, ${m})`;if(!n)d=i.setByOffset("global_idx",p(s.getByOffset("global_idx"),o.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(h,m,_="")=>{let y=`a_data[index_a${m}][component_a${m}]`,v=`b_data[index_b${m}][component_b${m}]`,x=`bool(c_data[index_c${m}] & (0xffu << (component_c${m} * 8)))`;return` + let output_indices${m} = ${i.offsetToIndices(`global_idx * 4u + ${m}u`)}; + let offset_a${m} = ${s.broadcastedIndicesToOffset(`output_indices${m}`,i)}; + let offset_b${m} = ${o.broadcastedIndicesToOffset(`output_indices${m}`,i)}; + let offset_c${m} = ${l.broadcastedIndicesToOffset(`output_indices${m}`,i)}; + let index_a${m} = offset_a${m} / 4u; + let index_b${m} = offset_b${m} / 4u; + let index_c${m} = offset_c${m} / 4u; + let component_a${m} = offset_a${m} % 4u; + let component_b${m} = offset_b${m} % 4u; + let component_c${m} = offset_c${m} % 4u; + ${h}[${m}] = ${_}(${p(y,v,x)}); + `};a===9?d=` + var data = vec4(0); + ${u("data",0,"u32")} + ${u("data",1,"u32")} + ${u("data",2,"u32")} + ${u("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:d=` + ${u("output_data[global_idx]",0)} + ${u("output_data[global_idx]",1)} + ${u("output_data[global_idx]",2)} + ${u("output_data[global_idx]",3)} + `}return` + ${t.registerUniform("vec_size","u32").declareVariables(l,s,o,i)} + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${d} + }`},Ip=t=>{let e=t[1].dims,r=t[2].dims,n=t[0].dims,a=t[1].dataType,i=!(j.areEqual(e,r)&&j.areEqual(r,n)),s=e,o=j.size(e);if(i){let d=Cr.calcShape(Cr.calcShape(e,r,!1),n,!1);if(!d)throw new Error("Can't perform where op on the given tensors");s=d,o=j.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>Cp(d,t,s,i,a),getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...ce(n,e,r,s)]})}},kp=t=>{t.compute(Ip(t.inputs))}}),Tp,Bg=V(()=>{ag(),Gl(),ig(),sg(),og(),lg(),ug(),fd(),fg(),mg(),gg(),_g(),yg(),wg(),bg(),vg(),$g(),xg(),dd(),Sg(),Eg(),Cg(),Ig(),kg(),xi(),Tg(),Ag(),Mg(),Og(),zg(),Rg(),Kr(),Ti(),Pg(),Tp=new Map([["Abs",[Zl]],["Acos",[Jl]],["Acosh",[eu]],["Add",[Nu]],["ArgMax",[Bl,Ei]],["ArgMin",[Pl,Ei]],["Asin",[tu]],["Asinh",[ru]],["Atan",[nu]],["Atanh",[au]],["Attention",[Wl]],["AveragePool",[kc,Ic]],["BatchNormalization",[jl]],["BiasAdd",[Xl]],["BiasSplitGelu",[Pu]],["Cast",[su,iu]],["Ceil",[uu]],["Clip",[lu]],["Concat",[Zu,Ju]],["Conv",[Ui,Li]],["ConvTranspose",[Cd,vd]],["Cos",[du]],["Cosh",[cu]],["CumSum",[kd,Td]],["Div",[Lu]],["Einsum",[Pd,Bd]],["Elu",[pu,na]],["Equal",[Uu]],["Erf",[hu]],["Exp",[fu]],["Expand",[Ud]],["FastGelu",[Wd]],["Floor",[mu]],["FusedConv",[Ui,Li]],["Gather",[qd,Hd]],["GatherElements",[Xd,Yd]],["Gelu",[gu]],["Gemm",[ec,Jd]],["GlobalAveragePool",[Ac,Tc]],["GlobalMaxPool",[Rc,zc]],["Greater",[Vu]],["GreaterOrEqual",[qu]],["HardSigmoid",[Su,xu]],["InstanceNormalization",[ac]],["LayerNormalization",[oc]],["LeakyRelu",[_u,na]],["Less",[Hu]],["LessOrEqual",[ju]],["Log",[Ou]],["MatMul",[ud]],["MatMulNBits",[dc,cc]],["MaxPool",[Mc,Oc]],["Mul",[Fu]],["MultiHeadAttention",[mc,hc]],["Neg",[wu]],["Not",[yu]],["Pad",[Sc]],["Pow",[Wu]],["Range",[Dc]],["Reciprocal",[bu]],["ReduceMin",[Al]],["ReduceMean",[El]],["ReduceMax",[Tl]],["ReduceSum",[Ol]],["ReduceProd",[Ml]],["ReduceL1",[Cl]],["ReduceL2",[Il]],["ReduceLogSum",[Rl]],["ReduceLogSumExp",[kl]],["ReduceSumSquare",[zl]],["Relu",[vu]],["Resize",[ep,tp]],["Sigmoid",[$u]],["Sin",[Eu]],["Sinh",[Cu]],["Slice",[up,dp]],["SkipLayerNormalization",[ap]],["Split",[bp,vp]],["Sqrt",[Iu]],["Softmax",[hp,fp]],["Sub",[Gu]],["Tan",[ku]],["Tanh",[Tu]],["ThresholdedRelu",[Mu,na]],["Tile",[Ep]],["Transpose",[qo,jo]],["Where",[kp]]])}),Ap,Dg=V(()=>{xt(),ir(),Se(),Ap=class{constructor(t){this.backend=t,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,r,n,a){$t(t.programInfo.name);let i=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let o=[];for(let d of e)o.push({binding:o.length,resource:{buffer:d.buffer}});for(let d of r)o.push({binding:o.length,resource:{buffer:d.buffer}});a&&o.push({binding:o.length,resource:a});let l=i.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:o,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:l,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}s.setPipeline(t.computePipeline),s.setBindGroup(0,l),s.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),ft(t.programInfo.name)}dispose(){}build(t,e){$t(t.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let a=Wo(e),i=t.getShaderSource(a),s=`${n.join(` +`)} +${a.additionalImplementations} +${i}`,o=r.createShaderModule({code:s,label:t.name});Ke("verbose",()=>`[WebGPU] ${t.name} shader code: ${s}`);let l=r.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:t.name});return ft(t.name),{programInfo:t,computePipeline:l}}normalizeDispatchGroupSize(t){let e=typeof t=="number"?t:t.x,r=typeof t=="number"?1:t.y||1,n=typeof t=="number"?1:t.z||1,a=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=a&&r<=a&&n<=a)return[e,r,n];let i=e*r*n,s=Math.ceil(Math.sqrt(i));if(s>a){if(s=Math.ceil(Math.cbrt(i)),s>a)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}else return[s,s,1]}}}),Mp,Op,zp,Rp,Ng=V(()=>{xt(),me(),ir(),tg(),rg(),Bg(),Dg(),Mp=(t,e)=>{if(e.length!==t.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${t.length}.`);let r=[];for(let n=0;n{let n=t.name;return t.shaderCache?.hint&&(n+="["+t.shaderCache.hint+"]"),n+=":"+r+`:${Mp(e,t.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,n},zp=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Rp=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,e){this.env=t;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};e.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):e.features.has("timestamp-query")&&r.push("timestamp-query"),e.features.has("shader-f16")&&r.push("shader-f16"),this.device=await e.requestDevice(n),this.adapterInfo=new zp(await e.requestAdapterInfo()),this.gpuDataManager=Do(this),this.programManager=new Ap(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Oo(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:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;$t(),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 e=new BigUint64Array(t.getMappedRange()),r=this.pendingQueries.get(t);for(let n=0;n"u"&&(this.queryTimeBase=h);let _=Number(h-this.queryTimeBase),y=Number(m-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(y))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:p.map(v=>({dims:v.dims,dataType:ar(v.dataType)})),outputsMetadata:u.map(v=>({dims:v.dims,dataType:ar(v.dataType)})),kernelId:i,kernelType:o,kernelName:l,programName:d,startTime:_,endTime:y});else{let v="";p.forEach((w,E)=>{v+=`input[${E}]: [${w.dims}] | ${ar(w.dataType)}, `});let x="";u.forEach((w,E)=>{x+=`output[${E}]: [${w.dims}] | ${ar(w.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${l}|${d}" ${v}${x}execution time: ${y-_} ns`)}Gr("GPU",`${d}::${h}::${m}`)}t.unmap(),this.pendingQueries.delete(t)}),ft()}run(t,e,r,n,a){$t(t.name);let i=[];for(let x=0;xw):r;if(d.length!==s.length)throw new Error(`Output size ${d.length} must be equal to ${s.length}.`);let p=[],u=[];for(let x=0;x=s.length)throw new Error(`Invalid output index: ${d[x]}`);if(d[x]===-3)continue;let w=d[x]===-1,E=d[x]===-2,I=w||E?a(s[x].dataType,s[x].dims):n(d[x],s[x].dataType,s[x].dims);if(p.push(I),I.data===0)continue;let k=this.gpuDataManager.get(I.data);if(!k)throw new Error(`no GPU data for output: ${I.data}`);if(w&&this.temporaryData.push(k),E){let A=this.kernelPersistentData.get(this.currentKernelId);A||(A=[],this.kernelPersistentData.set(this.currentKernelId,A)),A.push(k)}u.push(k)}if(i.length!==e.length||u.length!==p.length){if(u.length===0)return ft(t.name),p;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let h;if(l){let x=0,w=[];l.forEach(A=>{let D=typeof A.data=="number"?[A.data]:A.data;if(D.length===0)return;let L=A.type===10?2:4,Y,H;A.type===10?(H=D.length>4?16:D.length>2?8:D.length*L,Y=D.length>4?16:L*D.length):(H=D.length<=2?D.length*L:16,Y=16),x=Math.ceil(x/H)*H,w.push(x);let re=A.type===10?8:4;x+=D.length>4?Math.ceil(D.length/re)*Y:D.length*L});let E=16;x=Math.ceil(x/E)*E;let I=new ArrayBuffer(x);l.forEach((A,D)=>{let L=w[D],Y=typeof A.data=="number"?[A.data]:A.data;if(A.type===6)new Int32Array(I,L,Y.length).set(Y);else if(A.type===12)new Uint32Array(I,L,Y.length).set(Y);else if(A.type===10)new Uint16Array(I,L,Y.length).set(Y);else if(A.type===1)new Float32Array(I,L,Y.length).set(Y);else throw new Error(`Unsupported uniform type: ${ar(A.type)}`)});let k=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(k.buffer,0,I,0,x),this.gpuDataManager.release(k.id),h={offset:0,size:x,buffer:k.buffer}}let m=this.programManager.normalizeDispatchGroupSize(o),_=m[1]===1&&m[2]===1,y=Op(t,e,_),v=this.programManager.getArtifact(y);if(v||(v=this.programManager.build(t,m),this.programManager.setArtifact(y,v),Ke("info",()=>`[artifact] key: ${y}, programName: ${t.name}`)),Ke("info",()=>`[ProgramManager] run "${t.name}" (key=${y}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let x={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:e,outputTensorViews:p};this.pendingKernels.push(x),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(x)}return this.programManager.run(v,i,u,m,h),ft(t.name),p}upload(t,e){this.gpuDataManager.upload(t,e)}memcpy(t,e){this.gpuDataManager.memcpy(t,e)}async download(t,e){await this.gpuDataManager.download(t,e)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,e,r,n){let a=Tp.get(t);if(!a)throw new Error(`kernel not implemented: ${t}`);let i={kernelType:t,kernelName:n,kernelEntry:a[0],attributes:[a[1],r]};this.kernels.set(e,i)}releaseKernel(t){let e=this.kernelPersistentData.get(t);if(e){for(let r of e)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,e,r){let n=this.kernels.get(t);if(!n)throw new Error(`kernel not created: ${t}`);let a=n.kernelType,i=n.kernelName,s=n.kernelEntry,o=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${a}] ${i}" is not allowed to be called recursively`);this.currentKernelId=t,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),Ke("info",()=>`[WebGPU] Start to run kernel "[${a}] ${i}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),s(e,o[1]),0}catch(d){return r.push(Promise.resolve(`[WebGPU] Kernel "[${a}] ${i}" failed. ${d}`)),1}finally{l&&r.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${a}] ${i}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,e,r,n){let a=this.sessionExternalDataMapping.get(t);a||(a=new Map,this.sessionExternalDataMapping.set(t,a));let i=a.get(e),s=this.gpuDataManager.registerExternalBuffer(r,n,i?.[1]);return a.set(e,[s,r]),s}unregisterBuffers(t){let e=this.sessionExternalDataMapping.get(t);e&&(e.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let e=this.gpuDataManager.get(t);if(!e)throw new Error(`no GPU data for buffer: ${t}`);return e.buffer}createDownloader(t,e,r){return async()=>{let n=await _i(this,t,e);return Ro(n.buffer,r)}}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(){Ke("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(){Ke("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ke("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),r=t.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}}),Pp={};Er(Pp,{init:()=>Dp});var pa,Bp,Dp,Lg=V(()=>{me(),Ng(),ir(),Ce(),pa=class om{constructor(e,r,n,a){this.module=e,this.dataType=r,this.data=n,this.dims=a}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=j.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=j.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=j.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(j.size(e)!==j.size(this.dims))throw new Error("Invalid new shape");return new om(this.module,this.dataType,this.data,e)}},Bp=class{constructor(t,e,r){this.module=t,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let n=t.HEAPU32,a=r>>>2;this.opKernelContext=n[a++];let i=n[a++];this.outputCount=n[a++],this.customDataOffset=n[a++],this.customDataSize=n[a++];let s=[];for(let o=0;otypeof s=="number"?this.inputs[s]:s)??this.inputs,n=e?.outputs??[],a=(s,o,l)=>new pa(this.module,o,this.output(s,l),l),i=(s,o)=>{let l=Kn(s);if(!l)throw new Error(`Unsupported data type: ${s}`);let d=l*j.size(o),p=d>0?this.backend.gpuDataManager.create(d).id:0;return new pa(this.module,s,p,o)};return this.backend.run(t,r,n,a,i)}output(t,e){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+e.length)*4),a=n>>2;this.module.HEAPU32[a++]=e.length;for(let i=0;i{let a=e.jsepInit;if(!a)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(t==="webgpu"){let i=new Rp;await i.initialize(r,n),a("webgpu",[i,s=>i.alloc(s),s=>i.free(s),(s,o,l,d=!1)=>{if(d)Ke("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${o}, size=${l}`),i.memcpy(s,o);else{Ke("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${o}, size=${l}`);let p=e.HEAPU8.subarray(s>>>0,(s>>>0)+l);i.upload(o,p)}},async(s,o,l)=>{Ke("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${o}, size=${l}`),await i.download(s,()=>e.HEAPU8.subarray(o>>>0,(o>>>0)+l))},(s,o,l)=>i.createKernel(s,o,l,e.UTF8ToString(e._JsepGetNodeName(o))),s=>i.releaseKernel(s),(s,o,l,d)=>{Ke("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${s}, contextDataOffset=${o}`);let p=new Bp(e,i,o);return i.computeKernel(s,p,d)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else a("webnn")}}),Np,Lp,Up,Vt,Fp,as,Wp,Gp,is,Vp,Hp,qp,Ug=V(()=>{Jm(),eg(),me(),Hr(),di(),Io(),Np=(t,e)=>{Xe()._OrtInit(t,e)!==0&&Ne("Can't initialize onnxruntime.")},Lp=async t=>{Np(t.wasm.numThreads,Yn(t.logLevel))},Up=async(t,e)=>{{let r=(Lg(),tr(Pp)).init;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=t.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 a=t.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let i=t.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:a,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.')}if(!t.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",Xe(),t,n)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Xe(),t)}}},Vt=new Map,Fp=t=>{let e=Xe(),r=e.stackSave();try{let n=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,n,n+4)!==0&&Ne("Can't get session input/output count."),[e.HEAP32[n/4],e.HEAP32[n/4+1]]}finally{e.stackRestore(r)}},as=t=>{let e=Xe(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Wp=async(t,e)=>{let r,n,a=Xe();Array.isArray(t)?[r,n]=t:t.buffer===a.HEAPU8.buffer?[r,n]=[t.byteOffset,t.byteLength]:[r,n]=as(t);let i=0,s=0,o=0,l=[],d=[],p=[];try{if([s,l]=Co(e),e?.externalData&&a.mountExternalData){let w=[];for(let E of e.externalData){let I=typeof E=="string"?E:E.path;w.push(Xn(typeof E=="string"?E:E.data).then(k=>{a.mountExternalData(I,k)}))}await Promise.all(w)}i=await a._OrtCreateSession(r,n,s),i===0&&Ne("Can't create a session.");let[u,h]=Fp(i),m=!!e?.enableGraphCapture,_=[],y=[],v=[];for(let w=0;ww==="gpu-buffer")&&(o=a._OrtCreateBinding(i),o===0&&Ne("Can't create IO binding."),x={handle:o,outputPreferredLocations:v,outputPreferredLocationsEncoded:v.map(w=>fi(w))}),Vt.set(i,[i,d,p,x,m,!1]),[i,_,y]}catch(u){throw d.forEach(h=>a._OrtFree(h)),p.forEach(h=>a._OrtFree(h)),o!==0&&a._OrtReleaseBinding(o),i!==0&&a._OrtReleaseSession(i),u}finally{a._free(r),s!==0&&a._OrtReleaseSessionOptions(s),l.forEach(u=>a._free(u)),a.unmountExternalData?.()}},Gp=t=>{let e=Xe(),r=Vt.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[n,a,i,s,o]=r;s&&(o&&e._OrtClearBoundOutputs(s.handle),e._OrtReleaseBinding(s.handle)),e.jsepOnReleaseSession?.(t),a.forEach(l=>e._OrtFree(l)),i.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(n),Vt.delete(t)},is=(t,e,r,n,a,i=!1)=>{if(!t){e.push(0);return}let s=Xe(),o=t[0],l=t[1],d=t[3],p,u;if(o==="string"&&d==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let _=t[2].gpuBuffer,y=Kn(ci(o));u=l.reduce((x,w)=>x*w,1)*y;let v=s.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=v(n,a,_,u)}else{let _=t[2];if(Array.isArray(_)){u=4*_.length,p=s._malloc(u),r.push(p);let y=p/4;for(let v=0;v<_.length;v++){if(typeof _[v]!="string")throw new TypeError(`tensor data at index ${v} is not a string`);s.HEAPU32[y++]=je(_[v],r)}}else u=_.byteLength,p=s._malloc(u),r.push(p),s.HEAPU8.set(new Uint8Array(_.buffer,_.byteOffset,u),p)}let h=s.stackSave(),m=s.stackAlloc(4*l.length);try{let _=m/4;l.forEach(v=>s.HEAP32[_++]=v);let y=s._OrtCreateTensor(ci(o),p,u,m,l.length,fi(d));y===0&&Ne(`Can't create tensor for input/output. session=${n}, index=${a}.`),e.push(y)}finally{s.stackRestore(h)}},Vp=async(t,e,r,n,a,i)=>{let s=Xe(),o=Vt.get(t);if(!o)throw new Error(`cannot run inference. invalid session id: ${t}`);let l=o[0],d=o[1],p=o[2],u=o[3],h=o[4],m=o[5],_=e.length,y=n.length,v=0,x=[],w=[],E=[],I=[],k=s.stackSave(),A=s.stackAlloc(_*4),D=s.stackAlloc(_*4),L=s.stackAlloc(y*4),Y=s.stackAlloc(y*4);try{[v,x]=vo(i);for(let q=0;q<_;q++)is(r[q],w,I,t,e[q],h);for(let q=0;qLe*qe,1);B=ar(ze);let ut=u?.outputPreferredLocations[n[q]];if(B==="string"){if(ut==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Le=[],qe=Q/4;for(let it=0;it0){let Le=s.jsepGetBuffer;if(!Le)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let qe=Le(Q),it=Kn(ze);if(it===void 0||!hi(B))throw new Error(`Unsupported data type: ${B}`);te=!0,Ae.push([B,Ve,{gpuBuffer:qe,download:s.jsepCreateDownloader(qe,at*it,B),dispose:()=>{s._OrtReleaseTensor(J)}},"gpu-buffer"])}else{let Le=pi(B),qe=new Le(at);new Uint8Array(qe.buffer,qe.byteOffset,qe.byteLength).set(s.HEAPU8.subarray(Q,Q+qe.byteLength)),Ae.push([B,Ve,qe,"cpu"])}}finally{s.stackRestore(ae),B==="string"&&Q&&s._free(Q),te||s._OrtReleaseTensor(J)}}return u&&!h&&(s._OrtClearBoundOutputs(u.handle),Vt.set(t,[l,d,p,u,h,!1])),Ae}finally{s.stackRestore(k),w.forEach(H=>s._OrtReleaseTensor(H)),E.forEach(H=>s._OrtReleaseTensor(H)),I.forEach(H=>s._free(H)),v!==0&&s._OrtReleaseRunOptions(v),x.forEach(H=>s._free(H))}},Hp=t=>{let e=Xe(),r=Vt.get(t);if(!r)throw new Error("invalid session id");let n=r[0],a=e._OrtEndProfiling(n);a===0&&Ne("Can't get an profile file name."),e._OrtFree(a)},qp=t=>{let e=[];for(let r of t){let n=r[2];!Array.isArray(n)&&"buffer"in n&&e.push(n.buffer)}return e}}),Fg=Sr((t,e)=>{e.exports='/*!\n * ONNX Runtime Web v1.17.3\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var vn=Object.defineProperty;var dd=Object.getOwnPropertyDescriptor;var ld=Object.getOwnPropertyNames;var cd=Object.prototype.hasOwnProperty;var q=(e,t)=>()=>(e&&(t=e(e=0)),t);var pr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Mr=(e,t)=>{for(var r in t)vn(e,r,{get:t[r],enumerable:!0})},pd=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ld(t))!cd.call(e,n)&&n!==r&&vn(e,n,{get:()=>t[n],enumerable:!(o=dd(t,n))||o.enumerable});return e};var Ft=e=>pd(vn({},"__esModule",{value:!0}),e);var $n={};Mr($n,{createReadStream:()=>Po,readFile:()=>md,readFileSync:()=>fd});var md,fd,Po,_n=q(()=>{md=void 0,fd=void 0,Po=void 0});var xn={};Mr(xn,{join:()=>hd});var hd,Sn=q(()=>{hd=void 0});var Ro=pr((ko,Cn)=>{"use strict";var Oo=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){var r=t,o,n;r.ready=new Promise((d,h)=>{o=d,n=h}),r.mountExternalData=(d,h)=>{(r.Fa||(r.Fa=new Map)).set(d,h)},r.unmountExternalData=()=>{delete r.Fa};let s=()=>{let d=(w,S,P)=>(...N)=>{let K=nt,X=S?.();N=w(...N);let ae=S?.();return X!==ae&&(w=ae,P(X),S=P=null),nt!=K?Cr():N},h=w=>async(...S)=>{try{if(r.Ea)throw Error("Session already started");let P=r.Ea={Za:S[0],errors:[]},N=await w(...S);if(r.Ea!==P)throw Error("Session mismatch");r.La?.flush();let K=P.errors;if(0ae),0r._OrtCreateSession,w=>r._OrtCreateSession=w),r._OrtRun=h(d(r._OrtRun,()=>r._OrtRun,w=>r._OrtRun=w)),r._OrtRunWithBinding=h(d(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,w=>r._OrtRunWithBinding=w)),r._OrtBindInput=d(r._OrtBindInput,()=>r._OrtBindInput,w=>r._OrtBindInput=w),s=void 0};r.jsepInit=(d,h)=>{if(s?.(),d==="webgpu"){[r.La,r.Ra,r.Va,r.Ma,r.Ua,r.sa,r.Wa,r.Ya,r.Sa,r.Ta,r.Xa]=h;let w=r.La;r.jsepRegisterBuffer=(S,P,N,K)=>w.registerBuffer(S,P,N,K),r.jsepGetBuffer=S=>w.getBuffer(S),r.jsepCreateDownloader=(S,P,N)=>w.createDownloader(S,P,N),r.jsepOnReleaseSession=S=>{w.onReleaseSession(S)},r.jsepOnRunStart=S=>w.onRunStart(S)}};var u=Object.assign({},r),l="./this.program",a=(d,h)=>{throw h},p=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",b="",_,y,$;if(f){var I=(_n(),Ft($n)),C=(Sn(),Ft(xn));b=m?C.dirname(b)+"/":__dirname+"/",_=(d,h)=>(d=Ae(d)?new URL(d):C.normalize(d),I.readFileSync(d,h?void 0:"utf8")),$=d=>(d=_(d,!0),d.buffer||(d=new Uint8Array(d)),d),y=(d,h,w,S=!0)=>{d=Ae(d)?new URL(d):C.normalize(d),I.readFile(d,S?void 0:"utf8",(P,N)=>{P?w(P):h(S?N.buffer:N)})},!r.thisProgram&&1{throw process.exitCode=d,h},r.inspect=()=>"[Emscripten Module object]"}else(p||m)&&(m?b=self.location.href:typeof document<"u"&&document.currentScript&&(b=document.currentScript.src),e&&(b=e),b.indexOf("blob:")!==0?b=b.substr(0,b.replace(/[?#].*/,"").lastIndexOf("/")+1):b="",_=d=>{var h=new XMLHttpRequest;return h.open("GET",d,!1),h.send(null),h.responseText},m&&($=d=>{var h=new XMLHttpRequest;return h.open("GET",d,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),y=(d,h,w)=>{var S=new XMLHttpRequest;S.open("GET",d,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?h(S.response):w()},S.onerror=w,S.send(null)});var v=console.log.bind(console),A=console.error.bind(console);Object.assign(r,u),u=null,typeof WebAssembly!="object"&&se("no native wasm support detected");var T,D=!1,U,V,H,R,L,pe,Ie;function we(){var d=T.buffer;r.HEAP8=V=new Int8Array(d),r.HEAP16=new Int16Array(d),r.HEAPU8=H=new Uint8Array(d),r.HEAPU16=new Uint16Array(d),r.HEAP32=R=new Int32Array(d),r.HEAPU32=L=new Uint32Array(d),r.HEAPF32=pe=new Float32Array(d),r.HEAPF64=Ie=new Float64Array(d)}var ne=[],ze=[],Q=[],xe=0,me=null,ue=null;function se(d){throw d="Aborted("+d+")",A(d),D=!0,U=1,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),n(d),d}var he=d=>d.startsWith("data:application/octet-stream;base64,"),Ae=d=>d.startsWith("file://"),He;if(He="ort-wasm-simd.wasm",!he(He)){var G=He;He=r.locateFile?r.locateFile(G,b):b+G}function J(d){if($)return $(d);throw"both async and sync fetching of the wasm failed"}function Se(d){if(p||m){if(typeof fetch=="function"&&!Ae(d))return fetch(d,{credentials:"same-origin"}).then(h=>{if(!h.ok)throw"failed to load wasm binary file at \'"+d+"\'";return h.arrayBuffer()}).catch(()=>J(d));if(y)return new Promise((h,w)=>{y(d,S=>h(new Uint8Array(S)),w)})}return Promise.resolve().then(()=>J(d))}function Qe(d,h,w){return Se(d).then(S=>WebAssembly.instantiate(S,h)).then(S=>S).then(w,S=>{A(`failed to asynchronously prepare wasm: ${S}`),se(S)})}function Xe(d,h){var w=He;return typeof WebAssembly.instantiateStreaming!="function"||he(w)||Ae(w)||f||typeof fetch!="function"?Qe(w,d,h):fetch(w,{credentials:"same-origin"}).then(S=>WebAssembly.instantiateStreaming(S,d).then(h,function(P){return A(`wasm streaming compile failed: ${P}`),A("falling back to ArrayBuffer instantiation"),Qe(w,d,h)}))}var Le,wt={931760:(d,h,w,S)=>{if(typeof r>"u"||!r.Fa)return 1;if(d=qe(d>>>0),d.startsWith("./")&&(d=d.substring(2)),d=r.Fa.get(d),!d)return 2;if(h>>>=0,w>>>=0,h+w>d.byteLength)return 3;try{return H.set(d.subarray(h,h+w),S>>>0>>>0),0}catch{return 4}},932261:()=>{r.Sa()},932292:()=>{r.Ta()},932321:()=>{r.Xa()},932346:d=>r.Ra(d),932379:d=>r.Va(d),932411:(d,h,w)=>{r.Ma(d,h,w,!0)},932450:(d,h,w)=>{r.Ma(d,h,w)},932483:d=>{r.sa("Abs",d,void 0)},932534:d=>{r.sa("Neg",d,void 0)},932585:d=>{r.sa("Floor",d,void 0)},932638:d=>{r.sa("Ceil",d,void 0)},932690:d=>{r.sa("Reciprocal",d,void 0)},932748:d=>{r.sa("Sqrt",d,void 0)},932800:d=>{r.sa("Exp",d,void 0)},932851:d=>{r.sa("Erf",d,void 0)},932902:d=>{r.sa("Sigmoid",d,void 0)},932957:(d,h,w)=>{r.sa("HardSigmoid",d,{alpha:h,beta:w})},933036:d=>{r.sa("Log",d,void 0)},933087:d=>{r.sa("Sin",d,void 0)},933138:d=>{r.sa("Cos",d,void 0)},933189:d=>{r.sa("Tan",d,void 0)},933240:d=>{r.sa("Asin",d,void 0)},933292:d=>{r.sa("Acos",d,void 0)},933344:d=>{r.sa("Atan",d,void 0)},933396:d=>{r.sa("Sinh",d,void 0)},933448:d=>{r.sa("Cosh",d,void 0)},933500:d=>{r.sa("Asinh",d,void 0)},933553:d=>{r.sa("Acosh",d,void 0)},933606:d=>{r.sa("Atanh",d,void 0)},933659:d=>{r.sa("Tanh",d,void 0)},933711:d=>{r.sa("Not",d,void 0)},933762:(d,h,w)=>{r.sa("Clip",d,{min:h,max:w})},933831:d=>{r.sa("Clip",d,void 0)},933883:(d,h)=>{r.sa("Elu",d,{alpha:h})},933941:d=>{r.sa("Relu",d,void 0)},933993:(d,h)=>{r.sa("LeakyRelu",d,{alpha:h})},934057:(d,h)=>{r.sa("ThresholdedRelu",d,{alpha:h})},934127:(d,h)=>{r.sa("Cast",d,{to:h})},934185:d=>{r.sa("Add",d,void 0)},934236:d=>{r.sa("Sub",d,void 0)},934287:d=>{r.sa("Mul",d,void 0)},934338:d=>{r.sa("Div",d,void 0)},934389:d=>{r.sa("Pow",d,void 0)},934440:d=>{r.sa("Equal",d,void 0)},934493:d=>{r.sa("Greater",d,void 0)},934548:d=>{r.sa("GreaterOrEqual",d,void 0)},934610:d=>{r.sa("Less",d,void 0)},934662:d=>{r.sa("LessOrEqual",d,void 0)},934721:(d,h,w,S,P)=>{r.sa("ReduceMean",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},934880:(d,h,w,S,P)=>{r.sa("ReduceMax",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935038:(d,h,w,S,P)=>{r.sa("ReduceMin",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935196:(d,h,w,S,P)=>{r.sa("ReduceProd",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935355:(d,h,w,S,P)=>{r.sa("ReduceSum",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935513:(d,h,w,S,P)=>{r.sa("ReduceL1",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935670:(d,h,w,S,P)=>{r.sa("ReduceL2",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935827:(d,h,w,S,P)=>{r.sa("ReduceLogSum",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},935988:(d,h,w,S,P)=>{r.sa("ReduceSumSquare",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},936152:(d,h,w,S,P)=>{r.sa("ReduceLogSumExp",d,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},936316:d=>{r.sa("Where",d,void 0)},936369:(d,h,w)=>{r.sa("Transpose",d,{perm:h?Array.from(R.subarray(h>>>0,w>>>0)):[]})},936477:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe)=>{r.sa("ConvTranspose",d,{format:ae?"NHWC":"NCHW",autoPad:h,dilations:[w],group:S,kernel_shape:[P],pads:[N,K],strides:[X],wIsConst:()=>!!V[de>>>0],outputPadding:fe?Array.from(R.subarray(fe>>>0,Oe>>>0)):[],outputShape:Re?Array.from(R.subarray(Re>>>0,O>>>0)):[],activation:qe(oe)})},936879:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O)=>{r.sa("ConvTranspose",d,{format:X?"NHWC":"NCHW",autoPad:h,dilations:Array.from(R.subarray(w>>>0,(w>>>0)+2>>>0)),group:S,kernelShape:Array.from(R.subarray(P>>>0,(P>>>0)+2>>>0)),pads:Array.from(R.subarray(N>>>0,(N>>>0)+4>>>0)),strides:Array.from(R.subarray(K>>>0,(K>>>0)+2>>>0)),wIsConst:()=>!!V[ae>>>0],outputPadding:de?Array.from(R.subarray(de>>>0,fe>>>0)):[],outputShape:Oe?Array.from(R.subarray(Oe>>>0,Re>>>0)):[],activation:qe(O)})},937444:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe)=>{r.sa("ConvTranspose",d,{format:ae?"NHWC":"NCHW",autoPad:h,dilations:[w],group:S,kernel_shape:[P],pads:[N,K],strides:[X],wIsConst:()=>!!V[de>>>0],outputPadding:fe?Array.from(R.subarray(fe>>>0,Oe>>>0)):[],outputShape:Re?Array.from(R.subarray(Re>>>0,O>>>0)):[],activation:qe(oe)})},937846:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O)=>{r.sa("ConvTranspose",d,{format:X?"NHWC":"NCHW",autoPad:h,dilations:Array.from(R.subarray(w>>>0,(w>>>0)+2>>>0)),group:S,kernelShape:Array.from(R.subarray(P>>>0,(P>>>0)+2>>>0)),pads:Array.from(R.subarray(N>>>0,(N>>>0)+4>>>0)),strides:Array.from(R.subarray(K>>>0,(K>>>0)+2>>>0)),wIsConst:()=>!!V[ae>>>0],outputPadding:de?Array.from(R.subarray(de>>>0,fe>>>0)):[],outputShape:Oe?Array.from(R.subarray(Oe>>>0,Re>>>0)):[],activation:qe(O)})},938411:(d,h)=>{r.sa("GlobalAveragePool",d,{format:h?"NHWC":"NCHW"})},938502:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("AveragePool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},938786:(d,h)=>{r.sa("GlobalAveragePool",d,{format:h?"NHWC":"NCHW"})},938877:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("AveragePool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},939161:(d,h)=>{r.sa("GlobalMaxPool",d,{format:h?"NHWC":"NCHW"})},939248:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("MaxPool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},939528:(d,h)=>{r.sa("GlobalMaxPool",d,{format:h?"NHWC":"NCHW"})},939615:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("MaxPool",d,{format:Ce?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:P,dilations:[N,K],kernel_shape:[X,ae],pads:[de,fe,Oe,Re],strides:[O,oe]})},939895:(d,h,w,S,P)=>{r.sa("Gemm",d,{alpha:h,beta:w,transA:S,transB:P})},939999:d=>{r.sa("MatMul",d,void 0)},940053:(d,h,w,S)=>{r.sa("ArgMax",d,{keepDims:!!h,selectLastIndex:!!w,axis:S})},940161:(d,h,w,S)=>{r.sa("ArgMin",d,{keepDims:!!h,selectLastIndex:!!w,axis:S})},940269:(d,h)=>{r.sa("Softmax",d,{axis:h})},940332:(d,h)=>{r.sa("Concat",d,{axis:h})},940392:(d,h,w,S,P)=>{r.sa("Split",d,{axis:h,numOutputs:w,splitSizes:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},940532:d=>{r.sa("Expand",d,void 0)},940586:(d,h)=>{r.sa("Gather",d,{axis:Number(h)})},940657:(d,h)=>{r.sa("GatherElements",d,{axis:Number(h)})},940736:(d,h,w,S,P,N,K,X,ae,de,fe)=>{r.sa("Resize",d,{antialias:h,axes:w?Array.from(R.subarray(w>>>0,S>>>0)):[],coordinateTransformMode:qe(P),cubicCoeffA:N,excludeOutside:K,extrapolationValue:X,keepAspectRatioPolicy:qe(ae),mode:qe(de),nearestMode:qe(fe)})},941082:(d,h,w,S,P,N,K)=>{r.sa("Slice",d,{starts:h?Array.from(R.subarray(h>>>0,w>>>0)):[],ends:S?Array.from(R.subarray(S>>>0,P>>>0)):[],axes:N?Array.from(R.subarray(N>>>0,K>>>0)):[]})},941298:d=>{r.sa("Tile",d,void 0)},941350:(d,h,w)=>{r.sa("LayerNormalization",d,{axis:Number(h),epsilon:Number(w)})},941457:(d,h,w)=>{r.sa("InstanceNormalization",d,{epsilon:h,format:w?"NHWC":"NCHW"})},941571:(d,h,w)=>{r.sa("InstanceNormalization",d,{epsilon:h,format:w?"NHWC":"NCHW"})},941685:d=>{r.sa("Range",d,void 0)},941738:(d,h)=>{r.sa("Einsum",d,{equation:qe(h)})},941819:(d,h,w,S,P)=>{r.sa("Pad",d,{mode:h,value:w,pads:S?Array.from(R.subarray(S>>>0,P>>>0)):[]})},941946:(d,h,w,S,P,N)=>{r.sa("BatchNormalization",d,{epsilon:h,momentum:w,spatial:!!P,trainingMode:!!S,format:N?"NHWC":"NCHW"})},942115:(d,h,w,S,P,N)=>{r.sa("BatchNormalization",d,{epsilon:h,momentum:w,spatial:!!P,trainingMode:!!S,format:N?"NHWC":"NCHW"})},942284:(d,h,w)=>{r.sa("CumSum",d,{exclusive:Number(h),reverse:Number(w)})},942381:(d,h,w,S,P,N,K,X,ae)=>{r.sa("Attention",d,{numHeads:h,isUnidirectional:w,maskFilterValue:S,scale:P,doRotary:N,qkvHiddenSizes:K?Array.from(R.subarray(Number(X)>>>0,Number(X)+K>>>0)):[],pastPresentShareBuffer:!!ae})},942653:d=>{r.sa("BiasAdd",d,void 0)},942708:d=>{r.sa("BiasSplitGelu",d,void 0)},942769:d=>{r.sa("FastGelu",d,void 0)},942825:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re)=>{r.sa("Conv",d,{format:ae?"NHWC":"NCHW",auto_pad:h,dilations:[w],group:S,kernel_shape:[P],pads:N?Array.from(R.subarray(N>>>0,K>>>0)):[],strides:[X],w_is_const:()=>!!V[de>>>0],activation:qe(fe),activation_params:Oe?Array.from(pe.subarray(Oe>>>0,Re>>>0)):[]})},943195:(d,h,w,S,P,N,K,X,ae,de,fe,Oe,Re,O,oe,Ce)=>{r.sa("Conv",d,{format:Oe?"NHWC":"NCHW",auto_pad:h,dilations:[w,S],group:P,kernel_shape:[N,K],pads:X?Array.from(R.subarray(X>>>0,ae>>>0)):[],strides:[de,fe],w_is_const:()=>!!V[Re>>>0],activation:qe(O),activation_params:oe?Array.from(pe.subarray(oe>>>0,Ce>>>0)):[]})},943586:d=>{r.sa("Gelu",d,void 0)},943638:(d,h,w,S,P,N)=>{r.sa("MatMulNBits",d,{k:h,n:w,accuracyLevel:S,bits:P,blockSize:N})},943765:(d,h,w,S,P,N)=>{r.sa("MultiHeadAttention",d,{numHeads:h,isUnidirectional:w,maskFilterValue:S,scale:P,doRotary:N})},943924:(d,h)=>{r.sa("SkipLayerNormalization",d,{epsilon:h})},944005:d=>{r.Wa(d)},944039:(d,h)=>r.Ya(d,h,r.Ea.Za,r.Ea.errors)};function Ne(d){this.name="ExitStatus",this.message=`Program terminated with exit(${d})`,this.status=d}function Fe(d){this.Ja=d-24,this.Pa=function(h){L[this.Ja+4>>>2>>>0]=h},this.Oa=function(h){L[this.Ja+8>>>2>>>0]=h},this.eb=function(h,w){this.Na(),this.Pa(h),this.Oa(w)},this.Na=function(){L[this.Ja+16>>>2>>>0]=0}}var Je=0,kt=0,vt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,xt=(d,h,w)=>{h>>>=0;var S=h+w;for(w=h;d[w]&&!(w>=S);)++w;if(16P?S+=String.fromCharCode(P):(P-=65536,S+=String.fromCharCode(55296|P>>10,56320|P&1023))}}else S+=String.fromCharCode(P)}return S},qe=(d,h)=>(d>>>=0)?xt(H,d,h):"",Zt=d=>{for(var h=0,w=0;w=S?h++:2047>=S?h+=2:55296<=S&&57343>=S?(h+=4,++w):h+=3}return h},Vt=(d,h,w,S)=>{if(w>>>=0,!(0=K){var X=d.charCodeAt(++N);K=65536+((K&1023)<<10)|X&1023}if(127>=K){if(w>=S)break;h[w++>>>0]=K}else{if(2047>=K){if(w+1>=S)break;h[w++>>>0]=192|K>>6}else{if(65535>=K){if(w+2>=S)break;h[w++>>>0]=224|K>>12}else{if(w+3>=S)break;h[w++>>>0]=240|K>>18,h[w++>>>0]=128|K>>12&63}h[w++>>>0]=128|K>>6&63}h[w++>>>0]=128|K&63}}return h[w>>>0]=0,w-P},St=d=>d%4===0&&(d%100!==0||d%400===0),$t=[0,31,60,91,121,152,182,213,244,274,305,335],Nt=[0,31,59,90,120,151,181,212,243,273,304,334],Wt=d=>{var h=Zt(d)+1,w=Lt(h);return w&&Vt(d,H,w,h),w},Rt=[],Qt=(d,h)=>{Rt.length=0;for(var w;w=H[d++>>>0];){var S=w!=105;S&=w!=112,h+=S&&h%8?4:0,Rt.push(w==112?L[h>>>2>>>0]:w==105?R[h>>>2>>>0]:Ie[h>>>3>>>0]),h+=S?8:4}return Rt},at={},Xt=()=>{if(!Gt){var d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:l||"./this.program"},h;for(h in at)at[h]===void 0?delete d[h]:d[h]=at[h];var w=[];for(h in d)w.push(`${h}=${d[h]}`);Gt=w}return Gt},Gt,Ke=[null,[],[]],vr=[31,29,31,30,31,30,31,31,30,31,30,31],ke=[31,28,31,30,31,30,31,31,30,31,30,31];function $r(d){var h=Array(Zt(d)+1);return Vt(d,h,0,h.length),h}function Ht(d,h,w,S){function P(O,oe,Ce){for(O=typeof O=="number"?O.toString():O||"";O.lengthPr?-1:0ct-O.getDate())oe-=ct-O.getDate()+1,O.setDate(1),11>Ce?O.setMonth(Ce+1):(O.setMonth(0),O.setFullYear(O.getFullYear()+1));else{O.setDate(O.getDate()+oe);break}}return Ce=new Date(O.getFullYear()+1,0,4),oe=X(new Date(O.getFullYear(),0,4)),Ce=X(Ce),0>=K(oe,O)?0>=K(Ce,O)?O.getFullYear()+1:O.getFullYear():O.getFullYear()-1}d>>>=0,h>>>=0,w>>>=0,S>>>=0;var de=L[S+40>>>2>>>0];S={bb:R[S>>>2>>>0],ab:R[S+4>>>2>>>0],Ga:R[S+8>>>2>>>0],Ka:R[S+12>>>2>>>0],Ha:R[S+16>>>2>>>0],Da:R[S+20>>>2>>>0],xa:R[S+24>>>2>>>0],Ca:R[S+28>>>2>>>0],fb:R[S+32>>>2>>>0],$a:R[S+36>>>2>>>0],cb:de?qe(de):""},w=qe(w),de={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var fe in de)w=w.replace(new RegExp(fe,"g"),de[fe]);var Oe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Re="January February March April May June July August September October November December".split(" ");de={"%a":O=>Oe[O.xa].substring(0,3),"%A":O=>Oe[O.xa],"%b":O=>Re[O.Ha].substring(0,3),"%B":O=>Re[O.Ha],"%C":O=>N((O.Da+1900)/100|0,2),"%d":O=>N(O.Ka,2),"%e":O=>P(O.Ka,2," "),"%g":O=>ae(O).toString().substring(2),"%G":O=>ae(O),"%H":O=>N(O.Ga,2),"%I":O=>(O=O.Ga,O==0?O=12:12{for(var oe=0,Ce=0;Ce<=O.Ha-1;oe+=(St(O.Da+1900)?vr:ke)[Ce++]);return N(O.Ka+oe,3)},"%m":O=>N(O.Ha+1,2),"%M":O=>N(O.ab,2),"%n":()=>`\n`,"%p":O=>0<=O.Ga&&12>O.Ga?"AM":"PM","%S":O=>N(O.bb,2),"%t":()=>" ","%u":O=>O.xa||7,"%U":O=>N(Math.floor((O.Ca+7-O.xa)/7),2),"%V":O=>{var oe=Math.floor((O.Ca+7-(O.xa+6)%7)/7);if(2>=(O.xa+371-O.Ca-2)%7&&oe++,oe)oe==53&&(Ce=(O.xa+371-O.Ca)%7,Ce==4||Ce==3&&St(O.Da)||(oe=1));else{oe=52;var Ce=(O.xa+7-O.Ca-1)%7;(Ce==4||Ce==5&&St(O.Da%400-1))&&oe++}return N(oe,2)},"%w":O=>O.xa,"%W":O=>N(Math.floor((O.Ca+7-(O.xa+6)%7)/7),2),"%y":O=>(O.Da+1900).toString().substring(2),"%Y":O=>O.Da+1900,"%z":O=>{O=O.$a;var oe=0<=O;return O=Math.abs(O)/60,(oe?"+":"-")+("0000"+(O/60*100+O%60)).slice(-4)},"%Z":O=>O.cb,"%%":()=>"%"},w=w.replace(/%%/g,"\\0\\0");for(fe in de)w.includes(fe)&&(w=w.replace(new RegExp(fe,"g"),de[fe](S)));return w=w.replace(/\\0\\0/g,"%"),fe=$r(w),fe.length>h?0:(V.set(fe,d>>>0),fe.length-1)}var Ct=d=>{try{d()}catch(h){se(h)}};function mn(){var d=ee,h={};for(let[w,S]of Object.entries(d))h[w]=typeof S=="function"?function(){_t.push(w);try{return S.apply(null,arguments)}finally{D||(_t.pop(),nt&&it===1&&_t.length===0&&(it=0,Ct(dr),typeof Fibers<"u"&&Fibers.gb()))}}:S;return h}var it=0,nt=null,te=0,_t=[],Jt={},_r={},xr=0,er=null,Sr=[];function Cr(){return new Promise((d,h)=>{er={resolve:d,reject:h}})}function Ir(){var d=Lt(65548),h=d+12;L[d>>>2>>>0]=h,L[d+4>>>2>>>0]=h+65536,h=_t[0];var w=Jt[h];return w===void 0&&(w=xr++,Jt[h]=w,_r[w]=h),R[d+8>>>2>>>0]=w,d}function Ar(d){if(!D){if(it===0){var h=!1,w=!1;d((S=0)=>{if(!D&&(te=S,h=!0,w)){it=2,Ct(()=>lr(nt)),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.resume(),S=!1;try{var P=(0,ee[_r[R[nt+8>>>2>>>0]]])()}catch(X){P=X,S=!0}var N=!1;if(!nt){var K=er;K&&(er=null,(S?K.reject:K.resolve)(P),N=!0)}if(S&&!N)throw P}}),w=!0,h||(it=1,nt=Ir(),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.pause(),Ct(()=>ur(nt)))}else it===2?(it=0,Ct(cr),nr(nt),nt=null,Sr.forEach(S=>{if(!D)try{S();try{U=U=S=U,r.onExit?.(S),D=!0,a(S,new Ne(S))}catch(P){P instanceof Ne||P=="unwind"||a(1,P)}}catch(P){P instanceof Ne||P=="unwind"||a(1,P)}})):se(`invalid state: ${it}`);return te}}function tr(d){return Ar(h=>{d().then(h)})}var Tr={n:function(d,h,w){return tr(async()=>{await r.Ua(d,h,w)})},a:function(d,h,w){throw d>>>=0,new Fe(d).eb(h>>>0,w>>>0),Je=d,kt++,Je},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(d,h,w){d=h+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*h:NaN,w>>>=0,d=new Date(1e3*d),R[w>>>2>>>0]=d.getUTCSeconds(),R[w+4>>>2>>>0]=d.getUTCMinutes(),R[w+8>>>2>>>0]=d.getUTCHours(),R[w+12>>>2>>>0]=d.getUTCDate(),R[w+16>>>2>>>0]=d.getUTCMonth(),R[w+20>>>2>>>0]=d.getUTCFullYear()-1900,R[w+24>>>2>>>0]=d.getUTCDay(),R[w+28>>>2>>>0]=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(d,h,w){d=h+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*h:NaN,w>>>=0,d=new Date(1e3*d),R[w>>>2>>>0]=d.getSeconds(),R[w+4>>>2>>>0]=d.getMinutes(),R[w+8>>>2>>>0]=d.getHours(),R[w+12>>>2>>>0]=d.getDate(),R[w+16>>>2>>>0]=d.getMonth(),R[w+20>>>2>>>0]=d.getFullYear()-1900,R[w+24>>>2>>>0]=d.getDay(),R[w+28>>>2>>>0]=(St(d.getFullYear())?$t:Nt)[d.getMonth()]+d.getDate()-1|0,R[w+36>>>2>>>0]=-(60*d.getTimezoneOffset()),h=new Date(d.getFullYear(),6,1).getTimezoneOffset();var S=new Date(d.getFullYear(),0,1).getTimezoneOffset();R[w+32>>>2>>>0]=(h!=S&&d.getTimezoneOffset()==Math.min(S,h))|0},s:function(d){d>>>=0;var h=new Date(R[d+20>>>2>>>0]+1900,R[d+16>>>2>>>0],R[d+12>>>2>>>0],R[d+8>>>2>>>0],R[d+4>>>2>>>0],R[d>>>2>>>0],0),w=R[d+32>>>2>>>0],S=h.getTimezoneOffset(),P=new Date(h.getFullYear(),6,1).getTimezoneOffset(),N=new Date(h.getFullYear(),0,1).getTimezoneOffset(),K=Math.min(N,P);return 0>w?R[d+32>>>2>>>0]=+(P!=N&&K==S):0>>2>>>0]=h.getDay(),R[d+28>>>2>>>0]=(St(h.getFullYear())?$t:Nt)[h.getMonth()]+h.getDate()-1|0,R[d>>>2>>>0]=h.getSeconds(),R[d+4>>>2>>>0]=h.getMinutes(),R[d+8>>>2>>>0]=h.getHours(),R[d+12>>>2>>>0]=h.getDate(),R[d+16>>>2>>>0]=h.getMonth(),R[d+20>>>2>>>0]=h.getYear(),d=h.getTime(),isNaN(d)?(R[rr()>>>2>>>0]=61,d=-1):d/=1e3,or((Le=d,1<=+Math.abs(Le)?0>>0:~~+Math.ceil((Le-+(~~Le>>>0))/4294967296)>>>0:0)),d>>>0},o:function(){return-52},p:function(){},w:function(d,h,w){function S(ae){return(ae=ae.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?ae[1]:"GMT"}w>>>=0;var P=new Date().getFullYear(),N=new Date(P,0,1),K=new Date(P,6,1);P=N.getTimezoneOffset();var X=K.getTimezoneOffset();L[d>>>0>>>2>>>0]=60*Math.max(P,X),R[h>>>0>>>2>>>0]=+(P!=X),d=S(N),h=S(K),d=Wt(d),h=Wt(h),X>>2>>>0]=d,L[w+4>>>2>>>0]=h):(L[w>>>2>>>0]=h,L[w+4>>>2>>>0]=d)},e:()=>{se("")},b:function(d,h,w){return d>>>=0,h=Qt(h>>>0,w>>>0),wt[d].apply(null,h)},i:function(d,h,w){return d>>>=0,h=Qt(h>>>0,w>>>0),wt[d].apply(null,h)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(d,h,w){return h>>>=0,H.copyWithin(d>>>0>>>0,h>>>0,h+(w>>>0)>>>0)},u:function(d){d>>>=0;var h=H.length;if(4294901760=w;w*=2){var S=h*(1+.2/w);S=Math.min(S,d+100663296);var P=Math;S=Math.max(d,S);e:{P=(P.min.call(P,4294901760,S+(65536-S%65536)%65536)-T.buffer.byteLength+65535)/65536;try{T.grow(P),we();var N=1;break e}catch{}N=void 0}if(N)return!0}return!1},E:function(d,h){d>>>=0,h>>>=0;var w=0;return Xt().forEach((S,P)=>{var N=h+w;for(P=L[d+4*P>>>2>>>0]=N,N=0;N>>0>>>0]=S.charCodeAt(N);V[P>>>0>>>0]=0,w+=S.length+1}),0},F:function(d,h){d>>>=0,h>>>=0;var w=Xt();L[d>>>2>>>0]=w.length;var S=0;return w.forEach(P=>S+=P.length+1),L[h>>>2>>>0]=S,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(d,h,w,S){h>>>=0,w>>>=0,S>>>=0;for(var P=0,N=0;N>>2>>>0],X=L[h+4>>>2>>>0];h+=8;for(var ae=0;ae>>0],fe=Ke[d];de===0||de===10?((d===1?v:A)(xt(fe,0)),fe.length=0):fe.push(de)}P+=X}return L[S>>>2>>>0]=P,0},v:Ht,d:function(d,h,w,S){return Ht(d>>>0,h>>>0,w>>>0,S>>>0)}},ee=function(){function d(w){return ee=w.exports,ee=mn(),ee=Er(),T=ee.M,we(),ze.unshift(ee.N),xe--,xe==0&&(me!==null&&(clearInterval(me),me=null),ue&&(w=ue,ue=null,w())),ee}var h={a:Tr};if(xe++,r.instantiateWasm)try{return r.instantiateWasm(h,d)}catch(w){A(`Module.instantiateWasm callback failed with error: ${w}`),n(w)}return Xe(h,function(w){d(w.instance)}).catch(n),{}}();r._OrtInit=(d,h)=>(r._OrtInit=ee.O)(d,h),r._OrtGetLastError=(d,h)=>(r._OrtGetLastError=ee.P)(d,h),r._OrtCreateSessionOptions=(d,h,w,S,P,N,K,X,ae,de)=>(r._OrtCreateSessionOptions=ee.Q)(d,h,w,S,P,N,K,X,ae,de),r._OrtAppendExecutionProvider=(d,h)=>(r._OrtAppendExecutionProvider=ee.R)(d,h),r._OrtAddFreeDimensionOverride=(d,h,w)=>(r._OrtAddFreeDimensionOverride=ee.S)(d,h,w),r._OrtAddSessionConfigEntry=(d,h,w)=>(r._OrtAddSessionConfigEntry=ee.T)(d,h,w),r._OrtReleaseSessionOptions=d=>(r._OrtReleaseSessionOptions=ee.U)(d),r._OrtCreateSession=(d,h,w)=>(r._OrtCreateSession=ee.V)(d,h,w),r._OrtReleaseSession=d=>(r._OrtReleaseSession=ee.W)(d),r._OrtGetInputOutputCount=(d,h,w)=>(r._OrtGetInputOutputCount=ee.X)(d,h,w),r._OrtGetInputName=(d,h)=>(r._OrtGetInputName=ee.Y)(d,h),r._OrtGetOutputName=(d,h)=>(r._OrtGetOutputName=ee.Z)(d,h),r._OrtFree=d=>(r._OrtFree=ee._)(d),r._OrtCreateTensor=(d,h,w,S,P,N)=>(r._OrtCreateTensor=ee.$)(d,h,w,S,P,N),r._OrtGetTensorData=(d,h,w,S,P)=>(r._OrtGetTensorData=ee.aa)(d,h,w,S,P),r._OrtReleaseTensor=d=>(r._OrtReleaseTensor=ee.ba)(d),r._OrtCreateRunOptions=(d,h,w,S)=>(r._OrtCreateRunOptions=ee.ca)(d,h,w,S),r._OrtAddRunConfigEntry=(d,h,w)=>(r._OrtAddRunConfigEntry=ee.da)(d,h,w),r._OrtReleaseRunOptions=d=>(r._OrtReleaseRunOptions=ee.ea)(d),r._OrtCreateBinding=d=>(r._OrtCreateBinding=ee.fa)(d),r._OrtBindInput=(d,h,w)=>(r._OrtBindInput=ee.ga)(d,h,w),r._OrtBindOutput=(d,h,w,S)=>(r._OrtBindOutput=ee.ha)(d,h,w,S),r._OrtClearBoundOutputs=d=>(r._OrtClearBoundOutputs=ee.ia)(d),r._OrtReleaseBinding=d=>(r._OrtReleaseBinding=ee.ja)(d),r._OrtRunWithBinding=(d,h,w,S,P)=>(r._OrtRunWithBinding=ee.ka)(d,h,w,S,P),r._OrtRun=(d,h,w,S,P,N,K,X)=>(r._OrtRun=ee.la)(d,h,w,S,P,N,K,X),r._OrtEndProfiling=d=>(r._OrtEndProfiling=ee.ma)(d),r._JsepOutput=(d,h,w)=>(r._JsepOutput=ee.na)(d,h,w),r._JsepGetNodeName=d=>(r._JsepGetNodeName=ee.oa)(d);var rr=()=>(rr=ee.pa)(),Lt=r._malloc=d=>(Lt=r._malloc=ee.qa)(d),nr=r._free=d=>(nr=r._free=ee.ra)(d),or=d=>(or=ee.ta)(d),ar=()=>(ar=ee.ua)(),ir=d=>(ir=ee.va)(d),sr=d=>(sr=ee.wa)(d),ur=d=>(ur=ee.ya)(d),dr=()=>(dr=ee.za)(),lr=d=>(lr=ee.Aa)(d),cr=()=>(cr=ee.Ba)();r.___start_em_js=944151,r.___stop_em_js=944312;function Er(){var d=ee;d=Object.assign({},d);var h=S=>()=>S()>>>0,w=S=>P=>S(P)>>>0;return d.pa=h(d.pa),d.qa=w(d.qa),d.ua=h(d.ua),d.wa=w(d.wa),d}r.stackAlloc=sr,r.stackSave=ar,r.stackRestore=ir,r.UTF8ToString=qe,r.stringToUTF8=(d,h,w)=>Vt(d,H,h,w),r.lengthBytesUTF8=Zt;var It;ue=function d(){It||Bt(),It||(ue=d)};function Bt(){if(!(0Oo)});var Bo=pr(()=>{});var Do=pr(()=>{});var Mo={};Mr(Mo,{cpus:()=>gd});var gd,zo=q(()=>{gd=void 0});var No=pr((Vo,In)=>{"use strict";var Uo=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){function r(){return ne.buffer!=me.buffer&&G(),me}function o(){return ne.buffer!=me.buffer&&G(),ue}function n(){return ne.buffer!=me.buffer&&G(),se}function s(){return ne.buffer!=me.buffer&&G(),he}function u(){return ne.buffer!=me.buffer&&G(),Ae}function l(){return ne.buffer!=me.buffer&&G(),He}var a=t,p,m;a.ready=new Promise((i,c)=>{p=i,m=c}),a.mountExternalData=(i,c)=>{(a.cb||(a.cb=new Map)).set(i,c)},a.unmountExternalData=()=>{delete a.cb};let f=()=>{let i=(g,x,E)=>(...k)=>{let W=pt,Z=x?.();k=g(...k);let ge=x?.();return Z!==ge&&(g=ge,E(Z),x=E=null),pt!=W?td():k},c=g=>async(...x)=>{try{if(a.bb)throw Error("Session already started");let E=a.bb={Gb:x[0],errors:[]},k=await g(...x);if(a.bb!==E)throw Error("Session mismatch");a.kb?.flush();let W=E.errors;if(0ge),0a._OrtCreateSession,g=>a._OrtCreateSession=g),a._OrtRun=c(i(a._OrtRun,()=>a._OrtRun,g=>a._OrtRun=g)),a._OrtRunWithBinding=c(i(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,g=>a._OrtRunWithBinding=g)),a._OrtBindInput=i(a._OrtBindInput,()=>a._OrtBindInput,g=>a._OrtBindInput=g),f=void 0};a.jsepInit=(i,c)=>{if(f?.(),i==="webgpu"){[a.kb,a.xb,a.Bb,a.lb,a.Ab,a.Ea,a.Cb,a.Eb,a.yb,a.zb,a.Db]=c;let g=a.kb;a.jsepRegisterBuffer=(x,E,k,W)=>g.registerBuffer(x,E,k,W),a.jsepGetBuffer=x=>g.getBuffer(x),a.jsepCreateDownloader=(x,E,k)=>g.createDownloader(x,E,k),a.jsepOnReleaseSession=x=>{g.onReleaseSession(x)},a.jsepOnRunStart=x=>g.onRunStart(x)}};var b=Object.assign({},a),_="./this.program",y=(i,c)=>{throw c},$=typeof window=="object",I=typeof importScripts=="function",C=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",v=a.ENVIRONMENT_IS_PTHREAD||!1,A="";function T(i){return a.locateFile?a.locateFile(i,A):A+i}var D,U,V;if(C){var H=(_n(),Ft($n)),R=(Sn(),Ft(xn));A=I?R.dirname(A)+"/":__dirname+"/",D=(c,g)=>(c=vt(c)?new URL(c):R.normalize(c),H.readFileSync(c,g?void 0:"utf8")),V=c=>(c=D(c,!0),c.buffer||(c=new Uint8Array(c)),c),U=(c,g,x,E=!0)=>{c=vt(c)?new URL(c):R.normalize(c),H.readFile(c,E?void 0:"utf8",(k,W)=>{k?x(k):g(E?W.buffer:W)})},!a.thisProgram&&1{throw process.exitCode=c,g},a.inspect=()=>"[Emscripten Module object]";let i;try{i=Bo()}catch(c){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),c}global.Worker=i.Worker}else($||I)&&(I?A=self.location.href:typeof document<"u"&&document.currentScript&&(A=document.currentScript.src),typeof e<"u"&&e&&(A=e),A.indexOf("blob:")!==0?A=A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):A="",C||(D=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.send(null),c.responseText},I&&(V=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),U=(i,c,g)=>{var x=new XMLHttpRequest;x.open("GET",i,!0),x.responseType="arraybuffer",x.onload=()=>{x.status==200||x.status==0&&x.response?c(x.response):g()},x.onerror=g,x.send(null)}));C&&typeof performance>"u"&&(global.performance=Do().performance);var L=console.log.bind(console),pe=console.error.bind(console);C&&(L=(...i)=>H.writeSync(1,i.join(" ")+`\n`),pe=(...i)=>H.writeSync(2,i.join(" ")+`\n`));var Ie=L,we=pe;Object.assign(a,b),b=null,typeof WebAssembly!="object"&&Je("no native wasm support detected");var ne,ze,Q=!1,xe,me,ue,se,he,Ae,He;function G(){var i=ne.buffer;a.HEAP8=me=new Int8Array(i),a.HEAP16=new Int16Array(i),a.HEAPU8=ue=new Uint8Array(i),a.HEAPU16=new Uint16Array(i),a.HEAP32=se=new Int32Array(i),a.HEAPU32=he=new Uint32Array(i),a.HEAPF32=Ae=new Float32Array(i),a.HEAPF64=He=new Float64Array(i)}var J=16777216;if(v)ne=a.wasmMemory;else if(a.wasmMemory)ne=a.wasmMemory;else if(ne=new WebAssembly.Memory({initial:J/65536,maximum:65536,shared:!0}),!(ne.buffer instanceof SharedArrayBuffer))throw we("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),C&&we("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");G(),J=ne.buffer.byteLength;var Se=[],Qe=[],Xe=[],Le=0,wt=null,Ne=null;function Fe(){if(Le--,Le==0&&(wt!==null&&(clearInterval(wt),wt=null),Ne)){var i=Ne;Ne=null,i()}}function Je(i){throw i="Aborted("+i+")",we(i),Q=!0,xe=1,i=new WebAssembly.RuntimeError(i+". Build with -sASSERTIONS for more info."),m(i),i}var kt=i=>i.startsWith("data:application/octet-stream;base64,"),vt=i=>i.startsWith("file://"),xt;xt="ort-wasm-simd-threaded.wasm",kt(xt)||(xt=T(xt));function qe(i){if(V)return V(i);throw"both async and sync fetching of the wasm failed"}function Zt(i){if($||I){if(typeof fetch=="function"&&!vt(i))return fetch(i,{credentials:"same-origin"}).then(c=>{if(!c.ok)throw"failed to load wasm binary file at \'"+i+"\'";return c.arrayBuffer()}).catch(()=>qe(i));if(U)return new Promise((c,g)=>{U(i,x=>c(new Uint8Array(x)),g)})}return Promise.resolve().then(()=>qe(i))}function Vt(i,c,g){return Zt(i).then(x=>WebAssembly.instantiate(x,c)).then(x=>x).then(g,x=>{we(`failed to asynchronously prepare wasm: ${x}`),Je(x)})}function St(i,c){var g=xt;return typeof WebAssembly.instantiateStreaming!="function"||kt(g)||vt(g)||C||typeof fetch!="function"?Vt(g,i,c):fetch(g,{credentials:"same-origin"}).then(x=>WebAssembly.instantiateStreaming(x,i).then(c,function(E){return we(`wasm streaming compile failed: ${E}`),we("falling back to ArrayBuffer instantiation"),Vt(g,i,c)}))}var $t,Nt={933148:(i,c,g,x)=>{if(typeof a>"u"||!a.cb)return 1;if(i=Ke(i>>>0),i.startsWith("./")&&(i=i.substring(2)),i=a.cb.get(i),!i)return 2;if(c>>>=0,g>>>=0,x>>>=0,c+g>i.byteLength)return 3;try{return o().set(i.subarray(c,c+g),x>>>0),0}catch{return 4}},933649:()=>{a.yb()},933680:()=>{a.zb()},933709:()=>{a.Db()},933734:i=>a.xb(i),933767:i=>a.Bb(i),933799:(i,c,g)=>{a.lb(i,c,g,!0)},933838:(i,c,g)=>{a.lb(i,c,g)},933871:i=>{a.Ea("Abs",i,void 0)},933922:i=>{a.Ea("Neg",i,void 0)},933973:i=>{a.Ea("Floor",i,void 0)},934026:i=>{a.Ea("Ceil",i,void 0)},934078:i=>{a.Ea("Reciprocal",i,void 0)},934136:i=>{a.Ea("Sqrt",i,void 0)},934188:i=>{a.Ea("Exp",i,void 0)},934239:i=>{a.Ea("Erf",i,void 0)},934290:i=>{a.Ea("Sigmoid",i,void 0)},934345:(i,c,g)=>{a.Ea("HardSigmoid",i,{alpha:c,beta:g})},934424:i=>{a.Ea("Log",i,void 0)},934475:i=>{a.Ea("Sin",i,void 0)},934526:i=>{a.Ea("Cos",i,void 0)},934577:i=>{a.Ea("Tan",i,void 0)},934628:i=>{a.Ea("Asin",i,void 0)},934680:i=>{a.Ea("Acos",i,void 0)},934732:i=>{a.Ea("Atan",i,void 0)},934784:i=>{a.Ea("Sinh",i,void 0)},934836:i=>{a.Ea("Cosh",i,void 0)},934888:i=>{a.Ea("Asinh",i,void 0)},934941:i=>{a.Ea("Acosh",i,void 0)},934994:i=>{a.Ea("Atanh",i,void 0)},935047:i=>{a.Ea("Tanh",i,void 0)},935099:i=>{a.Ea("Not",i,void 0)},935150:(i,c,g)=>{a.Ea("Clip",i,{min:c,max:g})},935219:i=>{a.Ea("Clip",i,void 0)},935271:(i,c)=>{a.Ea("Elu",i,{alpha:c})},935329:i=>{a.Ea("Relu",i,void 0)},935381:(i,c)=>{a.Ea("LeakyRelu",i,{alpha:c})},935445:(i,c)=>{a.Ea("ThresholdedRelu",i,{alpha:c})},935515:(i,c)=>{a.Ea("Cast",i,{to:c})},935573:i=>{a.Ea("Add",i,void 0)},935624:i=>{a.Ea("Sub",i,void 0)},935675:i=>{a.Ea("Mul",i,void 0)},935726:i=>{a.Ea("Div",i,void 0)},935777:i=>{a.Ea("Pow",i,void 0)},935828:i=>{a.Ea("Equal",i,void 0)},935881:i=>{a.Ea("Greater",i,void 0)},935936:i=>{a.Ea("GreaterOrEqual",i,void 0)},935998:i=>{a.Ea("Less",i,void 0)},936050:i=>{a.Ea("LessOrEqual",i,void 0)},936109:(i,c,g,x,E)=>{a.Ea("ReduceMean",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936268:(i,c,g,x,E)=>{a.Ea("ReduceMax",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936426:(i,c,g,x,E)=>{a.Ea("ReduceMin",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936584:(i,c,g,x,E)=>{a.Ea("ReduceProd",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936743:(i,c,g,x,E)=>{a.Ea("ReduceSum",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},936901:(i,c,g,x,E)=>{a.Ea("ReduceL1",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937058:(i,c,g,x,E)=>{a.Ea("ReduceL2",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937215:(i,c,g,x,E)=>{a.Ea("ReduceLogSum",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937376:(i,c,g,x,E)=>{a.Ea("ReduceSumSquare",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937540:(i,c,g,x,E)=>{a.Ea("ReduceLogSumExp",i,{keepDims:!!c,noopWithEmptyAxes:!!g,axes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},937704:i=>{a.Ea("Where",i,void 0)},937757:(i,c,g)=>{a.Ea("Transpose",i,{perm:c?Array.from(n().subarray(c>>>0,g>>>0)):[]})},937865:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce)=>{a.Ea("ConvTranspose",i,{format:ge?"NHWC":"NCHW",autoPad:c,dilations:[g],group:x,kernel_shape:[E],pads:[k,W],strides:[Z],wIsConst:()=>!!r()[le>>>0],outputPadding:ve?Array.from(n().subarray(ve>>>0,Ue>>>0)):[],outputShape:Ve?Array.from(n().subarray(Ve>>>0,B>>>0)):[],activation:Ke(ce)})},938267:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B)=>{a.Ea("ConvTranspose",i,{format:Z?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(g>>>0,(g>>>0)+2>>>0)),group:x,kernelShape:Array.from(n().subarray(E>>>0,(E>>>0)+2>>>0)),pads:Array.from(n().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ge>>>0],outputPadding:le?Array.from(n().subarray(le>>>0,ve>>>0)):[],outputShape:Ue?Array.from(n().subarray(Ue>>>0,Ve>>>0)):[],activation:Ke(B)})},938832:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce)=>{a.Ea("ConvTranspose",i,{format:ge?"NHWC":"NCHW",autoPad:c,dilations:[g],group:x,kernel_shape:[E],pads:[k,W],strides:[Z],wIsConst:()=>!!r()[le>>>0],outputPadding:ve?Array.from(n().subarray(ve>>>0,Ue>>>0)):[],outputShape:Ve?Array.from(n().subarray(Ve>>>0,B>>>0)):[],activation:Ke(ce)})},939234:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B)=>{a.Ea("ConvTranspose",i,{format:Z?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(g>>>0,(g>>>0)+2>>>0)),group:x,kernelShape:Array.from(n().subarray(E>>>0,(E>>>0)+2>>>0)),pads:Array.from(n().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ge>>>0],outputPadding:le?Array.from(n().subarray(le>>>0,ve>>>0)):[],outputShape:Ue?Array.from(n().subarray(Ue>>>0,Ve>>>0)):[],activation:Ke(B)})},939799:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939890:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("AveragePool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},940174:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},940265:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("AveragePool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},940549:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},940636:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("MaxPool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},940916:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},941003:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("MaxPool",i,{format:Te?"NHWC":"NCHW",auto_pad:c,ceil_mode:g,count_include_pad:x,storage_order:E,dilations:[k,W],kernel_shape:[Z,ge],pads:[le,ve,Ue,Ve],strides:[B,ce]})},941283:(i,c,g,x,E)=>{a.Ea("Gemm",i,{alpha:c,beta:g,transA:x,transB:E})},941387:i=>{a.Ea("MatMul",i,void 0)},941441:(i,c,g,x)=>{a.Ea("ArgMax",i,{keepDims:!!c,selectLastIndex:!!g,axis:x})},941549:(i,c,g,x)=>{a.Ea("ArgMin",i,{keepDims:!!c,selectLastIndex:!!g,axis:x})},941657:(i,c)=>{a.Ea("Softmax",i,{axis:c})},941720:(i,c)=>{a.Ea("Concat",i,{axis:c})},941780:(i,c,g,x,E)=>{a.Ea("Split",i,{axis:c,numOutputs:g,splitSizes:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},941920:i=>{a.Ea("Expand",i,void 0)},941974:(i,c)=>{a.Ea("Gather",i,{axis:Number(c)})},942045:(i,c)=>{a.Ea("GatherElements",i,{axis:Number(c)})},942124:(i,c,g,x,E,k,W,Z,ge,le,ve)=>{a.Ea("Resize",i,{antialias:c,axes:g?Array.from(n().subarray(g>>>0,x>>>0)):[],coordinateTransformMode:Ke(E),cubicCoeffA:k,excludeOutside:W,extrapolationValue:Z,keepAspectRatioPolicy:Ke(ge),mode:Ke(le),nearestMode:Ke(ve)})},942470:(i,c,g,x,E,k,W)=>{a.Ea("Slice",i,{starts:c?Array.from(n().subarray(c>>>0,g>>>0)):[],ends:x?Array.from(n().subarray(x>>>0,E>>>0)):[],axes:k?Array.from(n().subarray(k>>>0,W>>>0)):[]})},942686:i=>{a.Ea("Tile",i,void 0)},942738:(i,c,g)=>{a.Ea("LayerNormalization",i,{axis:Number(c),epsilon:Number(g)})},942845:(i,c,g)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:g?"NHWC":"NCHW"})},942959:(i,c,g)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:g?"NHWC":"NCHW"})},943073:i=>{a.Ea("Range",i,void 0)},943126:(i,c)=>{a.Ea("Einsum",i,{equation:Ke(c)})},943207:(i,c,g,x,E)=>{a.Ea("Pad",i,{mode:c,value:g,pads:x?Array.from(n().subarray(x>>>0,E>>>0)):[]})},943334:(i,c,g,x,E,k)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:g,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},943503:(i,c,g,x,E,k)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:g,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},943672:(i,c,g)=>{a.Ea("CumSum",i,{exclusive:Number(c),reverse:Number(g)})},943769:(i,c,g,x,E,k,W,Z,ge)=>{a.Ea("Attention",i,{numHeads:c,isUnidirectional:g,maskFilterValue:x,scale:E,doRotary:k,qkvHiddenSizes:W?Array.from(n().subarray(Number(Z)>>>0,Number(Z)+W>>>0)):[],pastPresentShareBuffer:!!ge})},944041:i=>{a.Ea("BiasAdd",i,void 0)},944096:i=>{a.Ea("BiasSplitGelu",i,void 0)},944157:i=>{a.Ea("FastGelu",i,void 0)},944213:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve)=>{a.Ea("Conv",i,{format:ge?"NHWC":"NCHW",auto_pad:c,dilations:[g],group:x,kernel_shape:[E],pads:k?Array.from(n().subarray(k>>>0,W>>>0)):[],strides:[Z],w_is_const:()=>!!r()[le>>>0],activation:Ke(ve),activation_params:Ue?Array.from(u().subarray(Ue>>>0,Ve>>>0)):[]})},944583:(i,c,g,x,E,k,W,Z,ge,le,ve,Ue,Ve,B,ce,Te)=>{a.Ea("Conv",i,{format:Ue?"NHWC":"NCHW",auto_pad:c,dilations:[g,x],group:E,kernel_shape:[k,W],pads:Z?Array.from(n().subarray(Z>>>0,ge>>>0)):[],strides:[le,ve],w_is_const:()=>!!r()[Ve>>>0],activation:Ke(B),activation_params:ce?Array.from(u().subarray(ce>>>0,Te>>>0)):[]})},944974:i=>{a.Ea("Gelu",i,void 0)},945026:(i,c,g,x,E,k)=>{a.Ea("MatMulNBits",i,{k:c,n:g,accuracyLevel:x,bits:E,blockSize:k})},945153:(i,c,g,x,E,k)=>{a.Ea("MultiHeadAttention",i,{numHeads:c,isUnidirectional:g,maskFilterValue:x,scale:E,doRotary:k})},945312:(i,c)=>{a.Ea("SkipLayerNormalization",i,{epsilon:c})},945393:i=>{a.Cb(i)},945427:(i,c)=>a.Eb(i,c,a.bb.Gb,a.bb.errors)};function Wt(i){this.name="ExitStatus",this.message=`Program terminated with exit(${i})`,this.status=i}var Rt=i=>{i.terminate(),i.onmessage=()=>{}},Qt=i=>{te.Ya.length==0&&(it(),te.mb(te.Ya[0]));var c=te.Ya.pop();if(!c)return 6;te.Za.push(c),te.Qa[i.Xa]=c,c.Xa=i.Xa;var g={cmd:"run",start_routine:i.Hb,arg:i.ub,pthread_ptr:i.Xa};return C&&c.unref(),c.postMessage(g,i.Nb),0},at=0,Xt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Gt=(i,c,g)=>{c>>>=0;var x=c+g;for(g=c;i[g]&&!(g>=x);)++g;if(16E?x+=String.fromCharCode(E):(E-=65536,x+=String.fromCharCode(55296|E>>10,56320|E&1023))}}else x+=String.fromCharCode(E)}return x},Ke=(i,c)=>(i>>>=0)?Gt(o(),i,c):"",vr=i=>{var c=bn();return i=i(),Br(c),i};function ke(i,c){var g=arguments.length-2,x=arguments;return vr(()=>{for(var E=wn(8*g),k=E>>>3,W=0;W>>0]=Z}return wo(i,g,E,c)})}function $r(i){if(v)return ke(0,1,i);xe=i,0{if(xe=i,v)throw Jt(i),"unwind";$r(i)},Ct=i=>{i instanceof Wt||i=="unwind"||y(1,i)};function mn(){for(var i=a.numThreads;i--;)it();Se.unshift(()=>{Le++,nt(()=>Fe())})}function it(){var i=T("ort-wasm-simd-threaded.worker.js");i=new Worker(i),te.Ya.push(i)}function nt(i){v?i():Promise.all(te.Ya.map(te.mb)).then(i)}var te={Ya:[],Za:[],qb:[],Qa:{},hb(){v?(te.receiveObjectTransfer=te.Fb,te.threadInitTLS=te.pb,te.setExitStatus=te.ob):mn()},ob:i=>xe=i,Qb:["$terminateWorker"],Ib:()=>{for(var i of te.Za)Rt(i);for(i of te.Ya)Rt(i);te.Ya=[],te.Za=[],te.Qa=[]},nb:i=>{var c=i.Xa;delete te.Qa[c],te.Ya.push(i),te.Za.splice(te.Za.indexOf(i),1),i.Xa=0,gn(c)},Fb(){},pb(){te.qb.forEach(i=>i())},mb:i=>new Promise(c=>{i.onmessage=k=>{k=k.data;var W=k.cmd;if(k.targetThread&&k.targetThread!=Rr()){var Z=te.Qa[k.targetThread];Z?Z.postMessage(k,k.transferList):we(`Internal error! Worker sent a message "${W}" to target pthread ${k.targetThread}, but that thread no longer exists!`)}else W==="checkMailbox"?Bt():W==="spawnThread"?Qt(k):W==="cleanupThread"?te.nb(te.Qa[k.thread]):W==="killThread"?(k=k.thread,W=te.Qa[k],delete te.Qa[k],Rt(W),gn(k),te.Za.splice(te.Za.indexOf(W),1),W.Xa=0):W==="cancelThread"?te.Qa[k.thread].postMessage({cmd:"cancel"}):W==="loaded"?(i.loaded=!0,C&&!i.Xa&&i.unref(),c(i)):W==="alert"?alert(`Thread ${k.threadId}: ${k.text}`):k.target==="setimmediate"?i.postMessage(k):W==="callHandler"?a[k.handler](...k.args):W&&we(`worker sent an unknown command ${W}`)},i.onerror=k=>{throw we(`worker sent an error! ${k.filename}:${k.lineno}: ${k.message}`),k},C&&(i.on("message",k=>i.onmessage({data:k})),i.on("error",k=>i.onerror(k)));var g=[],x=["onExit"],E;for(E of x)a.hasOwnProperty(E)&&g.push(E);i.postMessage({cmd:"load",handlers:g,urlOrBlob:a.mainScriptUrlOrBlob||e,wasmMemory:ne,wasmModule:ze})})};a.PThread=te;var _t=i=>{for(;0{var i=Rr(),c=s()[i+52>>>2>>>0];i=s()[i+56>>>2>>>0],_o(c,c-i),Br(c)};function Jt(i){if(v)return ke(1,0,i);Ht(i)}a.invokeEntryPoint=(i,c)=>{i=xo.apply(null,[i,c]),0>>2>>>0]=c},this.sb=function(c){s()[this.gb+8>>>2>>>0]=c},this.hb=function(c,g){this.rb(),this.tb(c),this.sb(g)},this.rb=function(){s()[this.gb+16>>>2>>>0]=0}}var xr=0,er=0;function Sr(i,c,g,x){return v?ke(2,1,i,c,g,x):Cr(i,c,g,x)}function Cr(i,c,g,x){if(i>>>=0,c>>>=0,g>>>=0,x>>>=0,typeof SharedArrayBuffer>"u")return we("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var E=[];return v&&E.length===0?Sr(i,c,g,x):(i={Hb:g,Xa:i,ub:x,Nb:E},v?(i.Pb="spawnThread",postMessage(i,E),0):Qt(i))}function Ir(i,c,g){return v?ke(3,1,i,c,g):0}function Ar(i,c){if(v)return ke(4,1,i,c)}var tr=i=>{for(var c=0,g=0;g=x?c++:2047>=x?c+=2:55296<=x&&57343>=x?(c+=4,++g):c+=3}return c},Tr=(i,c,g,x)=>{if(g>>>=0,!(0=W){var Z=i.charCodeAt(++k);W=65536+((W&1023)<<10)|Z&1023}if(127>=W){if(g>=x)break;c[g++>>>0]=W}else{if(2047>=W){if(g+1>=x)break;c[g++>>>0]=192|W>>6}else{if(65535>=W){if(g+2>=x)break;c[g++>>>0]=224|W>>12}else{if(g+3>=x)break;c[g++>>>0]=240|W>>18,c[g++>>>0]=128|W>>12&63}c[g++>>>0]=128|W>>6&63}c[g++>>>0]=128|W&63}}return c[g>>>0]=0,g-E},ee=(i,c,g)=>Tr(i,o(),c,g);function rr(i,c){if(v)return ke(5,1,i,c)}function Lt(i,c,g){if(v)return ke(6,1,i,c,g)}function nr(i,c,g){return v?ke(7,1,i,c,g):0}function or(i,c){if(v)return ke(8,1,i,c)}function ar(i,c,g){if(v)return ke(9,1,i,c,g)}function ir(i,c,g,x){if(v)return ke(10,1,i,c,g,x)}function sr(i,c,g,x){if(v)return ke(11,1,i,c,g,x)}function ur(i,c,g,x){if(v)return ke(12,1,i,c,g,x)}function dr(i){if(v)return ke(13,1,i)}function lr(i,c){if(v)return ke(14,1,i,c)}function cr(i,c,g){if(v)return ke(15,1,i,c,g)}var Er=()=>{if(!(0>>=0,typeof Atomics.Ob=="function"&&(Atomics.Ob(n(),i>>>2,i).value.then(Bt),i+=128,Atomics.store(n(),i>>>2,1))}a.__emscripten_thread_mailbox_await=It;var Bt=()=>{var i=Rr();if(i&&(It(i),!Q))try{vo(),Er()}catch(c){Ct(c)}};a.checkMailbox=Bt;var d=[],h=i=>i%4===0&&(i%100!==0||i%400===0),w=[0,31,60,91,121,152,182,213,244,274,305,335],S=[0,31,59,90,120,151,181,212,243,273,304,334];function P(i,c,g,x,E,k,W,Z){return v?ke(16,1,i,c,g,x,E,k,W,Z):-52}function N(i,c,g,x,E,k,W){if(v)return ke(17,1,i,c,g,x,E,k,W)}var K=i=>{var c=tr(i)+1,g=hn(c);return g&&ee(i,g,c),g},X=[],ae=(i,c)=>{X.length=0;for(var g;g=o()[i++>>>0];){var x=g!=105;x&=g!=112,c+=x&&c%8?4:0,X.push(g==112?s()[c>>>2>>>0]:g==105?n()[c>>>2>>>0]:l()[c>>>3>>>0]),c+=x?8:4}return X},de={},fe=()=>{if(!Oe){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:_||"./this.program"},c;for(c in de)de[c]===void 0?delete i[c]:i[c]=de[c];var g=[];for(c in i)g.push(`${c}=${i[c]}`);Oe=g}return Oe},Oe;function Re(i,c){if(v)return ke(18,1,i,c);i>>>=0,c>>>=0;var g=0;return fe().forEach((x,E)=>{var k=c+g;for(E=s()[i+4*E>>>2>>>0]=k,k=0;k>>0>>>0]=x.charCodeAt(k);r()[E>>>0>>>0]=0,g+=x.length+1}),0}function O(i,c){if(v)return ke(19,1,i,c);i>>>=0,c>>>=0;var g=fe();s()[i>>>2>>>0]=g.length;var x=0;return g.forEach(E=>x+=E.length+1),s()[c>>>2>>>0]=x,0}function oe(i){return v?ke(20,1,i):52}function Ce(i,c,g,x){return v?ke(21,1,i,c,g,x):52}function ct(i,c,g,x,E){return v?ke(22,1,i,c,g,x,E):70}var Pr=[null,[],[]];function uo(i,c,g,x){if(v)return ke(23,1,i,c,g,x);c>>>=0,g>>>=0,x>>>=0;for(var E=0,k=0;k>>2>>>0],Z=s()[c+4>>>2>>>0];c+=8;for(var ge=0;ge>>0],ve=Pr[i];le===0||le===10?((i===1?Ie:we)(Gt(ve,0)),ve.length=0):ve.push(le)}E+=Z}return s()[x>>>2>>>0]=E,0}var lo=[31,29,31,30,31,30,31,31,30,31,30,31],co=[31,28,31,30,31,30,31,31,30,31,30,31];function Zu(i){var c=Array(tr(i)+1);return Tr(i,c,0,c.length),c}var Qu=(i,c)=>{r().set(i,c>>>0)};function po(i,c,g,x){function E(B,ce,Te){for(B=typeof B=="number"?B.toString():B||"";B.lengthEo?-1:0Dt-B.getDate())ce-=Dt-B.getDate()+1,B.setDate(1),11>Te?B.setMonth(Te+1):(B.setMonth(0),B.setFullYear(B.getFullYear()+1));else{B.setDate(B.getDate()+ce);break}}return Te=new Date(B.getFullYear()+1,0,4),ce=Z(new Date(B.getFullYear(),0,4)),Te=Z(Te),0>=W(ce,B)?0>=W(Te,B)?B.getFullYear()+1:B.getFullYear():B.getFullYear()-1}i>>>=0,c>>>=0,g>>>=0,x>>>=0;var le=s()[x+40>>>2>>>0];x={Lb:n()[x>>>2>>>0],Kb:n()[x+4>>>2>>>0],eb:n()[x+8>>>2>>>0],jb:n()[x+12>>>2>>>0],fb:n()[x+16>>>2>>>0],ab:n()[x+20>>>2>>>0],Wa:n()[x+24>>>2>>>0],$a:n()[x+28>>>2>>>0],Rb:n()[x+32>>>2>>>0],Jb:n()[x+36>>>2>>>0],Mb:le?Ke(le):""},g=Ke(g),le={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var ve in le)g=g.replace(new RegExp(ve,"g"),le[ve]);var Ue="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ve="January February March April May June July August September October November December".split(" ");le={"%a":B=>Ue[B.Wa].substring(0,3),"%A":B=>Ue[B.Wa],"%b":B=>Ve[B.fb].substring(0,3),"%B":B=>Ve[B.fb],"%C":B=>k((B.ab+1900)/100|0,2),"%d":B=>k(B.jb,2),"%e":B=>E(B.jb,2," "),"%g":B=>ge(B).toString().substring(2),"%G":B=>ge(B),"%H":B=>k(B.eb,2),"%I":B=>(B=B.eb,B==0?B=12:12{for(var ce=0,Te=0;Te<=B.fb-1;ce+=(h(B.ab+1900)?lo:co)[Te++]);return k(B.jb+ce,3)},"%m":B=>k(B.fb+1,2),"%M":B=>k(B.Kb,2),"%n":()=>`\n`,"%p":B=>0<=B.eb&&12>B.eb?"AM":"PM","%S":B=>k(B.Lb,2),"%t":()=>" ","%u":B=>B.Wa||7,"%U":B=>k(Math.floor((B.$a+7-B.Wa)/7),2),"%V":B=>{var ce=Math.floor((B.$a+7-(B.Wa+6)%7)/7);if(2>=(B.Wa+371-B.$a-2)%7&&ce++,ce)ce==53&&(Te=(B.Wa+371-B.$a)%7,Te==4||Te==3&&h(B.ab)||(ce=1));else{ce=52;var Te=(B.Wa+7-B.$a-1)%7;(Te==4||Te==5&&h(B.ab%400-1))&&ce++}return k(ce,2)},"%w":B=>B.Wa,"%W":B=>k(Math.floor((B.$a+7-(B.Wa+6)%7)/7),2),"%y":B=>(B.ab+1900).toString().substring(2),"%Y":B=>B.ab+1900,"%z":B=>{B=B.Jb;var ce=0<=B;return B=Math.abs(B)/60,(ce?"+":"-")+("0000"+(B/60*100+B%60)).slice(-4)},"%Z":B=>B.Mb,"%%":()=>"%"},g=g.replace(/%%/g,"\\0\\0");for(ve in le)g.includes(ve)&&(g=g.replace(new RegExp(ve,"g"),le[ve](x)));return g=g.replace(/\\0\\0/g,"%"),ve=Zu(g),ve.length>c?0:(Qu(ve,i),ve.length-1)}var Or=i=>{try{i()}catch(c){Je(c)}};function Xu(){var i=Y,c={};for(let[g,x]of Object.entries(i))c[g]=typeof x=="function"?function(){kr.push(g);try{return x.apply(null,arguments)}finally{Q||(kr.pop(),pt&&At===1&&kr.length===0&&(At=0,at+=1,Or(Co),typeof Fibers<"u"&&Fibers.Sb()))}}:x;return c}var At=0,pt=null,mo=0,kr=[],fo={},ho={},Ju=0,fn=null,ed=[];function td(){return new Promise((i,c)=>{fn={resolve:i,reject:c}})}function rd(){var i=hn(65548),c=i+12;s()[i>>>2>>>0]=c,s()[i+4>>>2>>>0]=c+65536,c=kr[0];var g=fo[c];return g===void 0&&(g=Ju++,fo[c]=g,ho[g]=c),c=g,n()[i+8>>>2>>>0]=c,i}function nd(){var i=n()[pt+8>>>2>>>0];return i=Y[ho[i]],--at,i()}function od(i){if(!Q){if(At===0){var c=!1,g=!1;i((x=0)=>{if(!Q&&(mo=x,c=!0,g)){At=2,Or(()=>Io(pt)),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.resume(),x=!1;try{var E=nd()}catch(Z){E=Z,x=!0}var k=!1;if(!pt){var W=fn;W&&(fn=null,(x?W.reject:W.resolve)(E),k=!0)}if(x&&!k)throw E}}),g=!0,c||(At=1,pt=rd(),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.pause(),Or(()=>So(pt)))}else At===2?(At=0,Or(Ao),yo(pt),pt=null,ed.forEach(x=>{if(!Q)try{x(),Er()}catch(E){Ct(E)}})):Je(`invalid state: ${At}`);return mo}}function ad(i){return od(c=>{i().then(c)})}te.hb();var id=[$r,Jt,Sr,Ir,Ar,rr,Lt,nr,or,ar,ir,sr,ur,dr,lr,cr,P,N,Re,O,oe,Ce,ct,uo],sd={r:function(i,c,g){return ad(async()=>{await a.Ab(i,c,g)})},b:function(i,c,g){throw i>>>=0,new _r(i).hb(c>>>0,g>>>0),xr=i,er++,xr},N:function(i){bo(i>>>0,!I,1,!$,131072,!1),te.pb()},l:function(i){i>>>=0,v?postMessage({cmd:"cleanupThread",thread:i}):te.nb(te.Qa[i])},J:Cr,i:Ir,T:Ar,F:rr,H:Lt,U:nr,R:or,L:ar,Q:ir,p:sr,G:ur,D:dr,S:lr,E:cr,q:()=>1,B:function(i,c){i>>>=0,i==c>>>0?setTimeout(()=>Bt()):v?postMessage({targetThread:i,cmd:"checkMailbox"}):(i=te.Qa[i])&&i.postMessage({cmd:"checkMailbox"})},K:function(i,c,g,x){c>>>=0,d.length=g,x=x>>>0>>>3;for(var E=0;E>>0];return i=0>i?Nt[-i-1]:id[i],te.vb=c,c=i.apply(null,d),te.vb=0,c},M:It,W:function(i){C&&te.Qa[i>>>0].ref()},u:function(i,c,g){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,g>>>=0,i=new Date(1e3*i),n()[g>>>2>>>0]=i.getUTCSeconds(),n()[g+4>>>2>>>0]=i.getUTCMinutes(),n()[g+8>>>2>>>0]=i.getUTCHours(),n()[g+12>>>2>>>0]=i.getUTCDate(),n()[g+16>>>2>>>0]=i.getUTCMonth(),n()[g+20>>>2>>>0]=i.getUTCFullYear()-1900,n()[g+24>>>2>>>0]=i.getUTCDay(),i=(i.getTime()-Date.UTC(i.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,n()[g+28>>>2>>>0]=i},v:function(i,c,g){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,g>>>=0,i=new Date(1e3*i),n()[g>>>2>>>0]=i.getSeconds(),n()[g+4>>>2>>>0]=i.getMinutes(),n()[g+8>>>2>>>0]=i.getHours(),n()[g+12>>>2>>>0]=i.getDate(),n()[g+16>>>2>>>0]=i.getMonth(),n()[g+20>>>2>>>0]=i.getFullYear()-1900,n()[g+24>>>2>>>0]=i.getDay(),c=(h(i.getFullYear())?w:S)[i.getMonth()]+i.getDate()-1|0,n()[g+28>>>2>>>0]=c,n()[g+36>>>2>>>0]=-(60*i.getTimezoneOffset()),c=new Date(i.getFullYear(),6,1).getTimezoneOffset();var x=new Date(i.getFullYear(),0,1).getTimezoneOffset();i=(c!=x&&i.getTimezoneOffset()==Math.min(x,c))|0,n()[g+32>>>2>>>0]=i},w:function(i){i>>>=0;var c=new Date(n()[i+20>>>2>>>0]+1900,n()[i+16>>>2>>>0],n()[i+12>>>2>>>0],n()[i+8>>>2>>>0],n()[i+4>>>2>>>0],n()[i>>>2>>>0],0),g=n()[i+32>>>2>>>0],x=c.getTimezoneOffset(),E=new Date(c.getFullYear(),6,1).getTimezoneOffset(),k=new Date(c.getFullYear(),0,1).getTimezoneOffset(),W=Math.min(k,E);return 0>g?n()[i+32>>>2>>>0]=+(E!=k&&W==x):0>>2>>>0]=c.getDay(),g=(h(c.getFullYear())?w:S)[c.getMonth()]+c.getDate()-1|0,n()[i+28>>>2>>>0]=g,n()[i>>>2>>>0]=c.getSeconds(),n()[i+4>>>2>>>0]=c.getMinutes(),n()[i+8>>>2>>>0]=c.getHours(),n()[i+12>>>2>>>0]=c.getDate(),n()[i+16>>>2>>>0]=c.getMonth(),n()[i+20>>>2>>>0]=c.getYear(),i=c.getTime(),isNaN(i)?(n()[go()>>>2>>>0]=61,i=-1):i/=1e3,$o(($t=i,1<=+Math.abs($t)?0<$t?+Math.floor($t/4294967296)>>>0:~~+Math.ceil(($t-+(~~$t>>>0))/4294967296)>>>0:0)),i>>>0},s:P,t:N,A:function(i,c,g){function x(le){return(le=le.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?le[1]:"GMT"}i>>>=0,c>>>=0,g>>>=0;var E=new Date().getFullYear(),k=new Date(E,0,1),W=new Date(E,6,1);E=k.getTimezoneOffset();var Z=W.getTimezoneOffset(),ge=Math.max(E,Z);s()[i>>>2>>>0]=60*ge,n()[c>>>2>>>0]=+(E!=Z),i=x(k),c=x(W),i=K(i),c=K(c),Z>>2>>>0]=i,s()[g+4>>>2>>>0]=c):(s()[g>>>2>>>0]=c,s()[g+4>>>2>>>0]=i)},d:()=>{Je("")},c:function(i,c,g){return i>>>=0,c=ae(c>>>0,g>>>0),Nt[i].apply(null,c)},k:function(i,c,g){return i>>>=0,c=ae(c>>>0,g>>>0),Nt[i].apply(null,c)},m:()=>{},j:()=>Date.now(),V:()=>{throw at+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>C?(zo(),Ft(Mo)).cpus().length:navigator.hardwareConcurrency,y:function(i){i>>>=0;var c=o().length;if(i<=c||4294901760=g;g*=2){var x=c*(1+.2/g);x=Math.min(x,i+100663296);var E=Math;x=Math.max(i,x);e:{E=(E.min.call(E,4294901760,x+(65536-x%65536)%65536)-ne.buffer.byteLength+65535)/65536;try{ne.grow(E),G();var k=1;break e}catch{}k=void 0}if(k)return!0}return!1},O:Re,P:O,I:Ht,h:oe,o:Ce,x:ct,n:uo,a:ne||a.wasmMemory,z:po,e:function(i,c,g,x){return po(i>>>0,c>>>0,g>>>0,x>>>0)}},Y=function(){function i(g,x){return Y=g.exports,Y=Xu(),Y=ud(),te.qb.push(Y.Da),Qe.unshift(Y.X),ze=x,Fe(),Y}var c={a:sd};if(Le++,a.instantiateWasm)try{return a.instantiateWasm(c,i)}catch(g){we(`Module.instantiateWasm callback failed with error: ${g}`),m(g)}return St(c,function(g){i(g.instance,g.module)}).catch(m),{}}();a._OrtInit=(i,c)=>(a._OrtInit=Y.Y)(i,c),a._OrtGetLastError=(i,c)=>(a._OrtGetLastError=Y.Z)(i,c),a._OrtCreateSessionOptions=(i,c,g,x,E,k,W,Z,ge,le)=>(a._OrtCreateSessionOptions=Y._)(i,c,g,x,E,k,W,Z,ge,le),a._OrtAppendExecutionProvider=(i,c)=>(a._OrtAppendExecutionProvider=Y.$)(i,c),a._OrtAddFreeDimensionOverride=(i,c,g)=>(a._OrtAddFreeDimensionOverride=Y.aa)(i,c,g),a._OrtAddSessionConfigEntry=(i,c,g)=>(a._OrtAddSessionConfigEntry=Y.ba)(i,c,g),a._OrtReleaseSessionOptions=i=>(a._OrtReleaseSessionOptions=Y.ca)(i),a._OrtCreateSession=(i,c,g)=>(a._OrtCreateSession=Y.da)(i,c,g),a._OrtReleaseSession=i=>(a._OrtReleaseSession=Y.ea)(i),a._OrtGetInputOutputCount=(i,c,g)=>(a._OrtGetInputOutputCount=Y.fa)(i,c,g),a._OrtGetInputName=(i,c)=>(a._OrtGetInputName=Y.ga)(i,c),a._OrtGetOutputName=(i,c)=>(a._OrtGetOutputName=Y.ha)(i,c),a._OrtFree=i=>(a._OrtFree=Y.ia)(i),a._OrtCreateTensor=(i,c,g,x,E,k)=>(a._OrtCreateTensor=Y.ja)(i,c,g,x,E,k),a._OrtGetTensorData=(i,c,g,x,E)=>(a._OrtGetTensorData=Y.ka)(i,c,g,x,E),a._OrtReleaseTensor=i=>(a._OrtReleaseTensor=Y.la)(i),a._OrtCreateRunOptions=(i,c,g,x)=>(a._OrtCreateRunOptions=Y.ma)(i,c,g,x),a._OrtAddRunConfigEntry=(i,c,g)=>(a._OrtAddRunConfigEntry=Y.na)(i,c,g),a._OrtReleaseRunOptions=i=>(a._OrtReleaseRunOptions=Y.oa)(i),a._OrtCreateBinding=i=>(a._OrtCreateBinding=Y.pa)(i),a._OrtBindInput=(i,c,g)=>(a._OrtBindInput=Y.qa)(i,c,g),a._OrtBindOutput=(i,c,g,x)=>(a._OrtBindOutput=Y.ra)(i,c,g,x),a._OrtClearBoundOutputs=i=>(a._OrtClearBoundOutputs=Y.sa)(i),a._OrtReleaseBinding=i=>(a._OrtReleaseBinding=Y.ta)(i),a._OrtRunWithBinding=(i,c,g,x,E)=>(a._OrtRunWithBinding=Y.ua)(i,c,g,x,E),a._OrtRun=(i,c,g,x,E,k,W,Z)=>(a._OrtRun=Y.va)(i,c,g,x,E,k,W,Z),a._OrtEndProfiling=i=>(a._OrtEndProfiling=Y.wa)(i),a._JsepOutput=(i,c,g)=>(a._JsepOutput=Y.xa)(i,c,g),a._JsepGetNodeName=i=>(a._JsepGetNodeName=Y.ya)(i);var go=()=>(go=Y.za)(),Rr=a._pthread_self=()=>(Rr=a._pthread_self=Y.Aa)(),hn=a._malloc=i=>(hn=a._malloc=Y.Ba)(i),yo=a._free=i=>(yo=a._free=Y.Ca)(i);a.__emscripten_tls_init=()=>(a.__emscripten_tls_init=Y.Da)();var bo=a.__emscripten_thread_init=(i,c,g,x,E,k)=>(bo=a.__emscripten_thread_init=Y.Fa)(i,c,g,x,E,k);a.__emscripten_thread_crashed=()=>(a.__emscripten_thread_crashed=Y.Ga)();var wo=(i,c,g,x)=>(wo=Y.Ha)(i,c,g,x),gn=i=>(gn=Y.Ia)(i),yn=a.__emscripten_thread_exit=i=>(yn=a.__emscripten_thread_exit=Y.Ja)(i),vo=()=>(vo=Y.Ka)(),$o=i=>($o=Y.La)(i),_o=(i,c)=>(_o=Y.Ma)(i,c),bn=()=>(bn=Y.Na)(),Br=i=>(Br=Y.Oa)(i),wn=i=>(wn=Y.Pa)(i),xo=a.dynCall_ii=(i,c)=>(xo=a.dynCall_ii=Y.Ra)(i,c),So=i=>(So=Y.Sa)(i),Co=()=>(Co=Y.Ta)(),Io=i=>(Io=Y.Ua)(i),Ao=()=>(Ao=Y.Va)();a.___start_em_js=945539,a.___stop_em_js=945700;function ud(){var i=Y;i=Object.assign({},i);var c=x=>()=>x()>>>0,g=x=>E=>x(E)>>>0;return i.za=c(i.za),i.Aa=c(i.Aa),i.Ba=g(i.Ba),i.emscripten_main_runtime_thread_id=c(i.emscripten_main_runtime_thread_id),i.Na=c(i.Na),i.Pa=g(i.Pa),i}a.wasmMemory=ne,a.stackAlloc=wn,a.stackSave=bn,a.stackRestore=Br,a.keepRuntimeAlive=()=>0Uo)});var Wo=pr((mp,yd)=>{yd.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\\n\'});var En,Tt,fr,Ur,hr,Ko,Pn,ie=q(()=>{"use strict";En=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},Tt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},fr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Ur=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},hr=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Ko=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",Pn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}});var Vr=q(()=>{"use strict"});var Yo=q(()=>{"use strict";Vr()});var Zo,Qo=q(()=>{"use strict";Zo="1.17.3"});var Xo,rt,On=q(()=>{"use strict";Qo();Xo="warning",rt={wasm:{},webgl:{},webgpu:{},versions:{common:Zo},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Xo=e}},get logLevel(){return Xo}};Object.defineProperty(rt,"logLevel",{enumerable:!0})});var qt,Jo=q(()=>{"use strict";On();qt=rt});var ea=q(()=>{"use strict"});var ta=q(()=>{"use strict";Nr()});var na=q(()=>{"use strict"});var oa=q(()=>{"use strict";Nr()});var Nr=q(()=>{"use strict";ea();ta();na();oa()});var Wr=q(()=>{"use strict";Nr()});var kn,aa,Mt,Et,Rn=q(()=>{"use strict";On();kn=(e,t)=>{(typeof rt.trace>"u"?!rt.wasm.trace:!rt.trace)||console.timeStamp(`${e}::ORT::${t}`)},aa=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let n=0;n{(typeof rt.trace>"u"?!rt.wasm.trace:!rt.trace)||aa("BEGIN",e)},Et=e=>{(typeof rt.trace>"u"?!rt.wasm.trace:!rt.trace)||aa("END",e)}});var ia=q(()=>{"use strict";Vr();Wr();Rn()});var sa=q(()=>{"use strict";ia()});var ua=q(()=>{"use strict"});var da=q(()=>{"use strict"});var la=q(()=>{"use strict"});var ca=q(()=>{"use strict"});var pa=q(()=>{"use strict";Vr();Wr()});var ma=q(()=>{"use strict";pa()});var Kt=q(()=>{"use strict";Yo();Jo();sa();Wr();ua();da();Rn();la();ca();ma()});var Td,Ed,fa,ha,ga,Pd,De,Pt=q(()=>{"use strict";ie();Td=["V","I","W","E","F"],Ed=(e,t)=>{console.log(`[${Td[e]},${new Date().toISOString()}]${t}`)},ga=(e,t)=>{fa=e,ha=t},Pd=(e,t)=>{let r=hr(e),o=hr(fa);r>=o&&Ed(r,typeof t=="function"?t():t)},De=(...e)=>{ha&&Pd(...e)}});var ya,ba=q(()=>{"use strict";ie();ya=(e,t)=>new(Ur(t))(e)});var Gr=q(()=>{"use strict"});var Hr,Od,wa,Dn,Bn,$a,_a=q(()=>{"use strict";Pt();Gr();Hr=e=>Math.ceil(e/16)*16,Od=1,wa=()=>Od++,Dn=async(e,t,r,o)=>{let n=Hr(r),s=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,s,0,n),e.flush(),await s.mapAsync(GPUMapMode.READ);let l=s.getMappedRange();if(o){let a=o();return a.set(new Uint8Array(l,0,r)),a}else return new Uint8Array(l.slice(0,r))}finally{s.destroy()}},Bn=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map}upload(t,r){let o=r.buffer,n=r.byteOffset,s=r.byteLength,u=Hr(s),l=this.storageCache.get(t);if(!l)throw new Error("gpu data for uploading does not exist");if(l.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${s}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:u,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=a.getMappedRange();new Uint8Array(p).set(new Uint8Array(o,n,s)),a.unmap();let m=this.backend.getCommandEncoder();this.backend.endComputePass(),m.copyBufferToBuffer(a,0,l.gpuData.buffer,0,u),De("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(a)}memcpy(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(r);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(o.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=Hr(o.originalSize),u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(t,r,o){let n;if(o){if(n=this.externalBuffers.get(o),n===void 0)throw new Error("previous buffer is not registered");if(t===o)return De("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`);this.externalBuffers.delete(o)}else n=wa();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,n),De("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, registered.`),n}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),De("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Hr(t),n,s=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,u=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||u){let a=s?this.freeBuffers:this.freeUniformBuffers,p=a.get(o);p||(p=[],a.set(o,p)),p.length>0?n=p.pop():n=this.backend.device.createBuffer({size:o,usage:r})}else n=this.backend.device.createBuffer({size:o,usage:r});let l={id:wa(),type:0,buffer:n};return this.storageCache.set(l.id,{gpuData:l,originalSize:t}),De("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=this.storageCache.get(t);if(!r)throw new Error("releasing data does not exist");return De("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("data does not exist");await Dn(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending)(t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(t.size).push(t):(t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(t.size).push(t):t.destroy();this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(o=>{o.destroy()}),this.capturedPendingBuffers.delete(t))}},$a=(...e)=>new Bn(...e)});var Mn,$e,je=q(()=>{"use strict";Mn=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},$e=e=>new Mn(e)});var zn,mt,z,zt,Lr,Fr,qr,_e=q(()=>{"use strict";zn=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},mt=class{static calcShape(t,r,o=!1){let n=t.length,s=r.length;if(n===0)return r;if(s===0)return t;let u=Math.max(t.length,r.length),l=new Array(u);if(o){if(n<2||s<2)return;let a=zn.calcMatMulShape([t[n-2],t[n-1]],[r[s-2],r[s-1]]);if(a===void 0)return;[l[u-2],l[u-1]]=a}for(let a=o?3:1;a<=u;a++){let p=n-a<0?1:t[n-a],m=s-a<0?1:r[s-a];if(p!==m&&p>1&&m>1)return;let f=Math.max(p,m);if(p&&m)l[u-a]=Math.max(p,m);else{if(f>1)return;l[u-a]=0}}return l}static isValidBroadcast(t,r){let o=t.length,n=r.length;if(o>n)return!1;for(let s=1;s<=o;s++)if(t[o-s]!==1&&t[o-s]!==r[n-s])return!1;return!0}},z=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let o=t.length;if(o===0)return[];let n=new Array(o),s=o-1;for(;s>=0;){if(t[s]%r===0){n[s]=t[s]/r;break}if(r%t[s]!==0)throw new Error("cannot convert shape");n[s]=1,r/=t[s],s--}for(s--;s>=0;s--)n[s]=t[s];return n}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,o){let n=1;for(let s=r;s=0;--n)o[n]=o[n+1]*t[n+1];return o}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(o=>this.normalizeAxis(o,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(o=>t[o]):t.slice().reverse()}static padShape(t,r){let o=t.length;return t.map((n,s)=>n+r[s]+r[s+o])}static areEqual(t,r){return t.length!==r.length?!1:t.every((o,n)=>o===r[n])}},zt=class e{static adjustPoolAttributes(t,r,o,n,s,u){if(!t&&o.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let l=0;l=o.length?o.push(r[l+2]):o[l]=r[l+2];for(let l=0;l=o[l]||u[l+o.length]>=o[l])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,o,n,s,u,l){if(l){if(s.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let a=0;a{"use strict";ie();_e();Kr=64,Vn=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},Pe=(e,t=1)=>{let r=Vn(e,t);return typeof r=="string"?r:r[0]},et=(e,t=1)=>{let r=Vn(e,t);return typeof r=="string"?r:r[1]},j=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:z.computeStrides(r)})}),t},Me=e=>e%4===0?4:e%2===0?2:1,Ye=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,st=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}f(${r})`,tt=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,re=(e,t,r,o)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?o==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:o==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Nn=(e,t,r,o,n)=>{let s=typeof r=="number",u=s?r:r.length,l=[...new Array(u).keys()],a=u<2?"u32":u<=4?`vec${u}`:`array`,p=Vn(t,n),m=typeof p=="string"?p:p[1],f=typeof p=="string"?p:p[0],b={indices:a,value:m,storage:f,tensor:t},_=G=>typeof G=="string"?G:`${G}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},$=s?"uniforms.":"",I=`${$}${e}_shape`,C=`${$}${e}_strides`,v="";for(let G=0;G ${b.indices} {\n var indices: ${b.indices};\n var current = offset;\n ${v}\n return indices;\n }`,T=G=>(y.offsetToIndices=!0,u<2?G:`o2i_${e}(${G})`),D=[];if(u>=2)for(let G=u-1;G>=0;G--)D.push(`${re(C,G,u)} * (indices[${G}])`);let U=u<2?"":`\n fn i2o_${e}(indices: ${b.indices}) -> u32 {\n return ${D.join("+")};\n }`,V=G=>(y.indicesToOffset=!0,u<2?G:`i2o_${e}(${G})`),H=(...G)=>u===0?"0u":`${b.indices}(${G.map(_).join(",")})`,R=(G,J)=>u<2?`${G}`:`${re(G,J,u)}`,L=(G,J,Se)=>u<2?`${G}=${Se};`:`${re(G,J,u)}=${Se};`,pe={},Ie=(G,J)=>{y.broadcastedIndicesToOffset=!0;let Se=`${J.name}broadcastedIndicesTo${e}Offset`;if(Se in pe)return`${Se}(${G})`;let Qe=[];for(let Xe=u-1;Xe>=0;Xe--){let Le=J.indicesGet("outputIndices",Xe+J.rank-u);Qe.push(`${R(C,Xe)} * (${Le} % ${R(I,Xe)})`)}return pe[Se]=`fn ${Se}(outputIndices: ${J.type.indices}) -> u32 {\n return ${Qe.length>0?Qe.join("+"):"0u"};\n }`,`${Se}(${G})`},we=(G,J)=>(()=>{if(b.storage===b.value)return`${e}[${G}]=${J};`;if(b.storage==="vec2"&&b.value==="i32")return`${e}[${G}]=vec2(u32(${J}), select(0u, 0xFFFFFFFFu, ${J} < 0));`;if(b.storage==="vec2"&&b.value==="u32")return`${e}[${G}]=vec2(u32(${J}), 0u);`;if(b.storage==="u32"&&b.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${J}));`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),ne=G=>(()=>{if(b.storage===b.value)return`${e}[${G}]`;if(b.storage==="vec2"&&b.value==="i32")return`i32(${e}[${G}].x)`;if(b.storage==="vec2"&&b.value==="u32")return`u32(${e}[${G}].x)`;if(b.storage==="u32"&&b.value==="vec4")return`vec4(bool(${e}[${G}] & 0xFFu), bool(${e}[${G}] & 0xFF00u), bool(${e}[${G}] & 0xFF0000u), bool(${e}[${G}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),ze=u<2?"":`\n fn get_${e}ByIndices(indices: ${b.indices}) -> ${m} {\n return ${ne(`i2o_${e}(indices)`)};\n }`,Q=u<2?"":(()=>{let G=l.map(Se=>`d${Se}: u32`).join(", "),J=l.map(Se=>`d${Se}`).join(", ");return`\n fn get_${e}(${G}) -> ${m} {\n return get_${e}ByIndices(${H(J)});\n }`})(),xe=(...G)=>{if(G.length!==u)throw new Error(`indices length must be ${u}`);let J=G.map(_).join(",");return u===0?ne("0u"):u===1?ne(J[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${J})`)},me=G=>u<2?ne(G):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${G})`),ue=u<2?"":`\n fn set_${e}ByIndices(indices: ${b.indices}, value: ${m}) {\n ${we(`i2o_${e}(indices)`,"value")}\n }`,se=u<2?"":(()=>{let G=l.map(Se=>`d${Se}: u32`).join(", "),J=l.map(Se=>`d${Se}`).join(", ");return`\n fn set_${e}(${G}, value: ${m}) {\n set_${e}ByIndices(${H(J)}, value);\n }`})();return{impl:()=>{let G=[],J=!1;return y.offsetToIndices&&(G.push(A),J=!0),y.indicesToOffset&&(G.push(U),J=!0),y.broadcastedIndicesToOffset&&(Object.values(pe).forEach(Se=>G.push(Se)),J=!0),y.set&&(G.push(se),J=!0),y.setByIndices&&(G.push(ue),J=!0),y.get&&(G.push(Q),J=!0),y.getByIndices&&(G.push(ze),J=!0),!s&&J&&G.unshift(`const ${I} = ${b.indices}(${r.join(",")});`,`const ${C} = ${b.indices}(${z.computeStrides(r).join(",")});`),G.join(`\n`)},type:b,offsetToIndices:T,indicesToOffset:V,broadcastedIndicesToOffset:Ie,indices:H,indicesGet:R,indicesSet:L,set:(...G)=>{if(G.length!==u+1)throw new Error(`indices length must be ${u}`);let J=G[u];if(typeof J!="string")throw new Error("value must be string");let Se=G.slice(0,u).map(_).join(",");return u===0?we("0u",J):u===1?we(Se[0],J):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${Se}, ${J})`)},setByOffset:we,setByIndices:(G,J)=>u<2?we(G,J):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${J});`),get:xe,getByOffset:ne,getByIndices:me,usage:o,name:e,strides:C,shape:I,rank:u}},M=(e,t,r,o=1)=>Nn(e,t,r,"input",o),F=(e,t,r,o=1)=>Nn(e,t,r,"output",o),jr=(e,t,r,o=1)=>Nn(e,t,r,"internal",o),Un=class{constructor(t){this.normalizedDispatchGroup=t;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=Kr){let r=typeof t=="number"?t:t[0],o=typeof t=="number"?1:t[1],n=typeof t=="number"?1:t[2],s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,u=s?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=s?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r*o*n}u + local_idx;`;return`@compute @workgroup_size(${r}, ${o}, ${n})\n fn main(${u}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let o=t.usage==="input"?"read":"read_write",n=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${n}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,o=1){return this.uniforms.push({name:t,type:r,length:o}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:o,length:n}of this.uniforms)if(n&&n>4)o==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(n/8)}>`):t.push(`${r}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?o:`vec${n}<${o}>`;t.push(`${r}:${s}`)}return`\n struct Uniforms { ${t.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}},xa=e=>new Un(e),jt=(e,t)=>{let r=e.length,o=[];for(let n=0;n1&&u===1&&o.unshift(s)}return o}});var kd,Sa,Rd,Bd,ot,Ca,Ia,Yt=q(()=>{"use strict";ie();_e();je();be();kd=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Sa=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Rd=(e,t)=>z.sortBasedOnPerm(e,Sa(e.length,t)),Bd=(e,t,r,o)=>{let n=[];n.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let s=0;s{let r=e.dataType,o=e.dims.length,n=Sa(o,t),s=Rd(e.dims,n),u=F("output",r,s.length),l=M("a",r,o),a=p=>`\n ${p.registerUniform("output_size","u32").declareVariables(l,u)}\n\n ${Bd(n,o,l,u)}\n\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${u.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${u.setByOffset("global_idx",l.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:p=>{let m=z.size(s);return{outputs:[{dims:s,dataType:p[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...j(p[0].dims,s)]}},getShaderSource:a}},Ca=(e,t)=>{kd(e.inputs),e.compute(ot(e.inputs[0],t.perm))},Ia=e=>$e({perm:e.perm})});var Dd,Md,zd,Ud,Vd,Nd,Wd,Gd,Hd,Ld,ft,Aa,Ta,Ea,Pa,Oa,ka,Ra,Ba,Da,Ma,za=q(()=>{"use strict";ie();_e();be();Yr();Yt();Dd={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Md={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},zd={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Ud={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Vd=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let s=0;se[s]);return[r,n]},Wd=(e,t)=>{let r=e.length+t.length,o=[],n=0;for(let s=0;s{for(let r=0;r{let r=[];if(!Gd(e,t)){for(let o=0;or.push(o))}return r},Ld=(e,t,r,o,n,s,u)=>{let l=r[0].dims,a=z.size(s),p=z.size(u),m=M("_A",r[0].dataType,l),f=F("output",n,s),b=32,_=`\n var aBestValues : array;\n `;return{name:e,shaderCache:t,getShaderSource:$=>`\n ${$.registerUniform("reduceSize","u32").declareVariables(m,f)}\n ${_}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${$.mainStart(b)}\n\n let outputIndex = global_idx / ${b};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${zd[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${b}) {\n let candidate = f32(${m.getByOffset("offset + k")});\n bestValue = ${Dd[o]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${b}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${Md[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${f.setByOffset("outputIndex",`${o==="mean"?`${f.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${f.type.storage}(${Ud[o]})`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:a},programUniforms:[{type:12,data:p}]})}},ft=(e,t,r,o)=>{let n=e.inputs.length===1?r:Wn(e.inputs,r),s=n.axes;s.length===0&&!n.noopWithEmptyAxes&&(s=e.inputs[0].dims.map((_,y)=>y));let u=z.normalizeAxes(s,e.inputs[0].dims.length),l=u,a=e.inputs[0],p=Hd(l,e.inputs[0].dims.length);p.length>0&&(a=e.compute(ot(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=Vd(l.length,a.dims.length));let[m,f]=Nd(a.dims,l),b=m;n.keepDims&&(b=Wd(m,u)),e.compute(Ld(t,{hint:n.cacheKey,inputDependencies:["type"]},[a],o,e.inputs[0].dataType,b,f),{inputs:[a]})},Aa=(e,t)=>{ft(e,"ReduceMeanShared",t,"mean")},Ta=(e,t)=>{ft(e,"ReduceL1Shared",t,"l1")},Ea=(e,t)=>{ft(e,"ReduceL2Shared",t,"l2")},Pa=(e,t)=>{ft(e,"ReduceLogSumExpShared",t,"logSumExp")},Oa=(e,t)=>{ft(e,"ReduceMaxShared",t,"max")},ka=(e,t)=>{ft(e,"ReduceMinShared",t,"min")},Ra=(e,t)=>{ft(e,"ReduceProdShared",t,"prod")},Ba=(e,t)=>{ft(e,"ReduceSumShared",t,"sum")},Da=(e,t)=>{ft(e,"ReduceSumSquareShared",t,"sumSquare")},Ma=(e,t)=>{ft(e,"ReduceLogSumShared",t,"logSum")}});var ht,Fd,Zr,Wn,gt,qd,Kd,jd,Yd,Zd,Qd,Xd,Jd,el,tl,yt,Ua,Va,Na,Wa,Ga,Ha,La,Fa,qa,Ka,Yr=q(()=>{"use strict";ie();_e();je();be();za();ht=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Fd=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Zr=(e,t,r,o,n,s,u=!1,l=!1)=>{let a=[],p=r[0].dims,m=p.length,f=z.normalizeAxes(n,m),b=!l&&f.length===0;p.forEach((I,C)=>{b||f.indexOf(C)>=0?u&&a.push(1):a.push(I)});let _=a.length,y=z.size(a);return{name:e,shaderCache:t,getShaderSource:I=>{let C=[],v=M("_A",r[0].dataType,m),A=F("output",s,_),T=o(v,A,f),D=T[2];for(let U=0,V=0;U=0?(u&&V++,D=`for(var j${U}: u32 = 0; j${U} < ${p[U]}; j${U}++) {\n ${T[2].includes("last_index")?`let last_index = j${U};`:""}\n ${v.indicesSet("input_indices",U,`j${U}`)}\n ${D}\n }`):(C.push(`${v.indicesSet("input_indices",U,A.indicesGet("output_indices",V))};`),V++);return`\n\n ${I.registerUniform("output_size","u32").declareVariables(v,A)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${v.type.indices};\n let output_indices = ${A.offsetToIndices("global_idx")};\n\n ${C.join(`\n`)}\n ${T[0]} // init ops for reduce max/min\n ${T[1]}\n ${D}\n ${T[3]}\n ${T.length===4?A.setByOffset("global_idx","value"):T.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...j(p,a)]})}},Wn=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),$e({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},gt=(e,t,r,o)=>{let n=e.inputs,s=n.length===1?r:Wn(n,r);e.compute(Zr(t,{hint:s.cacheKey,inputDependencies:["rank"]},[n[0]],s.noopWithEmptyAxes&&s.axes.length===0?Fd:o,s.axes,n[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},qd=(e,t)=>{ht(e.inputs),gt(e,"ReduceLogSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Kd=(e,t)=>{ht(e.inputs),gt(e,"ReduceL1",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},jd=(e,t)=>{ht(e.inputs),gt(e,"ReduceL2",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Yd=(e,t)=>{ht(e.inputs),gt(e,"ReduceLogSumExp",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},Zd=(e,t)=>{ht(e.inputs),gt(e,"ReduceMax",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(o.indicesSet("input_indices",l,0));return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = max(value, ${o.getByIndices("input_indices")});`,""]})},Qd=(e,t)=>{ht(e.inputs),gt(e,"ReduceMean",t,(o,n,s)=>{let u=1;for(let l=0;l=0||s.length===0)&&(u*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${o.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${u});`]})},Xd=(e,t)=>{ht(e.inputs),gt(e,"ReduceMin",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = min(value, ${o.getByIndices("input_indices")});`,""]})},Jd=(e,t)=>{ht(e.inputs),gt(e,"ReduceProd",t,(o,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},el=(e,t)=>{ht(e.inputs),gt(e,"ReduceSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},tl=(e,t)=>{ht(e.inputs),gt(e,"ReduceSumSquare",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += t * t;`,""])},yt=(e,t,r)=>{if(t.length===0)return r;let o=1,n=1;for(let s=0;s1024},Ua=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qd(e,t):Aa(e,t)},Va=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Kd(e,t):Ta(e,t)},Na=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jd(e,t):Ea(e,t)},Wa=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yd(e,t):Pa(e,t)},Ga=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zd(e,t):Oa(e,t)},Ha=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xd(e,t):ka(e,t)},La=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Jd(e,t):Ra(e,t)},Fa=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?el(e,t):Ba(e,t)},qa=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?tl(e,t):Da(e,t)},Ka=(e,t)=>{yt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qd(e,t):Ma(e,t)}});var ja,Ya,Za,Gn,Qa=q(()=>{"use strict";ie();je();Yr();ja=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Ya=(e,t)=>{ja(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(Zr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Za=(e,t)=>{ja(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(Zr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Gn=e=>$e(e)});var rl,nl,ol,al,Qr,il,Xa,Hn=q(()=>{"use strict";ie();Gr();be();rl=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5];if(u&&l)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error(\'Input "input" must have 3 dimensions\');let a=r.dims[0],p=r.dims[1],m=r.dims[2];if(n.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimensions\');if(o.dims.length!==2)throw new Error(\'Input "weights" is expected to have 2 dimensions\');if(o.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==o.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let f=n.dims[0]/3,b=f,_=b;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let A of t.qkvHiddenSizes)if(A%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");f=t.qkvHiddenSizes[0],b=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let y=p;if(f!==b)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==f+b+_)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let $=0;if(u){if(b!==_)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(u.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(u.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(u.dims[1]!==a)throw new Error(\'Input "past" second dimension must be batch_size\');if(u.dims[2]!==t.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(u.dims[4]!==b/t.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');t.pastPresentShareBuffer||($=u.dims[3])}let I=y+$,C=-1,v=0;if(s)throw new Error("Mask not supported");if(u)throw new Error("past is not supported");if(l)throw new Error("relativePositionBias is not supported");return{batchSize:a,sequenceLength:p,pastSequenceLength:$,kvSequenceLength:y,totalSequenceLength:I,maxSequenceLength:C,inputHiddenSize:m,hiddenSize:f,vHiddenSize:_,headSize:Math.floor(f/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},nl=(e,t,r,o)=>{let n=Me(o),s=64,u=o/n;u{let b=F("x",t.dataType,t.dims,n),_="thread_max_vector";n===2?_="max(thread_max_vector.x, thread_max_vector.y)":n===4&&(_="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let y=et(t.dataType),$=[{name:"d_inv",type:y},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return`\n var wgMax: array;\n var wgSum: array;\n ${f.registerUniforms($).declareVariables(b)}\n ${f.mainStart([s,1,1])}\n let localOffset = local_idx * uniforms.elements_per_wg;\n let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset;\n\n var thread_max_vector = ${Ye("f32",n,"-3.402823e+38f")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n thread_max_vector = max(${st(y,n,"x[offset + i]")}, thread_max_vector);\n }\n wgMax[local_idx] = ${_};\n workgroupBarrier();\n\n var maxValue = -3.402823e+38f;\n for (var i = 0u; i < ${s}; i++) {\n maxValue = max(wgMax[i], maxValue);\n }\n\n var sumVector = ${Ye("f32",n,"0")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n sumVector += exp(${st(y,n,"x[offset + i]")} - maxValue);\n }\n wgSum[local_idx] = ${tt("sumVector",n)};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${s}; i++) {\n sum += wgSum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n x[offset + i] = ${Ye(y,n,"uniforms.d_inv")};\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n let f32input = ${st(y,n,"x[offset + i]")};\n x[offset + i] = ${b.type.value}(exp(f32input - maxValue) / sum);\n }\n }\n }`};e.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${p};${n}`},getShaderSource:m,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:a})},{inputs:[t],outputs:[]})},ol=(e,t,r,o,n,s)=>{let u=[n.batchSize,n.numHeads,n.sequenceLength,n.kvSequenceLength+n.pastSequenceLength],l=s.scale===0?1/Math.sqrt(n.headSize):s.scale,a=Me(n.headSize),p=n.headSize/a,m=12,f={x:Math.ceil(n.totalSequenceLength/m),y:Math.ceil(n.sequenceLength/m),z:n.batchSize*n.numHeads},b=[{type:12,data:n.sequenceLength},{type:12,data:p},{type:12,data:n.totalSequenceLength},{type:12,data:n.kvSequenceLength},{type:t.dataType,data:l}],_=[t,r],y=I=>{let C=M("q",t.dataType,t.dims,a),v=M("key",r.dataType,r.dims,a),A=F("output",t.dataType,u),T=Pe(t.dataType),D=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:T}];return`\n const beta: ${T} = 1.0;\n const TILE_SIZE = ${m}u;\n\n var tileQ: array<${C.type.storage}, ${m*m}>;\n var tileK: array<${C.type.storage}, ${m*m}>;\n ${I.registerUniforms(D).declareVariables(C,v,A)}\n ${I.mainStart([m,m,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let lm = m + local_id.y;\n let ln = n + local_id.x;\n\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${Ye(T,a)};\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m + local_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:f,programUniforms:b}),getShaderSource:y},{inputs:_,outputs:[-1]})[0];return nl(e,$,n.batchSize*n.numHeads*n.sequenceLength,n.totalSequenceLength),$},al=(e,t,r,o)=>{let n=[o.batchSize,o.sequenceLength,o.vHiddenSize],s=12,u={x:Math.ceil(o.vHeadSize/s),y:Math.ceil(o.sequenceLength/s),z:o.batchSize*o.numHeads},l=[{type:12,data:o.sequenceLength},{type:12,data:o.totalSequenceLength},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.vHiddenSize}],a=p=>{let m=M("probs",t.dataType,t.dims),f=M("v",r.dataType,r.dims),b=F("output",t.dataType,n),_=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return`\n const TILE_SIZE = ${s}u;\n var tileQ: array<${m.type.value}, ${s*s}>;\n var tileK: array<${m.type.value}, ${s*s}>;\n ${p.registerUniforms(_).declareVariables(m,f,b)}\n ${p.mainStart([s,s,1])}\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${m.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:n,dataType:t.dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:l}),getShaderSource:a},{inputs:[t,r],outputs:[0]})[0]},Qr=(e,t,r,o,n,s,u,l,a,p,m)=>{let f=ol(e,t,r,a,p,m);al(e,f,o,p)},il=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],o=t.sequenceLength,n=t.inputHiddenSize,s=t.headSize,u=12,l={x:Math.ceil(t.headSize/u),y:Math.ceil(t.sequenceLength/u),z:t.batchSize*t.numHeads},a=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:o},{type:12,data:n},{type:12,data:s},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=f=>{let b=F("output_q",a[0].dataType,r),_=F("output_k",a[0].dataType,r),y=F("output_v",a[0].dataType,r),$=M("input",a[0].dataType,a[0].dims),I=M("weight",a[1].dataType,a[1].dims),C=M("bias",a[2].dataType,a[2].dims),v=$.type.storage,A=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`\n const TILE_SIZE = ${u}u;\n var tileInput: array<${v}, ${u*u}>;\n var tileWeightQ: array<${v}, ${u*u}>;\n var tileWeightK: array<${v}, ${u*u}>;\n var tileWeightV: array<${v}, ${u*u}>;\n ${f.registerUniforms(A).declareVariables($,I,C,b,_,y)}\n ${f.mainStart([u,u,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${v}(0);\n var valueK = ${v}(0);\n var valueV = ${v}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:p}),getShaderSource:m},{inputs:a,outputs:[-1,-1,-1]})},Xa=(e,t)=>{let r=rl(e.inputs,t),[o,n,s]=il(e,r);return Qr(e,o,n,s,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var sl,ul,dl,Ja,ei=q(()=>{"use strict";Kt();ie();_e();je();be();sl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(o,n,s)=>{let u=n.length;if(u!==o.length)throw new Error(`${s}: num dimensions != ${u}`);n.forEach((l,a)=>{if(l!==o[a])throw new Error(`${s}: dim[${a}] do not match`)})};if(e[0].dims.length>1){let o=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,o,"Invalid input scale"),r(e[2].dims,o,"Invalid input B"),r(e[3].dims,o,"Invalid input mean"),r(e[4].dims,o,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},ul=(e,t)=>{let{epsilon:r,spatial:o,format:n}=t,s=e[0].dims,u=o?Me(s[s.length-1]):1,l=n==="NHWC"&&s.length>1?u:1,a=z.size(s)/u,p=o,m=p?s.length:s,f=M("x",e[0].dataType,e[0].dims,u),b=M("scale",e[1].dataType,e[1].dims,l),_=M("bias",e[2].dataType,e[2].dims,l),y=M("inputMean",e[3].dataType,e[3].dims,l),$=M("inputVar",e[4].dataType,e[4].dims,l),I=F("y",e[0].dataType,m,u),C=()=>{let A="";if(o)A=`let cOffset = ${s.length===1?"0u":n==="NHWC"?`outputIndices[${s.length-1}] / ${u}`:"outputIndices[1]"};`;else if(n==="NCHW")A=`\n ${I.indicesSet("outputIndices","0","0")}\n let cOffset = ${I.indicesToOffset("outputIndices")};`;else{A=`var cIndices = ${b.type.indices}(0);\n cIndices[0] = outputIndices[${s.length-1}];`;for(let T=1;T`\n const epsilon = ${r};\n ${A.registerUniform("outputSize","u32").declareVariables(f,b,_,y,$,I)}\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${I.offsetToIndices(`global_idx * ${u}`)};\n ${C()}\n let scale = ${b.getByOffset("cOffset")};\n let bias = ${_.getByOffset("cOffset")};\n let inputMean = ${y.getByOffset("cOffset")};\n let inputVar = ${$.getByOffset("cOffset")};\n let x = ${f.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${I.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${o}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p?[{type:12,data:a},...j(s)]:[{type:12,data:a}]})}},dl=e=>$e(e),Ja=(e,t)=>{let{inputs:r,outputCount:o}=e,n=dl({...t,outputCount:o});if(qt.webgpu.validateInputContent&&sl(r,n),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ul(r,n))}});var ll,cl,ti,ri=q(()=>{"use strict";_e();be();ll=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},cl=e=>{let t=e[0].dims,r=e[0].dims[2],o=z.size(t)/4,n=e[0].dataType,s=M("input",n,t,4),u=M("bias",n,[r],4),l=M("residual",n,t,4),a=F("output",n,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:m=>`\n const channels = ${r}u / 4;\n ${m.declareVariables(s,u,l,a)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(o)}\n let value = ${s.getByOffset("global_idx")}\n + ${u.getByOffset("global_idx % channels")} + ${l.getByOffset("global_idx")};\n ${a.setByOffset("global_idx","value")}\n }`}},ti=e=>{ll(e.inputs),e.compute(cl(e.inputs))}});var pl,Ee,ni,oi,ai,ii,si,ui,di,li,ci,ml,pi,mi,fi,hi,Xr,gi,Jr,yi,bi,wi,vi,$i,_i,xi,Si,Ci,Ii,Ai,Ti,Ei,Pi,Oi,ki,Ri,Bi,Ln,Fn,Di,Mi,zi,en=q(()=>{"use strict";ie();_e();je();be();pl=(e,t,r,o,n,s)=>{let u=Math.ceil(t/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let a=M("inputData",r,[u],4),p=F("outputData",o,[u],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,p)}\n\n ${s??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${a.getByOffset("global_idx")};\n ${p.setByOffset("global_idx",l)}\n }`},Ee=(e,t,r,o,n,s=e.dataType)=>({name:t,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:u=>pl(u,z.size(e.dims),e.dataType,s,r,o),getRunData:u=>({outputs:[{dims:e.dims,dataType:s}],dispatchGroup:{x:Math.ceil(z.size(u[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(z.size(e.dims)/4)}]})}),ni=e=>{e.compute(Ee(e.inputs[0],"Abs","abs"))},oi=e=>{e.compute(Ee(e.inputs[0],"Acos","acos"))},ai=e=>{e.compute(Ee(e.inputs[0],"Acosh","acosh"))},ii=e=>{e.compute(Ee(e.inputs[0],"Asin","asin"))},si=e=>{e.compute(Ee(e.inputs[0],"Asinh","asinh"))},ui=e=>{e.compute(Ee(e.inputs[0],"Atan","atan"))},di=e=>{e.compute(Ee(e.inputs[0],"Atanh","atanh"))},li=e=>$e(e),ci=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute \'to\' from \'Cast\' operator): ${t.to}`)}e.compute(Ee(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},ml=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Fr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:qr;return $e({min:t,max:r})},pi=(e,t)=>{let r=e.inputs.length===1?t:ml(e.inputs),o=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Clip",n=>`clamp(${n}, clip_min_, clip_max_)`,`\n const clip_min_: vec4<${o}> = vec4(${o}(${r.min}));\n const clip_max_: vec4<${o}> = vec4(${o}(${r.max}));\n`,r.cacheKey),{inputs:[0]})},mi=e=>{e.compute(Ee(e.inputs[0],"Ceil","ceil"))},fi=e=>{e.compute(Ee(e.inputs[0],"Cos","cos"))},hi=e=>{e.compute(Ee(e.inputs[0],"Cosh","cosh"))},Xr=e=>$e(e),gi=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Elu",o=>`elu_vf32(${o})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Jr=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,yi=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Jr(t)))},bi=e=>{e.compute(Ee(e.inputs[0],"Exp","exp"))},wi=e=>{e.compute(Ee(e.inputs[0],"Floor","floor"))},vi=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Jr(t)))},$i=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"LeakyRelu",o=>`select(leaky_relu_alpha_ * ${o}, ${o}, ${o} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},_i=e=>{e.compute(Ee(e.inputs[0],"Not",t=>`!${t}`))},xi=e=>{e.compute(Ee(e.inputs[0],"Neg",t=>`-${t}`))},Si=e=>{e.compute(Ee(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Ci=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Ii=e=>{e.compute(Ee(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Ai=e=>$e(e),Ti=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"HardSigmoid",o=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${o} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Ei=e=>{e.compute(Ee(e.inputs[0],"Sin","sin"))},Pi=e=>{e.compute(Ee(e.inputs[0],"Sinh","sinh"))},Oi=e=>{e.compute(Ee(e.inputs[0],"Sqrt","sqrt"))},ki=e=>{e.compute(Ee(e.inputs[0],"Tan","tan"))},Ri=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Bi=e=>{e.compute(Ee(e.inputs[0],"Tanh",Ri))},Ln=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Ri("v")};\n}\n`,Fn=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Di=e=>{let t=et(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"FastGelu",Fn,Ln(t),void 0,e.inputs[0].dataType))},Mi=(e,t)=>{let r=et(e.inputs[0].dataType);return e.compute(Ee(e.inputs[0],"ThresholdedRelu",o=>`select(vec4<${r}>(0.0), ${o}, ${o} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},zi=e=>{e.compute(Ee(e.inputs[0],"Log","log"))}});var fl,hl,Vi,Ni=q(()=>{"use strict";_e();be();en();fl=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},hl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=M("input",e[0].dataType,e[0].dims,4),o=M("bias",e[0].dataType,[e[0].dims[2]],4),n=F("output",e[0].dataType,t,4),s=z.size(t)/4,u=Pe(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:a=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${a.declareVariables(r,o,n)}\n\n ${Jr(u)}\n\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(s)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${n.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},Vi=e=>{fl(e.inputs),e.compute(hl(e.inputs))}});var gl,yl,bt,Wi,Gi,Hi,Li,Fi,qi,Ki,ji,Yi,Zi,Qi=q(()=>{"use strict";ie();_e();be();gl=(e,t,r,o,n,s,u,l,a,p,m,f)=>{let b,_;typeof l=="string"?b=_=(v,A)=>`${l}((${v}),(${A}))`:typeof l=="function"?b=_=l:(b=l.scalar,_=l.vector);let y=F("outputData",m,o.length,4),$=M("aData",a,t.length,4),I=M("bData",p,r.length,4),C;if(n)if(s){let v=z.size(t)===1,A=z.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,D=r.length>0&&r[r.length-1]%4===0;v||A?C=y.setByOffset("global_idx",_(v?`${$.type.value}(${$.getByOffset("0")}.x)`:$.getByOffset("global_idx"),A?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"))):C=`\n let outputIndices = ${y.offsetToIndices("global_idx * 4u")};\n let offsetA = ${$.broadcastedIndicesToOffset("outputIndices",y)};\n let offsetB = ${I.broadcastedIndicesToOffset("outputIndices",y)};\n ${y.setByOffset("global_idx",_(u||T?$.getByOffset("offsetA / 4u"):`${$.type.value}(${$.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||D?I.getByOffset("offsetB / 4u"):`${I.type.value}(${I.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else C=y.setByOffset("global_idx",_($.getByOffset("global_idx"),I.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(A,T,D="")=>{let U=`aData[indexA${T}][componentA${T}]`,V=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${y.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${$.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let offsetB${T} = ${I.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${A}[${T}] = ${D}(${b(U,V)});\n `};m===9?C=`\n var data = vec4(0);\n ${v("data",0,"u32")}\n ${v("data",1,"u32")}\n ${v("data",2,"u32")}\n ${v("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:C=`\n ${v("outputData[global_idx]",0)}\n ${v("outputData[global_idx]",1)}\n ${v("outputData[global_idx]",2)}\n ${v("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables($,I,y)}\n\n ${f??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${C}\n }`},yl=(e,t,r,o,n,s,u=r.dataType)=>{let l=!z.areEqual(r.dims,o.dims),a=r.dims,p=z.size(r.dims),m=!1,f=!1,b=[l];if(l){let _=mt.calcShape(r.dims,o.dims,!1);if(!_)throw new Error("Can\'t perform binary op on the given tensors");a=_,p=z.size(a);let y=z.size(r.dims)===1,$=z.size(o.dims)===1,I=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,C=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;b.push(y),b.push($),b.push(I),b.push(C);let v=1;for(let A=1;A_.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:_=>gl(_,r.dims,o.dims,a,m,l,f,n,r.dataType,o.dataType,u,s),getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(z.size(a)/4)},...j(r.dims,o.dims,a)]})}},bt=(e,t,r,o,n,s)=>{e.compute(yl(t,n??"",e.inputs[0],e.inputs[1],r,o,s))},Wi=e=>{bt(e,"Add",(t,r)=>`${t}+${r}`)},Gi=e=>{bt(e,"Div",(t,r)=>`${t}/${r}`)},Hi=e=>{bt(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Li=e=>{bt(e,"Mul",(t,r)=>`${t}*${r}`)},Fi=e=>{let t=M("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;bt(e,"Pow",{scalar:(o,n)=>`pow_custom(${o},${n})`,vector:(o,n)=>`pow_vector_custom(${o},${n})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},qi=e=>{bt(e,"Sub",(t,r)=>`${t}-${r}`)},Ki=e=>{bt(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},ji=e=>{bt(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Yi=e=>{bt(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Zi=e=>{bt(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var wl,vl,$l,_l,Xi,Ji,es=q(()=>{"use strict";ie();_e();je();be();wl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,o=e[r],n=o.dataType,s=o.dims.length;e.forEach((u,l)=>{if(l!==r){if(u.dataType!==n)throw new Error("input tensors should be one type");if(u.dims.length!==s)throw new Error("input tensors should have the same shape");u.dims.forEach((a,p)=>{if(p!==t&&a!==o.dims[p])throw new Error("non concat dimensions must match")})}})},vl=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,$l=(e,t)=>{let r=e.length,o=[];for(let n=0;n{let n=z.size(r),s=new Array(e.length),u=new Array(e.length),l=0,a=[],p=[],m=[{type:12,data:n}];for(let $=0;$`uniforms.sizeInConcatAxis${$}`).join(","),y=$=>`\n\n ${(()=>{$.registerUniform("outputSize","u32");for(let I=0;I(${_});\n ${b} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${$l(u,f)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:r,dataType:o}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:m}),getShaderSource:y}},Xi=(e,t)=>{let r=e.inputs,o=r[0].dims,n=z.normalizeAxis(t.axis,o.length);wl(r,n);let s=o.slice();s[n]=r.reduce((l,a)=>l+(a.dims.length>n?a.dims[n]:0),0);let u=r.filter(l=>z.size(l.dims)>0);e.compute(_l(u,n,s,r[0].dataType),{inputs:u})},Ji=e=>$e({axis:e.axis})});var ut,dt,lt,tn,Ot=q(()=>{"use strict";ie();_e();ut=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},dt=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},lt=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},tn=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,o]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:o}}else if(t==="Clip"){let[r,o]=e?.activation_params||[Fr,qr];return{activation:t,clipMax:o,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var Ze,rn,nn=q(()=>{"use strict";Ze=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},rn=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var on,qn=q(()=>{"use strict";on=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var xl,Sl,gr,ts,Cl,yr,Il,an,br=q(()=>{"use strict";ie();_e();be();Ot();nn();xl=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,Sl=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,gr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32)=>{let a=t[1]*e[1],p=t[0]*e[0],m=n?a:s,f=n?s:a,b=m/t[0],_=s/t[1];if(!((n&&b===4&&e[1]===4||!n&&(b===3||b===4))&&m%t[0]===0&&s%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${b} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${b} must be 3 or 4.\n tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${m/b}>, ${f}>;\nvar mm_Bsub: array, ${p/e[0]}>, ${s}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${b};\nconst tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${a};\n\n let num_tiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${_};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${xl(n,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${o?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${b===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${Sl(n,b)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},ts=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,Cl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",yr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32,a=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],f=n?p:s,b=n?s:p;if(!(b%t[1]===0&&f%t[0]===0&&s%t[1]===0))throw new Error(`tileAHight ${b} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${f} must be divisible by workgroupSize[0]${t[0]}, tileInner ${s} must be divisible by workgroupSize[1]${t[1]}`);let _=b/t[1],y=f/t[0],$=s/t[1],I=a?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${p};\n let globalColStart = i32(workgroupId.x) * ${m};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${b}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${f}; inputCol = inputCol + ${t[0]}) {\n ${ts(n,o)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${n?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${p};\n\nlet tileRowA = i32(localId.y) * ${_};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${$};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${ts(n,o)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${$}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Cl(n)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${b}>;\n var mm_Bsub : array, ${s}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc : array, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${I}\n }\n`},Il=(e,t,r,o,n,s=!1)=>{let[u,l,a]=n,[p,m,f,b]=o,_=jt(u,a),y=jt(l,a),$=Pe(o[0].type.tensor),I=()=>{let A=m.rank,T=p.rank,D=`var aIndices: ${m.type.indices};`;for(let U=A-2-1,V=T-1;U>=0;U--,V--)D+=`\naIndices[${U}] = ${T>1?`batchIndices[${V}]`:"batchIndices"};`;return _.forEach(U=>{D+=`\naIndices[${U}] = 0;`}),D+=`\naIndices[${A-2}] = u32(row);\n aIndices[${A-1}] = u32(colIn);`,D},C=()=>{let A=f.rank,T=p.rank,D=`var bIndices: ${f.type.indices};`;for(let U=A-2-1,V=T-1;U>=0;U--,V--)D+=`\nbIndices[${U}] = ${T>1?`batchIndices[${V}]`:"batchIndices"};`;return y.forEach(U=>{D+=`\nbIndices[${U}] = 0;`}),D+=`\nbIndices[${A-2}] = u32(row);\n bIndices[${A-1}] = u32(colIn);`,D};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ze(e,$)} {\n var value = ${Ze(e,$)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n ${I()}\n value = ${m.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ze(e,$)} {\n var value = ${Ze(e,$)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n ${C()}\n value = ${f.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ze(e,$)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${s?"bias[colIn]":`${Ze(e,$)}(bias[row])`};`:""}\n ${r}\n ${b.setByIndices("vec3(coords)","value")}\n }\n }\n `},an=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s.slice(0,-2),a=u.slice(0,-2),p=o?o.slice(0,-2):r.slice(0,-2),m=z.size(p),f=s[s.length-2],b=s[s.length-1],_=u[u.length-1],y=b%4===0&&_%4===0,$=f<=8?[4,1,1]:[4,4,1],I=[8,8,1],C=[Math.ceil(_/I[0]/$[0]),Math.ceil(f/I[1]/$[1]),Math.ceil(m/I[2]/$[2])],v=y?4:1,A=[...l,f,b/v],T=A.length,D=[...a,b,_/v],U=D.length,V=[m,f,_/v],H=[{type:6,data:f},{type:6,data:_},{type:6,data:b}];dt(t,H),H.push(...j(p,A,D));let R=["rank","rank"],L=e.length>2;L&&(H.push(...j(e[2].dims)),R.push("rank")),H.push(...j(V));let pe=Ie=>{let we=p.length,ne=jr("batchDims",e[0].dataType,we,1),ze=Pe(e[0].dataType),Q=M("a",e[0].dataType,T,v),xe=M("b",e[1].dataType,U,v),me=F("result",e[0].dataType,V.length,v),ue=[Q,xe];if(L){let G=n?v:1;ue.push(M("bias",e[2].dataType,e[2].dims.length,G))}let se=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];lt(t,se);let he=Pe(me.type.tensor),Ae=ut(t,me.type.value,he),He=Il(v,L,Ae,[ne,Q,xe,me],[l,a,p],n);return`\n ${Ie.registerUniforms(se).registerInternalVariables(ne).declareVariables(...ue,me)}\n ${He}\n ${y?gr($,I,ze,ne):yr($,I,ze,ne)}\n `};return{name:"MatMul",shaderCache:{hint:`${$};${t.activation};${y};${n}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:C[0],y:C[1],z:C[2]},programUniforms:H}),getShaderSource:pe}}});var Al,rs,ns=q(()=>{"use strict";ie();Pt();be();Ot();nn();qn();br();Al=(e,t,r,o,n=!1,s,u=4,l=4,a=4,p="f32")=>{let m=L=>{switch(L){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${L} is not supported.`)}},f=L=>{switch(L){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${L} is not supported.`)}},b=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,_=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",$=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",I=e?"row":"col",C=e?"col":"row",v=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${I} / outWidth;\n let outCol = ${I} % outWidth;\n\n let WRow = ${C} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${C} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${C} % inChannels;\n var resData = ${Ze(u,p)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the \'same\' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${$}) {\n ${b}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${m(u)}\n }\n return resData;`,A=e?t&&o?`\n let col = colIn * ${u};\n ${v}`:`\n let col = colIn * ${u};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${v}\n }\n return ${Ze(u,p)}(0.0);`:o&&r?`\n let col = colIn * ${u};\n ${v}`:`\n let col = colIn * ${u};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${v}\n }\n return ${Ze(u,p)}(0.0);`,T=`${f(l)}`,D=Ze(a,p),U=e?Ze(u,p):Ze(l,p),V=e?Ze(l,p):Ze(u,p),H=ut(s,D,p);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${U} {\n ${e?A:T}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${V} {\n ${e?T:A}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${D}) {\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${_}\n ${rn(n)}\n ${H}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},rs=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],m=r[0],f=a?r[2]:r[3],b=a?r[1]:r[2],_=a?r[3]:r[1],y=a&&(p%4===0||p%3===0)&&_%4===0,$=a?_:f*b,I=a?f*b:_,C=[8,8,1],v=o<=8?[4,1,1]:[4,4,1],A=[Math.ceil($/C[0]/v[0]),Math.ceil(I/C[1]/v[1]),Math.ceil(m/C[2]/v[2])];De("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${A}`);let T=y?a&&p%4!==0?3:4:1,D=C[1]*v[1],U=C[0]*v[0],V=Math.max(C[0]*T,C[1]),H=o%D===0,R=n%U===0,L=s%V===0,pe=y?[T,4,4]:[1,1,1],Ie=[{type:6,data:o},{type:6,data:n},{type:6,data:s},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];dt(t,Ie),Ie.push(...j(e[0].dims,e[1].dims));let we=["rank","rank"];u&&(Ie.push(...j(e[2].dims)),we.push("rank")),Ie.push(...j(r));let ne=ze=>{let Q=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];lt(t,Q);let xe=y?4:1,me=Pe(e[0].dataType),ue=`\n fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${me}>`:me}) {\n result[flatIndex] = ${y?`vec4<${me}>`:me}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${y?`vec4<${me}>`:me}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${y?"/ 4":""}, value);\n }`,se=M("x",e[0].dataType,e[0].dims.length,T===3?1:T),he=M("w",e[1].dataType,e[1].dims.length,xe),Ae=[se,he],He=F("result",e[0].dataType,r.length,xe);if(u){let G=M("bias",e[2].dataType,e[2].dims.length,xe);Ae.push(G),ue+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${me}>`:me} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}return`\n ${on("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${ze.registerUniforms(Q).declareVariables(...Ae,He)}\n ${ue}\n ${Al(a,H,R,L,u,t,pe[0],pe[1],pe[2],me)}\n ${y?gr(v,C,me,void 0,!a,V):yr(v,C,me,void 0,!a,V,!1,void 0,l)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${T};${y};${H};${R};${L};${D};${U};${V}`,inputDependencies:we},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:Ie}),getShaderSource:ne}}});var Kn,os,as=q(()=>{"use strict";ie();_e();be();jn();Ot();Kn=(e,t,r)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",s=e[0].dims,u=e[1].dims,l=u[0]/t.group,a=t.format==="NHWC",p=sn(s,u,t.dilations,t.pads,t.strides,a),m=z.size(p),f=[{type:12,data:m},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:l}];dt(t,f),f.push(...j(s,u,p));let b=["rank","rank"];o&&(f.push(...j(e[2].dims)),b.push("rank")),f.push(...j(p));let _=y=>{let $=F("output",e[0].dataType,p.length),I=Pe($.type.tensor),C=ut(t,$.type.value,I),v=M("x",e[0].dataType,s.length),A=M("w",e[1].dataType,u.length),T=[v,A];o&&T.push(M("b",e[2].dataType,e[2].dims));let D=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return lt(t,D),`\n ${y.registerUniforms(D).declareVariables(...T,$)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${$.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${a?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${a?1:2}], outputIndices[${a?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel / uniforms.output_channels_per_group;\n\n var value: ${$.type.value} = ${$.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = group_id * uniforms.w_shape[1] + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[${a?1:2}]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[${a?2:3}]) {\n continue;\n }\n\n let xVal = ${a?v.get("batch","xHeight","xWidth","input_channel"):v.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${A.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${n}\n ${C}\n ${$.setByOffset("global_idx","value")}\n }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:b},getRunData:()=>({outputs:[{dims:r?r(p):p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:f}),getShaderSource:_}},os=(e,t,r)=>{let o=e.length>2,n=Me(r[3]),s=Me(r[2]),u=z.size(r)/n/s,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],a=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[r[0],r[1],r[2],r[3]/n],m=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];dt(t,m),m.push(...j(l,a,p));let f=(s-1)*t.strides[1]+a[1],b=_=>{let y=F("output",e[0].dataType,p.length,n),$=Pe(y.type.tensor),I=ut(t,y.type.value,$),C=M("x",e[0].dataType,l.length,n),v=M("w",e[1].dataType,a.length,n),A=[C,v];o&&A.push(M("b",e[2].dataType,e[2].dims,n));let T=o?"value += b[output_channel];":"",D=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return lt(t,D),`\n ${_.registerUniforms(D).declareVariables(...A,y)}\n ${_.mainStart()}\n ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${s}u;\n let col = (index1 % width1) * ${s}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${C.type.value}, ${f}>;\n var values: array<${y.type.value}, ${s}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w\'s height/width.\n for (var w_height: u32 = 0u; w_height < ${a[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${f}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${C.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${C.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${a[1]}; w_width++) {\n let w_val = ${v.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${s}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${s}u; i++) {\n var value = values[i];\n ${T}\n ${I}\n ${y.set("batch","row","col + i","output_channel","value")};\n }\n }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${n};${s};${f};${a[0]};${a[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:b}}});var Yn,Tl,is,Zn=q(()=>{"use strict";ie();_e();br();be();Ot();Yn=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s[s.length-2],a=u[u.length-1],p=s[s.length-1],m=Me(a),f=Me(p),b=Me(l),_=z.size(r)/m/b,y=e.length>2,$=o?o.slice(0,-2):r.slice(0,-2),C=[z.size($),l,a],v=[{type:12,data:_},{type:12,data:l},{type:12,data:a},{type:12,data:p}];dt(t,v),v.push(...j($,s,u)),y&&v.push(...j(e[2].dims)),v.push(...j(C));let A=T=>{let D=jr("batch_dims",e[0].dataType,$.length),U=M("a",e[0].dataType,s.length,f),V=M("b",e[1].dataType,u.length,m),H=F("output",e[0].dataType,C.length,m),R=Pe(H.type.tensor),L=ut(t,H.type.value,R),pe=[U,V],Ie="";if(y){let se=n?m:1;pe.push(M("bias",e[2].dataType,e[2].dims.length,se)),Ie=`${n?`value += bias[col / ${se}];`:`value += ${H.type.value}(bias[row + i]);`}`}let we=s.slice(0,-2),ne=u.slice(0,-2),ze=jt(we,$),Q=jt(ne,$),xe=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];lt(t,xe);let me=(se,he)=>{let Ae=se.rank,He=se.name;if(Ae===2)return`var ${He}_indices = ${se.type.indices}(0u, 0u);`;let G=D.rank,J=`var ${He}_indices: ${se.type.indices};`;for(let Se=Ae-2-1,Qe=G-1;Se>=0;Se--,Qe--)J+=`\n${He}_indices[${Se}] = ${G>1?`batch_indices[${Qe}]`:"batch_indices"};`;return he.forEach(Se=>{J+=`\n${He}_indices[${Se}] = 0;`}),J+=`${He}_indices[${Ae-2}] = 0u;\n ${He}_indices[${Ae-1}] = 0u;`,J},ue=()=>{let se=`var a_data: ${U.type.value};`;for(let he=0;he;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${f}) {\n ${ue()}\n }\n for (var i = 0u; i < ${b}u; i++) {\n var value = values[i];\n ${Ie}\n ${L}\n let cur_indices = ${H.type.indices}(batch, row + i, col);\n let offset = ${H.indicesToOffset("cur_indices")};\n ${H.setByOffset(`offset / ${m}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${f};${b};${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:A}},Tl=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},is=e=>{Tl(e.inputs);let t=mt.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can\'t use matmul on the given tensors");let r=t[t.length-1],o=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&o<8?e.compute(Yn(e.inputs,{activation:""},t)):e.compute(an(e.inputs,{activation:""},t))}});var sn,Qn,El,ss,Xn,Pl,Ol,Jn,jn=q(()=>{"use strict";_e();ns();br();as();Ot();Zn();Yt();sn=(e,t,r,o,n,s)=>{let u=e[0],l=e.slice(s?1:2,s?3:4),a=l.length,p=t[0],f=t.slice(2).map((y,$)=>y+(y-1)*(r[$]-1)),_=l.map((y,$)=>y+o[$]+o[$+a]).map((y,$)=>Math.floor((y-f[$]+n[$])/n[$]));return _.splice(0,0,u),_.splice(s?3:1,0,p),_},Qn=[2,3,1,0],El=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[1]*t.group;if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ss=(e,t)=>{let r=e.kernelShape.slice();for(let s=2;s{let t=tn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,s=e.group,u=e.kernel_shape,l=e.pads,a=e.strides,p=e.w_is_const();return{autoPad:o,format:r,dilations:n,group:s,kernelShape:u,pads:l,strides:a,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Pl=(e,t,r)=>{let o=ss(r,t),n=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&n&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let V=sn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,n),H=e.kernelCustomData.wT??e.compute(ot(t[1],Qn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=H);let R=[t[0],H];t.length===3&&R.push(t[2]),e.compute(os(R,o,V),{inputs:R})}else e.compute(Kn(t,o));return}let s=t.length===3,u=t[0].dims[n?1:2],l=t[0].dims[n?2:3],a=t[0].dims[n?3:1],p=t[1].dims[2],m=t[1].dims[3],f=sn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,n),b=f[n?1:2],_=f[n?2:3],y=f[n?3:1],$=n&&p===u&&m===l&&r.pads[0]===0&&r.pads[1]===0;if($||p===1&&m===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let U=f[0],V,H,R,L=[];if(n){let we=e.kernelCustomData.wT??e.compute(ot(t[1],Qn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=we),$){let ne=u*l*a;V=t[0].reshape([1,U,ne]),H=we.reshape([1,ne,y]),R=[1,U,y]}else V=t[0].reshape([U,u*l,a]),H=we.reshape([1,a,y]),R=[U,b*_,y];L.push(V),L.push(H)}else V=t[0].reshape([U,a,u*l]),H=t[1].reshape([1,y,a]),R=[U,y,b*_],L.push(H),L.push(V);s&&L.push(t[2]);let pe=R[2],Ie=L[0].dims[L[0].dims.length-1];pe<8&&Ie<8?e.compute(Yn(L,o,f,R,n),{inputs:L}):e.compute(an(L,o,f,R,n),{inputs:L});return}let I=!0,C=e.kernelCustomData.wT??e.compute(ot(t[1],Qn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=C);let v=[t[0],C];s&&v.push(t[2]);let A=n?b*_:y,T=n?y:b*_,D=p*m*a;e.compute(rs(v,o,f,A,T,D,s,I),{inputs:v})},Ol=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&o.push(e.inputs[2]);let n=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),u=[1].concat(t.dilations),l=[1].concat(t.kernelShape),a=ss({...t,pads:n,strides:s,dilations:u,kernelShape:l},o);e.compute(Kn(o,a,p=>r?[p[0],p[2],p[3]]:[]))},Jn=(e,t)=>{El(e.inputs,t),e.inputs[0].dims.length===3?Ol(e,t):Pl(e,e.inputs,t)}});var kl,us,ds=q(()=>{"use strict";ie();Pt();be();Ot();nn();qn();br();kl=(e,t=!1,r,o,n=4)=>{let s=C=>{switch(C){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${o}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${C} is not supported.`)}},u=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,l=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,a=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=e?"row":"col",f=e?"col":"row",b=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${m} / outWidth;\n let outCol = ${m} % outWidth;\n\n let WRow = ${f} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${f} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${a}) || fract(xR) > 0.0) {\n return ${o}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) {\n return ${o}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${f} % inChannels;\n ${u}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${n}];`,_=e?`\n let col = colIn * ${n};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${b}\n }\n return ${o}(0.0);`:`\n let col = colIn * ${n};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${b}\n }\n return ${o}(0.0);`,y=`\n let col = colIn * ${n};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${s(n)}\n }\n return ${o}(0.0);\n `,$=ut(r,o);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?_:y}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?y:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${o}) {\n let col = colIn * ${n};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${l}\n ${rn(t)}\n ${$}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${n}] = value;\n }\n }`},us=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],m=r[0],f=a?r[2]:r[3],b=a?r[1]:r[2],_=a?r[3]:r[1],y=a?p%4===0&&_%4===0:f%4===0&&_%4===0,$=a?_:f*b,I=a?f*b:_,C=y?[8,8,1]:[$<=4||I<=4?4:16,$>4&&I<=4?4:16,1],v=y?[4,4,1]:[$<=4?1:4,$>4&&I<=4?1:4,1],A=[Math.ceil($/C[0]/v[0]),Math.ceil(I/C[1]/v[1]),Math.ceil(m/C[2]/v[2])];De("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${A}`);let T=y?4:1,D=Math.max(C[0]*T,C[1]),U=y?4:1,V=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],H=[V[0]+(t.dilations[0]<=1?0:(V[0]-1)*(t.dilations[0]-1)),V[1]+(t.dilations[1]<=1?0:(V[1]-1)*(t.dilations[1]-1))],R=[H[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),H[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],L=[{type:6,data:o},{type:6,data:n},{type:6,data:s},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:V},{type:6,data:R}];dt(t,L),L.push(...j(e[0].dims,e[1].dims));let pe=["rank","rank"];u&&(L.push(...j(e[2].dims)),pe.push("rank")),L.push(...j(r));let Ie=we=>{let ne=M("x",e[0].dataType,e[0].dims.length,U),ze=M("w",e[1].dataType,e[1].dims.length,1),Q=F("result",e[0].dataType,r.length,U),xe=[ne,ze],me="";if(u){let he=M("bias",e[2].dataType,e[2].dims.length,U);xe.push(he),me+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${he.type.value} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}let ue=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:V.length},{name:"pads",type:"i32",length:R.length}];lt(t,ue);let se=Pe(e[0].dataType,1);if(se!=="f16"&&se!=="f32")throw new Error(`elemType ${se} is not supported.`);return`\n ${on("uniforms.result_strides")}\n ${we.registerUniforms(ue).declareVariables(...xe,Q)};\n ${me}\n ${kl(a,u,t,ne.type.value,T)}\n ${y?gr(v,C,se,void 0,!a,D):yr(v,C,se,void 0,!a,D,!1,void 0,l)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${v};${C};${y}`,inputDependencies:pe},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:L}),getShaderSource:Ie}}});var Rl,eo,ls=q(()=>{"use strict";ie();Pt();_e();be();Rl=(e,t,r,o,n,s=!1,u,l,a=!1)=>{let p=a?1:2,m=a?2:3,f=a?3:1,b=s?2:1,_=`\n fn setOutputAtIndex(flatIndex : u32, value : ${s?`vec4<${u}>`:u}) {\n result[flatIndex] = ${s?`vec4<${u}>`:u}(value);\n }`;o&&(_+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${s?`vec4<${u}>`:u} {\n return bias[coords.${a?"w":"y"}${s?"/ 4":""}];\n }`);let y=s?4:1,$=M("W",t[1].dataType,t[1].dims.length,y),I=M("Dy",t[0].dataType,t[0].dims.length,y),C=[I,$];o&&C.push(M("bias",t[2].dataType,[r[f]].length,y));let v=F("result",t[0].dataType,r.length,y),A=`{\n let batch: u32 = ${n?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${n?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${n?"global_id.y":"workgroup_id.y"} * ${b};\n let d1: u32 = ${n?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${b}>;\n for (var i = 0; i < ${b}; i++) {\n dotProd[i] = vec4<${u}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${u}(dyCorner.x) + ${u}(wR)) / ${u}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${u}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${u}(dyCorner.y) + ${u}(wC)) / ${u}(uniforms.strides.y);\n let dyC2 = (${u}(dyCorner.y) + 1.0 + ${u}(wC)) / ${u}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${u}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${u}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${I.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${I.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${f}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${I.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${$.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${I.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${u}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${b}; i = i + 1) {\n let value = dotProd[i] + ${o?"bias[c+i]":`vec4<${u}>(0.0)`};\n ${v.set("batch","r","c + i","d1","value")};\n }\n }`,T=`\n let outputIndices = ${v.offsetToIndices("global_idx")};\n let batch = ${v.indicesGet("outputIndices",0)};\n let d1 = ${v.indicesGet("outputIndices",f)};\n let r = ${v.indicesGet("outputIndices",p)};\n let c = ${v.indicesGet("outputIndices",m)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${u}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${u}(dyRCorner) + ${u}(wR)) / ${u}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${u}(uniforms.Dy_shape[${p}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${u}(dyCCorner) + ${u}(wC)) / ${u}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${u}(uniforms.Dy_shape[${m}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${a?I.get("batch","idyR","idyC","inputChannel"):I.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${$.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${o?"bias[d1]":`${u}(0.0)`};\n ${v.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(l).declareVariables(...C,v)}\n ${_}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${s?A:T}}`},eo=(e,t,r)=>{let o=e.length>2,n=t.outputShape,s=z.size(n),u=[Math.ceil(s/64),1,1];De("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let l=t.format==="NHWC",a=["rank","rank"],p=[t.strides[0],t.strides[1]],m=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],f=[t.dilations[0],t.dilations[1]],b=[m[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),m[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],_=[b[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),b[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],y=!1,$=t.group,I=e[1].dims,C=I[0]/$,v=I[1],A=[{type:6,data:s},{type:12,data:p},{type:12,data:m},{type:12,data:f},{type:12,data:b},{type:6,data:_},{type:12,data:C},{type:12,data:v},...j(e[0].dims,e[1].dims)];o&&(A.push(...j(e[2].dims)),a.push("rank")),A.push(...j(n));let T=u[1]===1&&u[2]===1,D=U=>{let V=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.length},{name:"filter_dims",type:"u32",length:m.length},{name:"dilations",type:"u32",length:m.length},{name:"effective_filter_dims",type:"u32",length:b.length},{name:"pads",type:"i32",length:_.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],H=Pe(e[0].dataType);return`${Rl(U,e,n,o,T,y,H,V,l)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:a},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],programUniforms:A}),getShaderSource:D}}});var Bl,Dl,Ml,cs,ps,zl,Ul,Vl,Nl,ms,fs=q(()=>{"use strict";ds();ls();Ot();Yt();Bl=(e,t,r,o,n,s)=>(e-1)*t+r+(o-1)*n+1-s,Dl=(e,t,r,o,n)=>{let s=Math.floor(e/2);t==="SAME_UPPER"?(r[o]=s,r[n]=e-s):t==="SAME_LOWER"&&(r[o]=e-s,r[n]=s)},Ml=(e,t,r,o,n,s,u,l,a,p)=>{let m=e.length-2,f=p.length===0;if(a.length===0)for(let y=0;y{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((f,b)=>f*b,1)===0){r.length=0;for(let f=2;ff+b,0)===0){let f=t[0].dims.length-2;a=new Array(f).fill(1)}let p=e.strides.slice();if(p.reduce((f,b)=>f+b,0)===0){let f=t[0].dims.length-2;p=new Array(f).fill(1)}Ml(l,r,a,e.autoPad,e.group,n,p,o,u,s);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:n,outputPadding:u,outputShape:s,dilations:a,strides:p}),m},ps=e=>{let t=tn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,s=e.group,u=e.kernelShape,l=e.pads,a=e.strides,p=e.wIsConst(),m=e.outputPadding,f=e.outputShape;return{autoPad:o,format:r,dilations:n,group:s,kernelShape:u,outputPadding:m,outputShape:f,pads:l,strides:a,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},zl=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[0];if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.reduce((m,f)=>m+f,0)>0&&t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.reduce((m,f)=>m+f,0)>0&&t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.reduce((m,f)=>m+f,0)>0&&t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.outputPadding.length!==s&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${s}D`);if(t.kernelShape.reduce((m,f)=>m+f,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Ul=[2,3,1,0],Vl=(e,t,r)=>{let o=cs(r,t),n=r.format==="NHWC",s=o.outputShape,u=s[n?3:1],l=t[0].dims[n?3:1];if(o.group!==1||u===1&&l===1){e.compute(eo(t,o));return}let a=s[n?1:2],p=s[n?2:3],m=t[1].dims[2],f=t[1].dims[3],b=n?a*p:u,_=n?u:a*p,y=m*f*l,$=!0,I=e.kernelCustomData.wT??e.compute(ot(t[1],Ul),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let C=[t[0],I],v=t.length===3;v&&(!n&&t[2].dims.length===1?C.push(t[2].reshape([t[2].dims[0],1,1])):C.push(t[2])),e.compute(us(C,o,s,b,_,y,v,$),{inputs:C})},Nl=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];o.length===3&&o.push(e.inputs[2]);let n=t.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let s=t.dilations;(s.length===0||s[0]===0)&&(s=[1]);let u=t.strides;(u.length===0||u[0]===0)&&(u=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],u=[1].concat(u),s=[1].concat(s),n=[1].concat(n);let a=cs({...t,pads:l,strides:u,dilations:s,kernelShape:n},o);e.compute(eo(o,a,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},ms=(e,t)=>{zl(e.inputs,t),e.inputs[0].dims.length===3?Nl(e,t):Vl(e,e.inputs,t)}});var Wl,hs,gs,ys=q(()=>{"use strict";ie();_e();je();be();Wl=(e,t,r,o)=>{let n=z.size(t),s=t.length,u=M("input",e,s),l=F("output",e,s),a=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=z.normalizeAxis(a,s),m=f=>{let b=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,_=re("uniforms.input_shape","uniforms.axis",s),y=o.reverse?b+(o.exclusive?" + 1":""):"0",$=o.reverse?_:b+(o.exclusive?"":" + 1");return`\n ${f.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,l)}\n ${f.mainStart()}\n ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${l.offsetToIndices("global_idx")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${$};\n for (var i : i32 = first; i < last; i++) {\n ${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${u.getByIndices("inputIndices")};\n }\n ${l.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:o.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},{type:6,data:p},...j(t,t)]}),getShaderSource:m}},hs=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,n=e.inputs[1];e.compute(Wl(o,r,n,t),{inputs:[0]})},gs=e=>{let t=e.exclusive===1,r=e.reverse===1;return $e({exclusive:t,reverse:r})}});var to,un,bs,Gl,Hl,ro,no,ws,Ll,vs,$s,_s=q(()=>{"use strict";ie();_e();je();be();to="[a-zA-Z]|\\\\.\\\\.\\\\.",un="("+to+")+",bs="^"+un+"$",Gl="("+un+",)*"+un,Hl="^"+Gl+"$",ro=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let o=this.symbolToIndices.get(t);o===void 0?o=[r]:o.push(r),this.symbolToIndices.set(t,o)}},no=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[o,n]=r.includes("->")?r.split("->",2):[r,""];if(!o.match(RegExp(Hl)))throw new Error("Invalid LHS term");if(o.split(",").forEach((l,a)=>{let p=t[a].dims.slice();if(!l.match(RegExp(bs)))throw new Error("Invalid LHS term");let m=this.processTerm(l,!0,p,a);this.lhs.push(m)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([l,a])=>a.count===1||l==="...").map(([l])=>l).join("");else if(!n.match(RegExp(un)))throw new Error("Invalid RHS");n.match(RegExp(to,"g"))?.forEach(l=>{if(l==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(l);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(t,r,o){let n=this.symbolToInfo.get(t);if(n!==void 0){if(n.dimValue!==r&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(o)}else n={count:1,dimValue:r,inputIndices:[o]};this.symbolToInfo.set(t,n)}processTerm(t,r,o,n=-1){let s=o.length,u=!1,l=[],a=0;if(!t.match(RegExp(bs))&&!r&&t!=="")throw new Error("Invalid LHS term");let p=t.match(RegExp(to,"g")),m=new ro(n);return p?.forEach((f,b)=>{if(f==="..."){if(u)throw new Error("Only one ellipsis is allowed per input term");u=!0;let _=s-p.length+1;if(_<0)throw new Error("Ellipsis out of bounds");if(l=o.slice(a,a+_),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let y=0;ye+"_max",Ll=(e,t,r,o)=>{let s=e.map(m=>m.length).map((m,f)=>M(`input${f}`,t,m)),u=z.size(o),l=F("output",t,o.length),a=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),p=m=>{let f=[],b="var prod = 1.0;",_="var sum = 0.0;",y="sum += prod;",$=[],I=[],C=[],v=[],A=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((D,U)=>{if(r.rhs.symbolToIndices.has(U)){let V=r.rhs.symbolToIndices.get(U)?.[0];V!==void 0&&r.lhs.forEach((H,R)=>{if(D.inputIndices.includes(R)){let L=H.symbolToIndices.get(U);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(pe=>{f.push(`${s[R].indicesSet(`input${R}Indices`,pe,l.indicesGet("outputIndices",V))}`)})}})}else r.lhs.forEach((V,H)=>{if(D.inputIndices.includes(H)){let R=V.symbolToIndices.get(U);if(R===void 0)throw new Error("Invalid symbol error");R.forEach(L=>{$.push(`${s[H].indicesSet(`input${H}Indices`,L,`${U}`)}`)}),v.push(`prod *= ${s[H].getByIndices(`input${H}Indices`)};`)}}),I.push(`for(var ${U}: u32 = 0; ${U} < uniforms.${ws(U)}; ${U}++) {`),C.push("}")});let T=A?[...f,`let sum = ${s.map((D,U)=>D.getByIndices(`input${U}Indices`)).join(" * ")};`]:[...f,_,...I,...$,b,...v,y,...C];return`\n ${m.registerUniforms(a.map(D=>({name:`${ws(D)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,l)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${l.offsetToIndices("global_idx")};\n ${s.map((D,U)=>`var input${U}Indices: ${s[U].type.indices};`).join(`\n`)}\n ${T.join(`\n`)};\n ${l.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let m=a.filter(b=>r.symbolToInfo.has(b)).map(b=>({type:12,data:r.symbolToInfo.get(b)?.dimValue||0}));m.push({type:12,data:u});let f=e.map((b,_)=>[...j(b)]).reduce((b,_)=>b.concat(_),m);return f.push(...j(o)),{outputs:[{dims:o,dataType:t}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}},getShaderSource:p}},vs=(e,t)=>{let r=new no(e.inputs,t.equation),o=r.outputDims,n=e.inputs.map((s,u)=>s.dims);e.compute(Ll(n,e.inputs[0].dataType,r,o))},$s=e=>{let t=e.equation.replace(/\\s+/g,"");return $e({equation:t})}});var Fl,xs,ql,Kl,Ss,Cs=q(()=>{"use strict";ie();_e();be();Fl=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=r.length{let r=e.length-t.length,o=[];for(let n=0;ne.length>t.length?xs(e,t):xs(t,e),Kl=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=ql(t,r),n=e[0].dataType,s=n===9?4:1,u=Math.ceil(z.size(o)/s),l=p=>{let m=M("input",n,t.length,s),f=F("output",n,o.length,s),b;if(n===9){let _=(y,$,I="")=>`\n let outputIndices${$} = ${f.offsetToIndices(`outputOffset + ${$}u`)};\n let offset${$} = ${m.broadcastedIndicesToOffset(`outputIndices${$}`,f)};\n let index${$} = offset${$} / 4u;\n let component${$} = offset${$} % 4u;\n ${y}[${$}] = ${I}(${m.getByOffset(`index${$}`)}[component${$}]);\n `;b=`\n let outputOffset = global_idx * ${s};\n var data = vec4(0);\n ${_("data",0,"u32")}\n ${_("data",1,"u32")}\n ${_("data",2,"u32")}\n ${_("data",3,"u32")}\n ${f.setByOffset("global_idx","data")}\n }`}else b=`\n let outputIndices = ${f.offsetToIndices("global_idx")};\n let inputOffset = ${m.broadcastedIndicesToOffset("outputIndices",f)};\n ${f.setByOffset("global_idx",m.getByOffset("inputOffset"))}\n }`;return`\n ${p.registerUniform("vec_size","u32").declareVariables(m,f)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${b}`},a=[{type:12,data:u},...j(t,o)];return{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:["rank"]},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:a})}},Ss=e=>{Fl(e.inputs),e.compute(Kl(e.inputs),{inputs:[0]})}});var jl,Is,As=q(()=>{"use strict";ie();_e();be();en();jl=e=>{let t=e[0].dataType,r=z.size(e[0].dims),o=z.size(e[1].dims),n=o%4===0,s=u=>{let l=M("x",t,[1],4),a=M("bias",t,[1],4),p=F("y",t,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],f=_=>`\n let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;\n let bias${_} = ${a.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,b=n?`\n let bias = ${a.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${f(0)}${f(1)}${f(2)}${f(3)}\n let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${u.registerUniforms(m).declareVariables(l,a,p)}\n\n ${Ln(et(t))}\n\n ${u.mainStart(Kr)}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${l.getByOffset("global_idx")};\n ${b}\n let x_in = x + bias;\n ${p.setByOffset("global_idx",Fn("x_in"))}\n }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:s,getRunData:u=>({outputs:[{dims:u[0].dims,dataType:u[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:o}],dispatchGroup:{x:Math.ceil(r/Kr/4)}})}},Is=e=>{e.inputs.length<2||z.size(e.inputs[1].dims)===0?Di(e):e.compute(jl(e.inputs))}});var Yl,Zl,Ts,Es,Ps=q(()=>{"use strict";ie();_e();je();be();Yl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Zl=(e,t)=>{let r=e[0].dims,o=e[1].dims,n=r.length,s=z.normalizeAxis(t.axis,n),u=r.slice(0);u.splice(s,1,...o);let l=r[s],a=e[0].dataType===9?4:1,p=Math.ceil(z.size(u)/a),m=[{type:12,data:p},{type:6,data:l},{type:12,data:s},...j(e[0].dims,e[1].dims,u)],f=b=>{let _=M("data",e[0].dataType,e[0].dims.length,a),y=M("inputIndices",e[1].dataType,e[1].dims.length),$=F("output",e[0].dataType,u.length,a),I=v=>{let A=o.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let D=0;D1?`indicesIndices${v}[${D}]`:`indicesIndices${v}`} = ${u.length>1?`outputIndices${v}[uniforms.axis + ${D}]`:`outputIndices${v}`};`;T+=`\n var idx${v} = ${y.getByIndices(`indicesIndices${v}`)};\n if (idx${v} < 0) {\n idx${v} = idx${v} + uniforms.axisDimLimit;\n }\n var dataIndices${v} : ${_.type.indices};\n `;for(let D=0,U=0;D1?`dataIndices${v}[${D}]`:`dataIndices${v}`} = u32(idx${v});`,U+=A):(T+=`${n>1?`dataIndices${v}[${D}]`:`dataIndices${v}`} = ${u.length>1?`outputIndices${v}[${U}]`:`outputIndices${v}`};`,U++);return T},C;if(e[0].dataType===9){let v=(A,T,D="")=>`\n let outputIndices${T} = ${$.offsetToIndices(`outputOffset + ${T}u`)};\n ${I(T)};\n let offset${T} = ${_.indicesToOffset(`dataIndices${T}`)};\n let index${T} = offset${T} / 4u;\n let component${T} = offset${T} % 4u;\n ${A}[${T}] = ${D}(${_.getByOffset(`index${T}`)}[component${T}]);\n `;C=`\n let outputOffset = global_idx * ${a};\n var value = vec4(0);\n ${v("value",0,"u32")}\n ${v("value",1,"u32")}\n ${v("value",2,"u32")}\n ${v("value",3,"u32")}\n ${$.setByOffset("global_idx","value")}\n `}else C=`\n let outputIndices = ${$.offsetToIndices("global_idx")};\n ${I("")};\n let value = ${_.getByIndices("dataIndices")};\n ${$.setByOffset("global_idx","value")};\n `;return`\n ${b.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,y,$)}\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${C}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:f}},Ts=e=>$e({axis:e.axis}),Es=(e,t)=>{let r=e.inputs;Yl(r),e.compute(Zl(e.inputs,t))}});var Ql,Xl,Os,ks,Rs=q(()=>{"use strict";ie();_e();je();be();Ql=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Xl=(e,t)=>{let r=e[0].dims,o=e[0].dataType,n=r.length,s=e[1].dims,u=e[1].dataType,l=z.normalizeAxis(t.axis,n),a=r[l],p=s.slice(0),m=z.size(p),f=M("input",o,n),b=M("indicesInput",u,s.length),_=F("output",o,p.length),y=[{type:12,data:m},{type:6,data:a},{type:12,data:l}];return y.push(...j(r,s,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:C=>`\n ${C.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,b,_)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${_.offsetToIndices("global_idx")};\n\n var idx = ${b.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${f.type.indices}(outputIndices);\n ${f.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${f.getByIndices("inputIndices")};\n\n ${_.setByOffset("global_idx","value")};\n }`}},Os=e=>$e({axis:e.axis}),ks=(e,t)=>{let r=e.inputs;Ql(r),e.compute(Xl(e.inputs,t))}});var Jl,ec,Bs,Ds,Ms=q(()=>{"use strict";ie();_e();be();Jl=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},ec=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[n,s,u]=Lr.getShapeOfGemmResult(r,t.transA,o,t.transB,e.length===3?e[2].dims:void 0),l=[n,s];if(!l)throw new Error("Can\'t use gemm on the given tensors");let a=z.size(l),p=[{type:12,data:a},{type:12,data:n},{type:12,data:s},{type:12,data:u},{type:1,data:t.alpha},{type:1,data:t.beta}],m=["type","type"];e.length===3&&(p.push(...j(e[2].dims)),m.push("rank")),p.push(...j(l));let f=b=>{let _="";t.transA&&t.transB?_="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?_="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?_="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(_="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let y=t.alpha===1?"":"value *= uniforms.alpha;",$=M("a",e[0].dataType,e[0].dims),I=M("b",e[1].dataType,e[1].dims),C=$.type.value,v=null,A=[$,I];e.length===3&&(v=M("c",e[2].dataType,e[2].dims.length),A.push(v));let T=F("output",e[0].dataType,l.length);A.push(T);let D=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`\n ${b.registerUniforms(D).declareVariables(...A)}\n\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${C}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${_}\n }\n\n ${y}\n ${(()=>v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",T)}; value += ${C}(uniforms.beta) * ${v.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:f}},Bs=e=>{let t=e.transA,r=e.transB,o=e.alpha,n=e.beta;return{transA:t,transB:r,alpha:o,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Ds=(e,t)=>{Jl(e.inputs),e.compute(ec(e.inputs,t))}});var tc,rc,nc,zs,Us=q(()=>{"use strict";ie();_e();be();tc=(e,t)=>{let r=e[0].dims,o=r,n=2,s=z.sizeToDimension(r,n),u=z.sizeFromDimension(r,n),l=Me(u),a=u/l,p=[r[0],r[1],a],m=["rank","type","type"],f=[{type:12,data:u},{type:12,data:a}];f.push(...j(p,p));let b=_=>{let y=M("x",e[0].dataType,p.length,l),$=M("scale",e[1].dataType,e[1].dims),I=M("bias",e[2].dataType,e[2].dims),C=F("output",e[0].dataType,p.length,l),v=[y,$,I,C],A=y.type.value,T=l===1?"f32":`vec${l}`,D=64,U=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${T}, ${D}>;\n const workgroupSize = ${D}u;\n ${_.registerUniforms(U).declareVariables(...v)}\n ${_.mainStart(D)}\n let norm = global_idx / workgroupSize;\n let batch = norm / uniforms.x_shape[1];\n let channel = norm % uniforms.x_shape[1];\n let localIndex = local_id.x;\n\n // initialize workgroup memory\n var initial = ${T}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${T}(${y.get("batch","channel","h")});\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the mean of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n meanShared = ${tt("workgroupShared[0]",l)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${T}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${T}(${y.get("batch","channel","h")}) - ${T}(meanShared);\n initial = initial + deviation * deviation;\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the sum of square of deviation of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n squaredNormShared = ${tt("workgroupShared[0]",l)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${$.getByOffset("channel")});\n let channelShift = f32(${I.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${y.get("batch","channel","h")} * ${A}(${T}(channelScale)) + ${A}(${T}(channelShift));\n ${C.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${l}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:s},programUniforms:f}),getShaderSource:b}},rc=(e,t,r,o,n,s,u,l)=>{let a=Me(u),p=64,m=a===1?"vec2f":`mat2x${a}f`,f=a===1?"f32":`vec${a}f`,b=(U,V)=>`${m}(${U}, ${V})`,_=n*u/a,y=Math.ceil(s/p),$=["type"],I=[{type:12,data:y},{type:12,data:s},{type:12,data:Math.floor(u/a)},{type:12,data:Math.floor(s*u/a)}],C=U=>{let V=M("input",t.dataType,t.dims,a);return`\n ${U.declareVariables(V)}\n @group(0) @binding(1) var output : array<${m}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${U.mainStart(p)}\n let currentImageNumber = global_idx / ${p} / uniforms.C;\n let currentChannelNumber = (global_idx / ${p}) % uniforms.C;\n let wgId = global_idx % ${p};\n let wgOffset = wgId * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${Ye("f32",a)};\n var squaredSum = ${Ye("f32",a)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${f}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${b("sum","squaredSum")};\n }`},v=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${a}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:[n,u,p,2],dataType:1}],dispatchGroup:{x:n*u/a},programUniforms:I}),getShaderSource:C},{inputs:[t],outputs:[-1]})[0],A=[{type:12,data:_},{type:12,data:s},{type:12,data:Math.floor(u/a)},{type:12,data:Math.floor(p*u/a)}],T=["type","type","type"],D=U=>{let V=M("scale",r.dataType,r.dims,a),H=M("bias",o.dataType,o.dims,a);return`\n @group(0) @binding(0) var input : array<${m}>;\n @group(0) @binding(1) var scale : array<${V.type.storage}>;\n @group(0) @binding(2) var bias : array<${H.type.storage}>;\n @group(0) @binding(3) var output : array<${m}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${U.mainStart()}\n ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")}\n let currentImageNumber = global_idx / uniforms.C;\n let currentChannelNumber = global_idx % uniforms.C;\n\n let offset = currentImageNumber * uniforms.image_size;\n var sum = ${Ye("f32",a)};\n var squaredSum = ${Ye("f32",a)};\n for (var i: u32 = 0; i < min(${p}, uniforms.H); i++) {\n let value = input[offset + i + currentChannelNumber * ${p}];\n sum += value[0];\n squaredSum += value[1];\n }\n sum = sum / f32(uniforms.H);\n squaredSum = squaredSum / f32(uniforms.H);\n let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${l}));\n let channelScale = invStdDev * ${f}(scale[currentChannelNumber]);\n let channelShift = ${f}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${b("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${a};${l}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:[n,u,2],dataType:1}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:A}),getShaderSource:D},{inputs:[v,r,o],outputs:[-1]})[0]},nc=(e,t,r)=>{let o=t[0].dims,n=o,s=o[0],u=o[o.length-1],l=z.sizeFromDimension(o,1)/u,a=Me(u),p=z.size(n)/a,m=[{type:12,data:l},{type:12,data:Math.floor(u/a)}],f=["type","type"],b=rc(e,t[0],t[1],t[2],s,l,u,r.epsilon),_=y=>{let $=Pe(t[0].dataType),I=a===1?"vec2f":`mat2x${a}f`,C=a===1?$:`vec${a}<${$}>`,v=M("input",t[0].dataType,t[0].dims,a),A=F("output",t[0].dataType,n,a);return`\n @group(0) @binding(0) var input : array<${v.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${I}>;\n @group(0) @binding(2) var output : array<${A.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${y.mainStart()}\n let currentImageNumber = global_idx / (uniforms.C * uniforms.H);\n let currentChannelNumber = global_idx % uniforms.C;\n\n let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber;\n let scale = scaleInput[scaleOffset];\n output[global_idx] = fma(input[global_idx], ${C}(scale[0]), ${C}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${a}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:_},{inputs:[t[0],b]})},zs=(e,t)=>{t.format==="NHWC"?nc(e,e.inputs,t):e.compute(tc(e.inputs,t))}});var oc,ac,Vs,Ns=q(()=>{"use strict";ie();_e();be();oc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},ac=(e,t,r)=>{let o=e[0].dims,n=e[1],s=e[2],u=o,l=z.normalizeAxis(t.axis,o.length),a=z.sizeToDimension(o,l),p=z.sizeFromDimension(o,l),m=z.size(n.dims),f=s?z.size(s.dims):0;if(m!==p||s&&f!==p)throw new Error(`Size of X.shape()[axis:] == ${p}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${m} and bias size of ${f}`);let b=[];for(let T=0;T1,C=r>2,v=T=>{let D=Pe(e[0].dataType),U=[M("x",e[0].dataType,e[0].dims,_),M("scale",n.dataType,n.dims,_)];s&&U.push(M("bias",s.dataType,s.dims,_)),U.push(F("output",e[0].dataType,u,_)),I&&U.push(F("mean_data_output",1,b)),C&&U.push(F("inv_std_output",1,b));let V=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${T.registerUniforms(V).declareVariables(...U)}\n ${T.mainStart()}\n ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${Ye("f32",_)};\n var mean_square_vector = ${Ye("f32",_)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${st(D,_,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${tt("mean_vector",_)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${tt("mean_square_vector",_)} / uniforms.norm_size - mean * mean + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${st(D,_,"x[j + offset]")};\n let f32scale = ${st(D,_,"scale[j]")};\n output[j + offset] = ${U[0].type.value}((f32input - mean) * inv_std_dev * f32scale\n ${s?`+ ${st(D,_,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${C?"inv_std_output[global_idx] = inv_std_dev":""};\n }`},A=[{dims:u,dataType:e[0].dataType}];return I&&A.push({dims:b,dataType:1}),C&&A.push({dims:b,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${r}`,inputDependencies:y},getRunData:()=>({outputs:A,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:$}),getShaderSource:v}},Vs=(e,t)=>{oc(e.inputs),e.compute(ac(e.inputs,t,e.outputCount))}});var ic,sc,Ws,Gs,Hs=q(()=>{"use strict";ie();_e();je();be();ic=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],o=r.dims.length;if(r.dims[o-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let n=Math.floor((t.k+t.blockSize-1)/t.blockSize),s=t.blockSize/8*t.bits,u=e[1];if(!z.areEqual(u.dims,[t.n,n,s]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(z.size(a)!==t.n*n)throw new Error("scales input size error.");if(e.length===4){let m=e[3].dims,f=t.bits>4?t.n*n:t.n*Math.floor((n+1)/2);if(z.size(m)!==f)throw new Error("zeroPoints input size error.")}},sc=(e,t)=>{let r=e[0].dims,o=r.length,n=r.slice(0,o-1).concat(t.n),s=r[o-2],l=t.blockSize/8*t.bits/4,a=Me(s),p=Me(t.n),m=Me(t.k),f=Me(l),b=z.size(n)/p/a,_=[{type:12,data:b},{type:12,data:t.k},{type:12,data:t.n},{type:12,data:t.accuracyLevel},{type:12,data:t.bits},{type:12,data:t.blockSize}],y=r.slice();y.splice(-1,1,t.k/m);let $=z.convertShape(e[1].dims).slice();$.splice(-1,1,l/f),_.push(...j(y)),_.push(...j($)),_.push(...j(e[2].dims)),e.length===4&&_.push(...j(z.convertShape(e[3].dims)));let I=n.slice();I.splice(-1,1,t.n/p),_.push(...j(I));let C=v=>{let A=M("a",e[0].dataType,y.length,m),T=M("b",12,$.length,f),D=M("scales",e[2].dataType,e[2].dims.length),U=[A,T,D],V=e.length===4?M("zero_points",12,e[3].dims.length):void 0;V&&U.push(V);let H=F("output",e[0].dataType,n.length,p),R=[{name:"output_size",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"accuracy_level",type:"u32"},{name:"bits",type:"u32"},{name:"block_size",type:"u32"}],L=Math.floor((t.k+t.blockSize-1)/t.blockSize),pe=Pe(e[0].dataType),Ie=(()=>{switch(m){case 1:return`array<${pe}, 8>`;case 2:return`mat4x2<${pe}>`;case 4:return`mat2x4<${pe}>`;default:throw new Error(`${m}-component is not supported.`)}})(),we=`\n fn dequantize(quantized: ${Ie}, zero_point: ${pe}, scale: ${pe}) -> ${Ie} {\n ${(()=>m===1?`var dequantized = ${Ie}(${Array.from({length:8},(Q,xe)=>`(quantized[${xe}] - zero_point) * scale`).join(", ")});\n return dequantized;`:`var zero_points: ${Ie} = ${Ie}(${Array(8).fill("zero_point").join(",")});\n return (quantized - zero_points) * scale;`)()}\n }`,ne=`\n fn ortUnpack8x4snorm(value: u32) -> ${Ie} {\n var quantized: ${Ie};\n var offset: u32 = 0;\n let count: u32 = 4;\n for (var i: u32 = 0; i < 8u; i++) {\n var result = ${pe}(extractBits(value, offset, count));\n ${(()=>{switch(m){case 1:return"quantized[i] = result;";case 2:return"quantized[i / 2][i % 2] = result;";case 4:return"quantized[i / 4][i % 4] = result;";default:throw new Error(`${m}-component is not supported.`)}})()}\n offset += count;\n }\n return quantized;\n }`,ze=V?`\n zero_point_offset += 4;\n if (zero_point_offset == 32) {\n zero_point_offset = 0;\n zero_point_index++;\n zero_point_word = ${V.getByOffset("zero_point_index")};\n }`:"";return`\n ${we};\n ${ne};\n ${v.registerUniforms(R).declareVariables(...U,H)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var output_values: array<${H.type.value}, ${a}>;\n var output_indices = ${H.offsetToIndices("global_idx")};\n var n = ${H.indicesGet("output_indices",o-1)};\n var m = ${H.indicesGet("output_indices",o-2)};\n var a_indices: ${A.type.indices} = output_indices;\n // Two zero points are packed into one byte because uniforms.bits <= 4.\n // zero_point_offset is either 0 or 4. It is bit offset within one byte.\n // TODO support zero_point_offset for bits > 4\n ${V?`\n var zero_point_index: u32 = n * ${p} * ((${L} + 1) / 2) / 4;\n var zero_point_word: u32 = ${V.getByOffset("zero_point_index")};\n var zero_point_offset: u32 = 0;`:""}\n var scale_index = n * ${L*p};\n var b_indices: ${T.type.indices};\n for (var c: u32 = 0; c < ${p}; c++) {\n ${T.indicesSet("b_indices","0",`n * ${p} + c`)};\n var block_offset: u32 = 0;\n for (var block: u32 = 0; block < ${L}; block++) {\n // The scale and zero points are computed per block.\n let scale = ${D.getByOffset("scale_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${pe}(${V?"extractBits(zero_point_word, zero_point_offset, 4)":8});\n ${T.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block_offset;\n for (var word: u32 = 0; word < ${l}; word += ${f}) {\n ${T.indicesSet("b_indices","2","word")};\n let b_data = ${T.getByIndices("b_indices")};\n for (var i: u32 = 0; i < ${f}; i++) {\n let b_value = ${f===1?"b_data":"b_data[word + i]"};\n let b_quantized_values: ${Ie} = ortUnpack8x4snorm(b_value);\n let b_dequantized_values = dequantize(b_quantized_values, zero_point, scale);\n // Number of B elements per 32-bit word is 32/bits = 32/4 = 8\n var offset: u32 = word_offset;\n for (var j: u32 = 0; j < 8/${m}; j++) {\n ${A.indicesSet("a_indices",o-1,`offset/${m}`)};\n for (var k: u32 = 0; k < ${a}u; k++) {\n ${A.indicesSet("a_indices",o-2,`m * ${a} + k`)};\n let a_data = ${A.getByIndices("a_indices")};\n output_values[k]${p>1?"[c]":""} += ${m===1?"a_data * b_dequantized_values[j]":"dot(a_data, b_dequantized_values[j])"};\n }\n offset += ${m};\n }\n word_offset += 8;\n }\n }\n scale_index++;\n ${ze}\n block_offset += uniforms.block_size;\n }\n // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte.\n ${V?`if (zero_point_offset % 8 > 0) {\n ${ze}\n }`:""}\n }\n for (var k: u32 = 0u; k < ${a}u; k++) {\n ${H.indicesSet("output_indices",o-2,`${a+" * m + k"}`)};\n ${H.setByIndices("output_indices","output_values[k]")}\n }\n }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:_}),getShaderSource:C}},Ws=(e,t)=>{ic(e.inputs,t),e.compute(sc(e.inputs,t))},Gs=e=>$e(e)});var uc,Fs,Ls,dc,oo,qs,Ks=q(()=>{"use strict";ie();_e();je();Gr();Hn();be();Yt();uc=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5],a=e[6],p=e[7];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=!1,f=r.dims[0],b=r.dims[1],_=r.dims.length===3?m?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=b,$=0,I=0,C=Math.floor(_/t.numHeads);if(a&&p){if(a.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(p.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');$=a.dims[2],I=a.dims[2]}else if(a||p)throw new Error(\'Input "past_key" and "past_value" shall be both present or both absent\');let v;if(o){if(r.dims.length!==3)throw new Error(\'Input "query" is expected to have 3 dimensions when key is given\');if(o.dims.length<3||o.dims.length>5)throw new Error(\'Input "key" is expected to have 3, 4, or 5 dimensions\');if(r.dims[0]!==o.dims[0])throw new Error(\'Input "query" and "key" shall have same dim 0 (batch size)\');if(o.dims.length===3){if(o.dims[2]!==r.dims[2])throw new Error(\'Input "query" and "key" shall have same dim 2 (hidden_size)\');v=2,y=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==C)throw new Error(\'Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv\');if(n)throw new Error(\'Expect "value" be none when "key" has packed kv format.\');v=5,y=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==C)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');v=0,y=o.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\'Input "query" is expected to have 3 or 5 dimensions when key is empty\');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error(\'Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv\');v=3}if(s){if(s.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(n&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let A=0;if(u){A=8;let H=u.dims;throw H.length===1?H[0]===f?A=1:H[0]===3*f+2&&(A=3):H.length===2&&H[0]===f&&H[1]===y&&(A=5),A===8?new Error(\'Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)\'):new Error("Mask not supported")}let T=!1,D=_;if(n){if(n.dims.length!==3&&n.dims.length!==4)throw new Error(\'Input "value" is expected to have 3 or 4 dimensions\');if(r.dims[0]!==n.dims[0])throw new Error(\'Input "query" and "value" shall have same dim 0 (batch_size)\');if(n.dims.length===3){if(y!==n.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');D=n.dims[2]}else{if(y!==n.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');D=n.dims[1]*n.dims[3],T=!0}}let U=$+y,V=!1;if(u)throw new Error("Key padding mask is not supported");if(l)throw new Error("extraAddQk is not supported");if(a)throw new Error("pastKey is not supported");if(p)throw new Error("pastValue is not supported");return{batchSize:f,sequenceLength:b,pastSequenceLength:$,kvSequenceLength:y,totalSequenceLength:U,maxSequenceLength:I,inputHiddenSize:0,hiddenSize:_,vHiddenSize:D,headSize:C,vHeadSize:Math.floor(D/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:A,scale:t.scale,broadcastResPosBias:V,passPastInKv:T,qkvFormat:v}},Fs=e=>$e({...e}),Ls=$e({perm:[0,2,1,3]}),dc=(e,t,r,o,n,s,u)=>{let l=[o,n,s],a=z.size(l),p=[{type:12,data:a},{type:12,data:u},{type:12,data:s}],m=f=>{let b=F("qkv_with_bias",t.dataType,l),_=M("qkv",t.dataType,l),y=M("bias",r.dataType,l),$=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${f.registerUniforms($).declareVariables(_,y,b)}\n ${f.mainStart()}\n ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},oo=(e,t,r,o,n,s,u,l)=>{let a=s;if(u){if(o===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return a=dc(e,s,u,t,o,r*n,l),a=a.reshape([t,o,r,n]),e.compute(ot(a,Ls.perm),{inputs:[a],outputs:[-1]})[0]}else return s.dims.length===3&&(a=s.reshape([t,o,r,n])),e.compute(ot(a,Ls.perm),{inputs:[a],outputs:[-1]})[0]},qs=(e,t)=>{let r=uc(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let o=e.inputs[1]&&e.inputs[2]&&e.inputs[1].dims.length===4&&e.inputs[2].dims.length===4,n=oo(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],e.inputs[3],0);if(o)return Qr(e,n,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t);let s=oo(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,e.inputs[1],e.inputs[3],r.hiddenSize),u=oo(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,e.inputs[2],e.inputs[3],2*r.hiddenSize);Qr(e,n,s,u,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],r,t)}});var lc,cc,pc,mc,fc,hc,gc,yc,js,Ys=q(()=>{"use strict";ie();_e();be();lc=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},cc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${re("uniforms.x_shape",n,t)})) {\n break;\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n }\n `},pc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${re("uniforms.x_shape",n,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${re("uniforms.x_shape",n,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},mc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${re("uniforms.x_shape",n,t)})) {\n k = i32(${re("uniforms.x_shape",n,t)}) - 1;\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},fc=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${re("uniforms.pads",n,r)};\n if (k < 0) {\n k += i32(${re("uniforms.x_shape",n,t)}]);\n }\n if (k >= i32(${re("uniforms.x_shape",n,t)})) {\n k -= i32(${re("uniforms.x_shape",n,t)});\n }\n offset += k * i32(${re("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},hc=(e,t,r)=>{switch(r.mode){case 0:return cc(e,t,r.pads.length);case 1:return pc(e,t,r.pads.length);case 2:return mc(e,t,r.pads.length);case 3:return fc(e,t,r.pads.length);default:throw new Error("Invalid mode")}},gc=(e,t)=>{let r=z.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,n=z.size(r),s=[{type:12,data:n},{type:12,data:t.pads}];t.mode===0&&s.push({type:e[0].dataType,data:t.value}),s.push(...j(e[0].dims,r));let u=["rank"],l=a=>{let p=F("output",e[0].dataType,r.length),m=M("x",e[0].dataType,o.length),f=m.type.value,b=hc(p,o.length,t),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&_.push({name:"constant_value",type:f}),`\n ${a.registerUniforms(_).declareVariables(m,p)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n\n var value = ${f}(0);\n ${b}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(z.size(r)/64)},programUniforms:s}),getShaderSource:l}},yc=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),o=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,n=e[0].dims.length,s=new Int32Array(2*n).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let a=0;as[Number(a)]=Number(l));let u=[];return s.forEach(l=>u.push(l)),{mode:t.mode,value:o,pads:u}}else return t},js=(e,t)=>{lc(e.inputs);let r=yc(e.inputs,t);e.compute(gc(e.inputs,r),{inputs:[0]})}});var dn,Zs,Qs,Xs,Js,bc,wc,eu,tu,ru,nu,ou,au,iu,su,uu,du,lu,cu,pu=q(()=>{"use strict";Kt();ie();_e();be();dn=e=>{if(qt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Zs=(e,t,r)=>{let o=t.format==="NHWC",n=e.dims.slice();o&&n.splice(1,0,n.pop());let s=Object.hasOwnProperty.call(t,"dilations"),u=t.kernelShape.slice(),l=t.strides.slice(),a=s?t.dilations.slice():[],p=t.pads.slice();zt.adjustPoolAttributes(r,n,u,l,a,p);let m=zt.computePoolOutputShape(r,n,l,a,u,p,t.autoPad),f=Object.assign({},t);s?Object.assign(f,{kernelShape:u,strides:l,pads:p,dilations:a,cacheKey:t.cacheKey}):Object.assign(f,{kernelShape:u,strides:l,pads:p,cacheKey:t.cacheKey});let b=m.slice();return b.push(b.splice(1,1)[0]),[f,o?b:m]},Qs=(e,t)=>{let r=t.format==="NHWC",o=z.size(e),n=z.size(t.kernelShape),s=[{type:12,data:o},{type:12,data:n}],u=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],a=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],f=!!(p+m);s.push({type:12,data:l},{type:12,data:a},{type:12,data:p},{type:12,data:m}),u.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let b=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],$=t.pads[t.pads.length/2-2],I=t.pads[t.pads.length-2];b=!!($+I),s.push({type:12,data:_},{type:12,data:y},{type:12,data:$},{type:12,data:I}),u.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[s,u,!0,f,b]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=z.computeStrides(t.kernelShape);s.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),u.push({name:"kernelStrides",type:"u32",length:l.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let a=t.pads.reduce((p,m)=>p+m);return[s,u,!!a,!1,!1]}},Xs=(e,t,r,o,n,s,u,l,a,p,m,f)=>{let b=n.format==="NHWC",_=t.type.value,y=F("output",t.type.tensor,o);if(n.kernelShape.length<=2){let $="",I="",C="",v=r-(b?2:1);if(m?$=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${v}] < 0 || xIndices[${v}]\n >= uniforms.x_shape[${v}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:$=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`,n.kernelShape.length===2){let T=r-(b?3:2);f?I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n `,C=`\n }\n `}return`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var value = ${_}(${l});\n var pad = 0;\n ${I}\n ${$}\n ${C}\n ${u}\n\n output[global_idx] = value;\n }`}else{if(b)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let $=n.kernelShape.length,I=n.pads.length,C="";return p?C=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:C=`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n `,`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${_}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${$-1}u; j++) {\n offsets[j] = offset / ${re("uniforms.kernelStrides","j",$)};\n offset -= offsets[j] * ${re("uniforms.kernelStrides","j",$)};\n }\n offsets[${$-1}] = offset;\n\n isPad = false;\n for (var j = ${r-$}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${re("uniforms.strides",`j - ${r-$}u`,$)}\n + offsets[j - ${r-$}u] - ${re("uniforms.pads","j - 2u",I)};\n ${C}\n }\n ${u}\n\n output[global_idx] = value;\n }`}},Js=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bc=e=>`${Js(e)};${e.countIncludePad}`,wc=e=>`${Js(e)};${e.storageOrder};${e.dilations}`,eu=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),tu=(e,t,r,o)=>{let[n,s]=Zs(t,o,r),u=M("x",t.dataType,t.dims.length),l=u.type.value,a="value += x_val;",p="";n.countIncludePad?p+=`value /= ${l}(uniforms.kernelSize);`:p+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,f,b,_,y]=Qs(s,n);m.push(...j(t.dims,s));let $=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${b};${_};${y}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(z.size(s)/64)},programUniforms:m}),getShaderSource:I=>Xs(I,u,t.dims.length,s.length,n,a,p,0,f,b,_,y)}},ru=e=>{let t=e.count_include_pad!==0,r=eu(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let o={countIncludePad:t,...r,cacheKey:""};return{...o,cacheKey:bc(o)}},nu=(e,t)=>{dn(e.inputs),e.compute(tu("AveragePool",e.inputs[0],!1,t))},ou={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},au=e=>{let t=e.format;return{format:t,...ou,cacheKey:t}},iu=(e,t)=>{dn(e.inputs),e.compute(tu("GlobalAveragePool",e.inputs[0],!0,t))},su=(e,t,r,o)=>{let[n,s]=Zs(t,o,r),u=`\n value = max(x_val, value);\n `,l="",a=M("x",t.dataType,t.dims.length),p=["rank"],[m,f,b,_,y]=Qs(s,n);return m.push(...j(t.dims,s)),{name:e,shaderCache:{hint:`${o.cacheKey};${b};${_};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(z.size(s)/64)},programUniforms:m}),getShaderSource:$=>Xs($,a,t.dims.length,s.length,n,u,l,t.dataType===10?-65504:-1e5,f,b,_,y)}},uu=(e,t)=>{dn(e.inputs),e.compute(su("MaxPool",e.inputs[0],!1,t))},du=e=>{let t=e.storage_order,r=e.dilations,o=eu(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(o.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:t,dilations:r,...o,cacheKey:""};return{...n,cacheKey:wc(n)}},lu=e=>{let t=e.format;return{format:t,...ou,cacheKey:t}},cu=(e,t)=>{dn(e.inputs),e.compute(su("GlobalMaxPool",e.inputs[0],!0,t))}});var $c,_c,mu,fu=q(()=>{"use strict";Kt();ie();be();$c=(e,t,r)=>{let o=e===t,n=et&&r>0;if(o||n||s)throw new Error("Range these inputs\' contents are invalid.")},_c=(e,t,r,o)=>{let n=Math.abs(Math.ceil((t-e)/r)),s=[n],u=n,l=[{type:12,data:u},{type:o,data:e},{type:o,data:r},...j(s)],a=p=>{let m=F("output",o,s.length),f=m.type.value,b=[{name:"outputSize",type:"u32"},{name:"start",type:f},{name:"delta",type:f}];return`\n ${p.registerUniforms(b).declareVariables(m)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${f}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:a,getRunData:()=>({outputs:[{dims:s,dataType:o}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l})}},mu=e=>{let t=0,r=0,o=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],o=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],o=e.inputs[2].getFloat32Array()[0]),qt.webgpu.validateInputContent&&$c(t,r,o),e.compute(_c(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var xc,Sc,Cc,Ic,Ac,Tc,Ec,Pc,Oc,kc,Rc,hu,Bc,Dc,Mc,zc,Uc,gu,yu,bu=q(()=>{"use strict";ie();_e();je();be();xc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Sc=(e,t,r)=>{t.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let o=new Array(r).fill(1);return t.forEach((n,s)=>o[n]=e[s]),o},Cc=(e,t,r,o,n,s)=>{let[u,l,a]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(u>0&&e.length>u&&e[u].dims.length>0)e[u].getFloat32Array().forEach(m=>s.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(l>0&&e.length>l&&e[l].dims.length>0){if(e[l].getFloat32Array().forEach(m=>o.push(m)),o.length!==0&&o.length!==p&&r>=18&&o.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");xc(o,t),t.axes.length>0&&Sc(o,t.axes,p).forEach((m,f)=>o[f]=m)}if(a>0&&e.length>a&&(e[a].getBigInt64Array().forEach(m=>n.push(Number(m))),n.length!==p||r>=18&&n.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(o.length!==t.axes.length)throw new Error(\'Resize requires "scales" input size to be of axes rank when axes attributes is specified\');if(n.length!==t.axes.length)throw new Error(\'Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified\')}if(typeof o<"u"&&typeof n<"u"&&o.length>0&&n.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},Ic=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Ac=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Tc=(e,t,r)=>{let o=new Array(r).fill(0).concat(new Array(r).fill(1)),n=e.length===0?o:e.slice();return t.length>0?(t.forEach((s,u)=>{o[s]=n[u],o[u+r]=n[t.length+u]}),o):n},Ec=(e,t,r,o)=>{let n=[];if(r.length>0)if(o.length>0){if(e.forEach(s=>n.push(s)),Math.max(...o)>e.length)throw new Error("axes is out of bound");o.forEach((s,u)=>n[s]=r[u])}else r.forEach(s=>n.push(s));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((s,u)=>Math.round(s*t[u]))}return n},Pc=(e,t,r)=>{let o=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(s=>t[s]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(s=>t[s]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let n=e.slice();return r.axes.length>0?(r.axes.forEach(s=>t[s]=o),r.axes.forEach(s=>n[s]=Math.round(e[s]*t[s]))):(t.fill(o,0,t.length),n.forEach((s,u)=>n[u]=Math.round(s*t[u]))),n},Oc=(e,t,r,o,n)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${re("uniforms.scales","i",o)};\n var roi_low = ${re("uniforms.roi","i",n)};\n var roi_hi = ${re("uniforms.roi",`i + ${t.length}`,n)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${re("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${re("uniforms.output_shape","i",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,kc=(e,t,r,o,n,s,u)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${o.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${re("uniforms.scales","i",n)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${re("uniforms.roi","i",s)};\n var roi_hi = ${re("uniforms.roi",`i + ${r.length}`,s)};\n var input_shape_i = ${re("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${re("uniforms.output_shape","i",o.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${u} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,Rc=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${re("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,hu=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",Bc=(e,t,r,o,n)=>{let[u,l,a,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(col, ${r[a]} - 1))`)};\n ${hu(e,p,u,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${m} = originalIndices[${l}];\n var col:${m} = originalIndices[${a}];\n ${o?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[a]} - 1)) {\n return ${n};\n }`:""};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[a]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${u}])`:"0"};\n var x11: ${m} = getInputValue(batch, channel, row1, col1);\n var x12: ${m} = getInputValue(batch, channel, row1, col2);\n var x21: ${m} = getInputValue(batch, channel, row2, col1);\n var x22: ${m} = getInputValue(batch, channel, row2, col2);\n var dx1: ${m} = abs(row - ${m}(row1));\n var dx2: ${m} = abs(${m}(row2) - row);\n var dy1: ${m} = abs(col - ${m}(col1));\n var dy2: ${m} = abs(${m}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Dc=(e,t,r,o,n,s,u,l,a,p)=>{let m=r.length===2,f=!0,[b,_]=m?[0,1]:f?[2,3]:[1,2],y=e.type.value,$=I=>{let C=I===b?"row":"col";return`\n fn ${C}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet("output_indices",I)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[I]},\n ${o[I]}, ${r[I]}, ${s[I]}, ${s[I]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[I]} - 1))) {\n return ${a};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${C}: ${y} = originalIdx + ${y}(i);\n if (${C} < 0 || ${C} >= ${r[I]}) {\n ${(()=>p?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${a};`:`${C} = max(0, min(${C}, ${r[I]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",I,`u32(${C})`)};\n data[i + 1] = ${I===b?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${$(b)};\n ${$(_)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};\n coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;\n coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${u} * twoMinusAbsS - 5 * ${u}) * twoMinusAbsS + 8 * ${u}) * twoMinusAbsS - 4 * ${u};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Mc=(e,t,r,o,n)=>{let[u,l,a,p,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],f=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${f} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(height, ${r[a]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)};\n ${hu(e,m,u,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${f} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${f} = originalIndices[${l}];\n var height:${f} = originalIndices[${a}];\n var width:${f} = originalIndices[${p}];\n ${o?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[a]} - 1) || width < 0 || (width > ${r[p]} - 1)) {\n return ${n};\n }`:""};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[a]} - 1));\n width = max(0, min(width, ${r[p]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${m}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${u}])`:"0"};\n\n var x111: ${f} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${f} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${f} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${f} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${f} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${f} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${f} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${f} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${f} = abs(depth - ${f}(depth1));\n var dx2: ${f} = abs(${f}(depth2) - depth);\n var dy1: ${f} = abs(height - ${f}(height1));\n var dy2: ${f} = abs(${f}(height2) - height);\n var dz1: ${f} = abs(width - ${f}(width1));\n var dz2: ${f} = abs(${f}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},zc=(e,t,r,o,n,s)=>{let u=e.dims,l=Tc(s,t.axes,u.length),a=Ec(u,o,n,t.axes),p=o.slice();o.length===0&&(p=u.map((v,A)=>v===0?1:a[A]/v),t.keepAspectRatioPolicy!=="stretch"&&(a=Pc(u,p,t)));let m=F("output",e.dataType,a.length),f=M("input",e.dataType,u.length),b=z.size(a),_=u.length===a.length&&u.every((v,A)=>v===a[A]),y=t.coordinateTransformMode==="tf_crop_and_resize",$=t.extrapolationValue,I=f.type.value,C=v=>`\n ${_?"":`\n ${Ic(t.coordinateTransformMode,I)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Rc(f,u)};\n ${Ac(t.nearestMode,r,I)};\n ${kc(f,m,u,a,p.length,l.length,y)};\n `;case"linear":return`\n ${Oc(m,u,a,p.length,l.length)};\n ${(()=>{if(u.length===2||u.length===4)return`${Bc(f,m,u,y,$)}`;if(u.length===3||u.length===5)return`${Mc(f,m,u,y,$)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(u.length===2||u.length===4)return`${Dc(f,m,u,a,p,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${v.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",l.length).declareVariables(f,m)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${_?"output[global_idx] = input[global_idx];":`\n let output_indices = ${m.offsetToIndices("global_idx")};\n var input_indices: ${f.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${f.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${u.length===2||u.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${n.length>0?n:""}|${l.length>0?l:""}|${_}|${u}`,inputDependencies:["rank"]},getShaderSource:C,getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:12,data:b},{type:1,data:p},{type:1,data:l},...j(u,a)]})}},Uc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},gu=(e,t)=>{let r=[],o=[],n=[],s=Uc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Cc(e.inputs,t,s,r,o,n),e.compute(zc(e.inputs[0],t,s,r,o,n),{inputs:[0]})},yu=e=>{let t=e.antialias,r=e.axes,o=e.coordinateTransformMode,n=e.cubicCoeffA,s=e.excludeOutside!==0,u=e.extrapolationValue,l=e.keepAspectRatioPolicy,a=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return $e({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:n,excludeOutside:s,extrapolationValue:u,keepAspectRatioPolicy:l,mode:a,nearestMode:p})}});var Vc,Nc,wu,vu=q(()=>{"use strict";ie();_e();be();Vc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],o=e[2];if(t.dataType!==r.dataType||t.dataType!==o.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let n=t.dims[t.dims.length-1],s=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==s)throw new Error("Skip must have the same sequence length as input");if(o.dims.length!==1)throw new Error("Gamma must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let u=e[3];if(u.dims.length!==1)throw new Error("Beta must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let u=e[4];if(u.dims.length!==1)throw new Error("Bias must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},Nc=(e,t,r,o)=>{let n=e[0].dims,s=z.size(n),u=n,l=s,a=n.slice(-1)[0],p=o?n.slice(0,-1).concat(1):[],m=e.length>3,f=e.length>4,b=o&&r>1,_=o&&r>2,y=r>3,$=Me(a),I=[{type:12,data:l},{type:12,data:$},{type:12,data:a},{type:1,data:t.epsilon}],C=A=>{let T=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],D=[M("x",e[0].dataType,e[0].dims,$),M("skip",e[1].dataType,e[1].dims,$),M("gamma",e[2].dataType,e[2].dims,$)];m&&D.push(M("beta",e[3].dataType,e[3].dims,$)),f&&D.push(M("bias",e[4].dataType,e[4].dims,$)),D.push(F("output",e[0].dataType,u,$)),b&&D.push(F("mean_output",1,p)),_&&D.push(F("inv_std_output",1,p)),y&&D.push(F("input_skip_bias_sum",e[0].dataType,u,$));let U=Pe(e[0].dataType);return`\n\n ${A.registerUniforms(T).declareVariables(...D)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")}\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n let offset = global_idx * hidden_size_vectorized;\n var sum = ${Ye("f32",$)};\n var squareSum = ${Ye("f32",$)};\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${f?"bias[i]":"0.0"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${y?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${st(U,$,"value")};\n sum += f32_value;\n squareSum += f32_value * f32_value;\n }\n let mean = ${tt("sum",$)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${tt("squareSum",$)} / f32(uniforms.hidden_size) - mean * mean + uniforms.epsilon);\n ${b?"mean_output[global_idx] = mean;":""}\n ${_?"inv_std_output[global_idx] = inv_std_dev;":""}\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n output[offset + i] = (output[offset + i] - ${U}(mean)) * ${U}(inv_std_dev) * gamma[i] + ${m?"beta[i]":"0.0"};\n }\n }`},v=[{dims:u,dataType:e[0].dataType}];return r>1&&v.push({dims:p,dataType:1}),r>2&&v.push({dims:p,dataType:1}),r>3&&v.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${$};${b};${_};${y}`,inputDependencies:e.map((A,T)=>"type")},getShaderSource:C,getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(l/a/64)},programUniforms:I})}},wu=(e,t)=>{Vc(e.inputs);let o=[0];e.outputCount>1&&o.push(-3),e.outputCount>2&&o.push(-3),e.outputCount>3&&o.push(3),e.compute(Nc(e.inputs,t,e.outputCount,!1),{outputs:o})}});var Wc,ln,Gc,$u,Hc,Lc,_u,xu,Su=q(()=>{"use strict";ie();_e();je();be();Wc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,o)=>{if(e[o+1].dataType!==6&&e[o+1].dataType!==7)throw new Error(`Input ${o} must be an array of int32 or int64`)})},ln=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(o=>r.push(Number(o)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(o=>r.push(Number(o)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Gc=(e,t)=>{if(e.length>1){let r=ln(e,1),o=ln(e,2),n=ln(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),$e({starts:r,ends:o,axes:n})}else return t},$u=(e,t,r,o,n)=>{let s=e;return e<0&&(s+=r[o[t]]),n[t]<0?Math.max(0,Math.min(s,r[o[t]]-1)):Math.max(0,Math.min(s,r[o[t]]))},Hc=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${re("uniforms.input_shape","i",r.length)};\n let steps_i = ${re("uniforms.steps","i",r.length)};\n let signs_i = ${re("uniforms.signs","i",r.length)};\n let starts_i = ${re("uniforms.starts","i",r.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,Lc=(e,t)=>{let r=e[0].dims,o=z.size(r),n=t.axes.length>0?z.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],s=ln(e,4);s.forEach(C=>C!==0||(()=>{throw new Error("step cannot be 0")})),s.length===0&&(s=Array(n.length).fill(1));let u=t.starts.map((C,v)=>$u(C,v,r,n,s)),l=t.ends.map((C,v)=>$u(C,v,r,n,s));if(n.length!==u.length||n.length!==l.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==r.length)for(let C=0;CMath.sign(C));s.forEach((C,v,A)=>{if(C<0){let T=(l[v]-u[v])/C,D=u[v],U=D+T*s[v];u[v]=U,l[v]=D,A[v]=-C}});let p=r.slice(0);n.forEach((C,v)=>{p[C]=Math.ceil((l[C]-u[C])/s[C])});let m={dims:p,dataType:e[0].dataType},f=F("output",e[0].dataType,p.length),b=M("input",e[0].dataType,e[0].dims.length),_=z.size(p),y=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:u.length},{name:"signs",type:"i32",length:a.length},{name:"steps",type:"u32",length:s.length}],$=[{type:12,data:_},{type:12,data:u},{type:6,data:a},{type:12,data:s},...j(e[0].dims,p)],I=C=>`\n ${C.registerUniforms(y).declareVariables(b,f)}\n ${Hc(b,f,r)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${f.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${f.setByOffset("global_idx",b.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${a.length}_${u.length}_${s.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:$})}},_u=(e,t)=>{Wc(e.inputs,t);let r=Gc(e.inputs,t);e.compute(Lc(e.inputs,r),{inputs:[0]})},xu=e=>{let t=e.starts,r=e.ends,o=e.axes;return $e({starts:t,ends:r,axes:o})}});var Fc,qc,Cu,Iu,Au=q(()=>{"use strict";ie();_e();je();be();Fc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},qc=(e,t)=>{let r=e.dims,o=z.size(r),n=64,s=t.axis;if(s<0&&(s=r.length+s),sC===4?`max(max(${I}.x, ${I}.y), max(${I}.z, ${I}.w))`:C===2?`max(${I}.x, ${I}.y)`:C===3?`max(max(${I}.x, ${I}.y), ${I}.z)`:I,f=M("x",e.dataType,e.dims,a),b=F("result",e.dataType,e.dims,a),_=f.type.value,y=Pe(e.dataType)==="f32"?`var threadMax = ${_}(-3.402823e+38f);`:`var threadMax = ${_}(-65504.0h);`,$=I=>`\n var rowMaxShared : ${_};\n var rowSumShared : ${_};\n var threadShared : array<${_}, ${n}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${_} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${_}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${I.registerUniform("packedCols","i32").declareVariables(f,b)}\n ${I.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${n};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${y}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${_}(${m("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${_}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${_}(${tt("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`;return{name:"Softmax",shaderCache:{hint:`${a}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:l},programUniforms:[{type:12,data:p}]}),getShaderSource:$}},Cu=(e,t)=>{Fc(e.inputs),e.compute(qc(e.inputs[0],t))},Iu=e=>$e({axis:e.axis})});var Kc,jc,Yc,Zc,Qc,Tu,Eu,Pu=q(()=>{"use strict";ie();_e();je();be();Kc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},jc=(e,t)=>{let r=[],o=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),o=r.length),$e({numOutputs:o,axis:t.axis,splitSizes:r})},Yc=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${re("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Zc=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=z.size(r),n=e[0].dataType,s=z.normalizeAxis(t.axis,r.length),u=new Array(t.numOutputs),l=M("input",n,r.length),a=new Array(t.numOutputs),p=[],m=[],f=0,b=[{type:12,data:o}];for(let y=0;y`\n ${y.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",a.length).declareVariables(l,...u)}\n ${Yc(a.length)}\n ${Zc(u)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${l.offsetToIndices("global_idx")};\n var index = ${l.indicesGet("indices",s)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${re("uniforms.size_in_split_axis","output_number - 1u",a.length)};\n ${l.indicesSet("indices",s,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:b})}},Tu=(e,t)=>{Kc(e.inputs);let r=e.inputs.length===1?t:jc(e.inputs,t);e.compute(Qc(e.inputs,r),{inputs:[0]})},Eu=e=>{let t=e.axis,r=e.splitSizes,o=e.numOutputs<0?r.length:e.numOutputs;if(o!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return $e({axis:t,numOutputs:o,splitSizes:r})}});var Ou,Xc,Jc,ep,ku,Ru=q(()=>{"use strict";ie();_e();be();Ou=e=>Array.from(e.getBigInt64Array(),Number),Xc=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ou(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Jc=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=Ou(e[1]),o=Jc(t,r),n=z.size(o),s=e[0].dataType,u=M("input",s,t.length),l=F("output",s,o.length),a=p=>`\n const inputShape = ${u.indices(...t)};\n ${p.registerUniform("output_size","u32").declareVariables(u,l)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${l.offsetToIndices("global_idx")};\n var input_indices: ${u.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i;\n\n ${u.indicesSet("input_indices","i","input_dim_value")}\n }\n ${l.setByOffset("global_idx",u.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...j(e[0].dims,o)]}),getShaderSource:a}},ku=e=>{Xc(e.inputs),e.compute(ep(e.inputs),{inputs:[0]})}});var tp,rp,Bu,Du=q(()=>{"use strict";ie();_e();be();tp=(e,t,r,o,n)=>{let s=F("output_data",n,r.length,4),u=M("a_data",t[1].dataType,t[1].dims.length,4),l=M("b_data",t[2].dataType,t[2].dims.length,4),a=M("c_data",t[0].dataType,t[0].dims.length,4),p,m=(f,b,_)=>`select(${b}, ${f}, ${_})`;if(!o)p=s.setByOffset("global_idx",m(u.getByOffset("global_idx"),l.getByOffset("global_idx"),a.getByOffset("global_idx")));else{let f=(b,_,y="")=>{let $=`a_data[index_a${_}][component_a${_}]`,I=`b_data[index_b${_}][component_b${_}]`,C=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`\n let output_indices${_} = ${s.offsetToIndices(`global_idx * 4u + ${_}u`)};\n let offset_a${_} = ${u.broadcastedIndicesToOffset(`output_indices${_}`,s)};\n let offset_b${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,s)};\n let offset_c${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,s)};\n let index_a${_} = offset_a${_} / 4u;\n let index_b${_} = offset_b${_} / 4u;\n let index_c${_} = offset_c${_} / 4u;\n let component_a${_} = offset_a${_} % 4u;\n let component_b${_} = offset_b${_} % 4u;\n let component_c${_} = offset_c${_} % 4u;\n ${b}[${_}] = ${y}(${m($,I,C)});\n `};n===9?p=`\n var data = vec4(0);\n ${f("data",0,"u32")}\n ${f("data",1,"u32")}\n ${f("data",2,"u32")}\n ${f("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=`\n ${f("output_data[global_idx]",0)}\n ${f("output_data[global_idx]",1)}\n ${f("output_data[global_idx]",2)}\n ${f("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,u,l,s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${p}\n }`},rp=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,n=e[1].dataType,s=!(z.areEqual(t,r)&&z.areEqual(r,o)),u=t,l=z.size(t);if(s){let p=mt.calcShape(mt.calcShape(t,r,!1),o,!1);if(!p)throw new Error("Can\'t perform where op on the given tensors");u=p,l=z.size(u)}let a=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>tp(p,e,u,s,n),getRunData:()=>({outputs:[{dims:u,dataType:n}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:a},...j(o,t,r,u)]})}},Bu=e=>{e.compute(rp(e.inputs))}});var Mu,zu=q(()=>{"use strict";Qa();Hn();ei();ri();Ni();Qi();es();jn();fs();ys();_s();Cs();As();Ps();Rs();Ms();Us();Ns();Zn();Hs();Ks();Ys();pu();fu();Yr();bu();vu();Su();Au();Pu();Ru();Yt();en();Du();Mu=new Map([["Abs",[ni]],["Acos",[oi]],["Acosh",[ai]],["Add",[Wi]],["ArgMax",[Za,Gn]],["ArgMin",[Ya,Gn]],["Asin",[ii]],["Asinh",[si]],["Atan",[ui]],["Atanh",[di]],["Attention",[Xa]],["AveragePool",[nu,ru]],["BatchNormalization",[Ja]],["BiasAdd",[ti]],["BiasSplitGelu",[Vi]],["Cast",[ci,li]],["Ceil",[mi]],["Clip",[pi]],["Concat",[Xi,Ji]],["Conv",[Jn,Xn]],["ConvTranspose",[ms,ps]],["Cos",[fi]],["Cosh",[hi]],["CumSum",[hs,gs]],["Div",[Gi]],["Einsum",[vs,$s]],["Elu",[gi,Xr]],["Equal",[Hi]],["Erf",[yi]],["Exp",[bi]],["Expand",[Ss]],["FastGelu",[Is]],["Floor",[wi]],["FusedConv",[Jn,Xn]],["Gather",[Es,Ts]],["GatherElements",[ks,Os]],["Gelu",[vi]],["Gemm",[Ds,Bs]],["GlobalAveragePool",[iu,au]],["GlobalMaxPool",[cu,lu]],["Greater",[Ki]],["GreaterOrEqual",[Yi]],["HardSigmoid",[Ti,Ai]],["InstanceNormalization",[zs]],["LayerNormalization",[Vs]],["LeakyRelu",[$i,Xr]],["Less",[ji]],["LessOrEqual",[Zi]],["Log",[zi]],["MatMul",[is]],["MatMulNBits",[Ws,Gs]],["MaxPool",[uu,du]],["Mul",[Li]],["MultiHeadAttention",[qs,Fs]],["Neg",[xi]],["Not",[_i]],["Pad",[js]],["Pow",[Fi]],["Range",[mu]],["Reciprocal",[Si]],["ReduceMin",[Ha]],["ReduceMean",[Ua]],["ReduceMax",[Ga]],["ReduceSum",[Fa]],["ReduceProd",[La]],["ReduceL1",[Va]],["ReduceL2",[Na]],["ReduceLogSum",[Ka]],["ReduceLogSumExp",[Wa]],["ReduceSumSquare",[qa]],["Relu",[Ci]],["Resize",[gu,yu]],["Sigmoid",[Ii]],["Sin",[Ei]],["Sinh",[Pi]],["Slice",[_u,xu]],["SkipLayerNormalization",[wu]],["Split",[Tu,Eu]],["Sqrt",[Oi]],["Softmax",[Cu,Iu]],["Sub",[qi]],["Tan",[ki]],["Tanh",[Bi]],["ThresholdedRelu",[Mi,Xr]],["Tile",[ku]],["Transpose",[Ca,Ia]],["Where",[Bu]]])});var cn,Uu=q(()=>{"use strict";Kt();Pt();be();cn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,o,n,s){Mt(t.programInfo.name);let u=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let m of r)a.push({binding:a.length,resource:{buffer:m.buffer}});for(let m of o)a.push({binding:a.length,resource:{buffer:m.buffer}});s&&a.push({binding:a.length,resource:s});let p=u.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:a,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,p),l.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Et(t.programInfo.name)}dispose(){}build(t,r){Mt(t.name);let o=this.backend.device,n=[];o.features.has("shader-f16")&&n.push("enable f16;");let s=xa(r),u=t.getShaderSource(s),l=`${n.join(`\n`)}\n${s.additionalImplementations}\n${u}`,a=o.createShaderModule({code:l,label:t.name});De("verbose",()=>`[WebGPU] ${t.name} shader code: ${l}`);let p=o.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:t.name});return Et(t.name),{programInfo:t,computePipeline:p}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,o=typeof t=="number"?1:t.y||1,n=typeof t=="number"?1:t.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=s&&o<=s&&n<=s)return[r,o,n];let u=r*o*n,l=Math.ceil(Math.sqrt(u));if(l>s){if(l=Math.ceil(Math.cbrt(u)),l>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}});var np,op,ao,pn,Vu=q(()=>{"use strict";Kt();ie();Pt();ba();_a();zu();Uu();np=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let o=0;o{let o=e.name;return e.shaderCache?.hint&&(o+="["+e.shaderCache.hint+"]"),o+=":"+r+`:${np(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},ao=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},pn=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let o=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:o};r.features.has("chromium-experimental-timestamp-query-inside-passes")?o.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&o.push("timestamp-query"),r.features.has("shader-f16")&&o.push("shader-f16"),this.device=await r.requestDevice(n),this.adapterInfo=new ao(await r.requestAdapterInfo()),this.gpuDataManager=$a(this),this.programManager=new cn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ga(t.logLevel,!!t.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Mt(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),o=this.pendingQueries.get(t);for(let n=0;n"u"&&(this.queryTimeBase=_);let $=Number(_-this.queryTimeBase),I=Number(y-this.queryTimeBase);if(!Number.isSafeInteger($)||!Number.isSafeInteger(I))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:f.map(C=>({dims:C.dims,dataType:Tt(C.dataType)})),outputsMetadata:b.map(C=>({dims:C.dims,dataType:Tt(C.dataType)})),kernelId:u,kernelType:a,kernelName:p,programName:m,startTime:$,endTime:I});else{let C="";f.forEach((A,T)=>{C+=`input[${T}]: [${A.dims}] | ${Tt(A.dataType)}, `});let v="";b.forEach((A,T)=>{v+=`output[${T}]: [${A.dims}] | ${Tt(A.dataType)}, `}),console.log(`[profiling] kernel "${u}|${a}|${p}|${m}" ${C}${v}execution time: ${I-$} ns`)}kn("GPU",`${m}::${_}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Et()}run(t,r,o,n,s){Mt(t.name);let u=[];for(let v=0;vA):o;if(m.length!==l.length)throw new Error(`Output size ${m.length} must be equal to ${l.length}.`);let f=[],b=[];for(let v=0;v=l.length)throw new Error(`Invalid output index: ${m[v]}`);if(m[v]===-3)continue;let A=m[v]===-1,T=m[v]===-2,D=A||T?s(l[v].dataType,l[v].dims):n(m[v],l[v].dataType,l[v].dims);if(f.push(D),D.data===0)continue;let U=this.gpuDataManager.get(D.data);if(!U)throw new Error(`no GPU data for output: ${D.data}`);if(A&&this.temporaryData.push(U),T){let V=this.kernelPersistentData.get(this.currentKernelId);V||(V=[],this.kernelPersistentData.set(this.currentKernelId,V)),V.push(U)}b.push(U)}if(u.length!==r.length||b.length!==f.length){if(b.length===0)return Et(t.name),f;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(p){let v=0,A=[];p.forEach(V=>{let H=typeof V.data=="number"?[V.data]:V.data;if(H.length===0)return;let R=V.type===10?2:4,L,pe;V.type===10?(pe=H.length>4?16:H.length>2?8:H.length*R,L=H.length>4?16:R*H.length):(pe=H.length<=2?H.length*R:16,L=16),v=Math.ceil(v/pe)*pe,A.push(v);let Ie=V.type===10?8:4;v+=H.length>4?Math.ceil(H.length/Ie)*L:H.length*R});let T=16;v=Math.ceil(v/T)*T;let D=new ArrayBuffer(v);p.forEach((V,H)=>{let R=A[H],L=typeof V.data=="number"?[V.data]:V.data;if(V.type===6)new Int32Array(D,R,L.length).set(L);else if(V.type===12)new Uint32Array(D,R,L.length).set(L);else if(V.type===10)new Uint16Array(D,R,L.length).set(L);else if(V.type===1)new Float32Array(D,R,L.length).set(L);else throw new Error(`Unsupported uniform type: ${Tt(V.type)}`)});let U=this.gpuDataManager.create(v,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(U.buffer,0,D,0,v),this.gpuDataManager.release(U.id),_={offset:0,size:v,buffer:U.buffer}}let y=this.programManager.normalizeDispatchGroupSize(a),$=y[1]===1&&y[2]===1,I=op(t,r,$),C=this.programManager.getArtifact(I);if(C||(C=this.programManager.build(t,y),this.programManager.setArtifact(I,C),De("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),De("info",()=>`[ProgramManager] run "${t.name}" (key=${I}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let v={kernelId:this.currentKernelId,programName:C.programInfo.name,inputTensorViews:r,outputTensorViews:f};this.pendingKernels.push(v),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(v)}return this.programManager.run(C,u,b,y,_),Et(t.name),f}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,o,n){let s=Mu.get(t);if(!s)throw new Error(`kernel not implemented: ${t}`);let u={kernelType:t,kernelName:n,kernelEntry:s[0],attributes:[s[1],o]};this.kernels.set(r,u)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let o of r)this.gpuDataManager.release(o.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,o){let n=this.kernels.get(t);if(!n)throw new Error(`kernel not created: ${t}`);let s=n.kernelType,u=n.kernelName,l=n.kernelEntry,a=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${u}" is not allowed to be called recursively`);this.currentKernelId=t,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),De("info",()=>`[WebGPU] Start to run kernel "[${s}] ${u}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),l(r,a[1]),0}catch(m){return o.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${u}" failed. ${m}`)),1}finally{p&&o.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel "[${s}] ${u}": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,o,n){let s=this.sessionExternalDataMapping.get(t);s||(s=new Map,this.sessionExternalDataMapping.set(t,s));let u=s.get(r),l=this.gpuDataManager.registerExternalBuffer(o,n,u?.[1]);return s.set(r,[l,o]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(o=>this.gpuDataManager.unregisterExternalBuffer(o[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,o){return async()=>{let n=await Dn(this,t,r);return ya(n.buffer,o)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){De("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){De("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){De("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),o=t.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var Nu={};Mr(Nu,{init:()=>ap});var wr,io,ap,Wu=q(()=>{"use strict";ie();Vu();Pt();_e();wr=class e{constructor(t,r,o,n){this.module=t;this.dataType=r;this.data=o;this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=z.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=z.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=z.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(z.size(t)!==z.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},io=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let n=t.HEAPU32,s=o>>>2;this.opKernelContext=n[s++];let u=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let l=[];for(let a=0;atypeof l=="number"?this.inputs[l]:l)??this.inputs,n=r?.outputs??[],s=(l,a,p)=>new wr(this.module,a,this.output(l,p),p),u=(l,a)=>{let p=fr(l);if(!p)throw new Error(`Unsupported data type: ${l}`);let m=p*z.size(a),f=m>0?this.backend.gpuDataManager.create(m).id:0;return new wr(this.module,l,f,a)};return this.backend.run(t,o,n,s,u)}output(t,r){let o=this.module.stackSave();try{let n=this.module.stackAlloc((1+r.length)*4),s=n>>2;this.module.HEAPU32[s++]=r.length;for(let u=0;u{let n=t.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let s=new pn;await s.initialize(r,o),n("webgpu",[s,u=>s.alloc(u),u=>s.free(u),(u,l,a,p=!1)=>{if(p)De("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${u}, dst=${l}, size=${a}`),s.memcpy(u,l);else{De("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${u}, gpuDataId=${l}, size=${a}`);let m=t.HEAPU8.subarray(u>>>0,(u>>>0)+a);s.upload(l,m)}},async(u,l,a)=>{De("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${u}, dataOffset=${l}, size=${a}`),await s.download(u,()=>t.HEAPU8.subarray(l>>>0,(l>>>0)+a))},(u,l,a)=>s.createKernel(u,l,a,t.UTF8ToString(t._JsepGetNodeName(l))),u=>s.releaseKernel(u),(u,l,a,p)=>{De("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${a}, kernel=${u}, contextDataOffset=${l}`);let m=new io(t,s,l);return s.computeKernel(u,m,p)},()=>s.captureBegin(),()=>s.captureEnd(),()=>s.replay()])}else n("webnn")}});var Ho;Ho=Ro();var bd=No(),An,Tn=!1,zr=!1,Go=!1,wd=e=>{if(e===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},vd=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},$d=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Lo=async e=>{if(Tn)return Promise.resolve();if(zr)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Go)throw new Error("previous call to \'initializeWebAssembly()\' failed.");zr=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,n=wd(r),s=o&&vd(),u=e.wasmPaths,l=typeof u=="string"?u:void 0,a=$d(s,n),p=typeof u=="object"?u[a]:void 0,m=!1,f=[];if(t>0&&f.push(new Promise(b=>{setTimeout(()=>{m=!0,b()},t)})),f.push(new Promise((b,_)=>{let y=n?bd:Ho,$={locateFile:(I,C)=>{if(n&&I.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Wo()],{type:"text/javascript"}));if(I.endsWith(".wasm")){if(p)return p;let v=l??C;return a==="ort-wasm-simd.wasm"?v+"ort-wasm-simd.jsep.wasm":a==="ort-wasm-simd-threaded.wasm"?v+"ort-wasm-simd-threaded.jsep.wasm":v+a}return C+I}};if(n)if($.numThreads=r,typeof Blob>"u")$.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let I=`var ortWasmThreaded=${y.toString()};`;$.mainScriptUrlOrBlob=new Blob([I],{type:"text/javascript"})}y($).then(I=>{zr=!1,Tn=!0,An=I,b()},I=>{zr=!1,Go=!0,_(I)})})),await Promise.race(f),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},We=()=>{if(Tn&&An)return An;throw new Error("WebAssembly is not initialized yet.")};var Ge=(e,t)=>{let r=We(),o=r.lengthBytesUTF8(e)+1,n=r._malloc(o);return r.stringToUTF8(e,n,o),t.push(n),n},mr=(e,t,r,o)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,s])=>{let u=t?t+n:n;if(typeof s=="object")mr(s,u+".",r,o);else if(typeof s=="string"||typeof s=="number")o(u,s.toString());else if(typeof s=="boolean")o(u,s?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof s}`)})},Be=e=>{let t=We(),r=t.stackSave();try{let o=t.stackAlloc(8);t._OrtGetLastError(o,o+4);let n=t.HEAP32[o/4],s=t.HEAPU32[o/4+1],u=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}};var Fo=e=>{let t=We(),r=0,o=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let s=0;return e?.tag!==void 0&&(s=Ge(e.tag,o)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&Be("Can\'t create run options."),e?.extra!==void 0&&mr(e.extra,"",new WeakSet,(u,l)=>{let a=Ge(u,o),p=Ge(l,o);t._OrtAddRunConfigEntry(r,a,p)!==0&&Be(`Can\'t set a run config entry: ${u} - ${l}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(u=>t._free(u)),s}};var _d=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},xd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Sd=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Cd=(e,t,r)=>{for(let o of t){let n=typeof o=="string"?o:o.name;switch(n){case"webnn":if(n="WEBNN",typeof o!="string"){let u=o;if(u?.deviceType){let l=Ge("deviceType",r),a=Ge(u.deviceType,r);We()._OrtAddSessionConfigEntry(e,l,a)!==0&&Be(`Can\'t set a session config entry: \'deviceType\' - ${u.deviceType}.`)}if(u?.numThreads){let l=u.numThreads;(typeof l!="number"||!Number.isInteger(l)||l<0)&&(l=0);let a=Ge("numThreads",r),p=Ge(l.toString(),r);We()._OrtAddSessionConfigEntry(e,a,p)!==0&&Be(`Can\'t set a session config entry: \'numThreads\' - ${u.numThreads}.`)}if(u?.powerPreference){let l=Ge("powerPreference",r),a=Ge(u.powerPreference,r);We()._OrtAddSessionConfigEntry(e,l,a)!==0&&Be(`Can\'t set a session config entry: \'powerPreference\' - ${u.powerPreference}.`)}}break;case"webgpu":if(n="JS",typeof o!="string"){let u=o;if(u?.preferredLayout){if(u.preferredLayout!=="NCHW"&&u.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${u.preferredLayout}`);let l=Ge("preferredLayout",r),a=Ge(u.preferredLayout,r);We()._OrtAddSessionConfigEntry(e,l,a)!==0&&Be(`Can\'t set a session config entry: \'preferredLayout\' - ${u.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let s=Ge(n,r);We()._OrtAppendExecutionProvider(e,s)!==0&&Be(`Can\'t append execution provider: ${n}.`)}},qo=e=>{let t=We(),r=0,o=[],n=e||{};Sd(n);try{let s=_d(n.graphOptimizationLevel??"all"),u=xd(n.executionMode??"sequential"),l=typeof n.logId=="string"?Ge(n.logId,o):0,a=n.logSeverityLevel??2;if(!Number.isInteger(a)||a<0||a>4)throw new Error(`log serverity level is not valid: ${a}`);let p=n.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof n.optimizedModelFilePath=="string"?Ge(n.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,u,!!n.enableProfiling,0,l,a,p,m),r===0&&Be("Can\'t create session options."),n.executionProviders&&Cd(r,n.executionProviders,o),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);let f=Ge("enableGraphCapture",o),b=Ge(n.enableGraphCapture.toString(),o);t._OrtAddSessionConfigEntry(r,f,b)!==0&&Be(`Can\'t set a session config entry: \'enableGraphCapture\' - ${n.enableGraphCapture}.`)}if(n.freeDimensionOverrides)for(let[f,b]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof b!="number"||!Number.isInteger(b)||b<0)throw new Error(`free dimension override value must be a non-negative integer: ${b}`);let _=Ge(f,o);t._OrtAddFreeDimensionOverride(r,_,b)!==0&&Be(`Can\'t set a free dimension override: ${f} - ${b}.`)}return n.extra!==void 0&&mr(n.extra,"",new WeakSet,(f,b)=>{let _=Ge(f,o),y=Ge(b,o);t._OrtAddSessionConfigEntry(r,_,y)!==0&&Be(`Can\'t set a session config entry: ${f} - ${b}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(u=>t._free(u)),s}};ie();var jo=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(e),o=[];for await(let n of r)o.push(n);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),o=r?parseInt(r,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),s;try{s=new ArrayBuffer(o)}catch(l){if(l instanceof RangeError){let a=Math.ceil(o/65536);s=new WebAssembly.Memory({initial:a,maximum:a}).buffer}else throw l}let u=0;for(;;){let{done:l,value:a}=await n.read();if(l)break;let p=a.byteLength;new Uint8Array(s,u,p).set(a),u+=p}return new Uint8Array(s,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var ip=(e,t)=>{We()._OrtInit(e,t)!==0&&Be("Can\'t initialize onnxruntime.")},Hu=async e=>{ip(e.wasm.numThreads,hr(e.logLevel))},Lu=async(e,t)=>{{let r=(Wu(),Ft(Nu)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let o=e.webgpu.adapter;if(o){if(typeof o.limits!="object"||typeof o.features!="object"||typeof o.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let s=e.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(o=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:s}),!o)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\')}if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",We(),e,o)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",We(),e)}}},Ut=new Map,sp=e=>{let t=We(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&Be("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},so=e=>{let t=We(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Fu=async(e,t)=>{let r,o,n=We();Array.isArray(e)?[r,o]=e:e.buffer===n.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=so(e);let s=0,u=0,l=0,a=[],p=[],m=[];try{if([u,a]=qo(t),t?.externalData&&n.mountExternalData){let v=[];for(let A of t.externalData){let T=typeof A=="string"?A:A.path;v.push(jo(typeof A=="string"?A:A.data).then(D=>{n.mountExternalData(T,D)}))}await Promise.all(v)}s=await n._OrtCreateSession(r,o,u),s===0&&Be("Can\'t create a session.");let[f,b]=sp(s),_=!!t?.enableGraphCapture,y=[],$=[],I=[];for(let v=0;vv==="gpu-buffer")&&(l=n._OrtCreateBinding(s),l===0&&Be("Can\'t create IO binding."),C={handle:l,outputPreferredLocations:I,outputPreferredLocationsEncoded:I.map(v=>Pn(v))}),Ut.set(s,[s,p,m,C,_,!1]),[s,y,$]}catch(f){throw p.forEach(b=>n._OrtFree(b)),m.forEach(b=>n._OrtFree(b)),l!==0&&n._OrtReleaseBinding(l),s!==0&&n._OrtReleaseSession(s),f}finally{n._free(r),u!==0&&n._OrtReleaseSessionOptions(u),a.forEach(f=>n._free(f)),n.unmountExternalData?.()}},qu=e=>{let t=We(),r=Ut.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,n,s,u,l]=r;u&&(l&&t._OrtClearBoundOutputs(u.handle),t._OrtReleaseBinding(u.handle)),t.jsepOnReleaseSession?.(e),n.forEach(a=>t._OrtFree(a)),s.forEach(a=>t._OrtFree(a)),t._OrtReleaseSession(o),Ut.delete(e)},Gu=(e,t,r,o,n,s=!1)=>{if(!e){t.push(0);return}let u=We(),l=e[0],a=e[1],p=e[3],m,f;if(l==="string"&&p==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(s&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let y=e[2].gpuBuffer,$=fr(En(l));f=a.reduce((C,v)=>C*v,1)*$;let I=u.jsepRegisterBuffer;if(!I)throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');m=I(o,n,y,f)}else{let y=e[2];if(Array.isArray(y)){f=4*y.length,m=u._malloc(f),r.push(m);let $=m/4;for(let I=0;Iu.HEAP32[y++]=I);let $=u._OrtCreateTensor(En(l),m,f,_,a.length,Pn(p));$===0&&Be(`Can\'t create tensor for input/output. session=${o}, index=${n}.`),t.push($)}finally{u.stackRestore(b)}},Ku=async(e,t,r,o,n,s)=>{let u=We(),l=Ut.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let a=l[0],p=l[1],m=l[2],f=l[3],b=l[4],_=l[5],y=t.length,$=o.length,I=0,C=[],v=[],A=[],T=[],D=u.stackSave(),U=u.stackAlloc(y*4),V=u.stackAlloc(y*4),H=u.stackAlloc($*4),R=u.stackAlloc($*4);try{[I,C]=Fo(s);for(let Q=0;QNe*Fe,1);he=Tt(J);let wt=f?.outputPreferredLocations[o[Q]];if(he==="string"){if(wt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ne=[],Fe=Ae/4;for(let Je=0;Je0){let Ne=u.jsepGetBuffer;if(!Ne)throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');let Fe=Ne(Ae),Je=fr(J);if(Je===void 0||!Ko(he))throw new Error(`Unsupported data type: ${he}`);se=!0,ze.push([he,Xe,{gpuBuffer:Fe,download:u.jsepCreateDownloader(Fe,Le*Je,he),dispose:()=>{u._OrtReleaseTensor(xe)}},"gpu-buffer"])}else{let Ne=Ur(he),Fe=new Ne(Le);new Uint8Array(Fe.buffer,Fe.byteOffset,Fe.byteLength).set(u.HEAPU8.subarray(Ae,Ae+Fe.byteLength)),ze.push([he,Xe,Fe,"cpu"])}}finally{u.stackRestore(me),he==="string"&&Ae&&u._free(Ae),se||u._OrtReleaseTensor(xe)}}return f&&!b&&(u._OrtClearBoundOutputs(f.handle),Ut.set(e,[a,p,m,f,b,!1])),ze}finally{u.stackRestore(D),v.forEach(L=>u._OrtReleaseTensor(L)),A.forEach(L=>u._OrtReleaseTensor(L)),T.forEach(L=>u._free(L)),I!==0&&u._OrtReleaseRunOptions(I),C.forEach(L=>u._free(L))}},ju=e=>{let t=We(),r=Ut.get(e);if(!r)throw new Error("invalid session id");let o=r[0],n=t._OrtEndProfiling(o);n===0&&Be("Can\'t get an profile file name."),t._OrtFree(n)},Yu=e=>{let t=[];for(let r of e){let o=r[2];!Array.isArray(o)&&"buffer"in o&&t.push(o.buffer)}return t};self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Lo(r.wasm).then(()=>{Hu(r).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=r;Lu(n,o).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})});break}case"copy-from":{let{buffer:o}=r,n=so(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=r;Fu(o,n).then(s=>{postMessage({type:t,out:s})},s=>{postMessage({type:t,err:s})});break}case"release":qu(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:s,outputIndices:u,options:l}=r;Ku(o,n,s,u,new Array(u.length).fill(null),l).then(a=>{a.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:a},Yu([...s,...a]))},a=>{postMessage({type:t,err:a})});break}case"end-profiling":ju(r),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}};})();\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n'}),Ht,gt,Ir,Zr,Jr,ss,ha,dr,cr,jp,en,Kp,Yp,Xp,Qp,Zp,Jp,eh,th=V(()=>{xt(),Ug(),Hr(),Ht=()=>!!Oe.wasm.proxy&&typeof document<"u",Ir=!1,Zr=!1,Jr=!1,ha=new Map,dr=(t,e)=>{let r=ha.get(t);r?r.push(e):ha.set(t,[e])},cr=()=>{if(Ir||!Zr||Jr||!gt)throw new Error("worker not ready")},jp=t=>{switch(t.data.type){case"init-wasm":Ir=!1,t.data.err?(Jr=!0,ss[1](t.data.err)):(Zr=!0,ss[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ha.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},en=typeof document<"u"?document?.currentScript?.src:void 0,Kp=async()=>{if(!Zr){if(Ir)throw new Error("multiple calls to 'initWasm()' detected.");if(Jr)throw new Error("previous call to 'initWasm()' failed.");if(Ir=!0,Ht())return Oe.wasm.wasmPaths===void 0&&en&&en.indexOf("blob:")!==0&&(Oe.wasm.wasmPaths=en.substr(0,+en.lastIndexOf("/")+1)),new Promise((t,e)=>{gt?.terminate();let r=URL.createObjectURL(new Blob([Fg()],{type:"text/javascript"}));gt=new Worker(r,{name:"ort-wasm-proxy-worker"}),gt.onerror=a=>e(a),gt.onmessage=jp,URL.revokeObjectURL(r),ss=[t,e];let n={type:"init-wasm",in:Oe};gt.postMessage(n)});try{await bo(Oe.wasm),await Lp(Oe),Zr=!0}catch(t){throw Jr=!0,t}finally{Ir=!1}}},Yp=async t=>{if(Ht())return cr(),new Promise((e,r)=>{dr("init-ep",[e,r]);let n={type:"init-ep",in:{epName:t,env:Oe}};gt.postMessage(n)});await Up(Oe,t)},Xp=async t=>Ht()?(cr(),new Promise((e,r)=>{dr("copy-from",[e,r]);let n={type:"copy-from",in:{buffer:t}};gt.postMessage(n,[t.buffer])})):as(t),Qp=async(t,e)=>{if(Ht()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return cr(),new Promise((r,n)=>{dr("create",[r,n]);let a={type:"create",in:{model:t,options:{...e}}},i=[];t instanceof Uint8Array&&i.push(t.buffer),gt.postMessage(a,i)})}else return Wp(t,e)},Zp=async t=>{if(Ht())return cr(),new Promise((e,r)=>{dr("release",[e,r]);let n={type:"release",in:t};gt.postMessage(n)});Gp(t)},Jp=async(t,e,r,n,a,i)=>{if(Ht()){if(r.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(a.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return cr(),new Promise((s,o)=>{dr("run",[s,o]);let l=r,d={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:n,options:i}};gt.postMessage(d,qp(l))})}else return Vp(t,e,r,n,a,i)},eh=async t=>{if(Ht())return cr(),new Promise((e,r)=>{dr("end-profiling",[e,r]);let n={type:"end-profiling",in:t};gt.postMessage(n)});Hp(t)}}),os,rh,nh,Wg=V(()=>{xt(),th(),me(),Io(),os=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},rh=t=>{switch(t[3]){case"cpu":return new st(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!hi(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:a}=t[2];return st.fromGpuBuffer(r,{dataType:e,dims:t[1],download:n,dispose:a})}default:throw new Error(`invalid data location: ${t[3]}`)}},nh=class{async fetchModelAndCopyToWasmMemory(t){return Xp(await Xn(t))}async loadModel(t,e){$t();let r;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?r=await Xn(t):r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames]=await Qp(r,e),ft()}async dispose(){return Zp(this.sessionId)}async run(t,e,r){$t();let n=[],a=[];Object.entries(t).forEach(u=>{let h=u[0],m=u[1],_=this.inputNames.indexOf(h);if(_===-1)throw new Error(`invalid input '${h}'`);n.push(m),a.push(_)});let i=[],s=[];Object.entries(e).forEach(u=>{let h=u[0],m=u[1],_=this.outputNames.indexOf(h);if(_===-1)throw new Error(`invalid output '${h}'`);i.push(m),s.push(_)});let o=n.map((u,h)=>os(u,()=>`input "${this.inputNames[a[h]]}"`)),l=i.map((u,h)=>u?os(u,()=>`output "${this.outputNames[s[h]]}"`):null),d=await Jp(this.sessionId,a,o,s,l,r),p={};for(let u=0;u{xt(),th(),Wg(),ah=()=>{if((typeof Oe.wasm.initTimeout!="number"||Oe.wasm.initTimeout<0)&&(Oe.wasm.initTimeout=0),typeof Oe.wasm.simd!="boolean"&&(Oe.wasm.simd=!0),typeof Oe.wasm.proxy!="boolean"&&(Oe.wasm.proxy=!1),typeof Oe.wasm.trace!="boolean"&&(Oe.wasm.trace=!1),typeof Oe.wasm.numThreads!="number"||!Number.isInteger(Oe.wasm.numThreads)||Oe.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Oe.wasm.numThreads=1);let t=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Oe.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ih=class{async init(t){ah(),await Kp(),await Yp(t)}async createInferenceSessionHandler(t,e){let r=new nh;return await r.loadModel(t,e),Promise.resolve(r)}}}),sh={};Er(sh,{wasmBackend:()=>oh});var oh,Vg=V(()=>{Gg(),oh=new ih});xt(),xt(),xt();var Hg="1.17.3",qg=io;{let t=(Vg(),tr(sh)).wasmBackend;rr("webgpu",t,5),rr("webnn",t,5),rr("cpu",t,10),rr("wasm",t,10)}Object.defineProperty(Oe.versions,"web",{value:Hg,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var jg=Object.freeze({__proto__:null,get InferenceSession(){return ai},get TRACE(){return Gr},get TRACE_FUNC_BEGIN(){return $t},get TRACE_FUNC_END(){return ft},get Tensor(){return st},get TrainingSession(){return ii},default:qg,get env(){return Oe},get registerBackend(){return rr}});const Kg=(t,e)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];const n=r.getContext("2d");if(n!=null){let a,i;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],i=t.dims[3]):(a=t.dims[3],i=t.dims[2]);const s=e?.format!==void 0?e.format:"RGB",o=e?.norm;let l,d;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?d=[0,0,0,0]:typeof o.bias=="number"?d=[o.bias,o.bias,o.bias,o.bias]:(d=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(d[3]=o.bias[3]));const p=i*a;let u=0,h=p,m=p*2,_=-1;s==="RGBA"?(u=0,h=p,m=p*2,_=p*3):s==="RGB"?(u=0,h=p,m=p*2):s==="RBG"&&(u=0,m=p,h=p*2);for(let y=0;y{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(r!=null){let a,i,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],i=t.dims[1],s=t.dims[3]):(a=t.dims[3],i=t.dims[2],s=t.dims[1]);const o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm;let d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const u=i*a;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let m=0,_=1,y=2,v=3,x=0,w=u,E=u*2,I=-1;o==="RGBA"?(x=0,w=u,E=u*2,I=u*3):o==="RGB"?(x=0,w=u,E=u*2):o==="RBG"&&(x=0,E=u,w=u*2),n=r.createImageData(a,i);for(let k=0;k{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:n}=e,a=e.norm??{mean:255,bias:0};let i,s;typeof a.mean=="number"?i=[a.mean,a.mean,a.mean,a.mean]:i=[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],typeof a.bias=="number"?s=[a.bias,a.bias,a.bias,a.bias]:s=[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];const o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",d=r*n,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3);let u=4,h=0,m=1,_=2,y=3,v=0,x=d,w=d*2,E=-1;o==="RGB"&&(u=3,h=0,m=1,_=2,y=-1),l==="RGBA"?E=d*3:l==="RBG"?(v=0,w=d,x=d*2):l==="BGR"&&(w=0,x=d,v=d*2);for(let k=0;k{const r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,n=typeof ImageData<"u"&&t instanceof ImageData,a=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,i=typeof t=="string";let s,o=e??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){const p=l();p.width=t.width,p.height=t.height;const u=d(p);if(u!=null){let h=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(o=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=h,o.width=m}else o.tensorFormat="RGBA",o.height=h,o.width=m;u.drawImage(t,0,0),s=u.getImageData(0,0,m,h).data}else throw new Error("Can not access image data")}else if(n){let p,u;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,u=e.resizedWidth):(p=t.height,u=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=p,o.width=u,e!==void 0){const h=l();h.width=u,h.height=p;const m=d(h);if(m!=null)m.putImageData(t,0,0),s=m.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else s=t.data}else if(a){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=t.width,p.height=t.height;const u=d(p);if(u!=null){const h=t.height,m=t.width;return u.drawImage(t,0,0,m,h),s=u.getImageData(0,0,m,h).data,o.height=h,o.width=m,ls(s,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((p,u)=>{const h=l(),m=d(h);if(!t||!m)return u();const _=new Image;_.crossOrigin="Anonymous",_.src=t,_.onload=()=>{h.width=_.width,h.height=_.height,m.drawImage(_,0,0,h.width,h.height);const y=m.getImageData(0,0,h.width,h.height);o.height=h.height,o.width=h.width,p(ls(y.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return ls(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},Qg=(t,e)=>{const{width:r,height:n,download:a,dispose:i}=e,s=[1,n,r,4];return new Mt({location:"texture",type:"float32",texture:t,dims:s,download:a,dispose:i})},Zg=(t,e)=>{const{dataType:r,dims:n,download:a,dispose:i}=e;return new Mt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:i})},Jg=(t,e,r)=>new Mt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]}),fa=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),us=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let lh=!1;const e0=()=>{if(!lh){lh=!0;const t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(fa.set("int64",BigInt64Array),us.set(BigInt64Array,"int64")),e&&(fa.set("uint64",BigUint64Array),us.set(BigUint64Array,"uint64"))}},t0=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Mt(t.type,t.data,e);case"cpu-pinned":return new Mt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Mt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Mt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let Mt=class{constructor(e,r,n){e0();let a,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,a=e.type,i=e.dims,e.location){case"cpu-pinned":{const o=fa.get(a);if(!o)throw new TypeError(`unsupported type "${a}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(a!=="float32")throw new TypeError(`unsupported type "${a}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(a!=="float32"&&a!=="float16"&&a!=="int32"&&a!=="int64"&&a!=="uint32"&&a!=="bool")throw new TypeError(`unsupported type "${a}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,l;if(typeof e=="string")if(a=e,l=n,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");o=r}else{const d=fa.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?o=d.from(r,BigInt):o=d.from(r)}else if(r instanceof d)o=r;else throw new TypeError(`A ${a} tensor's data must be type of ${d}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const d=typeof e[0];if(d==="string")a="string",o=e;else if(d==="boolean")a="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{const d=us.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);a=d,o=e}if(l===void 0)l=[o.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");i=l,this.cpuData=o,this.dataLocation="cpu"}const s=t0(i);if(this.cpuData&&s!==this.cpuData.length)throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=a,this.dims=i,this.size=s}static async fromImage(e,r){return Xg(e,r)}static fromTexture(e,r){return Qg(e,r)}static fromGpuBuffer(e,r){return Zg(e,r)}static fromPinnedBuffer(e,r,n){return Jg(e,r,n)}toDataURL(e){return Kg(this,e)}toImageData(e){return Yg(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return r0(this,e)}};const n0=Mt,tn=[];let ds,rn;Lr.IS_NODE_ENV?(rn=He??lm,tn.push("cpu"),ds=["cpu"]):(rn=jg,Lr.IS_WEBGPU_AVAILABLE&&tn.push("webgpu"),tn.push("wasm"),ds=["wasm"]);const a0=rn.InferenceSession;function i0(t){let e=ds;if(t){if(!tn.includes(t))throw new Error(`Unsupported device: "${t}". Should be one of: ${tn.join(", ")}.`);e=[t]}return e}async function uh(t,e){return await a0.create(t,e)}function dh(t){return t instanceof rn.Tensor}const pr=rn?.env;pr?.wasm&&(pr.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.3/dist/",pr.wasm.proxy=!Lr.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(pr.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(pr.wasm.simd=!1));function s0(){return pr?.wasm?.proxy}dt.backends.onnx=pr;const ch=async(t,e,r)=>{const n=await uh(t,e);return async a=>{const i=Object.fromEntries(Object.entries(a).map(([o,l])=>[o,l.ort_tensor])),s=await n.run(i);return new Z(s[r])}};class ph{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=ch(new Uint8Array([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20]),this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=ch(new Uint8Array([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20]),this.session_options,"y")),this._bicubic_interpolate_4d}}const hh=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class Z{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}ort_tensor;constructor(...e){return dh(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new n0(e[0],e[1],e[2]),new Proxy(this,{get:(r,n)=>{if(typeof n=="string"){let a=Number(n);if(Number.isInteger(a))return r._getitem(a)}return r[n]},set:(r,n,a)=>r[n]=a})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...r]=this.dims;if(r.length>0){const n=r.reduce((a,i)=>a*i);for(let a=0;a0){const a=n.reduce((i,s)=>i*s);return this._subarray(e,a,n)}else return new Z(this.type,[this.data[e]],n)}indexOf(e){const r=this.data;for(let n=0;np[1])throw new Error(`Invalid slice: ${p}`);let u=[Math.max(p[0],0),Math.min(p[1],this.dims[d])];n.push(u),r.push(u[1]-u[0])}else throw new Error(`Invalid slice: ${p}`)}let a=n.map(([d,p])=>p-d),i=a.reduce((d,p)=>d*p);const s=this.data;let o=new s.constructor(i);const l=this.stride();for(let d=0;d=0;--u){const m=a[u];p+=(h%m+n[u][0])*l[u],h=Math.floor(h/m)}o[d]=s[p]}return new Z(this.type,o,r)}permute(...e){return l0(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,n=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);const a=this.data;if(r===null){let o=a.reduce((l,d)=>l+d**e,0)**(1/e);return new Z(this.type,[o],[])}r=qt(r,this.dims.length);const i=this.dims.slice();i[r]=1;const s=new a.constructor(a.length/this.dims[r]);for(let o=0;o=0;--d){const h=this.dims[d];if(d!==r){const m=p%h;l+=m*u,u*=i[d]}p=Math.floor(p/h)}s[l]+=a[o]**e}if(e!==1)for(let o=0;o=0;--o){const p=this.dims[o];if(o!==r){const u=l%p;s+=u*d,d*=this.dims[o]}l=Math.floor(l/p)}a[i]/=n.data[s]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return c0(this.dims)}squeeze(e=null){return new Z(this.type,this.data,gh(this.dims,e))}squeeze_(e=null){return this.dims=gh(this.dims,e),this}unsqueeze(e=null){return new Z(this.type,this.data,_h(this.dims,e))}unsqueeze_(e=null){return this.dims=_h(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),a=this.dims.slice(e,r+1),i=this.dims.slice(r+1);return this.dims=[...n,a.reduce((s,o)=>s*o,1),...i],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ns!==r?a*i:a,1);e[r]=this.data.length/n}return new Z(this.type,this.data,e)}neg_(){const e=this.data;for(let r=0;ri*s);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let a=t;for(let i=e.length-1;i>=0;i--)a=a.reduce((s,o)=>{let l=s[s.length-1];return l.lengthr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,n)=>r!==1||!e.includes(n))),t}function _h(t,e){return e=qt(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function qt(t,e,r=null){if(t<-e||t>=e)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<0&&(t=(t%e+e)%e),t}function Ot(t,e=0){e=qt(e,t[0].dims.length);const r=t[0].dims.slice();r[e]=t.reduce((s,o)=>s+o.dims[e],0);const n=r.reduce((s,o)=>s*o,1),a=new t[0].data.constructor(n),i=t[0].type;if(e===0){let s=0;for(let o of t)a.set(o.data,s),s+=o.data.length}else{let s=0;for(let o=0;o=0;--u){const _=l.dims[u];let y=h%_;u===e&&(y+=s),p+=y*m,m*=r[u],h=Math.floor(h/_)}a[p]=l.data[d]}s+=l.dims[e]}}return new Z(i,a,r)}function nn(t,e=0){return Ot(t.map(r=>r.unsqueeze(e)),e)}function u0(t,e=null,r=1,n=!1){if(e===null){const d=t.data.reduce((m,_)=>m+_,0)/t.data.length,p=Math.sqrt(t.data.reduce((m,_)=>m+(_-d)**2,0)/(t.data.length-r)),u=new Z(t.type,[d],[]);return[new Z(t.type,[p],[]),u]}e=qt(e,t.dims.length);const a=cs(t,e,n),i=t.dims.slice();i[e]=1;const s=new t.data.constructor(t.data.length/t.dims[e]);for(let l=0;l=0;--p){const m=t.dims[p];if(p!==e){const _=u%m;d+=_*h,h*=i[p]}u=Math.floor(u/m)}s[d]+=(t.data[l]-a.data[d])**2}for(let l=0;ls+o,0);return new Z(t.type,[i/t.data.length],[])}e=qt(e,t.dims.length);const n=t.dims.slice();n[e]=1;const a=new t.data.constructor(t.data.length/t.dims[e]);for(let i=0;i=0;--o){const p=t.dims[o];if(o!==e){const u=l%p;s+=u*d,d*=n[o]}l=Math.floor(l/p)}a[s]+=t.data[i]}if(t.dims[e]!==1)for(let i=0;i0||o>0;)switch(l.push(s-1),d.push(o-1),i[s][o].item()){case 0:--s,--o;break;case 1:--s;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${o}]. Please file a bug report.`)}return l.reverse(),d.reverse(),[l,d]}function c0(t){const e=new Array(t.length);for(let r=t.length-1,n=1;r>=0;--r)e[r]=n,n*=t[r];return e}function ps(t,e,r,n){const a=t.reduce((i,s)=>i*s,1);return new Z(r,new n(a).fill(e),t)}function p0(t,e){let r,n;if(typeof e=="number")r="float32",n=Float32Array;else if(typeof e=="bigint")r="int64",n=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof e}`);return ps(t,e,r,n)}function h0(t,e){return p0(t.dims,e)}function ma(t){return ps(t,1n,"int64",BigInt64Array)}function f0(t){return ma(t.dims)}function m0(t){return ps(t,0n,"int64",BigInt64Array)}function g0(t){return m0(t.dims)}var ve=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"});Object.freeze({set:ve.Set,for:ve.For,in:ve.In,is:ve.Is,if:ve.If,else:ve.Else,endif:ve.EndIf,elif:ve.ElseIf,endfor:ve.EndFor,and:ve.And,or:ve.Or,not:ve.Not,"not in":ve.NotIn,true:ve.BooleanLiteral,false:ve.BooleanLiteral}),ve.OpenStatement,ve.CloseStatement,ve.OpenExpression,ve.CloseExpression,ve.OpenParen,ve.CloseParen,ve.OpenCurlyBracket,ve.CloseCurlyBracket,ve.OpenSquareBracket,ve.CloseSquareBracket,ve.Comma,ve.Dot,ve.Colon,ve.Pipe,ve.ComparisonBinaryOperator,ve.ComparisonBinaryOperator,ve.ComparisonBinaryOperator,ve.ComparisonBinaryOperator,ve.ComparisonBinaryOperator,ve.ComparisonBinaryOperator,ve.AdditiveBinaryOperator,ve.AdditiveBinaryOperator,ve.MultiplicativeBinaryOperator,ve.MultiplicativeBinaryOperator,ve.MultiplicativeBinaryOperator,ve.Equals;const _0=(()=>{const t=[...Array.from({length:94},(a,i)=>i+33),...Array.from({length:12},(a,i)=>i+161),...Array.from({length:82},(a,i)=>i+174)],e=t.slice();let r=0;for(let a=0;a<256;++a)t.includes(a)||(t.push(a),e.push(256+r),r+=1);const n=e.map(a=>String.fromCharCode(a));return Object.fromEntries(t.map((a,i)=>[a,n[i]]))})();mm(_0);const y0=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]];new Map(y0);async function w0(t,e){return await xr(t,"config.json",!0,e)}class b0{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main"}={}){let o=n??await w0(e,{progress_callback:r,config:n,cache_dir:a,local_files_only:i,revision:s});return new this(o)}}class jt{static async from_pretrained(...e){return b0.from_pretrained(...e)}}const ga=Object.freeze({cpu:"cpu",gpu:"gpu",wasm:"wasm",webgpu:"webgpu"}),v0=function(){let t;return async function(){if(t===void 0)if(Lr.IS_NODE_ENV)t=!0;else if(!Lr.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}}(),Tt=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8"}),$0=Object.freeze({[ga.cpu]:Tt.q8,[ga.gpu]:Tt.fp32,[ga.wasm]:Tt.q8,[ga.webgpu]:Tt.fp32}),yh=Object.freeze({[Tt.fp32]:"",[Tt.fp16]:"_fp16",[Tt.int8]:"_int8",[Tt.uint8]:"_uint8",[Tt.q8]:"_quantized"});class Ut extends Dt{_call(e,r){throw Error("`_call` should be implemented in a subclass")}}class hs extends Dt{_call(e,r){throw Error("`_call` should be implemented in a subclass")}}class wh extends Dt{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,r){let n=r;for(const a of this.processors)n=a(e,n);return n}[Symbol.iterator](){return this.processors.values()}}class x0 extends Ut{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let n=0;n1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);const n=e.length,a=r.slice([0,n],null),i=r.slice([n,r.dims[0]],null);for(let s=0;s1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(n)||n<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${n}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=n}}class R0 extends hs{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:n=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,n),this.filter_value=r}}class P0{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,$r(e,Object.getOwnPropertyNames(this)))}}class bh extends Dt{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}}class fs extends Dt{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof fs&&(e=e.criteria),this.criteria.push(...e)}_call(e,r){const n=new Array(e.length).fill(!1);for(const a of this.criteria){const i=a(e,r);for(let s=0;sr.length>=this.max_length)}}class D0 extends bh{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(n=>this.eos_token_id.includes(n.at(-1)))}}class _a extends Dt{constructor(e){super(),this.generation_config=e}_call(e,r=-1){return this.sample(e,r)}sample(e,r){throw Error("sample should be implemented in subclasses.")}getLogits(e,r){let n=e.dims.at(-1),a=e.data;if(r===-1)a=a.slice(-n);else{let i=r*n;a=a.slice(i,i+n)}return a}randomSelect(e){let r=e.reduce((a,i)=>a+i,0),n=Math.random()*r;for(let a=0;a1)return new U0(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new N0(e)}}class N0 extends _a{sample(e,r=-1){let n=this.getLogits(e,r);return[[er(n)[1],0]]}}class L0 extends _a{sample(e,r=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const a=this.getLogits(e,r),i=Us(a,n),s=Vn(i.map(o=>o[1]));return Array.from({length:this.generation_config.num_beams},()=>{const o=this.randomSelect(s);return[i[o][0],Math.log(s[o])]})}}class U0 extends _a{sample(e,r=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const a=this.getLogits(e,r),i=Us(a,n),s=Vn(i.map(o=>o[1]));return Array.from({length:this.generation_config.num_beams},(o,l)=>[i[l][0],Math.log(s[l])])}}const pe={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},ya=new Map,vh=new Map,an=new Map;async function F0(t,e,r){let n=r.device;n&&typeof n!="string"&&(n.hasOwnProperty(e)?n=n[e]:(console.warn(`Device not specified for ${e}. Using the default device.`),n=null));const a=i0(n);let i=r.dtype;if(typeof i!="string"&&(i&&i.hasOwnProperty(e)?i=i[e]:(i=$0[a[0]],console.warn(`Dtype not specified for ${e}. Using the default dtype: ${i}.`))),yh.hasOwnProperty(i)){if(i===Tt.fp16&&!await v0())throw new Error("The device does not support fp16.")}else throw new Error(`Invalid dtype: ${i}. Should be one of: ${Object.keys(Tt).join(", ")}`);const s=yh[i],o=`${r.subfolder??""}/${e}${s}.onnx`,l=await Ya(t,o,!0,r),d={...r.session_options};if(d.executionProviders??=a,d.externalData!==void 0)for(let p=0;pF0(t,e[s],r))),i={};for(let s=0;s0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const a=Object.keys(e).length,i=t.inputNames.length;if(a>i){let s=Object.keys(e).filter(o=>!t.inputNames.includes(o));console.warn(`WARNING: Too many inputs were provided (${a} > ${i}). The following inputs will be ignored: "${s.join(", ")}".`)}return r}async function Kt(t,e){const r=W0(t,e);try{const n=Object.fromEntries(Object.entries(r).map(([i,s])=>[i,s.ort_tensor]));let a=await t.run(n);a=$h(a);for(const[i,s]of Object.entries(r))i.startsWith("past_key_values")&&s.dispose();return a}catch(n){throw console.error(`An error occurred during model execution: "${n}".`),console.error("Inputs given to model:",r),n}}function $h(t){for(let e in t)dh(t[e])?t[e]=new Z(t[e]):typeof t[e]=="object"&&$h(t[e]);return t}function G0(t){if(t instanceof Z)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[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 Z("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new Z("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function xh(t){return new Z("bool",[t],[1])}async function Sh(t,e){let{encoder_outputs:r,past_key_values:n}=e;if(!r){const l=$r(e,t.sessions.model.inputNames);r=(await sn(t,l)).last_hidden_state}const{input_ids:a,decoder_input_ids:i,...s}=e;return s.input_ids=i,s.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(s.encoder_attention_mask=e.attention_mask),await ms(t,s,!0)}async function sn(t,e){const r=t.sessions.model,n=Object.create(null);for(const a of r.inputNames)n[a]=e[a];return r.inputNames.includes("token_type_ids")&&!n.token_type_ids&&(n.token_type_ids=new Z("int64",new BigInt64Array(n.input_ids.data.length),n.input_ids.dims)),await Kt(r,n)}async function ms(t,e,r=!1){const n=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:a,...i}=e;n.inputNames.includes("use_cache_branch")&&(i.use_cache_branch=xh(!!a)),t.addPastKeyValues(i,a);const s=$r(i,n.inputNames);return await Kt(n,s)}function V0(t,e,r,n){if(t.sessions.model.inputNames.includes("position_ids")&&r.attention_mask&&!r.position_ids){const[i,s]=r.attention_mask.dims,o=new BigInt64Array(r.attention_mask.data.length);for(let l=0;l[s.at(-1)])),a.decoder_input_ids=G0(e),a}class K extends Dt{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,r){super(),this.config=e,this.sessions=r;const n=an.get(this.constructor),a=ya.get(n);this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,a===pe.DecoderOnly?(this.can_generate=!0,this._forward=ms,this._prepare_inputs_for_generation=V0):a===pe.Seq2Seq||a===pe.Vision2Seq||a===pe.Musicgen?(this.can_generate=!0,this._forward=Sh,this._prepare_inputs_for_generation=H0):a===pe.EncoderDecoder?this._forward=Sh:a===pe.ImageTextToText?(this.can_generate=!0,console.warn("TODO: Implement visionDecoderForward")):this._forward=sn}async dispose(){const e=[];for(let r of Object.keys(this)){let n=this[r];n?.handler?.dispose!==void 0&&e.push(n.handler.dispose())}return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:d=null,dtype:p=null,session_options:u={}}={}){let h={progress_callback:r,config:n,cache_dir:a,local_files_only:i,revision:s,model_file_name:o,subfolder:l,device:d,dtype:p,session_options:u};const m=an.get(this),_=ya.get(m);let y;return _===pe.DecoderOnly?y=await Promise.all([jt.from_pretrained(e,h),hr(e,{model:h.model_file_name??"model"},h),xr(e,"generation_config.json",!1,h)]):_===pe.Seq2Seq||_===pe.Vision2Seq?y=await Promise.all([jt.from_pretrained(e,h),hr(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h),xr(e,"generation_config.json",!1,h)]):_===pe.MaskGeneration?y=await Promise.all([jt.from_pretrained(e,h),hr(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]):_===pe.EncoderDecoder?y=await Promise.all([jt.from_pretrained(e,h),hr(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h)]):_===pe.ImageTextToText?y=await Promise.all([jt.from_pretrained(e,h),hr(e,{embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"},h),xr(e,"generation_config.json",!1,h)]):_===pe.Musicgen?y=await Promise.all([jt.from_pretrained(e,h),hr(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h),xr(e,"generation_config.json",!1,h)]):(_!==pe.EncoderOnly&&console.warn(`Model type for '${m??n?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),y=await Promise.all([jt.from_pretrained(e,h),hr(e,{model:h.model_file_name??"model"},h)])),new this(...y)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_warper(e){const r=new wh;return e.temperature!==null&&e.temperature!==1&&r.push(new O0(e.temperature)),e.top_k!==null&&e.top_k!==0&&r.push(new R0(e.top_k)),e.top_p!==null&&e.top_p<1&&r.push(new z0(e.top_p)),r}_get_logits_processor(e,r,n=null){const a=new wh;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&a.push(new I0(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&a.push(new C0(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&a.push(new A0(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&a.push(new k0(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&a.push(new T0(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&a.push(new x0(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&a.push(new S0(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let i=r>1||e.forced_bos_token_id===null?r:r+1;e.forced_decoder_ids!==null&&(i+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),a.push(new E0(e.begin_suppress_tokens,i))}return e.guidance_scale!==null&&e.guidance_scale>1&&a.push(new M0(e.guidance_scale)),n!==null&&a.extend(n),a}_prepare_generation_config(e,r){const n=new P0(this.config);return"generation_config"in this&&Object.assign(n,this.generation_config),e&&Object.assign(n,e),r&&Object.assign(n,$r(r,Object.getOwnPropertyNames(n))),n}_get_stopping_criteria(e,r=null){const n=new fs;return e.max_length!==null&&n.push(new B0(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new D0(e.eos_token_id)),r&&n.extend(r),n}_validate_model_class(){if(!this.can_generate){const e=[vs,Ef,Sf,xf],r=an.get(this.constructor),n=new Set,a=this.config.model_type;for(const s of e){const o=s.get(a);o&&n.add(o[0])}let i=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(", ")}`),Error(i)}}prepare_inputs_for_generation(...e){return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:n,is_encoder_decoder:a}){return n.past_key_values=this.getPastKeyValues(r,n.past_key_values),n.input_ids=new Z("int64",e,[e.length,1]),a||(n.attention_mask=Ot([n.attention_mask,ma([n.attention_mask.dims[0],1])],1)),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:n}){const a=$r(n,this.forward_params),i=this.main_input_name;if(i in a){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else a[i]=e;return{inputs_tensor:a[i],model_inputs:a,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:n,generation_config:a}){const i=$r(r,this.sessions.model.inputNames);let{last_hidden_state:s}=await sn(this,i);return a.guidance_scale!==null&&a.guidance_scale>1&&(s=Ot([s,h0(s,0)],0),"attention_mask"in r&&(r.attention_mask=Ot([r.attention_mask,g0(r.attention_mask)],0))),r.encoder_outputs=s,r}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:r,model_kwargs:n,decoder_start_token_id:a,bos_token_id:i,generation_config:s}){a=a??i;let o;if(this.config.model_type==="musicgen")o=new Array(e*this.config.decoder.num_codebooks).fill(a);else if(Array.isArray(a)){if(a.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${a.length}`);o=a}else o=new Array(e).fill(a);const d=new Z("int64",o,[o.length,1]);return n.decoder_attention_mask=f0(d),{input_ids:d,model_inputs:n}}async generate({inputs:e=null,generation_config:r=null,logits_processor:n=null,stopping_criteria:a=null,streamer:i=null,...s}){this._validate_model_class(),r=this._prepare_generation_config(r,s);let{inputs_tensor:o,model_inputs:l,model_input_name:d}=this._prepare_model_inputs({inputs:e,model_kwargs:s});const p=this.config.is_encoder_decoder;p&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:l,model_input_name:d,generation_config:r})));let u;p?{input_ids:u,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[d].dims.at(0),model_input_name:d,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):u=l[d];let h=u.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=h+r.max_new_tokens);const m=this._get_logits_processor(r,h,n),_=this._get_stopping_criteria(r,a),y=l[d].dims.at(0),v=_a.getSampler(r),x=new Array(y).fill(0),w=u.tolist();for(i&&i.put(w);;){l=this.prepare_inputs_for_generation(w,l,r);const E=await this.forward(l),I=E.logits.slice(null,-1,null),k=m(w,I),A=[];for(let L=0;LL))break;l=this._update_model_kwargs_for_generation({generated_input_ids:A,outputs:E,model_inputs:l,is_encoder_decoder:p})}return i&&i.end(),new Z("int64",w.flat(),[w.length,w[0].length])}addAttentionsToBeam(e,r){if(this.config.is_encoder_decoder){if(!r.cross_attentions||r.cross_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.cross_attentions||(e.cross_attentions=[]),e.cross_attentions.push(r.cross_attentions)}if(!r.decoder_attentions||r.decoder_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.decoder_attentions||(e.decoder_attentions=[]),e.decoder_attentions.push(r.decoder_attentions)}groupBeams(e){const r=Object.create(null);for(const n of e)r[n.id]===void 0?r[n.id]=[n]:r[n.id].push(n);return Object.values(r)}getPastKeyValues(e,r){const n=Object.create(null);for(const a in e)if(a.startsWith("present")){let i=a.replace("present","past_key_values");r&&a.includes("encoder")?n[i]=r[i]:n[i]=e[a]}return n}getAttentions(e){const r=Object.create(null);for(const n of["cross_attentions","decoder_attentions"]){const a=[];for(const i in e)if(i.startsWith(n)){const s=i.split(".").pop();a[s]=e[i]}r[n]=a}return r}addPastKeyValues(e,r){if(r)Object.assign(e,r);else{const a="float32",i=[];if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??!0)){let s=[1,this.num_encoder_heads,0,this.encoder_dim_kv],o=[1,this.num_decoder_heads,0,this.decoder_dim_kv];for(let l=0;l{let p=Array.from({length:this.config.decoder_layers},(v,x)=>Ot(d.map(w=>w[x]),2)),u=nn(r.map(([v,x])=>n?p[v].slice(null,x,null,[0,n]):p[v].slice(null,x)));u=u.transpose(1,0,2,3);let[h,m]=u0(u,-2,0,!0),_=u.clone();for(let v=0;v<_.dims[0];++v){let x=_[v];for(let w=0;wu[x+1]-u[x]),_=gm([1],m).map(v=>!!v),y=[];for(let v=0;v<_.length;++v)_[v]&&y.push(h[v]*a);l[d].data.set(y,1)}return l}}class Dy extends K{main_input_name="pixel_values";constructor(e,r,n){super(e,r),this.generation_config=n;const a=this.config.encoder,i=this.config.decoder,s=a.model_type;(vf.get(s)??$f.get(s))||console.warn(`Model type for encoder '${s}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`);const l=vs.get(i.model_type);if(!l)throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`);const d=l[1],p=new d(i,{},n);this.add_encoder_pkv="num_decoder_layers"in p,this.add_encoder_pkv?(this.num_decoder_layers=p.num_decoder_layers,this.num_decoder_heads=p.num_decoder_heads,this.decoder_dim_kv=p.decoder_dim_kv,this.num_encoder_layers=p.num_encoder_layers,this.num_encoder_heads=p.num_encoder_heads,this.encoder_dim_kv=p.encoder_dim_kv):(this.num_layers=p.num_layers,this.num_heads=p.num_heads,this.dim_kv=p.dim_kv)}}class Ny extends K{forward_params=["input_ids","past_key_values","pixel_values","attention_mask"];constructor(e,r,n){super(e,r),this.generation_config=n;const a=this.config.text_config;this.config.pad_token_id=a.eos_token_id,this.num_heads=a.num_attention_heads,this.num_layers=a.num_hidden_layers,this.dim_kv=a.hidden_size/this.num_heads}}class Ly extends Ny{async encode_image({pixel_values:e}){return(await Kt(this.sessions.vision_encoder,{pixel_values:e})).image_features}async encode_text({input_ids:e}){return(await Kt(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:n,attention_mask:a}){const i=this.config.image_token_index,o=n.tolist().map(h=>h.findIndex(m=>m==i)),l=o.every(h=>h===-1),d=o.every(h=>h!==-1);if(!l&&!d)throw new Error("Every input should contain either 0 or 1 image token.");if(l)return{inputs_embeds:e,attention_mask:a,position_ids:null};let p=[],u=[];for(let h=0;ha*i,1);e.input_labels=new Z("int64",new BigInt64Array(n).fill(1n),r)}return await Kt(this.sessions.prompt_encoder_mask_decoder,{input_points:e.input_points,input_labels:e.input_labels,image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings})}async _call(e){return new cb(await super._call(e))}}class cb extends _t{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}}class cf extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class pb extends cf{}class hb extends cf{}class pf extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class fb extends pf{}class mb extends pf{}class fr extends K{}class gb extends fr{}class _b extends fr{async _call(e){return new kr(await super._call(e))}}class yb extends fr{async _call(e){return new ke(await super._call(e))}}class wb extends fr{async _call(e){return new rt(await super._call(e))}}class ys extends K{}class bb extends ys{}class vb extends ys{async _call(e){return new kr(await super._call(e))}}class $b extends ys{async _call(e){return new ke(await super._call(e))}}class Ea extends K{}class xb extends Ea{}class Sb extends Ea{async _call(e){return new kr(await super._call(e))}}class Eb extends Ea{async _call(e){return new ke(await super._call(e))}}class Cb extends Ea{async _call(e){return new rt(await super._call(e))}}class ws extends K{}class Ib extends ws{}class kb extends ws{async _call(e){return new kr(await super._call(e))}}class Tb extends ws{async _call(e){return new ke(await super._call(e))}}class Ab extends fr{}class Mb extends fr{async _call(e){return new kr(await super._call(e))}}class Ob extends fr{async _call(e){return new ke(await super._call(e))}}class wn extends K{}class zb extends wn{}class Rb extends wn{async _call(e){return new kr(await super._call(e))}}class Pb extends wn{async _call(e){return new ke(await super._call(e))}}class Bb extends wn{async _call(e){return new Tv(await super._call(e))}}class Db extends wn{async _call(e){return new rt(await super._call(e))}}class hf extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.hidden_size/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.hidden_size/this.num_encoder_heads}}class Nb extends hf{}class Lb extends hf{async generate_speech(e,r,{threshold:n=.5,minlenratio:a=0,maxlenratio:i=20,vocoder:s=null}={}){const o={input_ids:e},{encoder_outputs:l,encoder_attention_mask:d}=await sn(this,o),p=l.dims[1]/this.config.reduction_factor,u=Math.floor(p*i),h=Math.floor(p*a),m=this.config.num_mel_bins;let _=[],y=null,v=null,x=0;for(;;){++x;const I=xh(!!v);let k;v?k=v.output_sequence_out:k=new Z("float32",new Float32Array(m),[1,1,m]);let A={use_cache_branch:I,output_sequence:k,encoder_attention_mask:d,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(A,y),v=await Kt(this.sessions.decoder_model_merged,A),y=this.getPastKeyValues(v,y);const{prob:D,spectrum:L}=v;if(_.push(L),x>=h&&(Array.from(D.data).filter(Y=>Y>=n).length>0||x>=u))break}const w=Ot(_),{waveform:E}=await Kt(s.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:E}}}class Ub extends K{main_input_name="spectrogram"}class Fb extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_encoder_layers=this.num_decoder_layers=this.config.decoder_layers,this.num_encoder_heads=this.num_decoder_heads=this.config.decoder_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads}}class Wb extends Fb{}class ff extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Gb extends ff{}class Vb extends ff{}class mf extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Hb extends mf{}class qb extends mf{}class gf extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class jb extends gf{}class Kb extends gf{}class bs extends K{}class Yb extends bs{}class Xb extends bs{static async from_pretrained(e,r={}){return r.model_file_name??="text_model",super.from_pretrained(e,r)}}class Qb extends bs{static async from_pretrained(e,r={}){return r.model_file_name??="audio_model",super.from_pretrained(e,r)}}class Zb extends K{}class _f extends Zb{async _call(e){return new Mv(await super._call(e))}}class yf extends K{}class Jb extends yf{}class ev extends yf{}class tv extends K{constructor(e,r,n){super(e,r),this.generation_config=n,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.num_heads}}class rv extends tv{}class wf extends K{}class nv extends wf{}class av extends wf{async _call(e){return new ke(await super._call(e))}}class bf extends K{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(e,r,n){super(e,r),this.generation_config=n;const a=e.decoder;this.num_encoder_layers=this.num_decoder_layers=a.num_hidden_layers,this.num_encoder_heads=this.num_decoder_heads=a.num_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=a.hidden_size/this.num_decoder_heads}_apply_and_filter_by_delay_pattern_mask(e){const[r,n]=e.dims,a=this.config.decoder.num_codebooks,i=n-a;let s=0;for(let d=0;d0&&h<=i&&(e.data[s++]=e.data[d])}const o=Math.floor(r/a),l=s/(o*a);return new Z(e.type,e.data.slice(0,s),[o,a,l])}prepare_inputs_for_generation(e,r,n){let a=structuredClone(e);for(let s=0;s=o&&(a[s][o]=BigInt(this.config.decoder.pad_token_id));return n.guidance_scale!==null&&n.guidance_scale>1&&(a=a.concat(a)),super.prepare_inputs_for_generation(a,r,n)}async generate(e){const r=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:a}=await Kt(this.sessions.encodec_decode,{audio_codes:n});return a}}class iv{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:d=null,dtype:p=null,session_options:u={}}={}){let h={progress_callback:r,config:n,cache_dir:a,local_files_only:i,revision:s,model_file_name:o,subfolder:l,device:d,dtype:p,session_options:u};if(n=await jt.from_pretrained(e,h),h.config||(h.config=n),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let m of this.MODEL_CLASS_MAPPINGS){const _=m.get(n.model_type);if(_)return await _[1].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${n.model_type}", attempting to construct from base class.`),await K.from_pretrained(e,h);throw Error(`Unsupported model type: ${n.model_type}`)}}const vf=new Map([["bert",["BertModel",q0]],["nomic_bert",["NomicBertModel",Z0]],["roformer",["RoFormerModel",J0]],["electra",["ElectraModel",u_]],["esm",["EsmModel",R_]],["convbert",["ConvBertModel",a_]],["camembert",["CamembertModel",f_]],["deberta",["DebertaModel",w_]],["deberta-v2",["DebertaV2Model",S_]],["mpnet",["MPNetModel",W_]],["albert",["AlbertModel",Q_]],["distilbert",["DistilBertModel",T_]],["roberta",["RobertaModel",yy]],["xlm",["XLMModel",xy]],["xlm-roberta",["XLMRobertaModel",ky]],["clap",["ClapModel",Yb]],["clip",["CLIPModel",Uy]],["clipseg",["CLIPSegModel",Ky]],["chinese_clip",["ChineseCLIPModel",jy]],["siglip",["SiglipModel",Gy]],["mobilebert",["MobileBertModel",N_]],["squeezebert",["SqueezeBertModel",j_]],["wav2vec2",["Wav2Vec2Model",gb]],["wav2vec2-bert",["Wav2Vec2BertModel",Ib]],["unispeech",["UniSpeechModel",bb]],["unispeech-sat",["UniSpeechSatModel",xb]],["hubert",["HubertModel",Ab]],["wavlm",["WavLMModel",zb]],["audio-spectrogram-transformer",["ASTModel",zy]],["vits",["VitsModel",_f]],["detr",["DetrModel",Ow]],["table-transformer",["TableTransformerModel",Bw]],["vit",["ViTModel",bw]],["mobilevit",["MobileViTModel",Sw]],["owlvit",["OwlViTModel",Cw]],["owlv2",["Owlv2Model",kw]],["beit",["BeitModel",Aw]],["deit",["DeiTModel",Lw]],["convnext",["ConvNextModel",tb]],["convnextv2",["ConvNextV2Model",nb]],["dinov2",["Dinov2Model",ib]],["resnet",["ResNetModel",Fw]],["swin",["SwinModel",Gw]],["swin2sr",["Swin2SRModel",Hw]],["donut-swin",["DonutSwinModel",eb]],["yolos",["YolosModel",ob]],["dpt",["DPTModel",jw]],["glpn",["GLPNModel",Qw]],["hifigan",["SpeechT5HifiGan",Ub]],["efficientnet",["EfficientNetModel",nv]]]),$f=new Map([["t5",["T5Model",ty]],["longt5",["LongT5Model",ny]],["mt5",["MT5Model",iy]],["bart",["BartModel",oy]],["mbart",["MBartModel",dy]],["marian",["MarianModel",pb]],["whisper",["WhisperModel",Py]],["m2m_100",["M2M100Model",fb]],["blenderbot",["BlenderbotModel",fy]],["blenderbot-small",["BlenderbotSmallModel",gy]]]),sv=new Map([["bloom",["BloomModel",fw]],["gpt2",["GPT2Model",Xy]],["gptj",["GPTJModel",rw]],["gpt_bigcode",["GPTBigCodeModel",aw]],["gpt_neo",["GPTNeoModel",Zy]],["gpt_neox",["GPTNeoXModel",ew]],["codegen",["CodeGenModel",sw]],["llama",["LlamaModel",lw]],["qwen2",["Qwen2Model",dw]],["phi",["PhiModel",pw]],["mpt",["MptModel",gw]],["opt",["OPTModel",yw]],["mistral",["MistralModel",Gb]],["starcoder2",["Starcoder2Model",Hb]],["falcon",["FalconModel",jb]]]),xf=new Map([["speecht5",["SpeechT5ForSpeechToText",Nb]],["whisper",["WhisperForConditionalGeneration",By]]]),ov=new Map([["speecht5",["SpeechT5ForTextToSpeech",Lb]]]),lv=new Map([["vits",["VitsModel",_f]],["musicgen",["MusicgenForConditionalGeneration",bf]]]),uv=new Map([["bert",["BertForSequenceClassification",K0]],["roformer",["RoFormerForSequenceClassification",t_]],["electra",["ElectraForSequenceClassification",c_]],["esm",["EsmForSequenceClassification",B_]],["convbert",["ConvBertForSequenceClassification",s_]],["camembert",["CamembertForSequenceClassification",g_]],["deberta",["DebertaForSequenceClassification",v_]],["deberta-v2",["DebertaV2ForSequenceClassification",C_]],["mpnet",["MPNetForSequenceClassification",V_]],["albert",["AlbertForSequenceClassification",Z_]],["distilbert",["DistilBertForSequenceClassification",A_]],["roberta",["RobertaForSequenceClassification",by]],["xlm",["XLMForSequenceClassification",Ey]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ay]],["bart",["BartForSequenceClassification",uy]],["mbart",["MBartForSequenceClassification",py]],["mobilebert",["MobileBertForSequenceClassification",U_]],["squeezebert",["SqueezeBertForSequenceClassification",Y_]]]),dv=new Map([["bert",["BertForTokenClassification",Y0]],["roformer",["RoFormerForTokenClassification",r_]],["electra",["ElectraForTokenClassification",p_]],["esm",["EsmForTokenClassification",D_]],["convbert",["ConvBertForTokenClassification",o_]],["camembert",["CamembertForTokenClassification",__]],["deberta",["DebertaForTokenClassification",$_]],["deberta-v2",["DebertaV2ForTokenClassification",I_]],["mpnet",["MPNetForTokenClassification",H_]],["distilbert",["DistilBertForTokenClassification",M_]],["roberta",["RobertaForTokenClassification",vy]],["xlm",["XLMForTokenClassification",Cy]],["xlm-roberta",["XLMRobertaForTokenClassification",My]]]),Sf=new Map([["t5",["T5ForConditionalGeneration",ry]],["longt5",["LongT5ForConditionalGeneration",ay]],["mt5",["MT5ForConditionalGeneration",sy]],["bart",["BartForConditionalGeneration",ly]],["mbart",["MBartForConditionalGeneration",cy]],["marian",["MarianMTModel",hb]],["m2m_100",["M2M100ForConditionalGeneration",mb]],["blenderbot",["BlenderbotForConditionalGeneration",my]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",_y]]]),vs=new Map([["bloom",["BloomForCausalLM",mw]],["gpt2",["GPT2LMHeadModel",Qy]],["gptj",["GPTJForCausalLM",nw]],["gpt_bigcode",["GPTBigCodeForCausalLM",iw]],["gpt_neo",["GPTNeoForCausalLM",Jy]],["gpt_neox",["GPTNeoXForCausalLM",tw]],["codegen",["CodeGenForCausalLM",ow]],["llama",["LlamaForCausalLM",uw]],["qwen2",["Qwen2ForCausalLM",cw]],["phi",["PhiForCausalLM",hw]],["mpt",["MptForCausalLM",_w]],["opt",["OPTForCausalLM",ww]],["mbart",["MBartForCausalLM",hy]],["mistral",["MistralForCausalLM",Vb]],["starcoder2",["Starcoder2ForCausalLM",qb]],["falcon",["FalconForCausalLM",Kb]],["trocr",["TrOCRForCausalLM",Wb]],["stablelm",["StableLmForCausalLM",rv]]]),cv=new Map([["bert",["BertForMaskedLM",j0]],["roformer",["RoFormerForMaskedLM",e_]],["electra",["ElectraForMaskedLM",d_]],["esm",["EsmForMaskedLM",P_]],["convbert",["ConvBertForMaskedLM",i_]],["camembert",["CamembertForMaskedLM",m_]],["deberta",["DebertaForMaskedLM",b_]],["deberta-v2",["DebertaV2ForMaskedLM",E_]],["mpnet",["MPNetForMaskedLM",G_]],["albert",["AlbertForMaskedLM",ey]],["distilbert",["DistilBertForMaskedLM",z_]],["roberta",["RobertaForMaskedLM",wy]],["xlm",["XLMWithLMHeadModel",Sy]],["xlm-roberta",["XLMRobertaForMaskedLM",Ty]],["mobilebert",["MobileBertForMaskedLM",L_]],["squeezebert",["SqueezeBertForMaskedLM",K_]]]),pv=new Map([["bert",["BertForQuestionAnswering",X0]],["roformer",["RoFormerForQuestionAnswering",n_]],["electra",["ElectraForQuestionAnswering",h_]],["convbert",["ConvBertForQuestionAnswering",l_]],["camembert",["CamembertForQuestionAnswering",y_]],["deberta",["DebertaForQuestionAnswering",x_]],["deberta-v2",["DebertaV2ForQuestionAnswering",k_]],["mpnet",["MPNetForQuestionAnswering",q_]],["albert",["AlbertForQuestionAnswering",J_]],["distilbert",["DistilBertForQuestionAnswering",O_]],["roberta",["RobertaForQuestionAnswering",$y]],["xlm",["XLMForQuestionAnswering",Iy]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Oy]],["mobilebert",["MobileBertForQuestionAnswering",F_]],["squeezebert",["SqueezeBertForQuestionAnswering",X_]]]),Ef=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Dy]]]),hv=new Map([["llava",["LlavaForConditionalGeneration",Ly]]]),fv=new Map([["vit",["ViTForImageClassification",vw]],["mobilevit",["MobileViTForImageClassification",Ew]],["beit",["BeitForImageClassification",Mw]],["deit",["DeiTForImageClassification",Uw]],["convnext",["ConvNextForImageClassification",rb]],["convnextv2",["ConvNextV2ForImageClassification",ab]],["dinov2",["Dinov2ForImageClassification",sb]],["resnet",["ResNetForImageClassification",Ww]],["swin",["SwinForImageClassification",Vw]],["segformer",["SegformerForImageClassification",Jb]],["efficientnet",["EfficientNetForImageClassification",av]]]),mv=new Map([["detr",["DetrForObjectDetection",zw]],["table-transformer",["TableTransformerForObjectDetection",Dw]],["yolos",["YolosForObjectDetection",lb]]]),gv=new Map([["owlvit",["OwlViTForObjectDetection",Iw]],["owlv2",["Owlv2ForObjectDetection",Tw]]]),_v=new Map([["detr",["DetrForSegmentation",Rw]],["clipseg",["CLIPSegForImageSegmentation",Yy]]]),yv=new Map([["segformer",["SegformerForSemanticSegmentation",ev]]]),wv=new Map([["sam",["SamModel",df]]]),bv=new Map([["wav2vec2",["Wav2Vec2ForCTC",_b]],["wav2vec2-bert",["Wav2Vec2BertForCTC",kb]],["unispeech",["UniSpeechForCTC",vb]],["unispeech-sat",["UniSpeechSatForCTC",Sb]],["wavlm",["WavLMForCTC",Rb]],["hubert",["HubertForCTC",Mb]]]),vv=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",yb]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Tb]],["unispeech",["UniSpeechForSequenceClassification",$b]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Eb]],["wavlm",["WavLMForSequenceClassification",Pb]],["hubert",["HubertForSequenceClassification",Ob]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ry]]]),$v=new Map([["wavlm",["WavLMForXVector",Bb]]]),xv=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Cb]],["wavlm",["WavLMForAudioFrameClassification",Db]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",wb]]]),Sv=new Map([["vitmatte",["VitMatteForImageMatting",xw]]]),Ev=new Map([["swin2sr",["Swin2SRForImageSuperResolution",qw]]]),Cv=new Map([["dpt",["DPTForDepthEstimation",Kw]],["depth_anything",["DepthAnythingForDepthEstimation",Xw]],["glpn",["GLPNForDepthEstimation",Zw]]]),Iv=new Map([["clip",["CLIPVisionModelWithProjection",Wy]],["siglip",["SiglipVisionModel",Hy]]]),Cf=[[vf,pe.EncoderOnly],[$f,pe.EncoderDecoder],[sv,pe.DecoderOnly],[uv,pe.EncoderOnly],[dv,pe.EncoderOnly],[Sf,pe.Seq2Seq],[xf,pe.Seq2Seq],[vs,pe.DecoderOnly],[cv,pe.EncoderOnly],[pv,pe.EncoderOnly],[Ef,pe.Vision2Seq],[hv,pe.ImageTextToText],[fv,pe.EncoderOnly],[_v,pe.EncoderOnly],[yv,pe.EncoderOnly],[Sv,pe.EncoderOnly],[Ev,pe.EncoderOnly],[Cv,pe.EncoderOnly],[mv,pe.EncoderOnly],[gv,pe.EncoderOnly],[wv,pe.MaskGeneration],[bv,pe.EncoderOnly],[vv,pe.EncoderOnly],[ov,pe.Seq2Seq],[lv,pe.EncoderOnly],[$v,pe.EncoderOnly],[xv,pe.EncoderOnly],[Iv,pe.EncoderOnly]];for(const[t,e]of Cf)for(const[r,n]of t.values())ya.set(r,e),an.set(n,r),vh.set(r,n);const kv=[["MusicgenForConditionalGeneration",bf,pe.Musicgen],["CLIPTextModelWithProjection",Fy,pe.EncoderOnly],["SiglipTextModel",Vy,pe.EncoderOnly],["ClapTextModelWithProjection",Xb,pe.EncoderOnly],["ClapAudioModelWithProjection",Qb,pe.EncoderOnly]];for(const[t,e,r]of kv)ya.set(t,r),an.set(e,t),vh.set(t,e);class B2 extends iv{static MODEL_CLASS_MAPPINGS=Cf.map(e=>e[0]);static BASE_IF_FAIL=!0}class ke extends _t{constructor({logits:e}){super(),this.logits=e}}class Tv extends _t{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}}class rt extends _t{constructor({logits:e}){super(),this.logits=e}}class nt extends _t{constructor({logits:e}){super(),this.logits=e}}class lt extends _t{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}}class kr extends _t{constructor({logits:e}){super(),this.logits=e}}class Av extends _t{constructor({alphas:e}){super(),this.alphas=e}}class Mv extends _t{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}}const yt=typeof self<"u",Ov=yt&&self.constructor.name==="DedicatedWorkerGlobalScope";let mr,If,Yt;if(yt)mr=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},Yt=self.createImageBitmap,If=self.ImageData;else if(He)Yt=async t=>{const r=(await t.metadata()).channels,{data:n,info:a}=await t.raw().toBuffer({resolveWithObject:!0}),i=new wt(new Uint8ClampedArray(n),a.width,a.height,a.channels);return r!==void 0&&r!==a.channels&&i.convert(r),i};else throw new Error("Unable to load image processing library.");const zv={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},Rv=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class wt{constructor(e,r,n,a){this.data=e,this.width=r,this.height=n,this.channels=a}get size(){return[this.width,this.height]}static async read(e){if(e instanceof wt)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!yt)throw new Error("fromCanvas() is only supported in browser environments.");const n=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new wt(n,e.width,e.height,4)}static async fromURL(e){const r=await Ka(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);const n=await r.blob();return this.fromBlob(n)}static async fromBlob(e){if(yt){const r=await Yt(e),n=mr(r.width,r.height).getContext("2d");return n.drawImage(r,0,0),new this(n.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=He(await e.arrayBuffer());return await Yt(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new wt(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,n=0;r=0?l=n:p=-n,a>=0?d=a:u=-a,o.drawImage(s,l,d,e,r,p,u,e,r),new wt(o.getImageData(0,0,e,r).data,e,r,4).convert(i)}else{let i=this.toSharp();if(n>=0&&a>=0)i=i.extract({left:Math.floor(n),top:Math.floor(a),width:e,height:r});else if(n<=0&&a<=0){const s=Math.floor(-a),o=Math.floor(-n);i=i.extend({top:s,left:o,right:e-this.width-o,bottom:r-this.height-s})}else{let s=[0,0],o=0;a<0?(s[0]=Math.floor(-a),s[1]=r-this.height-s[0]):o=Math.floor(a);let l=[0,0],d=0;n<0?(l[0]=Math.floor(-n),l[1]=e-this.width-l[0]):d=Math.floor(n),i=i.extend({top:s[0],bottom:s[1],left:l[0],right:l[1]}).extract({left:d,top:o,width:e,height:r})}return await Yt(i)}}async toBlob(e="image/png",r=1){if(!yt)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new Z("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!yt)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),r=mr(e.width,e.height),n=new If(e.data,e.width,e.height);return r.getContext("2d").putImageData(n,0,0),r}_update(e,r,n,a=null){return this.data=e,this.width=r,this.height=n,a!==null&&(this.channels=a),this}clone(){return new wt(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(yt){if(Ov)throw new Error("Unable to save an image from a Web Worker.");const r=e.split(".").pop().toLowerCase(),n=Rv.get(r)??"image/png",a=await this.toBlob(n),i=URL.createObjectURL(a),s=document.createElement("a");s.href=i,s.download=e,s.click(),s.remove()}else{if(dt.useFS)return await this.toSharp().toFile(e);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(yt)throw new Error("toSharp() is only supported in server-side environments.");return He(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}function kf(t){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);const e=t-1,r=Math.PI/e,n=new Float64Array(t);for(let a=0;a2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,n=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*n:3*t/200};function $s(t,e="htk"){const r=Pv[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(n=>r(n))}const Bv={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,n=Math.log(6.4)/27)=>t>=r?e*Math.exp(n*(t-r)):200*t/3};function Dv(t,e="htk"){const r=Bv[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(n=>r(n))}function Nv(t,e){const r=Float64Array.from({length:e.length-1},(s,o)=>e[o+1]-e[o]),n=Array.from({length:t.length},()=>new Array(e.length));for(let s=0;snew Array(t.length));for(let s=0;st+n*i)}function bn(t,e,r,n,a,i=null,s="htk",o=!1){if(i!==null&&i!=="slaney")throw new Error('norm must be one of null or "slaney"');const l=$s(r,s),d=$s(n,s),p=Tf(l,d,e+2);let u=Dv(p,s),h;if(o){const _=a/(t*2);h=$s(Float64Array.from({length:t},(y,v)=>v*_),s),u=p}else h=Tf(0,Math.floor(a/2),t);const m=Nv(h,u);if(i!==null&&i==="slaney")for(let _=0;_a)throw Error(`frame_length (${r}) may not be larger than fft_length (${a})`);if(I!==r)throw new Error(`Length of the window (${I}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(s){if(o!=="reflect")throw new Error(`pad_mode="${o}" not implemented yet.`);const q=Math.floor((a-1)/2)+1;t=Lv(t,q,q)}const k=Math.floor(1+Math.floor((t.length-r)/n)),A=l?Math.floor(a/2)+1:a;let D=k,L=k;x!==null&&(x>k?w&&(L=x):L=D=x);const Y=new Em(a),H=new Float64Array(a),re=new Float64Array(Y.outputBufferSize),N=new Array(D);for(let q=0;q=1;--W)H[W]-=d*H[W-1];H[0]*=1-d}for(let W=0;WMath.pow(o,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(s=s.subarray(0,t)),n===null)return s;if(t>n)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${n})`);return s}function Wv([t,e,r,n]){return[t-r/2,e-n/2,t+r/2,e+n/2]}function xs(t,e=.5,r=null,n=!1){const a=t.logits,i=t.pred_boxes,[s,o,l]=a.dims;if(r!==null&&r.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let d=[];for(let p=0;pe&&x.push(E)}else{let E=er(v.data)[1];if(E===l-1||(w=Vn(v.data),w[E]k*u[(A+1)%2])),h.boxes.push(I),h.classes.push(E),h.scores.push(w[E])}}d.push(h)}return d}function vn(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function Mf(t,e,r=0,n=null){const a=t/e;let i=Im(a)*e;return n!==null&&i>n&&(i=Math.floor(a)*e),ii?d=Math.floor(i*l/a):i>a&&(l=Math.floor(a*d/i)),await e.resize(d,l,{resample:n}))}async crop_margin(e,r=200){const n=e.clone().grayscale(),a=xm(n.data)[0],s=er(n.data)[0]-a;if(s===0)return e;const o=r/255;let l=n.width,d=n.height,p=0,u=0;const h=n.data;for(let m=0;mthis.preprocess(i)));return{pixel_values:nn(n.map(i=>i.pixel_values),0),original_sizes:n.map(i=>i.original_size),reshaped_input_sizes:n.map(i=>i.reshaped_input_size)}}}class Gv extends Ge{post_process_semantic_segmentation(e,r=null){const n=e.logits,a=n.dims[0];if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const i=[];for(let s=0;sh[E]&&(h[E]=w[E],m[E]=x)}const _=new Array(l.dims[0]),y=u.data;for(let x=0;xx!==void 0);i.push({segmentation:u,labels:v})}return i}}class Of extends Ge{}class Vv extends Of{}class Hv extends Ge{}class qv extends Ge{}class zf extends Ge{}class jv extends zf{}class Kv extends Ge{}class Yv extends Ge{}class Rf extends Ge{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){const n=Math.floor(r/this.crop_pct),[a,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(a,i,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}}class Xv extends Rf{}class Qv extends Ge{}class Zv extends Ge{}class Jv extends Ge{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}}class e2 extends Ge{}class Pf extends Ge{post_process_object_detection(...e){return xs(...e)}}class t2 extends Pf{}class r2 extends Ge{}class n2 extends Ge{}class Bf extends Ge{pad_image(e,r,n,a={}){const[i,s,o]=r;let l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(o).fill(l));let d=this.image_std;Array.isArray(d)||(d=new Array(o).fill(l));const p=l.map((u,h)=>-u/d[h]);return super.pad_image(e,r,n,{center:!0,constant_values:p,...a})}}class a2 extends Bf{}class i2 extends Ge{async _call(e){const r=await super._call(e),n=[r.pixel_values.dims[0],64,64],a=new Z("int64",new BigInt64Array(n.reduce((i,s)=>i*s)).fill(1n),n);return{...r,pixel_mask:a}}post_process_object_detection(...e){return xs(...e)}remove_low_and_no_objects(e,r,n,a){let i=[],s=[],o=[];for(let l=0;ln&&(i.push(p),s.push(m),o.push(u))}return[i,s,o]}check_segment_validity(e,r,n,a=.5,i=.8){let s=[],o=0,l=0;const d=r[n].data;for(let u=0;u=a&&++l;let p=o>0&&l>0;return p&&(p=o/l>i),[p,s]}compute_segments(e,r,n,a,i,s=null,o=null){let[l,d]=o??e[0].dims,p=new Z("int32",new Int32Array(l*d),[l,d]),u=[];if(o!==null)for(let v=0;vm[E]&&(h[E]=v,m[E]=w[E])}let _=0;const y=p.data;for(let v=0;va!==r.dims[i]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Z("int64",e.flat(1/0).map(BigInt),n)}async _call(e,r=null,n=null){const a=await super._call(e);if(r&&(a.input_points=this.reshape_input_points(r,a.original_sizes,a.reshaped_input_sizes)),n){if(!a.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");a.input_labels=this.add_input_labels(n,a.input_points)}return a}async post_process_masks(e,r,n,{mask_threshold:a=0,binarize:i=!0,pad_size:s=null}={}){const o=[];s=s??this.pad_size;const l=[s.height,s.width];for(let d=0;da&&(_[y]=1);h=new Z("bool",_,h.dims)}o.push(h)}return o}generate_crop_boxes(e,r,{crop_n_layers:n=0,overlap_ratio:a=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:s=1}={}){}}class l2 extends Ge{pad_image(e,r,n,a={}){const[i,s,o]=r;return super.pad_image(e,r,{width:s+(n-s%n)%n,height:i+(n-i%n)%n},{mode:"symmetric",center:!1,constant_values:-1,...a})}}class u2 extends Ge{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);const n=await Promise.all(e.map(s=>this.preprocess(s))),a=await Promise.all(r.map(s=>this.preprocess(s,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:nn(n.map((s,o)=>Ot([s.pixel_values,a[o].pixel_values],0)),0),original_sizes:n.map(s=>s.original_size),reshaped_input_sizes:n.map(s=>s.reshaped_input_size)}}}class d2 extends gr{constructor(e){super(e),this.config.mel_filters??=bn(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Ia(this.config.n_fft,"hann")}_extract_fbank_features(e){const{data:r,dims:n}=Ca(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),a=er(r)[0];for(let i=0;ithis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,this.config.n_samples)):(r=new Float32Array(this.config.n_samples),r.set(e));const{data:n,dims:a}=this._extract_fbank_features(r);return{input_features:new Z("float32",n,[1,...a])}}}class c2 extends gr{_zero_mean_unit_var_norm(e){const n=e.reduce((i,s)=>i+s,0)/e.length,a=e.reduce((i,s)=>i+(s-n)**2,0)/e.length;return e.map(i=>(i-n)/Math.sqrt(a+1e-7))}async _call(e){vn(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));const n=[1,r.length];return{input_values:new Z("float32",r,n),attention_mask:new Z("int64",new BigInt64Array(r.length).fill(1n),n)}}}class p2 extends gr{constructor(e){super(e);const r=this.config.sampling_rate,n=bn(256,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);for(let a=0;an*32768),Ca(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:a=!0,return_attention_mask:i=!0}={}){vn(e,"SeamlessM4TFeatureExtractor");let s=this._extract_fbank_features(e,this.config.max_length);const o=s.data;if(a){const[y,v]=s.dims;for(let x=0;x0){const w=new Float32Array(v*(y+x));w.set(o),w.fill(this.config.padding_value,o.length);const E=y+x;s={data:w,dims:[E,v]},i&&(l=new Z("int64",new BigInt64Array(E),[1,E]),l.data.fill(1n,0,y))}}const[d,p]=s.dims,u=this.config.stride;if(d%u!==0)throw new Error(`The number of frames (${d}) must be a multiple of the stride (${u}).`);const m=new Z("float32",o,s.dims).view(1,Math.floor(d/u),p*u),_={input_features:m};if(i){const y=m.dims[1],v=new BigInt64Array(y);if(l){const x=l.data;for(let w=1,E=0;w0)if(n==="rand_trunc"){s=!0;const l=Math.floor(Math.random()*(o+1));e=e.subarray(l,l+r),i=this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples),i.dims=[1,...i.dims]}else throw new Error(`Truncation strategy "${n}" not implemented`);else{if(o<0){let l=new Float64Array(r);if(l.set(e),a==="repeat")for(let d=e.length;d{const[e,r]=await $2.getInstance();Df||(Df=!0,self.postMessage({type:"ready"}));const{type:n,data:a}=t.data;if(n==="reset")Ar=null,Es=null;else if(n==="segment"){self.postMessage({type:"segment_result",data:"start"});const i=await wt.read(t.data.data);Ar=await r(i),Es=await e.get_image_embeddings(Ar),self.postMessage({type:"segment_result",data:"done"})}else if(n==="decode"){const i=Ar.reshaped_input_sizes[0],s=a.map(m=>[m.point[0]*i[1],m.point[1]*i[0]]),o=a.map(m=>BigInt(m.label)),l=new Z("float32",s.flat(1/0),[1,1,s.length,2]),d=new Z("int64",o.flat(1/0),[1,1,o.length]),{pred_masks:p,iou_scores:u}=await e({...Es,input_points:l,input_labels:d}),h=await r.post_process_masks(p,Ar.original_sizes,Ar.reshaped_input_sizes);self.postMessage({type:"decode_result",data:{mask:wt.fromTensor(h[0][0]),scores:u.data}})}else throw new Error(`Unknown message type: ${n}`)}})();