diff --git "a/assets/index-BXu2AHtw.js" "b/assets/index-BXu2AHtw.js" deleted file mode 100644--- "a/assets/index-BXu2AHtw.js" +++ /dev/null @@ -1,2289 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();const Xe={},Gg=Object.freeze(Object.defineProperty({__proto__:null,default:Xe},Symbol.toStringTag,{value:"Module"})),Vg="3.0.0-alpha.0",pi=typeof self<"u",Hg=pi&&self.constructor.name==="DedicatedWorkerGlobalScope",bc=pi&&"caches"in self,qg=typeof navigator<"u"&&"gpu"in navigator,jg=typeof process<"u"&&process?.release?.name==="node",Xa=!xc(Xe),vc=!xc(Xe),Dn=Object.freeze({IS_BROWSER_ENV:pi,IS_WEBWORKER_ENV:Hg,IS_WEB_CACHE_AVAILABLE:bc,IS_WEBGPU_AVAILABLE:qg,IS_NODE_ENV:jg,IS_FS_AVAILABLE:Xa,IS_PATH_AVAILABLE:vc}),Us=Xa&&vc,$c=Us?Xe.dirname(Xe.dirname(Xe.fileURLToPath(import.meta.url))):"./",Kg=Us?Xe.join($c,"/.cache/"):null,jo="/models/",Yg=Us?Xe.join($c,jo):jo,_t={version:Vg,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!pi,localModelPath:Yg,useFS:Xa,useBrowserCache:bc,useFSCache:Xa,cacheDir:Kg,useCustomCache:!1,customCache:null};function xc(t){return Object.keys(t).length===0}const mt=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 yn(t,e){t&&t(e)}function Xg(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e]))}function Sc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qg(t){return Number.isInteger(t)||typeof t=="bigint"}function Ko(t){const e=[];let r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function st(...t){return Array.prototype.concat.apply([],t)}function Qa(t,e){return Math.abs((t+e)%(2*e)-e)}function Yr(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}var Ri={};class hi{_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=Xe.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Xe.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 hi(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 Xe.promises.readFile(this.filePath)).buffer}async blob(){const e=await Xe.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Xe.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function ys(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 bs(t){if(_t.useFS&&!ys(t))return new hi(t);if(typeof process<"u"&&process?.release?.name==="node"){const e=!!Ri?.TESTING_REMOTELY,r=_t.version,n=new Headers;if(n.set("User-Agent",`transformers.js/${r}; is_ci/${e};`),ys(t,["huggingface.co","hf.co"])){const i=Ri?.HF_TOKEN??Ri?.HF_ACCESS_TOKEN;i&&n.set("Authorization",`Bearer ${i}`)}return fetch(t,{headers:n})}else return fetch(t)}const Zg={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 Jg(t,e,r){if(!r)return null;const n=Zg[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${n}: "${e}".`)}class Yo{constructor(e){this.path=e}async match(e){let r=Xe.join(this.path,e),n=new hi(r);if(n.exists)return n}async put(e,r){const n=Buffer.from(await r.arrayBuffer());let a=Xe.join(this.path,e);try{await Xe.promises.mkdir(Xe.dirname(a),{recursive:!0}),await Xe.promises.writeFile(a,n)}catch(i){console.warn("An error occurred while writing the file to cache:",i)}}}async function e_(t,...e){for(let r of e)try{let n=await t.match(r);if(n)return n}catch{continue}}async function vs(t,e,r=!0,n={}){if(!_t.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`).");yn(n.progress_callback,{status:"initiate",name:t,file:e});let a;if(!a&&_t.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{a=await caches.open("transformers-cache")}catch($){console.warn("An error occurred while opening the browser cache:",$)}}if(!a&&_t.useFSCache&&(a=new Yo(n.cache_dir??_t.cacheDir)),!a&&_t.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const i=n.revision??"main";let s=ka(t,e),o=ka(_t.localModelPath,s),l=ka(_t.remoteHost,_t.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(i)),e),d=i==="main"?s:ka(t,i,e),c,u=a instanceof Yo?d:l,h=!1,m;a&&(m=await e_(a,o,u));const g=m!==void 0;if(m===void 0){if(_t.allowLocalModels)if(ys(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 bs(o),c=o}catch(y){console.warn(`Unable to load from local path "${o}": "${y}"`)}if(m===void 0||m.status===404){if(n.local_files_only||!_t.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 bs(l),m.status!==200)return Jg(m.status,l,r);c=u}h=a&&typeof Response<"u"&&m instanceof Response&&m.status===200}yn(n.progress_callback,{status:"download",name:t,file:e});const _={status:"progress",name:t,file:e};let b;return n.progress_callback?g&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(b=new Uint8Array(await m.arrayBuffer()),yn(n.progress_callback,{..._,progress:100,loaded:b.length,total:b.length})):b=await t_(m,$=>{yn(n.progress_callback,{..._,...$})}):b=new Uint8Array(await m.arrayBuffer()),h&&c&&await a.match(c)===void 0&&await a.put(c,new Response(b,{headers:m.headers})).catch($=>{console.warn(`Unable to add response to browser cache: ${$}.`)}),yn(n.progress_callback,{status:"done",name:t,file:e}),b}async function pr(t,e,r=!0,n={}){let a=await vs(t,e,r,n);if(a===null)return{};let s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}async function t_(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 c=i+d.length;if(c>n){n=c;let h=new Uint8Array(n);h.set(a),a=h}a.set(d,i),i=c;const u=i/n*100;return e({progress:u,loaded:i,total:n}),o()}return await o(),a}function ka(...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 r_(t,[e,r,n],[a,i],s="bilinear",o=!1){const l=i/n,d=a/r,c=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+=c%e[d]*i[d],c=Math.floor(c/e[d]);s[l]=t[o]}return[s,n]}function Hn(t){const e=mr(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 a_(t,e){let r=0;for(let n=0;n[n,r]).sort((r,n)=>n[1]-r[1]),e!==null&&e>0&&(t=t.slice(0,e)),t}function kc(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 Cc(t){return t>0&&(t&t-1)===0}class Tc{constructor(e){if(this.size=e|0,this.size<=1||!Cc(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;++c){const u=(c+1-e)**2/2,h=Math.sqrt(l**2+d**2)**u,m=u*Math.atan2(d,l),g=2*c;i[g]=h*Math.cos(m),i[g+1]=h*Math.sin(m),s[g]=i[g],s[g+1]=-i[g+1]}this._slicedChirpBuffer=i.subarray(r,n),this._f=new Tc(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,c=this._a;if(n)for(let u=0;u>1,g=r[m];a[u]=g*d[u],a[h]=g*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 Ca(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}function l_(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 Fs=Object.defineProperty,u_=Object.getOwnPropertyDescriptor,d_=Object.getOwnPropertyNames,c_=Object.prototype.hasOwnProperty,X=(t,e)=>()=>(t&&(e=t(t=0)),e),Qr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Zr=(t,e)=>{for(var r in e)Fs(t,r,{get:e[r],enumerable:!0})},p_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of d_(e))!c_.call(t,a)&&a!==r&&Fs(t,a,{get:()=>e[a],enumerable:!(n=u_(e,a))||n.enumerable});return t},Mr=t=>p_(Fs({},"__esModule",{value:!0}),t),bn,or,Ar,Xo,Ws,Gs=X(()=>{bn=new Map,or=[],Ar=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let n=bn.get(t);if(n===void 0)bn.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=or.indexOf(t);a!==-1&&or.splice(a,1);for(let i=0;i{let e=bn.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}}},Ws=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),n=r.length===0?or:r,a,i=[],s=new Set;for(let l of n){let d=await Xo(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)})]}}),h_=X(()=>{Gs()}),Ic,f_=X(()=>{Ic="1.17.3"}),Bi,kt,Ac=X(()=>{f_(),Bi="warning",kt={wasm:{},webgl:{},webgpu:{},versions:{common:Ic},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}`);Bi=t}},get logLevel(){return Bi}},Object.defineProperty(kt,"logLevel",{enumerable:!0})}),De,m_=X(()=>{Ac(),De=kt}),Mc,Oc,g_=X(()=>{Mc=(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 c=i*a,u=0,h=c,m=c*2,g=-1;s==="RGBA"?(u=0,h=c,m=c*2,g=c*3):s==="RGB"?(u=0,h=c,m=c*2):s==="RBG"&&(u=0,m=c,h=c*2);for(let _=0;_{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,c;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?c=[0,0,0,0]:typeof l.bias=="number"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[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,g=1,_=2,b=3,$=0,y=u,E=u*2,k=-1;o==="RGBA"?($=0,y=u,E=u*2,k=u*3):o==="RGB"?($=0,y=u,E=u*2):o==="RBG"&&($=0,E=u,y=u*2),n=r.createImageData(a,i);for(let T=0;T{Vs(),Ta=(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,c=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),u=4,h=0,m=1,g=2,_=3,b=0,$=d,y=d*2,E=-1;o==="RGB"&&(u=3,h=0,m=1,g=2,_=-1),l==="RGBA"?E=d*3:l==="RBG"?(b=0,y=d,$=d*2):l==="BGR"&&(y=0,$=d,b=d*2);for(let k=0;k{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=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(r){let c=l();c.width=t.width,c.height=t.height;let u=d(c);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 c,u;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,u=e.resizedWidth):(c=t.height,u=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=c,o.width=u,e!==void 0){let h=l();h.width=u,h.height=c;let m=d(h);if(m!=null)m.putImageData(t,0,0),s=m.getImageData(0,0,u,c).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 c=l();c.width=t.width,c.height=t.height;let u=d(c);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,Ta(s,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((c,u)=>{let h=l(),m=d(h);if(!t||!m)return u();let g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{h.width=g.width,h.height=g.height,m.drawImage(g,0,0,h.width,h.height);let _=m.getImageData(0,0,h.width,h.height);o.height=h.height,o.width=h.width,c(Ta(_.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return Ta(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},Pc=(t,e)=>{let{width:r,height:n,download:a,dispose:i}=e,s=[1,n,r,4];return new Lt({location:"texture",type:"float32",texture:t,dims:s,download:a,dispose:i})},Rc=(t,e)=>{let{dataType:r,dims:n,download:a,dispose:i}=e;return new Lt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:i})},Bc=(t,e,r)=>new Lt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Cr,An,Di,Dc,w_=X(()=>{Cr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),An=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Di=!1,Dc=()=>{if(!Di){Di=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;t&&(Cr.set("int64",BigInt64Array),An.set(BigInt64Array,"int64")),e&&(Cr.set("uint64",BigUint64Array),An.set(BigUint64Array,"uint64")),r?(Cr.set("float16",Float16Array),An.set(Float16Array,"float16")):Cr.set("float16",Uint16Array)}}}),Nc,Lc,y_=X(()=>{Vs(),Nc=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Lt(t.type,t.data,e);case"cpu-pinned":return new Lt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Lt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Lt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Lt,Vs=X(()=>{g_(),__(),w_(),y_(),Lt=class{constructor(t,e,r){Dc();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=Cr.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=Cr.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=An.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=Nc(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 zc(t,e)}static fromTexture(t,e){return Pc(t,e)}static fromGpuBuffer(t,e){return Rc(t,e)}static fromPinnedBuffer(t,e,r){return Bc(t,e,r)}toDataURL(t){return Mc(this,t)}toImageData(t){return Oc(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 Lc(this,t)}}}),ft,Hs=X(()=>{Vs(),ft=Lt}),Nn,Ni,Ut,Tt,Uc=X(()=>{Ac(),Nn=(t,e)=>{(typeof kt.trace>"u"?!kt.wasm.trace:!kt.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 kt.trace>"u"?!kt.wasm.trace:!kt.trace)||Ni("BEGIN",t)},Tt=t=>{(typeof kt.trace>"u"?!kt.wasm.trace:!kt.trace)||Ni("END",t)}}),Fc,b_=X(()=>{Gs(),Hs(),Uc(),Fc=class Wc{constructor(e){this.handler=e}async run(e,r,n){Ut();let a={},i={};if(typeof e!="object"||e===null||e instanceof ft||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 ft)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,c=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(c.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof ft)&&(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 c=o[d];c instanceof ft?l[d]=c:l[d]=new ft(c.type,c.data,c.dims)}return Tt(),l}async release(){return this.handler.dispose()}static async create(e,r,n,a){Ut();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 c=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>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.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>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.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(c,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await Ws(s),d=await o.createInferenceSessionHandler(i,l);return Tt(),new Wc(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),qs,v_=X(()=>{b_(),qs=Fc}),$_=X(()=>{}),x_=X(()=>{}),S_=X(()=>{}),E_=X(()=>{}),Qo,Gc,k_=X(()=>{Gs(),Hs(),Qo="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Gc=class Vc{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 Ws(i);if(s.createTrainingSessionHandler){let l=await s.createTrainingSessionHandler(e.checkpointState,e.trainModel,n,a,o);return new Vc(l,!!e.optimizerModel,!!e.evalModel)}else throw new Error(Qo)}typeNarrowingForRunStep(e,r,n,a,i){let s={},o={};if(typeof n!="object"||n===null||n instanceof ft||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 ft)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,c=Object.getOwnPropertyNames(a);for(let u of r)if(c.indexOf(u)!==-1){let h=a[u];(h===null||h instanceof ft)&&(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 ft?r[n]=a:r[n]=new ft(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()}}}),js,C_=X(()=>{k_(),js=Gc}),Hc={};Zr(Hc,{InferenceSession:()=>qs,TRACE:()=>Nn,TRACE_FUNC_BEGIN:()=>Ut,TRACE_FUNC_END:()=>Tt,Tensor:()=>ft,TrainingSession:()=>js,env:()=>De,registerBackend:()=>Ar});var Ft=X(()=>{h_(),m_(),v_(),Hs(),$_(),x_(),Uc(),S_(),E_(),C_()}),Ks={};Zr(Ks,{createReadStream:()=>Kc,readFile:()=>qc,readFileSync:()=>jc});var qc,jc,Kc,Yc=X(()=>{qc=void 0,jc=void 0,Kc=void 0}),Ys={};Zr(Ys,{join:()=>Xc});var Xc,Qc=X(()=>{Xc=void 0}),T_=Qr((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,v)=>{s=f,o=v}),i.mountExternalData=(f,v)=>{(i.Fa||(i.Fa=new Map)).set(f,v)},i.unmountExternalData=()=>{delete i.Fa};let l=()=>{let f=(S,I,z)=>(...V)=>{let re=wt,ue=I?.();V=S(...V);let _e=I?.();return ue!==_e&&(S=_e,z(ue),I=z=null),wt!=re?ma():V},v=S=>async(...I)=>{try{if(i.Ea)throw Error("Session already started");let z=i.Ea={Za:I[0],errors:[]},V=await S(...I);if(i.Ea!==z)throw Error("Session mismatch");i.La?.flush();let re=z.errors;if(0_e),0i._OrtCreateSession,S=>i._OrtCreateSession=S),i._OrtRun=v(f(i._OrtRun,()=>i._OrtRun,S=>i._OrtRun=S)),i._OrtRunWithBinding=v(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,v)=>{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]=v;let S=i.La;i.jsepRegisterBuffer=(I,z,V,re)=>S.registerBuffer(I,z,V,re),i.jsepGetBuffer=I=>S.getBuffer(I),i.jsepCreateDownloader=(I,z,V)=>S.createDownloader(I,z,V),i.jsepOnReleaseSession=I=>{S.onReleaseSession(I)},i.jsepOnRunStart=I=>S.onRunStart(I)}};var d=Object.assign({},i),c="./this.program",u=(f,v)=>{throw v},h=typeof window=="object",m=typeof importScripts=="function",g=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_="",b,$,y;if(g){var E=(Yc(),Mr(Ks)),k=(Qc(),Mr(Ys));_=m?k.dirname(_)+"/":__dirname+"/",b=(f,v)=>(f=Pe(f)?new URL(f):k.normalize(f),E.readFileSync(f,v?void 0:"utf8")),y=f=>(f=b(f,!0),f.buffer||(f=new Uint8Array(f)),f),$=(f,v,S,I=!0)=>{f=Pe(f)?new URL(f):k.normalize(f),E.readFile(f,I?void 0:"utf8",(z,V)=>{z?S(z):v(I?V.buffer:V)})},!i.thisProgram&&1{throw process.exitCode=f,v},i.inspect=()=>"[Emscripten Module object]"}else(h||m)&&(m?_=self.location.href:typeof document<"u"&&document.currentScript&&(_=document.currentScript.src),n&&(_=n),_.indexOf("blob:")!==0?_=_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1):_="",b=f=>{var v=new XMLHttpRequest;return v.open("GET",f,!1),v.send(null),v.responseText},m&&(y=f=>{var v=new XMLHttpRequest;return v.open("GET",f,!1),v.responseType="arraybuffer",v.send(null),new Uint8Array(v.response)}),$=(f,v,S)=>{var I=new XMLHttpRequest;I.open("GET",f,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?v(I.response):S()},I.onerror=S,I.send(null)});var T=console.log.bind(console),A=console.error.bind(console);Object.assign(i,d),d=null,typeof WebAssembly!="object"&&ne("no native wasm support detected");var R,W=!1,K,q,ee,P,J,te,F;function O(){var f=R.buffer;i.HEAP8=q=new Int8Array(f),i.HEAP16=new Int16Array(f),i.HEAPU8=ee=new Uint8Array(f),i.HEAPU16=new Uint16Array(f),i.HEAP32=P=new Int32Array(f),i.HEAPU32=J=new Uint32Array(f),i.HEAPF32=te=new Float32Array(f),i.HEAPF64=F=new Float64Array(f)}var G=[],ie=[],j=[],se=0,L=null;function ne(f){throw f="Aborted("+f+")",A(f),W=!0,K=1,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),o(f),f}var me=f=>f.startsWith("data:application/octet-stream;base64,"),Pe=f=>f.startsWith("file://"),Re;if(Re="ort-wasm-simd.wasm",!me(Re)){var nt=Re;Re=i.locateFile?i.locateFile(nt,_):_+nt}function He(f){if(y)return y(f);throw"both async and sync fetching of the wasm failed"}function ot(f){if(h||m){if(typeof fetch=="function"&&!Pe(f))return fetch(f,{credentials:"same-origin"}).then(v=>{if(!v.ok)throw"failed to load wasm binary file at '"+f+"'";return v.arrayBuffer()}).catch(()=>He(f));if($)return new Promise((v,S)=>{$(f,I=>v(new Uint8Array(I)),S)})}return Promise.resolve().then(()=>He(f))}function pt(f,v,S){return ot(f).then(I=>WebAssembly.instantiate(I,v)).then(I=>I).then(S,I=>{A(`failed to asynchronously prepare wasm: ${I}`),ne(I)})}function Ue(f,v){var S=Re;return typeof WebAssembly.instantiateStreaming!="function"||me(S)||Pe(S)||g||typeof fetch!="function"?pt(S,f,v):fetch(S,{credentials:"same-origin"}).then(I=>WebAssembly.instantiateStreaming(I,f).then(v,function(z){return A(`wasm streaming compile failed: ${z}`),A("falling back to ArrayBuffer instantiation"),pt(S,f,v)}))}var Ke,lt={931760:(f,v,S,I)=>{if(typeof i>"u"||!i.Fa)return 1;if(f=Qe(f>>>0),f.startsWith("./")&&(f=f.substring(2)),f=i.Fa.get(f),!f)return 2;if(v>>>=0,S>>>=0,v+S>f.byteLength)return 3;try{return ee.set(f.subarray(v,v+S),I>>>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,v,S)=>{i.Ma(f,v,S,!0)},932450:(f,v,S)=>{i.Ma(f,v,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,v,S)=>{i.sa("HardSigmoid",f,{alpha:v,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,v,S)=>{i.sa("Clip",f,{min:v,max:S})},933831:f=>{i.sa("Clip",f,void 0)},933883:(f,v)=>{i.sa("Elu",f,{alpha:v})},933941:f=>{i.sa("Relu",f,void 0)},933993:(f,v)=>{i.sa("LeakyRelu",f,{alpha:v})},934057:(f,v)=>{i.sa("ThresholdedRelu",f,{alpha:v})},934127:(f,v)=>{i.sa("Cast",f,{to:v})},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,v,S,I,z)=>{i.sa("ReduceMean",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},934880:(f,v,S,I,z)=>{i.sa("ReduceMax",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},935038:(f,v,S,I,z)=>{i.sa("ReduceMin",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},935196:(f,v,S,I,z)=>{i.sa("ReduceProd",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},935355:(f,v,S,I,z)=>{i.sa("ReduceSum",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},935513:(f,v,S,I,z)=>{i.sa("ReduceL1",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},935670:(f,v,S,I,z)=>{i.sa("ReduceL2",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},935827:(f,v,S,I,z)=>{i.sa("ReduceLogSum",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},935988:(f,v,S,I,z)=>{i.sa("ReduceSumSquare",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},936152:(f,v,S,I,z)=>{i.sa("ReduceLogSumExp",f,{keepDims:!!v,noopWithEmptyAxes:!!S,axes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},936316:f=>{i.sa("Where",f,void 0)},936369:(f,v,S)=>{i.sa("Transpose",f,{perm:v?Array.from(P.subarray(v>>>0,S>>>0)):[]})},936477:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B,ge)=>{i.sa("ConvTranspose",f,{format:_e?"NHWC":"NCHW",autoPad:v,dilations:[S],group:I,kernel_shape:[z],pads:[V,re],strides:[ue],wIsConst:()=>!!q[be>>>0],outputPadding:Se?Array.from(P.subarray(Se>>>0,Be>>>0)):[],outputShape:Ne?Array.from(P.subarray(Ne>>>0,B>>>0)):[],activation:Qe(ge)})},936879:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B)=>{i.sa("ConvTranspose",f,{format:ue?"NHWC":"NCHW",autoPad:v,dilations:Array.from(P.subarray(S>>>0,(S>>>0)+2>>>0)),group:I,kernelShape:Array.from(P.subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(P.subarray(V>>>0,(V>>>0)+4>>>0)),strides:Array.from(P.subarray(re>>>0,(re>>>0)+2>>>0)),wIsConst:()=>!!q[_e>>>0],outputPadding:be?Array.from(P.subarray(be>>>0,Se>>>0)):[],outputShape:Be?Array.from(P.subarray(Be>>>0,Ne>>>0)):[],activation:Qe(B)})},937444:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B,ge)=>{i.sa("ConvTranspose",f,{format:_e?"NHWC":"NCHW",autoPad:v,dilations:[S],group:I,kernel_shape:[z],pads:[V,re],strides:[ue],wIsConst:()=>!!q[be>>>0],outputPadding:Se?Array.from(P.subarray(Se>>>0,Be>>>0)):[],outputShape:Ne?Array.from(P.subarray(Ne>>>0,B>>>0)):[],activation:Qe(ge)})},937846:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B)=>{i.sa("ConvTranspose",f,{format:ue?"NHWC":"NCHW",autoPad:v,dilations:Array.from(P.subarray(S>>>0,(S>>>0)+2>>>0)),group:I,kernelShape:Array.from(P.subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(P.subarray(V>>>0,(V>>>0)+4>>>0)),strides:Array.from(P.subarray(re>>>0,(re>>>0)+2>>>0)),wIsConst:()=>!!q[_e>>>0],outputPadding:be?Array.from(P.subarray(be>>>0,Se>>>0)):[],outputShape:Be?Array.from(P.subarray(Be>>>0,Ne>>>0)):[],activation:Qe(B)})},938411:(f,v)=>{i.sa("GlobalAveragePool",f,{format:v?"NHWC":"NCHW"})},938502:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B,ge,Ie)=>{i.sa("AveragePool",f,{format:Ie?"NHWC":"NCHW",auto_pad:v,ceil_mode:S,count_include_pad:I,storage_order:z,dilations:[V,re],kernel_shape:[ue,_e],pads:[be,Se,Be,Ne],strides:[B,ge]})},938786:(f,v)=>{i.sa("GlobalAveragePool",f,{format:v?"NHWC":"NCHW"})},938877:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B,ge,Ie)=>{i.sa("AveragePool",f,{format:Ie?"NHWC":"NCHW",auto_pad:v,ceil_mode:S,count_include_pad:I,storage_order:z,dilations:[V,re],kernel_shape:[ue,_e],pads:[be,Se,Be,Ne],strides:[B,ge]})},939161:(f,v)=>{i.sa("GlobalMaxPool",f,{format:v?"NHWC":"NCHW"})},939248:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B,ge,Ie)=>{i.sa("MaxPool",f,{format:Ie?"NHWC":"NCHW",auto_pad:v,ceil_mode:S,count_include_pad:I,storage_order:z,dilations:[V,re],kernel_shape:[ue,_e],pads:[be,Se,Be,Ne],strides:[B,ge]})},939528:(f,v)=>{i.sa("GlobalMaxPool",f,{format:v?"NHWC":"NCHW"})},939615:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B,ge,Ie)=>{i.sa("MaxPool",f,{format:Ie?"NHWC":"NCHW",auto_pad:v,ceil_mode:S,count_include_pad:I,storage_order:z,dilations:[V,re],kernel_shape:[ue,_e],pads:[be,Se,Be,Ne],strides:[B,ge]})},939895:(f,v,S,I,z)=>{i.sa("Gemm",f,{alpha:v,beta:S,transA:I,transB:z})},939999:f=>{i.sa("MatMul",f,void 0)},940053:(f,v,S,I)=>{i.sa("ArgMax",f,{keepDims:!!v,selectLastIndex:!!S,axis:I})},940161:(f,v,S,I)=>{i.sa("ArgMin",f,{keepDims:!!v,selectLastIndex:!!S,axis:I})},940269:(f,v)=>{i.sa("Softmax",f,{axis:v})},940332:(f,v)=>{i.sa("Concat",f,{axis:v})},940392:(f,v,S,I,z)=>{i.sa("Split",f,{axis:v,numOutputs:S,splitSizes:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},940532:f=>{i.sa("Expand",f,void 0)},940586:(f,v)=>{i.sa("Gather",f,{axis:Number(v)})},940657:(f,v)=>{i.sa("GatherElements",f,{axis:Number(v)})},940736:(f,v,S,I,z,V,re,ue,_e,be,Se)=>{i.sa("Resize",f,{antialias:v,axes:S?Array.from(P.subarray(S>>>0,I>>>0)):[],coordinateTransformMode:Qe(z),cubicCoeffA:V,excludeOutside:re,extrapolationValue:ue,keepAspectRatioPolicy:Qe(_e),mode:Qe(be),nearestMode:Qe(Se)})},941082:(f,v,S,I,z,V,re)=>{i.sa("Slice",f,{starts:v?Array.from(P.subarray(v>>>0,S>>>0)):[],ends:I?Array.from(P.subarray(I>>>0,z>>>0)):[],axes:V?Array.from(P.subarray(V>>>0,re>>>0)):[]})},941298:f=>{i.sa("Tile",f,void 0)},941350:(f,v,S)=>{i.sa("LayerNormalization",f,{axis:Number(v),epsilon:Number(S)})},941457:(f,v,S)=>{i.sa("InstanceNormalization",f,{epsilon:v,format:S?"NHWC":"NCHW"})},941571:(f,v,S)=>{i.sa("InstanceNormalization",f,{epsilon:v,format:S?"NHWC":"NCHW"})},941685:f=>{i.sa("Range",f,void 0)},941738:(f,v)=>{i.sa("Einsum",f,{equation:Qe(v)})},941819:(f,v,S,I,z)=>{i.sa("Pad",f,{mode:v,value:S,pads:I?Array.from(P.subarray(I>>>0,z>>>0)):[]})},941946:(f,v,S,I,z,V)=>{i.sa("BatchNormalization",f,{epsilon:v,momentum:S,spatial:!!z,trainingMode:!!I,format:V?"NHWC":"NCHW"})},942115:(f,v,S,I,z,V)=>{i.sa("BatchNormalization",f,{epsilon:v,momentum:S,spatial:!!z,trainingMode:!!I,format:V?"NHWC":"NCHW"})},942284:(f,v,S)=>{i.sa("CumSum",f,{exclusive:Number(v),reverse:Number(S)})},942381:(f,v,S,I,z,V,re,ue,_e)=>{i.sa("Attention",f,{numHeads:v,isUnidirectional:S,maskFilterValue:I,scale:z,doRotary:V,qkvHiddenSizes:re?Array.from(P.subarray(Number(ue)>>>0,Number(ue)+re>>>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,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne)=>{i.sa("Conv",f,{format:_e?"NHWC":"NCHW",auto_pad:v,dilations:[S],group:I,kernel_shape:[z],pads:V?Array.from(P.subarray(V>>>0,re>>>0)):[],strides:[ue],w_is_const:()=>!!q[be>>>0],activation:Qe(Se),activation_params:Be?Array.from(te.subarray(Be>>>0,Ne>>>0)):[]})},943195:(f,v,S,I,z,V,re,ue,_e,be,Se,Be,Ne,B,ge,Ie)=>{i.sa("Conv",f,{format:Be?"NHWC":"NCHW",auto_pad:v,dilations:[S,I],group:z,kernel_shape:[V,re],pads:ue?Array.from(P.subarray(ue>>>0,_e>>>0)):[],strides:[be,Se],w_is_const:()=>!!q[Ne>>>0],activation:Qe(B),activation_params:ge?Array.from(te.subarray(ge>>>0,Ie>>>0)):[]})},943586:f=>{i.sa("Gelu",f,void 0)},943638:(f,v,S,I,z,V)=>{i.sa("MatMulNBits",f,{k:v,n:S,accuracyLevel:I,bits:z,blockSize:V})},943765:(f,v,S,I,z,V)=>{i.sa("MultiHeadAttention",f,{numHeads:v,isUnidirectional:S,maskFilterValue:I,scale:z,doRotary:V})},943924:(f,v)=>{i.sa("SkipLayerNormalization",f,{epsilon:v})},944005:f=>{i.Wa(f)},944039:(f,v)=>i.Ya(f,v,i.Ea.Za,i.Ea.errors)};function xt(f){this.name="ExitStatus",this.message=`Program terminated with exit(${f})`,this.status=f}function Lr(f){this.Ja=f-24,this.Pa=function(v){J[this.Ja+4>>>2>>>0]=v},this.Oa=function(v){J[this.Ja+8>>>2>>>0]=v},this.eb=function(v,S){this.Na(),this.Pa(v),this.Oa(S)},this.Na=function(){J[this.Ja+16>>>2>>>0]=0}}var nr=0,rn=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,gr=(f,v,S)=>{v>>>=0;var I=v+S;for(S=v;f[S]&&!(S>=I);)++S;if(16z?I+=String.fromCharCode(z):(z-=65536,I+=String.fromCharCode(55296|z>>10,56320|z&1023))}}else I+=String.fromCharCode(z)}return I},Qe=(f,v)=>(f>>>=0)?gr(ee,f,v):"",Ur=f=>{for(var v=0,S=0;S=I?v++:2047>=I?v+=2:55296<=I&&57343>=I?(v+=4,++S):v+=3}return v},nn=(f,v,S,I)=>{if(S>>>=0,!(0=re){var ue=f.charCodeAt(++V);re=65536+((re&1023)<<10)|ue&1023}if(127>=re){if(S>=I)break;v[S++>>>0]=re}else{if(2047>=re){if(S+1>=I)break;v[S++>>>0]=192|re>>6}else{if(65535>=re){if(S+2>=I)break;v[S++>>>0]=224|re>>12}else{if(S+3>=I)break;v[S++>>>0]=240|re>>18,v[S++>>>0]=128|re>>12&63}v[S++>>>0]=128|re>>6&63}v[S++>>>0]=128|re&63}}return v[S>>>0]=0,S-z},Xt=f=>f%4===0&&(f%100!==0||f%400===0),da=[0,31,60,91,121,152,182,213,244,274,305,335],Qt=[0,31,59,90,120,151,181,212,243,273,304,334],Fr=f=>{var v=Ur(f)+1,S=qr(v);return S&&nn(f,ee,S,v),S},_r=[],Wr=(f,v)=>{_r.length=0;for(var S;S=ee[f++>>>0];){var I=S!=105;I&=S!=112,v+=I&&v%8?4:0,_r.push(S==112?J[v>>>2>>>0]:S==105?P[v>>>2>>>0]:F[v>>>3>>>0]),v+=I?8:4}return _r},Gr={},Wt=()=>{if(!Vr){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",_:c||"./this.program"},v;for(v in Gr)Gr[v]===void 0?delete f[v]:f[v]=Gr[v];var S=[];for(v in f)S.push(`${v}=${f[v]}`);Vr=S}return Vr},Vr,ca=[null,[],[]],at=[31,29,31,30,31,30,31,31,30,31,30,31],pa=[31,28,31,30,31,30,31,31,30,31,30,31];function Le(f){var v=Array(Ur(f)+1);return nn(f,v,0,v.length),v}function an(f,v,S,I){function z(B,ge,Ie){for(B=typeof B=="number"?B.toString():B||"";B.lengthba?-1:0Vt-B.getDate())ge-=Vt-B.getDate()+1,B.setDate(1),11>Ie?B.setMonth(Ie+1):(B.setMonth(0),B.setFullYear(B.getFullYear()+1));else{B.setDate(B.getDate()+ge);break}}return Ie=new Date(B.getFullYear()+1,0,4),ge=ue(new Date(B.getFullYear(),0,4)),Ie=ue(Ie),0>=re(ge,B)?0>=re(Ie,B)?B.getFullYear()+1:B.getFullYear():B.getFullYear()-1}f>>>=0,v>>>=0,S>>>=0,I>>>=0;var be=J[I+40>>>2>>>0];I={bb:P[I>>>2>>>0],ab:P[I+4>>>2>>>0],Ga:P[I+8>>>2>>>0],Ka:P[I+12>>>2>>>0],Ha:P[I+16>>>2>>>0],Da:P[I+20>>>2>>>0],xa:P[I+24>>>2>>>0],Ca:P[I+28>>>2>>>0],fb:P[I+32>>>2>>>0],$a:P[I+36>>>2>>>0],cb:be?Qe(be):""},S=Qe(S),be={"%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 Se in be)S=S.replace(new RegExp(Se,"g"),be[Se]);var Be="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ne="January February March April May June July August September October November December".split(" ");be={"%a":B=>Be[B.xa].substring(0,3),"%A":B=>Be[B.xa],"%b":B=>Ne[B.Ha].substring(0,3),"%B":B=>Ne[B.Ha],"%C":B=>V((B.Da+1900)/100|0,2),"%d":B=>V(B.Ka,2),"%e":B=>z(B.Ka,2," "),"%g":B=>_e(B).toString().substring(2),"%G":B=>_e(B),"%H":B=>V(B.Ga,2),"%I":B=>(B=B.Ga,B==0?B=12:12{for(var ge=0,Ie=0;Ie<=B.Ha-1;ge+=(Xt(B.Da+1900)?at:pa)[Ie++]);return V(B.Ka+ge,3)},"%m":B=>V(B.Ha+1,2),"%M":B=>V(B.ab,2),"%n":()=>` -`,"%p":B=>0<=B.Ga&&12>B.Ga?"AM":"PM","%S":B=>V(B.bb,2),"%t":()=>" ","%u":B=>B.xa||7,"%U":B=>V(Math.floor((B.Ca+7-B.xa)/7),2),"%V":B=>{var ge=Math.floor((B.Ca+7-(B.xa+6)%7)/7);if(2>=(B.xa+371-B.Ca-2)%7&&ge++,ge)ge==53&&(Ie=(B.xa+371-B.Ca)%7,Ie==4||Ie==3&&Xt(B.Da)||(ge=1));else{ge=52;var Ie=(B.xa+7-B.Ca-1)%7;(Ie==4||Ie==5&&Xt(B.Da%400-1))&&ge++}return V(ge,2)},"%w":B=>B.xa,"%W":B=>V(Math.floor((B.Ca+7-(B.xa+6)%7)/7),2),"%y":B=>(B.Da+1900).toString().substring(2),"%Y":B=>B.Da+1900,"%z":B=>{B=B.$a;var ge=0<=B;return B=Math.abs(B)/60,(ge?"+":"-")+("0000"+(B/60*100+B%60)).slice(-4)},"%Z":B=>B.cb,"%%":()=>"%"},S=S.replace(/%%/g,"\0\0");for(Se in be)S.includes(Se)&&(S=S.replace(new RegExp(Se,"g"),be[Se](I)));return S=S.replace(/\0\0/g,"%"),Se=Le(S),Se.length>v?0:(q.set(Se,f>>>0),Se.length-1)}var ar=f=>{try{f()}catch(v){ne(v)}};function sn(){var f=de,v={};for(let[S,I]of Object.entries(f))v[S]=typeof I=="function"?function(){ce.push(S);try{return I.apply(null,arguments)}finally{W||(ce.pop(),wt&&Gt===1&&ce.length===0&&(Gt=0,ar(gn),typeof Fibers<"u"&&Fibers.gb()))}}:I;return v}var Gt=0,wt=null,ha=0,ce=[],wr={},on={},Ti=0,Hr=null,fa=[];function ma(){return new Promise((f,v)=>{Hr={resolve:f,reject:v}})}function ga(){var f=qr(65548),v=f+12;J[f>>>2>>>0]=v,J[f+4>>>2>>>0]=v+65536,v=ce[0];var S=wr[v];return S===void 0&&(S=Ti++,wr[v]=S,on[S]=v),P[f+8>>>2>>>0]=S,f}function _a(f){if(!W){if(Gt===0){var v=!1,S=!1;f((I=0)=>{if(!W&&(ha=I,v=!0,S)){Gt=2,ar(()=>_n(wt)),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.resume(),I=!1;try{var z=(0,de[on[P[wt+8>>>2>>>0]]])()}catch(ue){z=ue,I=!0}var V=!1;if(!wt){var re=Hr;re&&(Hr=null,(I?re.reject:re.resolve)(z),V=!0)}if(I&&!V)throw z}}),S=!0,v||(Gt=1,wt=ga(),typeof Browser<"u"&&Browser.Ia.Qa&&Browser.Ia.pause(),ar(()=>mn(wt)))}else Gt===2?(Gt=0,ar(wn),dn(wt),wt=null,fa.forEach(I=>{if(!W)try{I();try{K=K=I=K,i.onExit?.(I),W=!0,u(I,new xt(I))}catch(z){z instanceof xt||z=="unwind"||u(1,z)}}catch(z){z instanceof xt||z=="unwind"||u(1,z)}})):ne(`invalid state: ${Gt}`);return ha}}function ln(f){return _a(v=>{f().then(v)})}var wa={n:function(f,v,S){return ln(async()=>{await i.Ua(f,v,S)})},a:function(f,v,S){throw f>>>=0,new Lr(f).eb(v>>>0,S>>>0),nr=f,nr},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,v,S){f=v+2097152>>>0<4194305-!!f?(f>>>0)+4294967296*v:NaN,S>>>=0,f=new Date(1e3*f),P[S>>>2>>>0]=f.getUTCSeconds(),P[S+4>>>2>>>0]=f.getUTCMinutes(),P[S+8>>>2>>>0]=f.getUTCHours(),P[S+12>>>2>>>0]=f.getUTCDate(),P[S+16>>>2>>>0]=f.getUTCMonth(),P[S+20>>>2>>>0]=f.getUTCFullYear()-1900,P[S+24>>>2>>>0]=f.getUTCDay(),P[S+28>>>2>>>0]=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(f,v,S){f=v+2097152>>>0<4194305-!!f?(f>>>0)+4294967296*v:NaN,S>>>=0,f=new Date(1e3*f),P[S>>>2>>>0]=f.getSeconds(),P[S+4>>>2>>>0]=f.getMinutes(),P[S+8>>>2>>>0]=f.getHours(),P[S+12>>>2>>>0]=f.getDate(),P[S+16>>>2>>>0]=f.getMonth(),P[S+20>>>2>>>0]=f.getFullYear()-1900,P[S+24>>>2>>>0]=f.getDay(),P[S+28>>>2>>>0]=(Xt(f.getFullYear())?da:Qt)[f.getMonth()]+f.getDate()-1|0,P[S+36>>>2>>>0]=-(60*f.getTimezoneOffset()),v=new Date(f.getFullYear(),6,1).getTimezoneOffset();var I=new Date(f.getFullYear(),0,1).getTimezoneOffset();P[S+32>>>2>>>0]=(v!=I&&f.getTimezoneOffset()==Math.min(I,v))|0},s:function(f){f>>>=0;var v=new Date(P[f+20>>>2>>>0]+1900,P[f+16>>>2>>>0],P[f+12>>>2>>>0],P[f+8>>>2>>>0],P[f+4>>>2>>>0],P[f>>>2>>>0],0),S=P[f+32>>>2>>>0],I=v.getTimezoneOffset(),z=new Date(v.getFullYear(),6,1).getTimezoneOffset(),V=new Date(v.getFullYear(),0,1).getTimezoneOffset(),re=Math.min(V,z);return 0>S?P[f+32>>>2>>>0]=+(z!=V&&re==I):0>>2>>>0]=v.getDay(),P[f+28>>>2>>>0]=(Xt(v.getFullYear())?da:Qt)[v.getMonth()]+v.getDate()-1|0,P[f>>>2>>>0]=v.getSeconds(),P[f+4>>>2>>>0]=v.getMinutes(),P[f+8>>>2>>>0]=v.getHours(),P[f+12>>>2>>>0]=v.getDate(),P[f+16>>>2>>>0]=v.getMonth(),P[f+20>>>2>>>0]=v.getYear(),f=v.getTime(),isNaN(f)?(P[un()>>>2>>>0]=61,f=-1):f/=1e3,cn((Ke=f,1<=+Math.abs(Ke)?0>>0:~~+Math.ceil((Ke-+(~~Ke>>>0))/4294967296)>>>0:0)),f>>>0},o:function(){return-52},p:function(){},w:function(f,v,S){function I(_e){return(_e=_e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?_e[1]:"GMT"}S>>>=0;var z=new Date().getFullYear(),V=new Date(z,0,1),re=new Date(z,6,1);z=V.getTimezoneOffset();var ue=re.getTimezoneOffset();J[f>>>0>>>2>>>0]=60*Math.max(z,ue),P[v>>>0>>>2>>>0]=+(z!=ue),f=I(V),v=I(re),f=Fr(f),v=Fr(v),ue>>2>>>0]=f,J[S+4>>>2>>>0]=v):(J[S>>>2>>>0]=v,J[S+4>>>2>>>0]=f)},e:()=>{ne("")},b:function(f,v,S){return f>>>=0,v=Wr(v>>>0,S>>>0),lt[f].apply(null,v)},i:function(f,v,S){return f>>>=0,v=Wr(v>>>0,S>>>0),lt[f].apply(null,v)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(f,v,S){return v>>>=0,ee.copyWithin(f>>>0>>>0,v>>>0,v+(S>>>0)>>>0)},u:function(f){f>>>=0;var v=ee.length;if(4294901760=S;S*=2){var I=v*(1+.2/S);I=Math.min(I,f+100663296);var z=Math;I=Math.max(f,I);e:{z=(z.min.call(z,4294901760,I+(65536-I%65536)%65536)-R.buffer.byteLength+65535)/65536;try{R.grow(z),O();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1},E:function(f,v){f>>>=0,v>>>=0;var S=0;return Wt().forEach((I,z)=>{var V=v+S;for(z=J[f+4*z>>>2>>>0]=V,V=0;V>>0>>>0]=I.charCodeAt(V);q[z>>>0>>>0]=0,S+=I.length+1}),0},F:function(f,v){f>>>=0,v>>>=0;var S=Wt();J[f>>>2>>>0]=S.length;var I=0;return S.forEach(z=>I+=z.length+1),J[v>>>2>>>0]=I,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(f,v,S,I){v>>>=0,S>>>=0,I>>>=0;for(var z=0,V=0;V>>2>>>0],ue=J[v+4>>>2>>>0];v+=8;for(var _e=0;_e>>0],Se=ca[f];be===0||be===10?((f===1?T:A)(gr(Se,0)),Se.length=0):Se.push(be)}z+=ue}return J[I>>>2>>>0]=z,0},v:an,d:function(f,v,S,I){return an(f>>>0,v>>>0,S>>>0,I>>>0)}},de=function(){function f(S){return de=S.exports,de=sn(),de=ya(),R=de.M,O(),ie.unshift(de.N),se--,se==0&&L&&(S=L,L=null,S()),de}var v={a:wa};if(se++,i.instantiateWasm)try{return i.instantiateWasm(v,f)}catch(S){A(`Module.instantiateWasm callback failed with error: ${S}`),o(S)}return Ue(v,function(S){f(S.instance)}).catch(o),{}}();i._OrtInit=(f,v)=>(i._OrtInit=de.O)(f,v),i._OrtGetLastError=(f,v)=>(i._OrtGetLastError=de.P)(f,v),i._OrtCreateSessionOptions=(f,v,S,I,z,V,re,ue,_e,be)=>(i._OrtCreateSessionOptions=de.Q)(f,v,S,I,z,V,re,ue,_e,be),i._OrtAppendExecutionProvider=(f,v)=>(i._OrtAppendExecutionProvider=de.R)(f,v),i._OrtAddFreeDimensionOverride=(f,v,S)=>(i._OrtAddFreeDimensionOverride=de.S)(f,v,S),i._OrtAddSessionConfigEntry=(f,v,S)=>(i._OrtAddSessionConfigEntry=de.T)(f,v,S),i._OrtReleaseSessionOptions=f=>(i._OrtReleaseSessionOptions=de.U)(f),i._OrtCreateSession=(f,v,S)=>(i._OrtCreateSession=de.V)(f,v,S),i._OrtReleaseSession=f=>(i._OrtReleaseSession=de.W)(f),i._OrtGetInputOutputCount=(f,v,S)=>(i._OrtGetInputOutputCount=de.X)(f,v,S),i._OrtGetInputName=(f,v)=>(i._OrtGetInputName=de.Y)(f,v),i._OrtGetOutputName=(f,v)=>(i._OrtGetOutputName=de.Z)(f,v),i._OrtFree=f=>(i._OrtFree=de._)(f),i._OrtCreateTensor=(f,v,S,I,z,V)=>(i._OrtCreateTensor=de.$)(f,v,S,I,z,V),i._OrtGetTensorData=(f,v,S,I,z)=>(i._OrtGetTensorData=de.aa)(f,v,S,I,z),i._OrtReleaseTensor=f=>(i._OrtReleaseTensor=de.ba)(f),i._OrtCreateRunOptions=(f,v,S,I)=>(i._OrtCreateRunOptions=de.ca)(f,v,S,I),i._OrtAddRunConfigEntry=(f,v,S)=>(i._OrtAddRunConfigEntry=de.da)(f,v,S),i._OrtReleaseRunOptions=f=>(i._OrtReleaseRunOptions=de.ea)(f),i._OrtCreateBinding=f=>(i._OrtCreateBinding=de.fa)(f),i._OrtBindInput=(f,v,S)=>(i._OrtBindInput=de.ga)(f,v,S),i._OrtBindOutput=(f,v,S,I)=>(i._OrtBindOutput=de.ha)(f,v,S,I),i._OrtClearBoundOutputs=f=>(i._OrtClearBoundOutputs=de.ia)(f),i._OrtReleaseBinding=f=>(i._OrtReleaseBinding=de.ja)(f),i._OrtRunWithBinding=(f,v,S,I,z)=>(i._OrtRunWithBinding=de.ka)(f,v,S,I,z),i._OrtRun=(f,v,S,I,z,V,re,ue)=>(i._OrtRun=de.la)(f,v,S,I,z,V,re,ue),i._OrtEndProfiling=f=>(i._OrtEndProfiling=de.ma)(f),i._JsepOutput=(f,v,S)=>(i._JsepOutput=de.na)(f,v,S),i._JsepGetNodeName=f=>(i._JsepGetNodeName=de.oa)(f);var un=()=>(un=de.pa)(),qr=i._malloc=f=>(qr=i._malloc=de.qa)(f),dn=i._free=f=>(dn=i._free=de.ra)(f),cn=f=>(cn=de.ta)(f),pn=()=>(pn=de.ua)(),hn=f=>(hn=de.va)(f),fn=f=>(fn=de.wa)(f),mn=f=>(mn=de.ya)(f),gn=()=>(gn=de.za)(),_n=f=>(_n=de.Aa)(f),wn=()=>(wn=de.Ba)();i.___start_em_js=944151,i.___stop_em_js=944312;function ya(){var f=de;f=Object.assign({},f);var v=I=>()=>I()>>>0,S=I=>z=>I(z)>>>0;return f.pa=v(f.pa),f.qa=S(f.qa),f.ua=v(f.ua),f.wa=S(f.wa),f}i.stackAlloc=fn,i.stackSave=pn,i.stackRestore=hn,i.UTF8ToString=Qe,i.stringToUTF8=(f,v,S)=>nn(f,ee,v,S),i.lengthBytesUTF8=Ur;var ir;L=function f(){ir||yr(),ir||(L=f)};function yr(){if(!(0r)}),I_=Qr(()=>{}),A_=Qr(()=>{}),Zc={};Zr(Zc,{cpus:()=>Jc});var Jc,M_=X(()=>{Jc=void 0}),O_=Qr((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 G.buffer!=L.buffer&&He(),L}function s(){return G.buffer!=L.buffer&&He(),ne}function o(){return G.buffer!=L.buffer&&He(),me}function l(){return G.buffer!=L.buffer&&He(),Pe}function d(){return G.buffer!=L.buffer&&He(),Re}function c(){return G.buffer!=L.buffer&&He(),nt}var u=a,h,m;u.ready=new Promise((p,w)=>{h=p,m=w}),u.mountExternalData=(p,w)=>{(u.cb||(u.cb=new Map)).set(p,w)},u.unmountExternalData=()=>{delete u.cb};let g=()=>{let p=(x,C,M)=>(...D)=>{let H=Ht,le=C?.();D=x(...D);let Ee=C?.();return le!==Ee&&(x=Ee,M(le),C=M=null),Ht!=H?Rg():D},w=x=>async(...C)=>{try{if(u.bb)throw Error("Session already started");let M=u.bb={Gb:C[0],errors:[]},D=await x(...C);if(u.bb!==M)throw Error("Session mismatch");u.kb?.flush();let H=M.errors;if(0Ee),0u._OrtCreateSession,x=>u._OrtCreateSession=x),u._OrtRun=w(p(u._OrtRun,()=>u._OrtRun,x=>u._OrtRun=x)),u._OrtRunWithBinding=w(p(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,x=>u._OrtRunWithBinding=x)),u._OrtBindInput=p(u._OrtBindInput,()=>u._OrtBindInput,x=>u._OrtBindInput=x),g=void 0};u.jsepInit=(p,w)=>{if(g?.(),p==="webgpu"){[u.kb,u.xb,u.Bb,u.lb,u.Ab,u.Ea,u.Cb,u.Eb,u.yb,u.zb,u.Db]=w;let x=u.kb;u.jsepRegisterBuffer=(C,M,D,H)=>x.registerBuffer(C,M,D,H),u.jsepGetBuffer=C=>x.getBuffer(C),u.jsepCreateDownloader=(C,M,D)=>x.createDownloader(C,M,D),u.jsepOnReleaseSession=C=>{x.onReleaseSession(C)},u.jsepOnRunStart=C=>x.onRunStart(C)}};var _=Object.assign({},u),b="./this.program",$=(p,w)=>{throw w},y=typeof window=="object",E=typeof importScripts=="function",k=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",T=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function R(p){return u.locateFile?u.locateFile(p,A):A+p}var W,K,q;if(k){var ee=(Yc(),Mr(Ks)),P=(Qc(),Mr(Ys));A=E?P.dirname(A)+"/":__dirname+"/",W=(w,x)=>(w=gr(w)?new URL(w):P.normalize(w),ee.readFileSync(w,x?void 0:"utf8")),q=w=>(w=W(w,!0),w.buffer||(w=new Uint8Array(w)),w),K=(w,x,C,M=!0)=>{w=gr(w)?new URL(w):P.normalize(w),ee.readFile(w,M?void 0:"utf8",(D,H)=>{D?C(D):x(M?H.buffer:H)})},!u.thisProgram&&1{throw process.exitCode=w,x},u.inspect=()=>"[Emscripten Module object]";let p;try{p=I_()}catch(w){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),w}global.Worker=p.Worker}else(y||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="",k||(W=p=>{var w=new XMLHttpRequest;return w.open("GET",p,!1),w.send(null),w.responseText},E&&(q=p=>{var w=new XMLHttpRequest;return w.open("GET",p,!1),w.responseType="arraybuffer",w.send(null),new Uint8Array(w.response)}),K=(p,w,x)=>{var C=new XMLHttpRequest;C.open("GET",p,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?w(C.response):x()},C.onerror=x,C.send(null)}));k&&typeof performance>"u"&&(global.performance=A_().performance);var J=console.log.bind(console),te=console.error.bind(console);k&&(J=(...p)=>ee.writeSync(1,p.join(" ")+` -`),te=(...p)=>ee.writeSync(2,p.join(" ")+` -`));var F=J,O=te;Object.assign(u,_),_=null,typeof WebAssembly!="object"&&nr("no native wasm support detected");var G,ie,j=!1,se,L,ne,me,Pe,Re,nt;function He(){var p=G.buffer;u.HEAP8=L=new Int8Array(p),u.HEAP16=new Int16Array(p),u.HEAPU8=ne=new Uint8Array(p),u.HEAPU16=new Uint16Array(p),u.HEAP32=me=new Int32Array(p),u.HEAPU32=Pe=new Uint32Array(p),u.HEAPF32=Re=new Float32Array(p),u.HEAPF64=nt=new Float64Array(p)}var ot=16777216;if(T)G=u.wasmMemory;else if(u.wasmMemory)G=u.wasmMemory;else if(G=new WebAssembly.Memory({initial:ot/65536,maximum:65536,shared:!0}),!(G.buffer instanceof SharedArrayBuffer))throw O("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"),k&&O("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");He(),ot=G.buffer.byteLength;var pt=[],Ue=[],Ke=[],lt=0,xt=null;function Lr(){if(lt--,lt==0&&xt){var p=xt;xt=null,p()}}function nr(p){throw p="Aborted("+p+")",O(p),j=!0,se=1,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),m(p),p}var rn=p=>p.startsWith("data:application/octet-stream;base64,"),gr=p=>p.startsWith("file://"),Qe;Qe="ort-wasm-simd-threaded.wasm",rn(Qe)||(Qe=R(Qe));function Ur(p){if(q)return q(p);throw"both async and sync fetching of the wasm failed"}function nn(p){if(y||E){if(typeof fetch=="function"&&!gr(p))return fetch(p,{credentials:"same-origin"}).then(w=>{if(!w.ok)throw"failed to load wasm binary file at '"+p+"'";return w.arrayBuffer()}).catch(()=>Ur(p));if(K)return new Promise((w,x)=>{K(p,C=>w(new Uint8Array(C)),x)})}return Promise.resolve().then(()=>Ur(p))}function Xt(p,w,x){return nn(p).then(C=>WebAssembly.instantiate(C,w)).then(C=>C).then(x,C=>{O(`failed to asynchronously prepare wasm: ${C}`),nr(C)})}function da(p,w){var x=Qe;return typeof WebAssembly.instantiateStreaming!="function"||rn(x)||gr(x)||k||typeof fetch!="function"?Xt(x,p,w):fetch(x,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,p).then(w,function(M){return O(`wasm streaming compile failed: ${M}`),O("falling back to ArrayBuffer instantiation"),Xt(x,p,w)}))}var Qt,Fr={933148:(p,w,x,C)=>{if(typeof u>"u"||!u.cb)return 1;if(p=at(p>>>0),p.startsWith("./")&&(p=p.substring(2)),p=u.cb.get(p),!p)return 2;if(w>>>=0,x>>>=0,C>>>=0,w+x>p.byteLength)return 3;try{return s().set(p.subarray(w,w+x),C>>>0),0}catch{return 4}},933649:()=>{u.yb()},933680:()=>{u.zb()},933709:()=>{u.Db()},933734:p=>u.xb(p),933767:p=>u.Bb(p),933799:(p,w,x)=>{u.lb(p,w,x,!0)},933838:(p,w,x)=>{u.lb(p,w,x)},933871:p=>{u.Ea("Abs",p,void 0)},933922:p=>{u.Ea("Neg",p,void 0)},933973:p=>{u.Ea("Floor",p,void 0)},934026:p=>{u.Ea("Ceil",p,void 0)},934078:p=>{u.Ea("Reciprocal",p,void 0)},934136:p=>{u.Ea("Sqrt",p,void 0)},934188:p=>{u.Ea("Exp",p,void 0)},934239:p=>{u.Ea("Erf",p,void 0)},934290:p=>{u.Ea("Sigmoid",p,void 0)},934345:(p,w,x)=>{u.Ea("HardSigmoid",p,{alpha:w,beta:x})},934424:p=>{u.Ea("Log",p,void 0)},934475:p=>{u.Ea("Sin",p,void 0)},934526:p=>{u.Ea("Cos",p,void 0)},934577:p=>{u.Ea("Tan",p,void 0)},934628:p=>{u.Ea("Asin",p,void 0)},934680:p=>{u.Ea("Acos",p,void 0)},934732:p=>{u.Ea("Atan",p,void 0)},934784:p=>{u.Ea("Sinh",p,void 0)},934836:p=>{u.Ea("Cosh",p,void 0)},934888:p=>{u.Ea("Asinh",p,void 0)},934941:p=>{u.Ea("Acosh",p,void 0)},934994:p=>{u.Ea("Atanh",p,void 0)},935047:p=>{u.Ea("Tanh",p,void 0)},935099:p=>{u.Ea("Not",p,void 0)},935150:(p,w,x)=>{u.Ea("Clip",p,{min:w,max:x})},935219:p=>{u.Ea("Clip",p,void 0)},935271:(p,w)=>{u.Ea("Elu",p,{alpha:w})},935329:p=>{u.Ea("Relu",p,void 0)},935381:(p,w)=>{u.Ea("LeakyRelu",p,{alpha:w})},935445:(p,w)=>{u.Ea("ThresholdedRelu",p,{alpha:w})},935515:(p,w)=>{u.Ea("Cast",p,{to:w})},935573:p=>{u.Ea("Add",p,void 0)},935624:p=>{u.Ea("Sub",p,void 0)},935675:p=>{u.Ea("Mul",p,void 0)},935726:p=>{u.Ea("Div",p,void 0)},935777:p=>{u.Ea("Pow",p,void 0)},935828:p=>{u.Ea("Equal",p,void 0)},935881:p=>{u.Ea("Greater",p,void 0)},935936:p=>{u.Ea("GreaterOrEqual",p,void 0)},935998:p=>{u.Ea("Less",p,void 0)},936050:p=>{u.Ea("LessOrEqual",p,void 0)},936109:(p,w,x,C,M)=>{u.Ea("ReduceMean",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936268:(p,w,x,C,M)=>{u.Ea("ReduceMax",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936426:(p,w,x,C,M)=>{u.Ea("ReduceMin",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936584:(p,w,x,C,M)=>{u.Ea("ReduceProd",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936743:(p,w,x,C,M)=>{u.Ea("ReduceSum",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},936901:(p,w,x,C,M)=>{u.Ea("ReduceL1",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937058:(p,w,x,C,M)=>{u.Ea("ReduceL2",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937215:(p,w,x,C,M)=>{u.Ea("ReduceLogSum",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937376:(p,w,x,C,M)=>{u.Ea("ReduceSumSquare",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937540:(p,w,x,C,M)=>{u.Ea("ReduceLogSumExp",p,{keepDims:!!w,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},937704:p=>{u.Ea("Where",p,void 0)},937757:(p,w,x)=>{u.Ea("Transpose",p,{perm:w?Array.from(o().subarray(w>>>0,x>>>0)):[]})},937865:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N,$e)=>{u.Ea("ConvTranspose",p,{format:Ee?"NHWC":"NCHW",autoPad:w,dilations:[x],group:C,kernel_shape:[M],pads:[D,H],strides:[le],wIsConst:()=>!!i()[ve>>>0],outputPadding:ke?Array.from(o().subarray(ke>>>0,Fe>>>0)):[],outputShape:Ve?Array.from(o().subarray(Ve>>>0,N>>>0)):[],activation:at($e)})},938267:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N)=>{u.Ea("ConvTranspose",p,{format:le?"NHWC":"NCHW",autoPad:w,dilations:Array.from(o().subarray(x>>>0,(x>>>0)+2>>>0)),group:C,kernelShape:Array.from(o().subarray(M>>>0,(M>>>0)+2>>>0)),pads:Array.from(o().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(o().subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!i()[Ee>>>0],outputPadding:ve?Array.from(o().subarray(ve>>>0,ke>>>0)):[],outputShape:Fe?Array.from(o().subarray(Fe>>>0,Ve>>>0)):[],activation:at(N)})},938832:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N,$e)=>{u.Ea("ConvTranspose",p,{format:Ee?"NHWC":"NCHW",autoPad:w,dilations:[x],group:C,kernel_shape:[M],pads:[D,H],strides:[le],wIsConst:()=>!!i()[ve>>>0],outputPadding:ke?Array.from(o().subarray(ke>>>0,Fe>>>0)):[],outputShape:Ve?Array.from(o().subarray(Ve>>>0,N>>>0)):[],activation:at($e)})},939234:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N)=>{u.Ea("ConvTranspose",p,{format:le?"NHWC":"NCHW",autoPad:w,dilations:Array.from(o().subarray(x>>>0,(x>>>0)+2>>>0)),group:C,kernelShape:Array.from(o().subarray(M>>>0,(M>>>0)+2>>>0)),pads:Array.from(o().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(o().subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!i()[Ee>>>0],outputPadding:ve?Array.from(o().subarray(ve>>>0,ke>>>0)):[],outputShape:Fe?Array.from(o().subarray(Fe>>>0,Ve>>>0)):[],activation:at(N)})},939799:(p,w)=>{u.Ea("GlobalAveragePool",p,{format:w?"NHWC":"NCHW"})},939890:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N,$e,ze)=>{u.Ea("AveragePool",p,{format:ze?"NHWC":"NCHW",auto_pad:w,ceil_mode:x,count_include_pad:C,storage_order:M,dilations:[D,H],kernel_shape:[le,Ee],pads:[ve,ke,Fe,Ve],strides:[N,$e]})},940174:(p,w)=>{u.Ea("GlobalAveragePool",p,{format:w?"NHWC":"NCHW"})},940265:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N,$e,ze)=>{u.Ea("AveragePool",p,{format:ze?"NHWC":"NCHW",auto_pad:w,ceil_mode:x,count_include_pad:C,storage_order:M,dilations:[D,H],kernel_shape:[le,Ee],pads:[ve,ke,Fe,Ve],strides:[N,$e]})},940549:(p,w)=>{u.Ea("GlobalMaxPool",p,{format:w?"NHWC":"NCHW"})},940636:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N,$e,ze)=>{u.Ea("MaxPool",p,{format:ze?"NHWC":"NCHW",auto_pad:w,ceil_mode:x,count_include_pad:C,storage_order:M,dilations:[D,H],kernel_shape:[le,Ee],pads:[ve,ke,Fe,Ve],strides:[N,$e]})},940916:(p,w)=>{u.Ea("GlobalMaxPool",p,{format:w?"NHWC":"NCHW"})},941003:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N,$e,ze)=>{u.Ea("MaxPool",p,{format:ze?"NHWC":"NCHW",auto_pad:w,ceil_mode:x,count_include_pad:C,storage_order:M,dilations:[D,H],kernel_shape:[le,Ee],pads:[ve,ke,Fe,Ve],strides:[N,$e]})},941283:(p,w,x,C,M)=>{u.Ea("Gemm",p,{alpha:w,beta:x,transA:C,transB:M})},941387:p=>{u.Ea("MatMul",p,void 0)},941441:(p,w,x,C)=>{u.Ea("ArgMax",p,{keepDims:!!w,selectLastIndex:!!x,axis:C})},941549:(p,w,x,C)=>{u.Ea("ArgMin",p,{keepDims:!!w,selectLastIndex:!!x,axis:C})},941657:(p,w)=>{u.Ea("Softmax",p,{axis:w})},941720:(p,w)=>{u.Ea("Concat",p,{axis:w})},941780:(p,w,x,C,M)=>{u.Ea("Split",p,{axis:w,numOutputs:x,splitSizes:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},941920:p=>{u.Ea("Expand",p,void 0)},941974:(p,w)=>{u.Ea("Gather",p,{axis:Number(w)})},942045:(p,w)=>{u.Ea("GatherElements",p,{axis:Number(w)})},942124:(p,w,x,C,M,D,H,le,Ee,ve,ke)=>{u.Ea("Resize",p,{antialias:w,axes:x?Array.from(o().subarray(x>>>0,C>>>0)):[],coordinateTransformMode:at(M),cubicCoeffA:D,excludeOutside:H,extrapolationValue:le,keepAspectRatioPolicy:at(Ee),mode:at(ve),nearestMode:at(ke)})},942470:(p,w,x,C,M,D,H)=>{u.Ea("Slice",p,{starts:w?Array.from(o().subarray(w>>>0,x>>>0)):[],ends:C?Array.from(o().subarray(C>>>0,M>>>0)):[],axes:D?Array.from(o().subarray(D>>>0,H>>>0)):[]})},942686:p=>{u.Ea("Tile",p,void 0)},942738:(p,w,x)=>{u.Ea("LayerNormalization",p,{axis:Number(w),epsilon:Number(x)})},942845:(p,w,x)=>{u.Ea("InstanceNormalization",p,{epsilon:w,format:x?"NHWC":"NCHW"})},942959:(p,w,x)=>{u.Ea("InstanceNormalization",p,{epsilon:w,format:x?"NHWC":"NCHW"})},943073:p=>{u.Ea("Range",p,void 0)},943126:(p,w)=>{u.Ea("Einsum",p,{equation:at(w)})},943207:(p,w,x,C,M)=>{u.Ea("Pad",p,{mode:w,value:x,pads:C?Array.from(o().subarray(C>>>0,M>>>0)):[]})},943334:(p,w,x,C,M,D)=>{u.Ea("BatchNormalization",p,{epsilon:w,momentum:x,spatial:!!M,trainingMode:!!C,format:D?"NHWC":"NCHW"})},943503:(p,w,x,C,M,D)=>{u.Ea("BatchNormalization",p,{epsilon:w,momentum:x,spatial:!!M,trainingMode:!!C,format:D?"NHWC":"NCHW"})},943672:(p,w,x)=>{u.Ea("CumSum",p,{exclusive:Number(w),reverse:Number(x)})},943769:(p,w,x,C,M,D,H,le,Ee)=>{u.Ea("Attention",p,{numHeads:w,isUnidirectional:x,maskFilterValue:C,scale:M,doRotary:D,qkvHiddenSizes:H?Array.from(o().subarray(Number(le)>>>0,Number(le)+H>>>0)):[],pastPresentShareBuffer:!!Ee})},944041:p=>{u.Ea("BiasAdd",p,void 0)},944096:p=>{u.Ea("BiasSplitGelu",p,void 0)},944157:p=>{u.Ea("FastGelu",p,void 0)},944213:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve)=>{u.Ea("Conv",p,{format:Ee?"NHWC":"NCHW",auto_pad:w,dilations:[x],group:C,kernel_shape:[M],pads:D?Array.from(o().subarray(D>>>0,H>>>0)):[],strides:[le],w_is_const:()=>!!i()[ve>>>0],activation:at(ke),activation_params:Fe?Array.from(d().subarray(Fe>>>0,Ve>>>0)):[]})},944583:(p,w,x,C,M,D,H,le,Ee,ve,ke,Fe,Ve,N,$e,ze)=>{u.Ea("Conv",p,{format:Fe?"NHWC":"NCHW",auto_pad:w,dilations:[x,C],group:M,kernel_shape:[D,H],pads:le?Array.from(o().subarray(le>>>0,Ee>>>0)):[],strides:[ve,ke],w_is_const:()=>!!i()[Ve>>>0],activation:at(N),activation_params:$e?Array.from(d().subarray($e>>>0,ze>>>0)):[]})},944974:p=>{u.Ea("Gelu",p,void 0)},945026:(p,w,x,C,M,D)=>{u.Ea("MatMulNBits",p,{k:w,n:x,accuracyLevel:C,bits:M,blockSize:D})},945153:(p,w,x,C,M,D)=>{u.Ea("MultiHeadAttention",p,{numHeads:w,isUnidirectional:x,maskFilterValue:C,scale:M,doRotary:D})},945312:(p,w)=>{u.Ea("SkipLayerNormalization",p,{epsilon:w})},945393:p=>{u.Cb(p)},945427:(p,w)=>u.Eb(p,w,u.bb.Gb,u.bb.errors)};function _r(p){this.name="ExitStatus",this.message=`Program terminated with exit(${p})`,this.status=p}var Wr=p=>{p.terminate(),p.onmessage=()=>{}},Gr=p=>{ce.Ya.length==0&&(wt(),ce.mb(ce.Ya[0]));var w=ce.Ya.pop();if(!w)return 6;ce.Za.push(w),ce.Qa[p.Xa]=w,w.Xa=p.Xa;var x={cmd:"run",start_routine:p.Hb,arg:p.ub,pthread_ptr:p.Xa};return k&&w.unref(),w.postMessage(x,p.Nb),0},Wt=0,Vr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ca=(p,w,x)=>{w>>>=0;var C=w+x;for(x=w;p[x]&&!(x>=C);)++x;if(16M?C+=String.fromCharCode(M):(M-=65536,C+=String.fromCharCode(55296|M>>10,56320|M&1023))}}else C+=String.fromCharCode(M)}return C},at=(p,w)=>(p>>>=0)?ca(s(),p,w):"",pa=p=>{var w=zi();return p=p(),Sa(w),p};function Le(p,w){var x=arguments.length-2,C=arguments;return pa(()=>{for(var M=Pi(8*x),D=M>>>3,H=0;H>>0]=le}return Bo(p,x,M,w)})}function an(p){if(T)return Le(0,1,p);se=p,0{if(se=p,T)throw on(p),"unwind";an(p)},sn=p=>{p instanceof _r||p=="unwind"||$(1,p)};function Gt(){for(var p=u.numThreads;p--;)wt();pt.unshift(()=>{lt++,ha(()=>Lr())})}function wt(){var p=R("ort-wasm-simd-threaded.worker.js");p=new Worker(p),ce.Ya.push(p)}function ha(p){T?p():Promise.all(ce.Ya.map(ce.mb)).then(p)}var ce={Ya:[],Za:[],qb:[],Qa:{},hb(){T?(ce.receiveObjectTransfer=ce.Fb,ce.threadInitTLS=ce.pb,ce.setExitStatus=ce.ob):Gt()},ob:p=>se=p,Qb:["$terminateWorker"],Ib:()=>{for(var p of ce.Za)Wr(p);for(p of ce.Ya)Wr(p);ce.Ya=[],ce.Za=[],ce.Qa=[]},nb:p=>{var w=p.Xa;delete ce.Qa[w],ce.Ya.push(p),ce.Za.splice(ce.Za.indexOf(p),1),p.Xa=0,Mi(w)},Fb(){},pb(){ce.qb.forEach(p=>p())},mb:p=>new Promise(w=>{p.onmessage=D=>{D=D.data;var H=D.cmd;if(D.targetThread&&D.targetThread!=xa()){var le=ce.Qa[D.targetThread];le?le.postMessage(D,D.transferList):O(`Internal error! Worker sent a message "${H}" to target pthread ${D.targetThread}, but that thread no longer exists!`)}else H==="checkMailbox"?yr():H==="spawnThread"?Gr(D):H==="cleanupThread"?ce.nb(ce.Qa[D.thread]):H==="killThread"?(D=D.thread,H=ce.Qa[D],delete ce.Qa[D],Wr(H),Mi(D),ce.Za.splice(ce.Za.indexOf(H),1),H.Xa=0):H==="cancelThread"?ce.Qa[D.thread].postMessage({cmd:"cancel"}):H==="loaded"?(p.loaded=!0,k&&!p.Xa&&p.unref(),w(p)):H==="alert"?alert(`Thread ${D.threadId}: ${D.text}`):D.target==="setimmediate"?p.postMessage(D):H==="callHandler"?u[D.handler](...D.args):H&&O(`worker sent an unknown command ${H}`)},p.onerror=D=>{throw O(`worker sent an error! ${D.filename}:${D.lineno}: ${D.message}`),D},k&&(p.on("message",D=>p.onmessage({data:D})),p.on("error",D=>p.onerror(D)));var x=[],C=["onExit"],M;for(M of C)u.hasOwnProperty(M)&&x.push(M);p.postMessage({cmd:"load",handlers:x,urlOrBlob:u.mainScriptUrlOrBlob||n,wasmMemory:G,wasmModule:ie})})};u.PThread=ce;var wr=p=>{for(;0{var p=xa(),w=l()[p+52>>>2>>>0];p=l()[p+56>>>2>>>0],Lo(w,w-p),Sa(w)};function on(p){if(T)return Le(1,0,p);ar(p)}u.invokeEntryPoint=(p,w)=>{p=Uo.apply(null,[p,w]),0>>2>>>0]=w},this.sb=function(w){l()[this.gb+8>>>2>>>0]=w},this.hb=function(w,x){this.rb(),this.tb(w),this.sb(x)},this.rb=function(){l()[this.gb+16>>>2>>>0]=0}}var Hr=0;function fa(p,w,x,C){return T?Le(2,1,p,w,x,C):ma(p,w,x,C)}function ma(p,w,x,C){if(p>>>=0,w>>>=0,x>>>=0,C>>>=0,typeof SharedArrayBuffer>"u")return O("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var M=[];return T&&M.length===0?fa(p,w,x,C):(p={Hb:x,Xa:p,ub:C,Nb:M},T?(p.Pb="spawnThread",postMessage(p,M),0):Gr(p))}function ga(p,w,x){return T?Le(3,1,p,w,x):0}function _a(p,w){if(T)return Le(4,1,p,w)}var ln=p=>{for(var w=0,x=0;x=C?w++:2047>=C?w+=2:55296<=C&&57343>=C?(w+=4,++x):w+=3}return w},wa=(p,w,x,C)=>{if(x>>>=0,!(0=H){var le=p.charCodeAt(++D);H=65536+((H&1023)<<10)|le&1023}if(127>=H){if(x>=C)break;w[x++>>>0]=H}else{if(2047>=H){if(x+1>=C)break;w[x++>>>0]=192|H>>6}else{if(65535>=H){if(x+2>=C)break;w[x++>>>0]=224|H>>12}else{if(x+3>=C)break;w[x++>>>0]=240|H>>18,w[x++>>>0]=128|H>>12&63}w[x++>>>0]=128|H>>6&63}w[x++>>>0]=128|H&63}}return w[x>>>0]=0,x-M},de=(p,w,x)=>wa(p,s(),w,x);function un(p,w){if(T)return Le(5,1,p,w)}function qr(p,w,x){if(T)return Le(6,1,p,w,x)}function dn(p,w,x){return T?Le(7,1,p,w,x):0}function cn(p,w){if(T)return Le(8,1,p,w)}function pn(p,w,x){if(T)return Le(9,1,p,w,x)}function hn(p,w,x,C){if(T)return Le(10,1,p,w,x,C)}function fn(p,w,x,C){if(T)return Le(11,1,p,w,x,C)}function mn(p,w,x,C){if(T)return Le(12,1,p,w,x,C)}function gn(p){if(T)return Le(13,1,p)}function _n(p,w){if(T)return Le(14,1,p,w)}function wn(p,w,x){if(T)return Le(15,1,p,w,x)}var ya=()=>{if(!(0>>=0,typeof Atomics.Ob=="function"&&(Atomics.Ob(o(),p>>>2,p).value.then(yr),p+=128,Atomics.store(o(),p>>>2,1))}u.__emscripten_thread_mailbox_await=ir;var yr=()=>{var p=xa();if(p&&(ir(p),!j))try{Do(),ya()}catch(w){sn(w)}};u.checkMailbox=yr;var f=[],v=p=>p%4===0&&(p%100!==0||p%400===0),S=[0,31,60,91,121,152,182,213,244,274,305,335],I=[0,31,59,90,120,151,181,212,243,273,304,334];function z(p,w,x,C,M,D,H,le){return T?Le(16,1,p,w,x,C,M,D,H,le):-52}function V(p,w,x,C,M,D,H){if(T)return Le(17,1,p,w,x,C,M,D,H)}var re=p=>{var w=ln(p)+1,x=Ai(w);return x&&de(p,x,w),x},ue=[],_e=(p,w)=>{ue.length=0;for(var x;x=s()[p++>>>0];){var C=x!=105;C&=x!=112,w+=C&&w%8?4:0,ue.push(x==112?l()[w>>>2>>>0]:x==105?o()[w>>>2>>>0]:c()[w>>>3>>>0]),w+=C?8:4}return ue},be={},Se=()=>{if(!Be){var p={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",_:b||"./this.program"},w;for(w in be)be[w]===void 0?delete p[w]:p[w]=be[w];var x=[];for(w in p)x.push(`${w}=${p[w]}`);Be=x}return Be},Be;function Ne(p,w){if(T)return Le(18,1,p,w);p>>>=0,w>>>=0;var x=0;return Se().forEach((C,M)=>{var D=w+x;for(M=l()[p+4*M>>>2>>>0]=D,D=0;D>>0>>>0]=C.charCodeAt(D);i()[M>>>0>>>0]=0,x+=C.length+1}),0}function B(p,w){if(T)return Le(19,1,p,w);p>>>=0,w>>>=0;var x=Se();l()[p>>>2>>>0]=x.length;var C=0;return x.forEach(M=>C+=M.length+1),l()[w>>>2>>>0]=C,0}function ge(p){return T?Le(20,1,p):52}function Ie(p,w,x,C){return T?Le(21,1,p,w,x,C):52}function Vt(p,w,x,C,M){return T?Le(22,1,p,w,x,C,M):70}var ba=[null,[],[]];function ko(p,w,x,C){if(T)return Le(23,1,p,w,x,C);w>>>=0,x>>>=0,C>>>=0;for(var M=0,D=0;D>>2>>>0],le=l()[w+4>>>2>>>0];w+=8;for(var Ee=0;Ee>>0],ke=ba[p];ve===0||ve===10?((p===1?F:O)(ca(ke,0)),ke.length=0):ke.push(ve)}M+=le}return l()[C>>>2>>>0]=M,0}var Co=[31,29,31,30,31,30,31,31,30,31,30,31],To=[31,28,31,30,31,30,31,31,30,31,30,31];function Ag(p){var w=Array(ln(p)+1);return wa(p,w,0,w.length),w}var Mg=(p,w)=>{i().set(p,w>>>0)};function Io(p,w,x,C){function M(N,$e,ze){for(N=typeof N=="number"?N.toString():N||"";N.length<$e;)N=ze[0]+N;return N}function D(N,$e){return M(N,$e,"0")}function H(N,$e){function ze(qo){return 0>qo?-1:0br-N.getDate())$e-=br-N.getDate()+1,N.setDate(1),11>ze?N.setMonth(ze+1):(N.setMonth(0),N.setFullYear(N.getFullYear()+1));else{N.setDate(N.getDate()+$e);break}}return ze=new Date(N.getFullYear()+1,0,4),$e=le(new Date(N.getFullYear(),0,4)),ze=le(ze),0>=H($e,N)?0>=H(ze,N)?N.getFullYear()+1:N.getFullYear():N.getFullYear()-1}p>>>=0,w>>>=0,x>>>=0,C>>>=0;var ve=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:ve?at(ve):""},x=at(x),ve={"%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 ke in ve)x=x.replace(new RegExp(ke,"g"),ve[ke]);var Fe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ve="January February March April May June July August September October November December".split(" ");ve={"%a":N=>Fe[N.Wa].substring(0,3),"%A":N=>Fe[N.Wa],"%b":N=>Ve[N.fb].substring(0,3),"%B":N=>Ve[N.fb],"%C":N=>D((N.ab+1900)/100|0,2),"%d":N=>D(N.jb,2),"%e":N=>M(N.jb,2," "),"%g":N=>Ee(N).toString().substring(2),"%G":N=>Ee(N),"%H":N=>D(N.eb,2),"%I":N=>(N=N.eb,N==0?N=12:12{for(var $e=0,ze=0;ze<=N.fb-1;$e+=(v(N.ab+1900)?Co:To)[ze++]);return D(N.jb+$e,3)},"%m":N=>D(N.fb+1,2),"%M":N=>D(N.Kb,2),"%n":()=>` -`,"%p":N=>0<=N.eb&&12>N.eb?"AM":"PM","%S":N=>D(N.Lb,2),"%t":()=>" ","%u":N=>N.Wa||7,"%U":N=>D(Math.floor((N.$a+7-N.Wa)/7),2),"%V":N=>{var $e=Math.floor((N.$a+7-(N.Wa+6)%7)/7);if(2>=(N.Wa+371-N.$a-2)%7&&$e++,$e)$e==53&&(ze=(N.Wa+371-N.$a)%7,ze==4||ze==3&&v(N.ab)||($e=1));else{$e=52;var ze=(N.Wa+7-N.$a-1)%7;(ze==4||ze==5&&v(N.ab%400-1))&&$e++}return D($e,2)},"%w":N=>N.Wa,"%W":N=>D(Math.floor((N.$a+7-(N.Wa+6)%7)/7),2),"%y":N=>(N.ab+1900).toString().substring(2),"%Y":N=>N.ab+1900,"%z":N=>{N=N.Jb;var $e=0<=N;return N=Math.abs(N)/60,($e?"+":"-")+("0000"+(N/60*100+N%60)).slice(-4)},"%Z":N=>N.Mb,"%%":()=>"%"},x=x.replace(/%%/g,"\0\0");for(ke in ve)x.includes(ke)&&(x=x.replace(new RegExp(ke,"g"),ve[ke](C)));return x=x.replace(/\0\0/g,"%"),ke=Ag(x),ke.length>w?0:(Mg(ke,p),ke.length-1)}var va=p=>{try{p()}catch(w){nr(w)}};function Og(){var p=oe,w={};for(let[x,C]of Object.entries(p))w[x]=typeof C=="function"?function(){$a.push(x);try{return C.apply(null,arguments)}finally{j||($a.pop(),Ht&&sr===1&&$a.length===0&&(sr=0,Wt+=1,va(Wo),typeof Fibers<"u"&&Fibers.Sb()))}}:C;return w}var sr=0,Ht=null,Ao=0,$a=[],Mo={},Oo={},zg=0,Ii=null,Pg=[];function Rg(){return new Promise((p,w)=>{Ii={resolve:p,reject:w}})}function Bg(){var p=Ai(65548),w=p+12;l()[p>>>2>>>0]=w,l()[p+4>>>2>>>0]=w+65536,w=$a[0];var x=Mo[w];return x===void 0&&(x=zg++,Mo[w]=x,Oo[x]=w),w=x,o()[p+8>>>2>>>0]=w,p}function Dg(){var p=o()[Ht+8>>>2>>>0];return p=oe[Oo[p]],--Wt,p()}function Ng(p){if(!j){if(sr===0){var w=!1,x=!1;p((C=0)=>{if(!j&&(Ao=C,w=!0,x)){sr=2,va(()=>Go(Ht)),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.resume(),C=!1;try{var M=Dg()}catch(le){M=le,C=!0}var D=!1;if(!Ht){var H=Ii;H&&(Ii=null,(C?H.reject:H.resolve)(M),D=!0)}if(C&&!D)throw M}}),x=!0,w||(sr=1,Ht=Bg(),typeof Browser<"u"&&Browser.ib.wb&&Browser.ib.pause(),va(()=>Fo(Ht)))}else sr===2?(sr=0,va(Vo),Po(Ht),Ht=null,Pg.forEach(C=>{if(!j)try{C(),ya()}catch(M){sn(M)}})):nr(`invalid state: ${sr}`);return Ao}}function Lg(p){return Ng(w=>{p().then(w)})}ce.hb();var Ug=[an,on,fa,ga,_a,un,qr,dn,cn,pn,hn,fn,mn,gn,_n,wn,z,V,Ne,B,ge,Ie,Vt,ko],Fg={r:function(p,w,x){return Lg(async()=>{await u.Ab(p,w,x)})},b:function(p,w,x){throw p>>>=0,new Ti(p).hb(w>>>0,x>>>0),Hr=p,Hr},N:function(p){Ro(p>>>0,!E,1,!y,131072,!1),ce.pb()},l:function(p){p>>>=0,T?postMessage({cmd:"cleanupThread",thread:p}):ce.nb(ce.Qa[p])},J:ma,i:ga,T:_a,F:un,H:qr,U:dn,R:cn,L:pn,Q:hn,p:fn,G:mn,D:gn,S:_n,E:wn,q:()=>1,B:function(p,w){p>>>=0,p==w>>>0?setTimeout(()=>yr()):T?postMessage({targetThread:p,cmd:"checkMailbox"}):(p=ce.Qa[p])&&p.postMessage({cmd:"checkMailbox"})},K:function(p,w,x,C){w>>>=0,f.length=x,C=C>>>0>>>3;for(var M=0;M>>0];return p=0>p?Fr[-p-1]:Ug[p],ce.vb=w,w=p.apply(null,f),ce.vb=0,w},M:ir,W:function(p){k&&ce.Qa[p>>>0].ref()},u:function(p,w,x){p=w+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*w:NaN,x>>>=0,p=new Date(1e3*p),o()[x>>>2>>>0]=p.getUTCSeconds(),o()[x+4>>>2>>>0]=p.getUTCMinutes(),o()[x+8>>>2>>>0]=p.getUTCHours(),o()[x+12>>>2>>>0]=p.getUTCDate(),o()[x+16>>>2>>>0]=p.getUTCMonth(),o()[x+20>>>2>>>0]=p.getUTCFullYear()-1900,o()[x+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[x+28>>>2>>>0]=p},v:function(p,w,x){p=w+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*w:NaN,x>>>=0,p=new Date(1e3*p),o()[x>>>2>>>0]=p.getSeconds(),o()[x+4>>>2>>>0]=p.getMinutes(),o()[x+8>>>2>>>0]=p.getHours(),o()[x+12>>>2>>>0]=p.getDate(),o()[x+16>>>2>>>0]=p.getMonth(),o()[x+20>>>2>>>0]=p.getFullYear()-1900,o()[x+24>>>2>>>0]=p.getDay(),w=(v(p.getFullYear())?S:I)[p.getMonth()]+p.getDate()-1|0,o()[x+28>>>2>>>0]=w,o()[x+36>>>2>>>0]=-(60*p.getTimezoneOffset()),w=new Date(p.getFullYear(),6,1).getTimezoneOffset();var C=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=(w!=C&&p.getTimezoneOffset()==Math.min(C,w))|0,o()[x+32>>>2>>>0]=p},w:function(p){p>>>=0;var w=new Date(o()[p+20>>>2>>>0]+1900,o()[p+16>>>2>>>0],o()[p+12>>>2>>>0],o()[p+8>>>2>>>0],o()[p+4>>>2>>>0],o()[p>>>2>>>0],0),x=o()[p+32>>>2>>>0],C=w.getTimezoneOffset(),M=new Date(w.getFullYear(),6,1).getTimezoneOffset(),D=new Date(w.getFullYear(),0,1).getTimezoneOffset(),H=Math.min(D,M);return 0>x?o()[p+32>>>2>>>0]=+(M!=D&&H==C):0>>2>>>0]=w.getDay(),x=(v(w.getFullYear())?S:I)[w.getMonth()]+w.getDate()-1|0,o()[p+28>>>2>>>0]=x,o()[p>>>2>>>0]=w.getSeconds(),o()[p+4>>>2>>>0]=w.getMinutes(),o()[p+8>>>2>>>0]=w.getHours(),o()[p+12>>>2>>>0]=w.getDate(),o()[p+16>>>2>>>0]=w.getMonth(),o()[p+20>>>2>>>0]=w.getYear(),p=w.getTime(),isNaN(p)?(o()[zo()>>>2>>>0]=61,p=-1):p/=1e3,No((Qt=p,1<=+Math.abs(Qt)?0>>0:~~+Math.ceil((Qt-+(~~Qt>>>0))/4294967296)>>>0:0)),p>>>0},s:z,t:V,A:function(p,w,x){function C(ve){return(ve=ve.toTimeString().match(/\(([A-Za-z ]+)\)$/))?ve[1]:"GMT"}p>>>=0,w>>>=0,x>>>=0;var M=new Date().getFullYear(),D=new Date(M,0,1),H=new Date(M,6,1);M=D.getTimezoneOffset();var le=H.getTimezoneOffset(),Ee=Math.max(M,le);l()[p>>>2>>>0]=60*Ee,o()[w>>>2>>>0]=+(M!=le),p=C(D),w=C(H),p=re(p),w=re(w),le>>2>>>0]=p,l()[x+4>>>2>>>0]=w):(l()[x>>>2>>>0]=w,l()[x+4>>>2>>>0]=p)},d:()=>{nr("")},c:function(p,w,x){return p>>>=0,w=_e(w>>>0,x>>>0),Fr[p].apply(null,w)},k:function(p,w,x){return p>>>=0,w=_e(w>>>0,x>>>0),Fr[p].apply(null,w)},m:()=>{},j:()=>Date.now(),V:()=>{throw Wt+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>k?(M_(),Mr(Zc)).cpus().length:navigator.hardwareConcurrency,y:function(p){p>>>=0;var w=s().length;if(p<=w||4294901760=x;x*=2){var C=w*(1+.2/x);C=Math.min(C,p+100663296);var M=Math;C=Math.max(p,C);e:{M=(M.min.call(M,4294901760,C+(65536-C%65536)%65536)-G.buffer.byteLength+65535)/65536;try{G.grow(M),He();var D=1;break e}catch{}D=void 0}if(D)return!0}return!1},O:Ne,P:B,I:ar,h:ge,o:Ie,x:Vt,n:ko,a:G||u.wasmMemory,z:Io,e:function(p,w,x,C){return Io(p>>>0,w>>>0,x>>>0,C>>>0)}},oe=function(){function p(x,C){return oe=x.exports,oe=Og(),oe=Wg(),ce.qb.push(oe.Da),Ue.unshift(oe.X),ie=C,Lr(),oe}var w={a:Fg};if(lt++,u.instantiateWasm)try{return u.instantiateWasm(w,p)}catch(x){O(`Module.instantiateWasm callback failed with error: ${x}`),m(x)}return da(w,function(x){p(x.instance,x.module)}).catch(m),{}}();u._OrtInit=(p,w)=>(u._OrtInit=oe.Y)(p,w),u._OrtGetLastError=(p,w)=>(u._OrtGetLastError=oe.Z)(p,w),u._OrtCreateSessionOptions=(p,w,x,C,M,D,H,le,Ee,ve)=>(u._OrtCreateSessionOptions=oe._)(p,w,x,C,M,D,H,le,Ee,ve),u._OrtAppendExecutionProvider=(p,w)=>(u._OrtAppendExecutionProvider=oe.$)(p,w),u._OrtAddFreeDimensionOverride=(p,w,x)=>(u._OrtAddFreeDimensionOverride=oe.aa)(p,w,x),u._OrtAddSessionConfigEntry=(p,w,x)=>(u._OrtAddSessionConfigEntry=oe.ba)(p,w,x),u._OrtReleaseSessionOptions=p=>(u._OrtReleaseSessionOptions=oe.ca)(p),u._OrtCreateSession=(p,w,x)=>(u._OrtCreateSession=oe.da)(p,w,x),u._OrtReleaseSession=p=>(u._OrtReleaseSession=oe.ea)(p),u._OrtGetInputOutputCount=(p,w,x)=>(u._OrtGetInputOutputCount=oe.fa)(p,w,x),u._OrtGetInputName=(p,w)=>(u._OrtGetInputName=oe.ga)(p,w),u._OrtGetOutputName=(p,w)=>(u._OrtGetOutputName=oe.ha)(p,w),u._OrtFree=p=>(u._OrtFree=oe.ia)(p),u._OrtCreateTensor=(p,w,x,C,M,D)=>(u._OrtCreateTensor=oe.ja)(p,w,x,C,M,D),u._OrtGetTensorData=(p,w,x,C,M)=>(u._OrtGetTensorData=oe.ka)(p,w,x,C,M),u._OrtReleaseTensor=p=>(u._OrtReleaseTensor=oe.la)(p),u._OrtCreateRunOptions=(p,w,x,C)=>(u._OrtCreateRunOptions=oe.ma)(p,w,x,C),u._OrtAddRunConfigEntry=(p,w,x)=>(u._OrtAddRunConfigEntry=oe.na)(p,w,x),u._OrtReleaseRunOptions=p=>(u._OrtReleaseRunOptions=oe.oa)(p),u._OrtCreateBinding=p=>(u._OrtCreateBinding=oe.pa)(p),u._OrtBindInput=(p,w,x)=>(u._OrtBindInput=oe.qa)(p,w,x),u._OrtBindOutput=(p,w,x,C)=>(u._OrtBindOutput=oe.ra)(p,w,x,C),u._OrtClearBoundOutputs=p=>(u._OrtClearBoundOutputs=oe.sa)(p),u._OrtReleaseBinding=p=>(u._OrtReleaseBinding=oe.ta)(p),u._OrtRunWithBinding=(p,w,x,C,M)=>(u._OrtRunWithBinding=oe.ua)(p,w,x,C,M),u._OrtRun=(p,w,x,C,M,D,H,le)=>(u._OrtRun=oe.va)(p,w,x,C,M,D,H,le),u._OrtEndProfiling=p=>(u._OrtEndProfiling=oe.wa)(p),u._JsepOutput=(p,w,x)=>(u._JsepOutput=oe.xa)(p,w,x),u._JsepGetNodeName=p=>(u._JsepGetNodeName=oe.ya)(p);var zo=()=>(zo=oe.za)(),xa=u._pthread_self=()=>(xa=u._pthread_self=oe.Aa)(),Ai=u._malloc=p=>(Ai=u._malloc=oe.Ba)(p),Po=u._free=p=>(Po=u._free=oe.Ca)(p);u.__emscripten_tls_init=()=>(u.__emscripten_tls_init=oe.Da)();var Ro=u.__emscripten_thread_init=(p,w,x,C,M,D)=>(Ro=u.__emscripten_thread_init=oe.Fa)(p,w,x,C,M,D);u.__emscripten_thread_crashed=()=>(u.__emscripten_thread_crashed=oe.Ga)();var Bo=(p,w,x,C)=>(Bo=oe.Ha)(p,w,x,C),Mi=p=>(Mi=oe.Ia)(p),Oi=u.__emscripten_thread_exit=p=>(Oi=u.__emscripten_thread_exit=oe.Ja)(p),Do=()=>(Do=oe.Ka)(),No=p=>(No=oe.La)(p),Lo=(p,w)=>(Lo=oe.Ma)(p,w),zi=()=>(zi=oe.Na)(),Sa=p=>(Sa=oe.Oa)(p),Pi=p=>(Pi=oe.Pa)(p),Uo=u.dynCall_ii=(p,w)=>(Uo=u.dynCall_ii=oe.Ra)(p,w),Fo=p=>(Fo=oe.Sa)(p),Wo=()=>(Wo=oe.Ta)(),Go=p=>(Go=oe.Ua)(p),Vo=()=>(Vo=oe.Va)();u.___start_em_js=945539,u.___stop_em_js=945700;function Wg(){var p=oe;p=Object.assign({},p);var w=C=>()=>C()>>>0,x=C=>M=>C(M)>>>0;return p.za=w(p.za),p.Aa=w(p.Aa),p.Ba=x(p.Ba),p.emscripten_main_runtime_thread_id=w(p.emscripten_main_runtime_thread_id),p.Na=w(p.Na),p.Pa=x(p.Pa),p}u.wasmMemory=G,u.stackAlloc=Pi,u.stackSave=zi,u.stackRestore=Sa,u.keepRuntimeAlive=()=>0r)}),z_=Qr((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'}),Zo,Jo,Li,Ia,vn,Ui,el,tl,rl,ep,tt,qn=X(()=>{Zo=T_(),Jo=O_(),Ia=!1,vn=!1,Ui=!1,el=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}},tl=()=>{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}},rl=(t,e)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",ep=async t=>{if(Ia)return Promise.resolve();if(vn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ui)throw new Error("previous call to 'initializeWebAssembly()' failed.");vn=!0;let e=t.initTimeout,r=t.numThreads,n=t.simd,a=el(r),i=n&&tl(),s=t.wasmPaths,o=typeof s=="string"?s:void 0,l=rl(i,a),d=typeof s=="object"?s[l]:void 0,c=!1,u=[];if(e>0&&u.push(new Promise(h=>{setTimeout(()=>{c=!0,h()},e)})),u.push(new Promise((h,m)=>{let g=a?Jo:Zo,_={locateFile:(b,$)=>{if(a&&b.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([z_()],{type:"text/javascript"}));if(b.endsWith(".wasm")){if(d)return d;let y=o??$;return l==="ort-wasm-simd.wasm"?y+"ort-wasm-simd.jsep.wasm":l==="ort-wasm-simd-threaded.wasm"?y+"ort-wasm-simd-threaded.jsep.wasm":y+l}return $+b}};if(a)if(_.numThreads=r,typeof Blob>"u")_.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let b=`var ortWasmThreaded=${g.toString()};`;_.mainScriptUrlOrBlob=new Blob([b],{type:"text/javascript"})}g(_).then(b=>{vn=!1,Ia=!0,Li=b,h()},b=>{vn=!1,Ui=!0,m(b)})})),await Promise.race(u),c)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},tt=()=>{if(Ia&&Li)return Li;throw new Error("WebAssembly is not initialized yet.")}}),Je,Za,Ge,Xs=X(()=>{qn(),Je=(t,e)=>{let r=tt(),n=r.lengthBytesUTF8(t)+1,a=r._malloc(n);return r.stringToUTF8(t,a,n),e.push(a),a},Za=(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")Za(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}`)})},Ge=t=>{let e=tt(),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)}}}),tp,P_=X(()=>{qn(),Xs(),tp=t=>{let e=tt(),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&&Ge("Can't create run options."),t?.extra!==void 0&&Za(t.extra,"",new WeakSet,(s,o)=>{let l=Je(s,n),d=Je(o,n);e._OrtAddRunConfigEntry(r,l,d)!==0&&Ge(`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}}}),nl,al,il,sl,rp,R_=X(()=>{qn(),Xs(),nl=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}`)}},al=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},il=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)},sl=(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);tt()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ge(`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);tt()._OrtAddSessionConfigEntry(t,l,d)!==0&&Ge(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s?.powerPreference){let o=Je("powerPreference",r),l=Je(s.powerPreference,r);tt()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ge(`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);tt()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ge(`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);tt()._OrtAppendExecutionProvider(t,i)!==0&&Ge(`Can't append execution provider: ${a}.`)}},rp=t=>{let e=tt(),r=0,n=[],a=t||{};il(a);try{let i=nl(a.graphOptimizationLevel??"all"),s=al(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 c=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,c),r===0&&Ge("Can't create session options."),a.executionProviders&&sl(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&&Ge(`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&&Ge(`Can't set a free dimension override: ${u} - ${h}.`)}return a.extra!==void 0&&Za(a.extra,"",new WeakSet,(u,h)=>{let m=Je(u,n),g=Je(h,n);e._OrtAddSessionConfigEntry(r,m,g)!==0&&Ge(`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}}}),$s,Tr,Ja,Qs,ei,Zs,xs,ye=X(()=>{$s=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}`)}},Tr=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}`)}},Ja=t=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][t],Qs=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}`)}},ei=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}`)}},Zs=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool",xs=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}`)}}}),ti,np=X(()=>{ti=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)}}),ol,ll,ul,dl,ap,cl,et,Rr=X(()=>{ye(),ol=["V","I","W","E","F"],ll=(t,e)=>{console.log(`[${ol[t]},${new Date().toISOString()}]${e}`)},ap=(t,e)=>{ul=t,dl=e},cl=(t,e)=>{let r=ei(t),n=ei(ul);r>=n&&ll(r,typeof e=="function"?e():e)},et=(...t)=>{dl&&cl(...t)}}),ip,B_=X(()=>{ye(),ip=(t,e)=>new(Qs(e))(t)}),Js=X(()=>{}),$n,pl,Fi,Ss,hl,sp,D_=X(()=>{Rr(),Js(),$n=t=>Math.ceil(t/16)*16,pl=1,Fi=()=>pl++,Ss=async(t,e,r,n)=>{let a=$n(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()}},hl=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=$n(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),et("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=$n(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 et("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=Fi();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:e}),this.externalBuffers.set(t,n),et("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),et("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(t,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=$n(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:Fi(),type:0,buffer:n};return this.storageCache.set(s.id,{gpuData:s,originalSize:t}),et("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 et("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 Ss(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))}},sp=(...t)=>new hl(...t)}),fl,qe,ut=X(()=>{fl=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}},qe=t=>new fl(t)}),ml,Xr,Q,ri,op,eo,to,Te=X(()=>{ml=class{static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}},Xr=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=ml.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 c=Math.max(l,d);if(l&&d)s[i-o]=Math.max(l,d);else{if(c>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}},Q=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])}},ri=class Mn{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{ye(),Te(),ni=64,Aa=(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}`)}},it=(t,e=1)=>{let r=Aa(t,e);return typeof r=="string"?r:r[0]},Ct=(t,e=1)=>{let r=Aa(t,e);return typeof r=="string"?r:r[1]},he=(...t)=>{let e=[];return t.forEach(r=>{r.length!==0&&e.push({type:12,data:r},{type:12,data:Q.computeStrides(r)})}),e},rt=t=>t%4===0?4:t%2===0?2:1,bt=(t="f32",e,r="0")=>!e||e===1?`${t}(${r})`:`vec${e}<${t}>(${r})`,Zt=(t,e,r)=>t==="f32"?r:e===1?`f32(${r})`:`vec${e}f(${r})`,Kt=(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,we=(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,Ma=(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=Aa(e,a),c=typeof d=="string"?d:d[1],u=typeof d=="string"?d:d[0],h={indices:l,value:c,storage:u,tensor:e},m=L=>typeof L=="string"?L:`${L}u`,g={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},_=i?"uniforms.":"",b=`${_}${t}_shape`,$=`${_}${t}_strides`,y="";for(let L=0;L ${h.indices} { - var indices: ${h.indices}; - var current = offset; - ${y} - return indices; - }`,k=L=>(g.offsetToIndices=!0,s<2?L:`o2i_${t}(${L})`),T=[];if(s>=2)for(let L=s-1;L>=0;L--)T.push(`${we($,L,s)} * (indices[${L}])`);let A=s<2?"":` - fn i2o_${t}(indices: ${h.indices}) -> u32 { - return ${T.join("+")}; - }`,R=L=>(g.indicesToOffset=!0,s<2?L:`i2o_${t}(${L})`),W=(...L)=>s===0?"0u":`${h.indices}(${L.map(m).join(",")})`,K=(L,ne)=>s<2?`${L}`:`${we(L,ne,s)}`,q=(L,ne,me)=>s<2?`${L}=${me};`:`${we(L,ne,s)}=${me};`,ee={},P=(L,ne)=>{g.broadcastedIndicesToOffset=!0;let me=`${ne.name}broadcastedIndicesTo${t}Offset`;if(me in ee)return`${me}(${L})`;let Pe=[];for(let Re=s-1;Re>=0;Re--){let nt=ne.indicesGet("outputIndices",Re+ne.rank-s);Pe.push(`${K($,Re)} * (${nt} % ${K(b,Re)})`)}return ee[me]=`fn ${me}(outputIndices: ${ne.type.indices}) -> u32 { - return ${Pe.length>0?Pe.join("+"):"0u"}; - }`,`${me}(${L})`},J=(L,ne)=>(()=>{if(h.storage===h.value)return`${t}[${L}]=${ne};`;if(h.storage==="vec2"&&h.value==="i32")return`${t}[${L}]=vec2(u32(${ne}), select(0u, 0xFFFFFFFFu, ${ne} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${t}[${L}]=vec2(u32(${ne}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${t}[${L}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ne}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),te=L=>(()=>{if(h.storage===h.value)return`${t}[${L}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${t}[${L}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${t}[${L}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${t}[${L}] & 0xFFu), bool(${t}[${L}] & 0xFF00u), bool(${t}[${L}] & 0xFF0000u), bool(${t}[${L}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),F=s<2?"":` - fn get_${t}ByIndices(indices: ${h.indices}) -> ${c} { - return ${te(`i2o_${t}(indices)`)}; - }`,O=s<2?"":(()=>{let L=o.map(me=>`d${me}: u32`).join(", "),ne=o.map(me=>`d${me}`).join(", ");return` - fn get_${t}(${L}) -> ${c} { - return get_${t}ByIndices(${W(ne)}); - }`})(),G=(...L)=>{if(L.length!==s)throw new Error(`indices length must be ${s}`);let ne=L.map(m).join(",");return s===0?te("0u"):s===1?te(ne[0]):(g.get=!0,g.getByIndices=!0,g.indicesToOffset=!0,`get_${t}(${ne})`)},ie=L=>s<2?te(L):(g.getByIndices=!0,g.indicesToOffset=!0,`get_${t}ByIndices(${L})`),j=s<2?"":` - fn set_${t}ByIndices(indices: ${h.indices}, value: ${c}) { - ${J(`i2o_${t}(indices)`,"value")} - }`,se=s<2?"":(()=>{let L=o.map(me=>`d${me}: u32`).join(", "),ne=o.map(me=>`d${me}`).join(", ");return` - fn set_${t}(${L}, value: ${c}) { - set_${t}ByIndices(${W(ne)}, value); - }`})();return{impl:()=>{let L=[],ne=!1;return g.offsetToIndices&&(L.push(E),ne=!0),g.indicesToOffset&&(L.push(A),ne=!0),g.broadcastedIndicesToOffset&&(Object.values(ee).forEach(me=>L.push(me)),ne=!0),g.set&&(L.push(se),ne=!0),g.setByIndices&&(L.push(j),ne=!0),g.get&&(L.push(O),ne=!0),g.getByIndices&&(L.push(F),ne=!0),!i&&ne&&L.unshift(`const ${b} = ${h.indices}(${r.join(",")});`,`const ${$} = ${h.indices}(${Q.computeStrides(r).join(",")});`),L.join(` -`)},type:h,offsetToIndices:k,indicesToOffset:R,broadcastedIndicesToOffset:P,indices:W,indicesGet:K,indicesSet:q,set:(...L)=>{if(L.length!==s+1)throw new Error(`indices length must be ${s}`);let ne=L[s];if(typeof ne!="string")throw new Error("value must be string");let me=L.slice(0,s).map(m).join(",");return s===0?J("0u",ne):s===1?J(me[0],ne):(g.set=!0,g.setByIndices=!0,g.indicesToOffset=!0,`set_${t}(${me}, ${ne})`)},setByOffset:J,setByIndices:(L,ne)=>s<2?J(L,ne):(g.setByIndices=!0,g.indicesToOffset=!0,`set_${t}ByIndices(${L}, ${ne});`),get:G,getByOffset:te,getByIndices:ie,usage:n,name:t,strides:$,shape:b,rank:s}},Y=(t,e,r,n=1)=>Ma(t,e,r,"input",n),pe=(t,e,r,n=1)=>Ma(t,e,r,"output",n),ro=(t,e,r,n=1)=>Ma(t,e,r,"internal",n),gl=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=ni){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(` -`)}},lp=t=>new gl(t),Ln=(t,e)=>{let r=t.length,n=[];for(let a=0;a1&&s===1&&n.unshift(i)}return n}}),_l,Wi,wl,yl,er,up,dp,jn=X(()=>{ye(),Te(),ut(),Ce(),_l=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},Wi=(t,e)=>e&&e.length!==t?[...new Array(t).keys()].reverse():e,wl=(t,e)=>Q.sortBasedOnPerm(t,Wi(t.length,e)),yl=(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=Wi(n,e),i=wl(t.dims,a),s=pe("output",r,i.length),o=Y("a",r,n),l=d=>` - ${d.registerUniform("output_size","u32").declareVariables(o,s)} - - ${yl(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 c=Q.size(i);return{outputs:[{dims:i,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},...he(d[0].dims,i)]}},getShaderSource:l}},up=(t,e)=>{_l(t.inputs),t.compute(er(t.inputs[0],e.perm))},dp=t=>qe({perm:t.perm})}),bl,vl,$l,xl,Sl,El,kl,Cl,Tl,Il,Mt,cp,pp,hp,fp,mp,gp,_p,wp,yp,bp,N_=X(()=>{ye(),Te(),Ce(),no(),jn(),bl={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"},vl={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"},$l={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},xl={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Sl=(t,e)=>{let r=[];for(let n=e-t;n{let r=[],n=t.length;for(let i=0;it[i]);return[r,a]},kl=(t,e)=>{let r=t.length+e.length,n=[],a=0;for(let i=0;i{for(let r=0;r{let r=[];if(!Cl(t,e)){for(let n=0;nr.push(n))}return r},Il=(t,e,r,n,a,i,s)=>{let o=r[0].dims,l=Q.size(i),d=Q.size(s),c=Y("_A",r[0].dataType,o),u=pe("output",a,i),h=32,m=` - var aBestValues : array; - `;return{name:t,shaderCache:e,getShaderSource:g=>` - ${g.registerUniform("reduceSize","u32").declareVariables(c,u)} - ${m} - fn DIV_CEIL(a : u32, b : u32) -> u32 { - return ((a - 1u) / b + 1u); - } - ${g.mainStart(h)} - - let outputIndex = global_idx / ${h}; - let offset = outputIndex * uniforms.reduceSize; - - var bestValue = f32(${$l[n]}); - let Length = uniforms.reduceSize; - for (var k = local_idx; k < Length; k = k + ${h}) { - let candidate = f32(${c.getByOffset("offset + k")}); - bestValue = ${bl[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 = ${vl[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}(${xl[n]})`}`)}; - } - }`,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:l},programUniforms:[{type:12,data:d}]})}},Mt=(t,e,r,n)=>{let a=t.inputs.length===1?r:Es(t.inputs,r),i=a.axes;i.length===0&&!a.noopWithEmptyAxes&&(i=t.inputs[0].dims.map((m,g)=>g));let s=Q.normalizeAxes(i,t.inputs[0].dims.length),o=s,l=t.inputs[0],d=Tl(o,t.inputs[0].dims.length);d.length>0&&(l=t.compute(er(t.inputs[0],d),{inputs:[0],outputs:[-1]})[0],o=Sl(o.length,l.dims.length));let[c,u]=El(l.dims,o),h=c;a.keepDims&&(h=kl(c,s)),t.compute(Il(e,{hint:a.cacheKey,inputDependencies:["type"]},[l],n,t.inputs[0].dataType,h,u),{inputs:[l]})},cp=(t,e)=>{Mt(t,"ReduceMeanShared",e,"mean")},pp=(t,e)=>{Mt(t,"ReduceL1Shared",e,"l1")},hp=(t,e)=>{Mt(t,"ReduceL2Shared",e,"l2")},fp=(t,e)=>{Mt(t,"ReduceLogSumExpShared",e,"logSumExp")},mp=(t,e)=>{Mt(t,"ReduceMaxShared",e,"max")},gp=(t,e)=>{Mt(t,"ReduceMinShared",e,"min")},_p=(t,e)=>{Mt(t,"ReduceProdShared",e,"prod")},wp=(t,e)=>{Mt(t,"ReduceSumShared",e,"sum")},yp=(t,e)=>{Mt(t,"ReduceSumSquareShared",e,"sumSquare")},bp=(t,e)=>{Mt(t,"ReduceLogSumShared",e,"logSum")}}),Ot,Al,ai,Es,zt,Ml,Ol,zl,Pl,Rl,Bl,Dl,Nl,Ll,Ul,Pt,vp,$p,xp,Sp,Ep,kp,Cp,Tp,Ip,Ap,no=X(()=>{ye(),Te(),ut(),Ce(),N_(),Ot=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.")},Al=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],ai=(t,e,r,n,a,i,s=!1,o=!1)=>{let l=[],d=r[0].dims,c=d.length,u=Q.normalizeAxes(a,c),h=!o&&u.length===0;d.forEach((_,b)=>{h||u.indexOf(b)>=0?s&&l.push(1):l.push(_)});let m=l.length,g=Q.size(l);return{name:t,shaderCache:e,getShaderSource:_=>{let b=[],$=Y("_A",r[0].dataType,c),y=pe("output",i,m),E=n($,y,u),k=E[2];for(let T=0,A=0;T=0?(s&&A++,k=`for(var j${T}: u32 = 0; j${T} < ${d[T]}; j${T}++) { - ${E[2].includes("last_index")?`let last_index = j${T};`:""} - ${$.indicesSet("input_indices",T,`j${T}`)} - ${k} - }`):(b.push(`${$.indicesSet("input_indices",T,y.indicesGet("output_indices",A))};`),A++);return` - - ${_.registerUniform("output_size","u32").declareVariables($,y)} - - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${$.type.indices}; - let output_indices = ${y.offsetToIndices("global_idx")}; - - ${b.join(` -`)} - ${E[0]} // init ops for reduce max/min - ${E[1]} - ${k} - ${E[3]} - ${E.length===4?y.setByOffset("global_idx","value"):E.slice(4).join(` -`)} - }`},getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...he(d,l)]})}},Es=(t,e)=>{let r=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(n=>r.push(Number(n))),qe({axes:r,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},zt=(t,e,r,n)=>{let a=t.inputs,i=a.length===1?r:Es(a,r);t.compute(ai(e,{hint:i.cacheKey,inputDependencies:["rank"]},[a[0]],i.noopWithEmptyAxes&&i.axes.length===0?Al:n,i.axes,a[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},Ml=(t,e)=>{Ot(t.inputs),zt(t,"ReduceLogSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Ol=(t,e)=>{Ot(t.inputs),zt(t,"ReduceL1",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},zl=(t,e)=>{Ot(t.inputs),zt(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);"])},Pl=(t,e)=>{Ot(t.inputs),zt(t,"ReduceLogSumExp",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Rl=(t,e)=>{Ot(t.inputs),zt(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)=>{Ot(t.inputs),zt(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});`]})},Dl=(t,e)=>{Ot(t.inputs),zt(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")});`,""]})},Nl=(t,e)=>{Ot(t.inputs),zt(t,"ReduceProd",e,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Ll=(t,e)=>{Ot(t.inputs),zt(t,"ReduceSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Ul=(t,e)=>{Ot(t.inputs),zt(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;`,""])},Pt=(t,e,r)=>{if(e.length===0)return r;let n=1,a=1;for(let i=0;i1024},vp=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Bl(t,e):cp(t,e)},$p=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ol(t,e):pp(t,e)},xp=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?zl(t,e):hp(t,e)},Sp=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Pl(t,e):fp(t,e)},Ep=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Rl(t,e):mp(t,e)},kp=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Dl(t,e):gp(t,e)},Cp=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Nl(t,e):_p(t,e)},Tp=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ll(t,e):wp(t,e)},Ip=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ul(t,e):yp(t,e)},Ap=(t,e)=>{Pt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ml(t,e):bp(t,e)}}),Gi,Mp,Op,ks,L_=X(()=>{ye(),ut(),no(),Gi=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.")},Mp=(t,e)=>{Gi(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(ai("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},Op=(t,e)=>{Gi(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(ai("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},ks=t=>qe(t)}),Fl,Wl,Gl,Vl,ii,Hl,zp,Pp=X(()=>{ye(),Js(),Ce(),Fl=(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],c=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]!==c)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 g=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 _=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||(_=s.dims[3])}let b=g+_,$=-1,y=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:_,kvSequenceLength:g,totalSequenceLength:b,maxSequenceLength:$,inputHiddenSize:c,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:y,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Wl=(t,e,r,n)=>{let a=rt(n),i=64,s=n/a;s{let h=pe("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 g=Ct(e.dataType),_=[{name:"d_inv",type:g},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return` - var wgMax: array; - var wgSum: array; - ${u.registerUniforms(_).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 = ${bt("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(${Zt(g,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 = ${bt("f32",a,"0")}; - for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { - sumVector += exp(${Zt(g,a,"x[offset + i]")} - maxValue); - } - wgSum[local_idx] = ${Kt("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] = ${bt(g,a,"uniforms.d_inv")}; - } - } else { - for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { - let f32input = ${Zt(g,a,"x[offset + i]")}; - x[offset + i] = ${h.type.value}(exp(f32input - maxValue) / sum); - } - } - }`};t.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${i};${d};${a}`},getShaderSource:c,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:l})},{inputs:[e],outputs:[]})},Gl=(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=rt(a.headSize),d=a.headSize/l,c=12,u={x:Math.ceil(a.totalSequenceLength/c),y:Math.ceil(a.sequenceLength/c),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],g=b=>{let $=Y("q",e.dataType,e.dims,l),y=Y("key",r.dataType,r.dims,l),E=pe("output",e.dataType,s),k=it(e.dataType),T=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:k}];return` - const beta: ${k} = 1.0; - const TILE_SIZE = ${c}u; - - var tileQ: array<${$.type.storage}, ${c*c}>; - var tileK: array<${$.type.storage}, ${c*c}>; - ${b.registerUniforms(T).declareVariables($,y,E)} - ${b.mainStart([c,c,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 = ${bt(k,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:g},{inputs:m,outputs:[-1]})[0];return Wl(t,_,a.batchSize*a.numHeads*a.sequenceLength,a.totalSequenceLength),_},Vl=(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 c=Y("probs",e.dataType,e.dims),u=Y("v",r.dataType,r.dims),h=pe("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<${c.type.value}, ${i*i}>; - var tileK: array<${c.type.value}, ${i*i}>; - ${d.registerUniforms(m).declareVariables(c,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 = ${c.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]},ii=(t,e,r,n,a,i,s,o,l,d,c)=>{let u=Gl(t,e,r,l,d,c);Vl(t,u,n,d)},Hl=(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}],c=u=>{let h=pe("output_q",l[0].dataType,r),m=pe("output_k",l[0].dataType,r),g=pe("output_v",l[0].dataType,r),_=Y("input",l[0].dataType,l[0].dims),b=Y("weight",l[1].dataType,l[1].dims),$=Y("bias",l[2].dataType,l[2].dims),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<${y}, ${s*s}>; - var tileWeightQ: array<${y}, ${s*s}>; - var tileWeightK: array<${y}, ${s*s}>; - var tileWeightV: array<${y}, ${s*s}>; - ${u.registerUniforms(E).declareVariables(_,b,$,h,m,g)} - ${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 = ${y}(0); - var valueK = ${y}(0); - var valueV = ${y}(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:c},{inputs:l,outputs:[-1,-1,-1]})},zp=(t,e)=>{let r=Fl(t.inputs,e),[n,a,i]=Hl(t,r);return ii(t,n,a,i,t.inputs[4],void 0,void 0,void 0,t.inputs[5],r,e)}}),ql,jl,Kl,Rp,U_=X(()=>{Ft(),ye(),Te(),ut(),Ce(),ql=(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")},jl=(t,e)=>{let{epsilon:r,spatial:n,format:a}=e,i=t[0].dims,s=n?rt(i[i.length-1]):1,o=a==="NHWC"&&i.length>1?s:1,l=Q.size(i)/s,d=n,c=d?i.length:i,u=Y("x",t[0].dataType,t[0].dims,s),h=Y("scale",t[1].dataType,t[1].dims,o),m=Y("bias",t[2].dataType,t[2].dims,o),g=Y("inputMean",t[3].dataType,t[3].dims,o),_=Y("inputVar",t[4].dataType,t[4].dims,o),b=pe("y",t[0].dataType,c,s),$=()=>{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=` - ${b.indicesSet("outputIndices","0","0")} - let cOffset = ${b.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${h.type.indices}(0); - cIndices[0] = outputIndices[${i.length-1}];`;for(let k=1;k` - const epsilon = ${r}; - ${E.registerUniform("outputSize","u32").declareVariables(u,h,m,g,_,b)} - ${E.mainStart()} - ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${b.offsetToIndices(`global_idx * ${s}`)}; - ${$()} - let scale = ${h.getByOffset("cOffset")}; - let bias = ${m.getByOffset("cOffset")}; - let inputMean = ${g.getByOffset("cOffset")}; - let inputVar = ${_.getByOffset("cOffset")}; - let x = ${u.getByOffset("global_idx")}; - let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; - ${b.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:y,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d?[{type:12,data:l},...he(i)]:[{type:12,data:l}]})}},Kl=t=>qe(t),Rp=(t,e)=>{let{inputs:r,outputCount:n}=t,a=Kl({...e,outputCount:n});if(De.webgpu.validateInputContent&&ql(r,a),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(jl(r,a))}}),Yl,Xl,Bp,F_=X(()=>{Te(),Ce(),Yl=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")},Xl=t=>{let e=t[0].dims,r=t[0].dims[2],n=Q.size(e)/4,a=t[0].dataType,i=Y("input",a,e,4),s=Y("bias",a,[r],4),o=Y("residual",a,e,4),l=pe("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")} - }`}},Bp=t=>{Yl(t.inputs),t.compute(Xl(t.inputs))}}),Ql,Oe,Dp,Np,Lp,Up,Fp,Wp,Gp,Vp,Hp,Zl,qp,jp,Kp,Yp,Ha,Xp,qa,Qp,Zp,Jp,eh,th,rh,nh,ah,ih,sh,oh,lh,uh,dh,ch,ph,Vi,hh,Cs,Ts,fh,mh,gh,ao=X(()=>{ye(),Te(),ut(),Ce(),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=Y("inputData",r,[s],4),d=pe("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)} - }`},Oe=(t,e,r,n,a,i=t.dataType)=>({name:e,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:s=>Ql(s,Q.size(t.dims),t.dataType,i,r,n),getRunData:s=>({outputs:[{dims:t.dims,dataType:i}],dispatchGroup:{x:Math.ceil(Q.size(s[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(Q.size(t.dims)/4)}]})}),Dp=t=>{t.compute(Oe(t.inputs[0],"Abs","abs"))},Np=t=>{t.compute(Oe(t.inputs[0],"Acos","acos"))},Lp=t=>{t.compute(Oe(t.inputs[0],"Acosh","acosh"))},Up=t=>{t.compute(Oe(t.inputs[0],"Asin","asin"))},Fp=t=>{t.compute(Oe(t.inputs[0],"Asinh","asinh"))},Wp=t=>{t.compute(Oe(t.inputs[0],"Atan","atan"))},Gp=t=>{t.compute(Oe(t.inputs[0],"Atanh","atanh"))},Vp=t=>qe(t),Hp=(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(Oe(t.inputs[0],"Cast",r,void 0,e.cacheKey,e.to))},Zl=t=>{let e=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:eo,r=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:to;return qe({min:e,max:r})},qp=(t,e)=>{let r=t.inputs.length===1?e:Zl(t.inputs),n=Ct(t.inputs[0].dataType);t.compute(Oe(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]})},jp=t=>{t.compute(Oe(t.inputs[0],"Ceil","ceil"))},Kp=t=>{t.compute(Oe(t.inputs[0],"Cos","cos"))},Yp=t=>{t.compute(Oe(t.inputs[0],"Cosh","cosh"))},Ha=t=>qe(t),Xp=(t,e)=>{let r=Ct(t.inputs[0].dataType);t.compute(Oe(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))},qa=(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)); -}`,Qp=t=>{let e=Ct(t.inputs[0].dataType);t.compute(Oe(t.inputs[0],"Erf",r=>`erf_vf32(${r})`,qa(e)))},Zp=t=>{t.compute(Oe(t.inputs[0],"Exp","exp"))},Jp=t=>{t.compute(Oe(t.inputs[0],"Floor","floor"))},eh=t=>{let e=Ct(t.inputs[0].dataType);t.compute(Oe(t.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,qa(e)))},th=(t,e)=>{let r=Ct(t.inputs[0].dataType);t.compute(Oe(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))},rh=t=>{t.compute(Oe(t.inputs[0],"Not",e=>`!${e}`))},nh=t=>{t.compute(Oe(t.inputs[0],"Neg",e=>`-${e}`))},ah=t=>{t.compute(Oe(t.inputs[0],"Reciprocal",e=>`1.0/${e}`))},ih=t=>{let e=Ct(t.inputs[0].dataType);t.compute(Oe(t.inputs[0],"Relu",r=>`select(vec4<${e}>(0.0), ${r}, ${r} > vec4<${e}>(0.0))`))},sh=t=>{t.compute(Oe(t.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},oh=t=>qe(t),lh=(t,e)=>{let r=Ct(t.inputs[0].dataType);t.compute(Oe(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))},uh=t=>{t.compute(Oe(t.inputs[0],"Sin","sin"))},dh=t=>{t.compute(Oe(t.inputs[0],"Sinh","sinh"))},ch=t=>{t.compute(Oe(t.inputs[0],"Sqrt","sqrt"))},ph=t=>{t.compute(Oe(t.inputs[0],"Tan","tan"))},Vi=t=>`sign(${t}) * (1 - exp(-2 * abs(${t}))) / (1 + exp(-2 * abs(${t})))`,hh=t=>{t.compute(Oe(t.inputs[0],"Tanh",Vi))},Cs=(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 ${Vi("v")}; -} -`,Ts=t=>`(fast_gelu_a + fast_gelu_a * tanh_v(${t} * (fast_gelu_c * ${t} * ${t} + fast_gelu_b))) * ${t}`,fh=t=>{let e=Ct(t.inputs[0].dataType);t.compute(Oe(t.inputs[0],"FastGelu",Ts,Cs(e),void 0,t.inputs[0].dataType))},mh=(t,e)=>{let r=Ct(t.inputs[0].dataType);return t.compute(Oe(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},gh=t=>{t.compute(Oe(t.inputs[0],"Log","log"))}}),Jl,eu,_h,W_=X(()=>{Te(),Ce(),ao(),Jl=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")},eu=t=>{let e=t[0].dims.slice();e[2]=e[2]/2;let r=Y("input",t[0].dataType,t[0].dims,4),n=Y("bias",t[0].dataType,[t[0].dims[2]],4),a=pe("output",t[0].dataType,e,4),i=Q.size(e)/4,s=it(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)} - - ${qa(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")} - }`}},_h=t=>{Jl(t.inputs),t.compute(eu(t.inputs))}}),tu,ru,Rt,wh,yh,bh,vh,$h,xh,Sh,Eh,kh,Ch,G_=X(()=>{ye(),Te(),Ce(),tu=(t,e,r,n,a,i,s,o,l,d,c,u)=>{let h,m;typeof o=="string"?h=m=(y,E)=>`${o}((${y}),(${E}))`:typeof o=="function"?h=m=o:(h=o.scalar,m=o.vector);let g=pe("outputData",c,n.length,4),_=Y("aData",l,e.length,4),b=Y("bData",d,r.length,4),$;if(a)if(i){let y=Q.size(e)===1,E=Q.size(r)===1,k=e.length>0&&e[e.length-1]%4===0,T=r.length>0&&r[r.length-1]%4===0;y||E?$=g.setByOffset("global_idx",m(y?`${_.type.value}(${_.getByOffset("0")}.x)`:_.getByOffset("global_idx"),E?`${b.type.value}(${b.getByOffset("0")}.x)`:b.getByOffset("global_idx"))):$=` - let outputIndices = ${g.offsetToIndices("global_idx * 4u")}; - let offsetA = ${_.broadcastedIndicesToOffset("outputIndices",g)}; - let offsetB = ${b.broadcastedIndicesToOffset("outputIndices",g)}; - ${g.setByOffset("global_idx",m(s||k?_.getByOffset("offsetA / 4u"):`${_.type.value}(${_.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||T?b.getByOffset("offsetB / 4u"):`${b.type.value}(${b.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else $=g.setByOffset("global_idx",m(_.getByOffset("global_idx"),b.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=(E,k,T="")=>{let A=`aData[indexA${k}][componentA${k}]`,R=`bData[indexB${k}][componentB${k}]`;return` - let outputIndices${k} = ${g.offsetToIndices(`global_idx * 4u + ${k}u`)}; - let offsetA${k} = ${_.broadcastedIndicesToOffset(`outputIndices${k}`,g)}; - let offsetB${k} = ${b.broadcastedIndicesToOffset(`outputIndices${k}`,g)}; - let indexA${k} = offsetA${k} / 4u; - let indexB${k} = offsetB${k} / 4u; - let componentA${k} = offsetA${k} % 4u; - let componentB${k} = offsetB${k} % 4u; - ${E}[${k}] = ${T}(${h(A,R)}); - `};c===9?$=` - var data = vec4(0); - ${y("data",0,"u32")} - ${y("data",1,"u32")} - ${y("data",2,"u32")} - ${y("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$=` - ${y("outputData[global_idx]",0)} - ${y("outputData[global_idx]",1)} - ${y("outputData[global_idx]",2)} - ${y("outputData[global_idx]",3)} - `}return` - ${t.registerUniform("vec_size","u32").declareVariables(_,b,g)} - - ${u??""} - - ${t.mainStart()} - ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${$} - }`},ru=(t,e,r,n,a,i,s=r.dataType)=>{let o=!Q.areEqual(r.dims,n.dims),l=r.dims,d=Q.size(r.dims),c=!1,u=!1,h=[o];if(o){let m=Xr.calcShape(r.dims,n.dims,!1);if(!m)throw new Error("Can't perform binary op on the given tensors");l=m,d=Q.size(l);let g=Q.size(r.dims)===1,_=Q.size(n.dims)===1,b=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,$=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;h.push(g),h.push(_),h.push(b),h.push($);let y=1;for(let E=1;Em.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:m=>tu(m,r.dims,n.dims,l,c,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(Q.size(l)/4)},...he(r.dims,n.dims,l)]})}},Rt=(t,e,r,n,a,i)=>{t.compute(ru(e,a??"",t.inputs[0],t.inputs[1],r,n,i))},wh=t=>{Rt(t,"Add",(e,r)=>`${e}+${r}`)},yh=t=>{Rt(t,"Div",(e,r)=>`${e}/${r}`)},bh=t=>{Rt(t,"Equal",{scalar:(e,r)=>`u32(${e}==${r})`,vector:(e,r)=>`vec4(${e}==${r})`},void 0,void 0,9)},vh=t=>{Rt(t,"Mul",(e,r)=>`${e}*${r}`)},$h=t=>{let e=Y("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;Rt(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)); - } - `)},xh=t=>{Rt(t,"Sub",(e,r)=>`${e}-${r}`)},Sh=t=>{Rt(t,"Greater",{scalar:(e,r)=>`u32(${e}>${r})`,vector:(e,r)=>`vec4(${e}>${r})`},void 0,void 0,9)},Eh=t=>{Rt(t,"Less",{scalar:(e,r)=>`u32(${e}<${r})`,vector:(e,r)=>`vec4(${e}<${r})`},void 0,void 0,9)},kh=t=>{Rt(t,"GreaterOrEqual",{scalar:(e,r)=>`u32(${e}>=${r})`,vector:(e,r)=>`vec4(${e}>=${r})`},void 0,void 0,9)},Ch=t=>{Rt(t,"LessOrEqual",{scalar:(e,r)=>`u32(${e}<=${r})`,vector:(e,r)=>`vec4(${e}<=${r})`},void 0,void 0,9)}}),nu,au,iu,su,Th,Ih,V_=X(()=>{ye(),Te(),ut(),Ce(),nu=(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")})}})},au=(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; - }`,iu=(t,e)=>{let r=t.length,n=[];for(let a=0;a{let a=Q.size(r),i=new Array(t.length),s=new Array(t.length),o=0,l=[],d=[],c=[{type:12,data:a}];for(let _=0;_`uniforms.sizeInConcatAxis${_}`).join(","),g=_=>` - - ${(()=>{_.registerUniform("outputSize","u32");for(let b=0;b(${m}); - ${h} -= sizeInConcatAxis[inputIndex - 1u]; - } - - ${iu(s,u)} - }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:g}},Th=(t,e)=>{let r=t.inputs,n=r[0].dims,a=Q.normalizeAxis(e.axis,n.length);nu(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=>Q.size(o.dims)>0);t.compute(su(s,a,i,r[0].dataType),{inputs:s})},Ih=t=>qe({axis:t.axis})}),Or,zr,Pr,io,Br=X(()=>{ye(),Te(),Or=(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}`)}},zr=(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})},Pr=(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"})},io=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||[eo,to];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}}}),ht,so,oo=X(()=>{ht=(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.`)}},so=t=>` - ${t?"value = value + getBiasByOutputCoords(coords);":""} - `}),lo,Ah=X(()=>{lo=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)); -} -`}),ou,lu,si,Hi,uu,oi,du,uo,fi=X(()=>{ye(),Te(),Ce(),Br(),oo(),ou=(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":""}); - `,lu=(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];"} - }`,si=(t,e,r="f32",n,a=!1,i=32,s=!1,o=32)=>{let l=e[1]*t[1],d=e[0]*t[0],c=a?l:i,u=a?i:l,h=c/e[0],m=i/e[1];if(!((a&&h===4&&t[1]===4||!a&&(h===3||h===4))&&c%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 ${c} 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, ${c/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; - ${ou(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];"} - - ${lu(a,h)} - } - - workgroupBarrier(); - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); - } -}`},Hi=(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":""}); - `,uu=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",oi=(t,e,r="f32",n,a=!1,i=32,s=!1,o=32,l=!1)=>{let d=t[1]*e[1],c=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],g=u/e[0],_=i/e[1],b=l?` - let localRow = i32(localId.y); - let localCol = i32(localId.x); - let globalRowStart = i32(workgroupId.y) * ${d}; - let globalColStart = i32(workgroupId.x) * ${c}; - - // Loop over shared dimension. - for (var t = 0; t < num_tiles; t = t + 1) { - // Load one tile of A into local memory. - for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${e[1]}) { - for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${e[0]}) { - ${Hi(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 < ${c}; 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) * ${g}; -let tileRowB = i32(localId.y) * ${_}; -// Loop over shared dimension. -for (var t = 0; t < num_tiles; t = t + 1) { - // Load one tile of A into local memory. - for (var innerRow = 0; innerRow < ${m}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${g}; innerCol = innerCol + 1) { - let inputRow = tileRowA + innerRow; - let inputCol = tileColA + innerCol; - ${Hi(a,n)} - } - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol + innerCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, - kStart + inputRow, - globalCol + innerCol${n?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${r}, colPerThread>; - for (var k = 0; k < tileInner; k = k + 1) { - for (var inner = 0; inner < colPerThread; inner = inner + 1) { - BCached[inner] = mm_Bsub[k][tileCol + inner]; - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - ${uu(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; - } - } - ${b} - } -`},du=(t,e,r,n,a,i=!1)=>{let[s,o,l]=a,[d,c,u,h]=n,m=Ln(s,l),g=Ln(o,l),_=it(n[0].type.tensor),b=()=>{let y=c.rank,E=d.rank,k=`var aIndices: ${c.type.indices};`;for(let T=y-2-1,A=E-1;T>=0;T--,A--)k+=` -aIndices[${T}] = ${E>1?`batchIndices[${A}]`:"batchIndices"};`;return m.forEach(T=>{k+=` -aIndices[${T}] = 0;`}),k+=` -aIndices[${y-2}] = u32(row); - aIndices[${y-1}] = u32(colIn);`,k},$=()=>{let y=u.rank,E=d.rank,k=`var bIndices: ${u.type.indices};`;for(let T=y-2-1,A=E-1;T>=0;T--,A--)k+=` -bIndices[${T}] = ${E>1?`batchIndices[${A}]`:"batchIndices"};`;return g.forEach(T=>{k+=` -bIndices[${T}] = 0;`}),k+=` -bIndices[${y-2}] = u32(row); - bIndices[${y-1}] = u32(colIn);`,k};return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${ht(t,_)} { - var value = ${ht(t,_)}(0.0); - let col = colIn * ${t}; - if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) - { - ${b()} - value = ${c.getByIndices("aIndices")}; - } - return value; - } - - fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${ht(t,_)} { - var value = ${ht(t,_)}(0.0); - let col = colIn * ${t}; - if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) - { - ${$()} - value = ${u.getByIndices("bIndices")}; - } - return value; - } - - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ht(t,_)}) { - 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]":`${ht(t,_)}(bias[row])`};`:""} - ${r} - ${h.setByIndices("vec3(coords)","value")} - } - } - `},uo=(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),c=Q.size(d),u=i[i.length-2],h=i[i.length-1],m=s[s.length-1],g=h%4===0&&m%4===0,_=u<=8?[4,1,1]:[4,4,1],b=[8,8,1],$=[Math.ceil(m/b[0]/_[0]),Math.ceil(u/b[1]/_[1]),Math.ceil(c/b[2]/_[2])],y=g?4:1,E=[...o,u,h/y],k=E.length,T=[...l,h,m/y],A=T.length,R=[c,u,m/y],W=[{type:6,data:u},{type:6,data:m},{type:6,data:h}];zr(e,W),W.push(...he(d,E,T));let K=["rank","rank"],q=t.length>2;q&&(W.push(...he(t[2].dims)),K.push("rank")),W.push(...he(R));let ee=P=>{let J=d.length,te=ro("batchDims",t[0].dataType,J,1),F=it(t[0].dataType),O=Y("a",t[0].dataType,k,y),G=Y("b",t[1].dataType,A,y),ie=pe("result",t[0].dataType,R.length,y),j=[O,G];if(q){let Pe=a?y:1;j.push(Y("bias",t[2].dataType,t[2].dims.length,Pe))}let se=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Pr(e,se);let L=it(ie.type.tensor),ne=Or(e,ie.type.value,L),me=du(y,q,ne,[te,O,G,ie],[o,l,d],a);return` - ${P.registerUniforms(se).registerInternalVariables(te).declareVariables(...j,ie)} - ${me} - ${g?si(_,b,F,te):oi(_,b,F,te)} - `};return{name:"MatMul",shaderCache:{hint:`${_};${e.activation};${g};${a}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:W}),getShaderSource:ee}}}),cu,Mh,H_=X(()=>{ye(),Rr(),Ce(),Br(),oo(),Ah(),fi(),cu=(t,e,r,n,a=!1,i,s=4,o=4,l=4,d="f32")=>{let c=K=>{switch(K){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 ${K} is not supported.`)}},u=K=>{switch(K){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 ${K} 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); - `,g=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",_=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",b=t?"row":"col",$=t?"col":"row",y=` - let inChannels = i32(uniforms.w_shape[2]); - let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - let outRow = ${b} / outWidth; - let outCol = ${b} % outWidth; - - let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels); - let WCol = ${$} / inChannels % i32(uniforms.w_shape[1]); - let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; - let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; - let xCh = ${$} % inChannels; - var resData = ${ht(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 < ${g} && xCol >= 0 && xCol < ${_}) { - ${h} - let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); - ${c(s)} - } - return resData;`,E=t?e&&n?` - let col = colIn * ${s}; - ${y}`:` - let col = colIn * ${s}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${y} - } - return ${ht(s,d)}(0.0);`:n&&r?` - let col = colIn * ${s}; - ${y}`:` - let col = colIn * ${s}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${y} - } - return ${ht(s,d)}(0.0);`,k=`${u(o)}`,T=ht(l,d),A=ht(t?s:o,d),R=ht(t?o:s,d),W=Or(i,T,d);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} { - ${t?E:k} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${R} { - ${t?k:E} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${T}) { - 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} - ${so(a)} - ${W} - setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); - } - }`},Mh=(t,e,r,n,a,i,s,o)=>{let l=e.format==="NHWC",d=l?t[0].dims[3]:t[0].dims[1],c=r[0],u=l?r[2]:r[3],h=l?r[1]:r[2],m=l?r[3]:r[1],g=l&&(d%4===0||d%3===0)&&m%4===0,_=l?m:u*h,b=l?u*h:m,$=[8,8,1],y=n<=8?[4,1,1]:[4,4,1],E=[Math.ceil(_/$[0]/y[0]),Math.ceil(b/$[1]/y[1]),Math.ceil(c/$[2]/y[2])];et("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let k=g?l&&d%4!==0?3:4:1,T=$[1]*y[1],A=$[0]*y[0],R=Math.max($[0]*k,$[1]),W=n%T===0,K=a%A===0,q=i%R===0,ee=g?[k,4,4]:[1,1,1],P=[{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}];zr(e,P),P.push(...he(t[0].dims,t[1].dims));let J=["rank","rank"];s&&(P.push(...he(t[2].dims)),J.push("rank")),P.push(...he(r));let te=F=>{let O=[{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}];Pr(e,O);let G=g?4:1,ie=it(t[0].dataType),j=` - fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${ie}>`:ie}) { - result[flatIndex] = ${g?`vec4<${ie}>`:ie}(value); - } - fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${ie}>`:ie}) { - let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); - setOutputAtIndex(flatIndex ${g?"/ 4":""}, value); - }`,se=Y("x",t[0].dataType,t[0].dims.length,k===3?1:k),L=Y("w",t[1].dataType,t[1].dims.length,G),ne=[se,L],me=pe("result",t[0].dataType,r.length,G);if(s){let Pe=Y("bias",t[2].dataType,t[2].dims.length,G);ne.push(Pe),j+=` - fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${ie}>`:ie} { - return bias[coords.${l?"w":"y"}${g?"/ 4":""}]; - }`}return` - ${lo("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 }; - ${F.registerUniforms(O).declareVariables(...ne,me)} - ${j} - ${cu(l,W,K,q,s,e,ee[0],ee[1],ee[2],ie)} - ${g?si(y,$,ie,void 0,!l,R):oi(y,$,ie,void 0,!l,R,!1,void 0,o)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${k};${g};${W};${K};${q};${T};${A};${R}`,inputDependencies:J},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:P}),getShaderSource:te}}}),Is,Oh,q_=X(()=>{ye(),Te(),Ce(),Rh(),Br(),Is=(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=ja(i,s,e.dilations,e.pads,e.strides,l),c=Q.size(d),u=[{type:12,data:c},{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}];zr(e,u),u.push(...he(i,s,d));let h=["rank","rank"];n&&(u.push(...he(t[2].dims)),h.push("rank")),u.push(...he(d));let m=g=>{let _=pe("output",t[0].dataType,d.length),b=it(_.type.tensor),$=Or(e,_.type.value,b),y=Y("x",t[0].dataType,i.length),E=Y("w",t[1].dataType,s.length),k=[y,E];n&&k.push(Y("b",t[2].dataType,t[2].dims));let T=[{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 Pr(e,T),` - ${g.registerUniforms(T).declareVariables(...k,_)} - - ${g.mainStart()} - ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let outputIndices = ${_.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: ${_.type.value} = ${_.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?y.get("batch","xHeight","xWidth","input_channel"):y.get("batch","input_channel","xHeight","xWidth")}; - let wVal = ${E.get("output_channel","wInChannel","wHeight","wWidth")}; - value += xVal*wVal; - } - } - } - ${a} - ${$} - ${_.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(c/64)},programUniforms:u}),getShaderSource:m}},Oh=(t,e,r)=>{let n=t.length>2,a=rt(r[3]),i=rt(r[2]),s=Q.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],c=[{type:12,data:s},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];zr(e,c),c.push(...he(o,l,d));let u=(i-1)*e.strides[1]+l[1],h=m=>{let g=pe("output",t[0].dataType,d.length,a),_=it(g.type.tensor),b=Or(e,g.type.value,_),$=Y("x",t[0].dataType,o.length,a),y=Y("w",t[1].dataType,l.length,a),E=[$,y];n&&E.push(Y("b",t[2].dataType,t[2].dims,a));let k=n?"value += b[output_channel];":"",T=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Pr(e,T),` - ${m.registerUniforms(T).declareVariables(...E,g)} - ${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<${$.type.value}, ${u}>; - var values: array<${g.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] = ${$.get("batch","u32(x_height)","u32(x_width)","input_channel")}; - } else { - x_vals[i] = ${$.type.value}(0); - } - } - for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) { - let w_val = ${y.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]; - ${k} - ${b} - ${g.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:c}),getShaderSource:h}}}),As,pu,zh,Ph=X(()=>{ye(),Te(),fi(),Ce(),Br(),As=(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],c=rt(l),u=rt(d),h=rt(o),m=Q.size(r)/c/h,g=t.length>2,_=n?n.slice(0,-2):r.slice(0,-2),b=[Q.size(_),o,l],$=[{type:12,data:m},{type:12,data:o},{type:12,data:l},{type:12,data:d}];zr(e,$),$.push(...he(_,i,s)),g&&$.push(...he(t[2].dims)),$.push(...he(b));let y=E=>{let k=ro("batch_dims",t[0].dataType,_.length),T=Y("a",t[0].dataType,i.length,u),A=Y("b",t[1].dataType,s.length,c),R=pe("output",t[0].dataType,b.length,c),W=it(R.type.tensor),K=Or(e,R.type.value,W),q=[T,A],ee="";if(g){let j=a?c:1;q.push(Y("bias",t[2].dataType,t[2].dims.length,j)),ee=`${a?`value += bias[col / ${j}];`:`value += ${R.type.value}(bias[row + i]);`}`}let P=i.slice(0,-2),J=s.slice(0,-2),te=Ln(P,_),F=Ln(J,_),O=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Pr(e,O);let G=(j,se)=>{let L=j.rank,ne=j.name;if(L===2)return`var ${ne}_indices = ${j.type.indices}(0u, 0u);`;let me=k.rank,Pe=`var ${ne}_indices: ${j.type.indices};`;for(let Re=L-2-1,nt=me-1;Re>=0;Re--,nt--)Pe+=` -${ne}_indices[${Re}] = ${me>1?`batch_indices[${nt}]`:"batch_indices"};`;return se.forEach(Re=>{Pe+=` -${ne}_indices[${Re}] = 0;`}),Pe+=`${ne}_indices[${L-2}] = 0u; - ${ne}_indices[${L-1}] = 0u;`,Pe},ie=()=>{let j=`var a_data: ${T.type.value};`;for(let se=0;se; - for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { - ${ie()} - } - for (var i = 0u; i < ${h}u; i++) { - var value = values[i]; - ${ee} - ${K} - let cur_indices = ${R.type.indices}(batch, row + i, col); - let offset = ${R.indicesToOffset("cur_indices")}; - ${R.setByOffset(`offset / ${c}`,"value")}; - } - } - `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${c};${u};${h};${a}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:$}),getShaderSource:y}},pu=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.")},zh=t=>{pu(t.inputs);let e=Xr.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(As(t.inputs,{activation:""},e)):t.compute(uo(t.inputs,{activation:""},e))}}),ja,Oa,hu,qi,Ms,fu,mu,Os,Rh=X(()=>{Te(),H_(),fi(),q_(),Br(),Ph(),jn(),ja=(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],c=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-c[m]+a[m])/a[m]));return u.splice(0,0,s),u.splice(i?3:1,0,d),u},Oa=[2,3,1,0],hu=(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")},qi=(t,e)=>{let r=t.kernelShape.slice();for(let i=2;i{let e=io(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};`}},fu=(t,e,r)=>{let n=qi(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=ja(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),R=t.kernelCustomData.wT??t.compute(er(e[1],Oa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=R);let W=[e[0],R];e.length===3&&W.push(e[2]),t.compute(Oh(W,n,A),{inputs:W})}else t.compute(Is(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],c=e[1].dims[3],u=ja(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),h=u[a?1:2],m=u[a?2:3],g=u[a?3:1],_=a&&d===s&&c===o&&r.pads[0]===0&&r.pads[1]===0;if(_||d===1&&c===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],R,W,K,q=[];if(a){let J=t.kernelCustomData.wT??t.compute(er(e[1],Oa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=J),_){let te=s*o*l;R=e[0].reshape([1,A,te]),W=J.reshape([1,te,g]),K=[1,A,g]}else R=e[0].reshape([A,s*o,l]),W=J.reshape([1,l,g]),K=[A,h*m,g];q.push(R),q.push(W)}else R=e[0].reshape([A,l,s*o]),W=e[1].reshape([1,g,l]),K=[A,g,h*m],q.push(W),q.push(R);i&&q.push(e[2]);let ee=K[2],P=q[0].dims[q[0].dims.length-1];ee<8&&P<8?t.compute(As(q,n,u,K,a),{inputs:q}):t.compute(uo(q,n,u,K,a),{inputs:q});return}let b=!0,$=t.kernelCustomData.wT??t.compute(er(e[1],Oa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=$);let y=[e[0],$];i&&y.push(e[2]);let E=a?h*m:g,k=a?g:h*m,T=d*c*l;t.compute(Mh(y,n,u,E,k,T,i,b),{inputs:y})},mu=(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=qi({...e,pads:a,strides:i,dilations:s,kernelShape:o},n);t.compute(Is(n,l,d=>r?[d[0],d[2],d[3]]:[]))},Os=(t,e)=>{hu(t.inputs,e),t.inputs[0].dims.length===3?mu(t,e):fu(t,t.inputs,e)}}),gu,Bh,j_=X(()=>{ye(),Rr(),Ce(),Br(),oo(),Ah(),fi(),gu=(t,e=!1,r,n,a=4)=>{let i=b=>{switch(b){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 ${b} 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])",c=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 = ${c} / outWidth; - let outCol = ${c} % 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);`,g=` - 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); - `,_=Or(r,n);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { - ${t?m:g} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { - ${t?g: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} - ${so(e)} - ${_} - result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${a}] = value; - } - }`},Bh=(t,e,r,n,a,i,s,o)=>{let l=e.format==="NHWC",d=l?t[0].dims[3]:t[0].dims[1],c=r[0],u=l?r[2]:r[3],h=l?r[1]:r[2],m=l?r[3]:r[1],g=l?d%4===0&&m%4===0:u%4===0&&m%4===0,_=l?m:u*h,b=l?u*h:m,$=g?[8,8,1]:[_<=4||b<=4?4:16,_>4&&b<=4?4:16,1],y=g?[4,4,1]:[_<=4?1:4,_>4&&b<=4?1:4,1],E=[Math.ceil(_/$[0]/y[0]),Math.ceil(b/$[1]/y[1]),Math.ceil(c/$[2]/y[2])];et("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let k=g?4:1,T=Math.max($[0]*k,$[1]),A=g?4:1,R=[e.kernelShape[l?1:2],e.kernelShape[l?2:3]],W=[R[0]+(e.dilations[0]<=1?0:(R[0]-1)*(e.dilations[0]-1)),R[1]+(e.dilations[1]<=1?0:(R[1]-1)*(e.dilations[1]-1))],K=[W[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),W[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],q=[{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:R},{type:6,data:K}];zr(e,q),q.push(...he(t[0].dims,t[1].dims));let ee=["rank","rank"];s&&(q.push(...he(t[2].dims)),ee.push("rank")),q.push(...he(r));let P=J=>{let te=Y("x",t[0].dataType,t[0].dims.length,A),F=Y("w",t[1].dataType,t[1].dims.length,1),O=pe("result",t[0].dataType,r.length,A),G=[te,F],ie="";if(s){let L=Y("bias",t[2].dataType,t[2].dims.length,A);G.push(L),ie+=` - fn getBiasByOutputCoords(coords : vec4) -> ${L.type.value} { - return bias[coords.${l?"w":"y"}${g?"/ 4":""}]; - }`}let j=[{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:R.length},{name:"pads",type:"i32",length:K.length}];Pr(e,j);let se=it(t[0].dataType,1);if(se!=="f16"&&se!=="f32")throw new Error(`elemType ${se} is not supported.`);return` - ${lo("uniforms.result_strides")} - ${J.registerUniforms(j).declareVariables(...G,O)}; - ${ie} - ${gu(l,s,e,te.type.value,k)} - ${g?si(y,$,se,void 0,!l,T):oi(y,$,se,void 0,!l,T,!1,void 0,o)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${e.cacheKey};${y};${$};${g}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:q}),getShaderSource:P}}}),_u,zs,K_=X(()=>{ye(),Rr(),Te(),Ce(),_u=(t,e,r,n,a,i=!1,s,o,l=!1)=>{let d=l?1:2,c=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 g=i?4:1,_=Y("W",e[1].dataType,e[1].dims.length,g),b=Y("Dy",e[0].dataType,e[0].dims.length,g),$=[b,_];n&&$.push(Y("bias",e[2].dataType,[r[u]].length,g));let y=pe("result",e[0].dataType,r.length,g),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 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${b.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 = ${b.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 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${b.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 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${_.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${b.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)`}; - ${y.set("batch","r","c + i","d1","value")}; - } - }`,k=` - let outputIndices = ${y.offsetToIndices("global_idx")}; - let batch = ${y.indicesGet("outputIndices",0)}; - let d1 = ${y.indicesGet("outputIndices",u)}; - let r = ${y.indicesGet("outputIndices",d)}; - let c = ${y.indicesGet("outputIndices",c)}; - 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[${c}]) || - 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?b.get("batch","idyR","idyC","inputChannel"):b.get("batch","inputChannel","idyR","idyC")}; - let wValue = ${_.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; - dotProd = dotProd + xValue * wValue; - inputChannel = inputChannel + 1; - } - } - } - let value = dotProd + ${n?"bias[d1]":`${s}(0.0)`}; - ${y.setByOffset("global_idx","value")}; - `;return` - ${t.registerUniforms(o).declareVariables(...$,y)} - ${m} - - ${t.mainStart()} - ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${i?E:k}}`},zs=(t,e,r)=>{let n=t.length>2,a=e.outputShape,i=Q.size(a),s=[Math.ceil(i/64),1,1];et("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let o=e.format==="NHWC",l=["rank","rank"],d=[e.strides[0],e.strides[1]],c=[e.kernelShape[o?1:2],e.kernelShape[o?2:3]],u=[e.dilations[0],e.dilations[1]],h=[c[0]+(e.dilations[0]<=1?0:(e.kernelShape[o?1:2]-1)*(e.dilations[0]-1)),c[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],g=!1,_=e.group,b=t[1].dims,$=b[0]/_,y=b[1],E=[{type:6,data:i},{type:12,data:d},{type:12,data:c},{type:12,data:u},{type:12,data:h},{type:6,data:m},{type:12,data:$},{type:12,data:y},...he(t[0].dims,t[1].dims)];n&&(E.push(...he(t[2].dims)),l.push("rank")),E.push(...he(a));let k=s[1]===1&&s[2]===1,T=A=>{let R=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:d.length},{name:"filter_dims",type:"u32",length:c.length},{name:"dilations",type:"u32",length:c.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"}],W=it(t[0].dataType);return`${_u(A,t,a,n,k,g,W,R,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:T}}}),wu,yu,bu,ji,Dh,vu,$u,xu,Su,Nh,Y_=X(()=>{j_(),K_(),Br(),jn(),wu=(t,e,r,n,a,i)=>(t-1)*e+r+(n-1)*a+1-i,yu=(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)},bu=(t,e,r,n,a,i,s,o,l,d)=>{let c=t.length-2,u=d.length===0;if(l.length===0)for(let g=0;g{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)}bu(o,r,l,t.autoPad,t.group,a,d,n,s,i);let c=Object.assign({},t);return Object.assign(c,{kernelShape:r,pads:a,outputPadding:s,outputShape:i,dilations:l,strides:d}),c},Dh=t=>{let e=io(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(),c=t.outputPadding,u=t.outputShape;return{autoPad:n,format:r,dilations:a,group:i,kernelShape:s,outputPadding:c,outputShape:u,pads:o,strides:l,wIsConst:d,...e,cacheKey:`${t.format};${e.activation};`}},vu=(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")},$u=[2,3,1,0],xu=(t,e,r)=>{let n=ji(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(zs(e,n));return}let l=i[a?1:2],d=i[a?2:3],c=e[1].dims[2],u=e[1].dims[3],h=a?l*d:s,m=a?s:l*d,g=c*u*o,_=!0,b=t.kernelCustomData.wT??t.compute(er(e[1],$u),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=b);let $=[e[0],b],y=e.length===3;y&&(!a&&e[2].dims.length===1?$.push(e[2].reshape([e[2].dims[0],1,1])):$.push(e[2])),t.compute(Bh($,n,i,h,m,g,y,_),{inputs:$})},Su=(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=ji({...e,pads:o,strides:s,dilations:i,kernelShape:a},n);t.compute(zs(n,l,d=>r?[d[0],d[2],d[3]]:[d[0],d[1],d[3]]))},Nh=(t,e)=>{vu(t.inputs,e),t.inputs[0].dims.length===3?Su(t,e):xu(t,t.inputs,e)}}),Eu,Lh,Uh,X_=X(()=>{ye(),Te(),ut(),Ce(),Eu=(t,e,r,n)=>{let a=Q.size(e),i=e.length,s=Y("input",t,i),o=pe("output",t,i),l=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),d=Q.normalizeAxis(l,i),c=u=>{let h=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,m=we("uniforms.input_shape","uniforms.axis",i),g=n.reverse?h+(n.exclusive?" + 1":""):"0",_=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 = ${g}; - let last : i32 = ${_}; - 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},...he(e,e)]}),getShaderSource:c}},Lh=(t,e)=>{let r=t.inputs[0].dims,n=t.inputs[0].dataType,a=t.inputs[1];t.compute(Eu(n,r,a,e),{inputs:[0]})},Uh=t=>{let e=t.exclusive===1,r=t.reverse===1;return qe({exclusive:e,reverse:r})}}),za,xn,Ki,ku,Cu,Tu,Iu,Yi,Au,Fh,Wh,Q_=X(()=>{ye(),Te(),ut(),Ce(),za="[a-zA-Z]|\\.\\.\\.",xn="("+za+")+",Ki="^"+xn+"$",ku="("+xn+",)*"+xn,Cu="^"+ku+"$",Tu=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)}},Iu=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(Cu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let s=t[i].dims.slice();if(!a.match(RegExp(Ki)))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(xn)))throw new Error("Invalid RHS");n.match(RegExp(za,"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(Ki))&&!e&&t!=="")throw new Error("Invalid LHS term");let l=t.match(RegExp(za,"g")),d=new Tu(n);return l?.forEach((c,u)=>{if(c==="..."){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",Au=(t,e,r,n)=>{let a=t.map(d=>d.length).map((d,c)=>Y(`input${c}`,e,d)),i=Q.size(n),s=pe("output",e,n.length),o=[...r.symbolToInfo.keys()].filter(d=>!r.rhs.symbolToIndices.has(d)),l=d=>{let c=[],u="var prod = 1.0;",h="var sum = 0.0;",m="sum += prod;",g=[],_=[],b=[],$=[],y=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((k,T)=>{if(r.rhs.symbolToIndices.has(T)){let A=r.rhs.symbolToIndices.get(T)?.[0];A!==void 0&&r.lhs.forEach((R,W)=>{if(k.inputIndices.includes(W)){let K=R.symbolToIndices.get(T);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(q=>{c.push(`${a[W].indicesSet(`input${W}Indices`,q,s.indicesGet("outputIndices",A))}`)})}})}else r.lhs.forEach((A,R)=>{if(k.inputIndices.includes(R)){let W=A.symbolToIndices.get(T);if(W===void 0)throw new Error("Invalid symbol error");W.forEach(K=>{g.push(`${a[R].indicesSet(`input${R}Indices`,K,`${T}`)}`)}),$.push(`prod *= ${a[R].getByIndices(`input${R}Indices`)};`)}}),_.push(`for(var ${T}: u32 = 0; ${T} < uniforms.${Yi(T)}; ${T}++) {`),b.push("}")});let E=y?[...c,`let sum = ${a.map((k,T)=>k.getByIndices(`input${T}Indices`)).join(" * ")};`]:[...c,h,..._,...g,u,...$,m,...b];return` - ${d.registerUniforms(o.map(k=>({name:`${Yi(k)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...a,s)} - - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${s.offsetToIndices("global_idx")}; - ${a.map((k,T)=>`var input${T}Indices: ${a[T].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 c=t.map((u,h)=>[...he(u)]).reduce((u,h)=>u.concat(h),d);return c.push(...he(n)),{outputs:[{dims:n,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c}},getShaderSource:l}},Fh=(t,e)=>{let r=new Iu(t.inputs,e.equation),n=r.outputDims,a=t.inputs.map((i,s)=>i.dims);t.compute(Au(a,t.inputs[0].dataType,r,n))},Wh=t=>{let e=t.equation.replace(/\s+/g,"");return qe({equation:e})}}),Mu,Xi,Ou,zu,Gh,Z_=X(()=>{ye(),Te(),Ce(),Mu=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?Xi(t,e):Xi(e,t),zu=t=>{let e=t[0].dims,r=Array.from(t[1].getBigInt64Array(),Number),n=Ou(e,r),a=t[0].dataType,i=a===9?4:1,s=Math.ceil(Q.size(n)/i),o=d=>{let c=Y("input",a,e.length,i),u=pe("output",a,n.length,i),h;if(a===9){let m=(g,_,b="")=>` - let outputIndices${_} = ${u.offsetToIndices(`outputOffset + ${_}u`)}; - let offset${_} = ${c.broadcastedIndicesToOffset(`outputIndices${_}`,u)}; - let index${_} = offset${_} / 4u; - let component${_} = offset${_} % 4u; - ${g}[${_}] = ${b}(${c.getByOffset(`index${_}`)}[component${_}]); - `;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 = ${c.broadcastedIndicesToOffset("outputIndices",u)}; - ${u.setByOffset("global_idx",c.getByOffset("inputOffset"))} - }`;return` - ${d.registerUniform("vec_size","u32").declareVariables(c,u)} - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${h}`},l=[{type:12,data:s},...he(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})}},Gh=t=>{Mu(t.inputs),t.compute(zu(t.inputs),{inputs:[0]})}}),Pu,Vh,J_=X(()=>{ye(),Te(),Ce(),ao(),Pu=t=>{let e=t[0].dataType,r=Q.size(t[0].dims),n=Q.size(t[1].dims),a=n%4===0,i=s=>{let o=Y("x",e,[1],4),l=Y("bias",e,[1],4),d=pe("y",e,[1],4),c=[{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(c).declareVariables(o,l,d)} - - ${Cs(Ct(e))} - - ${s.mainStart(ni)} - ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} - - let x = ${o.getByOffset("global_idx")}; - ${h} - let x_in = x + bias; - ${d.setByOffset("global_idx",Ts("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/ni/4)}})}},Vh=t=>{t.inputs.length<2||Q.size(t.inputs[1].dims)===0?fh(t):t.compute(Pu(t.inputs))}}),Ru,Bu,Hh,qh,e0=X(()=>{ye(),Te(),ut(),Ce(),Ru=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},Bu=(t,e)=>{let r=t[0].dims,n=t[1].dims,a=r.length,i=Q.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(Q.size(s)/l),c=[{type:12,data:d},{type:6,data:o},{type:12,data:i},...he(t[0].dims,t[1].dims,s)],u=h=>{let m=Y("data",t[0].dataType,t[0].dims.length,l),g=Y("inputIndices",t[1].dataType,t[1].dims.length),_=pe("output",t[0].dataType,s.length,l),b=y=>{let E=n.length,k=`var indicesIndices${y} = ${g.type.indices}(0);`;for(let T=0;T1?`indicesIndices${y}[${T}]`:`indicesIndices${y}`} = ${s.length>1?`outputIndices${y}[uniforms.axis + ${T}]`:`outputIndices${y}`};`;k+=` - var idx${y} = ${g.getByIndices(`indicesIndices${y}`)}; - if (idx${y} < 0) { - idx${y} = idx${y} + uniforms.axisDimLimit; - } - var dataIndices${y} : ${m.type.indices}; - `;for(let T=0,A=0;T1?`dataIndices${y}[${T}]`:`dataIndices${y}`} = u32(idx${y});`,A+=E):(k+=`${a>1?`dataIndices${y}[${T}]`:`dataIndices${y}`} = ${s.length>1?`outputIndices${y}[${A}]`:`outputIndices${y}`};`,A++);return k},$;if(t[0].dataType===9){let y=(E,k,T="")=>` - let outputIndices${k} = ${_.offsetToIndices(`outputOffset + ${k}u`)}; - ${b(k)}; - let offset${k} = ${m.indicesToOffset(`dataIndices${k}`)}; - let index${k} = offset${k} / 4u; - let component${k} = offset${k} % 4u; - ${E}[${k}] = ${T}(${m.getByOffset(`index${k}`)}[component${k}]); - `;$=` - let outputOffset = global_idx * ${l}; - var value = vec4(0); - ${y("value",0,"u32")} - ${y("value",1,"u32")} - ${y("value",2,"u32")} - ${y("value",3,"u32")} - ${_.setByOffset("global_idx","value")} - `}else $=` - let outputIndices = ${_.offsetToIndices("global_idx")}; - ${b("")}; - let value = ${m.getByIndices("dataIndices")}; - ${_.setByOffset("global_idx","value")}; - `;return` - ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,g,_)} - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${$} - }`};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:c}),getShaderSource:u}},Hh=t=>qe({axis:t.axis}),qh=(t,e)=>{let r=t.inputs;Ru(r),t.compute(Bu(t.inputs,e))}}),Du,Nu,jh,Kh,t0=X(()=>{ye(),Te(),ut(),Ce(),Du=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.`)},Nu=(t,e)=>{let r=t[0].dims,n=t[0].dataType,a=r.length,i=t[1].dims,s=t[1].dataType,o=Q.normalizeAxis(e.axis,a),l=r[o],d=i.slice(0),c=Q.size(d),u=Y("input",n,a),h=Y("indicesInput",s,i.length),m=pe("output",n,d.length),g=[{type:12,data:c},{type:6,data:l},{type:12,data:o}];return g.push(...he(r,i,d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:_=>` - ${_.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,h,m)} - ${_.mainStart()} - ${_.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")}; - }`}},jh=t=>qe({axis:t.axis}),Kh=(t,e)=>{let r=t.inputs;Du(r),t.compute(Nu(t.inputs,e))}}),Lu,Uu,Yh,Xh,r0=X(()=>{ye(),Te(),Ce(),Lu=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")},Uu=(t,e)=>{let r=t[0].dims.slice(),n=t[1].dims.slice(),[a,i,s]=op.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=Q.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}],c=["type","type"];t.length===3&&(d.push(...he(t[2].dims)),c.push("rank")),d.push(...he(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 g=e.alpha===1?"":"value *= uniforms.alpha;",_=Y("a",t[0].dataType,t[0].dims),b=Y("b",t[1].dataType,t[1].dims),$=_.type.value,y=null,E=[_,b];t.length===3&&(y=Y("c",t[2].dataType,t[2].dims.length),E.push(y));let k=pe("output",t[0].dataType,o.length);E.push(k);let T=[{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(T).declareVariables(...E)} - - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let m = global_idx / uniforms.N; - let n = global_idx % uniforms.N; - - var value = ${$}(0); - for (var k: u32 = 0u; k < uniforms.K; k++) { - ${m} - } - - ${g} - ${y!=null?`let cOffset = ${y.broadcastedIndicesToOffset("vec2(m, n)",k)}; value += ${$}(uniforms.beta) * ${y.getByOffset("cOffset")};`:""} - output[global_idx] = value; - }`};return{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},Yh=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}`}},Xh=(t,e)=>{Lu(t.inputs),t.compute(Uu(t.inputs,e))}}),Fu,Wu,Gu,Qh,n0=X(()=>{ye(),Te(),Ce(),Fu=(t,e)=>{let r=t[0].dims,n=r,a=2,i=Q.sizeToDimension(r,a),s=Q.sizeFromDimension(r,a),o=rt(s),l=s/o,d=[r[0],r[1],l],c=["rank","type","type"],u=[{type:12,data:s},{type:12,data:l}];u.push(...he(d,d));let h=m=>{let g=Y("x",t[0].dataType,d.length,o),_=Y("scale",t[1].dataType,t[1].dims),b=Y("bias",t[2].dataType,t[2].dims),$=pe("output",t[0].dataType,d.length,o),y=[g,_,b,$],E=g.type.value,k=o===1?"f32":`vec${o}`,T=64,A=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` - var meanShared : f32; - var squaredNormShared : f32; - var workgroupShared : array<${k}, ${T}>; - const workgroupSize = ${T}u; - ${m.registerUniforms(A).declareVariables(...y)} - ${m.mainStart(T)} - 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 = ${k}(0); - for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { - initial = initial + ${k}(${g.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 = ${Kt("workgroupShared[0]",o)} / f32(uniforms.normSize); - } - workgroupBarrier(); - - // reinitialize workgroup memory. - initial = ${k}(0); - for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { - let deviation = ${k}(${g.get("batch","channel","h")}) - ${k}(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 = ${Kt("workgroupShared[0]",o)}; - } - workgroupBarrier(); - - let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); - let channelScale = invStdDev * f32(${_.getByOffset("channel")}); - let channelShift = f32(${b.getByOffset("channel")}) - meanShared * channelScale; - for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { - let value = ${g.get("batch","channel","h")} * ${E}(${k}(channelScale)) + ${E}(${k}(channelShift)); - ${$.set("batch","channel","h","value")}; - } - }`};return{name:"InstanceNormalization",shaderCache:{hint:`${e.epsilon};${o}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:i},programUniforms:u}),getShaderSource:h}},Wu=(t,e,r,n,a,i,s,o)=>{let l=rt(s),d=64,c=l===1?"vec2f":`mat2x${l}f`,u=l===1?"f32":`vec${l}f`,h=(A,R)=>`${c}(${A}, ${R})`,m=a*s/l,g=Math.ceil(i/d),_=["type"],b=[{type:12,data:g},{type:12,data:i},{type:12,data:Math.floor(s/l)},{type:12,data:Math.floor(i*s/l)}],$=A=>{let R=Y("input",e.dataType,e.dims,l);return` - ${A.declareVariables(R)} - @group(0) @binding(1) var output : array<${c}>; - 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 = ${bt("f32",l)}; - var squaredSum = ${bt("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")}; - }`},y=t.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:[a,s,d,2],dataType:1}],dispatchGroup:{x:a*s/l},programUniforms:b}),getShaderSource:$},{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)}],k=["type","type","type"],T=A=>{let R=Y("scale",r.dataType,r.dims,l),W=Y("bias",n.dataType,n.dims,l);return` - @group(0) @binding(0) var input : array<${c}>; - @group(0) @binding(1) var scale : array<${R.type.storage}>; - @group(0) @binding(2) var bias : array<${W.type.storage}>; - @group(0) @binding(3) var output : array<${c}>; - 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 = ${bt("f32",l)}; - var squaredSum = ${bt("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:k},getRunData:()=>({outputs:[{dims:[a,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:E}),getShaderSource:T},{inputs:[y,r,n],outputs:[-1]})[0]},Gu=(t,e,r)=>{let n=e[0].dims,a=n,i=n[0],s=n[n.length-1],o=Q.sizeFromDimension(n,1)/s,l=rt(s),d=Q.size(a)/l,c=[{type:12,data:o},{type:12,data:Math.floor(s/l)}],u=["type","type"],h=Wu(t,e[0],e[1],e[2],i,o,s,r.epsilon),m=g=>{let _=it(e[0].dataType),b=l===1?"vec2f":`mat2x${l}f`,$=l===1?_:`vec${l}<${_}>`,y=Y("input",e[0].dataType,e[0].dims,l),E=pe("output",e[0].dataType,a,l);return` - @group(0) @binding(0) var input : array<${y.type.storage}>; - @group(0) @binding(1) var scaleInput : array<${b}>; - @group(0) @binding(2) var output : array<${E.type.storage}>; - struct Uniforms {H: u32, C : u32}; - @group(0) @binding(3) var uniforms: Uniforms; - - ${g.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], ${$}(scale[0]), ${$}(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:c}),getShaderSource:m},{inputs:[e[0],h]})},Qh=(t,e)=>{e.format==="NHWC"?Gu(t,t.inputs,e):t.compute(Fu(t.inputs,e))}}),Vu,Hu,Zh,a0=X(()=>{ye(),Te(),Ce(),Vu=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Hu=(t,e,r)=>{let n=t[0].dims,a=t[1],i=t[2],s=n,o=Q.normalizeAxis(e.axis,n.length),l=Q.sizeToDimension(n,o),d=Q.sizeFromDimension(n,o),c=Q.size(a.dims),u=i?Q.size(i.dims):0;if(c!==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 ${c} and bias size of ${u}`);let h=[];for(let k=0;k1,$=r>2,y=k=>{let T=it(t[0].dataType),A=[Y("x",t[0].dataType,t[0].dims,m),Y("scale",a.dataType,a.dims,m)];i&&A.push(Y("bias",i.dataType,i.dims,m)),A.push(pe("output",t[0].dataType,s,m)),b&&A.push(pe("mean_data_output",1,h)),$&&A.push(pe("inv_std_output",1,h));let R=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` - ${k.registerUniforms(R).declareVariables(...A)} - ${k.mainStart()} - ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} - let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${bt("f32",m)}; - var mean_square_vector = ${bt("f32",m)}; - - for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${Zt(T,m,"x[h + offset]")}; - mean_vector += value; - mean_square_vector += value * value; - } - let mean = ${Kt("mean_vector",m)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${Kt("mean_square_vector",m)} / uniforms.norm_size - mean * mean + uniforms.epsilon); - - for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { - let f32input = ${Zt(T,m,"x[j + offset]")}; - let f32scale = ${Zt(T,m,"scale[j]")}; - output[j + offset] = ${A[0].type.value}((f32input - mean) * inv_std_dev * f32scale - ${i?`+ ${Zt(T,m,"bias[j]")}`:""} - ); - } - - ${b?"mean_data_output[global_idx] = mean":""}; - ${$?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},E=[{dims:s,dataType:t[0].dataType}];return b&&E.push({dims:h,dataType:1}),$&&E.push({dims:h,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${m};${r}`,inputDependencies:g},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:_}),getShaderSource:y}},Zh=(t,e)=>{Vu(t.inputs),t.compute(Hu(t.inputs,e,t.outputCount))}}),qu,ju,Jh,ef,i0=X(()=>{ye(),Te(),ut(),Ce(),qu=(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(!Q.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(Q.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(Q.size(l)!==d)throw new Error("zeroPoints input size error.")}},ju=(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=rt(i),l=rt(e.n),d=rt(e.k),c=rt(s),u=Q.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 g=Q.convertShape(t[1].dims).slice();g.splice(-1,1,s/c),h.push(...he(m)),h.push(...he(g)),h.push(...he(t[2].dims)),t.length===4&&h.push(...he(Q.convertShape(t[3].dims)));let _=a.slice();_.splice(-1,1,e.n/l),h.push(...he(_));let b=$=>{let y=Y("a",t[0].dataType,m.length,d),E=Y("b",12,g.length,c),k=Y("scales",t[2].dataType,t[2].dims.length),T=[y,E,k],A=t.length===4?Y("zero_points",12,t[3].dims.length):void 0;A&&T.push(A);let R=pe("output",t[0].dataType,a.length,l),W=[{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"}],K=Math.floor((e.k+e.blockSize-1)/e.blockSize),q=it(t[0].dataType),ee=(()=>{switch(d){case 1:return`array<${q}, 8>`;case 2:return`mat4x2<${q}>`;case 4:return`mat2x4<${q}>`;default:throw new Error(`${d}-component is not supported.`)}})(),P=` - fn dequantize(quantized: ${ee}, zero_point: ${q}, scale: ${q}) -> ${ee} { - ${d===1?`var dequantized = ${ee}(${Array.from({length:8},(F,O)=>`(quantized[${O}] - zero_point) * scale`).join(", ")}); - return dequantized;`:`var zero_points: ${ee} = ${ee}(${Array(8).fill("zero_point").join(",")}); - return (quantized - zero_points) * scale;`} - }`,J=` - fn ortUnpack8x4snorm(value: u32) -> ${ee} { - var quantized: ${ee}; - var offset: u32 = 0; - let count: u32 = 4; - for (var i: u32 = 0; i < 8u; i++) { - var result = ${q}(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; - }`,te=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` - ${P}; - ${J}; - ${$.registerUniforms(W).declareVariables(...T,R)} - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var output_values: array<${R.type.value}, ${o}>; - var output_indices = ${R.offsetToIndices("global_idx")}; - var n = ${R.indicesGet("output_indices",n-1)}; - var m = ${R.indicesGet("output_indices",n-2)}; - var a_indices: ${y.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} * ((${K} + 1) / 2) / 4; - var zero_point_word: u32 = ${A.getByOffset("zero_point_index")}; - var zero_point_offset: u32 = 0;`:""} - var scale_index = n * ${K*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 < ${K}; block++) { - // The scale and zero points are computed per block. - let scale = ${k.getByOffset("scale_index")}; - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${q}(${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 += ${c}) { - ${E.indicesSet("b_indices","2","word")}; - let b_data = ${E.getByIndices("b_indices")}; - for (var i: u32 = 0; i < ${c}; i++) { - let b_value = ${c===1?"b_data":"b_data[word + i]"}; - let b_quantized_values: ${ee} = 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++) { - ${y.indicesSet("a_indices",n-1,`offset/${d}`)}; - for (var k: u32 = 0; k < ${o}u; k++) { - ${y.indicesSet("a_indices",n-2,`m * ${o} + k`)}; - let a_data = ${y.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++; - ${te} - 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) { - ${te} - }`:""} - } - for (var k: u32 = 0u; k < ${o}u; k++) { - ${R.indicesSet("output_indices",n-2,`${o+" * m + k"}`)}; - ${R.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:b}},Jh=(t,e)=>{qu(t.inputs,e),t.compute(ju(t.inputs,e))},ef=t=>qe(t)}),Ku,tf,Qi,Yu,Pa,rf,s0=X(()=>{ye(),Te(),ut(),Js(),Pp(),Ce(),jn(),Ku=(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 c=!1,u=r.dims[0],h=r.dims[1],m=r.dims.length===3?c?r.dims[2]/3:r.dims[2]:e.numHeads*r.dims[4],g=h,_=0,b=0,$=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');_=l.dims[2],b=l.dims[2]}else if(l||d)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let y;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)');y=2,g=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==e.numHeads||n.dims[3]!==2||n.dims[4]!==$)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');y=5,g=n.dims[1]}else{if(n.dims[1]!==e.numHeads||n.dims[3]!==$)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');y=0,g=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');y=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 W=s.dims;throw W.length===1?W[0]===u?E=1:W[0]===3*u+2&&(E=3):W.length===2&&W[0]===u&&W[1]===g&&(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 k=!1,T=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(g!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');T=a.dims[2]}else{if(g!==a.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');T=a.dims[1]*a.dims[3],k=!0}}let A=_+g,R=!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:_,kvSequenceLength:g,totalSequenceLength:A,maxSequenceLength:b,inputHiddenSize:0,hiddenSize:m,vHiddenSize:T,headSize:$,vHeadSize:Math.floor(T/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:E,scale:e.scale,broadcastResPosBias:R,passPastInKv:k,qkvFormat:y}},tf=t=>qe({...t}),Qi=qe({perm:[0,2,1,3]}),Yu=(t,e,r,n,a,i,s)=>{let o=[n,a,i],l=Q.size(o),d=[{type:12,data:l},{type:12,data:s},{type:12,data:i}],c=u=>{let h=pe("qkv_with_bias",e.dataType,o),m=Y("qkv",e.dataType,o),g=Y("bias",r.dataType,o),_=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${u.registerUniforms(_).declareVariables(m,g,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:c},{inputs:[e,r],outputs:[-1]})[0]},Pa=(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=Yu(t,i,s,e,n,r*a,o),l=l.reshape([e,n,r,a]),t.compute(er(l,Qi.perm),{inputs:[l],outputs:[-1]})[0]}else return i.dims.length===3&&(l=i.reshape([e,n,r,a])),t.compute(er(l,Qi.perm),{inputs:[l],outputs:[-1]})[0]},rf=(t,e)=>{let r=Ku(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=Pa(t,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,t.inputs[0],t.inputs[3],0);if(n)return ii(t,a,t.inputs[1],t.inputs[2],t.inputs[4],void 0,void 0,void 0,t.inputs[5],r,e);let i=Pa(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,t.inputs[1],t.inputs[3],r.hiddenSize),s=Pa(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,t.inputs[2],t.inputs[3],2*r.hiddenSize);ii(t,a,i,s,t.inputs[4],void 0,t.inputs[6],t.inputs[7],t.inputs[5],r,e)}}),Xu,Qu,Zu,Ju,ed,td,rd,nd,nf,o0=X(()=>{ye(),Te(),Ce(),Xu=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].")}},Qu=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` - k = i32(${t.indicesGet("indices",a)}) - ${we("uniforms.pads",a,r)}; - if (k < 0) { - break; - } - if (k >= i32(${we("uniforms.x_shape",a,e)})) { - break; - } - offset += k * i32(${we("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]; - } - `},Zu=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` - k = i32(${t.indicesGet("indices",a)}) - ${we("uniforms.pads",a,r)}; - if (k < 0) { - k = -k; - } - { - let _2n_1 = 2 * (i32(${we("uniforms.x_shape",a,e)}) - 1); - k = k % _2n_1; - if(k >= i32(${we("uniforms.x_shape",a,e)})) { - k = _2n_1 - k; - } - } - offset += k * i32(${we("uniforms.x_strides",a,e)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},Ju=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` - k = i32(${t.indicesGet("indices",a)}) - ${we("uniforms.pads",a,r)}; - if (k < 0) { - k = 0; - } - if (k >= i32(${we("uniforms.x_shape",a,e)})) { - k = i32(${we("uniforms.x_shape",a,e)}) - 1; - } - offset += k * i32(${we("uniforms.x_strides",a,e)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},ed=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` - k = i32(${t.indicesGet("indices",a)}) - ${we("uniforms.pads",a,r)}; - if (k < 0) { - k += i32(${we("uniforms.x_shape",a,e)}]); - } - if (k >= i32(${we("uniforms.x_shape",a,e)})) { - k -= i32(${we("uniforms.x_shape",a,e)}); - } - offset += k * i32(${we("uniforms.x_strides",a,e)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},td=(t,e,r)=>{switch(r.mode){case 0:return Qu(t,e,r.pads.length);case 1:return Zu(t,e,r.pads.length);case 2:return Ju(t,e,r.pads.length);case 3:return ed(t,e,r.pads.length);default:throw new Error("Invalid mode")}},rd=(t,e)=>{let r=Q.padShape(t[0].dims.slice(),e.pads),n=t[0].dims,a=Q.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(...he(t[0].dims,r));let s=["rank"],o=l=>{let d=pe("output",t[0].dataType,r.length),c=Y("x",t[0].dataType,n.length),u=c.type.value,h=td(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(c,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(Q.size(r)/64)},programUniforms:i}),getShaderSource:o}},nd=(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},nf=(t,e)=>{Xu(t.inputs);let r=nd(t.inputs,e);t.compute(rd(t.inputs,r),{inputs:[0]})}}),Sn,Zi,Ji,es,ts,ad,id,rs,ns,af,sf,as,of,lf,is,uf,df,cf,pf,l0=X(()=>{Ft(),ye(),Te(),Ce(),Sn=t=>{if(De.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},Zi=(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();ri.adjustPoolAttributes(r,a,s,o,l,d);let c=ri.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=c.slice();return h.push(h.splice(1,1)[0]),[u,n?h:c]},Ji=(t,e)=>{let r=e.format==="NHWC",n=Q.size(t),a=Q.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],c=e.pads[e.pads.length-1],u=!!(d+c);i.push({type:12,data:o},{type:12,data:l},{type:12,data:d},{type:12,data:c}),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],g=e.strides[e.strides.length-2],_=e.pads[e.pads.length/2-2],b=e.pads[e.pads.length-2];h=!!(_+b),i.push({type:12,data:m},{type:12,data:g},{type:12,data:_},{type:12,data:b}),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=Q.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,c)=>d+c);return[i,s,!!l,!1,!1]}},es=(t,e,r,n,a,i,s,o,l,d,c,u)=>{let h=a.format==="NHWC",m=e.type.value,g=pe("output",e.type.tensor,n);if(a.kernelShape.length<=2){let _="",b="",$="",y=r-(h?2:1);if(c?_=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; - if (xIndices[${y}] < 0 || xIndices[${y}] - >= uniforms.x_shape[${y}]) { - pad++; - continue; - } - let x_val = x[${e.indicesToOffset("xIndices")}]; - ${i} - }`:_=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; - let x_val = x[${e.indicesToOffset("xIndices")}]; - ${i} - }`,a.kernelShape.length===2){let E=r-(h?3:2);u?b=` - 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; - } - `:b=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${E}] = indices[${E}] * uniforms.sh - uniforms.phStart + j; - `,$=` - } - `}return` - ${t.registerUniforms(l).declareVariables(e,g)} - - ${t.mainStart()} - ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let indices = ${g.offsetToIndices("global_idx")}; - var xIndices = ${g.offsetToIndices("global_idx")}; - - var value = ${m}(${o}); - var pad = 0; - ${b} - ${_} - ${$} - ${s} - - output[global_idx] = value; - }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let _=a.kernelShape.length,b=a.pads.length,$="";return d?$=` - if (xIndices[j] >= uniforms.x_shape[j]) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - let x_val = x[${e.indicesToOffset("xIndices")}]; - ${i} - }`:$=` - } - let x_val = x[${e.indicesToOffset("xIndices")}]; - ${i} - `,` - ${t.registerUniforms(l).declareVariables(e,g)} - - ${t.mainStart()} - ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let indices = ${g.offsetToIndices("global_idx")}; - var xIndices = ${g.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 < ${_-1}u; j++) { - offsets[j] = offset / ${we("uniforms.kernelStrides","j",_)}; - offset -= offsets[j] * ${we("uniforms.kernelStrides","j",_)}; - } - offsets[${_-1}] = offset; - - isPad = false; - for (var j = ${r-_}u; j < ${r}u; j++) { - xIndices[j] = indices[j] * ${we("uniforms.strides",`j - ${r-_}u`,_)} - + offsets[j - ${r-_}u] - ${we("uniforms.pads","j - 2u",b)}; - ${$} - } - ${s} - - output[global_idx] = value; - }`}},ts=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,ad=t=>`${ts(t)};${t.countIncludePad}`,id=t=>`${ts(t)};${t.storageOrder};${t.dilations}`,rs=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}),ns=(t,e,r,n)=>{let[a,i]=Zi(e,n,r),s=Y("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[c,u,h,m,g]=Ji(i,a);c.push(...he(e.dims,i));let _=["rank"];return{name:t,shaderCache:{hint:`${n.cacheKey};${h};${m};${g}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(Q.size(i)/64)},programUniforms:c}),getShaderSource:b=>es(b,s,e.dims.length,i.length,a,l,d,0,u,h,m,g)}},af=t=>{let e=t.count_include_pad!==0,r=rs(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:ad(n)}},sf=(t,e)=>{Sn(t.inputs),t.compute(ns("AveragePool",t.inputs[0],!1,e))},as={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},of=t=>{let e=t.format;return{format:e,...as,cacheKey:e}},lf=(t,e)=>{Sn(t.inputs),t.compute(ns("GlobalAveragePool",t.inputs[0],!0,e))},is=(t,e,r,n)=>{let[a,i]=Zi(e,n,r),s=` - value = max(x_val, value); - `,o="",l=Y("x",e.dataType,e.dims.length),d=["rank"],[c,u,h,m,g]=Ji(i,a);return c.push(...he(e.dims,i)),{name:t,shaderCache:{hint:`${n.cacheKey};${h};${m};${g}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(Q.size(i)/64)},programUniforms:c}),getShaderSource:_=>es(_,l,e.dims.length,i.length,a,s,o,e.dataType===10?-65504:-1e5,u,h,m,g)}},uf=(t,e)=>{Sn(t.inputs),t.compute(is("MaxPool",t.inputs[0],!1,e))},df=t=>{let e=t.storage_order,r=t.dilations,n=rs(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:id(a)}},cf=t=>{let e=t.format;return{format:e,...as,cacheKey:e}},pf=(t,e)=>{Sn(t.inputs),t.compute(is("GlobalMaxPool",t.inputs[0],!0,e))}}),sd,od,hf,u0=X(()=>{Ft(),ye(),Ce(),sd=(t,e,r)=>{let n=t===e,a=te&&r>0;if(n||a||i)throw new Error("Range these inputs' contents are invalid.")},od=(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},...he(i)],l=d=>{let c=pe("output",n,i.length),u=c.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` - ${d.registerUniforms(h).declareVariables(c)} - ${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})}},hf=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]),De.webgpu.validateInputContent&&sd(e,r,n),t.compute(od(e,r,n,t.inputs[0].dataType),{inputs:[]})}}),ld,ud,dd,cd,pd,hd,fd,md,gd,_d,wd,ss,yd,bd,vd,$d,xd,ff,mf,d0=X(()=>{ye(),Te(),ut(),Ce(),ld=(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")}},ud=(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},dd=(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(c=>i.push(c));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(c=>n.push(c)),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");ld(n,e),e.axes.length>0&&ud(n,e.axes,d).forEach((c,u)=>n[u]=c)}if(l>0&&t.length>l&&(t[l].getBigInt64Array().forEach(c=>a.push(Number(c))),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")},cd=(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`)}})()+"}",pd=(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`)}})()+"}",hd=(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},fd=(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},md=(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},gd=(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 = ${we("uniforms.scales","i",n)}; - var roi_low = ${we("uniforms.roi","i",a)}; - var roi_hi = ${we("uniforms.roi",`i + ${e.length}`,a)}; - if (scale == 1.0) { - original_indices[i] = ${t.type.value}(output_index); - } else { - var input_shape_i = ${we("uniforms.input_shape","i",e.length)}; - var output_shape_i = ${we("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; - }`,_d=(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 = ${we("uniforms.scales","i",a)}; - if (scale == 1.0) { - input_index = output_index; - } else { - var roi_low = ${we("uniforms.roi","i",i)}; - var roi_hi = ${we("uniforms.roi",`i + ${r.length}`,i)}; - var input_shape_i = ${we("uniforms.input_shape","i",r.length)}; - var output_shape_i = ${we("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; - }`,wd=(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 >= ${we("uniforms.input_shape","i",e.length)}) { - return false; - } - } - return true; - }`,ss=(t,e,r,n)=>t.rank>n?` - ${t.indicesSet("input_indices",e,"channel")}; - ${t.indicesSet("input_indices",r,"batch")}; -`:"",yd=(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))`)}; - ${ss(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); - }`},bd=(t,e,r,n,a,i,s,o,l,d)=>{let c=r.length===2,[u,h]=c?[0,1]:[2,3],m=t.type.value,g=_=>{let b=_===u?"row":"col";return` - fn ${b}CubicInterpolation(input_indices: ${t.type.indices}, output_indices: ${e.type.indices}) -> ${m} { - var output_index = ${e.indicesGet("output_indices",_)}; - var originalIdx: ${m} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[_]}, - ${n[_]}, ${r[_]}, ${i[_]}, ${i[_]} + ${r.length}); - var fractOriginalIdx: ${m} = originalIdx - floor(originalIdx); - var coefs = getCubicInterpolationCoefs(fractOriginalIdx); - - if (${o} && (originalIdx < 0 || originalIdx > (${r[_]} - 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 ${b}: ${m} = originalIdx + ${m}(i); - if (${b} < 0 || ${b} >= ${r[_]}) { - ${d?`coefs[i + 1] = 0.0; - continue;`:o?`return ${l};`:`${b} = max(0, min(${b}, ${r[_]} - 1));`}; - } - var input_indices_copy: ${t.type.indices} = input_indices; - ${t.indicesSet("input_indices_copy",_,`u32(${b})`)}; - data[i + 1] = ${_===u?t.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; - } - return cubicInterpolation1D(data, coefs); - }`};return` - ${g(u)}; - ${g(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); - } - `},vd=(t,e,r,n,a)=>{let[i,s,o,l,d]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],c=t.type.value;return` - fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${c} { - 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))`)}; - ${ss(t,d,i,3)} - return ${t.getByIndices("input_indices")}; - } - - fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${c} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var depth:${c} = originalIndices[${s}]; - var height:${c} = originalIndices[${o}]; - var width:${c} = 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: ${c} = getInputValue(batch, channel, depth1, height1, width1); - var x112: ${c} = getInputValue(batch, channel, depth1, height1, width2); - var x121: ${c} = getInputValue(batch, channel, depth1, height2, width1); - var x122: ${c} = getInputValue(batch, channel, depth1, height2, width2); - var x211: ${c} = getInputValue(batch, channel, depth2, height1, width1); - var x212: ${c} = getInputValue(batch, channel, depth2, height1, width2); - var x221: ${c} = getInputValue(batch, channel, depth2, height2, width1); - var x222: ${c} = getInputValue(batch, channel, depth2, height2, width2); - var dx1: ${c} = abs(depth - ${c}(depth1)); - var dx2: ${c} = abs(${c}(depth2) - depth); - var dy1: ${c} = abs(height - ${c}(height1)); - var dy2: ${c} = abs(${c}(height2) - height); - var dz1: ${c} = abs(width - ${c}(width1)); - var dz2: ${c} = abs(${c}(width2) - width); - if (depth1 == depth2) { - dx1 = 0.5; - dx2 = 0.5; - } - if (height1 == height2) { - dy1 = 0.5; - dy2 = 0.5; - } - if (width1 == width2) { - dz1 = 0.5; - dz2 = 0.5; - } - return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + - x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); - }`},$d=(t,e,r,n,a,i)=>{let s=t.dims,o=hd(i,e.axes,s.length),l=fd(s,n,a,e.axes),d=n.slice();n.length===0&&(d=s.map((y,E)=>y===0?1:l[E]/y),e.keepAspectRatioPolicy!=="stretch"&&(l=md(s,d,e)));let c=pe("output",t.dataType,l.length),u=Y("input",t.dataType,s.length),h=Q.size(l),m=s.length===l.length&&s.every((y,E)=>y===l[E]),g=e.coordinateTransformMode==="tf_crop_and_resize",_=e.extrapolationValue,b=u.type.value,$=y=>` - ${m?"":` - ${cd(e.coordinateTransformMode,b)}; - ${(()=>{switch(e.mode){case"nearest":return` - ${wd(u,s)}; - ${pd(e.nearestMode,r,b)}; - ${_d(u,c,s,l,d.length,o.length,g)}; - `;case"linear":return` - ${gd(c,s,l,d.length,o.length)}; - ${(()=>{if(s.length===2||s.length===4)return`${yd(u,c,s,g,_)}`;if(s.length===3||s.length===5)return`${vd(u,c,s,g,_)}`;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`${bd(u,c,s,l,d,o,e.cubicCoeffA,g,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")}})()}; - `} - ${y.registerUniform("output_size","u32").registerUniform("scales","f32",d.length).registerUniform("roi","f32",o.length).declareVariables(u,c)} - ${y.mainStart()} - ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${m?"output[global_idx] = input[global_idx];":` - let output_indices = ${c.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:$,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},...he(s,l)]})}},xd=t=>{let e=t.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},ff=(t,e)=>{let r=[],n=[],a=[],i=xd(t);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");dd(t.inputs,e,i,r,n,a),t.compute($d(t.inputs[0],e,i,r,n,a),{inputs:[0]})},mf=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 qe({antialias:e,axes:r,coordinateTransformMode:n,cubicCoeffA:a,excludeOutside:i,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:d})}}),Sd,Ed,gf,c0=X(()=>{ye(),Te(),Ce(),Sd=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")}},Ed=(t,e,r,n)=>{let a=t[0].dims,i=Q.size(a),s=a,o=i,l=a.slice(-1)[0],d=n?a.slice(0,-1).concat(1):[],c=t.length>3,u=t.length>4,h=n&&r>1,m=n&&r>2,g=r>3,_=rt(l),b=[{type:12,data:o},{type:12,data:_},{type:12,data:l},{type:1,data:e.epsilon}],$=E=>{let k=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],T=[Y("x",t[0].dataType,t[0].dims,_),Y("skip",t[1].dataType,t[1].dims,_),Y("gamma",t[2].dataType,t[2].dims,_)];c&&T.push(Y("beta",t[3].dataType,t[3].dims,_)),u&&T.push(Y("bias",t[4].dataType,t[4].dims,_)),T.push(pe("output",t[0].dataType,s,_)),h&&T.push(pe("mean_output",1,d)),m&&T.push(pe("inv_std_output",1,d)),g&&T.push(pe("input_skip_bias_sum",t[0].dataType,s,_));let A=it(t[0].dataType);return` - - ${E.registerUniforms(k).declareVariables(...T)} - - ${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 = ${bt("f32",_)}; - var squareSum = ${bt("f32",_)}; - 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; - ${g?"input_skip_bias_sum[offset + i] = value;":""} - output[offset + i] = value; - let f32_value = ${Zt(A,_,"value")}; - sum += f32_value; - squareSum += f32_value * f32_value; - } - let mean = ${Kt("sum",_)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${Kt("squareSum",_)} / 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] + ${c?"beta[i]":"0.0"}; - } - }`},y=[{dims:s,dataType:t[0].dataType}];return r>1&&y.push({dims:d,dataType:1}),r>2&&y.push({dims:d,dataType:1}),r>3&&y.push({dims:a,dataType:t[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${_};${h};${m};${g}`,inputDependencies:t.map((E,k)=>"type")},getShaderSource:$,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(o/l/64)},programUniforms:b})}},gf=(t,e)=>{Sd(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(Ed(t.inputs,e,t.outputCount,!1),{outputs:r})}}),kd,En,Cd,os,Td,Id,_f,wf,p0=X(()=>{ye(),Te(),ut(),Ce(),kd=(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`)})},En=(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},Cd=(t,e)=>{if(t.length>1){let r=En(t,1),n=En(t,2),a=En(t,3);return a.length===0&&(a=[...Array(t[0].dims.length).keys()]),qe({starts:r,ends:n,axes:a})}else return e},os=(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]]))},Td=(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 = ${we("uniforms.input_shape","i",r.length)}; - let steps_i = ${we("uniforms.steps","i",r.length)}; - let signs_i = ${we("uniforms.signs","i",r.length)}; - let starts_i = ${we("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; - }`,Id=(t,e)=>{let r=t[0].dims,n=Q.size(r),a=e.axes.length>0?Q.normalizeAxes(e.axes,r.length):[...Array(r.length).keys()],i=En(t,4);i.forEach($=>$!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(a.length).fill(1));let s=e.starts.map(($,y)=>os($,y,r,a,i)),o=e.ends.map(($,y)=>os($,y,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 $=0;$Math.sign($));i.forEach(($,y,E)=>{if($<0){let k=(o[y]-s[y])/$,T=s[y],A=T+k*i[y];s[y]=A,o[y]=T,E[y]=-$}});let d=r.slice(0);a.forEach(($,y)=>{d[$]=Math.ceil((o[$]-s[$])/i[$])});let c={dims:d,dataType:t[0].dataType},u=pe("output",t[0].dataType,d.length),h=Y("input",t[0].dataType,t[0].dims.length),m=Q.size(d),g=[{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}],_=[{type:12,data:m},{type:12,data:s},{type:6,data:l},{type:12,data:i},...he(t[0].dims,d)],b=$=>` - ${$.registerUniforms(g).declareVariables(h,u)} - ${Td(h,u,r)} - ${$.mainStart()} - ${$.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:b,getRunData:()=>({outputs:[c],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:_})}},_f=(t,e)=>{kd(t.inputs,e);let r=Cd(t.inputs,e);t.compute(Id(t.inputs,r),{inputs:[0]})},wf=t=>{let e=t.starts,r=t.ends,n=t.axes;return qe({starts:e,ends:r,axes:n})}}),Ad,Md,yf,bf,h0=X(()=>{ye(),Te(),ut(),Ce(),Ad=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},Md=(t,e)=>{let r=t.dims,n=Q.size(r),a=64,i=e.axis;if(i<0&&(i=r.length+i),i$===4?`max(max(${b}.x, ${b}.y), max(${b}.z, ${b}.w))`:$===2?`max(${b}.x, ${b}.y)`:$===3?`max(max(${b}.x, ${b}.y), ${b}.z)`:b,u=Y("x",t.dataType,t.dims,l),h=pe("result",t.dataType,t.dims,l),m=u.type.value,g=it(t.dataType)==="f32"?`var threadMax = ${m}(-3.402823e+38f);`:`var threadMax = ${m}(-65504.0h);`,_=b=>` - 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; - } - ${b.registerUniform("packedCols","i32").declareVariables(u,h)} - ${b.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 - ${g} - 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}(${c("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}(${Kt("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:_}},yf=(t,e)=>{Ad(t.inputs),t.compute(Md(t.inputs[0],e))},bf=t=>qe({axis:t.axis})}),Od,zd,Pd,Rd,Bd,vf,$f,f0=X(()=>{ye(),Te(),ut(),Ce(),Od=t=>{if(!t||t.length<1)throw new Error("too few inputs")},zd=(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),qe({numOutputs:n,axis:e.axis,splitSizes:r})},Pd=t=>` -fn calculateOutputIndex(index: u32) -> u32 { - for (var i: u32 = 0u; i < ${t}u; i += 1u ) { - if (index < ${we("uniforms.size_in_split_axis","i",t)}) { - return i; - } - } - return ${t}u; -}`,Rd=t=>{let e=t.length,r=[];for(let n=0;n{let r=t[0].dims,n=Q.size(r),a=t[0].dataType,i=Q.normalizeAxis(e.axis,r.length),s=new Array(e.numOutputs),o=Y("input",a,r.length),l=new Array(e.numOutputs),d=[],c=[],u=0,h=[{type:12,data:n}];for(let g=0;g` - ${g.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)} - ${Pd(l.length)} - ${Rd(s)} - - ${g.mainStart()} - ${g.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 -= ${we("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})}},vf=(t,e)=>{Od(t.inputs);let r=t.inputs.length===1?e:zd(t.inputs,e);t.compute(Bd(t.inputs,r),{inputs:[0]})},$f=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 qe({axis:e,numOutputs:n,splitSizes:r})}}),ls,Dd,Nd,Ld,xf,m0=X(()=>{ye(),Te(),Ce(),ls=t=>Array.from(t.getBigInt64Array(),Number),Dd=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(ls(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")},Nd=(t,e)=>{let r=[];for(let n=0;n{let e=t[0].dims,r=ls(t[1]),n=Nd(e,r),a=Q.size(n),i=t[0].dataType,s=Y("input",i,e.length),o=pe("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},...he(t[0].dims,n)]}),getShaderSource:l}},xf=t=>{Dd(t.inputs),t.compute(Ld(t.inputs),{inputs:[0]})}}),Ud,Fd,Sf,g0=X(()=>{ye(),Te(),Ce(),Ud=(t,e,r,n,a)=>{let i=pe("output_data",a,r.length,4),s=Y("a_data",e[1].dataType,e[1].dims.length,4),o=Y("b_data",e[2].dataType,e[2].dims.length,4),l=Y("c_data",e[0].dataType,e[0].dims.length,4),d,c=(u,h,m)=>`select(${h}, ${u}, ${m})`;if(!n)d=i.setByOffset("global_idx",c(s.getByOffset("global_idx"),o.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(h,m,g="")=>{let _=`a_data[index_a${m}][component_a${m}]`,b=`b_data[index_b${m}][component_b${m}]`,$=`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}] = ${g}(${c(_,b,$)}); - `};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} - }`},Fd=t=>{let e=t[1].dims,r=t[2].dims,n=t[0].dims,a=t[1].dataType,i=!(Q.areEqual(e,r)&&Q.areEqual(r,n)),s=e,o=Q.size(e);if(i){let d=Xr.calcShape(Xr.calcShape(e,r,!1),n,!1);if(!d)throw new Error("Can't perform where op on the given tensors");s=d,o=Q.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>Ud(d,t,s,i,a),getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...he(n,e,r,s)]})}},Sf=t=>{t.compute(Fd(t.inputs))}}),Ef,_0=X(()=>{L_(),Pp(),U_(),F_(),W_(),G_(),V_(),Rh(),Y_(),X_(),Q_(),Z_(),J_(),e0(),t0(),r0(),n0(),a0(),Ph(),i0(),s0(),o0(),l0(),u0(),no(),d0(),c0(),p0(),h0(),f0(),m0(),jn(),ao(),g0(),Ef=new Map([["Abs",[Dp]],["Acos",[Np]],["Acosh",[Lp]],["Add",[wh]],["ArgMax",[Op,ks]],["ArgMin",[Mp,ks]],["Asin",[Up]],["Asinh",[Fp]],["Atan",[Wp]],["Atanh",[Gp]],["Attention",[zp]],["AveragePool",[sf,af]],["BatchNormalization",[Rp]],["BiasAdd",[Bp]],["BiasSplitGelu",[_h]],["Cast",[Hp,Vp]],["Ceil",[jp]],["Clip",[qp]],["Concat",[Th,Ih]],["Conv",[Os,Ms]],["ConvTranspose",[Nh,Dh]],["Cos",[Kp]],["Cosh",[Yp]],["CumSum",[Lh,Uh]],["Div",[yh]],["Einsum",[Fh,Wh]],["Elu",[Xp,Ha]],["Equal",[bh]],["Erf",[Qp]],["Exp",[Zp]],["Expand",[Gh]],["FastGelu",[Vh]],["Floor",[Jp]],["FusedConv",[Os,Ms]],["Gather",[qh,Hh]],["GatherElements",[Kh,jh]],["Gelu",[eh]],["Gemm",[Xh,Yh]],["GlobalAveragePool",[lf,of]],["GlobalMaxPool",[pf,cf]],["Greater",[Sh]],["GreaterOrEqual",[kh]],["HardSigmoid",[lh,oh]],["InstanceNormalization",[Qh]],["LayerNormalization",[Zh]],["LeakyRelu",[th,Ha]],["Less",[Eh]],["LessOrEqual",[Ch]],["Log",[gh]],["MatMul",[zh]],["MatMulNBits",[Jh,ef]],["MaxPool",[uf,df]],["Mul",[vh]],["MultiHeadAttention",[rf,tf]],["Neg",[nh]],["Not",[rh]],["Pad",[nf]],["Pow",[$h]],["Range",[hf]],["Reciprocal",[ah]],["ReduceMin",[kp]],["ReduceMean",[vp]],["ReduceMax",[Ep]],["ReduceSum",[Tp]],["ReduceProd",[Cp]],["ReduceL1",[$p]],["ReduceL2",[xp]],["ReduceLogSum",[Ap]],["ReduceLogSumExp",[Sp]],["ReduceSumSquare",[Ip]],["Relu",[ih]],["Resize",[ff,mf]],["Sigmoid",[sh]],["Sin",[uh]],["Sinh",[dh]],["Slice",[_f,wf]],["SkipLayerNormalization",[gf]],["Split",[vf,$f]],["Sqrt",[ch]],["Softmax",[yf,bf]],["Sub",[xh]],["Tan",[ph]],["Tanh",[hh]],["ThresholdedRelu",[mh,Ha]],["Tile",[xf]],["Transpose",[up,dp]],["Where",[Sf]]])}),kf,w0=X(()=>{Ft(),Rr(),Ce(),kf=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){Ut(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(),Tt(t.programInfo.name)}dispose(){}build(t,e){Ut(t.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let a=lp(e),i=t.getShaderSource(a),s=`${n.join(` -`)} -${a.additionalImplementations} -${i}`,o=r.createShaderModule({code:s,label:t.name});et("verbose",()=>`[WebGPU] ${t.name} shader code: ${s}`);let l=r.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:t.name});return Tt(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]}}}),Wd,Gd,Vd,Cf,y0=X(()=>{Ft(),ye(),Rr(),B_(),D_(),_0(),w0(),Wd=(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+`:${Wd(e,t.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,n},Vd=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Cf=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 Vd(await e.requestAdapterInfo()),this.gpuDataManager=sp(this),this.programManager=new kf(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ap(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;Ut(),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 g=Number(h-this.queryTimeBase),_=Number(m-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(_))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:c.map(b=>({dims:b.dims,dataType:Tr(b.dataType)})),outputsMetadata:u.map(b=>({dims:b.dims,dataType:Tr(b.dataType)})),kernelId:i,kernelType:o,kernelName:l,programName:d,startTime:g,endTime:_});else{let b="";c.forEach((y,E)=>{b+=`input[${E}]: [${y.dims}] | ${Tr(y.dataType)}, `});let $="";u.forEach((y,E)=>{$+=`output[${E}]: [${y.dims}] | ${Tr(y.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${l}|${d}" ${b}${$}execution time: ${_-g} ns`)}Nn("GPU",`${d}::${h}::${m}`)}t.unmap(),this.pendingQueries.delete(t)}),Tt()}run(t,e,r,n,a){Ut(t.name);let i=[];for(let $=0;$y):r;if(d.length!==s.length)throw new Error(`Output size ${d.length} must be equal to ${s.length}.`);let c=[],u=[];for(let $=0;$=s.length)throw new Error(`Invalid output index: ${d[$]}`);if(d[$]===-3)continue;let y=d[$]===-1,E=d[$]===-2,k=y||E?a(s[$].dataType,s[$].dims):n(d[$],s[$].dataType,s[$].dims);if(c.push(k),k.data===0)continue;let T=this.gpuDataManager.get(k.data);if(!T)throw new Error(`no GPU data for output: ${k.data}`);if(y&&this.temporaryData.push(T),E){let A=this.kernelPersistentData.get(this.currentKernelId);A||(A=[],this.kernelPersistentData.set(this.currentKernelId,A)),A.push(T)}u.push(T)}if(i.length!==e.length||u.length!==c.length){if(u.length===0)return Tt(t.name),c;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 $=0,y=[];l.forEach(A=>{let R=typeof A.data=="number"?[A.data]:A.data;if(R.length===0)return;let W=A.type===10?2:4,K,q;A.type===10?(q=R.length>4?16:R.length>2?8:R.length*W,K=R.length>4?16:W*R.length):(q=R.length<=2?R.length*W:16,K=16),$=Math.ceil($/q)*q,y.push($);let ee=A.type===10?8:4;$+=R.length>4?Math.ceil(R.length/ee)*K:R.length*W});let E=16;$=Math.ceil($/E)*E;let k=new ArrayBuffer($);l.forEach((A,R)=>{let W=y[R],K=typeof A.data=="number"?[A.data]:A.data;if(A.type===6)new Int32Array(k,W,K.length).set(K);else if(A.type===12)new Uint32Array(k,W,K.length).set(K);else if(A.type===10)new Uint16Array(k,W,K.length).set(K);else if(A.type===1)new Float32Array(k,W,K.length).set(K);else throw new Error(`Unsupported uniform type: ${Tr(A.type)}`)});let T=this.gpuDataManager.create($,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(T.buffer,0,k,0,$),this.gpuDataManager.release(T.id),h={offset:0,size:$,buffer:T.buffer}}let m=this.programManager.normalizeDispatchGroupSize(o),g=m[1]===1&&m[2]===1,_=Gd(t,e,g),b=this.programManager.getArtifact(_);if(b||(b=this.programManager.build(t,m),this.programManager.setArtifact(_,b),et("info",()=>`[artifact] key: ${_}, programName: ${t.name}`)),et("info",()=>`[ProgramManager] run "${t.name}" (key=${_}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let $={kernelId:this.currentKernelId,programName:b.programInfo.name,inputTensorViews:e,outputTensorViews:c};this.pendingKernels.push($),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push($)}return this.programManager.run(b,i,u,m,h),Tt(t.name),c}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=Ef.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),et("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 Ss(this,t,e);return ip(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(){et("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(){et("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){et("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()}}}),Tf={};Zr(Tf,{init:()=>If});var Ra,Hd,If,b0=X(()=>{ye(),y0(),Rr(),Te(),Ra=class Af{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=Q.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=Q.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=Q.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Q.size(e)!==Q.size(this.dims))throw new Error("Invalid new shape");return new Af(this.module,this.dataType,this.data,e)}},Hd=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 Ra(this.module,o,this.output(s,l),l),i=(s,o)=>{let l=Ja(s);if(!l)throw new Error(`Unsupported data type: ${s}`);let d=l*Q.size(o),c=d>0?this.backend.gpuDataManager.create(d).id:0;return new Ra(this.module,s,c,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 Cf;await i.initialize(r,n),a("webgpu",[i,s=>i.alloc(s),s=>i.free(s),(s,o,l,d=!1)=>{if(d)et("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${o}, size=${l}`),i.memcpy(s,o);else{et("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${o}, size=${l}`);let c=e.HEAPU8.subarray(s>>>0,(s>>>0)+l);i.upload(o,c)}},async(s,o,l)=>{et("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)=>{et("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${s}, contextDataOffset=${o}`);let c=new Hd(e,i,o);return i.computeKernel(s,c,d)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else a("webnn")}}),qd,Mf,Of,lr,jd,Ps,zf,Pf,us,Rf,Bf,Df,v0=X(()=>{P_(),R_(),ye(),qn(),Xs(),np(),qd=(t,e)=>{tt()._OrtInit(t,e)!==0&&Ge("Can't initialize onnxruntime.")},Mf=async t=>{qd(t.wasm.numThreads,ei(t.logLevel))},Of=async(t,e)=>{{let r=(b0(),Mr(Tf)).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",tt(),t,n)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",tt(),t)}}},lr=new Map,jd=t=>{let e=tt(),r=e.stackSave();try{let n=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,n,n+4)!==0&&Ge("Can't get session input/output count."),[e.HEAP32[n/4],e.HEAP32[n/4+1]]}finally{e.stackRestore(r)}},Ps=t=>{let e=tt(),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]},zf=async(t,e)=>{let r,n,a=tt();Array.isArray(t)?[r,n]=t:t.buffer===a.HEAPU8.buffer?[r,n]=[t.byteOffset,t.byteLength]:[r,n]=Ps(t);let i=0,s=0,o=0,l=[],d=[],c=[];try{if([s,l]=rp(e),e?.externalData&&a.mountExternalData){let y=[];for(let E of e.externalData){let k=typeof E=="string"?E:E.path;y.push(ti(typeof E=="string"?E:E.data).then(T=>{a.mountExternalData(k,T)}))}await Promise.all(y)}i=await a._OrtCreateSession(r,n,s),i===0&&Ge("Can't create a session.");let[u,h]=jd(i),m=!!e?.enableGraphCapture,g=[],_=[],b=[];for(let y=0;yy==="gpu-buffer")&&(o=a._OrtCreateBinding(i),o===0&&Ge("Can't create IO binding."),$={handle:o,outputPreferredLocations:b,outputPreferredLocationsEncoded:b.map(y=>xs(y))}),lr.set(i,[i,d,c,$,m,!1]),[i,g,_]}catch(u){throw d.forEach(h=>a._OrtFree(h)),c.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?.()}},Pf=t=>{let e=tt(),r=lr.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),lr.delete(t)},us=(t,e,r,n,a,i=!1)=>{if(!t){e.push(0);return}let s=tt(),o=t[0],l=t[1],d=t[3],c,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 g=t[2].gpuBuffer,_=Ja($s(o));u=l.reduce(($,y)=>$*y,1)*_;let b=s.jsepRegisterBuffer;if(!b)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');c=b(n,a,g,u)}else{let g=t[2];if(Array.isArray(g)){u=4*g.length,c=s._malloc(u),r.push(c);let _=c/4;for(let b=0;bs.HEAP32[g++]=b);let _=s._OrtCreateTensor($s(o),c,u,m,l.length,xs(d));_===0&&Ge(`Can't create tensor for input/output. session=${n}, index=${a}.`),e.push(_)}finally{s.stackRestore(h)}},Rf=async(t,e,r,n,a,i)=>{let s=tt(),o=lr.get(t);if(!o)throw new Error(`cannot run inference. invalid session id: ${t}`);let l=o[0],d=o[1],c=o[2],u=o[3],h=o[4],m=o[5],g=e.length,_=n.length,b=0,$=[],y=[],E=[],k=[],T=s.stackSave(),A=s.stackAlloc(g*4),R=s.stackAlloc(g*4),W=s.stackAlloc(_*4),K=s.stackAlloc(_*4);try{[b,$]=tp(i);for(let O=0;OUe*Ke,1);L=Tr(Pe);let pt=u?.outputPreferredLocations[n[O]];if(L==="string"){if(pt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ue=[],Ke=ne/4;for(let lt=0;lt0){let Ue=s.jsepGetBuffer;if(!Ue)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ke=Ue(ne),lt=Ja(Pe);if(lt===void 0||!Zs(L))throw new Error(`Unsupported data type: ${L}`);se=!0,F.push([L,He,{gpuBuffer:Ke,download:s.jsepCreateDownloader(Ke,ot*lt,L),dispose:()=>{s._OrtReleaseTensor(G)}},"gpu-buffer"])}else{let Ue=Qs(L),Ke=new Ue(ot);new Uint8Array(Ke.buffer,Ke.byteOffset,Ke.byteLength).set(s.HEAPU8.subarray(ne,ne+Ke.byteLength)),F.push([L,He,Ke,"cpu"])}}finally{s.stackRestore(ie),L==="string"&&ne&&s._free(ne),se||s._OrtReleaseTensor(G)}}return u&&!h&&(s._OrtClearBoundOutputs(u.handle),lr.set(t,[l,d,c,u,h,!1])),F}finally{s.stackRestore(T),y.forEach(q=>s._OrtReleaseTensor(q)),E.forEach(q=>s._OrtReleaseTensor(q)),k.forEach(q=>s._free(q)),b!==0&&s._OrtReleaseRunOptions(b),$.forEach(q=>s._free(q))}},Bf=t=>{let e=tt(),r=lr.get(t);if(!r)throw new Error("invalid session id");let n=r[0],a=e._OrtEndProfiling(n);a===0&&Ge("Can't get an profile file name."),e._OrtFree(a)},Df=t=>{let e=[];for(let r of t){let n=r[2];!Array.isArray(n)&&"buffer"in n&&e.push(n.buffer)}return e}}),$0=Qr((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'}),ur,St,jr,kn,Cn,ds,Ba,vr,$r,Kd,Tn,Nf,Lf,Uf,Ff,Wf,Gf,Vf,Hf=X(()=>{Ft(),v0(),qn(),ur=()=>!!De.wasm.proxy&&typeof document<"u",jr=!1,kn=!1,Cn=!1,Ba=new Map,vr=(t,e)=>{let r=Ba.get(t);r?r.push(e):Ba.set(t,[e])},$r=()=>{if(jr||!kn||Cn||!St)throw new Error("worker not ready")},Kd=t=>{switch(t.data.type){case"init-wasm":jr=!1,t.data.err?(Cn=!0,ds[1](t.data.err)):(kn=!0,ds[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Ba.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},Tn=typeof document<"u"?document?.currentScript?.src:void 0,Nf=async()=>{if(!kn){if(jr)throw new Error("multiple calls to 'initWasm()' detected.");if(Cn)throw new Error("previous call to 'initWasm()' failed.");if(jr=!0,ur())return De.wasm.wasmPaths===void 0&&Tn&&Tn.indexOf("blob:")!==0&&(De.wasm.wasmPaths=Tn.substr(0,+Tn.lastIndexOf("/")+1)),new Promise((t,e)=>{St?.terminate();let r=URL.createObjectURL(new Blob([$0()],{type:"text/javascript"}));St=new Worker(r,{name:"ort-wasm-proxy-worker"}),St.onerror=a=>e(a),St.onmessage=Kd,URL.revokeObjectURL(r),ds=[t,e];let n={type:"init-wasm",in:De};St.postMessage(n)});try{await ep(De.wasm),await Mf(De),kn=!0}catch(t){throw Cn=!0,t}finally{jr=!1}}},Lf=async t=>{if(ur())return $r(),new Promise((e,r)=>{vr("init-ep",[e,r]);let n={type:"init-ep",in:{epName:t,env:De}};St.postMessage(n)});await Of(De,t)},Uf=async t=>ur()?($r(),new Promise((e,r)=>{vr("copy-from",[e,r]);let n={type:"copy-from",in:{buffer:t}};St.postMessage(n,[t.buffer])})):Ps(t),Ff=async(t,e)=>{if(ur()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return $r(),new Promise((r,n)=>{vr("create",[r,n]);let a={type:"create",in:{model:t,options:{...e}}},i=[];t instanceof Uint8Array&&i.push(t.buffer),St.postMessage(a,i)})}else return zf(t,e)},Wf=async t=>{if(ur())return $r(),new Promise((e,r)=>{vr("release",[e,r]);let n={type:"release",in:t};St.postMessage(n)});Pf(t)},Gf=async(t,e,r,n,a,i)=>{if(ur()){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 $r(),new Promise((s,o)=>{vr("run",[s,o]);let l=r,d={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:n,options:i}};St.postMessage(d,Df(l))})}else return Rf(t,e,r,n,a,i)},Vf=async t=>{if(ur())return $r(),new Promise((e,r)=>{vr("end-profiling",[e,r]);let n={type:"end-profiling",in:t};St.postMessage(n)});Bf(t)}}),cs,Yd,qf,x0=X(()=>{Ft(),Hf(),ye(),np(),cs=(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()}`)}},Yd=t=>{switch(t[3]){case"cpu":return new ft(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Zs(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:a}=t[2];return ft.fromGpuBuffer(r,{dataType:e,dims:t[1],download:n,dispose:a})}default:throw new Error(`invalid data location: ${t[3]}`)}},qf=class{async fetchModelAndCopyToWasmMemory(t){return Uf(await ti(t))}async loadModel(t,e){Ut();let r;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?r=await ti(t):r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames]=await Ff(r,e),Tt()}async dispose(){return Wf(this.sessionId)}async run(t,e,r){Ut();let n=[],a=[];Object.entries(t).forEach(u=>{let h=u[0],m=u[1],g=this.inputNames.indexOf(h);if(g===-1)throw new Error(`invalid input '${h}'`);n.push(m),a.push(g)});let i=[],s=[];Object.entries(e).forEach(u=>{let h=u[0],m=u[1],g=this.outputNames.indexOf(h);if(g===-1)throw new Error(`invalid output '${h}'`);i.push(m),s.push(g)});let o=n.map((u,h)=>cs(u,()=>`input "${this.inputNames[a[h]]}"`)),l=i.map((u,h)=>u?cs(u,()=>`output "${this.outputNames[s[h]]}"`):null),d=await Gf(this.sessionId,a,o,s,l,r),c={};for(let u=0;u{Ft(),Hf(),x0(),Xd=()=>{if((typeof De.wasm.initTimeout!="number"||De.wasm.initTimeout<0)&&(De.wasm.initTimeout=0),typeof De.wasm.simd!="boolean"&&(De.wasm.simd=!0),typeof De.wasm.proxy!="boolean"&&(De.wasm.proxy=!1),typeof De.wasm.trace!="boolean"&&(De.wasm.trace=!1),typeof De.wasm.numThreads!="number"||!Number.isInteger(De.wasm.numThreads)||De.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(De.wasm.numThreads=1);let t=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;De.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},jf=class{async init(t){Xd(),await Nf(),await Lf(t)}async createInferenceSessionHandler(t,e){let r=new qf;return await r.loadModel(t,e),Promise.resolve(r)}}}),Kf={};Zr(Kf,{wasmBackend:()=>Yf});var Yf,E0=X(()=>{S0(),Yf=new jf});Ft();Ft();Ft();var k0="1.17.3",C0=Hc;{let t=(E0(),Mr(Kf)).wasmBackend;Ar("webgpu",t,5),Ar("webnn",t,5),Ar("cpu",t,10),Ar("wasm",t,10)}Object.defineProperty(De.versions,"web",{value:k0,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. - * ============================================================================= - */const T0=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return qs},get TRACE(){return Nn},get TRACE_FUNC_BEGIN(){return Ut},get TRACE_FUNC_END(){return Tt},get Tensor(){return ft},get TrainingSession(){return js},default:C0,get env(){return De},get registerBackend(){return Ar}},Symbol.toStringTag,{value:"Module"})),I0=(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 c=i*a;let u=0,h=c,m=c*2,g=-1;s==="RGBA"?(u=0,h=c,m=c*2,g=c*3):s==="RGB"?(u=0,h=c,m=c*2):s==="RBG"&&(u=0,m=c,h=c*2);for(let _=0;_{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,c;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?c=[0,0,0,0]:typeof l.bias=="number"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[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,g=1,_=2,b=3,$=0,y=u,E=u*2,k=-1;o==="RGBA"?($=0,y=u,E=u*2,k=u*3):o==="RGB"?($=0,y=u,E=u*2):o==="RBG"&&($=0,E=u,y=u*2),n=r.createImageData(a,i);for(let T=0;T{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,c=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3);let u=4,h=0,m=1,g=2,_=3,b=0,$=d,y=d*2,E=-1;o==="RGB"&&(u=3,h=0,m=1,g=2,_=-1),l==="RGBA"?E=d*3:l==="RBG"?(b=0,y=d,$=d*2):l==="BGR"&&(y=0,$=d,b=d*2);for(let T=0;T{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=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(r){const c=l();c.width=t.width,c.height=t.height;const u=d(c);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 c,u;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,u=e.resizedWidth):(c=t.height,u=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=c,o.width=u,e!==void 0){const h=l();h.width=u,h.height=c;const m=d(h);if(m!=null)m.putImageData(t,0,0),s=m.getImageData(0,0,u,c).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 c=l();c.width=t.width,c.height=t.height;const u=d(c);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,ps(s,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((c,u)=>{const h=l(),m=d(h);if(!t||!m)return u();const g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{h.width=g.width,h.height=g.height,m.drawImage(g,0,0,h.width,h.height);const _=m.getImageData(0,0,h.width,h.height);o.height=h.height,o.width=h.width,c(ps(_.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return ps(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},O0=(t,e)=>{const{width:r,height:n,download:a,dispose:i}=e,s=[1,n,r,4];return new qt({location:"texture",type:"float32",texture:t,dims:s,download:a,dispose:i})},z0=(t,e)=>{const{dataType:r,dims:n,download:a,dispose:i}=e;return new qt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:i})},P0=(t,e,r)=>new qt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]}),li=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Rs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Qd=!1;const R0=()=>{if(!Qd){Qd=!0;const t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(li.set("int64",BigInt64Array),Rs.set(BigInt64Array,"int64")),e&&(li.set("uint64",BigUint64Array),Rs.set(BigUint64Array,"uint64"))}},B0=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new qt(t.type,t.data,e);case"cpu-pinned":return new qt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new qt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new qt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let qt=class{constructor(e,r,n){R0();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=li.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=li.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=Rs.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=B0(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 M0(e,r)}static fromTexture(e,r){return O0(e,r)}static fromGpuBuffer(e,r){return z0(e,r)}static fromPinnedBuffer(e,r,n){return P0(e,r,n)}toDataURL(e){return I0(this,e)}toImageData(e){return A0(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 D0(this,e)}};const N0=qt,zn=[];let Bs,Un;Dn.IS_NODE_ENV?(Un=Xe??Gg,zn.push("cpu"),Bs=["cpu"]):(Un=T0,Dn.IS_WEBGPU_AVAILABLE&&zn.push("webgpu"),zn.push("wasm"),Bs=["wasm"]);const L0=Un.InferenceSession;function U0(t){let e=Bs;if(t){if(!zn.includes(t))throw new Error(`Unsupported device: "${t}". Should be one of: ${zn.join(", ")}.`);e=[t]}return e}async function Xf(t,e){return await L0.create(t,e)}function Qf(t){return t instanceof Un.Tensor}const Ir=Un?.env;Ir?.wasm&&(Ir.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.3/dist/",Ir.wasm.proxy=!Dn.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(Ir.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(Ir.wasm.simd=!1));function F0(){return Ir?.wasm?.proxy}_t.backends.onnx=Ir;const Zd=async(t,e,r)=>{const n=await Xf(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 ae(s[r])}};class Jd{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Zd(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=Zd(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 ec=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 ae{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 Qf(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 ae(this.type,[this.data[e]],n)}indexOf(e){const r=this.data;for(let n=0;nc[1])throw new Error(`Invalid slice: ${c}`);let u=[Math.max(c[0],0),Math.min(c[1],this.dims[d])];n.push(u),r.push(u[1]-u[0])}else throw new Error(`Invalid slice: ${c}`)}let a=n.map(([d,c])=>c-d),i=a.reduce((d,c)=>d*c);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];c+=(h%m+n[u][0])*l[u],h=Math.floor(h/m)}o[d]=s[c]}return new ae(this.type,o,r)}permute(...e){return G0(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 ae(this.type,[o],[])}r=hr(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=c%h;l+=m*u,u*=i[d]}c=Math.floor(c/h)}s[l]+=a[o]**e}if(e!==1)for(let o=0;o=0;--o){const c=this.dims[o];if(o!==r){const u=l%c;s+=u*d,d*=this.dims[o]}l=Math.floor(l/c)}a[i]/=n.data[s]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return q0(this.dims)}squeeze(e=null){return new ae(this.type,this.data,rc(this.dims,e))}squeeze_(e=null){return this.dims=rc(this.dims,e),this}unsqueeze(e=null){return new ae(this.type,this.data,nc(this.dims,e))}unsqueeze_(e=null){return this.dims=nc(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 ae(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 nc(t,e){return e=hr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function hr(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 jt(t,e=0){e=hr(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 g=l.dims[u];let _=h%g;u===e&&(_+=s),c+=_*m,m*=r[u],h=Math.floor(h/g)}a[c]=l.data[d]}s+=l.dims[e]}}return new ae(i,a,r)}function Fn(t,e=0){return jt(t.map(r=>r.unsqueeze(e)),e)}function V0(t,e=null,r=1,n=!1){if(e===null){const d=t.data.reduce((m,g)=>m+g,0)/t.data.length,c=Math.sqrt(t.data.reduce((m,g)=>m+(g-d)**2,0)/(t.data.length-r)),u=new ae(t.type,[d],[]);return[new ae(t.type,[c],[]),u]}e=hr(e,t.dims.length);const a=co(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;--c){const m=t.dims[c];if(c!==e){const g=u%m;d+=g*h,h*=i[c]}u=Math.floor(u/m)}s[d]+=(t.data[l]-a.data[d])**2}for(let l=0;ls+o,0);return new ae(t.type,[i/t.data.length],[])}e=hr(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 c=t.dims[o];if(o!==e){const u=l%c;s+=u*d,d*=n[o]}l=Math.floor(l/c)}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 q0(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 po(t,e,r,n){const a=t.reduce((i,s)=>i*s,1);return new ae(r,new n(a).fill(e),t)}function j0(t,e){let r,n;return r="float32",n=Float32Array,po(t,e,r,n)}function K0(t,e){return j0(t.dims,e)}function ui(t){return po(t,1n,"int64",BigInt64Array)}function Y0(t){return ui(t.dims)}function X0(t){return po(t,0n,"int64",BigInt64Array)}function Q0(t){return X0(t.dims)}class Z0{constructor(e=(r,n)=>r>n){this._heap=[],this._comparator=e}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const r of e)this._heap.push(r),this._siftUp();return this.size}pop(){const e=this.peek(),r=this.size-1;return r>0&&this._swap(0,r),this._heap.pop(),this._siftDown(),e}replace(e){const r=this.peek();return this._heap[0]=e,this._siftDown(),r}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,r){return this._comparator(this._heap[e],this._heap[r])}_swap(e,r){const n=this._heap[e];this._heap[e]=this._heap[r],this._heap[r]=n}_siftUp(){let e=this.size-1;for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const a=new Pn(this.bosTokenId,0,0,0,0),i=new Pn(this.eosTokenId,1,this.len,0,0);this.nodes.push(a.clone()),this.nodes.push(i.clone()),this.beginNodes[this.len].push(i),this.endNodes[0].push(a)}insert(e,r,n,a){const i=this.nodes.length,s=new Pn(a,i,e,r,n);this.beginNodes[e].push(s),this.endNodes[e+r].push(s),this.nodes.push(s)}viterbi(){const e=this.len;let r=0;for(;r<=e;){if(this.beginNodes[r].length==0)return[];for(let o of this.beginNodes[r]){o.prev=null;let l=0,d=null;for(let c of this.endNodes[r]){const u=c.backtraceScore+o.score;(d===null||u>l)&&(d=c.clone(),l=u)}if(d!==null)o.prev=d,o.backtraceScore=l;else return[]}++r}const n=[],i=this.beginNodes[e][0].prev;if(i===null)return[];let s=i.clone();for(;s.prev!==null;)n.push(s.clone()),s=s.clone().prev.clone();return n.reverse(),n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){return this.viterbi().map(r=>this.piece(r))}tokenIds(){return this.viterbi().map(r=>r.tokenId)}}class Pn{constructor(e,r,n,a,i){this.tokenId=e,this.nodeId=r,this.pos=n,this.length=a,this.score=i,this.prev=null,this.backtraceScore=0}clone(){const e=new Pn(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}var U=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"}),ac=Object.freeze({set:U.Set,for:U.For,in:U.In,is:U.Is,if:U.If,else:U.Else,endif:U.EndIf,elif:U.ElseIf,endfor:U.EndFor,and:U.And,or:U.Or,not:U.Not,"not in":U.NotIn,true:U.BooleanLiteral,false:U.BooleanLiteral}),xr=class{constructor(t,e){this.value=t,this.type=e}};function ic(t){return/\w/.test(t)}function hs(t){return/[0-9]/.test(t)}var tw=[["{%",U.OpenStatement],["%}",U.CloseStatement],["{{",U.OpenExpression],["}}",U.CloseExpression],["(",U.OpenParen],[")",U.CloseParen],["{",U.OpenCurlyBracket],["}",U.CloseCurlyBracket],["[",U.OpenSquareBracket],["]",U.CloseSquareBracket],[",",U.Comma],[".",U.Dot],[":",U.Colon],["|",U.Pipe],["<=",U.ComparisonBinaryOperator],[">=",U.ComparisonBinaryOperator],["==",U.ComparisonBinaryOperator],["!=",U.ComparisonBinaryOperator],["<",U.ComparisonBinaryOperator],[">",U.ComparisonBinaryOperator],["+",U.AdditiveBinaryOperator],["-",U.AdditiveBinaryOperator],["*",U.MultiplicativeBinaryOperator],["/",U.MultiplicativeBinaryOperator],["%",U.MultiplicativeBinaryOperator],["=",U.Equals]],rw=new Map([["n",` -`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function nw(t,e={}){return t.endsWith(` -`)&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function aw(t,e={}){const r=[],n=nw(t,e);let a=0;const i=s=>{let o="";for(;s(n[a]);){if(n[a]==="\\"){if(++a,a>=n.length)throw new SyntaxError("Unexpected end of input");const l=n[a++],d=rw.get(l);if(d===void 0)throw new SyntaxError(`Unexpected escaped character: ${l}`);o+=d;continue}if(o+=n[a++],a>=n.length)throw new SyntaxError("Unexpected end of input")}return o};e:for(;a0){r.push(new xr(l,U.Text));continue}}i(l=>/\s/.test(l));const o=n[a];if(o==="-"||o==="+"){const l=r.at(-1)?.type;if(l===U.Text||l===void 0)throw new SyntaxError(`Unexpected character: ${o}`);switch(l){case U.Identifier:case U.NumericLiteral:case U.BooleanLiteral:case U.StringLiteral:case U.CloseParen:case U.CloseSquareBracket:break;default:{++a;const d=i(hs);r.push(new xr(`${o}${d}`,d.length>0?U.NumericLiteral:U.UnaryOperator));continue}}}for(const[l,d]of tw)if(n.slice(a,a+l.length)===l){r.push(new xr(l,d)),a+=l.length;continue e}if(o==="'"||o==='"'){++a;const l=i(d=>d!==o);r.push(new xr(l,U.StringLiteral)),++a;continue}if(hs(o)){const l=i(hs);r.push(new xr(l,U.NumericLiteral));continue}if(ic(o)){const l=i(ic),d=Object.hasOwn(ac,l)?ac[l]:U.Identifier;d===U.In&&r.at(-1)?.type===U.Not?(r.pop(),r.push(new xr("not in",U.NotIn))):r.push(new xr(l,d));continue}throw new SyntaxError(`Unexpected character: ${o}`)}return r}var Kn=class{type="Statement"},iw=class extends Kn{constructor(t){super(),this.body=t}type="Program"},sc=class extends Kn{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},sw=class extends Kn{constructor(t,e,r){super(),this.loopvar=t,this.iterable=e,this.body=r}type="For"},ow=class extends Kn{constructor(t,e){super(),this.assignee=t,this.value=e}type="Set"},Yt=class extends Kn{type="Expression"},lw=class extends Yt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},uw=class extends Yt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Kr=class extends Yt{constructor(t){super(),this.value=t}type="Identifier"},Jr=class extends Yt{constructor(t){super(),this.value=t}type="Literal"},dw=class extends Jr{type="NumericLiteral"},oc=class extends Jr{type="StringLiteral"},lc=class extends Jr{type="BooleanLiteral"},cw=class extends Jr{type="ArrayLiteral"},uc=class extends Jr{type="TupleLiteral"},pw=class extends Jr{type="ObjectLiteral"},In=class extends Yt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},hw=class extends Yt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},fw=class extends Yt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},mw=class extends Yt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},gw=class extends Yt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},_w=class extends Yt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"};function ww(t){const e=new iw([]);let r=0;function n(F,O){const G=t[r++];if(!G||G.type!==F)throw new Error(`Parser Error: ${O}. ${G.type} !== ${F}.`);return G}function a(){switch(t[r].type){case U.Text:return o();case U.OpenStatement:return l();case U.OpenExpression:return d();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function i(...F){return r+F.length<=t.length&&F.some((O,G)=>O!==t[r+G].type)}function s(...F){return r+F.length<=t.length&&F.every((O,G)=>O===t[r+G].type)}function o(){return new oc(n(U.Text,"Expected text token").value)}function l(){n(U.OpenStatement,"Expected opening statement token");let F;switch(t[r].type){case U.Set:++r,F=c(),n(U.CloseStatement,"Expected closing statement token");break;case U.If:++r,F=u(),n(U.OpenStatement,"Expected {% token"),n(U.EndIf,"Expected endif token"),n(U.CloseStatement,"Expected %} token");break;case U.For:++r,F=m(),n(U.OpenStatement,"Expected {% token"),n(U.EndFor,"Expected endfor token"),n(U.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type}`)}return F}function d(){n(U.OpenExpression,"Expected opening expression token");const F=g();return n(U.CloseExpression,"Expected closing expression token"),F}function c(){const F=g();if(s(U.Equals)){++r;const O=c();return new ow(F,O)}return F}function u(){const F=g();n(U.CloseStatement,"Expected closing statement token");const O=[],G=[];for(;!(t[r]?.type===U.OpenStatement&&(t[r+1]?.type===U.ElseIf||t[r+1]?.type===U.Else||t[r+1]?.type===U.EndIf));)O.push(a());if(t[r]?.type===U.OpenStatement&&t[r+1]?.type!==U.EndIf)if(++r,s(U.ElseIf))n(U.ElseIf,"Expected elseif token"),G.push(u());else for(n(U.Else,"Expected else token"),n(U.CloseStatement,"Expected closing statement token");!(t[r]?.type===U.OpenStatement&&t[r+1]?.type===U.EndIf);)G.push(a());return new sc(F,O,G)}function h(F=!1){const O=F?te:g,G=[O()],ie=s(U.Comma);for(;ie&&(++r,G.push(O()),!!s(U.Comma)););return ie?new uc(G):G[0]}function m(){const F=h(!0);if(!(F instanceof Kr||F instanceof uc))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${F.type} instead`);n(U.In,"Expected `in` keyword following loop variable");const O=g();n(U.CloseStatement,"Expected closing statement token");const G=[];for(;i(U.OpenStatement,U.EndFor);)G.push(a());return new sw(F,O,G)}function g(){return _()}function _(){const F=b();if(s(U.If)){++r;const O=b();n(U.Else,"Expected else token");const G=b();return new sc(O,[F],[G])}return F}function b(){let F=$();for(;s(U.Or);){const O=t[r];++r;const G=$();F=new In(O,F,G)}return F}function $(){let F=y();for(;s(U.And);){const O=t[r];++r;const G=y();F=new In(O,F,G)}return F}function y(){let F;for(;s(U.Not);){const O=t[r];++r;const G=y();F=new mw(O,G)}return F??E()}function E(){let F=k();for(;s(U.ComparisonBinaryOperator)||s(U.In)||s(U.NotIn);){const O=t[r];++r;const G=k();F=new In(O,F,G)}return F}function k(){let F=ee();for(;s(U.AdditiveBinaryOperator);){const O=t[r];++r;const G=ee();F=new In(O,F,G)}return F}function T(){const F=q();return s(U.OpenParen)?A(F):F}function A(F){let O=new uw(F,R());return s(U.OpenParen)&&(O=A(O)),O}function R(){n(U.OpenParen,"Expected opening parenthesis for arguments list");const F=W();return n(U.CloseParen,"Expected closing parenthesis for arguments list"),F}function W(){const F=[];for(;!s(U.CloseParen);){let O=g();if(s(U.Equals)){if(++r,!(O instanceof Kr))throw new SyntaxError("Expected identifier for keyword argument");const G=g();O=new _w(O,G)}F.push(O),s(U.Comma)&&++r}return F}function K(){const F=[];let O=!1;for(;!s(U.CloseSquareBracket);)s(U.Colon)?(F.push(void 0),++r,O=!0):(F.push(g()),s(U.Colon)&&(++r,O=!0));if(F.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(O){if(F.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new gw(...F)}return F[0]}function q(){let F=te();for(;s(U.Dot)||s(U.OpenSquareBracket);){const O=t[r];++r;let G;const ie=O.type!==U.Dot;if(ie)G=K(),n(U.CloseSquareBracket,"Expected closing square bracket");else if(G=te(),G.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");F=new lw(F,G,ie)}return F}function ee(){let F=P();for(;s(U.MultiplicativeBinaryOperator);){const O=t[r];++r;const G=P();F=new In(O,F,G)}return F}function P(){let F=J();for(;s(U.Is);){++r;const O=s(U.Not);O&&++r;let G=te();if(G instanceof lc&&(G=new Kr(G.value.toString())),!(G instanceof Kr))throw new SyntaxError("Expected identifier for the test");F=new fw(F,O,G)}return F}function J(){let F=T();for(;s(U.Pipe);){++r;let O=te();if(!(O instanceof Kr))throw new SyntaxError("Expected identifier for the filter");s(U.OpenParen)&&(O=A(O)),F=new hw(F,O)}return F}function te(){const F=t[r];switch(F.type){case U.NumericLiteral:return++r,new dw(Number(F.value));case U.StringLiteral:return++r,new oc(F.value);case U.BooleanLiteral:return++r,new lc(F.value==="true");case U.Identifier:return++r,new Kr(F.value);case U.OpenParen:{++r;const O=h();if(t[r].type!==U.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,O}case U.OpenSquareBracket:{++r;const O=[];for(;!s(U.CloseSquareBracket);)O.push(g()),s(U.Comma)&&++r;return++r,new cw(O)}case U.OpenCurlyBracket:{++r;const O=new Map;for(;!s(U.CloseCurlyBracket);){const G=g();n(U.Colon,"Expected colon between key and value in object literal");const ie=g();O.set(G,ie),s(U.Comma)&&++r}return++r,new pw(O)}default:throw new SyntaxError(`Unexpected token: ${F.type}`)}}for(;r=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const i=[];for(let s=e;a*se.toUpperCase())}var tr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new Ze(!!this.value)}},We=class extends tr{type="NumericValue"},Ae=class extends tr{type="StringValue";builtins=new Map([["upper",new Jt(()=>new Ae(this.value.toUpperCase()))],["lower",new Jt(()=>new Ae(this.value.toLowerCase()))],["strip",new Jt(()=>new Ae(this.value.trim()))],["title",new Jt(()=>new Ae(Jf(this.value)))],["length",new We(this.value.length)]])},Ze=class extends tr{type="BooleanValue"},Dt=class extends tr{type="ObjectValue";__bool__(){return new Ze(this.value.size>0)}builtins=new Map([["get",new Jt(([t,e])=>{if(!(t instanceof Ae))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Rn})],["items",new Jt(()=>new Ye(Array.from(this.value.entries()).map(([t,e])=>new Ye([new Ae(t),e]))))]])},Ye=class extends tr{type="ArrayValue";builtins=new Map([["length",new We(this.value.length)]]);__bool__(){return new Ze(this.value.length>0)}},bw=class extends Ye{type="TupleValue"},Jt=class extends tr{type="FunctionValue"},Rn=class extends tr{type="NullValue"},Bt=class extends tr{type="UndefinedValue"},Ds=class{constructor(t){this.parent=t}variables=new Map([["namespace",new Jt(t=>{if(t.length===0)return new Dt(new Map);if(t.length!==1||!(t[0]instanceof Dt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]);tests=new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Jt],["odd",t=>{if(t.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!==0}],["even",t=>{if(t.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["number",t=>t.type==="NumericValue"],["integer",t=>t.type==="NumericValue"&&Number.isInteger(t.value)],["iterable",t=>t instanceof Ye||t instanceof Ae],["lower",t=>{const e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value]]);set(t,e){return this.declareVariable(t,Ka(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Bt}catch{return new Bt}}},vw=class{global;constructor(t){this.global=t??new Ds}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new Ze(r.value==n.value);case"!=":return new Ze(r.value!=n.value)}if(r instanceof Bt||n instanceof Bt)throw new Error("Cannot perform operation on undefined values");if(r instanceof Rn||n instanceof Rn)throw new Error("Cannot perform operation on null values");if(r instanceof We&&n instanceof We)switch(t.operator.value){case"+":return new We(r.value+n.value);case"-":return new We(r.value-n.value);case"*":return new We(r.value*n.value);case"/":return new We(r.value/n.value);case"%":return new We(r.value%n.value);case"<":return new Ze(r.value":return new Ze(r.value>n.value);case">=":return new Ze(r.value>=n.value);case"<=":return new Ze(r.value<=n.value)}else if(r instanceof Ye&&n instanceof Ye)switch(t.operator.value){case"+":return new Ye(r.value.concat(n.value))}else if(n instanceof Ye){const a=n.value.find(i=>i.value===r.value)!==void 0;switch(t.operator.value){case"in":return new Ze(a);case"not in":return new Ze(!a)}}if(r instanceof Ae||n instanceof Ae)switch(t.operator.value){case"+":return new Ae(r.value.toString()+n.value.toString())}if(r instanceof Ae&&n instanceof Ae)switch(t.operator.value){case"in":return new Ze(n.value.includes(r.value));case"not in":return new Ze(!n.value.includes(r.value))}if(r instanceof Ae&&n instanceof Dt)switch(t.operator.value){case"in":return new Ze(n.value.has(r.value));case"not in":return new Ze(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if(t.filter.type==="Identifier"){const n=t.filter;if(r instanceof Ye)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new We(r.value.length);case"reverse":return new Ye(r.value.reverse());case"sort":return new Ye(r.value.sort((a,i)=>{if(a.type!==i.type)throw new Error(`Cannot compare different types: ${a.type} and ${i.type}`);switch(a.type){case"NumericValue":return a.value-i.value;case"StringValue":return a.value.localeCompare(i.value);default:throw new Error(`Cannot compare type: ${a.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof Ae)switch(n.value){case"length":return new We(r.value.length);case"upper":return new Ae(r.value.toUpperCase());case"lower":return new Ae(r.value.toLowerCase());case"title":return new Ae(Jf(r.value));case"capitalize":return new Ae(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new Ae(r.value.trim());default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(r instanceof We)switch(n.value){case"abs":return new We(Math.abs(r.value));default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(r instanceof Dt)switch(n.value){case"items":return new Ye(Array.from(r.value.entries()).map(([a,i])=>new Ye([new Ae(a),i])));case"length":return new We(r.value.size);default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}throw new Error(`Cannot apply filter "${n.value}" to type: ${r.type}`)}else if(t.filter.type==="CallExpression"){const n=t.filter;if(n.callee.type!=="Identifier")throw new Error(`Unknown filter: ${n.callee.type}`);const a=n.callee.value;if(r instanceof Ye){switch(a){case"selectattr":{if(r.value.some(c=>!(c instanceof Dt)))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some(c=>c.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[i,s,o]=n.args.map(c=>this.evaluate(c,e));let l;if(s){const c=e.tests.get(s.value);if(!c)throw new Error(`Unknown test: ${s.value}`);l=c}else l=(...c)=>c[0].__bool__().value;const d=r.value.filter(c=>{const u=c.value.get(i.value);return u?l(u,o):!1});return new Ye(d)}}throw new Error(`Unknown ArrayValue filter: ${a}`)}else throw new Error(`Cannot apply filter "${a}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const a=n(r);return new Ze(t.negate?!a:a)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);switch(t.operator.value){case"not":return new Ze(!r.value);default:throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const a=this.evaluate(n,e);a.type!=="NullValue"&&a.type!=="UndefinedValue"&&(r+=a.value)}return new Ae(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const r=[],n=new Map;for(const i of t.args)if(i.type==="KeywordArgumentExpression"){const s=i;n.set(s.key.value,this.evaluate(s.value,e))}else r.push(this.evaluate(i,e));n.size>0&&r.push(new Dt(n));const a=this.evaluate(t.callee,e);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);return a.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof Ye||t instanceof Ae))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),a=this.evaluate(e.stop,r),i=this.evaluate(e.step,r);if(!(n instanceof We||n instanceof Bt))throw new Error("Slice start must be numeric or undefined");if(!(a instanceof We||a instanceof Bt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof We||i instanceof Bt))throw new Error("Slice step must be numeric or undefined");return t instanceof Ye?new Ye(dc(t.value,n.value,a.value,i.value)):new Ae(dc(Array.from(t.value),n.value,a.value,i.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new Ae(t.property.value);let a;if(r instanceof Dt){if(!(n instanceof Ae))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof Ye||r instanceof Ae)if(n instanceof We)a=r.value.at(n.value),r instanceof Ae&&(a=new Ae(r.value.at(n.value)));else if(n instanceof Ae)a=r.builtins.get(n.value);else throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof Ae))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=r.builtins.get(n.value)}return a instanceof tr?a:new Bt}evaluateSet(t,e){const r=this.evaluate(t.value,e);if(t.assignee.type==="Identifier"){const n=t.assignee.value;e.setVariable(n,r)}else if(t.assignee.type==="MemberExpression"){const n=t.assignee,a=this.evaluate(n.object,e);if(!(a instanceof Dt))throw new Error("Cannot assign to member of non-object");if(n.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");a.value.set(n.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new Rn}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new Ds(e),n=this.evaluate(t.iterable,r);if(!(n instanceof Ye))throw new Error(`Expected iterable type in for loop: got ${n.type}`);let a="";for(let i=0;i0?n.value[i-1]:new Bt],["nextitem",ic.value.length?"few":"many"} items to unpack`);for(let u=0;uthis.evaluate(r,e)));case"TupleLiteral":return new bw(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{const r=new Map;for(const[n,a]of t.value){const i=this.evaluate(n,e);if(!(i instanceof Ae))throw new Error(`Object keys must be strings: got ${i.type}`);r.set(i.value,this.evaluate(a,e))}return new Dt(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Ka(t){switch(typeof t){case"number":return new We(t);case"string":return new Ae(t);case"boolean":return new Ze(t);case"object":return t===null?new Rn:Array.isArray(t)?new Ye(t.map(Ka)):new Dt(new Map(Object.entries(t).map(([e,r])=>[e,Ka(r)])));case"function":return new Jt((e,r)=>{const n=t(...e.map(a=>a.value))??null;return Ka(n)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var $w=class{parsed;constructor(t){const e=aw(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ww(e)}render(t){const e=new Ds;e.set("false",!1),e.set("true",!0),e.set("raise_exception",a=>{throw new Error(a)}),e.set("range",yw);for(const[a,i]of Object.entries(t))e.set(a,i);return new vw(e).run(this.parsed).value}};async function em(t,e){const r=await Promise.all([pr(t,"tokenizer.json",!0,e),pr(t,"tokenizer_config.json",!0,e)]);return e.legacy!==null&&(r[1].legacy=e.legacy),r}function xw(t,e){const r=[];let n=0;for(const a of t.matchAll(e)){const i=a[0];n0&&r.push(i),n=a.index+i.length}return nthis.tokens_to_ids.get(r)??this.unk_token_id)}convert_ids_to_tokens(e){return e.map(r=>this.vocab[r]??this.unk_token)}}class Iw extends Yn{constructor(e){super(e),this.tokens_to_ids=ho(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r}encode(e){const r=[];for(const n of e){const a=[...n];if(a.length>this.max_input_chars_per_word){r.push(this.unk_token);continue}let i=!1,s=0;const o=[];for(;s0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){d=c;break}--l}if(d===null){i=!0;break}o.push(d),s=l}i?r.push(this.unk_token):r.push(...o)}return r}}class Aw extends Yn{constructor(e,r){super(e);const n=e.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let a=0;a[a,i])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=r.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=kc(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new J0,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const r=e.sentence,n=r.length;let a=0;for(;a{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]]))})(),Mw=Xg(nm);class Ow extends Yn{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ho(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r;this.bpe_ranks=new Map(e.merges.map((r,n)=>[r,n])),this.merges=e.merges.map(r=>r.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(e){if(e.length===0)return[];const r=this.cache.get(e);if(r!==void 0)return r;const n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let a=[];if(n.length>1){const i=new Z0((l,d)=>l.score`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`)):r.push(this.unk_token)}return r}}class zw extends Yn{constructor(e,r){super(e),this.tokens_to_ids=ho(r.target_lang?e.vocab[r.target_lang]:e.vocab),this.bos_token=r.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=r.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=r.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=r.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[n,a]of this.tokens_to_ids)this.vocab[a]=n}encode(e){return e}}class vt extends mt{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new Gw(e);case"Precompiled":return new ly(e);case"Sequence":return new Ww(e);case"Replace":return new Pw(e);case"NFC":return new Rw(e);case"NFKC":return new Bw(e);case"NFKD":return new Dw(e);case"Strip":return new Nw(e);case"StripAccents":return new Lw(e);case"Lowercase":return new Uw(e);case"Prepend":return new Fw(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class Pw extends vt{normalize(e){const r=mi(this.config.pattern);return r===null?e:e.replaceAll(r,this.config.content)}}class Rw extends vt{normalize(e){return e=e.normalize("NFC"),e}}class Bw extends vt{normalize(e){return e=e.normalize("NFKC"),e}}class Dw extends vt{normalize(e){return e=e.normalize("NFKD"),e}}class Nw extends vt{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class Lw extends vt{normalize(e){return e=rm(e),e}}class Uw extends vt{normalize(e){return e=e.toLowerCase(),e}}class Fw extends vt{normalize(e){return e=this.config.prepend+e,e}}class Ww extends vt{constructor(e){super(e),this.normalizers=e.normalizers.map(r=>vt.fromConfig(r))}normalize(e){return this.normalizers.reduce((r,n)=>n.normalize(r),e)}}class Gw extends vt{_tokenize_chinese_chars(e){const r=[];for(let n=0;n=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103}stripAccents(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_is_control(e){switch(e){case" ":case` -`:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}_clean_text(e){const r=[];for(const n of e){const a=n.charCodeAt(0);a===0||a===65533||this._is_control(n)||(/^\s$/.test(n)?r.push(" "):r.push(n))}return r.join("")}normalize(e){return this.config.clean_text&&(e=this._clean_text(e)),this.config.handle_chinese_chars&&(e=this._tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.stripAccents(e))):this.config.strip_accents&&(e=this.stripAccents(e)),e}}class It extends mt{static fromConfig(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new Vw(e);case"Sequence":return new uy(e);case"Whitespace":return new dy(e);case"WhitespaceSplit":return new cy(e);case"Metaspace":return new sm(e);case"ByteLevel":return new Hw(e);case"Split":return new qw(e);case"Punctuation":return new jw(e);case"Digits":return new Kw(e);case"Replace":return new py(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e,r){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e,r){return(Array.isArray(e)?e.map(n=>this.pre_tokenize_text(n,r)):this.pre_tokenize_text(e,r)).flat()}_call(e,r){return this.pre_tokenize(e,r)}}class Vw extends It{constructor(e){super(),this.pattern=new RegExp(`[^\\s${Wn}]+|[${Wn}]`,"gu")}pre_tokenize_text(e,r){return e.trim().match(this.pattern)||[]}}class Hw extends It{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=nm,this.text_encoder=new TextEncoder}pre_tokenize_text(e,r){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(a=>Array.from(this.text_encoder.encode(a),i=>this.byte_encoder[i]).join(""))}}class qw extends It{constructor(e){super(),this.config=e,this.pattern=mi(this.config.pattern,this.config.invert)}pre_tokenize_text(e,r){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:xw(e,this.pattern)}}class jw extends It{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Wn}]+|[${Wn}]+`,"gu")}pre_tokenize_text(e,r){return e.match(this.pattern)||[]}}class Kw extends It{constructor(e){super(),this.config=e;const r=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(r,"gu")}pre_tokenize_text(e,r){return e.match(this.pattern)||[]}}class gi extends mt{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new Yw(e);case"ByteLevel":return new Xw(e);case"RobertaProcessing":return new im(e);case"BertProcessing":return new am(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...r){throw Error("post_process should be implemented in subclass.")}_call(e,...r){return this.post_process(e,...r)}}class am extends gi{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,r=null,{add_special_tokens:n=!0}={}){n&&(e=st([this.cls],e,[this.sep]));let a=new Array(e.length).fill(0);if(r!==null){const i=n&&this instanceof im?[this.sep]:[],s=n?[this.sep]:[];e=st(e,i,r,s),a=st(a,new Array(r.length+i.length+s.length).fill(1))}return{tokens:e,token_type_ids:a}}}class im extends am{}class Yw extends gi{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,r=null,{add_special_tokens:n=!0}={}){const a=r===null?this.single:this.pair;let i=[],s=[];for(const o of a)"SpecialToken"in o?n&&(i.push(o.SpecialToken.id),s.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(i=st(i,e),s=st(s,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(i=st(i,r),s=st(s,new Array(r.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:s}}}class Xw extends gi{post_process(e,r=null){return r&&(e=st(e,r)),{tokens:e}}}class $t extends mt{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(e===null)return null;switch(e.type){case"WordPiece":return new ty(e);case"Metaspace":return new oy(e);case"ByteLevel":return new ry(e);case"Replace":return new Qw(e);case"ByteFallback":return new Zw(e);case"Fuse":return new Jw(e);case"Strip":return new ey(e);case"Sequence":return new ay(e);case"CTC":return new ny(e);case"BPEDecoder":return new iy(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class Qw extends $t{decode_chain(e){const r=mi(this.config.pattern);return r===null?e:e.map(n=>n.replaceAll(r,this.config.content))}}class Zw extends $t{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const r=[];let n=[];for(const a of e){let i=null;if(a.length===6&&a.startsWith("<0x")&&a.endsWith(">")){const s=parseInt(a.slice(3,5),16);isNaN(s)||(i=s)}if(i!==null)n.push(i);else{if(n.length>0){const s=this.text_decoder.decode(Uint8Array.from(n));r.push(s),n=[]}r.push(a)}}if(n.length>0){const a=this.text_decoder.decode(Uint8Array.from(n));r.push(a),n=[]}return r}}class Jw extends $t{decode_chain(e){return[e.join("")]}}class ey extends $t{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map(r=>{let n=0;for(let i=0;i(n!==0&&(r.startsWith(this.config.prefix)?r=r.replace(this.config.prefix,""):r=" "+r),this.cleanup&&(r=fo(r)),r))}}class ry extends $t{constructor(e){super(e),this.byte_decoder=Mw,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const r=e.join(""),n=new Uint8Array([...r].map(i=>this.byte_decoder[i]));return this.text_decoder.decode(n)}decode_chain(e){const r=[];let n=[];for(const a of e)this.added_tokens.find(i=>i.content===a)!==void 0?(n.length>0&&(r.push(this.convert_tokens_to_string(n)),n=[]),r.push(a)):n.push(a);return n.length>0&&r.push(this.convert_tokens_to_string(n)),r}}class ny extends $t{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const r=[e[0]];for(let i=1;ii!==this.pad_token).join("");return this.cleanup&&(a=fo(a).replaceAll(this.word_delimiter_token," ").trim()),a}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class ay extends $t{constructor(e){super(e),this.decoders=e.decoders.map(r=>$t.fromConfig(r))}decode_chain(e){return this.decoders.reduce((r,n)=>n.decode_chain(r),e)}}class iy extends $t{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map((r,n)=>r.replaceAll(this.suffix,n===e.length-1?"":" "))}}class sy extends $t{decode_chain(e){let r="";for(let n=1;nn.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}}class uy extends It{constructor(e){super(),this.tokenizers=e.pretokenizers.map(r=>It.fromConfig(r))}pre_tokenize_text(e,r){return this.tokenizers.reduce((n,a)=>a.pre_tokenize(n,r),[e])}}class dy extends It{constructor(e){super()}pre_tokenize_text(e,r){return e.match(/\w+|[^\w\s]+/g)||[]}}class cy extends It{constructor(e){super()}pre_tokenize_text(e,r){return kw(e)}}class py extends It{constructor(e){super(),this.config=e,this.pattern=mi(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,r){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const hy=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function fy(t,e,r,n){for(const a of Object.keys(t)){const i=e-t[a].length,s=r(a),o=new Array(i).fill(s);t[a]=n==="right"?st(t[a],o):st(o,t[a])}}function my(t,e){for(const r of Object.keys(t))t[r].length=e}class xe extends mt{return_token_type_ids=!1;_default_chat_template=`{% for message in messages %}{{'<|im_start|>' + message['role'] + ' -' + message['content'] + '<|im_end|>' + ' -'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant -' }}{% endif %}`;padding_side="right";constructor(e,r){super(),this._tokenizer_config=r,this.normalizer=vt.fromConfig(e.normalizer),this.pre_tokenizer=It.fromConfig(e.pre_tokenizer),this.model=Yn.fromConfig(e.model,r),this.post_processor=gi.fromConfig(e.post_processor),this.decoder=$t.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const n of e.added_tokens){const a=new Tw(n);this.added_tokens.push(a),this.model.tokens_to_ids.set(a.content,a.id),this.model.vocab[a.id]=a.content,a.special&&(this.special_tokens.push(a.content),this.all_special_ids.push(a.id))}if(this.additional_special_tokens=r.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.map(n=>`${n.lstrip?"\\s*":""}(${Sc(n.content)})${n.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=r.model_max_length,this.remove_space=r.remove_space,this.clean_up_tokenization_spaces=r.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=r.do_lowercase_and_remove_accent??!1,r.padding_side&&(this.padding_side=r.padding_side),this.legacy=!1,this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){const n=Object.create(null);for(const{name:a,template:i}of this.chat_template){if(typeof a!="string"||typeof i!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[a]=i}this.chat_template=n}this._compiled_template_cache=new Map}getToken(...e){for(const r of e){const n=this._tokenizer_config[r];if(n)if(typeof n=="object"){if(n.__type==="AddedToken")return n.content;throw Error(`Unknown token: ${n}`)}else return n}return null}static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",legacy:o=null}={}){const l=await em(e,{progress_callback:r,config:n,cache_dir:a,local_files_only:i,revision:s,legacy:o});return new this(...l)}_call(e,{text_pair:r=null,add_special_tokens:n=!0,padding:a=!1,truncation:i=null,max_length:s=null,return_tensor:o=!0}={}){const l=Array.isArray(e);let d;if(l){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");d=e.map((u,h)=>this._encode_plus(u,{text_pair:r[h],add_special_tokens:n}))}else d=e.map(u=>this._encode_plus(u,{add_special_tokens:n}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");d=[this._encode_plus(e,{text_pair:r,add_special_tokens:n})]}if(s===null?a==="max_length"?s=this.model_max_length:s=mr(d.map(u=>u.input_ids.length))[0]:i||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),s=Math.min(s,this.model_max_length),a||i)for(let u=0;us?i&&my(d[u],s):a&&fy(d[u],s,h=>h==="input_ids"?this.pad_token_id:0,this.padding_side));const c={};if(o){if(!(a&&i)&&d.some(h=>{for(const m of Object.keys(h))if(h[m].length!==d[0][m]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const u=[d.length,d[0].input_ids.length];for(const h of Object.keys(d[0]))c[h]=new ae("int64",BigInt64Array.from(d.flatMap(m=>m[h]).map(BigInt)),u)}else{for(const u of Object.keys(d[0]))c[u]=d.map(h=>h[u]);if(!l)for(const u of Object.keys(c))c[u]=c[u][0]}return c}_encode_text(e){return e===null?null:(this.added_tokens_regex?e.split(this.added_tokens_regex).filter(a=>a):[e]).map((a,i)=>{if(this.added_tokens.find(o=>o.content===a)!==void 0)return a;{if(this.remove_space===!0&&(a=a.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(a=Sw(a)),this.normalizer!==null&&(a=this.normalizer(a)),a.length===0)return[];const o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:i}):[a];return this.model(o)}}).flat()}_encode_plus(e,{text_pair:r=null,add_special_tokens:n=!0}={}){const{tokens:a,token_type_ids:i}=this._tokenize_helper(e,{pair:r,add_special_tokens:n}),s=this.model.convert_tokens_to_ids(a),o={input_ids:s,attention_mask:new Array(s.length).fill(1)};return this.return_token_type_ids&&i&&(o.token_type_ids=i),o}_tokenize_helper(e,{pair:r=null,add_special_tokens:n=!1}={}){const a=this._encode_text(e),i=this._encode_text(r);return this.post_processor?this.post_processor(a,i,{add_special_tokens:n}):{tokens:st(a??[],i??[])}}tokenize(e,{pair:r=null,add_special_tokens:n=!1}={}){return this._tokenize_helper(e,{pair:r,add_special_tokens:n}).tokens}encode(e,{text_pair:r=null,add_special_tokens:n=!0}={}){return this._encode_plus(e,{text_pair:r,add_special_tokens:n}).input_ids}batch_decode(e,r={}){return e instanceof ae&&(e=e.tolist()),e.map(n=>this.decode(n,r))}decode(e,r={}){if(e instanceof ae&&(e=tm(e)),!Array.isArray(e)||e.length===0||!Qg(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:n=null}){let a=this.model.convert_ids_to_tokens(e);r&&(a=a.filter(s=>!this.special_tokens.includes(s)));let i=this.decoder?this.decoder(a):a.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(i=i.replaceAll(this.decoder.end_of_word_suffix," "),r&&(i=i.trim())),(n??this.clean_up_tokenization_spaces)&&(i=fo(i)),i}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(e,{chat_template:r=null,add_generation_prompt:n=!1,tokenize:a=!0,padding:i=!1,truncation:s=!1,max_length:o=null,return_tensor:l=!0,tokenizer_kwargs:d={},...c}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null&&this.default_chat_template&&typeof this.default_chat_template=="object"){const g=this.chat_template??this.default_chat_template;if(r!==null&&Object.hasOwn(g,r))r=g[r];else if(r===null&&"default"in g)r=g.default;else if(r===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(g).sort()}.`)}else r??=this.chat_template??this.default_chat_template;if(typeof r!="string")throw Error(`chat_template must be a string, but got ${typeof r}`);let u=this._compiled_template_cache.get(r);u===void 0&&(u=new $w(r),this._compiled_template_cache.set(r,u));const h=Object.create(null);for(const g of hy){const _=this.getToken(g);_&&(h[g]=_)}const m=u.render({messages:e,add_generation_prompt:n,...h,...c});return a?this._call(m,{add_special_tokens:!1,padding:i,truncation:s,max_length:o,return_tensor:l,...d}).input_ids:m}}class gy extends xe{return_token_type_ids=!0}class _y extends xe{return_token_type_ids=!0}class wy extends xe{return_token_type_ids=!0}class yy extends xe{return_token_type_ids=!0}class by extends xe{return_token_type_ids=!0}class vy extends xe{return_token_type_ids=!0}class $y extends xe{return_token_type_ids=!0}class xy extends xe{return_token_type_ids=!0}class Sy extends xe{return_token_type_ids=!0}class Ey extends xe{}class ky extends xe{}class Cy extends xe{return_token_type_ids=!0;constructor(e,r){super(e,r),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ty extends xe{return_token_type_ids=!0}class Iy extends xe{}class om extends xe{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}'}class Ay extends xe{}class lm extends xe{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)),this.lang_to_token=n=>n}_build_translation_inputs(e,r,n){return mo(this,e,r,n)}}class My extends lm{}class Oy extends xe{}class zy extends om{constructor(e,r){const n=".,!?…。,、।۔،",a=e.pre_tokenizer?.pretokenizers[0]?.pattern;a&&a.Regex===` ?[^(\\s|[${n}])]+`&&(a.Regex=` ?[^\\s${n}]+`),super(e,r)}}const Da="▁";class um extends xe{_default_chat_template=`{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> -' + system_message + ' -<> - -' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> -' + content.strip() + ' -<> - -' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`;DEFAULT_SYSTEM_PROMPT=`You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. - -If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.`;padding_side="left";constructor(e,r){super(e,r),this.use_default_system_prompt=r.use_default_system_prompt??!1,this.legacy=r.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new sm({replacement:Da,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(e){if(e===null)return null;if(this.legacy||e.length===0)return super._encode_text(e);let r=super._encode_text(Da+e.replaceAll(Da," "));return r.length>1&&r[0]===Da&&this.special_tokens.includes(r[1])&&(r=r.slice(1)),r}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll(` -`,"\\n").replaceAll("'","\\'"))}}class Py extends um{}class Ry extends xe{}class By extends xe{}class Dy extends xe{}class Ny extends xe{}class Ly extends xe{}class Uy extends xe{}class Fy extends xe{_default_chat_template=`{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + ' -' + message['content'] | trim + ' -' }}{% endfor %}{% if add_generation_prompt %}{{'model -'}}{% endif %}`}class Wy extends xe{}function mo(t,e,r,n){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const a=n.src_lang,i=n.tgt_lang;if(!t.language_codes.includes(i))throw new Error(`Target language code "${i}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(a!==void 0){if(!t.language_codes.includes(a))throw new Error(`Source language code "${a}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(const s of t.post_processor.config.single)if("SpecialToken"in s&&t.languageRegex.test(s.SpecialToken.id)){s.SpecialToken.id=t.lang_to_token(a);break}}return n.forced_bos_token_id=t.model.convert_tokens_to_ids([t.lang_to_token(i)])[0],t._call(e,r)}class Gy extends xe{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)),this.lang_to_token=n=>n}_build_translation_inputs(e,r,n){return mo(this,e,r,n)}}class Vy extends xe{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)).map(n=>n.slice(2,-2)),this.lang_to_token=n=>`__${n}__`}_build_translation_inputs(e,r,n){return mo(this,e,r,n)}}const dm=[["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"]],Na=new Map(dm),Hy=new Map([...dm.map(([t,e])=>[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class qy extends xe{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}';_decode_asr(e,{return_timestamps:r=!1,return_language:n=!1,time_precision:a=null,force_full_sequences:i=!0}={}){if(a===null)throw Error("Must specify time_precision");let s=null;const o=r==="word";function l(){return{language:s,timestamp:[null,null],text:""}}const d=[];let c=l(),u=0;const h=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let m=[],g=[],_=!1,b=null;const $=new Set(this.all_special_ids);for(const k of e){const T=k.tokens,A=o?k.token_timestamps:null;let R=null,W=h;if("stride"in k){const[ee,P,J]=k.stride;if(u-=P,b=ee-J,P&&(W=P/a+h),J)for(let te=T.length-1;te>=0;--te){const F=T[te];if(F>=h){if(R!==null&&(F-h)*a=h){const J=(P-h)*a+u,te=Ca(J,2);if(R!==null&&P>=R)_=!0;else if(_||m.length>0&&P0?(m.push(K),o&&g.push(q)):m.every(ee=>ee.length===0)&&(c=l(),m=[],K=[],g=[],q=[])}if(m.length>0){if(i&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[k,T]=this.findLongestCommonSequence(m,g),A=this.decode(k);c.text=A,o&&(c.words=this.collateWordTimestamps(k,T,s)),d.push(c)}let y=Object.create(null);const E=d.map(k=>k.text).join("");if(r||n){for(let k=0;k0;let o=s?[]:null,l=s?r[0]:null;for(let d=1;dte===ee[F]).length,J=P/k+T;P>1&&J>u&&(u=J,h=[A,R,K,q])}const[g,_,b,$]=h,y=Math.floor((_+g)/2),E=Math.floor(($+b)/2);i.push(...n.slice(0,y)),n=c.slice(E),a=n.length,s&&(o.push(...l.slice(0,y)),l=r[d].slice(E))}return i.push(...n),s?(o.push(...l),[i,o]):[i,[]]}collateWordTimestamps(e,r,n){const[a,i,s]=this.combineTokensIntoWords(e,n),o=[];for(let l=0;l=a){const o=Ca((s-a)*n,2);i.push(`<|${o}|>`),i.push([])}else i[i.length-1].push(s);return i=i.map(s=>typeof s=="string"?s:super.decode(s,r)),i.join("")}splitTokensOnUnicode(e){const r=this.decode(e,{decode_with_timestamps:!0}),n="�",a=[],i=[],s=[];let o=[],l=[],d=0;for(let c=0;c=this.model.tokens_to_ids.get("<|endoftext|>"),g=c.startsWith(" "),_=c.trim(),b=l.test(_);if(m||g||b||i.length===0)i.push(c),s.push(u),o.push(h);else{const $=i.length-1;i[$]+=c,s[$].push(...u),o[$].push(...h)}}return[i,s,o]}mergePunctuations(e,r,n,a,i){const s=structuredClone(e),o=structuredClone(r),l=structuredClone(n);let d=s.length-2,c=s.length-1;for(;d>=0;)s[d].startsWith(" ")&&a.includes(s[d].trim())?(s[c]=s[d]+s[c],o[c]=st(o[d],o[c]),l[c]=st(l[d],l[c]),s[d]="",o[d]=[],l[d]=[]):c=d,--d;for(d=0,c=1;cu),o.filter(u=>u.length>0),l.filter(u=>u.length>0)]}get_decoder_prompt_ids({language:e=null,task:r=null,no_timestamps:n=!0}={}){const a=[];if(e){e=e.toLowerCase();let i=Hy.get(e);if(i===void 0)if(Na.has(e))i=e;else{const l=e.length===2?Na.keys():Na.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(l)}`)}const s=this.model.tokens_to_ids.get(`<|${i}|>`);if(s===void 0)throw new Error(`Unable to find language "${i}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);a.push(s)}else a.push(null);if(r){if(r=r.toLowerCase(),r!=="transcribe"&&r!=="translate")throw new Error(`Task "${r}" is not supported. Must be one of: ["transcribe", "translate"]`);const i=this.model.tokens_to_ids.get(`<|${r}|>`);if(i===void 0)throw new Error(`Unable to find task "${r}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);a.push(i)}else a.push(null);if(n){const i=this.model.tokens_to_ids.get("<|notimestamps|>");if(i===void 0)throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');a.push(i)}return a.map((i,s)=>[s+1,i]).filter(i=>i[1]!==null)}}class jy extends xe{}class Ky extends xe{}class Yy extends xe{}class Xy extends xe{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(n=>this.languageRegex.test(n)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[r,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(r);if(n.length===2){const[a,i]=n;return this.supported_language_codes.includes(a)||console.warn(`Unsupported language code "${a}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),st([a],super._encode_text(i))}}}class Qy extends xe{}class cm extends xe{_default_chat_template="{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}"}class Zy extends cm{}class Jy extends xe{}class eb extends xe{}class tb extends xe{constructor(e,r){super(e,r),this.decoder=new sy({})}}class rb extends xe{}class nb{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:Iy,DistilBertTokenizer:Ey,CamembertTokenizer:ky,DebertaTokenizer:by,DebertaV2Tokenizer:vy,BertTokenizer:gy,HerbertTokenizer:$y,ConvBertTokenizer:xy,RoFormerTokenizer:Sy,XLMTokenizer:Cy,ElectraTokenizer:Ty,MobileBertTokenizer:wy,SqueezeBertTokenizer:yy,AlbertTokenizer:_y,GPT2Tokenizer:om,BartTokenizer:Ay,MBartTokenizer:lm,MBart50Tokenizer:My,RobertaTokenizer:Oy,WhisperTokenizer:qy,CodeGenTokenizer:jy,CLIPTokenizer:Ky,SiglipTokenizer:Yy,MarianTokenizer:Xy,BloomTokenizer:zy,NllbTokenizer:Gy,M2M100Tokenizer:Vy,LlamaTokenizer:um,CodeLlamaTokenizer:Py,XLMRobertaTokenizer:Ry,MPNetTokenizer:By,FalconTokenizer:Dy,GPTNeoXTokenizer:Ny,EsmTokenizer:Ly,Wav2Vec2CTCTokenizer:Qy,BlenderbotTokenizer:cm,BlenderbotSmallTokenizer:Zy,SpeechT5Tokenizer:Jy,NougatTokenizer:eb,VitsTokenizer:tb,Qwen2Tokenizer:Uy,GemmaTokenizer:Fy,Grok1Tokenizer:Wy,CohereTokenizer:rb,PreTrainedTokenizer:xe};static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",legacy:o=null}={}){const[l,d]=await em(e,{progress_callback:r,config:n,cache_dir:a,local_files_only:i,revision:s,legacy:o}),c=d.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let u=this.TOKENIZER_CLASS_MAPPING[c];return u||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=xe),new u(l,d)}}async function ab(t,e){return await pr(t,"config.json",!0,e)}class ib{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 ab(e,{progress_callback:r,config:n,cache_dir:a,local_files_only:i,revision:s});return new this(o)}}class dr{static async from_pretrained(...e){return ib.from_pretrained(...e)}}const La=Object.freeze({cpu:"cpu",gpu:"gpu",wasm:"wasm",webgpu:"webgpu"}),sb=function(){let t;return async function(){if(t===void 0)if(Dn.IS_NODE_ENV)t=!0;else if(!Dn.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}}(),yt=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4"}),ob=Object.freeze({[La.cpu]:yt.q8,[La.gpu]:yt.fp32,[La.wasm]:yt.q8,[La.webgpu]:yt.fp32}),cc=Object.freeze({[yt.fp32]:"",[yt.fp16]:"_fp16",[yt.int8]:"_int8",[yt.uint8]:"_uint8",[yt.q8]:"_quantized",[yt.q4]:"_q4",[yt.bnb4]:"_bnb4"});class rr extends mt{_call(e,r){throw Error("`_call` should be implemented in a subclass")}}class go extends mt{_call(e,r){throw Error("`_call` should be implemented in a subclass")}}class pc extends mt{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 lb extends rr{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 yb extends go{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 bb{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,Yr(e,Object.getOwnPropertyNames(this)))}}class pm extends mt{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}}class _o extends mt{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof _o&&(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 $b extends pm{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 _i extends mt{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 Eb(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 xb(e)}}class xb extends _i{sample(e,r=-1){let n=this.getLogits(e,r);return[[mr(n)[1],0]]}}class Sb extends _i{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=Ec(a,n),s=Hn(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 Eb extends _i{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=Ec(a,n),s=Hn(i.map(o=>o[1]));return Array.from({length:this.generation_config.num_beams},(o,l)=>[i[l][0],Math.log(s[l])])}}const fe={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},ci=new Map,hm=new Map,Bn=new Map;async function kb(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=U0(n);let i=r.dtype;if(typeof i!="string"&&(i&&i.hasOwnProperty(e)?i=i[e]:(i=ob[a[0]],console.warn(`Dtype not specified for ${e}. Using the default dtype: ${i}.`))),cc.hasOwnProperty(i)){if(i===yt.fp16&&!await sb())throw new Error("The device does not support fp16.")}else throw new Error(`Invalid dtype: ${i}. Should be one of: ${Object.keys(yt).join(", ")}`);const s=cc[i],o=`${r.subfolder??""}/${e}${s}.onnx`,l=await vs(t,o,!0,r),d={...r.session_options};if(d.executionProviders??=a,d.externalData!==void 0)for(let c=0;ckb(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 fr(t,e){const r=Cb(t,e);try{const n=Object.fromEntries(Object.entries(r).map(([i,s])=>[i,s.ort_tensor]));let a=await t.run(n);a=fm(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 fm(t){for(let e in t)Qf(t[e])?t[e]=new ae(t[e]):typeof t[e]=="object"&&fm(t[e]);return t}function Tb(t){if(t instanceof ae)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 ae("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new ae("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function mm(t){return new ae("bool",[t],[1])}async function hc(t,e){let{encoder_outputs:r,past_key_values:n}=e;if(!r){const l=Yr(e,t.sessions.model.inputNames);r=(await Gn(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 wo(t,s,!0)}async function Gn(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 ae("int64",new BigInt64Array(n.input_ids.data.length),n.input_ids.dims)),await fr(r,n)}async function wo(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=mm(!!a)),t.addPastKeyValues(i,a);const s=Yr(i,n.inputNames);return await fr(n,s)}function Ib(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=Tb(e),a}class Z extends mt{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,r){super(),this.config=e,this.sessions=r;const n=Bn.get(this.constructor),a=ci.get(n);this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,a===fe.DecoderOnly?(this.can_generate=!0,this._forward=wo,this._prepare_inputs_for_generation=Ib):a===fe.Seq2Seq||a===fe.Vision2Seq||a===fe.Musicgen?(this.can_generate=!0,this._forward=hc,this._prepare_inputs_for_generation=Ab):a===fe.EncoderDecoder?this._forward=hc:a===fe.ImageTextToText?(this.can_generate=!0,console.warn("TODO: Implement visionDecoderForward")):this._forward=Gn}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:c=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:c,session_options:u};const m=Bn.get(this),g=ci.get(m);let _;return g===fe.DecoderOnly?_=await Promise.all([dr.from_pretrained(e,h),Sr(e,{model:h.model_file_name??"model"},h),pr(e,"generation_config.json",!1,h)]):g===fe.Seq2Seq||g===fe.Vision2Seq?_=await Promise.all([dr.from_pretrained(e,h),Sr(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h),pr(e,"generation_config.json",!1,h)]):g===fe.MaskGeneration?_=await Promise.all([dr.from_pretrained(e,h),Sr(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]):g===fe.EncoderDecoder?_=await Promise.all([dr.from_pretrained(e,h),Sr(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h)]):g===fe.ImageTextToText?_=await Promise.all([dr.from_pretrained(e,h),Sr(e,{embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"},h),pr(e,"generation_config.json",!1,h)]):g===fe.Musicgen?_=await Promise.all([dr.from_pretrained(e,h),Sr(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h),pr(e,"generation_config.json",!1,h)]):(g!==fe.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.`),_=await Promise.all([dr.from_pretrained(e,h),Sr(e,{model:h.model_file_name??"model"},h)])),new this(..._)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_warper(e){const r=new pc;return e.temperature!==null&&e.temperature!==1&&r.push(new _b(e.temperature)),e.top_k!==null&&e.top_k!==0&&r.push(new yb(e.top_k)),e.top_p!==null&&e.top_p<1&&r.push(new wb(e.top_p)),r}_get_logits_processor(e,r,n=null){const a=new pc;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&a.push(new pb(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&a.push(new cb(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&a.push(new mb(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&a.push(new hb(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 fb(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&a.push(new lb(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&a.push(new ub(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 db(e.begin_suppress_tokens,i))}return e.guidance_scale!==null&&e.guidance_scale>1&&a.push(new gb(e.guidance_scale)),n!==null&&a.extend(n),a}_prepare_generation_config(e,r){const n=new bb(this.config);return"generation_config"in this&&Object.assign(n,this.generation_config),e&&Object.assign(n,e),r&&Object.assign(n,Yr(r,Object.getOwnPropertyNames(n))),n}_get_stopping_criteria(e,r=null){const n=new _o;return e.max_length!==null&&n.push(new vb(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new $b(e.eos_token_id)),r&&n.extend(r),n}_validate_model_class(){if(!this.can_generate){const e=[So,gg,mg,fg],r=Bn.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 ae("int64",e,[e.length,1]),a||(n.attention_mask=jt([n.attention_mask,ui([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=Yr(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=Yr(r,this.sessions.model.inputNames);let{last_hidden_state:s}=await Gn(this,i);return a.guidance_scale!==null&&a.guidance_scale>1&&(s=jt([s,K0(s,0)],0),"attention_mask"in r&&(r.attention_mask=jt([r.attention_mask,Q0(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 ae("int64",o,[o.length,1]);return n.decoder_attention_mask=Y0(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 c=this.config.is_encoder_decoder;c&&("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;c?{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),g=this._get_stopping_criteria(r,a),_=l[d].dims.at(0),b=_i.getSampler(r),$=new Array(_).fill(0),y=u.tolist();for(i&&i.put(y);;){l=this.prepare_inputs_for_generation(y,l,r);const E=await this.forward(l),k=E.logits.slice(null,-1,null),T=m(y,k),A=[];for(let W=0;WW))break;l=this._update_model_kwargs_for_generation({generated_input_ids:A,outputs:E,model_inputs:l,is_encoder_decoder:c})}return i&&i.end(),new ae("int64",y.flat(),[y.length,y[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 c=Array.from({length:this.config.decoder_layers},(b,$)=>jt(d.map(y=>y[$]),2)),u=Fn(r.map(([b,$])=>n?c[b].slice(null,$,null,[0,n]):c[b].slice(null,$)));u=u.transpose(1,0,2,3);let[h,m]=V0(u,-2,0,!0),g=u.clone();for(let b=0;bu[$+1]-u[$]),g=st([1],m).map(b=>!!b),_=[];for(let b=0;bh.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 c=[],u=[];for(let h=0;hi*s,1);e.input_labels=new ae("int64",new BigInt64Array(a).fill(1n),n)}const r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await fr(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new Y1(await super._call(e))}}class Y1 extends At{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}}class rg extends Z{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 X1 extends rg{}class Q1 extends rg{}class ng extends Z{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 Z1 extends ng{}class J1 extends ng{}class Dr extends Z{}class e$ extends Dr{}class t$ extends Dr{async _call(e){return new en(await super._call(e))}}class r$ extends Dr{async _call(e){return new Me(await super._call(e))}}class n$ extends Dr{async _call(e){return new dt(await super._call(e))}}class vo extends Z{}class a$ extends vo{}class i$ extends vo{async _call(e){return new en(await super._call(e))}}class s$ extends vo{async _call(e){return new Me(await super._call(e))}}class Si extends Z{}class o$ extends Si{}class l$ extends Si{async _call(e){return new en(await super._call(e))}}class u$ extends Si{async _call(e){return new Me(await super._call(e))}}class d$ extends Si{async _call(e){return new dt(await super._call(e))}}class $o extends Z{}class c$ extends $o{}class p$ extends $o{async _call(e){return new en(await super._call(e))}}class h$ extends $o{async _call(e){return new Me(await super._call(e))}}class f$ extends Dr{}class m$ extends Dr{async _call(e){return new en(await super._call(e))}}class g$ extends Dr{async _call(e){return new Me(await super._call(e))}}class la extends Z{}class _$ extends la{}class w$ extends la{async _call(e){return new en(await super._call(e))}}class y$ extends la{async _call(e){return new Me(await super._call(e))}}class b$ extends la{async _call(e){return new hx(await super._call(e))}}class v$ extends la{async _call(e){return new dt(await super._call(e))}}class ag extends Z{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 $$ extends ag{}class x$ extends ag{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 Gn(this,o),c=l.dims[1]/this.config.reduction_factor,u=Math.floor(c*i),h=Math.floor(c*a),m=this.config.num_mel_bins;let g=[],_=null,b=null,$=0;for(;;){++$;const k=mm(!!b);let T;b?T=b.output_sequence_out:T=new ae("float32",new Float32Array(m),[1,1,m]);let A={use_cache_branch:k,output_sequence:T,encoder_attention_mask:d,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(A,_),b=await fr(this.sessions.decoder_model_merged,A),_=this.getPastKeyValues(b,_);const{prob:R,spectrum:W}=b;if(g.push(W),$>=h&&(Array.from(R.data).filter(K=>K>=n).length>0||$>=u))break}const y=jt(g),{waveform:E}=await fr(s.sessions.model,{spectrogram:y});return{spectrogram:y,waveform:E}}}class S$ extends Z{main_input_name="spectrogram"}class E$ extends Z{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 k$ extends E${}class ig extends Z{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 C$ extends ig{}class T$ extends ig{}class sg extends Z{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 I$ extends sg{}class A$ extends sg{}class og extends Z{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 M$ extends og{}class O$ extends og{}class xo extends Z{}class z$ extends xo{}class P$ extends xo{static async from_pretrained(e,r={}){return r.model_file_name??="text_model",super.from_pretrained(e,r)}}class R$ extends xo{static async from_pretrained(e,r={}){return r.model_file_name??="audio_model",super.from_pretrained(e,r)}}class B$ extends Z{}class lg extends B${async _call(e){return new mx(await super._call(e))}}class ug extends Z{}class D$ extends ug{}class N$ extends ug{}class L$ extends Z{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 U$ extends L${}class dg extends Z{}class F$ extends dg{}class W$ extends dg{async _call(e){return new Me(await super._call(e))}}class cg extends Z{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 ae(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 fr(this.sessions.encodec_decode,{audio_codes:n});return a}}class G${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:c=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:c,session_options:u};if(n=await dr.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 g=m.get(n.model_type);if(g)return await g[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 Z.from_pretrained(e,h);throw Error(`Unsupported model type: ${n.model_type}`)}}const pg=new Map([["bert",["BertModel",Mb]],["nomic_bert",["NomicBertModel",Db]],["roformer",["RoFormerModel",Nb]],["electra",["ElectraModel",Kb]],["esm",["EsmModel",yv]],["convbert",["ConvBertModel",Gb]],["camembert",["CamembertModel",Jb]],["deberta",["DebertaModel",av]],["deberta-v2",["DebertaV2Model",uv]],["mpnet",["MPNetModel",Cv]],["albert",["AlbertModel",Bv]],["distilbert",["DistilBertModel",fv]],["roberta",["RobertaModel",n2]],["xlm",["XLMModel",l2]],["xlm-roberta",["XLMRobertaModel",h2]],["clap",["ClapModel",z$]],["clip",["CLIPModel",E2]],["clipseg",["CLIPSegModel",M2]],["chinese_clip",["ChineseCLIPModel",A2]],["siglip",["SiglipModel",k2]],["mobilebert",["MobileBertModel",xv]],["squeezebert",["SqueezeBertModel",Ov]],["wav2vec2",["Wav2Vec2Model",e$]],["wav2vec2-bert",["Wav2Vec2BertModel",c$]],["unispeech",["UniSpeechModel",a$]],["unispeech-sat",["UniSpeechSatModel",o$]],["hubert",["HubertModel",f$]],["wavlm",["WavLMModel",_$]],["audio-spectrogram-transformer",["ASTModel",w2]],["vits",["VitsModel",lg]],["detr",["DetrModel",m1]],["table-transformer",["TableTransformerModel",y1]],["vit",["ViTModel",n1]],["mobilevit",["MobileViTModel",o1]],["owlvit",["OwlViTModel",u1]],["owlv2",["Owlv2Model",c1]],["beit",["BeitModel",h1]],["deit",["DeiTModel",$1]],["convnext",["ConvNextModel",N1]],["convnextv2",["ConvNextV2Model",U1]],["dinov2",["Dinov2Model",W1]],["resnet",["ResNetModel",S1]],["swin",["SwinModel",k1]],["swin2sr",["Swin2SRModel",T1]],["donut-swin",["DonutSwinModel",D1]],["yolos",["YolosModel",V1]],["dpt",["DPTModel",A1]],["glpn",["GLPNModel",P1]],["hifigan",["SpeechT5HifiGan",S$]],["efficientnet",["EfficientNetModel",F$]]]),hg=new Map([["t5",["T5Model",Uv]],["longt5",["LongT5Model",Wv]],["mt5",["MT5Model",Vv]],["bart",["BartModel",qv]],["mbart",["MBartModel",Yv]],["marian",["MarianModel",X1]],["whisper",["WhisperModel",b2]],["m2m_100",["M2M100Model",Z1]],["blenderbot",["BlenderbotModel",Jv]],["blenderbot-small",["BlenderbotSmallModel",t2]]]),V$=new Map([["bloom",["BloomModel",Q2]],["gpt2",["GPT2Model",z2]],["gptj",["GPTJModel",L2]],["gpt_bigcode",["GPTBigCodeModel",F2]],["gpt_neo",["GPTNeoModel",R2]],["gpt_neox",["GPTNeoXModel",D2]],["codegen",["CodeGenModel",G2]],["llama",["LlamaModel",H2]],["qwen2",["Qwen2Model",j2]],["phi",["PhiModel",Y2]],["mpt",["MptModel",J2]],["opt",["OPTModel",t1]],["mistral",["MistralModel",C$]],["starcoder2",["Starcoder2Model",I$]],["falcon",["FalconModel",M$]]]),fg=new Map([["speecht5",["SpeechT5ForSpeechToText",$$]],["whisper",["WhisperForConditionalGeneration",v2]]]),H$=new Map([["speecht5",["SpeechT5ForTextToSpeech",x$]]]),q$=new Map([["vits",["VitsModel",lg]],["musicgen",["MusicgenForConditionalGeneration",cg]]]),j$=new Map([["bert",["BertForSequenceClassification",zb]],["roformer",["RoFormerForSequenceClassification",Ub]],["electra",["ElectraForSequenceClassification",Xb]],["esm",["EsmForSequenceClassification",vv]],["convbert",["ConvBertForSequenceClassification",Hb]],["camembert",["CamembertForSequenceClassification",tv]],["deberta",["DebertaForSequenceClassification",sv]],["deberta-v2",["DebertaV2ForSequenceClassification",cv]],["mpnet",["MPNetForSequenceClassification",Iv]],["albert",["AlbertForSequenceClassification",Dv]],["distilbert",["DistilBertForSequenceClassification",mv]],["roberta",["RobertaForSequenceClassification",i2]],["xlm",["XLMForSequenceClassification",d2]],["xlm-roberta",["XLMRobertaForSequenceClassification",m2]],["bart",["BartForSequenceClassification",Kv]],["mbart",["MBartForSequenceClassification",Qv]],["mobilebert",["MobileBertForSequenceClassification",Ev]],["squeezebert",["SqueezeBertForSequenceClassification",Pv]]]),K$=new Map([["bert",["BertForTokenClassification",Pb]],["roformer",["RoFormerForTokenClassification",Fb]],["electra",["ElectraForTokenClassification",Qb]],["esm",["EsmForTokenClassification",$v]],["convbert",["ConvBertForTokenClassification",qb]],["camembert",["CamembertForTokenClassification",rv]],["deberta",["DebertaForTokenClassification",ov]],["deberta-v2",["DebertaV2ForTokenClassification",pv]],["mpnet",["MPNetForTokenClassification",Av]],["distilbert",["DistilBertForTokenClassification",gv]],["roberta",["RobertaForTokenClassification",s2]],["xlm",["XLMForTokenClassification",c2]],["xlm-roberta",["XLMRobertaForTokenClassification",g2]]]),mg=new Map([["t5",["T5ForConditionalGeneration",Fv]],["longt5",["LongT5ForConditionalGeneration",Gv]],["mt5",["MT5ForConditionalGeneration",Hv]],["bart",["BartForConditionalGeneration",jv]],["mbart",["MBartForConditionalGeneration",Xv]],["marian",["MarianMTModel",Q1]],["m2m_100",["M2M100ForConditionalGeneration",J1]],["blenderbot",["BlenderbotForConditionalGeneration",e2]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",r2]]]),So=new Map([["bloom",["BloomForCausalLM",Z2]],["gpt2",["GPT2LMHeadModel",P2]],["gptj",["GPTJForCausalLM",U2]],["gpt_bigcode",["GPTBigCodeForCausalLM",W2]],["gpt_neo",["GPTNeoForCausalLM",B2]],["gpt_neox",["GPTNeoXForCausalLM",N2]],["codegen",["CodeGenForCausalLM",V2]],["llama",["LlamaForCausalLM",q2]],["qwen2",["Qwen2ForCausalLM",K2]],["phi",["PhiForCausalLM",X2]],["mpt",["MptForCausalLM",e1]],["opt",["OPTForCausalLM",r1]],["mbart",["MBartForCausalLM",Zv]],["mistral",["MistralForCausalLM",T$]],["starcoder2",["Starcoder2ForCausalLM",A$]],["falcon",["FalconForCausalLM",O$]],["trocr",["TrOCRForCausalLM",k$]],["stablelm",["StableLmForCausalLM",U$]]]),Y$=new Map([["bert",["BertForMaskedLM",Ob]],["roformer",["RoFormerForMaskedLM",Lb]],["electra",["ElectraForMaskedLM",Yb]],["esm",["EsmForMaskedLM",bv]],["convbert",["ConvBertForMaskedLM",Vb]],["camembert",["CamembertForMaskedLM",ev]],["deberta",["DebertaForMaskedLM",iv]],["deberta-v2",["DebertaV2ForMaskedLM",dv]],["mpnet",["MPNetForMaskedLM",Tv]],["albert",["AlbertForMaskedLM",Lv]],["distilbert",["DistilBertForMaskedLM",wv]],["roberta",["RobertaForMaskedLM",a2]],["xlm",["XLMWithLMHeadModel",u2]],["xlm-roberta",["XLMRobertaForMaskedLM",f2]],["mobilebert",["MobileBertForMaskedLM",Sv]],["squeezebert",["SqueezeBertForMaskedLM",zv]]]),X$=new Map([["bert",["BertForQuestionAnswering",Rb]],["roformer",["RoFormerForQuestionAnswering",Wb]],["electra",["ElectraForQuestionAnswering",Zb]],["convbert",["ConvBertForQuestionAnswering",jb]],["camembert",["CamembertForQuestionAnswering",nv]],["deberta",["DebertaForQuestionAnswering",lv]],["deberta-v2",["DebertaV2ForQuestionAnswering",hv]],["mpnet",["MPNetForQuestionAnswering",Mv]],["albert",["AlbertForQuestionAnswering",Nv]],["distilbert",["DistilBertForQuestionAnswering",_v]],["roberta",["RobertaForQuestionAnswering",o2]],["xlm",["XLMForQuestionAnswering",p2]],["xlm-roberta",["XLMRobertaForQuestionAnswering",_2]],["mobilebert",["MobileBertForQuestionAnswering",kv]],["squeezebert",["SqueezeBertForQuestionAnswering",Rv]]]),gg=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$2]]]),Q$=new Map([["llava",["LlavaForConditionalGeneration",S2]]]),Z$=new Map([["vit",["ViTForImageClassification",a1]],["mobilevit",["MobileViTForImageClassification",l1]],["beit",["BeitForImageClassification",f1]],["deit",["DeiTForImageClassification",x1]],["convnext",["ConvNextForImageClassification",L1]],["convnextv2",["ConvNextV2ForImageClassification",F1]],["dinov2",["Dinov2ForImageClassification",G1]],["resnet",["ResNetForImageClassification",E1]],["swin",["SwinForImageClassification",C1]],["segformer",["SegformerForImageClassification",D$]],["efficientnet",["EfficientNetForImageClassification",W$]]]),J$=new Map([["detr",["DetrForObjectDetection",g1]],["table-transformer",["TableTransformerForObjectDetection",b1]],["yolos",["YolosForObjectDetection",H1]]]),ex=new Map([["owlvit",["OwlViTForObjectDetection",d1]],["owlv2",["Owlv2ForObjectDetection",p1]]]),tx=new Map([["detr",["DetrForSegmentation",_1]],["clipseg",["CLIPSegForImageSegmentation",O2]]]),rx=new Map([["segformer",["SegformerForSemanticSegmentation",N$]]]),nx=new Map([["sam",["SamModel",K1]]]),ax=new Map([["wav2vec2",["Wav2Vec2ForCTC",t$]],["wav2vec2-bert",["Wav2Vec2BertForCTC",p$]],["unispeech",["UniSpeechForCTC",i$]],["unispeech-sat",["UniSpeechSatForCTC",l$]],["wavlm",["WavLMForCTC",w$]],["hubert",["HubertForCTC",m$]]]),ix=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",r$]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",h$]],["unispeech",["UniSpeechForSequenceClassification",s$]],["unispeech-sat",["UniSpeechSatForSequenceClassification",u$]],["wavlm",["WavLMForSequenceClassification",y$]],["hubert",["HubertForSequenceClassification",g$]],["audio-spectrogram-transformer",["ASTForAudioClassification",y2]]]),sx=new Map([["wavlm",["WavLMForXVector",b$]]]),ox=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",d$]],["wavlm",["WavLMForAudioFrameClassification",v$]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",n$]]]),lx=new Map([["vitmatte",["VitMatteForImageMatting",s1]]]),ux=new Map([["swin2sr",["Swin2SRForImageSuperResolution",I1]]]),dx=new Map([["dpt",["DPTForDepthEstimation",M1]],["depth_anything",["DepthAnythingForDepthEstimation",z1]],["glpn",["GLPNForDepthEstimation",R1]]]),cx=new Map([["clip",["CLIPVisionModelWithProjection",Sm]],["siglip",["SiglipVisionModel",T2]]]),_g=[[pg,fe.EncoderOnly],[hg,fe.EncoderDecoder],[V$,fe.DecoderOnly],[j$,fe.EncoderOnly],[K$,fe.EncoderOnly],[mg,fe.Seq2Seq],[fg,fe.Seq2Seq],[So,fe.DecoderOnly],[Y$,fe.EncoderOnly],[X$,fe.EncoderOnly],[gg,fe.Vision2Seq],[Q$,fe.ImageTextToText],[Z$,fe.EncoderOnly],[tx,fe.EncoderOnly],[rx,fe.EncoderOnly],[lx,fe.EncoderOnly],[ux,fe.EncoderOnly],[dx,fe.EncoderOnly],[J$,fe.EncoderOnly],[ex,fe.EncoderOnly],[nx,fe.MaskGeneration],[ax,fe.EncoderOnly],[ix,fe.EncoderOnly],[H$,fe.Seq2Seq],[q$,fe.EncoderOnly],[sx,fe.EncoderOnly],[ox,fe.EncoderOnly],[cx,fe.EncoderOnly]];for(const[t,e]of _g)for(const[r,n]of t.values())ci.set(r,e),Bn.set(n,r),hm.set(r,n);const px=[["MusicgenForConditionalGeneration",cg,fe.Musicgen],["CLIPTextModelWithProjection",xm,fe.EncoderOnly],["SiglipTextModel",C2,fe.EncoderOnly],["ClapTextModelWithProjection",P$,fe.EncoderOnly],["ClapAudioModelWithProjection",R$,fe.EncoderOnly]];for(const[t,e,r]of px)ci.set(t,r),Bn.set(e,t),hm.set(t,e);class uS extends G${static MODEL_CLASS_MAPPINGS=_g.map(e=>e[0]);static BASE_IF_FAIL=!0}class Me extends At{constructor({logits:e}){super(),this.logits=e}}class hx extends At{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}}class dt extends At{constructor({logits:e}){super(),this.logits=e}}class ct extends At{constructor({logits:e}){super(),this.logits=e}}class gt extends At{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}}class en extends At{constructor({logits:e}){super(),this.logits=e}}class fx extends At{constructor({alphas:e}){super(),this.alphas=e}}class mx extends At{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}}const Et=typeof self<"u",gx=Et&&self.constructor.name==="DedicatedWorkerGlobalScope";let Er,wg,cr;if(Et)Er=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},cr=self.createImageBitmap,wg=self.ImageData;else if(Xe)cr=async t=>{const r=(await t.metadata()).channels,{data:n,info:a}=await t.raw().toBuffer({resolveWithObject:!0}),i=new Nt(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 _x={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},wx=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class Nt{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 Nt)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(!Et)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 Nt(n,e.width,e.height,4)}static async fromURL(e){const r=await bs(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(Et){const r=await cr(e),n=Er(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=Xe(await e.arrayBuffer());return await cr(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 Nt(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:c=-n,a>=0?d=a:u=-a,o.drawImage(s,l,d,e,r,c,u,e,r),new Nt(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 cr(i)}}async toBlob(e="image/png",r=1){if(!Et)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 ae("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(!Et)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),r=Er(e.width,e.height),n=new wg(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 Nt(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(Et){if(gx)throw new Error("Unable to save an image from a Web Worker.");const r=e.split(".").pop().toLowerCase(),n=wx.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(_t.useFS)return await this.toSharp().toFile(e);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Et)throw new Error("toSharp() is only supported in server-side environments.");return Xe(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}function fc(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 fs(t,e="htk"){const r=yx[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 bx={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 vx(t,e="htk"){const r=bx[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 $x(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 Vn(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=fs(r,s),d=fs(n,s),c=mc(l,d,e+2);let u=vx(c,s),h;if(o){const g=a/(t*2);h=fs(Float64Array.from({length:t},(_,b)=>b*g),s),u=c}else h=mc(0,Math.floor(a/2),t);const m=$x(h,u);if(i!==null&&i==="slaney")for(let g=0;ga)throw Error(`frame_length (${r}) may not be larger than fft_length (${a})`);if(k!==r)throw new Error(`Length of the window (${k}) 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 O=Math.floor((a-1)/2)+1;t=xx(t,O,O)}const T=Math.floor(1+Math.floor((t.length-r)/n)),A=l?Math.floor(a/2)+1:a;let R=T,W=T;$!==null&&($>T?y&&(W=$):W=R=$);const K=new s_(a),q=new Float64Array(a),ee=new Float64Array(K.outputBufferSize),P=new Array(R);for(let O=0;O=1;--j)q[j]-=d*q[j-1];q[0]*=1-d}for(let j=0;jMath.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 kx([t,e,r,n]){return[t-r/2,e-n/2,t+r/2,e+n/2]}function Eo(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 c=0;ce&&$.push(E)}else{let E=mr(b.data)[1];if(E===l-1||(y=Hn(b.data),y[E]T*u[(A+1)%2])),h.boxes.push(k),h.classes.push(E),h.scores.push(y[E])}}d.push(h)}return d}function ua(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 gc(t,e,r=0,n=null){const a=t/e;let i=l_(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=kc(n.data)[0],s=mr(n.data)[0]-a;if(s===0)return e;const o=r/255;let l=n.width,d=n.height,c=0,u=0;const h=n.data;for(let m=0;mthis.preprocess(i)));return{pixel_values:Fn(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 Cx extends je{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]=y[E],m[E]=$)}const g=new Array(l.dims[0]),_=u.data;for(let $=0;$<_.length;++$){const y=_[$];g[y]=y}const b=g.filter($=>$!==void 0);i.push({segmentation:u,labels:b})}return i}}class bg extends je{}class Tx extends bg{}class Ix extends je{}class Ax extends je{}class vg extends je{}class Mx extends vg{}class Ox extends je{}class zx extends je{}class $g extends je{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 Px extends $g{}class Rx extends je{}class Bx extends je{}class Dx extends je{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 Nx extends je{}class xg extends je{post_process_object_detection(...e){return Eo(...e)}}class Lx extends xg{}class Ux extends je{}class Fx extends je{}class Sg extends je{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 c=l.map((u,h)=>-u/d[h]);return super.pad_image(e,r,n,{center:!0,constant_values:c,...a})}}class Wx extends Sg{}class Gx extends je{async _call(e){const r=await super._call(e),n=[r.pixel_values.dims[0],64,64],a=new ae("int64",new BigInt64Array(n.reduce((i,s)=>i*s)).fill(1n),n);return{...r,pixel_mask:a}}post_process_object_detection(...e){return Eo(...e)}remove_low_and_no_objects(e,r,n,a){let i=[],s=[],o=[];for(let l=0;ln&&(i.push(c),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 c=o>0&&l>0;return c&&(c=o/l>i),[c,s]}compute_segments(e,r,n,a,i,s=null,o=null){let[l,d]=o??e[0].dims,c=new ae("int32",new Int32Array(l*d),[l,d]),u=[];if(o!==null)for(let b=0;bm[E]&&(h[E]=b,m[E]=y[E])}let g=0;const _=c.data;for(let b=0;ba!==r.dims[i]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new ae("int64",e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:r=null,input_labels:n=null,input_boxes:a=null}={}){const i=await super._call(e);if(r&&(i.input_points=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return a&&(i.input_boxes=this.reshape_input_points(a,i.original_sizes,i.reshaped_input_sizes,!0)),i}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&&(g[_]=1);h=new ae("bool",g,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 qx extends je{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 jx extends je{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:Fn(n.map((s,o)=>jt([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 Kx extends Nr{constructor(e){super(e),this.config.mel_filters??=Vn(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=ki(this.config.n_fft,"hann")}_extract_fbank_features(e){const{data:r,dims:n}=Ei(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=mr(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 ae("float32",n,[1,...a])}}}class Yx extends Nr{_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){ua(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 ae("float32",r,n),attention_mask:new ae("int64",new BigInt64Array(r.length).fill(1n),n)}}}class Xx extends Nr{constructor(e){super(e);const r=this.config.sampling_rate,n=Vn(256,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);for(let a=0;an*32768),Ei(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}={}){ua(e,"SeamlessM4TFeatureExtractor");let s=this._extract_fbank_features(e,this.config.max_length);const o=s.data;if(a){const[_,b]=s.dims;for(let $=0;$0){const y=new Float32Array(b*(_+$));y.set(o),y.fill(this.config.padding_value,o.length);const E=_+$;s={data:y,dims:[E,b]},i&&(l=new ae("int64",new BigInt64Array(E),[1,E]),l.data.fill(1n,0,_))}}const[d,c]=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 ae("float32",o,s.dims).view(1,Math.floor(d/u),c*u),g={input_features:m};if(i){const _=m.dims[1],b=new BigInt64Array(_);if(l){const $=l.data;for(let y=1,E=0;y0)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;dt),Ga.length>0){const t=Ga.map(n=>Ya.value.replaceAll("{}",n)),e=Eg(t,{padding:"max_length",truncation:!0}),{text_embeds:r}=await kg(e);Wa=r.normalize().tolist()}else Ua.innerHTML="";if(Wa){wc.drawImage(On,0,0,kr,kr);const t=wc.getImageData(0,0,kr,kr).data,e=new Nt(t,kr,kr,4),r=await Cg(e),{image_embeds:n}=await Tg(r),a=n.normalize().tolist()[0],i=Wa.map(o=>a_(o,a)*100),s=Hn(i).map((o,l)=>[o,l]).sort((o,l)=>l[0]-o[0]);Ua.innerHTML="";for(const[o,l]of s)Ua.appendChild(document.createTextNode(`${Ga[l]}: ${o.toFixed(2)}`)),Ua.appendChild(document.createElement("br"))}if(_s!==void 0){const t=1e3/(performance.now()-_s);Ci.textContent=`FPS: ${t.toFixed(2)}`}_s=performance.now(),gs=!1}()),window.requestAnimationFrame(Ig)}navigator.mediaDevices.getUserMedia({video:!0}).then(t=>{On.srcObject=t,On.play();const e=t.getVideoTracks()[0],{width:r,height:n}=e.getSettings();On.width=r,On.height=n;const a=r/n,[i,s]=a>720/405?[720,720/a]:[405*a,405];_c.style.width=`${i}px`,_c.style.height=`${s}px`,window.requestAnimationFrame(Ig)}).catch(t=>{alert(t)});