diff --git "a/assets/index-C2x4uvch.js" "b/assets/index-C2x4uvch.js" deleted file mode 100644--- "a/assets/index-C2x4uvch.js" +++ /dev/null @@ -1,2171 +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"]'))r(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"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(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 r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();function Vn(t,e){t&&t(e)}function Rg(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e]))}function pc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Et=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 Bg(t){return t?.prototype?.__proto__?.constructor?.name==="TypedArray"}function hc(t){return Number.isInteger(t)||typeof t=="bigint"}function Pg(t){return t!=null}function Ho(t){const e=[];let n=t;for(;Array.isArray(n);)e.push(n.length),n=n[0];return e}function qo(t,e,n=void 0){const r=t[e];if(r!==void 0)return delete t[e],r;if(n===void 0)throw Error(`Key ${e} does not exist in object.`);return n}function dt(...t){return Array.prototype.concat.apply([],t)}function Dg(...t){return t.reduce((e,n)=>e.flatMap(r=>n.map(a=>[r,a])))}function Ha(t,e){return Math.abs((t+e)%(2*e)-e)}const je={},Ng=Object.freeze(Object.defineProperty({__proto__:null,default:je},Symbol.toStringTag,{value:"Module"})),Fg="3.0.0-alpha.0",fc=typeof self<"u",Lg=fc&&"caches"in self,_s=!mc(je),Ug=!mc(je),oi=_s&&Ug,Fs=oi?je.dirname(je.dirname(je.fileURLToPath(import.meta.url))):"./",Wg=oi?je.join(Fs,"/.cache/"):null,jo="/models/",Vg=oi?je.join(Fs,jo):jo,at={backends:{onnx:{},tfjs:{}},__dirname:Fs,version:Fg,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!fc,localModelPath:Vg,useFS:_s,useBrowserCache:Lg,useFSCache:_s,cacheDir:Wg,useCustomCache:!1,customCache:null};function mc(t){return Object.keys(t).length===0}var zi={};class li{_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=je.existsSync(e),this.exists){this.status=200,this.statusText="OK";let n=je.statSync(e);this.headers.set("content-length",n.size.toString()),this.updateContentType();let r=this;this.body=new ReadableStream({start(a){r.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 li(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 je.promises.readFile(this.filePath)).buffer}async blob(){const e=await je.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await je.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function ws(t,e=null){let n;try{n=new URL(t)}catch{return!1}return e&&!e.includes(n.hostname)?!1:n.protocol==="http:"||n.protocol==="https:"}async function qa(t){if(at.useFS&&!ws(t))return new li(t);if(typeof process<"u"&&process?.release?.name==="node"){const e=!!zi?.TESTING_REMOTELY,n=at.version,r=new Headers;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${e};`),ws(t,["huggingface.co","hf.co"])){const i=zi?.HF_TOKEN??zi?.HF_ACCESS_TOKEN;i&&r.set("Authorization",`Bearer ${i}`)}return fetch(t,{headers:r})}else return fetch(t)}const Gg={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 Hg(t,e,n){if(!n)return null;const r=Gg[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${r}: "${e}".`)}class Ko{constructor(e){this.path=e}async match(e){let n=je.join(this.path,e),r=new li(n);if(r.exists)return r}async put(e,n){const r=Buffer.from(await n.arrayBuffer());let a=je.join(this.path,e);try{await je.promises.mkdir(je.dirname(a),{recursive:!0}),await je.promises.writeFile(a,r)}catch(i){console.warn("An error occurred while writing the file to cache:",i)}}}async function qg(t,...e){for(let n of e)try{let r=await t.match(n);if(r)return r}catch{continue}}async function ys(t,e,n=!0,r={}){if(!at.allowLocalModels&&r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");Vn(r.progress_callback,{status:"initiate",name:t,file:e});let a;if(!a&&at.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{a=await caches.open("transformers-cache")}catch(y){console.warn("An error occurred while opening the browser cache:",y)}}if(!a&&at.useFSCache&&(a=new Ko(r.cache_dir??at.cacheDir)),!a&&at.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const i=r.revision??"main";let s=Ca(t,e),o=Ca(at.localModelPath,s),l=Ca(at.remoteHost,at.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(i)),e),d=i==="main"?s:Ca(t,i,e),c,u=a instanceof Ko?d:l,h=!1,f;a&&(f=await qg(a,o,u));const g=f!==void 0;if(f===void 0){if(at.allowLocalModels)if(ws(s)){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else try{f=await qa(o),c=o}catch($){console.warn(`Unable to load from local path "${o}": "${$}"`)}if(f===void 0||f.status===404){if(r.local_files_only||!at.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${o}".`);return null}if(f=await qa(l),f.status!==200)return Hg(f.status,l,n);c=u}h=a&&typeof Response<"u"&&f instanceof Response&&f.status===200}Vn(r.progress_callback,{status:"download",name:t,file:e});const w={status:"progress",name:t,file:e};let b;return r.progress_callback?g&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(b=new Uint8Array(await f.arrayBuffer()),Vn(r.progress_callback,{...w,progress:100,loaded:b.length,total:b.length})):b=await jg(f,y=>{Vn(r.progress_callback,{...w,...y})}):b=new Uint8Array(await f.arrayBuffer()),h&&c&&await a.match(c)===void 0&&await a.put(c,new Response(b,{headers:f.headers})).catch(y=>{console.warn(`Unable to add response to browser cache: ${y}.`)}),Vn(r.progress_callback,{status:"done",name:t,file:e}),b}async function Yn(t,e,n=!0,r={}){let a=await ys(t,e,n,r);if(a===null)return{};let s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}async function jg(t,e){const n=t.headers.get("Content-Length");n===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(n??"0"),a=new Uint8Array(r),i=0;const s=t.body.getReader();async function o(){const{done:l,value:d}=await s.read();if(l)return;let c=i+d.length;if(c>r){r=c;let h=new Uint8Array(r);h.set(a),a=h}a.set(d,i),i=c;const u=i/r*100;return e({progress:u,loaded:i,total:r}),o()}return await o(),a}function Ca(...t){return t=t.map((e,n)=>(n&&(e=e.replace(new RegExp("^/"),"")),n!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Kg(t,[e,n,r],[a,i],s="bilinear",o=!1){const l=i/r,d=a/n,c=new t.constructor(a*i*e),u=n*r,h=a*i;for(let f=0;f=0;--o)a[o]=l,r[o]=e[n[o]],l*=r[o];const i=n.map((o,l)=>a[n.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,r]}function ht(t){const e=Ot(t)[0],n=t.map(i=>Math.exp(i-e)),r=n.reduce((i,s)=>i+s,0);return n.map(i=>i/r)}function Xg(t){return ht(t).map(r=>Math.log(r))}function Zn(t,e=0){return t=Array.from(t).map((n,r)=>[r,n]).sort((n,r)=>r[1]-n[1]),e!==null&&e>0&&(t=t.slice(0,e)),t}function gc(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],n=0;for(let r=1;re&&(e=t[r],n=r);return[Number(e),n]}function _c(t){return t>0&&(t&t-1)===0}class wc{constructor(e){if(this.size=e|0,this.size<=1||!_c(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 r=0;rr;r<<=1)++n;this._width=n%2===0?n-1:n,this._bitrev=new Int32Array(1<>>a&3)<>>1);for(let a=0;a>>1]=e[a];return r}toComplexArray(e,n){const r=n||this.createComplexArray();for(let a=0;a>>1],r[a+1]=0;return r}completeSpectrum(e){const n=this._csize,r=n>>>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,r)}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,f=u*Math.atan2(d,l),g=2*c;i[g]=h*Math.cos(f),i[g+1]=h*Math.sin(f),s[g]=i[g],s[g+1]=-i[g+1]}this._slicedChirpBuffer=i.subarray(n,r),this._f=new wc(a>>1),this._f.transform(this._chirpBuffer,s)}_transform(e,n,r){const a=this._buffer1,i=this._buffer2,s=this._outBuffer1,o=this._outBuffer2,l=this._chirpBuffer,d=this._slicedChirpBuffer,c=this._a;if(r)for(let u=0;u>1,g=n[f];a[u]=g*d[u],a[h]=g*d[h]}else for(let u=0;u=t.length&&(l=2*(t.length-1)-l),r[s++]=t[l]}r.sort(),n[i]=r[a]}return n}function Ar(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}/*! - * ONNX Runtime Web v1.17.1 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */var Ls=Object.defineProperty,e_=Object.getOwnPropertyDescriptor,t_=Object.getOwnPropertyNames,n_=Object.prototype.hasOwnProperty,X=(t,e)=>()=>(t&&(e=t(t=0)),e),Jn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),er=(t,e)=>{for(var n in e)Ls(t,n,{get:e[n],enumerable:!0})},r_=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of t_(e))!n_.call(t,a)&&a!==n&&Ls(t,a,{get:()=>e[a],enumerable:!(r=e_(e,a))||r.enumerable});return t},Cn=t=>r_(Ls({},"__esModule",{value:!0}),t),br,cn,jn,Us,Ws=X(()=>{br=new Map,cn=[],jn=(t,e,n)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let r=br.get(t);if(r===void 0)br.set(t,{backend:e,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${n}`)}if(n>=0){let a=cn.indexOf(t);a!==-1&&cn.splice(a,1);for(let i=0;i{let e=t.length===0?cn:t,n=[];for(let r of e){let a=br.get(r);if(a){if(a.initialized)return a.backend;if(a.aborted)continue;let i=!!a.initPromise;try{return i||(a.initPromise=a.backend.init(r)),await a.initPromise,a.initialized=!0,a.backend}catch(s){i||n.push({name:r,err:s}),a.aborted=!0}finally{delete a.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map(r=>`[${r.name}] ${r.err}`).join(", ")}`)}}),a_=X(()=>{Ws()}),yc,i_=X(()=>{yc="1.17.1"}),Ri,Kn,bc=X(()=>{i_(),Ri="warning",Kn={wasm:{},webgl:{},webgpu:{},versions:{common:yc},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}`);Ri=t}},get logLevel(){return Ri}},Object.defineProperty(Kn,"logLevel",{enumerable:!0})}),Ne,s_=X(()=>{bc(),Ne=Kn}),vc,$c,o_=X(()=>{vc=(t,e)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=t.dims[3],n.height=t.dims[2];let r=n.getContext("2d");if(r!=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,f=c*2,g=-1;s==="RGBA"?(u=0,h=c,f=c*2,g=c*3):s==="RGB"?(u=0,h=c,f=c*2):s==="RBG"&&(u=0,f=c,h=c*2);for(let w=0;w{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(n!=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,f=0,g=1,w=2,b=3,y=0,$=u,k=u*2,S=-1;o==="RGBA"?(y=0,$=u,k=u*2,S=u*3):o==="RGB"?(y=0,$=u,k=u*2):o==="RBG"&&(y=0,k=u,$=u*2),r=n.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:n,width:r}=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=n*r,c=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),u=4,h=0,f=1,g=2,w=3,b=0,y=d,$=d*2,k=-1;o==="RGB"&&(u=3,h=0,f=1,g=2,w=-1),l==="RGBA"?k=d*3:l==="RBG"?(b=0,$=d,y=d*2):l==="BGR"&&($=0,y=d,b=d*2);for(let S=0;S{let n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,r=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(n){let c=l();c.width=t.width,c.height=t.height;let u=d(c);if(u!=null){let h=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,f=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=f}else o.tensorFormat="RGBA",o.height=h,o.width=f;u.drawImage(t,0,0),s=u.getImageData(0,0,f,h).data}else throw new Error("Can not access image data")}else if(r){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 f=d(h);if(f!=null)f.putImageData(t,0,0),s=f.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,f=t.width;return u.drawImage(t,0,0,f,h),s=u.getImageData(0,0,f,h).data,o.height=h,o.width=f,Ta(s,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((c,u)=>{let h=l(),f=d(h);if(!t||!f)return u();let g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{h.width=g.width,h.height=g.height,f.drawImage(g,0,0,h.width,h.height);let w=f.getImageData(0,0,h.width,h.height);o.height=h.height,o.width=h.width,c(Ta(w.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")},Sc=(t,e)=>{let{width:n,height:r,download:a,dispose:i}=e,s=[1,r,n,4];return new Lt({location:"texture",type:"float32",texture:t,dims:s,download:a,dispose:i})},Ec=(t,e)=>{let{dataType:n,dims:r,download:a,dispose:i}=e;return new Lt({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:a,dispose:i})},kc=(t,e,n)=>new Lt({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]})}),Or,Na,Bi,Cc,u_=X(()=>{Or=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Na=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Bi=!1,Cc=()=>{if(!Bi){Bi=!0;let t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(Or.set("int64",BigInt64Array),Na.set(BigInt64Array,"int64")),e&&(Or.set("uint64",BigUint64Array),Na.set(BigUint64Array,"uint64"))}}}),Tc,Ic,d_=X(()=>{Vs(),Tc=t=>{let e=1;for(let n=0;n{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(()=>{o_(),l_(),u_(),d_(),Lt=class{constructor(t,e,n){Cc();let r,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,r=t.type,a=t.dims,t.location){case"cpu-pinned":{let s=Or.get(r);if(!s)throw new TypeError(`unsupported type "${r}" 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(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="bool")throw new TypeError(`unsupported type "${r}" 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(r=t,o=n,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");s=e}else{let l=Or.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16")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 ${r} 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")r="string",s=t;else if(l==="boolean")r="bool",s=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else{let l=Na.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);r=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=Tc(a);if(this.cpuData&&i!==this.cpuData.length)throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=a,this.size=i}static async fromImage(t,e){return xc(t,e)}static fromTexture(t,e){return Sc(t,e)}static fromGpuBuffer(t,e){return Ec(t,e)}static fromPinnedBuffer(t,e,n){return kc(t,e,n)}toDataURL(t){return vc(this,t)}toImageData(t){return $c(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 Ic(this,t)}}}),gt,Gs=X(()=>{Vs(),gt=Lt}),Dr,Pi,Ut,Wt,Ac=X(()=>{bc(),Dr=(t,e)=>{Kn.wasm.trace&&console.timeStamp(`${t}::ORT::${e}`)},Pi=(t,e)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let a=0;a{Kn.wasm.trace&&Pi("BEGIN",t)},Wt=t=>{Kn.wasm.trace&&Pi("END",t)}}),Mc,c_=X(()=>{Ws(),Gs(),Ac(),Mc=class Oc{constructor(e){this.handler=e}async run(e,n,r){Ut();let a={},i={};if(typeof e!="object"||e===null||e instanceof gt||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 n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof gt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let d of n){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 r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,c=Object.getOwnPropertyNames(n);for(let u of this.outputNames)if(c.indexOf(u)!==-1){let h=n[u];(h===null||h instanceof gt)&&(d=!0,s=!1,a[u]=h)}if(d){if(typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else i=n}}else if(typeof n<"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 gt?l[d]=c:l[d]=new gt(c.type,c.data,c.dims)}return Wt(),l}async release(){return this.handler.dispose()}static async create(e,n,r,a){Ut();let i,s={};if(typeof e=="string"){if(i=e,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(i=e,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let d=e,c=0,u=e.byteLength;if(typeof n=="object"&&n!==null)s=n;else if(typeof n=="number"){if(c=n,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(u=e.byteLength-c,typeof r=="number"){if(u=r,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||c+u>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-c}].`);if(typeof a=="object"&&a!==null)s=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(d,c,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let o=(s.executionProviders||[]).map(d=>typeof d=="string"?d:d.name),l=await(await Us(o)).createInferenceSessionHandler(i,s);return Wt(),new Oc(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Hs,p_=X(()=>{c_(),Hs=Mc}),h_=X(()=>{}),Yo,zc,f_=X(()=>{Ws(),Gs(),Yo="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",zc=class Rc{constructor(e,n,r){this.handler=e,this.hasOptimizerModel=n,this.hasEvalModel=r}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,n){let r=e.evalModel||"",a=e.optimizerModel||"",i=n||{},s=(i.executionProviders||[]).map(l=>typeof l=="string"?l:l.name),o=await Us(s);if(o.createTrainingSessionHandler){let l=await o.createTrainingSessionHandler(e.checkpointState,e.trainModel,r,a,i);return new Rc(l,!!e.optimizerModel,!!e.evalModel)}else throw new Error(Yo)}typeNarrowingForRunStep(e,n,r,a,i){let s={},o={};if(typeof r!="object"||r===null||r instanceof gt||Array.isArray(r))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 gt)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(n.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 n)if(c.indexOf(u)!==-1){let h=a[u];(h===null||h instanceof gt)&&(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 r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(l)for(let d of n)s[d]=null;return[s,o]}convertHandlerReturnTypeToMapOfTensors(e){let n={};for(let r in e)if(Object.hasOwnProperty.call(e,r)){let a=e[r];a instanceof gt?n[r]=a:n[r]=new gt(a.type,a.data,a.dims)}return n}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,n,r){let[a,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,n,r),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,n,r){if(this.hasEvalModel){let[a,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,n,r),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,n=!0){let r=await this.getParametersSize(n);if(e.length!==4*r)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,n)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}}),qs,m_=X(()=>{f_(),qs=zc}),Bc={};er(Bc,{InferenceSession:()=>Hs,TRACE:()=>Dr,TRACE_FUNC_BEGIN:()=>Ut,TRACE_FUNC_END:()=>Wt,Tensor:()=>gt,TrainingSession:()=>qs,env:()=>Ne,registerBackend:()=>jn});var Vt=X(()=>{a_(),s_(),p_(),Gs(),Ac(),h_(),m_()}),js={};er(js,{createReadStream:()=>Nc,readFile:()=>Pc,readFileSync:()=>Dc});var Pc,Dc,Nc,Fc=X(()=>{Pc=void 0,Dc=void 0,Nc=void 0}),Ks={};er(Ks,{join:()=>Lc});var Lc,Uc=X(()=>{Lc=void 0}),g_=Jn((t,e)=>{var n=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),function(a={}){var i=a,s,o;i.ready=new Promise((m,v)=>{s=m,o=v}),i.mountExternalData=(m,v)=>{(i.Fa||(i.Fa=new Map)).set(m,v)},i.unmountExternalData=()=>{delete i.Fa},i.jsepInit=(m,v,E,I,F,K,ne,we)=>{i.ab=m,i.Qa=v,i.Sa=E,i.La=I,i.Ra=F,i.sa=K,i.Ta=ne,i.Ua=we,v=(le,de,ge)=>(...ke)=>{let Oe=yt,B=de?.();ke=le(...ke);let _e=de?.();return B!==_e&&(le=_e,ge(B),de=ge=null),yt!=Oe?ga():ke},E=le=>async(...de)=>{try{if(i.Ea)throw Error("Session already started");let ge=i.Ea={Va:de[0],errors:[]},ke=await le(...de);if(i.Ea!==ge)throw Error("Session mismatch");m.flush();let Oe=ge.errors;if(0_e),0i._OrtRun,le=>i._OrtRun=le)),i._OrtRunWithBinding=E(v(i._OrtRunWithBinding,()=>i._OrtRunWithBinding,le=>i._OrtRunWithBinding=le)),i._OrtBindInput=v(i._OrtBindInput,()=>i._OrtBindInput,le=>i._OrtBindInput=le),i.jsepRegisterBuffer=(le,de,ge,ke)=>m.registerBuffer(le,de,ge,ke),i.jsepUnregisterBuffers=le=>{m.unregisterBuffers(le)},i.jsepGetBuffer=le=>m.getBuffer(le),i.jsepCreateDownloader=(le,de,ge)=>m.createDownloader(le,de,ge)};var l=Object.assign({},i),d="./this.program",c=(m,v)=>{throw v},u=typeof window=="object",h=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="",w,b,y;if(f){var $=(Fc(),Cn(js)),k=(Uc(),Cn(Ks));g=h?k.dirname(g)+"/":__dirname+"/",w=(m,v)=>(m=$e(m)?new URL(m):k.normalize(m),$.readFileSync(m,v?void 0:"utf8")),y=m=>(m=w(m,!0),m.buffer||(m=new Uint8Array(m)),m),b=(m,v,E,I=!0)=>{m=$e(m)?new URL(m):k.normalize(m),$.readFile(m,I?void 0:"utf8",(F,K)=>{F?E(F):v(I?K.buffer:K)})},!i.thisProgram&&1{throw process.exitCode=m,v},i.inspect=()=>"[Emscripten Module object]"}else(u||h)&&(h?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),r&&(g=r),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",w=m=>{var v=new XMLHttpRequest;return v.open("GET",m,!1),v.send(null),v.responseText},h&&(y=m=>{var v=new XMLHttpRequest;return v.open("GET",m,!1),v.responseType="arraybuffer",v.send(null),new Uint8Array(v.response)}),b=(m,v,E)=>{var I=new XMLHttpRequest;I.open("GET",m,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?v(I.response):E()},I.onerror=E,I.send(null)});var S=console.log.bind(console),T=console.error.bind(console);Object.assign(i,l),l=null,typeof WebAssembly!="object"&&W("no native wasm support detected");var A,P=!1,N,V,j,M,G,O,R;function H(){var m=A.buffer;i.HEAP8=V=new Int8Array(m),i.HEAP16=new Int16Array(m),i.HEAPU8=j=new Uint8Array(m),i.HEAPU16=new Uint16Array(m),i.HEAP32=M=new Int32Array(m),i.HEAPU32=G=new Uint32Array(m),i.HEAPF32=O=new Float32Array(m),i.HEAPF64=R=new Float64Array(m)}var te=[],ae=[],re=[],Y=0,ue=null;function W(m){throw m="Aborted("+m+")",T(m),P=!0,N=1,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),o(m),m}var oe=m=>m.startsWith("data:application/octet-stream;base64,"),$e=m=>m.startsWith("file://"),Fe;if(Fe="ort-wasm-simd.wasm",!oe(Fe)){var Pe=Fe;Fe=i.locateFile?i.locateFile(Pe,g):g+Pe}function We(m){if(y)return y(m);throw"both async and sync fetching of the wasm failed"}function wt(m){if(u||h){if(typeof fetch=="function"&&!$e(m))return fetch(m,{credentials:"same-origin"}).then(v=>{if(!v.ok)throw"failed to load wasm binary file at '"+m+"'";return v.arrayBuffer()}).catch(()=>We(m));if(b)return new Promise((v,E)=>{b(m,I=>v(new Uint8Array(I)),E)})}return Promise.resolve().then(()=>We(m))}function Le(m,v,E){return wt(m).then(I=>WebAssembly.instantiate(I,v)).then(I=>I).then(E,I=>{T(`failed to asynchronously prepare wasm: ${I}`),W(I)})}function Ve(m,v){var E=Fe;return typeof WebAssembly.instantiateStreaming!="function"||oe(E)||$e(E)||f||typeof fetch!="function"?Le(E,m,v):fetch(E,{credentials:"same-origin"}).then(I=>WebAssembly.instantiateStreaming(I,m).then(v,function(F){return T(`wasm streaming compile failed: ${F}`),T("falling back to ArrayBuffer instantiation"),Le(E,m,v)}))}var nt,Ct={931056:(m,v,E,I)=>{if(typeof i>"u"||!i.Fa)return 1;if(m=Xe(m>>>0),m.startsWith("./")&&(m=m.substring(2)),m=i.Fa.get(m),!m)return 2;if(v>>>=0,E>>>=0,v+E>m.byteLength)return 3;try{return j.set(m.subarray(v,v+E),I>>>0>>>0),0}catch{return 4}},931557:m=>i.Qa(m),931590:m=>i.Sa(m),931622:(m,v,E)=>{i.La(m,v,E,!0)},931661:(m,v,E)=>{i.La(m,v,E)},931694:m=>{i.sa("Abs",m,void 0)},931745:m=>{i.sa("Neg",m,void 0)},931796:m=>{i.sa("Floor",m,void 0)},931849:m=>{i.sa("Ceil",m,void 0)},931901:m=>{i.sa("Reciprocal",m,void 0)},931959:m=>{i.sa("Sqrt",m,void 0)},932011:m=>{i.sa("Exp",m,void 0)},932062:m=>{i.sa("Erf",m,void 0)},932113:m=>{i.sa("Sigmoid",m,void 0)},932168:m=>{i.sa("Log",m,void 0)},932219:m=>{i.sa("Sin",m,void 0)},932270:m=>{i.sa("Cos",m,void 0)},932321:m=>{i.sa("Tan",m,void 0)},932372:m=>{i.sa("Asin",m,void 0)},932424:m=>{i.sa("Acos",m,void 0)},932476:m=>{i.sa("Atan",m,void 0)},932528:m=>{i.sa("Sinh",m,void 0)},932580:m=>{i.sa("Cosh",m,void 0)},932632:m=>{i.sa("Asinh",m,void 0)},932685:m=>{i.sa("Acosh",m,void 0)},932738:m=>{i.sa("Atanh",m,void 0)},932791:m=>{i.sa("Tanh",m,void 0)},932843:m=>{i.sa("Not",m,void 0)},932894:(m,v,E)=>{i.sa("Clip",m,{min:v,max:E})},932963:m=>{i.sa("Clip",m,void 0)},933015:(m,v)=>{i.sa("Elu",m,{alpha:v})},933073:m=>{i.sa("Relu",m,void 0)},933125:(m,v)=>{i.sa("LeakyRelu",m,{alpha:v})},933189:(m,v)=>{i.sa("ThresholdedRelu",m,{alpha:v})},933259:(m,v)=>{i.sa("Cast",m,{to:v})},933317:m=>{i.sa("Add",m,void 0)},933368:m=>{i.sa("Sub",m,void 0)},933419:m=>{i.sa("Mul",m,void 0)},933470:m=>{i.sa("Div",m,void 0)},933521:m=>{i.sa("Pow",m,void 0)},933572:m=>{i.sa("Equal",m,void 0)},933625:m=>{i.sa("Greater",m,void 0)},933680:m=>{i.sa("GreaterOrEqual",m,void 0)},933742:m=>{i.sa("Less",m,void 0)},933794:m=>{i.sa("LessOrEqual",m,void 0)},933853:(m,v,E,I,F)=>{i.sa("ReduceMean",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},934012:(m,v,E,I,F)=>{i.sa("ReduceMax",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},934170:(m,v,E,I,F)=>{i.sa("ReduceMin",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},934328:(m,v,E,I,F)=>{i.sa("ReduceProd",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},934487:(m,v,E,I,F)=>{i.sa("ReduceSum",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},934645:(m,v,E,I,F)=>{i.sa("ReduceL1",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},934802:(m,v,E,I,F)=>{i.sa("ReduceL2",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},934959:(m,v,E,I,F)=>{i.sa("ReduceLogSum",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},935120:(m,v,E,I,F)=>{i.sa("ReduceSumSquare",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},935284:(m,v,E,I,F)=>{i.sa("ReduceLogSumExp",m,{keepDims:!!v,noopWithEmptyAxes:!!E,axes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},935448:m=>{i.sa("Where",m,void 0)},935501:(m,v,E)=>{i.sa("Transpose",m,{perm:v?Array.from(M.subarray(v>>>0,E>>>0)):[]})},935609:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B,_e)=>{i.sa("ConvTranspose",m,{format:le?"NHWC":"NCHW",autoPad:v,dilations:[E],group:I,kernel_shape:[F],pads:[K,ne],strides:[we],wIsConst:()=>!!V[de>>>0],outputPadding:ge?Array.from(M.subarray(ge>>>0,ke>>>0)):[],outputShape:Oe?Array.from(M.subarray(Oe>>>0,B>>>0)):[],activation:Xe(_e)})},936011:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B)=>{i.sa("ConvTranspose",m,{format:we?"NHWC":"NCHW",autoPad:v,dilations:Array.from(M.subarray(E>>>0,(E>>>0)+2>>>0)),group:I,kernelShape:Array.from(M.subarray(F>>>0,(F>>>0)+2>>>0)),pads:Array.from(M.subarray(K>>>0,(K>>>0)+4>>>0)),strides:Array.from(M.subarray(ne>>>0,(ne>>>0)+2>>>0)),wIsConst:()=>!!V[le>>>0],outputPadding:de?Array.from(M.subarray(de>>>0,ge>>>0)):[],outputShape:ke?Array.from(M.subarray(ke>>>0,Oe>>>0)):[],activation:Xe(B)})},936576:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B,_e)=>{i.sa("ConvTranspose",m,{format:le?"NHWC":"NCHW",autoPad:v,dilations:[E],group:I,kernel_shape:[F],pads:[K,ne],strides:[we],wIsConst:()=>!!V[de>>>0],outputPadding:ge?Array.from(M.subarray(ge>>>0,ke>>>0)):[],outputShape:Oe?Array.from(M.subarray(Oe>>>0,B>>>0)):[],activation:Xe(_e)})},936978:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B)=>{i.sa("ConvTranspose",m,{format:we?"NHWC":"NCHW",autoPad:v,dilations:Array.from(M.subarray(E>>>0,(E>>>0)+2>>>0)),group:I,kernelShape:Array.from(M.subarray(F>>>0,(F>>>0)+2>>>0)),pads:Array.from(M.subarray(K>>>0,(K>>>0)+4>>>0)),strides:Array.from(M.subarray(ne>>>0,(ne>>>0)+2>>>0)),wIsConst:()=>!!V[le>>>0],outputPadding:de?Array.from(M.subarray(de>>>0,ge>>>0)):[],outputShape:ke?Array.from(M.subarray(ke>>>0,Oe>>>0)):[],activation:Xe(B)})},937543:(m,v)=>{i.sa("GlobalAveragePool",m,{format:v?"NHWC":"NCHW"})},937634:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B,_e,Te)=>{i.sa("AveragePool",m,{format:Te?"NHWC":"NCHW",auto_pad:v,ceil_mode:E,count_include_pad:I,storage_order:F,dilations:[K,ne],kernel_shape:[we,le],pads:[de,ge,ke,Oe],strides:[B,_e]})},937918:(m,v)=>{i.sa("GlobalAveragePool",m,{format:v?"NHWC":"NCHW"})},938009:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B,_e,Te)=>{i.sa("AveragePool",m,{format:Te?"NHWC":"NCHW",auto_pad:v,ceil_mode:E,count_include_pad:I,storage_order:F,dilations:[K,ne],kernel_shape:[we,le],pads:[de,ge,ke,Oe],strides:[B,_e]})},938293:(m,v)=>{i.sa("GlobalMaxPool",m,{format:v?"NHWC":"NCHW"})},938380:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B,_e,Te)=>{i.sa("MaxPool",m,{format:Te?"NHWC":"NCHW",auto_pad:v,ceil_mode:E,count_include_pad:I,storage_order:F,dilations:[K,ne],kernel_shape:[we,le],pads:[de,ge,ke,Oe],strides:[B,_e]})},938660:(m,v)=>{i.sa("GlobalMaxPool",m,{format:v?"NHWC":"NCHW"})},938747:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B,_e,Te)=>{i.sa("MaxPool",m,{format:Te?"NHWC":"NCHW",auto_pad:v,ceil_mode:E,count_include_pad:I,storage_order:F,dilations:[K,ne],kernel_shape:[we,le],pads:[de,ge,ke,Oe],strides:[B,_e]})},939027:(m,v,E,I,F)=>{i.sa("Gemm",m,{alpha:v,beta:E,transA:I,transB:F})},939131:m=>{i.sa("MatMul",m,void 0)},939185:(m,v,E,I)=>{i.sa("ArgMax",m,{keepDims:!!v,selectLastIndex:!!E,axis:I})},939293:(m,v,E,I)=>{i.sa("ArgMin",m,{keepDims:!!v,selectLastIndex:!!E,axis:I})},939401:(m,v)=>{i.sa("Softmax",m,{axis:v})},939464:(m,v)=>{i.sa("Concat",m,{axis:v})},939524:(m,v,E,I,F)=>{i.sa("Split",m,{axis:v,numOutputs:E,splitSizes:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},939664:m=>{i.sa("Expand",m,void 0)},939718:(m,v)=>{i.sa("Gather",m,{axis:Number(v)})},939789:(m,v)=>{i.sa("GatherElements",m,{axis:Number(v)})},939868:(m,v,E,I,F,K,ne,we,le,de,ge)=>{i.sa("Resize",m,{antialias:v,axes:E?Array.from(M.subarray(E>>>0,I>>>0)):[],coordinateTransformMode:Xe(F),cubicCoeffA:K,excludeOutside:ne,extrapolationValue:we,keepAspectRatioPolicy:Xe(le),mode:Xe(de),nearestMode:Xe(ge)})},940214:(m,v,E,I,F,K,ne)=>{i.sa("Slice",m,{starts:v?Array.from(M.subarray(v>>>0,E>>>0)):[],ends:I?Array.from(M.subarray(I>>>0,F>>>0)):[],axes:K?Array.from(M.subarray(K>>>0,ne>>>0)):[]})},940430:m=>{i.sa("Tile",m,void 0)},940482:(m,v,E)=>{i.sa("LayerNormalization",m,{axis:Number(v),epsilon:Number(E)})},940589:(m,v,E)=>{i.sa("InstanceNormalization",m,{epsilon:v,format:E?"NHWC":"NCHW"})},940703:(m,v,E)=>{i.sa("InstanceNormalization",m,{epsilon:v,format:E?"NHWC":"NCHW"})},940817:m=>{i.sa("Range",m,void 0)},940870:(m,v)=>{i.sa("Einsum",m,{equation:Xe(v)})},940951:(m,v,E,I,F)=>{i.sa("Pad",m,{mode:v,value:E,pads:I?Array.from(M.subarray(I>>>0,F>>>0)):[]})},941078:(m,v,E,I,F,K)=>{i.sa("BatchNormalization",m,{epsilon:v,momentum:E,spatial:!!F,trainingMode:!!I,format:K?"NHWC":"NCHW"})},941247:(m,v,E,I,F,K)=>{i.sa("BatchNormalization",m,{epsilon:v,momentum:E,spatial:!!F,trainingMode:!!I,format:K?"NHWC":"NCHW"})},941416:(m,v,E)=>{i.sa("CumSum",m,{exclusive:Number(v),reverse:Number(E)})},941513:(m,v,E,I,F,K,ne,we,le)=>{i.sa("Attention",m,{numHeads:v,isUnidirectional:E,maskFilterValue:I,scale:F,doRotary:K,qkvHiddenSizes:ne?Array.from(M.subarray(Number(we)>>>0,Number(we)+ne>>>0)):[],pastPresentShareBuffer:!!le})},941785:m=>{i.sa("Gelu",m,void 0)},941837:(m,v,E,I,F,K)=>{i.sa("MultiHeadAttention",m,{numHeads:v,isUnidirectional:E,maskFilterValue:I,scale:F,doRotary:K})},941996:m=>{i.sa("BiasAdd",m,void 0)},942051:m=>{i.sa("BiasSplitGelu",m,void 0)},942112:(m,v)=>{i.sa("SkipLayerNormalization",m,{epsilon:v})},942193:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe)=>{i.sa("Conv",m,{format:le?"NHWC":"NCHW",auto_pad:v,dilations:[E],group:I,kernel_shape:[F],pads:K?Array.from(M.subarray(K>>>0,ne>>>0)):[],strides:[we],w_is_const:()=>!!V[de>>>0],activation:Xe(ge),activation_params:ke?Array.from(O.subarray(ke>>>0,Oe>>>0)):[]})},942563:(m,v,E,I,F,K,ne,we,le,de,ge,ke,Oe,B,_e,Te)=>{i.sa("Conv",m,{format:ke?"NHWC":"NCHW",auto_pad:v,dilations:[E,I],group:F,kernel_shape:[K,ne],pads:we?Array.from(M.subarray(we>>>0,le>>>0)):[],strides:[de,ge],w_is_const:()=>!!V[Oe>>>0],activation:Xe(B),activation_params:_e?Array.from(O.subarray(_e>>>0,Te>>>0)):[]})},942954:m=>{i.Ta(m)},942988:(m,v)=>i.Ua(m,v,i.Ea.Va,i.Ea.errors)};function zt(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}function da(m){this.Ja=m-24,this.Oa=function(v){G[this.Ja+4>>>2>>>0]=v},this.Na=function(v){G[this.Ja+8>>>2>>>0]=v},this.$a=function(v,E){this.Ma(),this.Oa(v),this.Na(E)},this.Ma=function(){G[this.Ja+16>>>2>>>0]=0}}var on=0,ar=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,wn=(m,v,E)=>{v>>>=0;var I=v+E;for(E=v;m[E]&&!(E>=I);)++E;if(16F?I+=String.fromCharCode(F):(F-=65536,I+=String.fromCharCode(55296|F>>10,56320|F&1023))}}else I+=String.fromCharCode(F)}return I},Xe=(m,v)=>(m>>>=0)?wn(j,m,v):"",zn=m=>{for(var v=0,E=0;E=I?v++:2047>=I?v+=2:55296<=I&&57343>=I?(v+=4,++E):v+=3}return v},ir=(m,v,E,I)=>{if(E>>>=0,!(0=ne){var we=m.charCodeAt(++K);ne=65536+((ne&1023)<<10)|we&1023}if(127>=ne){if(E>=I)break;v[E++>>>0]=ne}else{if(2047>=ne){if(E+1>=I)break;v[E++>>>0]=192|ne>>6}else{if(65535>=ne){if(E+2>=I)break;v[E++>>>0]=224|ne>>12}else{if(E+3>=I)break;v[E++>>>0]=240|ne>>18,v[E++>>>0]=128|ne>>12&63}v[E++>>>0]=128|ne>>6&63}v[E++>>>0]=128|ne&63}}return v[E>>>0]=0,E-F},en=m=>m%4===0&&(m%100!==0||m%400===0),ca=[0,31,60,91,121,152,182,213,244,274,305,335],tn=[0,31,59,90,120,151,181,212,243,273,304,334],Rn=m=>{var v=zn(m)+1,E=Fn(v);return E&&ir(m,j,E,v),E},yn=[],Bn=(m,v)=>{yn.length=0;for(var E;E=j[m++>>>0];){var I=E!=105;I&=E!=112,v+=I&&v%8?4:0,yn.push(E==112?G[v>>>2>>>0]:E==105?M[v>>>2>>>0]:R[v>>>3>>>0]),v+=I?8:4}return yn},Pn={},Gt=()=>{if(!Dn){var m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"},v;for(v in Pn)Pn[v]===void 0?delete m[v]:m[v]=Pn[v];var E=[];for(v in m)E.push(`${v}=${m[v]}`);Dn=E}return Dn},Dn,pa=[null,[],[]],rt=[31,29,31,30,31,30,31,31,30,31,30,31],ha=[31,28,31,30,31,30,31,31,30,31,30,31];function Ue(m){var v=Array(zn(m)+1);return ir(m,v,0,v.length),v}function sr(m,v,E,I){function F(B,_e,Te){for(B=typeof B=="number"?B.toString():B||"";B.length<_e;)B=Te[0]+B;return B}function K(B,_e){return F(B,_e,"0")}function ne(B,_e){function Te(va){return 0>va?-1:0qt-B.getDate())_e-=qt-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()+_e);break}}return Te=new Date(B.getFullYear()+1,0,4),_e=we(new Date(B.getFullYear(),0,4)),Te=we(Te),0>=ne(_e,B)?0>=ne(Te,B)?B.getFullYear()+1:B.getFullYear():B.getFullYear()-1}m>>>=0,v>>>=0,E>>>=0,I>>>=0;var de=G[I+40>>>2>>>0];I={Ya:M[I>>>2>>>0],Xa:M[I+4>>>2>>>0],Ga:M[I+8>>>2>>>0],Ka:M[I+12>>>2>>>0],Ha:M[I+16>>>2>>>0],Da:M[I+20>>>2>>>0],xa:M[I+24>>>2>>>0],Ca:M[I+28>>>2>>>0],bb:M[I+32>>>2>>>0],Wa:M[I+36>>>2>>>0],Za:de?Xe(de):""},E=Xe(E),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 ge in de)E=E.replace(new RegExp(ge,"g"),de[ge]);var ke="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Oe="January February March April May June July August September October November December".split(" ");de={"%a":B=>ke[B.xa].substring(0,3),"%A":B=>ke[B.xa],"%b":B=>Oe[B.Ha].substring(0,3),"%B":B=>Oe[B.Ha],"%C":B=>K((B.Da+1900)/100|0,2),"%d":B=>K(B.Ka,2),"%e":B=>F(B.Ka,2," "),"%g":B=>le(B).toString().substring(2),"%G":B=>le(B),"%H":B=>K(B.Ga,2),"%I":B=>(B=B.Ga,B==0?B=12:12{for(var _e=0,Te=0;Te<=B.Ha-1;_e+=(en(B.Da+1900)?rt:ha)[Te++]);return K(B.Ka+_e,3)},"%m":B=>K(B.Ha+1,2),"%M":B=>K(B.Xa,2),"%n":()=>` -`,"%p":B=>0<=B.Ga&&12>B.Ga?"AM":"PM","%S":B=>K(B.Ya,2),"%t":()=>" ","%u":B=>B.xa||7,"%U":B=>K(Math.floor((B.Ca+7-B.xa)/7),2),"%V":B=>{var _e=Math.floor((B.Ca+7-(B.xa+6)%7)/7);if(2>=(B.xa+371-B.Ca-2)%7&&_e++,_e)_e==53&&(Te=(B.xa+371-B.Ca)%7,Te==4||Te==3&&en(B.Da)||(_e=1));else{_e=52;var Te=(B.xa+7-B.Ca-1)%7;(Te==4||Te==5&&en(B.Da%400-1))&&_e++}return K(_e,2)},"%w":B=>B.xa,"%W":B=>K(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.Wa;var _e=0<=B;return B=Math.abs(B)/60,(_e?"+":"-")+("0000"+(B/60*100+B%60)).slice(-4)},"%Z":B=>B.Za,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0");for(ge in de)E.includes(ge)&&(E=E.replace(new RegExp(ge,"g"),de[ge](I)));return E=E.replace(/\0\0/g,"%"),ge=Ue(E),ge.length>v?0:(V.set(ge,m>>>0),ge.length-1)}var ln=m=>{try{m()}catch(v){W(v)}};function or(){var m=he,v={};for(let[E,I]of Object.entries(m))v[E]=typeof I=="function"?function(){me.push(E);try{return I.apply(null,arguments)}finally{P||(me.pop(),yt&&Ht===1&&me.length===0&&(Ht=0,ln(_r),typeof Fibers<"u"&&Fibers.cb()))}}:I;return v}var Ht=0,yt=null,fa=0,me=[],bn={},lr={},ki=0,Nn=null,ma=[];function ga(){return new Promise((m,v)=>{Nn={resolve:m,reject:v}})}function _a(){var m=Fn(65548),v=m+12;G[m>>>2>>>0]=v,G[m+4>>>2>>>0]=v+65536,v=me[0];var E=bn[v];return E===void 0&&(E=ki++,bn[v]=E,lr[E]=v),M[m+8>>>2>>>0]=E,m}function wa(m){if(!P){if(Ht===0){var v=!1,E=!1;m((I=0)=>{if(!P&&(fa=I,v=!0,E)){Ht=2,ln(()=>wr(yt)),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.resume(),I=!1;try{var F=(0,he[lr[M[yt+8>>>2>>>0]]])()}catch(we){F=we,I=!0}var K=!1;if(!yt){var ne=Nn;ne&&(Nn=null,(I?ne.reject:ne.resolve)(F),K=!0)}if(I&&!K)throw F}}),E=!0,v||(Ht=1,yt=_a(),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.pause(),ln(()=>gr(yt)))}else Ht===2?(Ht=0,ln(yr),cr(yt),yt=null,ma.forEach(I=>{if(!P)try{I();try{N=N=I=N,i.onExit?.(I),P=!0,c(I,new zt(I))}catch(F){F instanceof zt||F=="unwind"||c(1,F)}}catch(F){F instanceof zt||F=="unwind"||c(1,F)}})):W(`invalid state: ${Ht}`);return fa}}function ur(m){return wa(v=>{m().then(v)})}var ya={n:function(m,v,E){return ur(async()=>{await i.Ra(m,v,E)})},a:function(m,v,E){throw m>>>=0,new da(m).$a(v>>>0,E>>>0),on=m,on},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(m,v,E){m=v+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*v:NaN,E>>>=0,m=new Date(1e3*m),M[E>>>2>>>0]=m.getUTCSeconds(),M[E+4>>>2>>>0]=m.getUTCMinutes(),M[E+8>>>2>>>0]=m.getUTCHours(),M[E+12>>>2>>>0]=m.getUTCDate(),M[E+16>>>2>>>0]=m.getUTCMonth(),M[E+20>>>2>>>0]=m.getUTCFullYear()-1900,M[E+24>>>2>>>0]=m.getUTCDay(),M[E+28>>>2>>>0]=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(m,v,E){m=v+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*v:NaN,E>>>=0,m=new Date(1e3*m),M[E>>>2>>>0]=m.getSeconds(),M[E+4>>>2>>>0]=m.getMinutes(),M[E+8>>>2>>>0]=m.getHours(),M[E+12>>>2>>>0]=m.getDate(),M[E+16>>>2>>>0]=m.getMonth(),M[E+20>>>2>>>0]=m.getFullYear()-1900,M[E+24>>>2>>>0]=m.getDay(),M[E+28>>>2>>>0]=(en(m.getFullYear())?ca:tn)[m.getMonth()]+m.getDate()-1|0,M[E+36>>>2>>>0]=-(60*m.getTimezoneOffset()),v=new Date(m.getFullYear(),6,1).getTimezoneOffset();var I=new Date(m.getFullYear(),0,1).getTimezoneOffset();M[E+32>>>2>>>0]=(v!=I&&m.getTimezoneOffset()==Math.min(I,v))|0},s:function(m){m>>>=0;var v=new Date(M[m+20>>>2>>>0]+1900,M[m+16>>>2>>>0],M[m+12>>>2>>>0],M[m+8>>>2>>>0],M[m+4>>>2>>>0],M[m>>>2>>>0],0),E=M[m+32>>>2>>>0],I=v.getTimezoneOffset(),F=new Date(v.getFullYear(),6,1).getTimezoneOffset(),K=new Date(v.getFullYear(),0,1).getTimezoneOffset(),ne=Math.min(K,F);return 0>E?M[m+32>>>2>>>0]=+(F!=K&&ne==I):0>>2>>>0]=v.getDay(),M[m+28>>>2>>>0]=(en(v.getFullYear())?ca:tn)[v.getMonth()]+v.getDate()-1|0,M[m>>>2>>>0]=v.getSeconds(),M[m+4>>>2>>>0]=v.getMinutes(),M[m+8>>>2>>>0]=v.getHours(),M[m+12>>>2>>>0]=v.getDate(),M[m+16>>>2>>>0]=v.getMonth(),M[m+20>>>2>>>0]=v.getYear(),m=v.getTime(),isNaN(m)?(M[dr()>>>2>>>0]=61,m=-1):m/=1e3,pr((nt=m,1<=+Math.abs(nt)?0>>0:~~+Math.ceil((nt-+(~~nt>>>0))/4294967296)>>>0:0)),m>>>0},o:function(){return-52},p:function(){},w:function(m,v,E){function I(le){return(le=le.toTimeString().match(/\(([A-Za-z ]+)\)$/))?le[1]:"GMT"}E>>>=0;var F=new Date().getFullYear(),K=new Date(F,0,1),ne=new Date(F,6,1);F=K.getTimezoneOffset();var we=ne.getTimezoneOffset();G[m>>>0>>>2>>>0]=60*Math.max(F,we),M[v>>>0>>>2>>>0]=+(F!=we),m=I(K),v=I(ne),m=Rn(m),v=Rn(v),we>>2>>>0]=m,G[E+4>>>2>>>0]=v):(G[E>>>2>>>0]=v,G[E+4>>>2>>>0]=m)},e:()=>{W("")},b:function(m,v,E){return m>>>=0,v=Bn(v>>>0,E>>>0),Ct[m].apply(null,v)},i:function(m,v,E){return m>>>=0,v=Bn(v>>>0,E>>>0),Ct[m].apply(null,v)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(m,v,E){return v>>>=0,j.copyWithin(m>>>0>>>0,v>>>0,v+(E>>>0)>>>0)},u:function(m){m>>>=0;var v=j.length;if(4294901760=E;E*=2){var I=v*(1+.2/E);I=Math.min(I,m+100663296);var F=Math;I=Math.max(m,I);e:{F=(F.min.call(F,4294901760,I+(65536-I%65536)%65536)-A.buffer.byteLength+65535)/65536;try{A.grow(F),H();var K=1;break e}catch{}K=void 0}if(K)return!0}return!1},E:function(m,v){m>>>=0,v>>>=0;var E=0;return Gt().forEach((I,F)=>{var K=v+E;for(F=G[m+4*F>>>2>>>0]=K,K=0;K>>0>>>0]=I.charCodeAt(K);V[F>>>0>>>0]=0,E+=I.length+1}),0},F:function(m,v){m>>>=0,v>>>=0;var E=Gt();G[m>>>2>>>0]=E.length;var I=0;return E.forEach(F=>I+=F.length+1),G[v>>>2>>>0]=I,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(m,v,E,I){v>>>=0,E>>>=0,I>>>=0;for(var F=0,K=0;K>>2>>>0],we=G[v+4>>>2>>>0];v+=8;for(var le=0;le>>0],ge=pa[m];de===0||de===10?((m===1?S:T)(wn(ge,0)),ge.length=0):ge.push(de)}F+=we}return G[I>>>2>>>0]=F,0},v:sr,d:function(m,v,E,I){return sr(m>>>0,v>>>0,E>>>0,I>>>0)}},he=function(){function m(E){return he=E.exports,he=or(),he=ba(),A=he.M,H(),ae.unshift(he.N),Y--,Y==0&&ue&&(E=ue,ue=null,E()),he}var v={a:ya};if(Y++,i.instantiateWasm)try{return i.instantiateWasm(v,m)}catch(E){T(`Module.instantiateWasm callback failed with error: ${E}`),o(E)}return Ve(v,function(E){m(E.instance)}).catch(o),{}}();i._OrtInit=(m,v)=>(i._OrtInit=he.O)(m,v),i._OrtGetLastError=(m,v)=>(i._OrtGetLastError=he.P)(m,v),i._OrtCreateSessionOptions=(m,v,E,I,F,K,ne,we,le,de)=>(i._OrtCreateSessionOptions=he.Q)(m,v,E,I,F,K,ne,we,le,de),i._OrtAppendExecutionProvider=(m,v)=>(i._OrtAppendExecutionProvider=he.R)(m,v),i._OrtAddFreeDimensionOverride=(m,v,E)=>(i._OrtAddFreeDimensionOverride=he.S)(m,v,E),i._OrtAddSessionConfigEntry=(m,v,E)=>(i._OrtAddSessionConfigEntry=he.T)(m,v,E),i._OrtReleaseSessionOptions=m=>(i._OrtReleaseSessionOptions=he.U)(m),i._OrtCreateSession=(m,v,E)=>(i._OrtCreateSession=he.V)(m,v,E),i._OrtReleaseSession=m=>(i._OrtReleaseSession=he.W)(m),i._OrtGetInputOutputCount=(m,v,E)=>(i._OrtGetInputOutputCount=he.X)(m,v,E),i._OrtGetInputName=(m,v)=>(i._OrtGetInputName=he.Y)(m,v),i._OrtGetOutputName=(m,v)=>(i._OrtGetOutputName=he.Z)(m,v),i._OrtFree=m=>(i._OrtFree=he._)(m),i._OrtCreateTensor=(m,v,E,I,F,K)=>(i._OrtCreateTensor=he.$)(m,v,E,I,F,K),i._OrtGetTensorData=(m,v,E,I,F)=>(i._OrtGetTensorData=he.aa)(m,v,E,I,F),i._OrtReleaseTensor=m=>(i._OrtReleaseTensor=he.ba)(m),i._OrtCreateRunOptions=(m,v,E,I)=>(i._OrtCreateRunOptions=he.ca)(m,v,E,I),i._OrtAddRunConfigEntry=(m,v,E)=>(i._OrtAddRunConfigEntry=he.da)(m,v,E),i._OrtReleaseRunOptions=m=>(i._OrtReleaseRunOptions=he.ea)(m),i._OrtCreateBinding=m=>(i._OrtCreateBinding=he.fa)(m),i._OrtBindInput=(m,v,E)=>(i._OrtBindInput=he.ga)(m,v,E),i._OrtBindOutput=(m,v,E,I)=>(i._OrtBindOutput=he.ha)(m,v,E,I),i._OrtClearBoundOutputs=m=>(i._OrtClearBoundOutputs=he.ia)(m),i._OrtReleaseBinding=m=>(i._OrtReleaseBinding=he.ja)(m),i._OrtRunWithBinding=(m,v,E,I,F)=>(i._OrtRunWithBinding=he.ka)(m,v,E,I,F),i._OrtRun=(m,v,E,I,F,K,ne,we)=>(i._OrtRun=he.la)(m,v,E,I,F,K,ne,we),i._OrtEndProfiling=m=>(i._OrtEndProfiling=he.ma)(m),i._JsepOutput=(m,v,E)=>(i._JsepOutput=he.na)(m,v,E),i._JsepGetNodeName=m=>(i._JsepGetNodeName=he.oa)(m);var dr=()=>(dr=he.pa)(),Fn=i._malloc=m=>(Fn=i._malloc=he.qa)(m),cr=i._free=m=>(cr=i._free=he.ra)(m),pr=m=>(pr=he.ta)(m),hr=()=>(hr=he.ua)(),fr=m=>(fr=he.va)(m),mr=m=>(mr=he.wa)(m),gr=m=>(gr=he.ya)(m),_r=()=>(_r=he.za)(),wr=m=>(wr=he.Aa)(m),yr=()=>(yr=he.Ba)();i.___start_em_js=943100,i.___stop_em_js=943261;function ba(){var m=he;m=Object.assign({},m);var v=I=>()=>I()>>>0,E=I=>F=>I(F)>>>0;return m.pa=v(m.pa),m.qa=E(m.qa),m.ua=v(m.ua),m.wa=E(m.wa),m}i.stackAlloc=mr,i.stackSave=hr,i.stackRestore=fr,i.UTF8ToString=Xe,i.stringToUTF8=(m,v,E)=>ir(m,j,v,E),i.lengthBytesUTF8=zn;var un;ue=function m(){un||vn(),un||(ue=m)};function vn(){if(!(0n)}),__=Jn(()=>{}),w_=Jn(()=>{}),Wc={};er(Wc,{cpus:()=>Vc});var Vc,y_=X(()=>{Vc=void 0}),b_=Jn((t,e)=>{var n=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),function(a={}){function i(){return te.buffer!=ue.buffer&&We(),ue}function s(){return te.buffer!=ue.buffer&&We(),W}function o(){return te.buffer!=ue.buffer&&We(),oe}function l(){return te.buffer!=ue.buffer&&We(),$e}function d(){return te.buffer!=ue.buffer&&We(),Fe}function c(){return te.buffer!=ue.buffer&&We(),Pe}var u=a,h,f;u.ready=new Promise((p,_)=>{h=p,f=_}),u.mountExternalData=(p,_)=>{(u.cb||(u.cb=new Map)).set(p,_)},u.unmountExternalData=()=>{delete u.cb},u.jsepInit=(p,_,x,C,z,U,q,fe)=>{u.Mb=p,u.wb=_,u.yb=x,u.kb=C,u.xb=z,u.Ea=U,u.zb=q,u.Ab=fe,_=(ce,pe,ye)=>(...Ae)=>{let De=jt,D=pe?.();Ae=ce(...Ae);let be=pe?.();return D!==be&&(ce=be,ye(D),pe=ye=null),jt!=De?kg():Ae},x=ce=>async(...pe)=>{try{if(u.bb)throw Error("Session already started");let ye=u.bb={Cb:pe[0],errors:[]},Ae=await ce(...pe);if(u.bb!==ye)throw Error("Session mismatch");p.flush();let De=ye.errors;if(0be),0u._OrtRun,ce=>u._OrtRun=ce)),u._OrtRunWithBinding=x(_(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,ce=>u._OrtRunWithBinding=ce)),u._OrtBindInput=_(u._OrtBindInput,()=>u._OrtBindInput,ce=>u._OrtBindInput=ce),u.jsepRegisterBuffer=(ce,pe,ye,Ae)=>p.registerBuffer(ce,pe,ye,Ae),u.jsepUnregisterBuffers=ce=>{p.unregisterBuffers(ce)},u.jsepGetBuffer=ce=>p.getBuffer(ce),u.jsepCreateDownloader=(ce,pe,ye)=>p.createDownloader(ce,pe,ye)};var g=Object.assign({},u),w="./this.program",b=(p,_)=>{throw _},y=typeof window=="object",$=typeof importScripts=="function",k=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",S=u.ENVIRONMENT_IS_PTHREAD||!1,T="";function A(p){return u.locateFile?u.locateFile(p,T):T+p}var P,N,V;if(k){var j=(Fc(),Cn(js)),M=(Uc(),Cn(Ks));T=$?M.dirname(T)+"/":__dirname+"/",P=(_,x)=>(_=wn(_)?new URL(_):M.normalize(_),j.readFileSync(_,x?void 0:"utf8")),V=_=>(_=P(_,!0),_.buffer||(_=new Uint8Array(_)),_),N=(_,x,C,z=!0)=>{_=wn(_)?new URL(_):M.normalize(_),j.readFile(_,z?void 0:"utf8",(U,q)=>{U?C(U):x(z?q.buffer:q)})},!u.thisProgram&&1{throw process.exitCode=_,x},u.inspect=()=>"[Emscripten Module object]";let p;try{p=__()}catch(_){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),_}global.Worker=p.Worker}else(y||$)&&($?T=self.location.href:typeof document<"u"&&document.currentScript&&(T=document.currentScript.src),typeof r<"u"&&r&&(T=r),T.indexOf("blob:")!==0?T=T.substr(0,T.replace(/[?#].*/,"").lastIndexOf("/")+1):T="",k||(P=p=>{var _=new XMLHttpRequest;return _.open("GET",p,!1),_.send(null),_.responseText},$&&(V=p=>{var _=new XMLHttpRequest;return _.open("GET",p,!1),_.responseType="arraybuffer",_.send(null),new Uint8Array(_.response)}),N=(p,_,x)=>{var C=new XMLHttpRequest;C.open("GET",p,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?_(C.response):x()},C.onerror=x,C.send(null)}));k&&typeof performance>"u"&&(global.performance=w_().performance);var G=console.log.bind(console),O=console.error.bind(console);k&&(G=(...p)=>j.writeSync(1,p.join(" ")+` -`),O=(...p)=>j.writeSync(2,p.join(" ")+` -`));var R=G,H=O;Object.assign(u,g),g=null,typeof WebAssembly!="object"&&on("no native wasm support detected");var te,ae,re=!1,Y,ue,W,oe,$e,Fe,Pe;function We(){var p=te.buffer;u.HEAP8=ue=new Int8Array(p),u.HEAP16=new Int16Array(p),u.HEAPU8=W=new Uint8Array(p),u.HEAPU16=new Uint16Array(p),u.HEAP32=oe=new Int32Array(p),u.HEAPU32=$e=new Uint32Array(p),u.HEAPF32=Fe=new Float32Array(p),u.HEAPF64=Pe=new Float64Array(p)}var wt=16777216;if(S)te=u.wasmMemory;else if(u.wasmMemory)te=u.wasmMemory;else if(te=new WebAssembly.Memory({initial:wt/65536,maximum:65536,shared:!0}),!(te.buffer instanceof SharedArrayBuffer))throw H("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&&H("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");We(),wt=te.buffer.byteLength;var Le=[],Ve=[],nt=[],Ct=0,zt=null;function da(){if(Ct--,Ct==0&&zt){var p=zt;zt=null,p()}}function on(p){throw p="Aborted("+p+")",H(p),re=!0,Y=1,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),f(p),p}var ar=p=>p.startsWith("data:application/octet-stream;base64,"),wn=p=>p.startsWith("file://"),Xe;Xe="ort-wasm-simd-threaded.wasm",ar(Xe)||(Xe=A(Xe));function zn(p){if(V)return V(p);throw"both async and sync fetching of the wasm failed"}function ir(p){if(y||$){if(typeof fetch=="function"&&!wn(p))return fetch(p,{credentials:"same-origin"}).then(_=>{if(!_.ok)throw"failed to load wasm binary file at '"+p+"'";return _.arrayBuffer()}).catch(()=>zn(p));if(N)return new Promise((_,x)=>{N(p,C=>_(new Uint8Array(C)),x)})}return Promise.resolve().then(()=>zn(p))}function en(p,_,x){return ir(p).then(C=>WebAssembly.instantiate(C,_)).then(C=>C).then(x,C=>{H(`failed to asynchronously prepare wasm: ${C}`),on(C)})}function ca(p,_){var x=Xe;return typeof WebAssembly.instantiateStreaming!="function"||ar(x)||wn(x)||k||typeof fetch!="function"?en(x,p,_):fetch(x,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,p).then(_,function(z){return H(`wasm streaming compile failed: ${z}`),H("falling back to ArrayBuffer instantiation"),en(x,p,_)}))}var tn,Rn={932428:(p,_,x,C)=>{if(typeof u>"u"||!u.cb)return 1;if(p=rt(p>>>0),p.startsWith("./")&&(p=p.substring(2)),p=u.cb.get(p),!p)return 2;if(_>>>=0,x>>>=0,C>>>=0,_+x>p.byteLength)return 3;try{return s().set(p.subarray(_,_+x),C>>>0),0}catch{return 4}},932929:p=>u.wb(p),932962:p=>u.yb(p),932994:(p,_,x)=>{u.kb(p,_,x,!0)},933033:(p,_,x)=>{u.kb(p,_,x)},933066:p=>{u.Ea("Abs",p,void 0)},933117:p=>{u.Ea("Neg",p,void 0)},933168:p=>{u.Ea("Floor",p,void 0)},933221:p=>{u.Ea("Ceil",p,void 0)},933273:p=>{u.Ea("Reciprocal",p,void 0)},933331:p=>{u.Ea("Sqrt",p,void 0)},933383:p=>{u.Ea("Exp",p,void 0)},933434:p=>{u.Ea("Erf",p,void 0)},933485:p=>{u.Ea("Sigmoid",p,void 0)},933540:p=>{u.Ea("Log",p,void 0)},933591:p=>{u.Ea("Sin",p,void 0)},933642:p=>{u.Ea("Cos",p,void 0)},933693:p=>{u.Ea("Tan",p,void 0)},933744:p=>{u.Ea("Asin",p,void 0)},933796:p=>{u.Ea("Acos",p,void 0)},933848:p=>{u.Ea("Atan",p,void 0)},933900:p=>{u.Ea("Sinh",p,void 0)},933952:p=>{u.Ea("Cosh",p,void 0)},934004:p=>{u.Ea("Asinh",p,void 0)},934057:p=>{u.Ea("Acosh",p,void 0)},934110:p=>{u.Ea("Atanh",p,void 0)},934163:p=>{u.Ea("Tanh",p,void 0)},934215:p=>{u.Ea("Not",p,void 0)},934266:(p,_,x)=>{u.Ea("Clip",p,{min:_,max:x})},934335:p=>{u.Ea("Clip",p,void 0)},934387:(p,_)=>{u.Ea("Elu",p,{alpha:_})},934445:p=>{u.Ea("Relu",p,void 0)},934497:(p,_)=>{u.Ea("LeakyRelu",p,{alpha:_})},934561:(p,_)=>{u.Ea("ThresholdedRelu",p,{alpha:_})},934631:(p,_)=>{u.Ea("Cast",p,{to:_})},934689:p=>{u.Ea("Add",p,void 0)},934740:p=>{u.Ea("Sub",p,void 0)},934791:p=>{u.Ea("Mul",p,void 0)},934842:p=>{u.Ea("Div",p,void 0)},934893:p=>{u.Ea("Pow",p,void 0)},934944:p=>{u.Ea("Equal",p,void 0)},934997:p=>{u.Ea("Greater",p,void 0)},935052:p=>{u.Ea("GreaterOrEqual",p,void 0)},935114:p=>{u.Ea("Less",p,void 0)},935166:p=>{u.Ea("LessOrEqual",p,void 0)},935225:(p,_,x,C,z)=>{u.Ea("ReduceMean",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},935384:(p,_,x,C,z)=>{u.Ea("ReduceMax",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},935542:(p,_,x,C,z)=>{u.Ea("ReduceMin",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},935700:(p,_,x,C,z)=>{u.Ea("ReduceProd",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},935859:(p,_,x,C,z)=>{u.Ea("ReduceSum",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},936017:(p,_,x,C,z)=>{u.Ea("ReduceL1",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},936174:(p,_,x,C,z)=>{u.Ea("ReduceL2",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},936331:(p,_,x,C,z)=>{u.Ea("ReduceLogSum",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},936492:(p,_,x,C,z)=>{u.Ea("ReduceSumSquare",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},936656:(p,_,x,C,z)=>{u.Ea("ReduceLogSumExp",p,{keepDims:!!_,noopWithEmptyAxes:!!x,axes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},936820:p=>{u.Ea("Where",p,void 0)},936873:(p,_,x)=>{u.Ea("Transpose",p,{perm:_?Array.from(o().subarray(_>>>0,x>>>0)):[]})},936981:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D,be)=>{u.Ea("ConvTranspose",p,{format:ce?"NHWC":"NCHW",autoPad:_,dilations:[x],group:C,kernel_shape:[z],pads:[U,q],strides:[fe],wIsConst:()=>!!i()[pe>>>0],outputPadding:ye?Array.from(o().subarray(ye>>>0,Ae>>>0)):[],outputShape:De?Array.from(o().subarray(De>>>0,D>>>0)):[],activation:rt(be)})},937383:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D)=>{u.Ea("ConvTranspose",p,{format:fe?"NHWC":"NCHW",autoPad:_,dilations:Array.from(o().subarray(x>>>0,(x>>>0)+2>>>0)),group:C,kernelShape:Array.from(o().subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(o().subarray(U>>>0,(U>>>0)+4>>>0)),strides:Array.from(o().subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!i()[ce>>>0],outputPadding:pe?Array.from(o().subarray(pe>>>0,ye>>>0)):[],outputShape:Ae?Array.from(o().subarray(Ae>>>0,De>>>0)):[],activation:rt(D)})},937948:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D,be)=>{u.Ea("ConvTranspose",p,{format:ce?"NHWC":"NCHW",autoPad:_,dilations:[x],group:C,kernel_shape:[z],pads:[U,q],strides:[fe],wIsConst:()=>!!i()[pe>>>0],outputPadding:ye?Array.from(o().subarray(ye>>>0,Ae>>>0)):[],outputShape:De?Array.from(o().subarray(De>>>0,D>>>0)):[],activation:rt(be)})},938350:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D)=>{u.Ea("ConvTranspose",p,{format:fe?"NHWC":"NCHW",autoPad:_,dilations:Array.from(o().subarray(x>>>0,(x>>>0)+2>>>0)),group:C,kernelShape:Array.from(o().subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(o().subarray(U>>>0,(U>>>0)+4>>>0)),strides:Array.from(o().subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!i()[ce>>>0],outputPadding:pe?Array.from(o().subarray(pe>>>0,ye>>>0)):[],outputShape:Ae?Array.from(o().subarray(Ae>>>0,De>>>0)):[],activation:rt(D)})},938915:(p,_)=>{u.Ea("GlobalAveragePool",p,{format:_?"NHWC":"NCHW"})},939006:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D,be,ze)=>{u.Ea("AveragePool",p,{format:ze?"NHWC":"NCHW",auto_pad:_,ceil_mode:x,count_include_pad:C,storage_order:z,dilations:[U,q],kernel_shape:[fe,ce],pads:[pe,ye,Ae,De],strides:[D,be]})},939290:(p,_)=>{u.Ea("GlobalAveragePool",p,{format:_?"NHWC":"NCHW"})},939381:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D,be,ze)=>{u.Ea("AveragePool",p,{format:ze?"NHWC":"NCHW",auto_pad:_,ceil_mode:x,count_include_pad:C,storage_order:z,dilations:[U,q],kernel_shape:[fe,ce],pads:[pe,ye,Ae,De],strides:[D,be]})},939665:(p,_)=>{u.Ea("GlobalMaxPool",p,{format:_?"NHWC":"NCHW"})},939752:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D,be,ze)=>{u.Ea("MaxPool",p,{format:ze?"NHWC":"NCHW",auto_pad:_,ceil_mode:x,count_include_pad:C,storage_order:z,dilations:[U,q],kernel_shape:[fe,ce],pads:[pe,ye,Ae,De],strides:[D,be]})},940032:(p,_)=>{u.Ea("GlobalMaxPool",p,{format:_?"NHWC":"NCHW"})},940119:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D,be,ze)=>{u.Ea("MaxPool",p,{format:ze?"NHWC":"NCHW",auto_pad:_,ceil_mode:x,count_include_pad:C,storage_order:z,dilations:[U,q],kernel_shape:[fe,ce],pads:[pe,ye,Ae,De],strides:[D,be]})},940399:(p,_,x,C,z)=>{u.Ea("Gemm",p,{alpha:_,beta:x,transA:C,transB:z})},940503:p=>{u.Ea("MatMul",p,void 0)},940557:(p,_,x,C)=>{u.Ea("ArgMax",p,{keepDims:!!_,selectLastIndex:!!x,axis:C})},940665:(p,_,x,C)=>{u.Ea("ArgMin",p,{keepDims:!!_,selectLastIndex:!!x,axis:C})},940773:(p,_)=>{u.Ea("Softmax",p,{axis:_})},940836:(p,_)=>{u.Ea("Concat",p,{axis:_})},940896:(p,_,x,C,z)=>{u.Ea("Split",p,{axis:_,numOutputs:x,splitSizes:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},941036:p=>{u.Ea("Expand",p,void 0)},941090:(p,_)=>{u.Ea("Gather",p,{axis:Number(_)})},941161:(p,_)=>{u.Ea("GatherElements",p,{axis:Number(_)})},941240:(p,_,x,C,z,U,q,fe,ce,pe,ye)=>{u.Ea("Resize",p,{antialias:_,axes:x?Array.from(o().subarray(x>>>0,C>>>0)):[],coordinateTransformMode:rt(z),cubicCoeffA:U,excludeOutside:q,extrapolationValue:fe,keepAspectRatioPolicy:rt(ce),mode:rt(pe),nearestMode:rt(ye)})},941586:(p,_,x,C,z,U,q)=>{u.Ea("Slice",p,{starts:_?Array.from(o().subarray(_>>>0,x>>>0)):[],ends:C?Array.from(o().subarray(C>>>0,z>>>0)):[],axes:U?Array.from(o().subarray(U>>>0,q>>>0)):[]})},941802:p=>{u.Ea("Tile",p,void 0)},941854:(p,_,x)=>{u.Ea("LayerNormalization",p,{axis:Number(_),epsilon:Number(x)})},941961:(p,_,x)=>{u.Ea("InstanceNormalization",p,{epsilon:_,format:x?"NHWC":"NCHW"})},942075:(p,_,x)=>{u.Ea("InstanceNormalization",p,{epsilon:_,format:x?"NHWC":"NCHW"})},942189:p=>{u.Ea("Range",p,void 0)},942242:(p,_)=>{u.Ea("Einsum",p,{equation:rt(_)})},942323:(p,_,x,C,z)=>{u.Ea("Pad",p,{mode:_,value:x,pads:C?Array.from(o().subarray(C>>>0,z>>>0)):[]})},942450:(p,_,x,C,z,U)=>{u.Ea("BatchNormalization",p,{epsilon:_,momentum:x,spatial:!!z,trainingMode:!!C,format:U?"NHWC":"NCHW"})},942619:(p,_,x,C,z,U)=>{u.Ea("BatchNormalization",p,{epsilon:_,momentum:x,spatial:!!z,trainingMode:!!C,format:U?"NHWC":"NCHW"})},942788:(p,_,x)=>{u.Ea("CumSum",p,{exclusive:Number(_),reverse:Number(x)})},942885:(p,_,x,C,z,U,q,fe,ce)=>{u.Ea("Attention",p,{numHeads:_,isUnidirectional:x,maskFilterValue:C,scale:z,doRotary:U,qkvHiddenSizes:q?Array.from(o().subarray(Number(fe)>>>0,Number(fe)+q>>>0)):[],pastPresentShareBuffer:!!ce})},943157:p=>{u.Ea("Gelu",p,void 0)},943209:(p,_,x,C,z,U)=>{u.Ea("MultiHeadAttention",p,{numHeads:_,isUnidirectional:x,maskFilterValue:C,scale:z,doRotary:U})},943368:p=>{u.Ea("BiasAdd",p,void 0)},943423:p=>{u.Ea("BiasSplitGelu",p,void 0)},943484:(p,_)=>{u.Ea("SkipLayerNormalization",p,{epsilon:_})},943565:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De)=>{u.Ea("Conv",p,{format:ce?"NHWC":"NCHW",auto_pad:_,dilations:[x],group:C,kernel_shape:[z],pads:U?Array.from(o().subarray(U>>>0,q>>>0)):[],strides:[fe],w_is_const:()=>!!i()[pe>>>0],activation:rt(ye),activation_params:Ae?Array.from(d().subarray(Ae>>>0,De>>>0)):[]})},943935:(p,_,x,C,z,U,q,fe,ce,pe,ye,Ae,De,D,be,ze)=>{u.Ea("Conv",p,{format:Ae?"NHWC":"NCHW",auto_pad:_,dilations:[x,C],group:z,kernel_shape:[U,q],pads:fe?Array.from(o().subarray(fe>>>0,ce>>>0)):[],strides:[pe,ye],w_is_const:()=>!!i()[De>>>0],activation:rt(D),activation_params:be?Array.from(d().subarray(be>>>0,ze>>>0)):[]})},944326:p=>{u.zb(p)},944360:(p,_)=>u.Ab(p,_,u.bb.Cb,u.bb.errors)};function yn(p){this.name="ExitStatus",this.message=`Program terminated with exit(${p})`,this.status=p}var Bn=p=>{p.terminate(),p.onmessage=()=>{}},Pn=p=>{me.Ya.length==0&&(yt(),me.lb(me.Ya[0]));var _=me.Ya.pop();if(!_)return 6;me.Za.push(_),me.Qa[p.Xa]=_,_.Xa=p.Xa;var x={cmd:"run",start_routine:p.Db,arg:p.tb,pthread_ptr:p.Xa};return k&&_.unref(),_.postMessage(x,p.Jb),0},Gt=0,Dn=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,pa=(p,_,x)=>{_>>>=0;var C=_+x;for(x=_;p[x]&&!(x>=C);)++x;if(16z?C+=String.fromCharCode(z):(z-=65536,C+=String.fromCharCode(55296|z>>10,56320|z&1023))}}else C+=String.fromCharCode(z)}return C},rt=(p,_)=>(p>>>=0)?pa(s(),p,_):"",ha=p=>{var _=Mi();return p=p(),Ea(_),p};function Ue(p,_){var x=arguments.length-2,C=arguments;return ha(()=>{for(var z=Oi(8*x),U=z>>>3,q=0;q>>0]=fe}return Ro(p,x,z,_)})}function sr(p){if(S)return Ue(0,1,p);Y=p,0{if(Y=p,S)throw lr(p),"unwind";sr(p)},or=p=>{p instanceof yn||p=="unwind"||b(1,p)};function Ht(){for(var p=u.numThreads;p--;)yt();Le.unshift(()=>{Ct++,fa(()=>da())})}function yt(){var p=A("ort-wasm-simd-threaded.worker.js");p=new Worker(p),me.Ya.push(p)}function fa(p){S?p():Promise.all(me.Ya.map(me.lb)).then(p)}var me={Ya:[],Za:[],pb:[],Qa:{},hb(){S?(me.receiveObjectTransfer=me.Bb,me.threadInitTLS=me.ob,me.setExitStatus=me.nb):Ht()},nb:p=>Y=p,Nb:["$terminateWorker"],Eb:()=>{for(var p of me.Za)Bn(p);for(p of me.Ya)Bn(p);me.Ya=[],me.Za=[],me.Qa=[]},mb:p=>{var _=p.Xa;delete me.Qa[_],me.Ya.push(p),me.Za.splice(me.Za.indexOf(p),1),p.Xa=0,Ii(_)},Bb(){},ob(){me.pb.forEach(p=>p())},lb:p=>new Promise(_=>{p.onmessage=U=>{U=U.data;var q=U.cmd;if(U.targetThread&&U.targetThread!=Sa()){var fe=me.Qa[U.targetThread];fe?fe.postMessage(U,U.transferList):H(`Internal error! Worker sent a message "${q}" to target pthread ${U.targetThread}, but that thread no longer exists!`)}else q==="checkMailbox"?vn():q==="spawnThread"?Pn(U):q==="cleanupThread"?me.mb(me.Qa[U.thread]):q==="killThread"?(U=U.thread,q=me.Qa[U],delete me.Qa[U],Bn(q),Ii(U),me.Za.splice(me.Za.indexOf(q),1),q.Xa=0):q==="cancelThread"?me.Qa[U.thread].postMessage({cmd:"cancel"}):q==="loaded"?(p.loaded=!0,k&&!p.Xa&&p.unref(),_(p)):q==="alert"?alert(`Thread ${U.threadId}: ${U.text}`):U.target==="setimmediate"?p.postMessage(U):q==="callHandler"?u[U.handler](...U.args):q&&H(`worker sent an unknown command ${q}`)},p.onerror=U=>{throw H(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U},k&&(p.on("message",U=>p.onmessage({data:U})),p.on("error",U=>p.onerror(U)));var x=[],C=["onExit"],z;for(z of C)u.hasOwnProperty(z)&&x.push(z);p.postMessage({cmd:"load",handlers:x,urlOrBlob:u.mainScriptUrlOrBlob||r,wasmMemory:te,wasmModule:ae})})};u.PThread=me;var bn=p=>{for(;0{var p=Sa(),_=l()[p+52>>>2>>>0];p=l()[p+56>>>2>>>0],Do(_,_-p),Ea(_)};function lr(p){if(S)return Ue(1,0,p);ln(p)}u.invokeEntryPoint=(p,_)=>{p=No.apply(null,[p,_]),0>>2>>>0]=_},this.rb=function(_){l()[this.gb+8>>>2>>>0]=_},this.hb=function(_,x){this.qb(),this.sb(_),this.rb(x)},this.qb=function(){l()[this.gb+16>>>2>>>0]=0}}var Nn=0;function ma(p,_,x,C){return S?Ue(2,1,p,_,x,C):ga(p,_,x,C)}function ga(p,_,x,C){if(p>>>=0,_>>>=0,x>>>=0,C>>>=0,typeof SharedArrayBuffer>"u")return H("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var z=[];return S&&z.length===0?ma(p,_,x,C):(p={Db:x,Xa:p,tb:C,Jb:z},S?(p.Lb="spawnThread",postMessage(p,z),0):Pn(p))}function _a(p,_,x){return S?Ue(3,1,p,_,x):0}function wa(p,_){if(S)return Ue(4,1,p,_)}var ur=p=>{for(var _=0,x=0;x=C?_++:2047>=C?_+=2:55296<=C&&57343>=C?(_+=4,++x):_+=3}return _},ya=(p,_,x,C)=>{if(x>>>=0,!(0=q){var fe=p.charCodeAt(++U);q=65536+((q&1023)<<10)|fe&1023}if(127>=q){if(x>=C)break;_[x++>>>0]=q}else{if(2047>=q){if(x+1>=C)break;_[x++>>>0]=192|q>>6}else{if(65535>=q){if(x+2>=C)break;_[x++>>>0]=224|q>>12}else{if(x+3>=C)break;_[x++>>>0]=240|q>>18,_[x++>>>0]=128|q>>12&63}_[x++>>>0]=128|q>>6&63}_[x++>>>0]=128|q&63}}return _[x>>>0]=0,x-z},he=(p,_,x)=>ya(p,s(),_,x);function dr(p,_){if(S)return Ue(5,1,p,_)}function Fn(p,_,x){if(S)return Ue(6,1,p,_,x)}function cr(p,_,x){return S?Ue(7,1,p,_,x):0}function pr(p,_){if(S)return Ue(8,1,p,_)}function hr(p,_,x){if(S)return Ue(9,1,p,_,x)}function fr(p,_,x,C){if(S)return Ue(10,1,p,_,x,C)}function mr(p,_,x,C){if(S)return Ue(11,1,p,_,x,C)}function gr(p,_,x,C){if(S)return Ue(12,1,p,_,x,C)}function _r(p){if(S)return Ue(13,1,p)}function wr(p,_){if(S)return Ue(14,1,p,_)}function yr(p,_,x){if(S)return Ue(15,1,p,_,x)}var ba=()=>{if(!(0>>=0,typeof Atomics.Kb=="function"&&(Atomics.Kb(o(),p>>>2,p).value.then(vn),p+=128,Atomics.store(o(),p>>>2,1))}u.__emscripten_thread_mailbox_await=un;var vn=()=>{var p=Sa();if(p&&(un(p),!re))try{Bo(),ba()}catch(_){or(_)}};u.checkMailbox=vn;var m=[],v=p=>p%4===0&&(p%100!==0||p%400===0),E=[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 F(p,_,x,C,z,U,q,fe){return S?Ue(16,1,p,_,x,C,z,U,q,fe):-52}function K(p,_,x,C,z,U,q){if(S)return Ue(17,1,p,_,x,C,z,U,q)}var ne=p=>{var _=ur(p)+1,x=Ti(_);return x&&he(p,x,_),x},we=[],le=(p,_)=>{we.length=0;for(var x;x=s()[p++>>>0];){var C=x!=105;C&=x!=112,_+=C&&_%8?4:0,we.push(x==112?l()[_>>>2>>>0]:x==105?o()[_>>>2>>>0]:c()[_>>>3>>>0]),_+=C?8:4}return we},de={},ge=()=>{if(!ke){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",_:w||"./this.program"},_;for(_ in de)de[_]===void 0?delete p[_]:p[_]=de[_];var x=[];for(_ in p)x.push(`${_}=${p[_]}`);ke=x}return ke},ke;function Oe(p,_){if(S)return Ue(18,1,p,_);p>>>=0,_>>>=0;var x=0;return ge().forEach((C,z)=>{var U=_+x;for(z=l()[p+4*z>>>2>>>0]=U,U=0;U>>0>>>0]=C.charCodeAt(U);i()[z>>>0>>>0]=0,x+=C.length+1}),0}function B(p,_){if(S)return Ue(19,1,p,_);p>>>=0,_>>>=0;var x=ge();l()[p>>>2>>>0]=x.length;var C=0;return x.forEach(z=>C+=z.length+1),l()[_>>>2>>>0]=C,0}function _e(p){return S?Ue(20,1,p):52}function Te(p,_,x,C){return S?Ue(21,1,p,_,x,C):52}function qt(p,_,x,C,z){return S?Ue(22,1,p,_,x,C,z):70}var va=[null,[],[]];function So(p,_,x,C){if(S)return Ue(23,1,p,_,x,C);_>>>=0,x>>>=0,C>>>=0;for(var z=0,U=0;U>>2>>>0],fe=l()[_+4>>>2>>>0];_+=8;for(var ce=0;ce>>0],ye=va[p];pe===0||pe===10?((p===1?R:H)(pa(ye,0)),ye.length=0):ye.push(pe)}z+=fe}return l()[C>>>2>>>0]=z,0}var Eo=[31,29,31,30,31,30,31,31,30,31,30,31],ko=[31,28,31,30,31,30,31,31,30,31,30,31];function vg(p){var _=Array(ur(p)+1);return ya(p,_,0,_.length),_}var $g=(p,_)=>{i().set(p,_>>>0)};function Co(p,_,x,C){function z(D,be,ze){for(D=typeof D=="number"?D.toString():D||"";D.lengthGo?-1:0$n-D.getDate())be-=$n-D.getDate()+1,D.setDate(1),11>ze?D.setMonth(ze+1):(D.setMonth(0),D.setFullYear(D.getFullYear()+1));else{D.setDate(D.getDate()+be);break}}return ze=new Date(D.getFullYear()+1,0,4),be=fe(new Date(D.getFullYear(),0,4)),ze=fe(ze),0>=q(be,D)?0>=q(ze,D)?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}p>>>=0,_>>>=0,x>>>=0,C>>>=0;var pe=l()[C+40>>>2>>>0];C={Hb:o()[C>>>2>>>0],Gb: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],Ob:o()[C+32>>>2>>>0],Fb:o()[C+36>>>2>>>0],Ib:pe?rt(pe):""},x=rt(x),pe={"%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 ye in pe)x=x.replace(new RegExp(ye,"g"),pe[ye]);var Ae="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),De="January February March April May June July August September October November December".split(" ");pe={"%a":D=>Ae[D.Wa].substring(0,3),"%A":D=>Ae[D.Wa],"%b":D=>De[D.fb].substring(0,3),"%B":D=>De[D.fb],"%C":D=>U((D.ab+1900)/100|0,2),"%d":D=>U(D.jb,2),"%e":D=>z(D.jb,2," "),"%g":D=>ce(D).toString().substring(2),"%G":D=>ce(D),"%H":D=>U(D.eb,2),"%I":D=>(D=D.eb,D==0?D=12:12{for(var be=0,ze=0;ze<=D.fb-1;be+=(v(D.ab+1900)?Eo:ko)[ze++]);return U(D.jb+be,3)},"%m":D=>U(D.fb+1,2),"%M":D=>U(D.Gb,2),"%n":()=>` -`,"%p":D=>0<=D.eb&&12>D.eb?"AM":"PM","%S":D=>U(D.Hb,2),"%t":()=>" ","%u":D=>D.Wa||7,"%U":D=>U(Math.floor((D.$a+7-D.Wa)/7),2),"%V":D=>{var be=Math.floor((D.$a+7-(D.Wa+6)%7)/7);if(2>=(D.Wa+371-D.$a-2)%7&&be++,be)be==53&&(ze=(D.Wa+371-D.$a)%7,ze==4||ze==3&&v(D.ab)||(be=1));else{be=52;var ze=(D.Wa+7-D.$a-1)%7;(ze==4||ze==5&&v(D.ab%400-1))&&be++}return U(be,2)},"%w":D=>D.Wa,"%W":D=>U(Math.floor((D.$a+7-(D.Wa+6)%7)/7),2),"%y":D=>(D.ab+1900).toString().substring(2),"%Y":D=>D.ab+1900,"%z":D=>{D=D.Fb;var be=0<=D;return D=Math.abs(D)/60,(be?"+":"-")+("0000"+(D/60*100+D%60)).slice(-4)},"%Z":D=>D.Ib,"%%":()=>"%"},x=x.replace(/%%/g,"\0\0");for(ye in pe)x.includes(ye)&&(x=x.replace(new RegExp(ye,"g"),pe[ye](C)));return x=x.replace(/\0\0/g,"%"),ye=vg(x),ye.length>_?0:($g(ye,p),ye.length-1)}var $a=p=>{try{p()}catch(_){on(_)}};function xg(){var p=se,_={};for(let[x,C]of Object.entries(p))_[x]=typeof C=="function"?function(){xa.push(x);try{return C.apply(null,arguments)}finally{re||(xa.pop(),jt&&dn===1&&xa.length===0&&(dn=0,Gt+=1,$a(Lo),typeof Fibers<"u"&&Fibers.Pb()))}}:C;return _}var dn=0,jt=null,To=0,xa=[],Io={},Ao={},Sg=0,Ci=null,Eg=[];function kg(){return new Promise((p,_)=>{Ci={resolve:p,reject:_}})}function Cg(){var p=Ti(65548),_=p+12;l()[p>>>2>>>0]=_,l()[p+4>>>2>>>0]=_+65536,_=xa[0];var x=Io[_];return x===void 0&&(x=Sg++,Io[_]=x,Ao[x]=_),_=x,o()[p+8>>>2>>>0]=_,p}function Tg(){var p=o()[jt+8>>>2>>>0];return p=se[Ao[p]],--Gt,p()}function Ig(p){if(!re){if(dn===0){var _=!1,x=!1;p((C=0)=>{if(!re&&(To=C,_=!0,x)){dn=2,$a(()=>Uo(jt)),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.resume(),C=!1;try{var z=Tg()}catch(fe){z=fe,C=!0}var U=!1;if(!jt){var q=Ci;q&&(Ci=null,(C?q.reject:q.resolve)(z),U=!0)}if(C&&!U)throw z}}),x=!0,_||(dn=1,jt=Cg(),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.pause(),$a(()=>Fo(jt)))}else dn===2?(dn=0,$a(Wo),Oo(jt),jt=null,Eg.forEach(C=>{if(!re)try{C(),ba()}catch(z){or(z)}})):on(`invalid state: ${dn}`);return To}}function Ag(p){return Ig(_=>{p().then(_)})}me.hb();var Mg=[sr,lr,ma,_a,wa,dr,Fn,cr,pr,hr,fr,mr,gr,_r,wr,yr,F,K,Oe,B,_e,Te,qt,So],Og={r:function(p,_,x){return Ag(async()=>{await u.xb(p,_,x)})},b:function(p,_,x){throw p>>>=0,new ki(p).hb(_>>>0,x>>>0),Nn=p,Nn},N:function(p){zo(p>>>0,!$,1,!y,131072,!1),me.ob()},l:function(p){p>>>=0,S?postMessage({cmd:"cleanupThread",thread:p}):me.mb(me.Qa[p])},J:ga,i:_a,T:wa,F:dr,H:Fn,U:cr,R:pr,L:hr,Q:fr,p:mr,G:gr,D:_r,S:wr,E:yr,q:()=>1,B:function(p,_){p>>>=0,p==_>>>0?setTimeout(()=>vn()):S?postMessage({targetThread:p,cmd:"checkMailbox"}):(p=me.Qa[p])&&p.postMessage({cmd:"checkMailbox"})},K:function(p,_,x,C){_>>>=0,m.length=x,C=C>>>0>>>3;for(var z=0;z>>0];return p=0>p?Rn[-p-1]:Mg[p],me.ub=_,_=p.apply(null,m),me.ub=0,_},M:un,W:function(p){k&&me.Qa[p>>>0].ref()},u:function(p,_,x){p=_+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*_: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,_,x){p=_+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*_: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(),_=(v(p.getFullYear())?E:I)[p.getMonth()]+p.getDate()-1|0,o()[x+28>>>2>>>0]=_,o()[x+36>>>2>>>0]=-(60*p.getTimezoneOffset()),_=new Date(p.getFullYear(),6,1).getTimezoneOffset();var C=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=(_!=C&&p.getTimezoneOffset()==Math.min(C,_))|0,o()[x+32>>>2>>>0]=p},w:function(p){p>>>=0;var _=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=_.getTimezoneOffset(),z=new Date(_.getFullYear(),6,1).getTimezoneOffset(),U=new Date(_.getFullYear(),0,1).getTimezoneOffset(),q=Math.min(U,z);return 0>x?o()[p+32>>>2>>>0]=+(z!=U&&q==C):0>>2>>>0]=_.getDay(),x=(v(_.getFullYear())?E:I)[_.getMonth()]+_.getDate()-1|0,o()[p+28>>>2>>>0]=x,o()[p>>>2>>>0]=_.getSeconds(),o()[p+4>>>2>>>0]=_.getMinutes(),o()[p+8>>>2>>>0]=_.getHours(),o()[p+12>>>2>>>0]=_.getDate(),o()[p+16>>>2>>>0]=_.getMonth(),o()[p+20>>>2>>>0]=_.getYear(),p=_.getTime(),isNaN(p)?(o()[Mo()>>>2>>>0]=61,p=-1):p/=1e3,Po((tn=p,1<=+Math.abs(tn)?0>>0:~~+Math.ceil((tn-+(~~tn>>>0))/4294967296)>>>0:0)),p>>>0},s:F,t:K,A:function(p,_,x){function C(pe){return(pe=pe.toTimeString().match(/\(([A-Za-z ]+)\)$/))?pe[1]:"GMT"}p>>>=0,_>>>=0,x>>>=0;var z=new Date().getFullYear(),U=new Date(z,0,1),q=new Date(z,6,1);z=U.getTimezoneOffset();var fe=q.getTimezoneOffset(),ce=Math.max(z,fe);l()[p>>>2>>>0]=60*ce,o()[_>>>2>>>0]=+(z!=fe),p=C(U),_=C(q),p=ne(p),_=ne(_),fe>>2>>>0]=p,l()[x+4>>>2>>>0]=_):(l()[x>>>2>>>0]=_,l()[x+4>>>2>>>0]=p)},d:()=>{on("")},c:function(p,_,x){return p>>>=0,_=le(_>>>0,x>>>0),Rn[p].apply(null,_)},k:function(p,_,x){return p>>>=0,_=le(_>>>0,x>>>0),Rn[p].apply(null,_)},m:()=>{},j:()=>Date.now(),V:()=>{throw Gt+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>k?(y_(),Cn(Wc)).cpus().length:navigator.hardwareConcurrency,y:function(p){p>>>=0;var _=s().length;if(p<=_||4294901760=x;x*=2){var C=_*(1+.2/x);C=Math.min(C,p+100663296);var z=Math;C=Math.max(p,C);e:{z=(z.min.call(z,4294901760,C+(65536-C%65536)%65536)-te.buffer.byteLength+65535)/65536;try{te.grow(z),We();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1},O:Oe,P:B,I:ln,h:_e,o:Te,x:qt,n:So,a:te||u.wasmMemory,z:Co,e:function(p,_,x,C){return Co(p>>>0,_>>>0,x>>>0,C>>>0)}},se=function(){function p(x,C){return se=x.exports,se=xg(),se=zg(),me.pb.push(se.Da),Ve.unshift(se.X),ae=C,da(),se}var _={a:Og};if(Ct++,u.instantiateWasm)try{return u.instantiateWasm(_,p)}catch(x){H(`Module.instantiateWasm callback failed with error: ${x}`),f(x)}return ca(_,function(x){p(x.instance,x.module)}).catch(f),{}}();u._OrtInit=(p,_)=>(u._OrtInit=se.Y)(p,_),u._OrtGetLastError=(p,_)=>(u._OrtGetLastError=se.Z)(p,_),u._OrtCreateSessionOptions=(p,_,x,C,z,U,q,fe,ce,pe)=>(u._OrtCreateSessionOptions=se._)(p,_,x,C,z,U,q,fe,ce,pe),u._OrtAppendExecutionProvider=(p,_)=>(u._OrtAppendExecutionProvider=se.$)(p,_),u._OrtAddFreeDimensionOverride=(p,_,x)=>(u._OrtAddFreeDimensionOverride=se.aa)(p,_,x),u._OrtAddSessionConfigEntry=(p,_,x)=>(u._OrtAddSessionConfigEntry=se.ba)(p,_,x),u._OrtReleaseSessionOptions=p=>(u._OrtReleaseSessionOptions=se.ca)(p),u._OrtCreateSession=(p,_,x)=>(u._OrtCreateSession=se.da)(p,_,x),u._OrtReleaseSession=p=>(u._OrtReleaseSession=se.ea)(p),u._OrtGetInputOutputCount=(p,_,x)=>(u._OrtGetInputOutputCount=se.fa)(p,_,x),u._OrtGetInputName=(p,_)=>(u._OrtGetInputName=se.ga)(p,_),u._OrtGetOutputName=(p,_)=>(u._OrtGetOutputName=se.ha)(p,_),u._OrtFree=p=>(u._OrtFree=se.ia)(p),u._OrtCreateTensor=(p,_,x,C,z,U)=>(u._OrtCreateTensor=se.ja)(p,_,x,C,z,U),u._OrtGetTensorData=(p,_,x,C,z)=>(u._OrtGetTensorData=se.ka)(p,_,x,C,z),u._OrtReleaseTensor=p=>(u._OrtReleaseTensor=se.la)(p),u._OrtCreateRunOptions=(p,_,x,C)=>(u._OrtCreateRunOptions=se.ma)(p,_,x,C),u._OrtAddRunConfigEntry=(p,_,x)=>(u._OrtAddRunConfigEntry=se.na)(p,_,x),u._OrtReleaseRunOptions=p=>(u._OrtReleaseRunOptions=se.oa)(p),u._OrtCreateBinding=p=>(u._OrtCreateBinding=se.pa)(p),u._OrtBindInput=(p,_,x)=>(u._OrtBindInput=se.qa)(p,_,x),u._OrtBindOutput=(p,_,x,C)=>(u._OrtBindOutput=se.ra)(p,_,x,C),u._OrtClearBoundOutputs=p=>(u._OrtClearBoundOutputs=se.sa)(p),u._OrtReleaseBinding=p=>(u._OrtReleaseBinding=se.ta)(p),u._OrtRunWithBinding=(p,_,x,C,z)=>(u._OrtRunWithBinding=se.ua)(p,_,x,C,z),u._OrtRun=(p,_,x,C,z,U,q,fe)=>(u._OrtRun=se.va)(p,_,x,C,z,U,q,fe),u._OrtEndProfiling=p=>(u._OrtEndProfiling=se.wa)(p),u._JsepOutput=(p,_,x)=>(u._JsepOutput=se.xa)(p,_,x),u._JsepGetNodeName=p=>(u._JsepGetNodeName=se.ya)(p);var Mo=()=>(Mo=se.za)(),Sa=u._pthread_self=()=>(Sa=u._pthread_self=se.Aa)(),Ti=u._malloc=p=>(Ti=u._malloc=se.Ba)(p),Oo=u._free=p=>(Oo=u._free=se.Ca)(p);u.__emscripten_tls_init=()=>(u.__emscripten_tls_init=se.Da)();var zo=u.__emscripten_thread_init=(p,_,x,C,z,U)=>(zo=u.__emscripten_thread_init=se.Fa)(p,_,x,C,z,U);u.__emscripten_thread_crashed=()=>(u.__emscripten_thread_crashed=se.Ga)();var Ro=(p,_,x,C)=>(Ro=se.Ha)(p,_,x,C),Ii=p=>(Ii=se.Ia)(p),Ai=u.__emscripten_thread_exit=p=>(Ai=u.__emscripten_thread_exit=se.Ja)(p),Bo=()=>(Bo=se.Ka)(),Po=p=>(Po=se.La)(p),Do=(p,_)=>(Do=se.Ma)(p,_),Mi=()=>(Mi=se.Na)(),Ea=p=>(Ea=se.Oa)(p),Oi=p=>(Oi=se.Pa)(p),No=u.dynCall_ii=(p,_)=>(No=u.dynCall_ii=se.Ra)(p,_),Fo=p=>(Fo=se.Sa)(p),Lo=()=>(Lo=se.Ta)(),Uo=p=>(Uo=se.Ua)(p),Wo=()=>(Wo=se.Va)();u.___start_em_js=944472,u.___stop_em_js=944633;function zg(){var p=se;p=Object.assign({},p);var _=C=>()=>C()>>>0,x=C=>z=>C(z)>>>0;return p.za=_(p.za),p.Aa=_(p.Aa),p.Ba=x(p.Ba),p.emscripten_main_runtime_thread_id=_(p.emscripten_main_runtime_thread_id),p.Na=_(p.Na),p.Pa=x(p.Pa),p}u.wasmMemory=te,u.stackAlloc=Oi,u.stackSave=Mi,u.stackRestore=Ea,u.keepRuntimeAlive=()=>0n)}),v_=Jn((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'}),Xo,Qo,Di,Ia,vr,Ni,Zo,Jo,el,Gc,tt,Gr=X(()=>{Xo=g_(),Qo=b_(),Ia=!1,vr=!1,Ni=!1,Zo=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}},Jo=()=>{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}},el=(t,e)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Gc=async t=>{if(Ia)return Promise.resolve();if(vr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ni)throw new Error("previous call to 'initializeWebAssembly()' failed.");vr=!0;let e=t.initTimeout,n=t.numThreads,r=t.simd,a=Zo(n),i=r&&Jo(),s=t.wasmPaths,o=typeof s=="string"?s:void 0,l=el(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,f)=>{let g=a?Qo:Xo,w={locateFile:(b,y)=>{if(a&&b.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([v_()],{type:"text/javascript"}));if(b.endsWith(".wasm")){if(d)return d;let $=o??y;return l==="ort-wasm-simd.wasm"?$+"ort-wasm-simd.jsep.wasm":l==="ort-wasm-simd-threaded.wasm"?$+"ort-wasm-simd-threaded.jsep.wasm":$+l}return y+b}};if(a)if(w.numThreads=n,typeof Blob>"u")w.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let b=`var ortWasmThreaded=${g.toString()};`;w.mainScriptUrlOrBlob=new Blob([b],{type:"text/javascript"})}g(w).then(b=>{vr=!1,Ia=!0,Di=b,h()},b=>{vr=!1,Ni=!0,f(b)})})),await Promise.race(u),c)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},tt=()=>{if(Ia&&Di)return Di;throw new Error("WebAssembly is not initialized yet.")}}),et,ja,He,Ys=X(()=>{Gr(),et=(t,e)=>{let n=tt(),r=n.lengthBytesUTF8(t)+1,a=n._malloc(r);return n.stringToUTF8(t,a,r),e.push(a),a},ja=(t,e,n,r)=>{if(typeof t=="object"&&t!==null){if(n.has(t))throw new Error("Circular reference in options");n.add(t)}Object.entries(t).forEach(([a,i])=>{let s=e?e+a:a;if(typeof i=="object")ja(i,s+".",n,r);else if(typeof i=="string"||typeof i=="number")r(s,i.toString());else if(typeof i=="boolean")r(s,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},He=t=>{let e=tt(),n=e.stackSave();try{let r=e.stackAlloc(8);e._OrtGetLastError(r,r+4);let a=e.HEAP32[r/4],i=e.HEAPU32[r/4+1],s=i?e.UTF8ToString(i):"";throw new Error(`${t} ERROR_CODE: ${a}, ERROR_MESSAGE: ${s}`)}finally{e.stackRestore(n)}}}),Hc,$_=X(()=>{Gr(),Ys(),Hc=t=>{let e=tt(),n=0,r=[],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=et(t.tag,r)),n=e._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,i),n===0&&He("Can't create run options."),t?.extra!==void 0&&ja(t.extra,"",new WeakSet,(s,o)=>{let l=et(s,r),d=et(o,r);e._OrtAddRunConfigEntry(n,l,d)!==0&&He(`Can't set a run config entry: ${s} - ${o}.`)}),[n,r]}catch(i){throw n!==0&&e._OrtReleaseRunOptions(n),r.forEach(s=>e._free(s)),i}}}),tl,nl,rl,al,qc,x_=X(()=>{Gr(),Ys(),tl=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}`)}},nl=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},rl=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(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(t.enableMemPattern=!1)},al=(t,e,n)=>{for(let r of e){let a=typeof r=="string"?r:r.name;switch(a){case"webnn":if(a="WEBNN",typeof r!="string"){let s=r;if(s?.deviceType){let o=et("deviceType",n),l=et(s.deviceType,n);tt()._OrtAddSessionConfigEntry(t,o,l)!==0&&He(`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=et("numThreads",n),d=et(o.toString(),n);tt()._OrtAddSessionConfigEntry(t,l,d)!==0&&He(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s?.powerPreference){let o=et("powerPreference",n),l=et(s.powerPreference,n);tt()._OrtAddSessionConfigEntry(t,o,l)!==0&&He(`Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.`)}}break;case"webgpu":if(a="JS",typeof r!="string"){let s=r;if(s?.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let o=et("preferredLayout",n),l=et(s.preferredLayout,n);tt()._OrtAddSessionConfigEntry(t,o,l)!==0&&He(`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=et(a,n);tt()._OrtAppendExecutionProvider(t,i)!==0&&He(`Can't append execution provider: ${a}.`)}},qc=t=>{let e=tt(),n=0,r=[],a=t||{};rl(a);try{let i=tl(a.graphOptimizationLevel??"all"),s=nl(a.executionMode??"sequential"),o=typeof a.logId=="string"?et(a.logId,r):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"?et(a.optimizedModelFilePath,r):0;if(n=e._OrtCreateSessionOptions(i,!!a.enableCpuMemArena,!!a.enableMemPattern,s,!!a.enableProfiling,0,o,l,d,c),n===0&&He("Can't create session options."),a.executionProviders&&al(n,a.executionProviders,r),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 f=et(u,r);e._OrtAddFreeDimensionOverride(n,f,h)!==0&&He(`Can't set a free dimension override: ${u} - ${h}.`)}return a.extra!==void 0&&ja(a.extra,"",new WeakSet,(u,h)=>{let f=et(u,r),g=et(h,r);e._OrtAddSessionConfigEntry(n,f,g)!==0&&He(`Can't set a session config entry: ${u} - ${h}.`)}),[n,r]}catch(i){throw n!==0&&e._OrtReleaseSessionOptions(n),r.forEach(s=>e._free(s)),i}}}),bs,Yt,Ka,Xs,Ya,Qs,vs,Ye=X(()=>{bs=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}`)}},Yt=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}`)}},Ka=t=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][t],Xs=t=>{switch(t){case"float16":return 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}`)}},Ya=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}`)}},Qs=t=>t==="float32"||t==="int32"||t==="int64"||t==="bool"||t==="float16"||t==="uint32",vs=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}`)}}}),Xa,jc=X(()=>{Xa=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 n=(void 0)(t),r=[];for await(let a of n)r.push(a);return new Uint8Array(Buffer.concat(r))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let n=e.headers.get("Content-Length"),r=n?parseInt(n,10):0;if(r<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(r)}catch(o){if(o instanceof RangeError){let l=Math.ceil(r/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,r)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),il,sl,ol,ll,Kc,ul,it,In=X(()=>{Ye(),il=["V","I","W","E","F"],sl=(t,e)=>{console.log(`[${il[t]},${new Date().toISOString()}]${e}`)},Kc=(t,e)=>{ol=t,ll=e},ul=(t,e)=>{let n=Ya(t),r=Ya(ol);n>=r&&sl(n,typeof e=="function"?e():e)},it=(...t)=>{ll&&ul(...t)}}),Yc,S_=X(()=>{Ye(),Yc=(t,e)=>new(Xs(e))(t)}),Zs=X(()=>{}),$r,dl,Fi,$s,cl,Xc,E_=X(()=>{In(),Zs(),$r=t=>Math.ceil(t/16)*16,dl=1,Fi=()=>dl++,$s=async(t,e,n,r)=>{let a=$r(n),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(r){let l=r();return l.set(new Uint8Array(o,0,n)),l}else return new Uint8Array(o.slice(0,n))}finally{i.destroy()}},cl=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}upload(t,e){let n=e.buffer,r=e.byteOffset,a=e.byteLength,i=$r(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(n,r,a)),o.unmap();let d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(o,0,s.gpuData.buffer,0,i),it("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(o)}memcpy(t,e){let n=this.storageCache.get(t);if(!n)throw new Error("source gpu data for memcpy does not exist");let r=this.storageCache.get(e);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");let a=$r(n.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,a)}registerExternalBuffer(t,e,n){let r;if(n){if(r=this.externalBuffers.get(n),r===void 0)throw new Error("previous buffer is not registered");if(t===n)return it("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${r}, buffer is the same, skip.`),r;this.externalBuffers.delete(n)}else r=Fi();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:t},originalSize:e}),this.externalBuffers.set(t,r),it("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${r}, registered.`),r}unregisterExternalBuffer(t){let e=this.externalBuffers.get(t);e!==void 0&&(this.storageCache.delete(e),this.externalBuffers.delete(t),it("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(t,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=$r(t),r,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(n);l||(l=[],o.set(n,l)),l.length>0?r=l.pop():r=this.backend.device.createBuffer({size:n,usage:e})}else r=this.backend.device.createBuffer({size:n,usage:e});let s={id:Fi(),type:0,buffer:r};return this.storageCache.set(s.id,{gpuData:s,originalSize:t}),it("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 it("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 n=this.storageCache.get(t);if(!n)throw new Error("data does not exist");await $s(this.backend,n.gpuData.buffer,n.originalSize,e)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();this.buffersForUploadingPending=[];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=[]}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.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map}},Xc=(...t)=>new cl(...t)}),pl,qe,ot=X(()=>{pl=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 pl(t)}),hl,Xn,J,Qa,Qc,Js,eo,Ie=X(()=>{hl=class{static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}},Xn=class{static calcShape(t,e,n=!1){let r=t.length,a=e.length;if(r===0)return e;if(a===0)return t;let i=Math.max(t.length,e.length),s=new Array(i);if(n){if(r<2||a<2)return;let o=hl.calcMatMulShape([t[r-2],t[r-1]],[e[a-2],e[a-1]]);if(o===void 0)return;[s[i-2],s[i-1]]=o}for(let o=n?3:1;o<=i;o++){let l=r-o<0?1:t[r-o],d=a-o<0?1:e[a-o];if(l!==d&&l>1&&d>1)return;s[i-o]=Math.max(l,d)}return s}static isValidBroadcast(t,e){let n=t.length,r=e.length;if(n>r)return!1;for(let a=1;a<=n;a++)if(t[n-a]!==1&&t[n-a]!==e[r-a])return!1;return!0}},J=class Fa{static size(e){return Fa.getSizeFromDimensionRange(e,0,e.length)}static sizeFromDimension(e,n){if(n<0||n>e.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return Fa.getSizeFromDimensionRange(e,n,e.length)}static sizeToDimension(e,n){if(n<0||n>e.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${e.length} dimensions.`);return Fa.getSizeFromDimensionRange(e,0,n)}static getSizeFromDimensionRange(e,n,r){let a=1;for(let i=n;i=0;--a)r[a]=r[a+1]*e[a+1];return r}static normalizeAxis(e,n){if(e<-n&&e>=n)throw new Error("unsupported axis for this operation.");return e<0?e+n:e}static normalizeAxes(e,n){return e.map(r=>this.normalizeAxis(r,n??e.length))}static sortBasedOnPerm(e,n){return n?n.map(r=>e[r]):e.slice().reverse()}static padShape(e,n){let r=e.length;return e.map((a,i)=>a+n[i]+n[i+r])}static areEqual(e,n){return e.length!==n.length?!1:e.every((r,a)=>r===n[a])}},Qa=class Mr{static adjustPoolAttributes(e,n,r,a,i,s){if(!e&&r.length!==n.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=r.length?r.push(n[o+2]):r[o]=n[o+2];for(let o=0;o=r[o]||s[o+r.length]>=r[o])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,n,r,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(n.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(),Ie(),fl=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}`)}},At=(t,e=1)=>{let n=Aa(t,e);return typeof n=="string"?n:n[0]},nn=(t,e=1)=>{let n=Aa(t,e);return typeof n=="string"?n:n[1]},ie=t=>t.length===0?[]:[{type:"uint32",data:t},{type:"uint32",data:J.computeStrides(t)}],$t=t=>t%4===0?4:t%2===0?2:1,vt=(t="f32",e,n="0")=>!e||e===1?`${t}(${n})`:`vec${e}<${t}>(${n})`,rn=(t,e,n)=>t==="f32"?n:e===1?`f32(${n})`:`vec${e}f(${n})`,Qt=(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,xe=(t,e,n)=>t.startsWith("uniforms.")&&n>4?typeof e=="string"?`${t}[(${e}) / 4][(${e}) % 4]`:`${t}[${Math.floor(e/4)}][${e%4}]`:n>1?`${t}[${e}]`:t,Ma=(t,e,n,r,a)=>{let i=typeof n=="number",s=i?n:n.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},f=W=>typeof W=="string"?W:`${W}u`,g={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},w=i?"uniforms.":"",b=`${w}${t}_shape`,y=`${w}${t}_strides`,$="";for(let W=0;W ${h.indices} { - var indices: ${h.indices}; - var current = offset; - ${$} - return indices; - }`,S=W=>(g.offsetToIndices=!0,s<2?W:`o2i_${t}(${W})`),T=[];if(s>=2)for(let W=s-1;W>=0;W--)T.push(`${xe(y,W,s)} * (indices[${W}])`);let A=s<2?"":` - fn i2o_${t}(indices: ${h.indices}) -> u32 { - return ${T.join("+")}; - }`,P=W=>(g.indicesToOffset=!0,s<2?W:`i2o_${t}(${W})`),N=(...W)=>s===0?"0u":`${h.indices}(${W.map(f).join(",")})`,V=(W,oe)=>s<2?`${W}`:`${xe(W,oe,s)}`,j=(W,oe,$e)=>s<2?`${W}=${$e};`:`${xe(W,oe,s)}=${$e};`,M={},G=(W,oe)=>{g.broadcastedIndicesToOffset=!0;let $e=`${oe.name}broadcastedIndicesTo${t}Offset`;if($e in M)return`${$e}(${W})`;let Fe=[];for(let Pe=s-1;Pe>=0;Pe--){let We=oe.indicesGet("outputIndices",Pe+oe.rank-s);Fe.push(`${V(y,Pe)} * (${We} % ${V(b,Pe)})`)}return M[$e]=`fn ${$e}(outputIndices: ${oe.type.indices}) -> u32 { - return ${Fe.length>0?Fe.join("+"):"0u"}; - }`,`${$e}(${W})`},O=(W,oe)=>(()=>{if(h.storage===h.value)return`${t}[${W}]=${oe};`;if(h.storage==="vec2"&&h.value==="i32")return`${t}[${W}]=vec2(u32(${oe}), select(0u, 0xFFFFFFFFu, ${oe} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${t}[${W}]=vec2(u32(${oe}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${t}[${W}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${oe}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),R=W=>(()=>{if(h.storage===h.value)return`${t}[${W}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${t}[${W}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${t}[${W}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${t}[${W}] & 0xFFu), bool(${t}[${W}] & 0xFF00u), bool(${t}[${W}] & 0xFF0000u), bool(${t}[${W}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),H=s<2?"":` - fn get_${t}ByIndices(indices: ${h.indices}) -> ${c} { - return ${R(`i2o_${t}(indices)`)}; - }`,te=s<2?"":(()=>{let W=o.map($e=>`d${$e}: u32`).join(", "),oe=o.map($e=>`d${$e}`).join(", ");return` - fn get_${t}(${W}) -> ${c} { - return get_${t}ByIndices(${N(oe)}); - }`})(),ae=(...W)=>{if(W.length!==s)throw new Error(`indices length must be ${s}`);let oe=W.map(f).join(",");return s===0?R("0u"):s===1?R(oe[0]):(g.get=!0,g.getByIndices=!0,g.indicesToOffset=!0,`get_${t}(${oe})`)},re=W=>s<2?R(W):(g.getByIndices=!0,g.indicesToOffset=!0,`get_${t}ByIndices(${W})`),Y=s<2?"":` - fn set_${t}ByIndices(indices: ${h.indices}, value: ${c}) { - ${O(`i2o_${t}(indices)`,"value")} - }`,ue=s<2?"":(()=>{let W=o.map($e=>`d${$e}: u32`).join(", "),oe=o.map($e=>`d${$e}`).join(", ");return` - fn set_${t}(${W}, value: ${c}) { - set_${t}ByIndices(${N(oe)}, value); - }`})();return{impl:()=>{let W=[],oe=!1;return g.offsetToIndices&&(W.push(k),oe=!0),g.indicesToOffset&&(W.push(A),oe=!0),g.broadcastedIndicesToOffset&&(Object.values(M).forEach($e=>W.push($e)),oe=!0),g.set&&(W.push(ue),oe=!0),g.setByIndices&&(W.push(Y),oe=!0),g.get&&(W.push(te),oe=!0),g.getByIndices&&(W.push(H),oe=!0),!i&&oe&&W.unshift(`const ${b} = ${h.indices}(${n.join(",")});`,`const ${y} = ${h.indices}(${J.computeStrides(n).join(",")});`),W.join(` -`)},type:h,offsetToIndices:S,indicesToOffset:P,broadcastedIndicesToOffset:G,indices:N,indicesGet:V,indicesSet:j,set:(...W)=>{if(W.length!==s+1)throw new Error(`indices length must be ${s}`);let oe=W[s];if(typeof oe!="string")throw new Error("value must be string");let $e=W.slice(0,s).map(f).join(",");return s===0?O("0u",oe):s===1?O($e[0],oe):(g.set=!0,g.setByIndices=!0,g.indicesToOffset=!0,`set_${t}(${$e}, ${oe})`)},setByOffset:O,setByIndices:(W,oe)=>s<2?O(W,oe):(g.setByIndices=!0,g.indicesToOffset=!0,`set_${t}ByIndices(${W}, ${oe});`),get:ae,getByOffset:R,getByIndices:re,usage:r,name:t,strides:y,shape:b,rank:s}},Q=(t,e,n,r=1)=>Ma(t,e,n,"input",r),ve=(t,e,n,r=1)=>Ma(t,e,n,"output",r),to=(t,e,n,r=1)=>Ma(t,e,n,"internal",r),ml=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=fl){let e=typeof t=="number"?t:t[0],n=typeof t=="number"?1:t[1],r=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*n*r}u + local_idx;`;return`@compute @workgroup_size(${e}, ${n}, ${r}) - 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 n=t.usage==="input"?"read":"read_write",r=t.type.storage;return`@group(0) @binding(${e}) var ${t.name}: array<${r}>;`}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,n=1){return this.uniforms.push({name:t,type:e,length:n}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:e,type:n,length:r}of this.uniforms)if(r&&r>4)t.push(`${e}:array, ${Math.ceil(r/4)}>`);else{let a=r==null||r===1?n:`vec${r}<${n}>`;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(` -`)}},Zc=t=>new ml(t),Nr=(t,e)=>{let n=t.length,r=[];for(let a=0;a1&&s===1&&r.unshift(i)}return r},st=t=>!0}),gl,Li,_l,wl,_n,Jc,ep,Hr=X(()=>{Ie(),ot(),Ce(),gl=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},Li=(t,e)=>e&&e.length!==t?[...new Array(t).keys()].reverse():e,_l=(t,e)=>J.sortBasedOnPerm(t,Li(t.length,e)),wl=(t,e,n,r)=>{let a=[];a.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} { - var a: ${n.type.indices};`);for(let i=0;i{let n=t.dataType,r=t.dims.length,a=Li(r,e),i=st(r),s=_l(t.dims,a),o=i?s.length:s,l=i?r:t.dims,d=ve("output",n,o),c=Q("a",n,l),u=h=>` - ${h.registerUniform("output_size","u32").declareVariables(c,d)} - - ${wl(a,r,c,d)} - - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${d.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${d.setByOffset("global_idx",c.getByIndices("aIndices"))} - }`;return{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:i?["rank"]:["dims"]},getRunData:h=>{let f=J.size(s);return{outputs:[{dims:s,dataType:h[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:i?[{type:"uint32",data:f},...ie(h[0].dims),...ie(s)]:[{type:"uint32",data:f}]}},getShaderSource:u}},Jc=(t,e)=>{gl(t.inputs),t.compute(_n(t.inputs[0],e.perm))},ep=t=>qe({perm:t.perm})}),yl,bl,vl,$l,xl,Sl,El,kl,Cl,Tl,Rt,tp,np,rp,ap,ip,sp,op,lp,up,dp,k_=X(()=>{Ie(),Ce(),no(),Hr(),yl={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"},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",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},vl={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},$l={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},xl=(t,e)=>{let n=[];for(let r=e-t;r{let n=[],r=t.length;for(let i=0;it[i]);return[n,a]},El=(t,e)=>{let n=t.length+e.length,r=[],a=0;for(let i=0;i{for(let n=0;n{let n=[];if(!kl(t,e)){for(let r=0;rn.push(r))}return n},Tl=(t,e,n,r,a,i,s)=>{let o=n[0].dims,l=J.size(i),d=J.size(s),c=Q("_A",n[0].dataType,o),u=ve("output",a,i),h=32,f=` - var aBestValues : array<${u.type.storage}, ${h}>; - `;return{name:t,shaderCache:e,getShaderSource:g=>` - ${g.registerUniform("reduceSize","u32").declareVariables(c,u)} - ${f} - 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 = ${u.type.storage}(${vl[r]}); - let Length = uniforms.reduceSize; - for (var k = local_idx; k < Length; k = k + ${h}) { - let candidate = ${u.type.storage}(${c.getByOffset("offset + k")}); - bestValue = ${yl[r]}; - } - 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 = ${bl[r]}; - aBestValues[local_idx] = bestValue; - } - reduceSize = interval; - workgroupBarrier(); - } - - if (local_idx == 0u) { - ${u.setByOffset("outputIndex",`${r==="mean"?`bestValue / ${u.type.storage}(uniforms.reduceSize)`:`${$l[r]}`}`)}; - } - }`,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:l},programUniforms:[{type:"uint32",data:d}]})}},Rt=(t,e,n,r)=>{let a=t.inputs.length===1?n:xs(t.inputs,n),i=a.axes;i.length===0&&!a.noopWithEmptyAxes&&(i=t.inputs[0].dims.map((f,g)=>g));let s=J.normalizeAxes(i,t.inputs[0].dims.length),o=s,l=t.inputs[0],d=Cl(o,t.inputs[0].dims.length);d.length>0&&(l=t.compute(_n(t.inputs[0],d),{inputs:[0],outputs:[-1]})[0],o=xl(o.length,l.dims.length));let[c,u]=Sl(l.dims,o),h=c;a.keepDims&&(h=El(c,s)),t.compute(Tl(e,{hint:a.cacheKey,inputDependencies:["type"]},[l],r,t.inputs[0].dataType,h,u),{inputs:[l]})},tp=(t,e)=>{Rt(t,"ReduceMeanShared",e,"mean")},np=(t,e)=>{Rt(t,"ReduceL1Shared",e,"l1")},rp=(t,e)=>{Rt(t,"ReduceL2Shared",e,"l2")},ap=(t,e)=>{Rt(t,"ReduceLogSumExpShared",e,"logSumExp")},ip=(t,e)=>{Rt(t,"ReduceMaxShared",e,"max")},sp=(t,e)=>{Rt(t,"ReduceMinShared",e,"min")},op=(t,e)=>{Rt(t,"ReduceProdShared",e,"prod")},lp=(t,e)=>{Rt(t,"ReduceSumShared",e,"sum")},up=(t,e)=>{Rt(t,"ReduceSumSquareShared",e,"sumSquare")},dp=(t,e)=>{Rt(t,"ReduceLogSumShared",e,"logSum")}}),Bt,Il,Za,xs,Pt,Al,Ml,Ol,zl,Rl,Bl,Pl,Dl,Nl,Fl,Dt,cp,pp,hp,fp,mp,gp,_p,wp,yp,bp,no=X(()=>{Ie(),ot(),Ce(),k_(),Bt=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.")},Il=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],Za=(t,e,n,r,a,i,s=!1,o=!1)=>{let l=[],d=n[0].dims,c=d.length,u=J.normalizeAxes(a,c),h=!o&&u.length===0;d.forEach((w,b)=>{h||u.indexOf(b)>=0?s&&l.push(1):l.push(w)});let f=l.length,g=J.size(l);return{name:t,shaderCache:e,getShaderSource:w=>{let b=[],y=Q("_A",n[0].dataType,c),$=ve("output",i,f),k=r(y,$,u),S=k[2];for(let T=0,A=0;T=0?(s&&A++,S=`for(var j${T}: u32 = 0; j${T} < ${d[T]}; j${T}++) { - ${k[2].includes("last_index")?`let last_index = j${T};`:""} - ${y.indicesSet("input_indices",T,`j${T}`)} - ${S} - }`):(b.push(`${y.indicesSet("input_indices",T,$.indicesGet("output_indices",A))};`),A++);return` - - ${w.registerUniform("output_size","u32").declareVariables(y,$)} - - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${y.type.indices}; - let output_indices = ${$.offsetToIndices("global_idx")}; - - ${b.join(` -`)} - ${k[0]} // init ops for reduce max/min - ${k[1]} - ${S} - ${k[3]} - ${k.length===4?$.setByOffset("global_idx","value"):k.slice(4).join(` -`)} - }`},getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:"uint32",data:g},...ie(d),...ie(l)]})}},xs=(t,e)=>{let n=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(r=>n.push(Number(r))),qe({axes:n,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},Pt=(t,e,n,r)=>{let a=t.inputs,i=a.length===1?n:xs(a,n);t.compute(Za(e,{hint:i.cacheKey,inputDependencies:["rank"]},[a[0]],i.noopWithEmptyAxes&&i.axes.length===0?Il:r,i.axes,a[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},Al=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceLogSum",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},Ml=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceL1",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},Ol=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceL2",e,(n,r)=>[`var t = ${r.type.value}(0); var value = ${r.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},zl=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceLogSumExp",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Rl=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceMax",e,(n,r,a)=>{let i=[];for(let s=0;s=0||a.length===0)&&i.push(n.indicesSet("input_indices",s,0));return[`${i.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Bl=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceMean",e,(n,r,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(${n.getByIndices("input_indices")});`,`let value = ${r.type.value}(sum / ${i});`]})},Pl=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceMin",e,(n,r,a)=>{let i=[];for(let s=0;s=0||a.length===0)&&i.push(`input_indices[${s}] = 0;`);return[`${i.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Dl=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceProd",e,(n,r)=>[`var value = ${r.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Nl=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceSum",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Fl=(t,e)=>{Bt(t.inputs),Pt(t,"ReduceSumSquare",e,(n,r)=>[`var t = ${r.type.value}(0); var value = ${r.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},Dt=(t,e,n)=>{if(e.length===0)return n;let r=1,a=1;for(let i=0;i1024},cp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Bl(t,e):tp(t,e)},pp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ml(t,e):np(t,e)},hp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ol(t,e):rp(t,e)},fp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?zl(t,e):ap(t,e)},mp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Rl(t,e):ip(t,e)},gp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Pl(t,e):sp(t,e)},_p=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Dl(t,e):op(t,e)},wp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Nl(t,e):lp(t,e)},yp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Fl(t,e):up(t,e)},bp=(t,e)=>{Dt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Al(t,e):dp(t,e)}}),Ui,vp,$p,Ss,C_=X(()=>{Ye(),ot(),no(),Ui=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.")},vp=(t,e)=>{Ui(t.inputs);let n=(r,a,i)=>{let s=[];for(let o=0;o=0||i.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` -`)}`,`var value = ${r.getByIndices("input_indices")}; -var best_index : i32 = 0;`,`if (${r.getByIndices("input_indices")} ${e.selectLastIndex>0?"<=":"<"} value) { - value = ${r.getByIndices("input_indices")}; - best_index = i32(last_index); - }`,"",a.setByOffset("global_idx","best_index")]};t.compute(Za("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],n,[e.axis],7,e.keepDims),{inputs:[0]})},$p=(t,e)=>{Ui(t.inputs);let n=(r,a,i)=>{let s=[];for(let o=0;o=0||i.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` -`)}`,`var value = ${r.getByIndices("input_indices")}; -var best_index : i32 = 0;`,`if (${r.getByIndices("input_indices")} ${e.selectLastIndex>0?">=":">"} value) { - value = ${r.getByIndices("input_indices")}; - best_index = i32(last_index); - }`,"",a.setByOffset("global_idx","best_index")]};t.compute(Za("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],n,[e.axis],7,e.keepDims),{inputs:[0]})},Ss=t=>qe(t)}),Ll,Ul,Wl,Vl,Ja,Gl,xp,Sp=X(()=>{Ye(),Zs(),Ce(),Ll=(t,e)=>{let n=t[0],r=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(n.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=n.dims[0],d=n.dims[1],c=n.dims[2];if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(r.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(r.dims[0]!==c)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(a.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=a.dims[0]/3,h=u,f=h;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let k of e.qkvHiddenSizes)if(k%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=e.qkvHiddenSizes[0],h=e.qkvHiddenSizes[1],f=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+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let w=0;if(s){if(h!==f)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||(w=s.dims[3])}let b=g+w,y=-1,$=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:w,kvSequenceLength:g,totalSequenceLength:b,maxSequenceLength:y,inputHiddenSize:c,hiddenSize:u,vHiddenSize:f,headSize:Math.floor(u/e.numHeads),vHeadSize:Math.floor(f/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:$,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ul=(t,e,n,r)=>{let a=$t(r),i=64,s=r/a;s{let h=ve("x",e.dataType,e.dims,a),f="thread_max_vector";a===2?f="max(thread_max_vector.x, thread_max_vector.y)":a===4&&(f="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let g=nn(e.dataType),w=[{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(w).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 = ${vt("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(${rn(g,a,"x[offset + i]")}, thread_max_vector); - } - wgMax[local_idx] = ${f}; - workgroupBarrier(); - - var maxValue = -3.402823e+38f; - for (var i = 0u; i < ${i}; i++) { - maxValue = max(wgMax[i], maxValue); - } - - var sumVector = ${vt("f32",a,"0")}; - for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { - sumVector += exp(${rn(g,a,"x[offset + i]")} - maxValue); - } - wgSum[local_idx] = ${Qt("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] = ${vt("f32",a,"uniforms.d_inv")}; - } - } else { - for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { - let f32input = ${rn(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:n},programUniforms:l})},{inputs:[e],outputs:[]})},Wl=(t,e,n,r,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=$t(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=Yt(e.dataType),f=[{type:"uint32",data:a.sequenceLength},{type:"uint32",data:d},{type:"uint32",data:a.totalSequenceLength},{type:"uint32",data:a.kvSequenceLength},{type:h,data:o}],g=[e,n],w=y=>{let $=Q("q",e.dataType,e.dims,l),k=Q("key",n.dataType,n.dims,l),S=ve("output",e.dataType,s),T=At(e.dataType),A=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:T}];return` - const beta: ${T} = 1.0; - const TILE_SIZE = ${c}u; - - var tileQ: array<${$.type.storage}, ${c*c}>; - var tileK: array<${$.type.storage}, ${c*c}>; - ${y.registerUniforms(A).declareVariables($,k,S)} - ${y.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 = ${vt(T,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:f}),getShaderSource:w},{inputs:g,outputs:[-1]})[0];return Ul(t,b,a.batchSize*a.numHeads*a.sequenceLength,a.totalSequenceLength),b},Vl=(t,e,n,r)=>{let a=[r.batchSize,r.sequenceLength,r.vHiddenSize],i=12,s={x:Math.ceil(r.vHeadSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},o=[{type:"uint32",data:r.sequenceLength},{type:"uint32",data:r.totalSequenceLength},{type:"uint32",data:r.vHeadSize},{type:"uint32",data:r.numHeads},{type:"uint32",data:r.vHiddenSize}],l=d=>{let c=Q("probs",e.dataType,e.dims),u=Q("v",n.dataType,n.dims),h=ve("output",e.dataType,a),f=[{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(f).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,n],outputs:[0]})[0]},Ja=(t,e,n,r,a,i,s,o,l,d,c)=>{let u=Wl(t,e,n,l,d,c);Vl(t,u,r,d)},Gl=(t,e)=>{let n=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],r=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:"uint32",data:r},{type:"uint32",data:a},{type:"uint32",data:i},{type:"uint32",data:e.numHeads},{type:"uint32",data:e.headSize},{type:"uint32",data:e.hiddenSize},{type:"uint32",data:e.hiddenSize+e.hiddenSize+e.vHiddenSize}],c=u=>{let h=ve("output_q",l[0].dataType,n),f=ve("output_k",l[0].dataType,n),g=ve("output_v",l[0].dataType,n),w=Q("input",l[0].dataType,l[0].dims),b=Q("weight",l[1].dataType,l[1].dims),y=Q("bias",l[2].dataType,l[2].dims),$=w.type.storage,k=[{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<${$}, ${s*s}>; - var tileWeightQ: array<${$}, ${s*s}>; - var tileWeightK: array<${$}, ${s*s}>; - var tileWeightV: array<${$}, ${s*s}>; - ${u.registerUniforms(k).declareVariables(w,b,y,h,f,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 = ${$}(0); - var valueK = ${$}(0); - var valueV = ${$}(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:n,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:t.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:d}),getShaderSource:c},{inputs:l,outputs:[-1,-1,-1]})},xp=(t,e)=>{let n=Ll(t.inputs,e),[r,a,i]=Gl(t,n);return Ja(t,r,a,i,t.inputs[4],void 0,void 0,void 0,t.inputs[5],n,e)}}),Hl,ql,jl,Ep,T_=X(()=>{Vt(),Ie(),ot(),Ce(),Hl=(t,e)=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(r,a,i)=>{let s=a.length;if(s!==r.length)throw new Error(`${i}: num dimensions != ${s}`);a.forEach((o,l)=>{if(o!==r[l])throw new Error(`${i}: dim[${l}] do not match`)})};if(t[0].dims.length>1){let r=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);n(t[1].dims,r,"Invalid input scale"),n(t[2].dims,r,"Invalid input B"),n(t[3].dims,r,"Invalid input mean"),n(t[4].dims,r,"Invalid input var")}else n(t[1].dims,[1],"Invalid input scale"),n(t[2].dims,[1],"Invalid input B"),n(t[3].dims,[1],"Invalid input mean"),n(t[4].dims,[1],"Invalid input var")},ql=(t,e)=>{let{epsilon:n,spatial:r,format:a}=e,i=t[0].dims,s=r?$t(i[i.length-1]):1,o=a==="NHWC"&&i.length>1?s:1,l=J.size(i)/s,d=st(i.length)&&r,c=d?i.length:i,u=Q("x",t[0].dataType,t[0].dims,s),h=Q("scale",t[1].dataType,t[1].dims,o),f=Q("bias",t[2].dataType,t[2].dims,o),g=Q("inputMean",t[3].dataType,t[3].dims,o),w=Q("inputVar",t[4].dataType,t[4].dims,o),b=ve("y",t[0].dataType,c,s),y=()=>{let k="";if(r)k=`let cOffset = ${i.length===1?"0u":a==="NHWC"?`outputIndices[${i.length-1}] / ${s}`:"outputIndices[1]"};`;else if(a==="NCHW")k=` - ${b.indicesSet("outputIndices","0","0")} - let cOffset = ${b.indicesToOffset("outputIndices")};`;else{k=`var cIndices = ${h.type.indices}(0); - cIndices[0] = outputIndices[${i.length-1}];`;for(let S=1;S` - const epsilon = ${n}; - ${k.registerUniform("outputSize","u32").declareVariables(u,h,f,g,w,b)} - ${k.mainStart()} - ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${b.offsetToIndices(`global_idx * ${s}`)}; - ${y()} - let scale = ${h.getByOffset("cOffset")}; - let bias = ${f.getByOffset("cOffset")}; - let inputMean = ${g.getByOffset("cOffset")}; - let inputVar = ${w.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}_${r}_${s}`,inputDependencies:d?["rank","type","type","type","type"]:void 0},getShaderSource:$,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d?[{type:"uint32",data:l},...ie(i)]:[{type:"uint32",data:l}]})}},jl=t=>qe(t),Ep=(t,e)=>{let{inputs:n,outputCount:r}=t,a=jl({...e,outputCount:r});if(Ne.webgpu.validateInputContent&&Hl(n,a),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(ql(n,a))}}),Kl,Yl,kp,I_=X(()=>{Ie(),Ce(),Kl=t=>{if(t[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(t[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(t[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(t[0].dims[2]!==t[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Yl=t=>{let e=t[0].dims,n=t[0].dims[2],r=J.size(e)/4,a=t[0].dataType,i=Q("input",a,e,4),s=Q("bias",a,[n],4),o=Q("residual",a,e,4),l=ve("output",a,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:d=>` - const channels = ${n}u / 4; - ${d.declareVariables(i,s,o,l)} - - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes(r)} - let value = ${i.getByOffset("global_idx")} - + ${s.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")}; - ${l.setByOffset("global_idx","value")} - }`}},kp=t=>{Kl(t.inputs),t.compute(Yl(t.inputs))}}),Xl,Be,Cp,Tp,Ip,Ap,Mp,Op,zp,Rp,Bp,Ql,Pp,Dp,Np,Fp,La,Lp,Ua,Up,Wp,Vp,Gp,Hp,qp,jp,Kp,Yp,Xp,Qp,Zp,Jp,eh,th,nh,rh,ah=X(()=>{Ye(),Ie(),ot(),Ce(),Xl=(t,e,n,r,a,i)=>{let s=Math.ceil(e/4),o="";typeof a=="string"?o=`${a}(a)`:o=a("a");let l=Q("inputData",n,[s],4),d=ve("outputData",r,[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)} - }`},Be=(t,e,n,r,a,i=t.dataType)=>({name:e,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:s=>Xl(s,J.size(t.dims),t.dataType,i,n,r),getRunData:s=>({outputs:[{dims:t.dims,dataType:i}],dispatchGroup:{x:Math.ceil(J.size(s[0].dims)/64/4)},programUniforms:[{type:"uint32",data:Math.ceil(J.size(t.dims)/4)}]})}),Cp=t=>{t.compute(Be(t.inputs[0],"Abs","abs"))},Tp=t=>{t.compute(Be(t.inputs[0],"Acos","acos"))},Ip=t=>{t.compute(Be(t.inputs[0],"Acosh","acosh"))},Ap=t=>{t.compute(Be(t.inputs[0],"Asin","asin"))},Mp=t=>{t.compute(Be(t.inputs[0],"Asinh","asinh"))},Op=t=>{t.compute(Be(t.inputs[0],"Atan","atan"))},zp=t=>{t.compute(Be(t.inputs[0],"Atanh","atanh"))},Rp=t=>qe(t),Bp=(t,e)=>{let n;switch(e.to){case 10:n="vec4";break;case 1:n="vec4";break;case 12:n="vec4";break;case 6:n="vec4";break;case 9:n="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${e.to}`)}t.compute(Be(t.inputs[0],"Cast",n,void 0,e.cacheKey,e.to))},Ql=t=>{let e=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:Js,n=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:eo;return qe({min:e,max:n})},Pp=(t,e)=>{let n=t.inputs.length===1?e:Ql(t.inputs),r=nn(t.inputs[0].dataType);t.compute(Be(t.inputs[0],"Clip",a=>`clamp(${a}, clip_min_, clip_max_)`,` - const clip_min_: vec4<${r}> = vec4(${r}(${n.min})); - const clip_max_: vec4<${r}> = vec4(${r}(${n.max})); -`,n.cacheKey),{inputs:[0]})},Dp=t=>{t.compute(Be(t.inputs[0],"Ceil","ceil"))},Np=t=>{t.compute(Be(t.inputs[0],"Cos","cos"))},Fp=t=>{t.compute(Be(t.inputs[0],"Cosh","cosh"))},La=t=>qe(t),Lp=(t,e)=>{let n=nn(t.inputs[0].dataType);t.compute(Be(t.inputs[0],"Elu",r=>`elu_vf32(${r})`,` - const elu_alpha_ = ${n}(${e.alpha}); - - fn elu_f32(a: ${n}) -> ${n} { - return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); - } - - fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> { - return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); - }`,e.cacheKey))},Ua=(t,e="f32")=>` -const r0: ${e} = 0.3275911; -const r1: ${e} = 0.254829592; -const r2: ${e} = -0.284496736; -const r3: ${e} = 1.421413741; -const r4: ${e} = -1.453152027; -const r5: ${e} = 1.061405429; - -fn erf_vf32(v: ${t}) -> ${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)); -}`,Up=t=>{let e=nn(t.inputs[0].dataType);t.compute(Be(t.inputs[0],"Erf",n=>`erf_vf32(${n})`,Ua(`vec4<${e}>`,e)))},Wp=t=>{t.compute(Be(t.inputs[0],"Exp","exp"))},Vp=t=>{t.compute(Be(t.inputs[0],"Floor","floor"))},Gp=t=>{let e=nn(t.inputs[0].dataType);t.compute(Be(t.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,Ua(`vec4<${e}>`,e)))},Hp=(t,e)=>{let n=nn(t.inputs[0].dataType);t.compute(Be(t.inputs[0],"LeakyRelu",r=>`select(leaky_relu_alpha_ * ${r}, ${r}, ${r} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${e.alpha});`,e.cacheKey))},qp=t=>{t.compute(Be(t.inputs[0],"Not",e=>`!${e}`))},jp=t=>{t.compute(Be(t.inputs[0],"Neg",e=>`-${e}`))},Kp=t=>{t.compute(Be(t.inputs[0],"Reciprocal",e=>`1.0/${e}`))},Yp=t=>{let e=nn(t.inputs[0].dataType);t.compute(Be(t.inputs[0],"Relu",n=>`select(vec4<${e}>(0.0), ${n}, ${n} > vec4<${e}>(0.0))`))},Xp=t=>{t.compute(Be(t.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},Qp=t=>{t.compute(Be(t.inputs[0],"Sin","sin"))},Zp=t=>{t.compute(Be(t.inputs[0],"Sinh","sinh"))},Jp=t=>{t.compute(Be(t.inputs[0],"Sqrt","sqrt"))},eh=t=>{t.compute(Be(t.inputs[0],"Tan","tan"))},th=t=>{t.compute(Be(t.inputs[0],"Tanh","tanh"))},nh=(t,e)=>{let n=nn(t.inputs[0].dataType);return t.compute(Be(t.inputs[0],"ThresholdedRelu",r=>`select(vec4<${n}>(0.0), ${r}, ${r} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${e.alpha});`,e.cacheKey)),0},rh=t=>{t.compute(Be(t.inputs[0],"Log","log"))}}),Zl,Jl,ih,A_=X(()=>{Ie(),Ce(),ah(),Zl=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")},Jl=t=>{let e=t[0].dims.slice();e[2]=e[2]/2;let n=Q("input",t[0].dataType,t[0].dims,4),r=Q("bias",t[0].dataType,[t[0].dims[2]],4),a=ve("output",t[0].dataType,e,4),i=J.size(e)/4,s=At(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(n,r,a)} - - ${Ua(`vec4<${s}>`,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")} - }`}},ih=t=>{Zl(t.inputs),t.compute(Jl(t.inputs))}}),eu,tu,Nt,sh,oh,lh,uh,dh,ch,ph,hh,fh,mh,M_=X(()=>{Ye(),Ie(),Ce(),eu=(t,e,n,r,a,i,s,o,l,d,c,u,h)=>{let f,g;typeof o=="string"?f=g=(A,P)=>`${o}((${A}),(${P}))`:typeof o=="function"?f=g=o:(f=o.scalar,g=o.vector);let w=u?e.length:e,b=u?n.length:n,y=u?r.length:r,$=ve("outputData",c,y,4),k=Q("aData",l,w,4),S=Q("bData",d,b,4),T;if(a)if(i){let A=J.size(e)===1,P=J.size(n)===1,N=e.length>0&&e[e.length-1]%4===0,V=n.length>0&&n[n.length-1]%4===0;A||P?T=$.setByOffset("global_idx",g(A?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"),P?`${S.type.value}(${S.getByOffset("0")}.x)`:S.getByOffset("global_idx"))):T=` - let outputIndices = ${$.offsetToIndices("global_idx * 4u")}; - let offsetA = ${k.broadcastedIndicesToOffset("outputIndices",$)}; - let offsetB = ${S.broadcastedIndicesToOffset("outputIndices",$)}; - ${$.setByOffset("global_idx",g(s||N?k.getByOffset("offsetA / 4u"):`${k.type.value}(${k.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||V?S.getByOffset("offsetB / 4u"):`${S.type.value}(${S.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else T=$.setByOffset("global_idx",g(k.getByOffset("global_idx"),S.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let A=(P,N,V="")=>{let j=`aData[indexA${N}][componentA${N}]`,M=`bData[indexB${N}][componentB${N}]`;return` - let outputIndices${N} = ${$.offsetToIndices(`global_idx * 4u + ${N}u`)}; - let offsetA${N} = ${k.broadcastedIndicesToOffset(`outputIndices${N}`,$)}; - let offsetB${N} = ${S.broadcastedIndicesToOffset(`outputIndices${N}`,$)}; - let indexA${N} = offsetA${N} / 4u; - let indexB${N} = offsetB${N} / 4u; - let componentA${N} = offsetA${N} % 4u; - let componentB${N} = offsetB${N} % 4u; - ${P}[${N}] = ${V}(${f(j,M)}); - `};c===9?T=` - var data = vec4(0); - ${A("data",0,"u32")} - ${A("data",1,"u32")} - ${A("data",2,"u32")} - ${A("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:T=` - ${A("outputData[global_idx]",0)} - ${A("outputData[global_idx]",1)} - ${A("outputData[global_idx]",2)} - ${A("outputData[global_idx]",3)} - `}return` - ${t.registerUniform("vec_size","u32").declareVariables(k,S,$)} - - ${h??""} - - ${t.mainStart()} - ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${T} - }`},tu=(t,e,n,r,a,i,s=n.dataType)=>{let o=!J.areEqual(n.dims,r.dims),l=n.dims,d=J.size(n.dims),c=!1,u=!1,h=[o];if(o){let g=Xn.calcShape(n.dims,r.dims,!1);if(!g)throw new Error("Can't perform binary op on the given tensors");l=g,d=J.size(l);let w=J.size(n.dims)===1,b=J.size(r.dims)===1,y=n.dims.length>0&&n.dims[n.dims.length-1]%4===0,$=r.dims.length>0&&r.dims[r.dims.length-1]%4===0;h.push(w),h.push(b),h.push(y),h.push($);let k=1;for(let S=1;Sg.toString()).join("_"),inputDependencies:f?["rank","rank"]:["dims","dims"]},getShaderSource:g=>eu(g,n.dims,r.dims,l,c,o,u,a,n.dataType,r.dataType,s,f,i),getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:f?[{type:"uint32",data:Math.ceil(J.size(l)/4)},...ie(n.dims),...ie(r.dims),...ie(l)]:[{type:"uint32",data:Math.ceil(J.size(l)/4)}]})}},Nt=(t,e,n,r,a,i)=>{t.compute(tu(e,a??"",t.inputs[0],t.inputs[1],n,r,i))},sh=t=>{Nt(t,"Add",(e,n)=>`${e}+${n}`)},oh=t=>{Nt(t,"Div",(e,n)=>`${e}/${n}`)},lh=t=>{Nt(t,"Equal",{scalar:(e,n)=>`u32(${e}==${n})`,vector:(e,n)=>`vec4(${e}==${n})`},void 0,void 0,9)},uh=t=>{Nt(t,"Mul",(e,n)=>`${e}*${n}`)},dh=t=>{let e=Q("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;Nt(t,"Pow",{scalar:(n,r)=>`pow_custom(${n},${r})`,vector:(n,r)=>`pow_vector_custom(${n},${r})`},` - 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)); - } - `)},ch=t=>{Nt(t,"Sub",(e,n)=>`${e}-${n}`)},ph=t=>{Nt(t,"Greater",{scalar:(e,n)=>`u32(${e}>${n})`,vector:(e,n)=>`vec4(${e}>${n})`},void 0,void 0,9)},hh=t=>{Nt(t,"Less",{scalar:(e,n)=>`u32(${e}<${n})`,vector:(e,n)=>`vec4(${e}<${n})`},void 0,void 0,9)},fh=t=>{Nt(t,"GreaterOrEqual",{scalar:(e,n)=>`u32(${e}>=${n})`,vector:(e,n)=>`vec4(${e}>=${n})`},void 0,void 0,9)},mh=t=>{Nt(t,"LessOrEqual",{scalar:(e,n)=>`u32(${e}<=${n})`,vector:(e,n)=>`vec4(${e}<=${n})`},void 0,void 0,9)}}),nu,ru,au,iu,gh,_h,O_=X(()=>{Ie(),ot(),Ce(),nu=t=>{if(!t||t.length<1)throw new Error("too few inputs");let e=t[0].dataType,n=t[0].dims.length;for(let r of t){if(r.dataType!==e)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}},ru=(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; - }`,au=(t,e)=>{let n=t.length,r=[];for(let a=0;a{let n=t[0].dims.slice();if(e>=n.length||e<-1*n.length)throw new Error("axis specified for concat doesn't match input dimensionality");let r=e<0?n.length+e:e,a=n.slice(0);for(let S=1;S`uniforms.sizeInConcatAxis${S}`).join(","),k=S=>` - - ${(()=>{S.registerUniform("outputSize","u32");for(let T=0;T(${$}); - ${y} -= sizeInConcatAxis[inputIndex - 1u]; - } - - ${au(o,b)} - }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:f}),getShaderSource:k}},gh=(t,e)=>{nu(t.inputs),t.compute(iu(t.inputs,e.axis))},_h=t=>qe({axis:t.axis})}),tr,ro,An=X(()=>{Ie(),tr=(t,e)=>{switch(t.activation){case"Relu":return{activationFunction:"",applyActivation:`value = max(value, ${e}(0.0));`};case"Sigmoid":return{activationFunction:"",applyActivation:`value = (${e}(1.0) / (${e}(1.0) + exp(-value)));`};case"Clip":return{activationFunction:`const clip_min_=${e}(${t.clipMin});const clip_max_=${e}(${t.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},ro=t=>{let e=t?.activation||"";if(e==="Clip"){let[n,r]=t?.activation_params||[Js,eo];return{activation:e,clipMax:r,clipMin:n,activationCacheKey:`${e}:${n},${r}`}}return{activation:e,activationCacheKey:e}}}),ct,ao,io=X(()=>{ct=(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.`)}},ao=t=>` - ${t?"value = value + getBiasByOutputCoords(coords);":""} - `}),so,wh=X(()=>{so=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)); -} -`}),su,ou,ei,Wi,lu,ti,uu,oo,ui=X(()=>{Ie(),Ce(),An(),io(),su=(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":""}); - `,ou=(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];"} - }`,ei=(t,e,n="f32",r,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],f=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)"}; - ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} - let globalRowStart = i32(workgroupId.y) * ${l}; - - let numTiles = ${s?`${Math.ceil(o/i)}`:"(uniforms.dimInner - 1) / tileInner + 1"}; - var kStart = ${s?`i32(globalId.z) * ${o}`:"0"}; - - var acc: array, rowPerThread>; - - // Loop over shared dimension. - let tileRowB = localRow * ${f}; - for (var t = 0; t < numTiles; 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; - ${su(a,r)} - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${r?", 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];"} - - ${ou(a,h)} - } - - workgroupBarrier(); - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); - } -}`},Wi=(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":""}); - `,lu=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ti=(t,e,n="f32",r,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 f=h/e[1],g=u/e[0],w=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 < numTiles; 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]}) { - ${Wi(a,r)} - } - } - // 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${r?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${n}, 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) * ${f}; -let tileColA = i32(localId.x) * ${g}; -let tileRowB = i32(localId.y) * ${w}; -// Loop over shared dimension. -for (var t = 0; t < numTiles; t = t + 1) { - // Load one tile of A into local memory. - for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${g}; innerCol = innerCol + 1) { - let inputRow = tileRowA + innerRow; - let inputCol = tileColA + innerCol; - ${Wi(a,r)} - } - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${w}; 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${r?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${n}, 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) { - ${lu(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)"}; - ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} - let numTiles = ${s?`${Math.ceil(o/i)}`:"(uniforms.dimInner - 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} - } -`},uu=(t,e,n,r,a,i=!1)=>{let[s,o,l]=a,[d,c,u,h]=r,f=Nr(s,l),g=Nr(o,l),w=At(r[0].type.tensor),b=()=>{let $=c.rank,k=d.rank,S=`var aIndices: ${c.type.indices};`;for(let T=$-2-1,A=k-1;T>=0;T--,A--)S+=` -aIndices[${T}] = ${k>1?`batchIndices[${A}]`:"batchIndices"};`;return f.forEach(T=>{S+=` -aIndices[${T}] = 0;`}),S+=` -aIndices[${$-2}] = u32(row); - aIndices[${$-1}] = u32(colIn);`,S},y=()=>{let $=u.rank,k=d.rank,S=`var bIndices: ${u.type.indices};`;for(let T=$-2-1,A=k-1;T>=0;T--,A--)S+=` -bIndices[${T}] = ${k>1?`batchIndices[${A}]`:"batchIndices"};`;return g.forEach(T=>{S+=` -bIndices[${T}] = 0;`}),S+=` -bIndices[${$-2}] = u32(row); - bIndices[${$-1}] = u32(colIn);`,S};return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${ct(t,w)} { - var value = ${ct(t,w)}(0.0); - let col = colIn * ${t}; - if(row < uniforms.dimAOuter && col < uniforms.dimInner) - { - ${b()} - value = ${c.getByIndices("aIndices")}; - } - return value; - } - - fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${ct(t,w)} { - var value = ${ct(t,w)}(0.0); - let col = colIn * ${t}; - if(row < uniforms.dimInner && col < uniforms.dimBOuter) - { - ${y()} - value = ${u.getByIndices("bIndices")}; - } - return value; - } - - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ct(t,w)}) { - let col = colIn * ${t}; - if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { - var value = valueIn; - let coords = vec3(batch, row, colIn); - ${e?`value = value + ${i?"bias[colIn]":`${ct(t,w)}(bias[row])`};`:""} - ${n} - ${h.setByIndices("vec3(coords)","value")} - } - } - `},oo=(t,e,n,r,a=!1)=>{let i=t[0].dims,s=t[1].dims,o=i.slice(0,-2),l=s.slice(0,-2),d=r?r.slice(0,-2):n.slice(0,-2),c=st(d.length),u=c?d.length:d,h=to("batchDims",t[0].dataType,u,1),f=J.size(d),g=i[i.length-2],w=i[i.length-1],b=s[s.length-1],y=w%4===0&&b%4===0,$=g<=8?[4,1,1]:[4,4,1],k=[8,8,1],S=[Math.ceil(b/k[0]/$[0]),Math.ceil(g/k[1]/$[1]),Math.ceil(f/k[2]/$[2])],T=At(t[0].dataType),A=y?4:1,P=[...o,g,w/A],N=st(P.length),V=N?P.length:P,j=[...l,w,b/A],M=st(j.length),G=M?j.length:j,O=[f,g,b/A],R=Q("a",t[0].dataType,V,A),H=Q("b",t[1].dataType,G,A),te=ve("result",t[0].dataType,O.length,A),ae=[R,H],re=[{type:"int32",data:g},{type:"int32",data:b},{type:"int32",data:w}];c&&re.push(...ie(d)),N&&re.push(...ie(P)),M&&re.push(...ie(j));let Y=[];Y.push(N?"rank":"dims"),Y.push(M?"rank":"dims");let ue=t.length>2,{activationFunction:W,applyActivation:oe}=tr(e,te.type.value),$e=uu(A,ue,oe,[h,R,H,te],[o,l,d],a);if(ue){let Pe=a?A:1;ae.push(Q("bias",t[2].dataType,t[2].dims.length,Pe)),re.push(...ie(t[2].dims)),Y.push("rank")}re.push(...ie(O));let Fe=Pe=>` - ${Pe.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").registerInternalVariables(h).declareVariables(...ae,te)} - ${W} - ${$e} - ${y?ei($,k,T,h):ti($,k,T,h)} - `;return{name:"MatMul",shaderCache:{hint:e.activationCacheKey+`${$}${y}${a}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:re}),getShaderSource:Fe}}}),du,yh,z_=X(()=>{In(),Ce(),An(),io(),wh(),ui(),du=(t,e,n,r,a=!1,i,s=4,o=4,l=4,d="f32")=>{let c=j=>{switch(j){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 ${j} is not supported.`)}},u=j=>{switch(j){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 ${j} is not supported.`)}},h=t?` - let coord = vec4(batch, xRow, xCol, xCh); - `:` - let coord = vec4(batch, xCh, xRow, xCol); - `,f=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])",w=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",b=t?"row":"col",y=t?"col":"row",$=` - 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 = ${y} / (filterDims[1] * inChannels); - let WCol = ${y} / inChannels % filterDims[1]; - let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0]; - let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1]; - let xCh = ${y} % inChannels; - var resData = ${ct(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 < ${w}) { - ${h} - let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); - ${c(s)} - } - return resData;`,k=t?e&&r?` - let col = colIn * ${s}; - ${$}`:` - let col = colIn * ${s}; - if (row < uniforms.dimAOuter && col < uniforms.dimInner) { - ${$} - } - return ${ct(s,d)}(0.0);`:r&&n?` - let col = colIn * ${s}; - ${$}`:` - let col = colIn * ${s}; - if (row < uniforms.dimInner && col < uniforms.dimBOuter) { - ${$} - } - return ${ct(s,d)}(0.0);`,S=`${u(o)}`,T=ct(l,d),A=ct(t?s:o,d),P=ct(t?o:s,d),{activationFunction:N,applyActivation:V}=tr(i,T);return` - ${N} - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} { - ${t?k:S} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${P} { - ${t?S:k} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${T}) { - let col = colIn * ${l}; - if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) - { - var value = valueIn; - let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - ${f} - ${ao(a)} - ${V} - setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); - } - }`},yh=(t,e,n,r,a,i,s,o)=>{let l=e.format==="NHWC",d=l?t[0].dims[3]:t[0].dims[1],c=n[0],u=l?n[2]:n[3],h=l?n[1]:n[2],f=l?n[3]:n[1],g=l&&(d%4===0||d%3===0)&&f%4===0,w=l?f:u*h,b=l?u*h:f,y=[8,8,1],$=r<=8?[4,1,1]:[4,4,1],k=[Math.ceil(w/y[0]/$[0]),Math.ceil(b/y[1]/$[1]),Math.ceil(c/y[2]/$[2])];it("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${k}`);let S=g?l&&d%4!==0?3:4:1,T=y[1]*$[1],A=y[0]*$[0],P=Math.max(y[0]*S,y[1]),N=r%T===0,V=a%A===0,j=i%P===0,M=g?[S,4,4]:[1,1,1],G=At(t[0].dataType),O=g?4:1,R=[{type:"int32",data:r},{type:"int32",data:a},{type:"int32",data:i}],H=Q("x",t[0].dataType,t[0].dims.length,S===3?1:S),te=Q("w",t[1].dataType,t[1].dims.length,O),ae=[H,te];R.push(...ie(t[0].dims)),R.push(...ie(t[1].dims));let re=` - fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${G}>`:G}) { - result[flatIndex] = ${g?`vec4<${G}>`:G}(value); - } - fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${G}>`:G}) { - let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); - setOutputAtIndex(flatIndex ${g?"/ 4":""}, value); - }`;if(s){let ue=Q("bias",t[2].dataType,t[2].dims.length,O);ae.push(ue),R.push(...ie(t[2].dims)),re+=` - fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${G}>`:G} { - return bias[coords.${l?"w":"y"}${g?"/ 4":""}]; - }`}let Y=ve("result",t[0].dataType,n.length,O);return R.push(...ie(n)),{name:"Conv2DMatMul",shaderCache:{hint:e.cacheKey},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:k[0],y:k[1],z:k[2]},programUniforms:R}),getShaderSource:ue=>` - ${so("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 }; - ${ue.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...ae,Y)} - const filterDims : vec2 = vec2(${e.kernelShape[0]}, ${e.kernelShape[1]}); - const pad : vec2 = vec2(${e.pads[0]}, ${e.pads[1]}); - const stride : vec2 = vec2(${e.strides[0]}, ${e.strides[1]}); - const dilation : vec2 = vec2(${e.dilations[0]}, ${e.dilations[1]}); - ${re} - ${du(l,N,V,j,s,e,M[0],M[1],M[2],G)} - ${g?ei($,y,G,void 0,!l,P):ti($,y,G,void 0,!l,P,!1,void 0,o)}`}}}),Es,R_=X(()=>{Ie(),Ce(),$h(),An(),Es=(t,e,n)=>{let r=t.length>2,a=r?"value += b[output_channel];":"",i=t[0].dims,s=t[1].dims,o=s[0]/e.group,l=e.format==="NHWC",d=Cs(i,s,e.dilations,e.pads,e.strides,l),c=J.size(d),u=ve("output",t[0].dataType,d),{activationFunction:h,applyActivation:f}=tr(e,u.type.value),g=Q("x",t[0].dataType,i),w=Q("w",t[1].dataType,s),b=[g,w];r&&b.push(Q("b",t[2].dataType,t[2].dims));let y=$=>` - const strides: vec2 = vec2(${e.strides[0]}u, ${e.strides[1]}u); - const pads: vec2 = vec2(${e.pads[0]}u, ${e.pads[1]}u); - - ${$.declareVariables(...b,u)} - - ${h} - - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes(c)} - - let outputIndices = ${u.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}]) * strides - pads; - let group_id: u32 = output_channel / ${o}u; - - var value: ${u.type.value} = ${u.type.value}(0); - for (var wInChannel: u32 = 0u; wInChannel < ${s[1]}u; wInChannel++) { - let input_channel = group_id * ${s[1]}u + wInChannel; - for (var wHeight: u32 = 0u; wHeight < ${s[2]}u; wHeight++) { - let xHeight = xRCCorner.x + wHeight * ${e.dilations[0]}u; - - if (xHeight < 0u || xHeight >= ${i[l?1:2]}u) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < ${s[3]}u; wWidth++) { - let xWidth = xRCCorner.y + wWidth * ${e.dilations[1]}u; - if (xWidth < 0u || xWidth >= ${i[l?2:3]}u) { - continue; - } - - let xVal = ${l?g.get("batch","xHeight","xWidth","input_channel"):g.get("batch","input_channel","xHeight","xWidth")}; - let wVal = ${w.get("output_channel","wInChannel","wHeight","wWidth")}; - value += xVal*wVal; - } - } - } - ${a} - ${f} - ${u.setByOffset("global_idx","value")} - }`;return{name:"GroupedConv",shaderCache:{hint:e.cacheKey},getRunData:()=>({outputs:[{dims:n?n(d):d,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)}}),getShaderSource:y}}}),ks,cu,bh,vh=X(()=>{Ie(),ui(),Ce(),An(),ks=(t,e,n,r,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=$t(l),u=$t(d),h=$t(o),f=J.size(n)/c/h,g=t.length>2,w=r?r.slice(0,-2):n.slice(0,-2),b=[J.size(w),o,l],y=[{type:"uint32",data:f},{type:"uint32",data:o},{type:"uint32",data:l},{type:"uint32",data:d},...ie(w),...ie(i),...ie(s)];g&&y.push(...ie(t[2].dims)),y.push(...ie(b));let $=k=>{let S=to("batch_dims",t[0].dataType,w.length),T=Q("a",t[0].dataType,i.length,u),A=Q("b",t[1].dataType,s.length,c),P=ve("output",t[0].dataType,b.length,c),{activationFunction:N,applyActivation:V}=tr(e,P.type.value),j=[T,A],M="";if(g){let re=a?c:1;j.push(Q("bias",t[2].dataType,t[2].dims.length,re)),M=`${a?`value += bias[col / ${re}];`:`value += ${P.type.value}(bias[row + i]);`}`}let G=i.slice(0,-2),O=s.slice(0,-2),R=Nr(G,w),H=Nr(O,w),te=(re,Y)=>{let ue=re.rank,W=re.name;if(ue===2)return`var ${W}_indices = ${re.type.indices}(0u, 0u);`;let oe=S.rank,$e=`var ${W}_indices: ${re.type.indices};`;for(let Fe=ue-2-1,Pe=oe-1;Fe>=0;Fe--,Pe--)$e+=` -${W}_indices[${Fe}] = ${oe>1?`batch_indices[${Pe}]`:"batch_indices"};`;return Y.forEach(Fe=>{$e+=` -${W}_indices[${Fe}] = 0;`}),$e+=`${W}_indices[${ue-2}] = 0u; - ${W}_indices[${ue-1}] = 0u;`,$e},ae=()=>{let re=`var a_data: ${T.type.value};`;for(let Y=0;Y; - for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { - ${ae()} - } - for (var i = 0u; i < ${h}u; i++) { - var value = values[i]; - ${M} - ${V} - let cur_indices = ${P.type.indices}(batch, row + i, col); - let offset = ${P.indicesToOffset("cur_indices")}; - ${P.setByOffset(`offset / ${c}`,"value")}; - } - } - `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activationCacheKey}_${c}_${u}_${h}_${a}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:y}),getShaderSource:$}},cu=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.")},bh=t=>{cu(t.inputs);let e=Xn.calcShape(t.inputs[0].dims,t.inputs[1].dims,!0);if(!e)throw new Error("Can't use matmul on the given tensors");let n=e[e.length-1],r=t.inputs[0].dims[t.inputs[0].dims.length-1];n<8&&r<8?t.compute(ks(t.inputs,{activation:"",activationCacheKey:""},e)):t.compute(oo(t.inputs,{activation:"",activationCacheKey:""},e))}}),Cs,Vi,pu,Gi,Ts,hu,fu,Is,$h=X(()=>{Ie(),ot(),z_(),ui(),R_(),An(),vh(),Hr(),Cs=(t,e,n,r,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,f)=>h+(h-1)*(n[f]-1)),u=o.map((h,f)=>h+r[f]+r[f+l]).map((h,f)=>Math.floor((h-c[f]+a[f])/a[f]));return u.splice(0,0,s),u.splice(i?3:1,0,d),u},Vi=[2,3,1,0],pu=(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 n=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],r=t[1].dims[1]*e.group;if(n!==r)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")},Gi=(t,e)=>{let n=t.kernelShape.slice();for(let i=2;i{let e=ro(t),n=t.format,r=["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 qe({autoPad:r,format:n,dilations:a,group:i,kernelShape:s,pads:o,strides:l,wIsConst:d,...e})},hu=(t,e,n)=>{let r=Gi(n,e),a=n.format==="NHWC";if(n.group!==1){t.compute(Es(e,r));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=Cs(e[0].dims,e[1].dims,n.dilations,r.pads,n.strides,a),h=u[a?1:2],f=u[a?2:3],g=u[a?3:1],w=a&&d===s&&c===o&&n.pads[0]===0&&n.pads[1]===0;if(w||d===1&&c===1&&n.dilations[0]===1&&n.dilations[1]===1&&n.strides[0]===1&&n.strides[1]===1&&n.pads[0]===0&&n.pads[1]===0){let A=u[0],P,N,V,j=[];if(a){let O=t.kernelCustomData.wT??t.compute(_n(e[1],Vi),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=O),w){let R=s*o*l;P=e[0].reshape([1,A,R]),N=O.reshape([1,R,g]),V=[1,A,g]}else P=e[0].reshape([A,s*o,l]),N=O.reshape([1,l,g]),V=[A,h*f,g];j.push(P),j.push(N)}else P=e[0].reshape([A,l,s*o]),N=e[1].reshape([1,g,l]),V=[A,g,h*f],j.push(N),j.push(P);i&&j.push(e[2]);let M=V[2],G=j[0].dims[j[0].dims.length-1];M<8&&G<8?t.compute(ks(j,r,u,V,a),{inputs:j}):t.compute(oo(j,r,u,V,a),{inputs:j});return}let b=!0,y=t.kernelCustomData.wT??t.compute(_n(e[1],Vi),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=y);let $=[e[0],y];i&&$.push(e[2]);let k=a?h*f:g,S=a?g:h*f,T=d*c*l;t.compute(yh($,r,u,k,S,T,i,b),{inputs:$})},fu=(t,e)=>{let n=e.format==="NHWC",r=[t.inputs[0].reshape(n?[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&&r.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=Gi({...e,pads:a,strides:i,dilations:s,kernelShape:o},r);t.compute(Es(r,l,d=>n?[d[0],d[2],d[3]]:[]))},Is=(t,e)=>{pu(t.inputs,e),t.inputs[0].dims.length===3?fu(t,e):hu(t,t.inputs,e)}}),mu,xh,B_=X(()=>{In(),Ce(),An(),io(),wh(),ui(),mu=(t,e=!1,n,r=4)=>{let a=ct(r,"f32"),i=y=>{switch(y){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 vec4(v0, v1, v2, v3); - `;default:throw new Error(`innerElementSize ${y} 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?"outBackprop[1]":"outBackprop[2]",d=t?"outBackprop[2]":"outBackprop[3]",c=t?"row":"col",u=t?"col":"row",h=` - let inChannels = ${t?"outBackprop[3]":"outBackprop[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} / (filterDims[1] * inChannels); - let WCol = ${u} / inChannels % filterDims[1]; - let xR = f32(outRow - pads[0] + dilation[0] * WRow) / f32(strides[0]); - let xC = f32(outCol - pads[1] + dilation[1] * WCol) / f32(strides[1]); - if (xR < 0.0 || xR >= f32(${l}) || fract(xR) > 0.0) { - return ${a}(0.0); - } - if (xC < 0.0 || xC >= f32(${d}) || fract(xC) > 0.0) { - return ${a}(0.0); - } - let iXR = i32(xR); - let iXC = i32(xC); - let xCh = ${u} % inChannels; - ${s} - return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${r}];`,f=t?` - let col = colIn * ${r}; - if (row < uniforms.dimAOuter && col < uniforms.dimInner) { - ${h} - } - return ${a}(0.0);`:` - let col = colIn * ${r}; - if (row < uniforms.dimInner && col < uniforms.dimBOuter) { - ${h} - } - return ${a}(0.0);`,g=` - let col = colIn * ${r}; - let inChannels = ${t?"outBackprop[3]":"outBackprop[1]"}; - let coordX = filterDims.x - 1 - row / (filterDims[1] * inChannels); - let coordY = filterDims.y - 1 - (row / inChannels) % filterDims[1]; - if (${t?"row < uniforms.dimInner && col < uniforms.dimBOuter":"row < uniforms.dimInner && col < uniforms.dimAOuter"} && coordX >= 0 && coordY >= 0) { - let rowInner = row % inChannels; - let coord = vec4(coordX, coordY, col, rowInner); - ${i(r)} - } - return ${a}(0.0); - `,{activationFunction:w,applyActivation:b}=tr(n,a);return` - ${w} - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${a} { - ${t?f:g} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${a} { - ${t?g:f} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${a}) { - let col = colIn * ${r}; - if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { - var value = valueInput; - let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - ${o} - ${ao(e)} - ${b} - result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${r}] = value; - } - }`},xh=(t,e,n,r,a,i,s,o)=>{let l=e.format==="NHWC",d=l?t[0].dims[3]:t[0].dims[1],c=n[0],u=l?n[2]:n[3],h=l?n[1]:n[2],f=l?n[3]:n[1],g=l?d%4===0&&f%4===0:u%4===0&&f%4===0,w=l?f:u*h,b=l?u*h:f,y=g?[8,8,1]:[w<=4||b<=4?4:16,w>4&&b<=4?4:16,1],$=g?[4,4,1]:[w<=4?1:4,w>4&&b<=4?1:4,1],k=[Math.ceil(w/y[0]/$[0]),Math.ceil(b/y[1]/$[1]),Math.ceil(c/y[2]/$[2])];it("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${k}`);let S=g?4:1,T=Math.max(y[0]*S,y[1]),A=g?4:1,P=[{type:"int32",data:r},{type:"int32",data:a},{type:"int32",data:i}],N=Q("x",t[0].dataType,t[0].dims.length,A),V=Q("w",t[1].dataType,t[1].dims.length,1),j=ve("result",t[0].dataType,n.length,A),M=[N,V];P.push(...ie(t[0].dims)),P.push(...ie(t[1].dims));let G="";if(s){let O=Q("bias",t[2].dataType,t[2].dims.length,A);M.push(O),P.push(...ie(t[2].dims)),G+=` - fn getBiasByOutputCoords(coords : vec4) -> ${g?"vec4":"f32"} { - return bias[coords.${l?"w":"y"}${g?"/ 4":""}]; - }`}return P.push(...ie(n)),{name:"Conv2DTransposeMatMul",shaderCache:{hint:e.cacheKey},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:k[0],y:k[1],z:k[2]},programUniforms:P}),getShaderSource:O=>` - ${so("uniforms.result_strides")} - ${O.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...M,j)}; - const outBackprop : vec4 = vec4(${t[0].dims.join(",")}); - const filterDims : vec2 = vec2(${e.kernelShape[l?1:2]}, ${e.kernelShape[l?2:3]}); - const effectiveFilterDims : vec2 = filterDims + vec2( - ${e.dilations[0]<=1?0:(e.kernelShape[l?1:2]-1)*(e.dilations[0]-1)}, - ${e.dilations[1]<=1?0:(e.kernelShape[l?2:3]-1)*(e.dilations[1]-1)}); - const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${e.pads[0]+e.pads[2]})/2, - i32(effectiveFilterDims[1]) - 1 - (${e.pads[1]+e.pads[3]})/2); - const strides : vec2 = vec2(${e.strides[0]}, ${e.strides[1]}); - const dilation : vec2 = vec2(${e.dilations[0]}, ${e.dilations[1]}); - const dimAOuter : i32 = ${r}; - const dimBOuter : i32 = ${a}; - const dimInner : i32 = ${i}; - ${G} - ${mu(l,s,e,S)} - ${g?ei($,y,"f32",void 0,!l,T):ti($,y,"f32",void 0,!l,T,!1,void 0,o)}`}}}),gu,As,P_=X(()=>{In(),Ie(),Ce(),gu=(t,e,n,r,a,i,s=!1,o)=>{let l=n.format==="NHWC",d=l?1:2,c=l?2:3,u=l?3:1,h=J.size(r),f=s?2:1,g=n.group,w=e[1].dims,b=w[0]/g,y=w[1],$=` - fn setOutputAtIndex(flatIndex : u32, value : ${s?`vec4<${o}>`:o}) { - result[flatIndex] = ${s?`vec4<${o}>`:o}(value); - }`;a&&($+=` - fn getBiasByOutputCoords(coords : vec4) -> ${s?`vec4<${o}>`:o} { - return bias[coords.${l?"w":"y"}${s?"/ 4":""}]; - }`);let k=s?4:1,S=Q("W",e[1].dataType,e[1].dims,k),T=Q("Dy",e[0].dataType,e[0].dims,k),A=[T,S];a&&A.push(Q("bias",e[2].dataType,[r[u]],k));let P=ve("result",e[0].dataType,r,k),N=`{ - let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / outShape[1]; - let r = ${i?"global_id.z":"workgroup_id.z"} % outShape[1]; - let c = ${i?"global_id.y":"workgroup_id.y"} * ${f}; - let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4; - - let dyCorner = vec2(i32(r), i32(c)) - vec2(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, ${f}>; - for (var i = 0; i < ${f}; i++) { - dotProd[i] = vec4<${o}>(0.0); - } - for (var wR: u32 = 0; wR < filterDims[0]; wR = wR + 1) { - var dyR = (${o}(dyCorner.x) + ${o}(wR)) / ${o}(strides.x); - let wRPerm = filterDims[0] - 1 - wR; - if (dyR < 0.0 || dyR >= ${o}(outBackprop[1]) || - fract(dyR) > 0.0 || wRPerm < 0) { - continue; - } - let idyR: u32 = u32(dyR); - - for (var wC: u32 = 0; wC < filterDims[1]; wC = wC + 1) { - let dyC = (${o}(dyCorner.y) + ${o}(wC)) / ${o}(strides.y); - let dyC2 = (${o}(dyCorner.y) + 1.0 + ${o}(wC)) / ${o}(strides.y); - let wCPerm = filterDims[1] - 1 - wC; - if (wCPerm < 0) { - continue; - } - var bDyCVal = true; - var bDyCVal2 = true; - if (dyC < 0.0 || dyC >= ${o}(outBackprop[2]) || - fract(dyC) > 0.0) { - bDyCVal = false; - } - if (dyC2 < 0.0 || dyC2 >= ${o}(outBackprop[2]) || - fract(dyC2) > 0.0) { - bDyCVal2 = false; - } - - let idyC: u32 = u32(dyC); - let idyC2: u32 = u32(dyC2); - if (bDyCVal && bDyCVal2) { - let d2Length = outBackprop[3]; - for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { - let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${T.get("batch","idyR","idyC","d2")}; - let tmpval = vec4<${o}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[0] = dotProd[0] + tmpval; - - xValue = ${T.get("batch","idyR","idyC2","d2")}; - - dotProd[1] = dotProd[1] + vec4<${o}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - } - } else if (bDyCVal) { - let d2Length = outBackprop[${u}]; - for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { - let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${T.get("batch","idyR","idyC","d2")}; - let tmpval = vec4<${o}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[0] = dotProd[0] + tmpval; - } - } else if (bDyCVal2) { - let d2Length = outBackprop[3]; - for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { - let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${T.get("batch","idyR","idyC2","d2")}; - let tmpval = vec4<${o}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[1] = dotProd[1] + tmpval; - } - } - } - } - - for (var i: u32 = 0; i < ${f}; i = i + 1) { - let value = dotProd[i] + ${a?"bias[c+i]":`vec4<${o}>(0.0)`}; - ${P.set("batch","r","c + i","d1","value")}; - } - }`,V=` - let outputIndices = ${P.offsetToIndices("global_idx")}; - let batch = ${P.indicesGet("outputIndices",0)}; - let d1 = ${P.indicesGet("outputIndices",u)}; - let r = ${P.indicesGet("outputIndices",d)}; - let c = ${P.indicesGet("outputIndices",c)}; - let dyCorner = vec2(i32(r), i32(c)) - pads; - let dyRCorner = dyCorner.x; - let dyCCorner = dyCorner.y; - let groupId = d1 / ${y}; - let wOutChannel = d1 - groupId * ${y}; - // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). - // ? = to be determined. : = across all values in that axis. - var dotProd = ${o}(0.0); - for (var wR: u32 = 0; wR < effectiveFilterDims.x; wR = wR + 1) { - if (wR % dilations.x != 0) { - continue; - } - let dyR = (${o}(dyRCorner) + ${o}(wR)) / ${o}(strides[0]); - let wRPerm = filterDims.x - 1 - wR / dilations.x; - if (dyR < 0.0 || dyR >= ${o}(outBackprop[${d}]) || fract(dyR) > 0.0 || - wRPerm < 0) { - continue; - } - let idyR: u32 = u32(dyR); - - for (var wC: u32 = 0; wC < effectiveFilterDims.y; wC = wC + 1) { - if (wC % dilations.y != 0) { - continue; - } - let dyC = (${o}(dyCCorner) + ${o}(wC)) / ${o}(strides.y); - let wCPerm = filterDims.y - 1 - wC / dilations.y; - if (dyC < 0.0 || dyC >= ${o}(outBackprop[${c}]) || - fract(dyC) > 0.0 || wCPerm < 0) { - continue; - } - let idyC: u32 = u32(dyC); - var inputChannel = groupId * ${b}; - for (var d2: u32 = 0; d2 < ${b}; d2 = d2 + 1) { - let xValue = ${l?T.get("batch","idyR","idyC","inputChannel"):T.get("batch","inputChannel","idyR","idyC")}; - let wValue = ${S.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; - dotProd = dotProd + xValue * wValue; - inputChannel = inputChannel + 1; - } - } - } - let value = dotProd + ${a?"bias[d1]":`${o}(0.0)`}; - ${P.setByOffset("global_idx","value")}; - `;return` - ${t.declareVariables(...A,P)} - ${$} - const outShape : vec4 = vec4(${r.join(",")}); - const outBackprop : vec4 = vec4(${e[0].dims.join(",")}); - const strides : vec2 = vec2(${n.strides[0]}, ${n.strides[1]}); - const filterDims : vec2 = vec2(${n.kernelShape[l?1:2]}, ${n.kernelShape[l?2:3]}); - const dilations : vec2 = vec2(${n.dilations[0]}, ${n.dilations[1]}); - const effectiveFilterDims : vec2 = filterDims + vec2( - ${n.dilations[0]<=1?0:(n.kernelShape[l?1:2]-1)*(n.dilations[0]-1)}, - ${n.dilations[1]<=1?0:(n.kernelShape[l?2:3]-1)*(n.dilations[1]-1)}); - const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${n.pads[0]+n.pads[2]})/2, - i32(effectiveFilterDims[1]) - 1 - (${n.pads[1]+n.pads[3]})/2); - ${t.mainStart()} - ${t.guardAgainstOutOfBoundsWorkgroupSizes(h)}; - ${s?N:V}}`},As=(t,e,n)=>{let r=t.length>2,a=e.outputShape,i=J.size(a),s=[Math.ceil(i/64),1,1];it("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let o=At(t[0].dataType);return{name:"ConvTranspose2D",shaderCache:{hint:e.cacheKey},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:n?n(a):a,dataType:t[0].dataType}]}),getShaderSource:l=>gu(l,t,e,a,r,s[1]===1&&s[2]===1,!1,o)}}}),_u,wu,yu,Hi,Sh,bu,vu,$u,xu,Eh,D_=X(()=>{ot(),B_(),P_(),An(),Hr(),_u=(t,e,n,r,a,i)=>(t-1)*e+n+(r-1)*a+1-i,wu=(t,e,n,r,a)=>{let i=Math.floor(t/2);e==="SAME_UPPER"?(n[r]=i,n[a]=t-i):e==="SAME_LOWER"&&(n[r]=t-i,n[a]=i)},yu=(t,e,n,r,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 n=t.kernelShape.slice();if(t.kernelShape.length===0||t.kernelShape.reduce((h,f)=>h*f,1)===0){n.length=0;for(let h=2;hh+f,0)===0){let h=e[0].dims.length-2;l=new Array(h).fill(1)}let d=t.strides.slice();if(d.reduce((h,f)=>h+f,0)===0){let h=e[0].dims.length-2;d=new Array(h).fill(1)}yu(o,n,l,t.autoPad,t.group,a,d,r,s,i);let c=Object.assign({},t),u=t.cacheKey+[n.join("n,"),a.join(","),d.join(","),s.join(","),i.join(","),l.join(",")].join("_");return Object.assign(c,{kernelShape:n,pads:a,outputPadding:s,outputShape:i,dilations:l,strides:d,cacheKey:u}),c},Sh=t=>{let e=ro(t),n=t.format,r=["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 qe({autoPad:r,format:n,dilations:a,group:i,kernelShape:s,outputPadding:c,outputShape:u,pads:o,strides:l,wIsConst:d,...e})},bu=(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 n=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],r=t[1].dims[0];if(n!==r)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")},vu=[2,3,1,0],$u=(t,e,n)=>{let r=Hi(n,e),a=n.format==="NHWC",i=r.outputShape,s=i[a?3:1],o=e[0].dims[a?3:1];if(r.group!==1||s===1&&o===1){t.compute(As(e,r));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,f=a?s:l*d,g=c*u*o,w=!0,b=t.kernelCustomData.wT??t.compute(_n(e[1],vu),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=b);let y=[e[0],b],$=e.length===3;$&&(!a&&e[2].dims.length===1?y.push(e[2].reshape([e[2].dims[0],1,1])):y.push(e[2])),t.compute(xh(y,r,i,h,f,g,$,w),{inputs:y})},xu=(t,e)=>{let n=e.format==="NHWC",r=[t.inputs[0].reshape(n?[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]])];r.length===3&&r.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=Hi({...e,pads:o,strides:s,dilations:i,kernelShape:a},r);t.compute(As(r,l,d=>n?[d[0],d[2],d[3]]:[d[0],d[1],d[3]]))},Eh=(t,e)=>{bu(t.inputs,e),t.inputs[0].dims.length===3?xu(t,e):$u(t,t.inputs,e)}}),Su,kh,Ch,N_=X(()=>{Ye(),Ie(),ot(),Ce(),Su=(t,e,n,r)=>{let a=J.size(e),i=e.length,s=Q("input",t,i),o=ve("output",t,i),l=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),d=J.normalizeAxis(l,i),c=u=>{let h=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,f=xe("uniforms.input_shape","uniforms.axis",i),g=r.reverse?h+(r.exclusive?" + 1":""):"0",w=r.reverse?f:h+(r.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 = ${w}; - 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:r.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:e,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:"uint32",data:a},{type:"int32",data:d},...ie(e),...ie(e)]}),getShaderSource:c}},kh=(t,e)=>{let n=t.inputs[0].dims,r=t.inputs[0].dataType,a=t.inputs[1];t.compute(Su(r,n,a,e),{inputs:[0]})},Ch=t=>{let e=t.exclusive===1,n=t.reverse===1;return qe({exclusive:e,reverse:n})}}),Oa,xr,qi,Eu,ku,Cu,Tu,ji,Iu,Th,Ih,F_=X(()=>{Ie(),ot(),Ce(),Oa="[a-zA-Z]|\\.\\.\\.",xr="("+Oa+")+",qi="^"+xr+"$",Eu="("+xr+",)*"+xr,ku="^"+Eu+"$",Cu=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,e){let n=this.symbolToIndices.get(t);n===void 0?n=[e]:n.push(e),this.symbolToIndices.set(t,n)}},Tu=class{constructor(t,e){this.equation=e,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,r]=e.includes("->")?e.split("->",2):[e,""];if(!n.match(RegExp(ku)))throw new Error("Invalid LHS term");if(n.split(",").forEach((a,i)=>{let s=t[i].dims.slice();if(!a.match(RegExp(qi)))throw new Error("Invalid LHS term");let o=this.processTerm(a,!0,s,i);this.lhs.push(o)}),r==="")r+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!r.match(RegExp(xr)))throw new Error("Invalid RHS");r.match(RegExp(Oa,"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(r,!1,this.outputDims)}addSymbol(t,e,n){let r=this.symbolToInfo.get(t);if(r!==void 0){if(r.dimValue!==e&&r.count!==1)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:e,inputIndices:[n]};this.symbolToInfo.set(t,r)}processTerm(t,e,n,r=-1){let a=n.length,i=!1,s=[],o=0;if(!t.match(RegExp(qi))&&!e&&t!=="")throw new Error("Invalid LHS term");let l=t.match(RegExp(Oa,"g")),d=new Cu(r);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=n.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 f=0;ft+"_max",Iu=(t,e,n,r,a)=>{let i=e.map((h,f)=>t[f]?h.length:h).map((h,f)=>Q(`input${f}`,n,h)),s=J.size(a),o=st(a.length),l=o?a.length:a,d=ve("output",n,l),c=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),u=h=>{let f=[],g="var prod = 1.0;",w="var sum = 0.0;",b="sum += prod;",y=[],$=[],k=[],S=[],T=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((P,N)=>{if(r.rhs.symbolToIndices.has(N)){let V=r.rhs.symbolToIndices.get(N)?.[0];V!==void 0&&r.lhs.forEach((j,M)=>{if(P.inputIndices.includes(M)){let G=j.symbolToIndices.get(N);if(G===void 0)throw new Error("Invalid symbol error");G.forEach(O=>{f.push(`${i[M].indicesSet(`input${M}Indices`,O,d.indicesGet("outputIndices",V))}`)})}})}else r.lhs.forEach((V,j)=>{if(P.inputIndices.includes(j)){let M=V.symbolToIndices.get(N);if(M===void 0)throw new Error("Invalid symbol error");M.forEach(G=>{y.push(`${i[j].indicesSet(`input${j}Indices`,G,`${N}`)}`)}),S.push(`prod *= ${i[j].getByIndices(`input${j}Indices`)};`)}}),$.push(`for(var ${N}: u32 = 0; ${N} < uniforms.${ji(N)}; ${N}++) {`),k.push("}")});let A=T?[...f,`let sum = ${i.map((P,N)=>P.getByIndices(`input${N}Indices`)).join(" * ")};`]:[...f,w,...$,...y,g,...S,b,...k];return` - ${h.registerUniforms(c.map(P=>({name:`${ji(P)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,d)} - - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${d.offsetToIndices("global_idx")}; - ${i.map((P,N)=>`var input${N}Indices: ${i[N].type.indices};`).join(` -`)} - ${A.join(` -`)}; - ${d.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:t.map(h=>h?"rank":"dims")},getRunData:()=>{let h=c.filter(g=>r.symbolToInfo.has(g)).map(g=>({type:"uint32",data:r.symbolToInfo.get(g)?.dimValue||0}));h.push({type:"uint32",data:s});let f=e.filter((g,w)=>t[w]).map((g,w)=>[...ie(g)]).reduce((g,w)=>g.concat(w),h);return o&&f.push(...ie(a)),{outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:f}},getShaderSource:u}},Th=(t,e)=>{let n=new Tu(t.inputs,e.equation),r=t.inputs.map((s,o)=>st(s.dims.length)),a=n.outputDims,i=t.inputs.map((s,o)=>s.dims);t.compute(Iu(r,i,t.inputs[0].dataType,n,a))},Ih=t=>{let e=t.equation.replace(/\s+/g,"");return qe({equation:e})}}),Au,Ki,Mu,Ou,Ah,L_=X(()=>{Ye(),Ie(),Ce(),Au=t=>{if(!t||t.length!==2)throw new Error("Expand requires 2 input.");let e=t[0].dims,n=Array.from(t[1].getBigInt64Array(),Number),r=n.length{let n=t.length-e.length,r=[];for(let a=0;at.length>e.length?Ki(t,e):Ki(e,t),Ou=t=>{let e=t[0].dims,n=Array.from(t[1].getBigInt64Array(),Number),r=Mu(e,n),a=t[0].dataType,i=a===9?4:1,s=Math.ceil(J.size(r)/i),o=st(e.length),l=st(r.length),d=u=>{let h=o?e.length:e,f=l?r.length:r,g=Q("input",a,h,i),w=ve("output",a,f,i),b;if(a===9){let y=($,k,S="")=>` - let outputIndices${k} = ${w.offsetToIndices(`outputOffset + ${k}u`)}; - let offset${k} = ${g.broadcastedIndicesToOffset(`outputIndices${k}`,w)}; - let index${k} = offset${k} / 4u; - let component${k} = offset${k} % 4u; - ${$}[${k}] = ${S}(${g.getByOffset(`index${k}`)}[component${k}]); - `;b=` - let outputOffset = global_idx * ${i}; - var data = vec4(0); - ${y("data",0,"u32")} - ${y("data",1,"u32")} - ${y("data",2,"u32")} - ${y("data",3,"u32")} - ${w.setByOffset("global_idx","data")} - }`}else b=` - let outputIndices = ${w.offsetToIndices("global_idx")}; - let inputOffset = ${g.broadcastedIndicesToOffset("outputIndices",w)}; - ${w.setByOffset("global_idx",g.getByOffset("inputOffset"))} - }`;return` - ${u.registerUniform("vec_size","u32").declareVariables(g,w)} - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${b}`},c=[{type:"uint32",data:s}];return o&&c.push(...ie(e)),l&&c.push(...ie(r)),{name:"Expand",shaderCache:{hint:`${r.length}`,inputDependencies:[o?"rank":"dims"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c})}},Ah=t=>{Au(t.inputs),t.compute(Ou(t.inputs),{inputs:[0]})}}),zu,Ru,Mh,Oh,U_=X(()=>{Ye(),Ie(),ot(),Ce(),zu=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},Ru=(t,e)=>{let n=t[0].dims,r=t[1].dims,a=n.length,i=J.normalizeAxis(e.axis,a),s=n.slice(0);s.splice(i,1,...r);let o=n[i],l=t[0].dataType===9?4:1,d=Math.ceil(J.size(s)/l),c=st(t[0].dims.length),u=c?t[0].dims.length:t[0].dims,h=st(t[1].dims.length),f=h?t[1].dims.length:t[1].dims,g=st(s.length),w=g?s.length:s,b=[{type:"uint32",data:d},{type:"int32",data:o},{type:"uint32",data:i}];c&&b.push(...ie(t[0].dims)),h&&b.push(...ie(t[1].dims)),g&&b.push(...ie(s));let y=[];y.push(c?"rank":"dims"),y.push(h?"rank":"dims");let $=k=>{let S=Q("data",t[0].dataType,u,l),T=Q("inputIndices",t[1].dataType,f),A=ve("output",t[0].dataType,w,l),P=V=>{let j=r.length,M=`var indicesIndices${V} = ${T.type.indices}(0);`;for(let G=0;G1?`indicesIndices${V}[${G}]`:`indicesIndices${V}`} = ${s.length>1?`outputIndices${V}[uniforms.axis + ${G}]`:`outputIndices${V}`};`;M+=` - var idx${V} = ${T.getByIndices(`indicesIndices${V}`)}; - if (idx${V} < 0) { - idx${V} = idx${V} + uniforms.axisDimLimit; - } - var dataIndices${V} = ${S.type.indices}(0); - `;for(let G=0,O=0;G1?`dataIndices${V}[${G}]`:`dataIndices${V}`} = u32(idx${V});`,O+=j):(M+=`${a>1?`dataIndices${V}[${G}]`:`dataIndices${V}`} = ${s.length>1?`outputIndices${V}[${O}]`:`outputIndices${V}`};`,O++);return M},N;if(t[0].dataType===9){let V=(j,M,G="")=>` - let outputIndices${M} = ${A.offsetToIndices(`outputOffset + ${M}u`)}; - ${P(M)}; - let offset${M} = ${S.indicesToOffset(`dataIndices${M}`)}; - let index${M} = offset${M} / 4u; - let component${M} = offset${M} % 4u; - ${j}[${M}] = ${G}(${S.getByOffset(`index${M}`)}[component${M}]); - `;N=` - let outputOffset = global_idx * ${l}; - var value = vec4(0); - ${V("value",0,"u32")} - ${V("value",1,"u32")} - ${V("value",2,"u32")} - ${V("value",3,"u32")} - ${A.setByOffset("global_idx","value")} - `}else N=` - let outputIndices = ${A.offsetToIndices("global_idx")}; - ${P("")}; - let value = ${S.getByIndices("dataIndices")}; - ${A.setByOffset("global_idx","value")}; - `;return` - ${k.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(S,T,A)} - ${k.mainStart()} - ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${N} - }`};return{name:"Gather",shaderCache:{hint:e.cacheKey,inputDependencies:y},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:b}),getShaderSource:$}},Mh=t=>qe({axis:t.axis}),Oh=(t,e)=>{let n=t.inputs;zu(n),t.compute(Ru(t.inputs,e))}}),Bu,Pu,zh,Rh,W_=X(()=>{Ie(),ot(),Ce(),Bu=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.`)},Pu=(t,e)=>{let n=t[0].dims,r=t[0].dataType,a=n.length,i=t[1].dims,s=t[1].dataType,o=J.normalizeAxis(e.axis,a),l=n[o],d=i.slice(0),c=J.size(d),u=Q("input",r,a),h=Q("indicesInput",s,i.length),f=ve("output",r,d.length),g=[{type:"uint32",data:c},{type:"int32",data:l},{type:"uint32",data:o}];return g.push(...ie(n)),g.push(...ie(i)),g.push(...ie(d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:w=>` - ${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,h,f)} - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let outputIndices = ${f.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")}; - - ${f.setByOffset("global_idx","value")}; - }`}},zh=t=>qe({axis:t.axis}),Rh=(t,e)=>{let n=t.inputs;Bu(n),t.compute(Pu(t.inputs,e))}}),Du,Nu,Bh,Ph,V_=X(()=>{Ie(),Ce(),Du=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")},Nu=(t,e)=>{let n=t[0].dims.slice(),r=t[1].dims.slice(),[a,i,s]=Qc.getShapeOfGemmResult(n,e.transA,r,e.transB,t.length===3?t[2].dims:void 0),o=[a,i];if(!o)throw new Error("Can't use gemm on the given tensors");let l=J.size(o),d=[{type:"uint32",data:l},{type:"uint32",data:a},{type:"uint32",data:i},{type:"uint32",data:s},{type:"float32",data:e.alpha},{type:"float32",data:e.beta}],c=["type","type"];t.length===3&&(d.push(...ie(t[2].dims)),c.push("rank")),d.push(...ie(o));let u=h=>{let f="";e.transA&&e.transB?f="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":e.transA&&!e.transB?f="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!e.transA&&e.transB?f="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!e.transA&&!e.transB&&(f="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let g=e.alpha===1?"":"value *= uniforms.alpha;",w=Q("a",t[0].dataType,t[0].dims),b=Q("b",t[1].dataType,t[1].dims),y=w.type.value,$=null,k=[w,b];t.length===3&&($=Q("c",t[2].dataType,t[2].dims.length),k.push($));let S=ve("output",t[0].dataType,o.length);k.push(S);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(...k)} - - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let m = global_idx / uniforms.N; - let n = global_idx % uniforms.N; - - var value = ${y}(0); - for (var k: u32 = 0u; k < uniforms.K; k++) { - ${f} - } - - ${g} - ${$!=null?`let cOffset = ${$.broadcastedIndicesToOffset("vec2(m, n)",S)}; value += ${y}(uniforms.beta) * ${$.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}},Bh=t=>{let e=t.transA,n=t.transB,r=t.alpha,a=t.beta;return{transA:e,transB:n,alpha:r,beta:a,cacheKey:`${t.transA};${t.transB};${t.alpha===1}`}},Ph=(t,e)=>{Du(t.inputs),t.compute(Nu(t.inputs,e))}}),Fu,Lu,Uu,Dh,G_=X(()=>{Ye(),Ie(),Ce(),Fu=(t,e)=>{let n=t[0].dims,r=n,a=2,i=J.sizeToDimension(n,a),s=J.sizeFromDimension(n,a),o=$t(s),l=s/o,d=[n[0],n[1],l],c=["rank","type","type"],u=[{type:"uint32",data:s},{type:"uint32",data:l}];u.push(...ie(d),...ie(d));let h=f=>{let g=Q("x",t[0].dataType,d.length,o),w=Q("scale",t[1].dataType,t[1].dims),b=Q("bias",t[2].dataType,t[2].dims),y=ve("output",t[0].dataType,d.length,o),$=[g,w,b,y],k=g.type.value,S=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<${S}, ${T}>; - const workgroupSize = ${T}u; - ${f.registerUniforms(A).declareVariables(...$)} - ${f.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 = ${S}(0); - for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { - initial = initial + ${S}(${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 = ${Qt("workgroupShared[0]",o)} / f32(uniforms.normSize); - } - workgroupBarrier(); - - // reinitialize workgroup memory. - initial = ${S}(0); - for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { - let deviation = ${S}(${g.get("batch","channel","h")}) - ${S}(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 = ${Qt("workgroupShared[0]",o)}; - } - workgroupBarrier(); - - let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); - let channelScale = invStdDev * f32(${w.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")} * ${k}(${S}(channelScale)) + ${k}(${S}(channelShift)); - ${y.set("batch","channel","h","value")}; - } - }`};return{name:"InstanceNormalization",shaderCache:{hint:`${e.epsilon};${o}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:i},programUniforms:u}),getShaderSource:h}},Lu=(t,e,n,r,a,i,s,o)=>{let l=$t(s),d=64,c=l===1?"vec2f":`mat2x${l}f`,u=l===1?"f32":`vec${l}f`,h=(A,P)=>`${c}(${A}, ${P})`,f=a*s/l,g=Math.ceil(i/d),w=["type"],b=[{type:"uint32",data:g},{type:"uint32",data:i},{type:"uint32",data:Math.floor(s/l)},{type:"uint32",data:Math.floor(i*s/l)}],y=A=>{let P=Q("input",e.dataType,e.dims,l);return` - ${A.declareVariables(P)} - @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 = ${vt("f32",l)}; - var squaredSum = ${vt("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")}; - }`},$=t.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:[a,s,d,2],dataType:1}],dispatchGroup:{x:a*s/l},programUniforms:b}),getShaderSource:y},{inputs:[e],outputs:[-1]})[0],k=[{type:"uint32",data:f},{type:"uint32",data:i},{type:"uint32",data:Math.floor(s/l)},{type:"uint32",data:Math.floor(d*s/l)}],S=["type","type","type"],T=A=>{let P=Q("scale",n.dataType,n.dims,l),N=Q("bias",r.dataType,r.dims,l);return` - @group(0) @binding(0) var input : array<${c}>; - @group(0) @binding(1) var scale : array<${P.type.storage}>; - @group(0) @binding(2) var bias : array<${N.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 = ${vt("f32",l)}; - var squaredSum = ${vt("f32",l)}; - for (var i: u32 = 0; i < ${d}; 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:S},getRunData:()=>({outputs:[{dims:[a,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:k}),getShaderSource:T},{inputs:[$,n,r],outputs:[-1]})[0]},Uu=(t,e,n)=>{let r=e[0].dims,a=r,i=r[0],s=r[r.length-1],o=J.sizeFromDimension(r,1)/s,l=$t(s),d=J.size(a)/l,c=[{type:"uint32",data:o},{type:"uint32",data:Math.floor(s/l)}],u=["type","type"],h=Lu(t,e[0],e[1],e[2],i,o,s,n.epsilon),f=g=>{let w=At(e[0].dataType),b=l===1?"vec2f":`mat2x${l}f`,y=l===1?w:`vec${l}<${w}>`,$=Q("input",e[0].dataType,e[0].dims,l),k=ve("output",e[0].dataType,a,l);return` - @group(0) @binding(0) var input : array<${$.type.storage}>; - @group(0) @binding(1) var scaleInput : array<${b}>; - @group(0) @binding(2) var output : array<${k.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], ${y}(scale[0]), ${y}(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:f},{inputs:[e[0],h]})},Dh=(t,e)=>{e.format==="NHWC"?Uu(t,t.inputs,e):t.compute(Fu(t.inputs,e))}}),Wu,Vu,Nh,H_=X(()=>{Ye(),Ie(),Ce(),Wu=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Vu=(t,e,n)=>{let r=t[0].dims,a=t[1],i=t[2],s=r,o=J.normalizeAxis(e.axis,r.length),l=J.sizeToDimension(r,o),d=J.sizeFromDimension(r,o),c=J.size(a.dims),u=i?J.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 S=0;S1,y=n>2,$=S=>{let T=At(t[0].dataType),A=[Q("x",t[0].dataType,t[0].dims,f),Q("scale",a.dataType,a.dims,f)];i&&A.push(Q("bias",i.dataType,i.dims,f)),A.push(ve("output",t[0].dataType,s,f)),b&&A.push(ve("mean_data_output",1,h)),y&&A.push(ve("inv_std_output",1,h));let P=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` - ${S.registerUniforms(P).declareVariables(...A)} - ${S.mainStart()} - ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} - let offset = global_idx * uniforms.norm_size_vectorized; - var meanVector = ${vt("f32",f)}; - var meanSquareVector = ${vt("f32",f)}; - - for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${rn(T,f,"x[h + offset]")}; - meanVector += value; - meanSquareVector += value * value; - } - let mean = ${Qt("meanVector",f)} / uniforms.norm_size; - let invStdDev = - inverseSqrt(${Qt("meanSquareVector",f)} / uniforms.norm_size - mean * mean + uniforms.epsilon); - - for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { - let f32input = ${rn(T,f,"x[j + offset]")}; - let f32scale = ${rn(T,f,"scale[j]")}; - output[j + offset] = ${A[0].type.value}((f32input - mean) * invStdDev * f32scale - ${i?`+ ${rn(T,f,"bias[j]")}`:""} - ); - } - - ${b?"mean_data_output[global_idx] = mean":""}; - ${y?"inv_std_output[global_idx] = invStdDev":""}; - }`},k=[{dims:s,dataType:t[0].dataType}];return b&&k.push({dims:h,dataType:1}),y&&k.push({dims:h,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${n}`,inputDependencies:g},getRunData:()=>({outputs:k,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:w}),getShaderSource:$}},Nh=(t,e)=>{Wu(t.inputs),t.compute(Vu(t.inputs,e,t.outputCount))}}),Gu,Fh,Yi,Hu,za,Lh,q_=X(()=>{Ie(),ot(),Zs(),Sp(),Ce(),Hr(),Gu=(t,e)=>{let n=t[0],r=t[1],a=t[2],i=t[3],s=t[4],o=t[5],l=t[6],d=t[7];if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,u=n.dims[0],h=n.dims[1],f=n.dims.length===3?c?n.dims[2]/3:n.dims[2]:e.numHeads*n.dims[4],g=h,w=0,b=0,y=Math.floor(f/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');w=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 $;if(r){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(r.dims.length===3){if(r.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');$=2,g=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==e.numHeads||r.dims[3]!==2||r.dims[4]!==y)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.');$=5,g=r.dims[1]}else{if(r.dims[1]!==e.numHeads||r.dims[3]!==y)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,g=r.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(n.dims.length===5&&(n.dims[2]!==e.numHeads||n.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(a&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let k=0;if(s){k=8;let N=s.dims;throw N.length===1?N[0]===u?k=1:N[0]===3*u+2&&(k=3):N.length===2&&N[0]===u&&N[1]===g&&(k=5),k===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let S=!1,T=f;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(n.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],S=!0}}let A=w+g,P=!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:w,kvSequenceLength:g,totalSequenceLength:A,maxSequenceLength:b,inputHiddenSize:0,hiddenSize:f,vHiddenSize:T,headSize:y,vHeadSize:Math.floor(T/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:k,scale:e.scale,broadcastResPosBias:P,passPastInKv:S,qkvFormat:$}},Fh=t=>qe({...t}),Yi=qe({perm:[0,2,1,3]}),Hu=(t,e,n,r,a,i,s)=>{let o=[r,a,i],l=J.size(o),d=[{type:"uint32",data:l},{type:"uint32",data:s},{type:"uint32",data:i}],c=u=>{let h=ve("qkv_with_bias",e.dataType,o),f=Q("qkv",e.dataType,o),g=Q("bias",n.dataType,o),w=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${u.registerUniforms(w).declareVariables(f,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,n],outputs:[-1]})[0]},za=(t,e,n,r,a,i,s,o)=>{let l=i;if(s){if(r===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Hu(t,i,s,e,r,n*a,o),l=l.reshape([e,r,n,a]),t.compute(_n(l,Yi.perm),{inputs:[l],outputs:[-1]})[0]}else return i.dims.length===3&&(l=i.reshape([e,r,n,a])),t.compute(_n(l,Yi.perm),{inputs:[l],outputs:[-1]})[0]},Lh=(t,e)=>{let n=Gu(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 r=t.inputs[1]&&t.inputs[2]&&t.inputs[1].dims.length===4&&t.inputs[2].dims.length===4,a=za(t,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.inputs[0],t.inputs[3],0);if(r)return Ja(t,a,t.inputs[1],t.inputs[2],t.inputs[4],void 0,void 0,void 0,t.inputs[5],n,e);let i=za(t,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,t.inputs[1],t.inputs[3],n.hiddenSize),s=za(t,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,t.inputs[2],t.inputs[3],2*n.hiddenSize);Ja(t,a,i,s,t.inputs[4],void 0,t.inputs[6],t.inputs[7],t.inputs[5],n,e)}}),qu,ju,Ku,Yu,Xu,Qu,Zu,Ju,Uh,j_=X(()=>{Ye(),Ie(),Ce(),qu=t=>{if(!t||t.length<1)throw new Error("Too few inputs");if(t[0].dataType!==1)throw new Error("Input type must be float.");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].")}},ju=(t,e,n)=>{let r="";for(let a=e-1;a>=0;--a)r+=` - k = i32(${t.indicesGet("indices",a)}) - ${xe("uniforms.pads",a,n)}; - if (k < 0) { - break; - } - if (k >= i32(${xe("uniforms.x_shape",a,e)})) { - break; - } - offset += k * i32(${xe("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; - ${r} - value = x[offset]; - } - `},Ku=(t,e,n)=>{let r="";for(let a=e-1;a>=0;--a)r+=` - k = i32(${t.indicesGet("indices",a)}) - ${xe("uniforms.pads",a,n)}; - if (k < 0) { - k = -k; - } - { - let _2n_1 = 2 * (i32(${xe("uniforms.x_shape",a,e)}) - 1); - k = k % _2n_1; - if(k >= i32(${xe("uniforms.x_shape",a,e)})) { - k = _2n_1 - k; - } - } - offset += k * i32(${xe("uniforms.x_strides",a,e)}); - `;return` - var offset = 0; - var k = 0; - ${r} - value = x[offset]; - `},Yu=(t,e,n)=>{let r="";for(let a=e-1;a>=0;--a)r+=` - k = i32(${t.indicesGet("indices",a)}) - ${xe("uniforms.pads",a,n)}; - if (k < 0) { - k = 0; - } - if (k >= i32(${xe("uniforms.x_shape",a,e)})) { - k = i32(${xe("uniforms.x_shape",a,e)}) - 1; - } - offset += k * i32(${xe("uniforms.x_strides",a,e)}); - `;return` - var offset = 0; - var k = 0; - ${r} - value = x[offset]; - `},Xu=(t,e,n)=>{let r="";for(let a=e-1;a>=0;--a)r+=` - k = i32(${t.indicesGet("indices",a)}) - ${xe("uniforms.pads",a,n)}; - if (k < 0) { - k += i32(${xe("uniforms.x_shape",a,e)}]); - } - if (k >= i32(${xe("uniforms.x_shape",a,e)})) { - k -= i32(${xe("uniforms.x_shape",a,e)}); - } - offset += k * i32(${xe("uniforms.x_strides",a,e)}); - `;return` - var offset = 0; - var k = 0; - ${r} - value = x[offset]; - `},Qu=(t,e,n)=>{switch(n.mode){case 0:return ju(t,e,n.pads.length);case 1:return Ku(t,e,n.pads.length);case 2:return Yu(t,e,n.pads.length);case 3:return Xu(t,e,n.pads.length);default:throw new Error("Invalid mode")}},Zu=(t,e)=>{let n=J.padShape(t[0].dims.slice(),e.pads),r=t[0].dims,a=[{type:"uint32",data:J.size(n)},{type:"uint32",data:e.pads}];if(e.mode===0){let o=Yt(t[0].dataType);a.push({type:o,data:e.value})}a.push(...ie(t[0].dims),...ie(n));let i=["rank"],s=o=>{let l=ve("output",t[0].dataType,n.length),d=Q("x",t[0].dataType,r.length),c=d.type.value,u=Qu(l,r.length,e),h=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&h.push({name:"constant_value",type:c}),` - ${o.registerUniforms(h).declareVariables(d,l)} - ${o.mainStart()} - ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${l.offsetToIndices("global_idx")}; - - var value = ${c}(0); - ${u} - output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${e.mode}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(J.size(n)/64)},programUniforms:a}),getShaderSource:s}},Ju=(t,e)=>{if(t.length>1){let n=t[1].getBigInt64Array(),r=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:r,pads:s}}else return e},Uh=(t,e)=>{qu(t.inputs);let n=Ju(t.inputs,e);t.compute(Zu(t.inputs,n),{inputs:[0]})}}),Sr,Xi,Qi,Zi,Ji,ed,td,es,ts,Wh,Vh,ns,Gh,Hh,rs,qh,jh,Kh,Yh,K_=X(()=>{Vt(),Ie(),Ce(),Sr=t=>{if(Ne.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},Xi=(t,e,n)=>{let r=e.format==="NHWC",a=t.dims.slice();r&&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();Qa.adjustPoolAttributes(n,a,s,o,l,d);let c=Qa.computePoolOutputShape(n,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,r?h:c]},Qi=(t,e)=>{let n=e.format==="NHWC",r=J.size(t),a=J.size(e.kernelShape),i=[{type:"uint32",data:r},{type:"uint32",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:"uint32",data:o},{type:"uint32",data:l},{type:"uint32",data:d},{type:"uint32",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 f=e.kernelShape[e.kernelShape.length-2],g=e.strides[e.strides.length-2],w=e.pads[e.pads.length/2-2],b=e.pads[e.pads.length-2];h=!!(w+b),i.push({type:"uint32",data:f},{type:"uint32",data:g},{type:"uint32",data:w},{type:"uint32",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(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let o=J.computeStrides(e.kernelShape);i.push({type:"uint32",data:o},{type:"uint32",data:e.pads},{type:"uint32",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]}},Zi=(t,e,n,r,a,i,s,o,l,d,c,u)=>{let h=a.format==="NHWC",f=e.type.value,g=ve("output",e.type.tensor,r);if(a.kernelShape.length<=2){let w="",b="",y="",$=n-(h?2:1);if(c?w=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i; - if (xIndices[${$}] < 0 || xIndices[${$}] - >= uniforms.x_shape[${$}]) { - pad++; - continue; - } - let x_val = x[${e.indicesToOffset("xIndices")}]; - ${i} - }`:w=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i; - let x_val = x[${e.indicesToOffset("xIndices")}]; - ${i} - }`,a.kernelShape.length===2){let k=n-(h?3:2);u?b=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; - if (xIndices[${k}] < 0 || xIndices[${k}] >= uniforms.x_shape[${k}]) { - pad += i32(uniforms.kw); - continue; - } - `:b=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; - `,y=` - } - `}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 = ${f}(${o}); - var pad = 0; - ${b} - ${w} - ${y} - ${s} - - output[global_idx] = value; - }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let w=a.kernelShape.length,b=a.pads.length,y="";return d?y=` - if (xIndices[j] >= uniforms.x_shape[j]) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - let x_val = x[${e.indicesToOffset("xIndices")}]; - ${i} - }`:y=` - } - 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 = ${f}(${o}); - var pad = 0; - var isPad = false; - - for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { - var offset = i; - for (var j = 0u; j < ${w-1}u; j++) { - offsets[j] = offset / ${xe("uniforms.kernelStrides","j",w)}; - offset -= offsets[j] * ${xe("uniforms.kernelStrides","j",w)}; - } - offsets[${w-1}] = offset; - - isPad = false; - for (var j = ${n-w}u; j < ${n}u; j++) { - xIndices[j] = indices[j] * ${xe("uniforms.strides",`j - ${n-w}u`,w)} - + offsets[j - ${n-w}u] - ${xe("uniforms.pads","j - 2u",b)}; - ${y} - } - ${s} - - output[global_idx] = value; - }`}},Ji=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,ed=t=>`${Ji(t)};${t.countIncludePad}`,td=t=>`${Ji(t)};${t.storageOrder};${t.dilations}`,es=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}),ts=(t,e,n,r)=>{let[a,i]=Xi(e,r,n),s=Q("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,f,g]=Qi(i,a);c.push(...ie(e.dims),...ie(i));let w=["rank"];return{name:t,shaderCache:{hint:`${r.cacheKey};${h};${f};${g}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(J.size(i)/64)},programUniforms:c}),getShaderSource:b=>Zi(b,s,e.dims.length,i.length,a,l,d,0,u,h,f,g)}},Wh=t=>{let e=t.count_include_pad!==0,n=es(t);if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let r={countIncludePad:e,...n,cacheKey:""};return{...r,cacheKey:ed(r)}},Vh=(t,e)=>{Sr(t.inputs),t.compute(ts("AveragePool",t.inputs[0],!1,e))},ns={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Gh=t=>{let e=t.format;return{format:e,...ns,cacheKey:e}},Hh=(t,e)=>{Sr(t.inputs),t.compute(ts("GlobalAveragePool",t.inputs[0],!0,e))},rs=(t,e,n,r)=>{let[a,i]=Xi(e,r,n),s=` - value = max(x_val, value); - `,o="",l=Q("x",e.dataType,e.dims.length),d=["rank"],[c,u,h,f,g]=Qi(i,a);return c.push(...ie(e.dims),...ie(i)),{name:t,shaderCache:{hint:`${r.cacheKey};${h};${f};${g}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(J.size(i)/64)},programUniforms:c}),getShaderSource:w=>Zi(w,l,e.dims.length,i.length,a,s,o,-1e5,u,h,f,g)}},qh=(t,e)=>{Sr(t.inputs),t.compute(rs("MaxPool",t.inputs[0],!1,e))},jh=t=>{let e=t.storage_order,n=t.dilations,r=es(t);if(e!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let a={storageOrder:e,dilations:n,...r,cacheKey:""};return{...a,cacheKey:td(a)}},Kh=t=>{let e=t.format;return{format:e,...ns,cacheKey:e}},Yh=(t,e)=>{Sr(t.inputs),t.compute(rs("GlobalMaxPool",t.inputs[0],!0,e))}}),nd,rd,Xh,Y_=X(()=>{Vt(),Ye(),Ce(),nd=(t,e,n)=>{let r=t===e,a=te&&n>0;if(r||a||i)throw new Error("Range these inputs' contents are invalid.")},rd=(t,e,n,r)=>{let a=Math.abs(Math.ceil((e-t)/n)),i=[a],s=a,o=Yt(r),l=[{type:"uint32",data:s},{type:o,data:t},{type:o,data:n},...ie(i)],d=c=>{let u=ve("output",r,i.length),h=u.type.value,f=[{name:"outputSize",type:"u32"},{name:"start",type:h},{name:"delta",type:h}];return` - ${c.registerUniforms(f).declareVariables(u)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - output[global_idx] = uniforms.start + ${h}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l})}},Xh=t=>{let e=0,n=0,r=0;t.inputs[0].dataType===6?(e=t.inputs[0].getInt32Array()[0],n=t.inputs[1].getInt32Array()[0],r=t.inputs[2].getInt32Array()[0]):t.inputs[0].dataType===1&&(e=t.inputs[0].getFloat32Array()[0],n=t.inputs[1].getFloat32Array()[0],r=t.inputs[2].getFloat32Array()[0]),Ne.webgpu.validateInputContent&&nd(e,n,r),t.compute(rd(e,n,r,t.inputs[0].dataType),{inputs:[]})}}),ad,id,sd,od,ld,ud,dd,cd,pd,hd,fd,as,md,gd,_d,wd,yd,Qh,Zh,X_=X(()=>{Ie(),ot(),Ce(),ad=(t,e)=>{if(t.every(n=>n>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")}},id=(t,e,n)=>{e.every(a=>a>=0&&a{throw new Error("Resize requires axes input values to be positive and less than rank")}));let r=new Array(n).fill(1);return e.forEach((a,i)=>r[a]=t[i]),r},sd=(t,e,n,r,a,i)=>{let[s,o,l]=n>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=>r.push(c)),r.length!==0&&r.length!==d&&n>=18&&r.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");ad(r,e),e.axes.length>0&&id(r,e.axes,d).forEach((c,u)=>r[u]=c)}if(l>0&&t.length>l&&(t[l].getBigInt64Array().forEach(c=>a.push(Number(c))),a.length!==d||n>=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(r.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 r<"u"&&typeof a<"u"&&r.length>0&&a.length>d)throw new Error("Resize requires only of scales or sizes to be specified")},od=(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`)}})()+"}",ld=(t,e,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{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`)}})()+"}",ud=(t,e,n)=>{let r=new Array(n).fill(0).concat(new Array(n).fill(1)),a=t.length===0?r:t.slice();return e.length>0?(e.forEach((i,s)=>{r[i]=a[s],r[s+n]=a[e.length+s]}),r):a},dd=(t,e,n,r)=>{let a=[];if(n.length>0)if(r.length>0){if(t.forEach(i=>a.push(i)),Math.max(...r)>t.length)throw new Error("axes is out of bound");r.forEach((i,s)=>a[i]=n[s])}else n.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},cd=(t,e,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map(i=>e[i]),Number.MAX_VALUE):Math.min(...e,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map(i=>e[i]),Number.MIN_VALUE):Math.max(...e,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();e.fill(1,0,e.length);let a=t.slice();return n.axes.length>0?(n.axes.forEach(i=>e[i]=r),n.axes.forEach(i=>a[i]=Math.round(t[i]*e[i]))):(e.fill(r,0,e.length),a.forEach((i,s)=>a[s]=Math.round(i*e[s]))),a},pd=(t,e,n,r,a)=>` - fn calculateOriginalIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> array<${t.type.value}, ${n.length}> { - var original_indices: array<${t.type.value}, ${n.length}>; - for (var i:u32 = 0; i < ${n.length}; i++) { - var output_index = ${t.indicesGet("output_indices","i")}; - var scale = ${xe("uniforms.scales","i",r)}; - var roi_low = ${xe("uniforms.roi","i",a)}; - var roi_hi = ${xe("uniforms.roi",`i + ${e.length}`,a)}; - if (scale == 1.0) { - original_indices[i] = ${t.type.value}(output_index); - } else { - var input_shape_i = ${xe("uniforms.input_shape","i",e.length)}; - var output_shape_i = ${xe("uniforms.output_shape","i",n.length)}; - original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - } - } - return original_indices; - }`,hd=(t,e,n,r,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 < ${r.length}; i++) { - var output_index = ${e.indicesGet("output_indices","i")}; - var input_index: u32; - var scale = ${xe("uniforms.scales","i",a)}; - if (scale == 1.0) { - input_index = output_index; - } else { - var roi_low = ${xe("uniforms.roi","i",i)}; - var roi_hi = ${xe("uniforms.roi",`i + ${n.length}`,i)}; - var input_shape_i = ${xe("uniforms.input_shape","i",n.length)}; - var output_shape_i = ${xe("uniforms.output_shape","i",r.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; - }`,fd=(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 >= ${xe("uniforms.input_shape","i",e.length)}) { - return false; - } - } - return true; - }`,as=(t,e,n,r)=>t.rank>r?` - ${t.indicesSet("input_indices",e,"channel")}; - ${t.indicesSet("input_indices",n,"batch")}; -`:"",md=(t,e,n,r,a)=>{let[i,s,o,l]=n.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, ${n[s]} - 1))`)}; - ${t.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)}; - ${as(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}]; - ${r?`if (row < 0 || row > (${n[s]} - 1) || col < 0 || col > (${n[o]} - 1)) { - return ${a}; - }`:""}; - row = max(0, min(row, ${n[s]} - 1)); - col = max(0, min(col, ${n[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 = ${n.length>2?`u32(originalIndices[${l}])`:"0"}; - var batch: u32 = ${n.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); - }`},gd=(t,e,n,r,a,i,s,o,l,d)=>{let c=n.length===2,[u,h]=c?[0,1]:[2,3],f=t.type.value,g=w=>{let b=w===u?"row":"col";return` - fn ${b}CubicInterpolation(input_indices: ${t.type.indices}, output_indices: ${e.type.indices}) -> ${f} { - var output_index = ${e.indicesGet("output_indices",w)}; - var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[w]}, - ${r[w]}, ${n[w]}, ${i[w]}, ${i[w]} + ${n.length}); - var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); - var coefs = getCubicInterpolationCoefs(fractOriginalIdx); - - if (${o} && (originalIdx < 0 || originalIdx > (${n[w]} - 1))) { - return ${l}; - } - var data: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); - for (var i: i32 = -1; i < 3; i++) { - var ${b}: ${f} = originalIdx + ${f}(i); - if (${b} < 0 || ${b} >= ${n[w]}) { - ${d?`coefs[i + 1] = 0.0; - continue;`:o?`return ${l};`:`${b} = max(0, min(${b}, ${n[w]} - 1));`}; - } - var input_indices_copy: ${t.type.indices} = input_indices; - ${t.indicesSet("input_indices_copy",w,`u32(${b})`)}; - data[i + 1] = ${w===u?t.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; - } - return cubicInterpolation1D(data, coefs); - }`};return` - ${g(u)}; - ${g(h)}; - fn getCubicInterpolationCoefs(s: ${f}) -> array<${f}, 4> { - var absS = abs(s); - var coeffs: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); - var oneMinusAbsS: ${f} = 1.0 - absS; - var twoMinusAbsS: ${f} = 2.0 - absS; - var onePlusAbsS: ${f} = 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<${f}, 4>, coefs: array<${f}, 4>) -> ${f} { - var coefsSum: ${f} = 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}) -> ${f} { - var input_indices: ${t.type.indices} = output_indices; - return colCubicInterpolation(input_indices, output_indices); - } - `},_d=(t,e,n,r,a)=>{let[i,s,o,l,d]=n.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, ${n[s]} - 1))`)}; - ${t.indicesSet("input_indices",o,`max(0, min(height, ${n[o]} - 1))`)}; - ${t.indicesSet("input_indices",l,`max(0, min(width, ${n[l]} - 1))`)}; - ${as(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}]; - ${r?`if (depth < 0 || depth > (${n[s]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[l]} - 1)) { - return ${a}; - }`:""}; - - depth = max(0, min(depth, ${n[s]} - 1)); - height = max(0, min(height, ${n[o]} - 1)); - width = max(0, min(width, ${n[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 = ${n.length>3?`u32(originalIndices[${d}])`:"0"}; - var batch: u32 = ${n.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); - }`},wd=(t,e,n,r,a,i)=>{let s=t.dims,o=ud(i,e.axes,s.length),l=dd(s,r,a,e.axes),d=r.slice();r.length===0&&(d=s.map(($,k)=>$===0?1:l[k]/$),e.keepAspectRatioPolicy!=="stretch"&&(l=cd(s,d,e)));let c=ve("output",t.dataType,l.length),u=Q("input",t.dataType,s.length),h=J.size(l),f=s.length===l.length&&s.every(($,k)=>$===l[k]),g=e.coordinateTransformMode==="tf_crop_and_resize",w=e.extrapolationValue,b=u.type.value,y=$=>` - ${f?"":` - ${od(e.coordinateTransformMode,b)}; - ${(()=>{switch(e.mode){case"nearest":return` - ${fd(u,s)}; - ${ld(e.nearestMode,n,b)}; - ${hd(u,c,s,l,d.length,o.length,g)}; - `;case"linear":return` - ${pd(c,s,l,d.length,o.length)}; - ${(()=>{if(s.length===2||s.length===4)return`${md(u,c,s,g,w)}`;if(s.length===3||s.length===5)return`${_d(u,c,s,g,w)}`;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`${gd(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")}})()}; - `} - ${$.registerUniform("output_size","u32").registerUniform("scales","f32",d.length).registerUniform("roi","f32",o.length).declareVariables(u,c)} - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${f?"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}|${n}|${d.length>0?d:""}|${a.length>0?a:""}|${o.length>0?o:""}|${f}|${s}`,inputDependencies:["rank"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:"uint32",data:h},{type:"float32",data:d},{type:"float32",data:o},...ie(s),...ie(l)]})}},yd=t=>{let e=t.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},Qh=(t,e)=>{let n=[],r=[],a=[],i=yd(t);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");sd(t.inputs,e,i,n,r,a),t.compute(wd(t.inputs[0],e,i,n,r,a),{inputs:[0]})},Zh=t=>{let e=t.antialias,n=t.axes,r=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:n,coordinateTransformMode:r,cubicCoeffA:a,excludeOutside:i,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:d})}}),bd,vd,Jh,ef,Q_=X(()=>{Ye(),Ie(),ot(),Ce(),bd=t=>{if(!t||t.length<3)throw new Error("layerNorm requires at least 3 inputs.");let e=t[0],n=t[1],r=t[2];if(e.dataType!==n.dataType||e.dataType!==r.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(n.dims.length!==3&&n.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(n.dims[n.dims.length-1]!==a)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(r.dims.length!==1)throw new Error("Gamma must be 1D");if(r.dims[r.dims.length-1]!==a)throw new Error("Gamma must have the same hidden size as input");if(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")}},vd=(t,e,n,r)=>{let a=t[0].dims,i=J.size(a),s=a,o=i,l=a.slice(-1)[0],d=r?a.slice(0,-1).concat(1):[],c=t.length>3,u=t.length>4,h=r&&n>1,f=r&&n>2,g=n>3,w=$t(l),b=[Q("x",t[0].dataType,t[0].dims,w),Q("skip",t[1].dataType,t[1].dims,w),Q("gamma",t[2].dataType,t[2].dims,w)];c&&b.push(Q("beta",t[3].dataType,t[3].dims,w)),u&&b.push(Q("bias",t[4].dataType,t[4].dims,w)),b.push(ve("output",t[0].dataType,s,w)),h&&b.push(ve("meanOutput",1,d)),f&&b.push(ve("invStdOutput",1,d)),g&&b.push(ve("inputSkipBiasSum",t[0].dataType,s,w));let y=At(t[0].dataType),$=S=>` - const hiddenSize: f32 = ${l}; - const hiddenSizeVectorized: u32 = ${l/w}; - const epsilon: f32 = ${e.epsilon}; - - ${S.declareVariables(...b)} - - ${S.mainStart()} - ${S.guardAgainstOutOfBoundsWorkgroupSizes(o/l)} - let offset = global_idx * hiddenSizeVectorized; - var sum = ${vt("f32",w)}; - var squareSum = ${vt("f32",w)}; - for (var i: u32 = 0; i < hiddenSizeVectorized; i++) { - let skipValue = skip[offset + i]; - let biasValue = ${u?"bias[i]":"0.0"}; - let inputValue = x[offset + i]; - let value = inputValue + skipValue + biasValue; - ${g?"inputSkipBiasSum[offset + i] = value;":""} - output[offset + i] = value; - let f32Value = ${rn(y,w,"value")}; - sum += f32Value; - squareSum += f32Value * f32Value; - } - let mean = ${Qt("sum",w)} / hiddenSize; - let invStdDev = inverseSqrt(${Qt("squareSum",w)} / hiddenSize - mean * mean + epsilon); - ${h?"meanOutput[global_idx] = mean;":""} - ${f?"invStdOutput[global_idx] = invStdDev;":""} - for (var i: u32 = 0; i < hiddenSizeVectorized; i++) { - output[offset + i] = (output[offset + i] - ${y}(mean)) * ${y}(invStdDev) * gamma[i] - + ${c?"beta[i]":"0.0"}; - } - }`,k=[{dims:s,dataType:t[0].dataType}];return n>1&&k.push({dims:d,dataType:1}),n>2&&k.push({dims:d,dataType:1}),n>3&&k.push({dims:a,dataType:t[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:e.cacheKey},getShaderSource:$,getRunData:()=>({outputs:k,dispatchGroup:{x:Math.ceil(o/l/64)}})}},Jh=(t,e)=>{bd(t.inputs);let n=[0];t.outputCount>1&&n.push(-3),t.outputCount>2&&n.push(-3),t.outputCount>3&&n.push(3),t.compute(vd(t.inputs,e,t.outputCount,!1),{outputs:n})},ef=t=>{let e=t.epsilon;return qe({epsilon:e})}}),$d,Er,xd,is,Sd,Ed,tf,nf,Z_=X(()=>{Ye(),Ie(),ot(),Ce(),$d=(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((n,r)=>{if(t[r+1].dataType!==6&&t[r+1].dataType!==7)throw new Error(`Input ${r} must be an array of int32 or int64`)})},Er=(t,e)=>{let n=[];if(t.length>e)if(t[e].dataType===7)t[e].getBigInt64Array().forEach(r=>n.push(Number(r)));else if(t[e].dataType===6)t[e].getInt32Array().forEach(r=>n.push(Number(r)));else throw new Error(`Input ${e} must be an array of int32 or int64`);return n},xd=(t,e)=>{if(t.length>1){let n=Er(t,1),r=Er(t,2),a=Er(t,3);return a.length===0&&(a=[...Array(t[0].dims.length).keys()]),qe({starts:n,ends:r,axes:a})}else return e},is=(t,e,n,r,a)=>{let i=t;return t<0&&(i+=n[r[e]]),a[e]<0?Math.max(0,Math.min(i,n[r[e]]-1)):Math.max(0,Math.min(i,n[r[e]]))},Sd=(t,e,n)=>`fn calculateInputIndices(output_indices: ${e.type.indices}) -> ${t.type.indices} { - var input_indices: ${t.type.indices}; - var carry = 0u; - for (var i = ${n.length}; i >= 0; i--) { - let input_shape_i = ${xe("uniforms.input_shape","i",n.length)}; - let steps_i = ${xe("uniforms.steps","i",n.length)}; - let signs_i = ${xe("uniforms.signs","i",n.length)}; - let starts_i = ${xe("uniforms.starts","i",n.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; - }`,Ed=(t,e)=>{let n=t[0].dims,r=J.size(n),a=e.axes.length>0?J.normalizeAxes(e.axes,n.length):[...Array(n.length).keys()],i=Er(t,4);i.forEach(y=>y!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(a.length).fill(1));let s=e.starts.map((y,$)=>is(y,$,n,a,i)),o=e.ends.map((y,$)=>is(y,$,n,a,i));if(a.length!==s.length||a.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(a.length!==n.length)for(let y=0;yMath.sign(y));i.forEach((y,$,k)=>{if(y<0){let S=(o[$]-s[$])/y,T=s[$],A=T+S*i[$];s[$]=A,o[$]=T,k[$]=-y}});let d=n.slice(0);a.forEach((y,$)=>{d[y]=Math.ceil((o[y]-s[y])/i[y])});let c={dims:d,dataType:t[0].dataType},u=ve("output",t[0].dataType,d.length),h=Q("input",t[0].dataType,t[0].dims.length),f=J.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}],w=[{type:"uint32",data:f},{type:"uint32",data:s},{type:"int32",data:l},{type:"uint32",data:i},...ie(t[0].dims),...ie(d)],b=y=>` - ${y.registerUniforms(g).declareVariables(h,u)} - ${Sd(h,u,n)} - ${y.mainStart()} - ${y.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(r/64)},programUniforms:w})}},tf=(t,e)=>{$d(t.inputs,e);let n=xd(t.inputs,e);t.compute(Ed(t.inputs,n),{inputs:[0]})},nf=t=>{let e=t.starts,n=t.ends,r=t.axes;return qe({starts:e,ends:n,axes:r})}}),kd,Cd,rf,af,J_=X(()=>{Ie(),ot(),Ce(),kd=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},Cd=(t,e)=>{let n=t.dims,r=J.size(n),a=64,i=e.axis;if(i<0&&(i=n.length+i),iy===4?`max(max(${b}.x, ${b}.y), max(${b}.z, ${b}.w))`:y===2?`max(${b}.x, ${b}.y)`:y===3?`max(max(${b}.x, ${b}.y), ${b}.z)`:b,u=Q("x",t.dataType,t.dims,l),h=ve("result",t.dataType,t.dims,l),f=u.type.value,g=At(t.dataType)==="f32"?`var threadMax = ${f}(-3.402823e+38f);`:`var threadMax = ${f}(-65504.0h);`,w=b=>` - var rowMaxShared : ${f}; - var rowSumShared : ${f}; - var threadShared : array<${f}, ${a}>; - - fn getValue(row: i32, col: i32, row_stride: i32) -> ${f} { - let index = row * row_stride + col; - return x[index]; - } - - fn setValue(row: i32, col: i32, row_stride: i32, value: ${f}) { - 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 = ${f}(${c("threadShared[0]",l)}); - } - workgroupBarrier(); - - // find the rows sum - var threadSum = ${f}(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 = ${f}(${Qt("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:n,dataType:t.dataType}],dispatchGroup:{x:o},programUniforms:[{type:"uint32",data:d}]}),getShaderSource:w}},rf=(t,e)=>{kd(t.inputs),t.compute(Cd(t.inputs[0],e))},af=t=>qe({axis:t.axis})}),Td,Id,Ad,Md,Od,sf,of,e0=X(()=>{Ie(),ot(),Ce(),Td=t=>{if(!t||t.length<1)throw new Error("too few inputs")},Id=(t,e)=>{let n=[],r=e.numOutputs;return t[1].dims[0]>0&&(t[1].getBigInt64Array().forEach(a=>n.push(Number(a))),r=n.length),qe({numOutputs:r,axis:e.axis,splitSizes:n})},Ad=t=>` -fn calculateOutputIndex(index: u32) -> u32 { - for (var i: u32 = 0u; i < ${t}u; i += 1u ) { - if (index < ${xe("uniforms.size_in_split_axis","i",t)}) { - return i; - } - } - return ${t}u; -}`,Md=t=>{let e=t.length,n=[];for(let r=0;r{let n=t[0].dims,r=J.size(n),a=t[0].dataType,i=J.normalizeAxis(e.axis,n.length),s=new Array(e.numOutputs),o=Q("input",a,n),l=new Array(e.numOutputs),d=[],c=[],u=0,h=[{type:"uint32",data:r}];for(let g=0;gh.push(...ie(g)));let f=g=>` - ${g.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)} - ${Ad(l.length)} - ${Md(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 -= ${xe("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:f,getRunData:()=>({outputs:d,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:h})}},sf=(t,e)=>{Td(t.inputs);let n=t.inputs.length===1?e:Id(t.inputs,e);t.compute(Od(t.inputs,n),{inputs:[0]})},of=t=>{let e=t.axis,n=t.splitSizes,r=t.numOutputs<0?n.length:t.numOutputs;if(r!==n.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qe({axis:e,numOutputs:r,splitSizes:n})}}),ss,zd,Rd,Bd,lf,t0=X(()=>{Ye(),Ie(),Ce(),ss=t=>Array.from(t.getBigInt64Array(),Number),zd=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(ss(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")},Rd=(t,e)=>{let n=[];for(let r=0;r{let e=t[0].dims,n=ss(t[1]),r=Rd(e,n),a=J.size(r),i=t[0].dataType,s=Q("input",i,e.length),o=ve("output",i,r.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:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:"uint32",data:a},...ie(t[0].dims),...ie(r)]}),getShaderSource:l}},lf=t=>{zd(t.inputs),t.compute(Bd(t.inputs),{inputs:[0]})}}),Pd,Dd,uf,n0=X(()=>{Ye(),Ie(),Ce(),Pd=(t,e,n,r,a)=>{let i=ve("output_data",a,n.length,4),s=Q("a_data",e[1].dataType,e[1].dims.length,4),o=Q("b_data",e[2].dataType,e[2].dims.length,4),l=Q("c_data",e[0].dataType,e[0].dims.length,4),d,c=(u,h,f)=>`select(${h}, ${u}, ${f})`;if(!r)d=i.setByOffset("global_idx",c(s.getByOffset("global_idx"),o.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(h,f,g="")=>{let w=`a_data[index_a${f}][component_a${f}]`,b=`b_data[index_b${f}][component_b${f}]`,y=`bool(c_data[index_c${f}] & ${4278190080>>>(3-f)*8}u)`;return` - let output_indices${f} = ${i.offsetToIndices(`global_idx * 4u + ${f}u`)}; - let offset_a${f} = ${s.broadcastedIndicesToOffset(`output_indices${f}`,i)}; - let offset_b${f} = ${o.broadcastedIndicesToOffset(`output_indices${f}`,i)}; - let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,i)}; - let index_a${f} = offset_a${f} / 4u; - let index_b${f} = offset_b${f} / 4u; - let index_c${f} = offset_c${f} / 4u; - let component_a${f} = offset_a${f} % 4u; - let component_b${f} = offset_b${f} % 4u; - ${h}[${f}] = ${g}(${c(w,b,y)}); - `};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} - }`},Dd=t=>{let e=t[1].dims,n=t[2].dims,r=t[0].dims,a=t[1].dataType,i=!(J.areEqual(e,n)&&J.areEqual(n,r)),s=e,o=J.size(e);if(i){let d=Xn.calcShape(Xn.calcShape(e,n,!1),r,!1);if(!d)throw new Error("Can't perform where op on the given tensors");s=d,o=J.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>Pd(d,t,s,i,a),getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:"uint32",data:l},...ie(r),...ie(e),...ie(n),...ie(s)]})}},uf=t=>{t.compute(Dd(t.inputs))}}),df,r0=X(()=>{C_(),Sp(),T_(),I_(),A_(),M_(),O_(),$h(),D_(),N_(),F_(),L_(),U_(),W_(),V_(),G_(),H_(),vh(),q_(),j_(),K_(),Y_(),no(),X_(),Q_(),Z_(),J_(),e0(),t0(),Hr(),ah(),n0(),df=new Map([["Abs",[Cp]],["Acos",[Tp]],["Acosh",[Ip]],["Add",[sh]],["ArgMax",[$p,Ss]],["ArgMin",[vp,Ss]],["Asin",[Ap]],["Asinh",[Mp]],["Atan",[Op]],["Atanh",[zp]],["Attention",[xp]],["AveragePool",[Vh,Wh]],["BatchNormalization",[Ep]],["BiasAdd",[kp]],["BiasSplitGelu",[ih]],["Cast",[Bp,Rp]],["Ceil",[Dp]],["Clip",[Pp]],["Concat",[gh,_h]],["Conv",[Is,Ts]],["ConvTranspose",[Eh,Sh]],["Cos",[Np]],["Cosh",[Fp]],["CumSum",[kh,Ch]],["Div",[oh]],["Einsum",[Th,Ih]],["Elu",[Lp,La]],["Equal",[lh]],["Erf",[Up]],["Exp",[Wp]],["Expand",[Ah]],["Floor",[Vp]],["FusedConv",[Is,Ts]],["Gather",[Oh,Mh]],["GatherElements",[Rh,zh]],["Gelu",[Gp]],["Gemm",[Ph,Bh]],["GlobalAveragePool",[Hh,Gh]],["GlobalMaxPool",[Yh,Kh]],["Greater",[ph]],["GreaterOrEqual",[fh]],["InstanceNormalization",[Dh]],["LayerNormalization",[Nh]],["LeakyRelu",[Hp,La]],["Less",[hh]],["LessOrEqual",[mh]],["Log",[rh]],["MatMul",[bh]],["MaxPool",[qh,jh]],["Mul",[uh]],["MultiHeadAttention",[Lh,Fh]],["Neg",[jp]],["Not",[qp]],["Pad",[Uh]],["Pow",[dh]],["Range",[Xh]],["Reciprocal",[Kp]],["ReduceMin",[gp]],["ReduceMean",[cp]],["ReduceMax",[mp]],["ReduceSum",[wp]],["ReduceProd",[_p]],["ReduceL1",[pp]],["ReduceL2",[hp]],["ReduceLogSum",[bp]],["ReduceLogSumExp",[fp]],["ReduceSumSquare",[yp]],["Relu",[Yp]],["Resize",[Qh,Zh]],["Sigmoid",[Xp]],["Sin",[Qp]],["Sinh",[Zp]],["Slice",[tf,nf]],["SkipLayerNormalization",[Jh,ef]],["Split",[sf,of]],["Sqrt",[Jp]],["Softmax",[rf,af]],["Sub",[ch]],["Tan",[eh]],["Tanh",[th]],["ThresholdedRelu",[nh,La]],["Tile",[lf]],["Transpose",[Jc,ep]],["Where",[uf]]])}),cf,a0=X(()=>{Vt(),In(),Ce(),cf=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,n,r,a){Ut(t.programInfo.name);let i=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2),s.setPipeline(t.computePipeline);let o=[];for(let d of e)o.push({binding:o.length,resource:{buffer:d.buffer}});for(let d of n)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});s.setBindGroup(0,l),s.dispatchWorkgroups(...r),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(),Wt(t.programInfo.name)}dispose(){}build(t,e){Ut(t.name);let n=this.backend.device,r=[];n.features.has("shader-f16")&&r.push("enable f16;");let a=Zc(e),i=t.getShaderSource(a),s=`${r.join(` -`)} -${a.additionalImplementations} -${i}`,o=n.createShaderModule({code:s,label:t.name});it("verbose",()=>`[WebGPU] ${t.name} shader code: ${s}`);let l=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:t.name});return Wt(t.name),{programInfo:t,computePipeline:l}}normalizeDispatchGroupSize(t){let e=typeof t=="number"?t:t.x,n=typeof t=="number"?1:t.y||1,r=typeof t=="number"?1:t.z||1,a=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=a&&n<=a&&r<=a)return[e,n,r];let i=e*n*r,s=Math.ceil(Math.sqrt(i));if(s>a){if(s=Math.ceil(Math.cbrt(i)),s>a)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}else return[s,s,1]}}}),Nd,Fd,pf,i0=X(()=>{Vt(),Ye(),In(),S_(),E_(),r0(),a0(),Nd=(t,e)=>{if(e.length!==t.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${t.length}.`);let n=[];for(let r=0;r{let r=t.name;return t.shaderCache?.hint&&(r+="["+t.shaderCache.hint+"]"),r+=":"+n+`:${Nd(e,t.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},pf=class{constructor(){this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=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 n=[],r={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:n};e.features.has("chromium-experimental-timestamp-query-inside-passes")?n.push("chromium-experimental-timestamp-query-inside-passes"):e.features.has("timestamp-query")&&n.push("timestamp-query"),e.features.has("shader-f16")&&n.push("shader-f16"),this.device=await e.requestDevice(r),this.gpuDataManager=Xc(this),this.programManager=new cf(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Kc(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}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder(),this.setQueryType(),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}))),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=this.getCommandEncoder().beginComputePass(t)}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()),n=this.pendingQueries.get(t);for(let r=0;r"u"&&(this.queryTimeBase=h);let g=Number(h-this.queryTimeBase),w=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(w))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:Yt(b.dataType)})),outputsMetadata:u.map(b=>({dims:b.dims,dataType:Yt(b.dataType)})),kernelId:i,kernelType:o,kernelName:l,programName:d,startTime:g,endTime:w});else{let b="";c.forEach(($,k)=>{b+=`input[${k}]: [${$.dims}] | ${Yt($.dataType)}, `});let y="";u.forEach(($,k)=>{y+=`output[${k}]: [${$.dims}] | ${Yt($.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${l}|${d}" ${b}${y}execution time: ${w-g} ns`)}Dr("GPU",`${d}::${h}::${f}`)}t.unmap(),this.pendingQueries.delete(t)}),Wt()}run(t,e,n,r,a){Ut(t.name);let i=[];for(let y=0;y$):n;if(d.length!==s.length)throw new Error(`Output size ${d.length} must be equal to ${s.length}.`);let c=[],u=[];for(let y=0;y=s.length)throw new Error(`Invalid output index: ${d[y]}`);if(d[y]===-3)continue;let $=d[y]===-1,k=d[y]===-2,S=$||k?a(s[y].dataType,s[y].dims):r(d[y],s[y].dataType,s[y].dims),T=this.gpuDataManager.get(S.data);if(!T)throw new Error(`no GPU data for output: ${S.data}`);if($&&this.temporaryData.push(T),k){let A=this.kernelPersistentData.get(this.currentKernelId);A||(A=[],this.kernelPersistentData.set(this.currentKernelId,A)),A.push(T)}c.push(S),u.push(T)}let h;if(l){let y=0,$=[];l.forEach(A=>{let P=typeof A.data=="number"?[A.data]:A.data;if(P.length===0)return;let N=P.length<=2?P.length*4:16;y=Math.ceil(y/N)*N,$.push(y),y+=P.length>4?Math.ceil(P.length/4)*16:P.length*4});let k=16;y=Math.ceil(y/k)*k;let S=new ArrayBuffer(y);l.forEach((A,P)=>{let N=$[P],V=typeof A.data=="number"?[A.data]:A.data;A.type==="int32"?new Int32Array(S,N,V.length).set(V):A.type==="uint32"?new Uint32Array(S,N,V.length).set(V):new Float32Array(S,N,V.length).set(V)});let T=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(T.buffer,0,S,0,y),this.gpuDataManager.release(T.id),h={offset:0,size:y,buffer:T.buffer}}let f=this.programManager.normalizeDispatchGroupSize(o),g=f[1]===1&&f[2]===1,w=Fd(t,e,g),b=this.programManager.getArtifact(w);if(b||(b=this.programManager.build(t,f),this.programManager.setArtifact(w,b),it("info",()=>`[artifact] key: ${w}, programName: ${t.name}`)),it("info",()=>`[ProgramManager] run "${t.name}" (key=${w}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"){let y={kernelId:this.currentKernelId,programName:b.programInfo.name,inputTensorViews:e,outputTensorViews:c};this.pendingKernels.push(y)}return this.programManager.run(b,i,u,f,h),Wt(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,n,r){let a=df.get(t);if(!a)throw new Error(`kernel not implemented: ${t}`);let i={kernelType:t,kernelName:r,kernelEntry:a[0],attributes:[a[1],n]};this.kernels.set(e,i)}releaseKernel(t){let e=this.kernelPersistentData.get(t);if(e){for(let n of e)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,e,n){let r=this.kernels.get(t);if(!r)throw new Error(`kernel not created: ${t}`);let a=r.kernelType,i=r.kernelName,s=r.kernelEntry,o=r.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),it("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 n.push(Promise.resolve(`[WebGPU] Kernel "[${a}] ${i}" failed. ${d}`)),1}finally{l&&n.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,n,r){let a=this.sessionExternalDataMapping.get(t);a||(a=new Map,this.sessionExternalDataMapping.set(t,a));let i=a.get(e),s=this.gpuDataManager.registerExternalBuffer(n,r,i?.[1]);return a.set(e,[s,n]),s}unregisterBuffers(t){let e=this.sessionExternalDataMapping.get(t);e&&(e.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[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,n){return async()=>{let r=await $s(this,t,e);return Yc(r.buffer,n)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||this.env.wasm.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"))}}}),hf={};er(hf,{init:()=>ff});var Ra,Ld,ff,s0=X(()=>{Ye(),i0(),In(),Ie(),Ra=class mf{constructor(e,n,r,a){this.module=e,this.dataType=n,this.data=r,this.dims=a}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=J.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=J.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=J.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(J.size(e)!==J.size(this.dims))throw new Error("Invalid new shape");return new mf(this.module,this.dataType,this.data,e)}},Ld=class{constructor(t,e,n){this.module=t,this.backend=e,this.customDataOffset=0,this.customDataSize=0;let r=t.HEAPU32,a=n>>>2;this.opKernelContext=r[a++];let i=r[a++];this.outputCount=r[a++],this.customDataOffset=r[a++],this.customDataSize=r[a++];let s=[];for(let o=0;otypeof s=="number"?this.inputs[s]:s)??this.inputs,r=e?.outputs??[],a=(s,o,l)=>new Ra(this.module,o,this.output(s,l),l),i=(s,o)=>{let l=Ka(s);if(!l)throw new Error(`Unsupported data type: ${s}`);let d=l*J.size(o);return new Ra(this.module,s,this.backend.gpuDataManager.create(d).id,o)};return this.backend.run(t,n,r,a,i)}output(t,e){let n=this.module.stackSave();try{let r=this.module.stackAlloc((1+e.length)*4),a=r>>2;this.module.HEAPU32[a++]=e.length;for(let i=0;i{let r=t.jsepInit;if(!r)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");let a=new pf;await a.initialize(e,n),r(a,i=>a.alloc(i),i=>a.free(i),(i,s,o,l=!1)=>{if(l)it("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${s}, size=${o}`),a.memcpy(i,s);else{it("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${s}, size=${o}`);let d=t.HEAPU8.subarray(i>>>0,(i>>>0)+o);a.upload(s,d)}},async(i,s,o)=>{it("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${s}, size=${o}`),await a.download(i,()=>t.HEAPU8.subarray(s>>>0,(s>>>0)+o))},(i,s,o)=>a.createKernel(i,s,o,t.UTF8ToString(t._JsepGetNodeName(s))),i=>a.releaseKernel(i),(i,s,o,l)=>{it("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${o}, kernel=${i}, contextDataOffset=${s}`);let d=new Ld(t,a,s);return a.computeKernel(i,d,l)})}}),Ud,gf,_f,Ln,Wd,Ms,wf,yf,os,bf,vf,$f,o0=X(()=>{$_(),x_(),Ye(),Gr(),Ys(),jc(),Ud=(t,e)=>{tt()._OrtInit(t,e)!==0&&He("Can't initialize onnxruntime.")},gf=async t=>{Ud(t.wasm.numThreads,Ya(t.logLevel))},_f=async(t,e)=>{if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=await navigator.gpu.requestAdapter();if(!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");let r=(s0(),Cn(hf)).init;await r(tt(),t,n)}},Ln=new Map,Wd=t=>{let e=tt(),n=e.stackSave();try{let r=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,r,r+4)!==0&&He("Can't get session input/output count."),[e.HEAP32[r/4],e.HEAP32[r/4+1]]}finally{e.stackRestore(n)}},Ms=t=>{let e=tt(),n=e._malloc(t.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,n),[n,t.byteLength]},wf=async(t,e)=>{let n,r,a=tt();Array.isArray(t)?[n,r]=t:t.buffer===a.HEAPU8.buffer?[n,r]=[t.byteOffset,t.byteLength]:[n,r]=Ms(t);let i=0,s=0,o=0,l=[],d=[],c=[];try{if([s,l]=qc(e),e?.externalData&&a.mountExternalData){let y=[];for(let $ of e.externalData){let k=typeof $=="string"?$:$.path;y.push(Xa(typeof $=="string"?$:$.data).then(S=>{a.mountExternalData(k,S)}))}await Promise.all(y)}i=a._OrtCreateSession(n,r,s),i===0&&He("Can't create a session.");let[u,h]=Wd(i),f=[],g=[],w=[];for(let y=0;yy==="gpu-buffer")&&(o=a._OrtCreateBinding(i),o===0&&He("Can't create IO binding."),b={handle:o,outputPreferredLocations:w,outputPreferredLocationsEncoded:w.map(y=>vs(y))}),Ln.set(i,[i,d,c,b]),[i,f,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(n),s!==0&&a._OrtReleaseSessionOptions(s),l.forEach(u=>a._free(u)),a.unmountExternalData?.()}},yf=t=>{let e=tt(),n=Ln.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[r,a,i,s]=n;s&&e._OrtReleaseBinding(s.handle),e.jsepUnregisterBuffers?.(t),a.forEach(o=>e._OrtFree(o)),i.forEach(o=>e._OrtFree(o)),e._OrtReleaseSession(r),Ln.delete(t)},os=(t,e,n,r,a)=>{if(!t){e.push(0);return}let i=tt(),s=t[0],o=t[1],l=t[3],d,c;if(s==="string"&&l==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(l==="gpu-buffer"){let f=t[2].gpuBuffer,g=Ka(bs(s));c=o.reduce((w,b)=>w*b,1)*g,d=i.jsepRegisterBuffer(r,a,f,c)}else{let f=t[2];if(Array.isArray(f)){c=4*f.length,d=i._malloc(c),n.push(d);let g=d/4;for(let w=0;wi.HEAP32[f++]=w);let g=i._OrtCreateTensor(bs(s),d,c,h,o.length,vs(l));g===0&&He(`Can't create tensor for input/output. session=${r}, index=${a}.`),e.push(g)}finally{i.stackRestore(u)}},bf=async(t,e,n,r,a,i)=>{let s=tt(),o=Ln.get(t);if(!o)throw new Error(`cannot run inference. invalid session id: ${t}`);let[l,d,c,u]=o,h=e.length,f=r.length,g=0,w=[],b=[],y=[],$=[],k=s.stackSave(),S=s.stackAlloc(h*4),T=s.stackAlloc(h*4),A=s.stackAlloc(f*4),P=s.stackAlloc(f*4);try{[g,w]=Hc(i);for(let R=0;RLe*Ve,1);Y=Yt(oe);let wt=u?.outputPreferredLocations[r[R]];if(Y==="string"){if(wt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Le=[],Ve=ue/4;for(let nt=0;nt0){let Le=s.jsepGetBuffer(ue),Ve=Ka(oe);if(Ve===void 0||!Qs(Y))throw new Error(`Unsupported data type: ${Y}`);re=!0,O.push([Y,Pe,{gpuBuffer:Le,download:s.jsepCreateDownloader(Le,We*Ve,Y),dispose:()=>{s._OrtReleaseTensor(H)}},"gpu-buffer"])}else{let Le=Xs(Y),Ve=new Le(We);new Uint8Array(Ve.buffer,Ve.byteOffset,Ve.byteLength).set(s.HEAPU8.subarray(ue,ue+Ve.byteLength)),O.push([Y,Pe,Ve,"cpu"])}}finally{s.stackRestore(te),Y==="string"&&ue&&s._free(ue),re||s._OrtReleaseTensor(H)}}return u&&s._OrtClearBoundOutputs(u.handle),O}finally{s.stackRestore(k),b.forEach(N=>s._OrtReleaseTensor(N)),y.forEach(N=>s._OrtReleaseTensor(N)),$.forEach(N=>s._free(N)),g!==0&&s._OrtReleaseRunOptions(g),w.forEach(N=>s._free(N))}},vf=t=>{let e=tt(),n=Ln.get(t);if(!n)throw new Error("invalid session id");let r=n[0],a=e._OrtEndProfiling(r);a===0&&He("Can't get an profile file name."),e._OrtFree(a)},$f=t=>{let e=[];for(let n of t){let r=n[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),l0=Jn((t,e)=>{e.exports='/*!\n * ONNX Runtime Web v1.17.1\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var hn=Object.defineProperty;var Lu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var ju=Object.prototype.hasOwnProperty;var j=(e,t)=>()=>(e&&(t=e(e=0)),t);var dr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Br=(e,t)=>{for(var r in t)hn(e,r,{get:t[r],enumerable:!0})},qu=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fu(t))!ju.call(e,n)&&n!==r&&hn(e,n,{get:()=>t[n],enumerable:!(o=Lu(t,n))||o.enumerable});return e};var Ht=e=>qu(hn({},"__esModule",{value:!0}),e);var gn={};Br(gn,{createReadStream:()=>xo,readFile:()=>Ku,readFileSync:()=>Yu});var Ku,Yu,xo,yn=j(()=>{Ku=void 0,Yu=void 0,xo=void 0});var bn={};Br(bn,{join:()=>Zu});var Zu,wn=j(()=>{Zu=void 0});var Io=dr((Co,vn)=>{"use strict";var _o=(()=>{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,m)=>{o=d,n=m}),r.mountExternalData=(d,m)=>{(r.Fa||(r.Fa=new Map)).set(d,m)},r.unmountExternalData=()=>{delete r.Fa},r.jsepInit=(d,m,v,C,B,H,q,le)=>{r.ab=d,r.Qa=m,r.Sa=v,r.La=C,r.Ra=B,r.sa=H,r.Ta=q,r.Ua=le,m=(J,re,se)=>(...we)=>{let _e=tt,P=re?.();we=J(...we);let ue=re?.();return P!==ue&&(J=ue,se(P),re=se=null),tt!=_e?xr():we},v=J=>async(...re)=>{try{if(r.Ea)throw Error("Session already started");let se=r.Ea={Va:re[0],errors:[]},we=await J(...re);if(r.Ea!==se)throw Error("Session mismatch");d.flush();let _e=se.errors;if(0<_e.length){let P=await Promise.all(_e);if(P=P.filter(ue=>ue),0r._OrtRun,J=>r._OrtRun=J)),r._OrtRunWithBinding=v(m(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,J=>r._OrtRunWithBinding=J)),r._OrtBindInput=m(r._OrtBindInput,()=>r._OrtBindInput,J=>r._OrtBindInput=J),r.jsepRegisterBuffer=(J,re,se,we)=>d.registerBuffer(J,re,se,we),r.jsepUnregisterBuffers=J=>{d.unregisterBuffers(J)},r.jsepGetBuffer=J=>d.getBuffer(J),r.jsepCreateDownloader=(J,re,se)=>d.createDownloader(J,re,se)};var s=Object.assign({},r),u="./this.program",l=(d,m)=>{throw m},a=typeof window=="object",p=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="",b,w,y;if(h){var _=(yn(),Ht(gn)),I=(wn(),Ht(bn));g=p?I.dirname(g)+"/":__dirname+"/",b=(d,m)=>(d=We(d)?new URL(d):I.normalize(d),_.readFileSync(d,m?void 0:"utf8")),y=d=>(d=b(d,!0),d.buffer||(d=new Uint8Array(d)),d),w=(d,m,v,C=!0)=>{d=We(d)?new URL(d):I.normalize(d),_.readFile(d,C?void 0:"utf8",(B,H)=>{B?v(B):m(C?H.buffer:H)})},!r.thisProgram&&1{throw process.exitCode=d,m},r.inspect=()=>"[Emscripten Module object]"}else(a||p)&&(p?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),e&&(g=e),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",b=d=>{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.send(null),m.responseText},p&&(y=d=>{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),w=(d,m,v)=>{var C=new XMLHttpRequest;C.open("GET",d,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?m(C.response):v()},C.onerror=v,C.send(null)});var $=console.log.bind(console),x=console.error.bind(console);Object.assign(r,s),s=null,typeof WebAssembly!="object"&&he("no native wasm support detected");var E,A=!1,z,R,V,T,N,te,Y;function K(){var d=E.buffer;r.HEAP8=R=new Int8Array(d),r.HEAP16=new Int16Array(d),r.HEAPU8=V=new Uint8Array(d),r.HEAPU16=new Uint16Array(d),r.HEAP32=T=new Int32Array(d),r.HEAPU32=N=new Uint32Array(d),r.HEAPF32=te=new Float32Array(d),r.HEAPF64=Y=new Float64Array(d)}var Q=[],Z=[],Ee=[],Pe=0,fe=null,Ie=null;function he(d){throw d="Aborted("+d+")",x(d),A=!0,z=1,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),n(d),d}var ye=d=>d.startsWith("data:application/octet-stream;base64,"),We=d=>d.startsWith("file://"),De;if(De="ort-wasm-simd.wasm",!ye(De)){var Ge=De;De=r.locateFile?r.locateFile(Ge,g):g+Ge}function G(d){if(y)return y(d);throw"both async and sync fetching of the wasm failed"}function ee(d){if(a||p){if(typeof fetch=="function"&&!We(d))return fetch(d,{credentials:"same-origin"}).then(m=>{if(!m.ok)throw"failed to load wasm binary file at \'"+d+"\'";return m.arrayBuffer()}).catch(()=>G(d));if(w)return new Promise((m,v)=>{w(d,C=>m(new Uint8Array(C)),v)})}return Promise.resolve().then(()=>G(d))}function be(d,m,v){return ee(d).then(C=>WebAssembly.instantiate(C,m)).then(C=>C).then(v,C=>{x(`failed to asynchronously prepare wasm: ${C}`),he(C)})}function et(d,m){var v=De;return typeof WebAssembly.instantiateStreaming!="function"||ye(v)||We(v)||h||typeof fetch!="function"?be(v,d,m):fetch(v,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,d).then(m,function(B){return x(`wasm streaming compile failed: ${B}`),x("falling back to ArrayBuffer instantiation"),be(v,d,m)}))}var ze,Ue={931056:(d,m,v,C)=>{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(m>>>=0,v>>>=0,m+v>d.byteLength)return 3;try{return V.set(d.subarray(m,m+v),C>>>0>>>0),0}catch{return 4}},931557:d=>r.Qa(d),931590:d=>r.Sa(d),931622:(d,m,v)=>{r.La(d,m,v,!0)},931661:(d,m,v)=>{r.La(d,m,v)},931694:d=>{r.sa("Abs",d,void 0)},931745:d=>{r.sa("Neg",d,void 0)},931796:d=>{r.sa("Floor",d,void 0)},931849:d=>{r.sa("Ceil",d,void 0)},931901:d=>{r.sa("Reciprocal",d,void 0)},931959:d=>{r.sa("Sqrt",d,void 0)},932011:d=>{r.sa("Exp",d,void 0)},932062:d=>{r.sa("Erf",d,void 0)},932113:d=>{r.sa("Sigmoid",d,void 0)},932168:d=>{r.sa("Log",d,void 0)},932219:d=>{r.sa("Sin",d,void 0)},932270:d=>{r.sa("Cos",d,void 0)},932321:d=>{r.sa("Tan",d,void 0)},932372:d=>{r.sa("Asin",d,void 0)},932424:d=>{r.sa("Acos",d,void 0)},932476:d=>{r.sa("Atan",d,void 0)},932528:d=>{r.sa("Sinh",d,void 0)},932580:d=>{r.sa("Cosh",d,void 0)},932632:d=>{r.sa("Asinh",d,void 0)},932685:d=>{r.sa("Acosh",d,void 0)},932738:d=>{r.sa("Atanh",d,void 0)},932791:d=>{r.sa("Tanh",d,void 0)},932843:d=>{r.sa("Not",d,void 0)},932894:(d,m,v)=>{r.sa("Clip",d,{min:m,max:v})},932963:d=>{r.sa("Clip",d,void 0)},933015:(d,m)=>{r.sa("Elu",d,{alpha:m})},933073:d=>{r.sa("Relu",d,void 0)},933125:(d,m)=>{r.sa("LeakyRelu",d,{alpha:m})},933189:(d,m)=>{r.sa("ThresholdedRelu",d,{alpha:m})},933259:(d,m)=>{r.sa("Cast",d,{to:m})},933317:d=>{r.sa("Add",d,void 0)},933368:d=>{r.sa("Sub",d,void 0)},933419:d=>{r.sa("Mul",d,void 0)},933470:d=>{r.sa("Div",d,void 0)},933521:d=>{r.sa("Pow",d,void 0)},933572:d=>{r.sa("Equal",d,void 0)},933625:d=>{r.sa("Greater",d,void 0)},933680:d=>{r.sa("GreaterOrEqual",d,void 0)},933742:d=>{r.sa("Less",d,void 0)},933794:d=>{r.sa("LessOrEqual",d,void 0)},933853:(d,m,v,C,B)=>{r.sa("ReduceMean",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934012:(d,m,v,C,B)=>{r.sa("ReduceMax",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934170:(d,m,v,C,B)=>{r.sa("ReduceMin",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934328:(d,m,v,C,B)=>{r.sa("ReduceProd",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934487:(d,m,v,C,B)=>{r.sa("ReduceSum",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934645:(d,m,v,C,B)=>{r.sa("ReduceL1",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934802:(d,m,v,C,B)=>{r.sa("ReduceL2",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934959:(d,m,v,C,B)=>{r.sa("ReduceLogSum",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935120:(d,m,v,C,B)=>{r.sa("ReduceSumSquare",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935284:(d,m,v,C,B)=>{r.sa("ReduceLogSumExp",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935448:d=>{r.sa("Where",d,void 0)},935501:(d,m,v)=>{r.sa("Transpose",d,{perm:m?Array.from(T.subarray(m>>>0,v>>>0)):[]})},935609:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue)=>{r.sa("ConvTranspose",d,{format:J?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernel_shape:[B],pads:[H,q],strides:[le],wIsConst:()=>!!R[re>>>0],outputPadding:se?Array.from(T.subarray(se>>>0,we>>>0)):[],outputShape:_e?Array.from(T.subarray(_e>>>0,P>>>0)):[],activation:qe(ue)})},936011:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P)=>{r.sa("ConvTranspose",d,{format:le?"NHWC":"NCHW",autoPad:m,dilations:Array.from(T.subarray(v>>>0,(v>>>0)+2>>>0)),group:C,kernelShape:Array.from(T.subarray(B>>>0,(B>>>0)+2>>>0)),pads:Array.from(T.subarray(H>>>0,(H>>>0)+4>>>0)),strides:Array.from(T.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!R[J>>>0],outputPadding:re?Array.from(T.subarray(re>>>0,se>>>0)):[],outputShape:we?Array.from(T.subarray(we>>>0,_e>>>0)):[],activation:qe(P)})},936576:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue)=>{r.sa("ConvTranspose",d,{format:J?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernel_shape:[B],pads:[H,q],strides:[le],wIsConst:()=>!!R[re>>>0],outputPadding:se?Array.from(T.subarray(se>>>0,we>>>0)):[],outputShape:_e?Array.from(T.subarray(_e>>>0,P>>>0)):[],activation:qe(ue)})},936978:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P)=>{r.sa("ConvTranspose",d,{format:le?"NHWC":"NCHW",autoPad:m,dilations:Array.from(T.subarray(v>>>0,(v>>>0)+2>>>0)),group:C,kernelShape:Array.from(T.subarray(B>>>0,(B>>>0)+2>>>0)),pads:Array.from(T.subarray(H>>>0,(H>>>0)+4>>>0)),strides:Array.from(T.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!R[J>>>0],outputPadding:re?Array.from(T.subarray(re>>>0,se>>>0)):[],outputShape:we?Array.from(T.subarray(we>>>0,_e>>>0)):[],activation:qe(P)})},937543:(d,m)=>{r.sa("GlobalAveragePool",d,{format:m?"NHWC":"NCHW"})},937634:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("AveragePool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},937918:(d,m)=>{r.sa("GlobalAveragePool",d,{format:m?"NHWC":"NCHW"})},938009:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("AveragePool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},938293:(d,m)=>{r.sa("GlobalMaxPool",d,{format:m?"NHWC":"NCHW"})},938380:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("MaxPool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},938660:(d,m)=>{r.sa("GlobalMaxPool",d,{format:m?"NHWC":"NCHW"})},938747:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("MaxPool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},939027:(d,m,v,C,B)=>{r.sa("Gemm",d,{alpha:m,beta:v,transA:C,transB:B})},939131:d=>{r.sa("MatMul",d,void 0)},939185:(d,m,v,C)=>{r.sa("ArgMax",d,{keepDims:!!m,selectLastIndex:!!v,axis:C})},939293:(d,m,v,C)=>{r.sa("ArgMin",d,{keepDims:!!m,selectLastIndex:!!v,axis:C})},939401:(d,m)=>{r.sa("Softmax",d,{axis:m})},939464:(d,m)=>{r.sa("Concat",d,{axis:m})},939524:(d,m,v,C,B)=>{r.sa("Split",d,{axis:m,numOutputs:v,splitSizes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},939664:d=>{r.sa("Expand",d,void 0)},939718:(d,m)=>{r.sa("Gather",d,{axis:Number(m)})},939789:(d,m)=>{r.sa("GatherElements",d,{axis:Number(m)})},939868:(d,m,v,C,B,H,q,le,J,re,se)=>{r.sa("Resize",d,{antialias:m,axes:v?Array.from(T.subarray(v>>>0,C>>>0)):[],coordinateTransformMode:qe(B),cubicCoeffA:H,excludeOutside:q,extrapolationValue:le,keepAspectRatioPolicy:qe(J),mode:qe(re),nearestMode:qe(se)})},940214:(d,m,v,C,B,H,q)=>{r.sa("Slice",d,{starts:m?Array.from(T.subarray(m>>>0,v>>>0)):[],ends:C?Array.from(T.subarray(C>>>0,B>>>0)):[],axes:H?Array.from(T.subarray(H>>>0,q>>>0)):[]})},940430:d=>{r.sa("Tile",d,void 0)},940482:(d,m,v)=>{r.sa("LayerNormalization",d,{axis:Number(m),epsilon:Number(v)})},940589:(d,m,v)=>{r.sa("InstanceNormalization",d,{epsilon:m,format:v?"NHWC":"NCHW"})},940703:(d,m,v)=>{r.sa("InstanceNormalization",d,{epsilon:m,format:v?"NHWC":"NCHW"})},940817:d=>{r.sa("Range",d,void 0)},940870:(d,m)=>{r.sa("Einsum",d,{equation:qe(m)})},940951:(d,m,v,C,B)=>{r.sa("Pad",d,{mode:m,value:v,pads:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},941078:(d,m,v,C,B,H)=>{r.sa("BatchNormalization",d,{epsilon:m,momentum:v,spatial:!!B,trainingMode:!!C,format:H?"NHWC":"NCHW"})},941247:(d,m,v,C,B,H)=>{r.sa("BatchNormalization",d,{epsilon:m,momentum:v,spatial:!!B,trainingMode:!!C,format:H?"NHWC":"NCHW"})},941416:(d,m,v)=>{r.sa("CumSum",d,{exclusive:Number(m),reverse:Number(v)})},941513:(d,m,v,C,B,H,q,le,J)=>{r.sa("Attention",d,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:B,doRotary:H,qkvHiddenSizes:q?Array.from(T.subarray(Number(le)>>>0,Number(le)+q>>>0)):[],pastPresentShareBuffer:!!J})},941785:d=>{r.sa("Gelu",d,void 0)},941837:(d,m,v,C,B,H)=>{r.sa("MultiHeadAttention",d,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:B,doRotary:H})},941996:d=>{r.sa("BiasAdd",d,void 0)},942051:d=>{r.sa("BiasSplitGelu",d,void 0)},942112:(d,m)=>{r.sa("SkipLayerNormalization",d,{epsilon:m})},942193:(d,m,v,C,B,H,q,le,J,re,se,we,_e)=>{r.sa("Conv",d,{format:J?"NHWC":"NCHW",auto_pad:m,dilations:[v],group:C,kernel_shape:[B],pads:H?Array.from(T.subarray(H>>>0,q>>>0)):[],strides:[le],w_is_const:()=>!!R[re>>>0],activation:qe(se),activation_params:we?Array.from(te.subarray(we>>>0,_e>>>0)):[]})},942563:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("Conv",d,{format:we?"NHWC":"NCHW",auto_pad:m,dilations:[v,C],group:B,kernel_shape:[H,q],pads:le?Array.from(T.subarray(le>>>0,J>>>0)):[],strides:[re,se],w_is_const:()=>!!R[_e>>>0],activation:qe(P),activation_params:ue?Array.from(te.subarray(ue>>>0,Se>>>0)):[]})},942954:d=>{r.Ta(d)},942988:(d,m)=>r.Ua(d,m,r.Ea.Va,r.Ea.errors)};function Me(d){this.name="ExitStatus",this.message=`Program terminated with exit(${d})`,this.status=d}function wt(d){this.Ja=d-24,this.Oa=function(m){N[this.Ja+4>>>2>>>0]=m},this.Na=function(m){N[this.Ja+8>>>2>>>0]=m},this.$a=function(m,v){this.Ma(),this.Oa(m),this.Na(v)},this.Ma=function(){N[this.Ja+16>>>2>>>0]=0}}var rt=0,Dt=0,At=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,vt=(d,m,v)=>{m>>>=0;var C=m+v;for(v=m;d[v]&&!(v>=C);)++v;if(16B?C+=String.fromCharCode(B):(B-=65536,C+=String.fromCharCode(55296|B>>10,56320|B&1023))}}else C+=String.fromCharCode(B)}return C},qe=(d,m)=>(d>>>=0)?vt(V,d,m):"",qt=d=>{for(var m=0,v=0;v=C?m++:2047>=C?m+=2:55296<=C&&57343>=C?(m+=4,++v):m+=3}return m},Mt=(d,m,v,C)=>{if(v>>>=0,!(0=q){var le=d.charCodeAt(++H);q=65536+((q&1023)<<10)|le&1023}if(127>=q){if(v>=C)break;m[v++>>>0]=q}else{if(2047>=q){if(v+1>=C)break;m[v++>>>0]=192|q>>6}else{if(65535>=q){if(v+2>=C)break;m[v++>>>0]=224|q>>12}else{if(v+3>=C)break;m[v++>>>0]=240|q>>18,m[v++>>>0]=128|q>>12&63}m[v++>>>0]=128|q>>6&63}m[v++>>>0]=128|q&63}}return m[v>>>0]=0,v-B},$t=d=>d%4===0&&(d%100!==0||d%400===0),yt=[0,31,60,91,121,152,182,213,244,274,305,335],zt=[0,31,59,90,120,151,181,212,243,273,304,334],Ut=d=>{var m=qt(d)+1,v=Wt(m);return v&&Mt(d,V,v,m),v},Tt=[],Kt=(d,m)=>{Tt.length=0;for(var v;v=V[d++>>>0];){var C=v!=105;C&=v!=112,m+=C&&m%8?4:0,Tt.push(v==112?N[m>>>2>>>0]:v==105?T[m>>>2>>>0]:Y[m>>>3>>>0]),m+=C?8:4}return Tt},nt={},Yt=()=>{if(!Vt){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",_:u||"./this.program"},m;for(m in nt)nt[m]===void 0?delete d[m]:d[m]=nt[m];var v=[];for(m in d)v.push(`${m}=${d[m]}`);Vt=v}return Vt},Vt,Ye=[null,[],[]],br=[31,29,31,30,31,30,31,31,30,31,30,31],Oe=[31,28,31,30,31,30,31,31,30,31,30,31];function wr(d){var m=Array(qt(d)+1);return Mt(d,m,0,m.length),m}function Nt(d,m,v,C){function B(P,ue,Se){for(P=typeof P=="number"?P.toString():P||"";P.lengthTr?-1:0st-P.getDate())ue-=st-P.getDate()+1,P.setDate(1),11>Se?P.setMonth(Se+1):(P.setMonth(0),P.setFullYear(P.getFullYear()+1));else{P.setDate(P.getDate()+ue);break}}return Se=new Date(P.getFullYear()+1,0,4),ue=le(new Date(P.getFullYear(),0,4)),Se=le(Se),0>=q(ue,P)?0>=q(Se,P)?P.getFullYear()+1:P.getFullYear():P.getFullYear()-1}d>>>=0,m>>>=0,v>>>=0,C>>>=0;var re=N[C+40>>>2>>>0];C={Ya:T[C>>>2>>>0],Xa:T[C+4>>>2>>>0],Ga:T[C+8>>>2>>>0],Ka:T[C+12>>>2>>>0],Ha:T[C+16>>>2>>>0],Da:T[C+20>>>2>>>0],xa:T[C+24>>>2>>>0],Ca:T[C+28>>>2>>>0],bb:T[C+32>>>2>>>0],Wa:T[C+36>>>2>>>0],Za:re?qe(re):""},v=qe(v),re={"%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 re)v=v.replace(new RegExp(se,"g"),re[se]);var we="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),_e="January February March April May June July August September October November December".split(" ");re={"%a":P=>we[P.xa].substring(0,3),"%A":P=>we[P.xa],"%b":P=>_e[P.Ha].substring(0,3),"%B":P=>_e[P.Ha],"%C":P=>H((P.Da+1900)/100|0,2),"%d":P=>H(P.Ka,2),"%e":P=>B(P.Ka,2," "),"%g":P=>J(P).toString().substring(2),"%G":P=>J(P),"%H":P=>H(P.Ga,2),"%I":P=>(P=P.Ga,P==0?P=12:12{for(var ue=0,Se=0;Se<=P.Ha-1;ue+=($t(P.Da+1900)?br:Oe)[Se++]);return H(P.Ka+ue,3)},"%m":P=>H(P.Ha+1,2),"%M":P=>H(P.Xa,2),"%n":()=>`\n`,"%p":P=>0<=P.Ga&&12>P.Ga?"AM":"PM","%S":P=>H(P.Ya,2),"%t":()=>" ","%u":P=>P.xa||7,"%U":P=>H(Math.floor((P.Ca+7-P.xa)/7),2),"%V":P=>{var ue=Math.floor((P.Ca+7-(P.xa+6)%7)/7);if(2>=(P.xa+371-P.Ca-2)%7&&ue++,ue)ue==53&&(Se=(P.xa+371-P.Ca)%7,Se==4||Se==3&&$t(P.Da)||(ue=1));else{ue=52;var Se=(P.xa+7-P.Ca-1)%7;(Se==4||Se==5&&$t(P.Da%400-1))&&ue++}return H(ue,2)},"%w":P=>P.xa,"%W":P=>H(Math.floor((P.Ca+7-(P.xa+6)%7)/7),2),"%y":P=>(P.Da+1900).toString().substring(2),"%Y":P=>P.Da+1900,"%z":P=>{P=P.Wa;var ue=0<=P;return P=Math.abs(P)/60,(ue?"+":"-")+("0000"+(P/60*100+P%60)).slice(-4)},"%Z":P=>P.Za,"%%":()=>"%"},v=v.replace(/%%/g,"\\0\\0");for(se in re)v.includes(se)&&(v=v.replace(new RegExp(se,"g"),re[se](C)));return v=v.replace(/\\0\\0/g,"%"),se=wr(v),se.length>m?0:(R.set(se,d>>>0),se.length-1)}var St=d=>{try{d()}catch(m){he(m)}};function un(){var d=ae,m={};for(let[v,C]of Object.entries(d))m[v]=typeof C=="function"?function(){bt.push(v);try{return C.apply(null,arguments)}finally{A||(bt.pop(),tt&&ot===1&&bt.length===0&&(ot=0,St(ir),typeof Fibers<"u"&&Fibers.cb()))}}:C;return m}var ot=0,tt=null,de=0,bt=[],Zt={},vr={},$r=0,Qt=null,Sr=[];function xr(){return new Promise((d,m)=>{Qt={resolve:d,reject:m}})}function _r(){var d=Wt(65548),m=d+12;N[d>>>2>>>0]=m,N[d+4>>>2>>>0]=m+65536,m=bt[0];var v=Zt[m];return v===void 0&&(v=$r++,Zt[m]=v,vr[v]=m),T[d+8>>>2>>>0]=v,d}function Cr(d){if(!A){if(ot===0){var m=!1,v=!1;d((C=0)=>{if(!A&&(de=C,m=!0,v)){ot=2,St(()=>sr(tt)),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.resume(),C=!1;try{var B=(0,ae[vr[T[tt+8>>>2>>>0]]])()}catch(le){B=le,C=!0}var H=!1;if(!tt){var q=Qt;q&&(Qt=null,(C?q.reject:q.resolve)(B),H=!0)}if(C&&!H)throw B}}),v=!0,m||(ot=1,tt=_r(),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.pause(),St(()=>ar(tt)))}else ot===2?(ot=0,St(ur),er(tt),tt=null,Sr.forEach(C=>{if(!A)try{C();try{z=z=C=z,r.onExit?.(C),A=!0,l(C,new Me(C))}catch(B){B instanceof Me||B=="unwind"||l(1,B)}}catch(B){B instanceof Me||B=="unwind"||l(1,B)}})):he(`invalid state: ${ot}`);return de}}function Xt(d){return Cr(m=>{d().then(m)})}var Ir={n:function(d,m,v){return Xt(async()=>{await r.Ra(d,m,v)})},a:function(d,m,v){throw d>>>=0,new wt(d).$a(m>>>0,v>>>0),rt=d,Dt++,rt},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,m,v){d=m+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*m:NaN,v>>>=0,d=new Date(1e3*d),T[v>>>2>>>0]=d.getUTCSeconds(),T[v+4>>>2>>>0]=d.getUTCMinutes(),T[v+8>>>2>>>0]=d.getUTCHours(),T[v+12>>>2>>>0]=d.getUTCDate(),T[v+16>>>2>>>0]=d.getUTCMonth(),T[v+20>>>2>>>0]=d.getUTCFullYear()-1900,T[v+24>>>2>>>0]=d.getUTCDay(),T[v+28>>>2>>>0]=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(d,m,v){d=m+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*m:NaN,v>>>=0,d=new Date(1e3*d),T[v>>>2>>>0]=d.getSeconds(),T[v+4>>>2>>>0]=d.getMinutes(),T[v+8>>>2>>>0]=d.getHours(),T[v+12>>>2>>>0]=d.getDate(),T[v+16>>>2>>>0]=d.getMonth(),T[v+20>>>2>>>0]=d.getFullYear()-1900,T[v+24>>>2>>>0]=d.getDay(),T[v+28>>>2>>>0]=($t(d.getFullYear())?yt:zt)[d.getMonth()]+d.getDate()-1|0,T[v+36>>>2>>>0]=-(60*d.getTimezoneOffset()),m=new Date(d.getFullYear(),6,1).getTimezoneOffset();var C=new Date(d.getFullYear(),0,1).getTimezoneOffset();T[v+32>>>2>>>0]=(m!=C&&d.getTimezoneOffset()==Math.min(C,m))|0},s:function(d){d>>>=0;var m=new Date(T[d+20>>>2>>>0]+1900,T[d+16>>>2>>>0],T[d+12>>>2>>>0],T[d+8>>>2>>>0],T[d+4>>>2>>>0],T[d>>>2>>>0],0),v=T[d+32>>>2>>>0],C=m.getTimezoneOffset(),B=new Date(m.getFullYear(),6,1).getTimezoneOffset(),H=new Date(m.getFullYear(),0,1).getTimezoneOffset(),q=Math.min(H,B);return 0>v?T[d+32>>>2>>>0]=+(B!=H&&q==C):0>>2>>>0]=m.getDay(),T[d+28>>>2>>>0]=($t(m.getFullYear())?yt:zt)[m.getMonth()]+m.getDate()-1|0,T[d>>>2>>>0]=m.getSeconds(),T[d+4>>>2>>>0]=m.getMinutes(),T[d+8>>>2>>>0]=m.getHours(),T[d+12>>>2>>>0]=m.getDate(),T[d+16>>>2>>>0]=m.getMonth(),T[d+20>>>2>>>0]=m.getYear(),d=m.getTime(),isNaN(d)?(T[Jt()>>>2>>>0]=61,d=-1):d/=1e3,tr((ze=d,1<=+Math.abs(ze)?0>>0:~~+Math.ceil((ze-+(~~ze>>>0))/4294967296)>>>0:0)),d>>>0},o:function(){return-52},p:function(){},w:function(d,m,v){function C(J){return(J=J.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?J[1]:"GMT"}v>>>=0;var B=new Date().getFullYear(),H=new Date(B,0,1),q=new Date(B,6,1);B=H.getTimezoneOffset();var le=q.getTimezoneOffset();N[d>>>0>>>2>>>0]=60*Math.max(B,le),T[m>>>0>>>2>>>0]=+(B!=le),d=C(H),m=C(q),d=Ut(d),m=Ut(m),le>>2>>>0]=d,N[v+4>>>2>>>0]=m):(N[v>>>2>>>0]=m,N[v+4>>>2>>>0]=d)},e:()=>{he("")},b:function(d,m,v){return d>>>=0,m=Kt(m>>>0,v>>>0),Ue[d].apply(null,m)},i:function(d,m,v){return d>>>=0,m=Kt(m>>>0,v>>>0),Ue[d].apply(null,m)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(d,m,v){return m>>>=0,V.copyWithin(d>>>0>>>0,m>>>0,m+(v>>>0)>>>0)},u:function(d){d>>>=0;var m=V.length;if(4294901760=v;v*=2){var C=m*(1+.2/v);C=Math.min(C,d+100663296);var B=Math;C=Math.max(d,C);e:{B=(B.min.call(B,4294901760,C+(65536-C%65536)%65536)-E.buffer.byteLength+65535)/65536;try{E.grow(B),K();var H=1;break e}catch{}H=void 0}if(H)return!0}return!1},E:function(d,m){d>>>=0,m>>>=0;var v=0;return Yt().forEach((C,B)=>{var H=m+v;for(B=N[d+4*B>>>2>>>0]=H,H=0;H>>0>>>0]=C.charCodeAt(H);R[B>>>0>>>0]=0,v+=C.length+1}),0},F:function(d,m){d>>>=0,m>>>=0;var v=Yt();N[d>>>2>>>0]=v.length;var C=0;return v.forEach(B=>C+=B.length+1),N[m>>>2>>>0]=C,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(d,m,v,C){m>>>=0,v>>>=0,C>>>=0;for(var B=0,H=0;H>>2>>>0],le=N[m+4>>>2>>>0];m+=8;for(var J=0;J>>0],se=Ye[d];re===0||re===10?((d===1?$:x)(vt(se,0)),se.length=0):se.push(re)}B+=le}return N[C>>>2>>>0]=B,0},v:Nt,d:function(d,m,v,C){return Nt(d>>>0,m>>>0,v>>>0,C>>>0)}},ae=function(){function d(v){return ae=v.exports,ae=un(),ae=Ar(),E=ae.M,K(),Z.unshift(ae.N),Pe--,Pe==0&&(fe!==null&&(clearInterval(fe),fe=null),Ie&&(v=Ie,Ie=null,v())),ae}var m={a:Ir};if(Pe++,r.instantiateWasm)try{return r.instantiateWasm(m,d)}catch(v){x(`Module.instantiateWasm callback failed with error: ${v}`),n(v)}return et(m,function(v){d(v.instance)}).catch(n),{}}();r._OrtInit=(d,m)=>(r._OrtInit=ae.O)(d,m),r._OrtGetLastError=(d,m)=>(r._OrtGetLastError=ae.P)(d,m),r._OrtCreateSessionOptions=(d,m,v,C,B,H,q,le,J,re)=>(r._OrtCreateSessionOptions=ae.Q)(d,m,v,C,B,H,q,le,J,re),r._OrtAppendExecutionProvider=(d,m)=>(r._OrtAppendExecutionProvider=ae.R)(d,m),r._OrtAddFreeDimensionOverride=(d,m,v)=>(r._OrtAddFreeDimensionOverride=ae.S)(d,m,v),r._OrtAddSessionConfigEntry=(d,m,v)=>(r._OrtAddSessionConfigEntry=ae.T)(d,m,v),r._OrtReleaseSessionOptions=d=>(r._OrtReleaseSessionOptions=ae.U)(d),r._OrtCreateSession=(d,m,v)=>(r._OrtCreateSession=ae.V)(d,m,v),r._OrtReleaseSession=d=>(r._OrtReleaseSession=ae.W)(d),r._OrtGetInputOutputCount=(d,m,v)=>(r._OrtGetInputOutputCount=ae.X)(d,m,v),r._OrtGetInputName=(d,m)=>(r._OrtGetInputName=ae.Y)(d,m),r._OrtGetOutputName=(d,m)=>(r._OrtGetOutputName=ae.Z)(d,m),r._OrtFree=d=>(r._OrtFree=ae._)(d),r._OrtCreateTensor=(d,m,v,C,B,H)=>(r._OrtCreateTensor=ae.$)(d,m,v,C,B,H),r._OrtGetTensorData=(d,m,v,C,B)=>(r._OrtGetTensorData=ae.aa)(d,m,v,C,B),r._OrtReleaseTensor=d=>(r._OrtReleaseTensor=ae.ba)(d),r._OrtCreateRunOptions=(d,m,v,C)=>(r._OrtCreateRunOptions=ae.ca)(d,m,v,C),r._OrtAddRunConfigEntry=(d,m,v)=>(r._OrtAddRunConfigEntry=ae.da)(d,m,v),r._OrtReleaseRunOptions=d=>(r._OrtReleaseRunOptions=ae.ea)(d),r._OrtCreateBinding=d=>(r._OrtCreateBinding=ae.fa)(d),r._OrtBindInput=(d,m,v)=>(r._OrtBindInput=ae.ga)(d,m,v),r._OrtBindOutput=(d,m,v,C)=>(r._OrtBindOutput=ae.ha)(d,m,v,C),r._OrtClearBoundOutputs=d=>(r._OrtClearBoundOutputs=ae.ia)(d),r._OrtReleaseBinding=d=>(r._OrtReleaseBinding=ae.ja)(d),r._OrtRunWithBinding=(d,m,v,C,B)=>(r._OrtRunWithBinding=ae.ka)(d,m,v,C,B),r._OrtRun=(d,m,v,C,B,H,q,le)=>(r._OrtRun=ae.la)(d,m,v,C,B,H,q,le),r._OrtEndProfiling=d=>(r._OrtEndProfiling=ae.ma)(d),r._JsepOutput=(d,m,v)=>(r._JsepOutput=ae.na)(d,m,v),r._JsepGetNodeName=d=>(r._JsepGetNodeName=ae.oa)(d);var Jt=()=>(Jt=ae.pa)(),Wt=r._malloc=d=>(Wt=r._malloc=ae.qa)(d),er=r._free=d=>(er=r._free=ae.ra)(d),tr=d=>(tr=ae.ta)(d),rr=()=>(rr=ae.ua)(),nr=d=>(nr=ae.va)(d),or=d=>(or=ae.wa)(d),ar=d=>(ar=ae.ya)(d),ir=()=>(ir=ae.za)(),sr=d=>(sr=ae.Aa)(d),ur=()=>(ur=ae.Ba)();r.___start_em_js=943100,r.___stop_em_js=943261;function Ar(){var d=ae;d=Object.assign({},d);var m=C=>()=>C()>>>0,v=C=>B=>C(B)>>>0;return d.pa=m(d.pa),d.qa=v(d.qa),d.ua=m(d.ua),d.wa=v(d.wa),d}r.stackAlloc=or,r.stackSave=rr,r.stackRestore=nr,r.UTF8ToString=qe,r.stringToUTF8=(d,m,v)=>Mt(d,V,m,v),r.lengthBytesUTF8=qt;var xt;Ie=function d(){xt||Et(),xt||(Ie=d)};function Et(){if(!(0_o)});var Ao=dr(()=>{});var To=dr(()=>{});var Eo={};Br(Eo,{cpus:()=>Qu});var Qu,Oo=j(()=>{Qu=void 0});var Ro=dr((ko,$n)=>{"use strict";var Po=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){function r(){return Q.buffer!=fe.buffer&&Ge(),fe}function o(){return Q.buffer!=fe.buffer&&Ge(),Ie}function n(){return Q.buffer!=fe.buffer&&Ge(),he}function s(){return Q.buffer!=fe.buffer&&Ge(),ye}function u(){return Q.buffer!=fe.buffer&&Ge(),We}function l(){return Q.buffer!=fe.buffer&&Ge(),De}var a=t,p,h;a.ready=new Promise((i,c)=>{p=i,h=c}),a.mountExternalData=(i,c)=>{(a.cb||(a.cb=new Map)).set(i,c)},a.unmountExternalData=()=>{delete a.cb},a.jsepInit=(i,c,f,S,O,D,W,ie)=>{a.Mb=i,a.wb=c,a.yb=f,a.kb=S,a.xb=O,a.Ea=D,a.zb=W,a.Ab=ie,c=(ne,oe,pe)=>(...xe)=>{let Te=ut,k=oe?.();xe=ne(...xe);let me=oe?.();return k!==me&&(ne=me,pe(k),oe=pe=null),ut!=Te?Mu():xe},f=ne=>async(...oe)=>{try{if(a.bb)throw Error("Session already started");let pe=a.bb={Cb:oe[0],errors:[]},xe=await ne(...oe);if(a.bb!==pe)throw Error("Session mismatch");i.flush();let Te=pe.errors;if(0me),0a._OrtRun,ne=>a._OrtRun=ne)),a._OrtRunWithBinding=f(c(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,ne=>a._OrtRunWithBinding=ne)),a._OrtBindInput=c(a._OrtBindInput,()=>a._OrtBindInput,ne=>a._OrtBindInput=ne),a.jsepRegisterBuffer=(ne,oe,pe,xe)=>i.registerBuffer(ne,oe,pe,xe),a.jsepUnregisterBuffers=ne=>{i.unregisterBuffers(ne)},a.jsepGetBuffer=ne=>i.getBuffer(ne),a.jsepCreateDownloader=(ne,oe,pe)=>i.createDownloader(ne,oe,pe)};var g=Object.assign({},a),b="./this.program",w=(i,c)=>{throw c},y=typeof window=="object",_=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",$=a.ENVIRONMENT_IS_PTHREAD||!1,x="";function E(i){return a.locateFile?a.locateFile(i,x):x+i}var A,z,R;if(I){var V=(yn(),Ht(gn)),T=(wn(),Ht(bn));x=_?T.dirname(x)+"/":__dirname+"/",A=(c,f)=>(c=At(c)?new URL(c):T.normalize(c),V.readFileSync(c,f?void 0:"utf8")),R=c=>(c=A(c,!0),c.buffer||(c=new Uint8Array(c)),c),z=(c,f,S,O=!0)=>{c=At(c)?new URL(c):T.normalize(c),V.readFile(c,O?void 0:"utf8",(D,W)=>{D?S(D):f(O?W.buffer:W)})},!a.thisProgram&&1{throw process.exitCode=c,f},a.inspect=()=>"[Emscripten Module object]";let i;try{i=Ao()}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(y||_)&&(_?x=self.location.href:typeof document<"u"&&document.currentScript&&(x=document.currentScript.src),typeof e<"u"&&e&&(x=e),x.indexOf("blob:")!==0?x=x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):x="",I||(A=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.send(null),c.responseText},_&&(R=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),z=(i,c,f)=>{var S=new XMLHttpRequest;S.open("GET",i,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?c(S.response):f()},S.onerror=f,S.send(null)}));I&&typeof performance>"u"&&(global.performance=To().performance);var N=console.log.bind(console),te=console.error.bind(console);I&&(N=(...i)=>V.writeSync(1,i.join(" ")+`\n`),te=(...i)=>V.writeSync(2,i.join(" ")+`\n`));var Y=N,K=te;Object.assign(a,g),g=null,typeof WebAssembly!="object"&&rt("no native wasm support detected");var Q,Z,Ee=!1,Pe,fe,Ie,he,ye,We,De;function Ge(){var i=Q.buffer;a.HEAP8=fe=new Int8Array(i),a.HEAP16=new Int16Array(i),a.HEAPU8=Ie=new Uint8Array(i),a.HEAPU16=new Uint16Array(i),a.HEAP32=he=new Int32Array(i),a.HEAPU32=ye=new Uint32Array(i),a.HEAPF32=We=new Float32Array(i),a.HEAPF64=De=new Float64Array(i)}var G=16777216;if($)Q=a.wasmMemory;else if(a.wasmMemory)Q=a.wasmMemory;else if(Q=new WebAssembly.Memory({initial:G/65536,maximum:65536,shared:!0}),!(Q.buffer instanceof SharedArrayBuffer))throw K("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),I&&K("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ge(),G=Q.buffer.byteLength;var ee=[],be=[],et=[],ze=0,Ue=null,Me=null;function wt(){if(ze--,ze==0&&(Ue!==null&&(clearInterval(Ue),Ue=null),Me)){var i=Me;Me=null,i()}}function rt(i){throw i="Aborted("+i+")",K(i),Ee=!0,Pe=1,i=new WebAssembly.RuntimeError(i+". Build with -sASSERTIONS for more info."),h(i),i}var Dt=i=>i.startsWith("data:application/octet-stream;base64,"),At=i=>i.startsWith("file://"),vt;vt="ort-wasm-simd-threaded.wasm",Dt(vt)||(vt=E(vt));function qe(i){if(R)return R(i);throw"both async and sync fetching of the wasm failed"}function qt(i){if(y||_){if(typeof fetch=="function"&&!At(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(z)return new Promise((c,f)=>{z(i,S=>c(new Uint8Array(S)),f)})}return Promise.resolve().then(()=>qe(i))}function Mt(i,c,f){return qt(i).then(S=>WebAssembly.instantiate(S,c)).then(S=>S).then(f,S=>{K(`failed to asynchronously prepare wasm: ${S}`),rt(S)})}function $t(i,c){var f=vt;return typeof WebAssembly.instantiateStreaming!="function"||Dt(f)||At(f)||I||typeof fetch!="function"?Mt(f,i,c):fetch(f,{credentials:"same-origin"}).then(S=>WebAssembly.instantiateStreaming(S,i).then(c,function(O){return K(`wasm streaming compile failed: ${O}`),K("falling back to ArrayBuffer instantiation"),Mt(f,i,c)}))}var yt,zt={932428:(i,c,f,S)=>{if(typeof a>"u"||!a.cb)return 1;if(i=Ye(i>>>0),i.startsWith("./")&&(i=i.substring(2)),i=a.cb.get(i),!i)return 2;if(c>>>=0,f>>>=0,S>>>=0,c+f>i.byteLength)return 3;try{return o().set(i.subarray(c,c+f),S>>>0),0}catch{return 4}},932929:i=>a.wb(i),932962:i=>a.yb(i),932994:(i,c,f)=>{a.kb(i,c,f,!0)},933033:(i,c,f)=>{a.kb(i,c,f)},933066:i=>{a.Ea("Abs",i,void 0)},933117:i=>{a.Ea("Neg",i,void 0)},933168:i=>{a.Ea("Floor",i,void 0)},933221:i=>{a.Ea("Ceil",i,void 0)},933273:i=>{a.Ea("Reciprocal",i,void 0)},933331:i=>{a.Ea("Sqrt",i,void 0)},933383:i=>{a.Ea("Exp",i,void 0)},933434:i=>{a.Ea("Erf",i,void 0)},933485:i=>{a.Ea("Sigmoid",i,void 0)},933540:i=>{a.Ea("Log",i,void 0)},933591:i=>{a.Ea("Sin",i,void 0)},933642:i=>{a.Ea("Cos",i,void 0)},933693:i=>{a.Ea("Tan",i,void 0)},933744:i=>{a.Ea("Asin",i,void 0)},933796:i=>{a.Ea("Acos",i,void 0)},933848:i=>{a.Ea("Atan",i,void 0)},933900:i=>{a.Ea("Sinh",i,void 0)},933952:i=>{a.Ea("Cosh",i,void 0)},934004:i=>{a.Ea("Asinh",i,void 0)},934057:i=>{a.Ea("Acosh",i,void 0)},934110:i=>{a.Ea("Atanh",i,void 0)},934163:i=>{a.Ea("Tanh",i,void 0)},934215:i=>{a.Ea("Not",i,void 0)},934266:(i,c,f)=>{a.Ea("Clip",i,{min:c,max:f})},934335:i=>{a.Ea("Clip",i,void 0)},934387:(i,c)=>{a.Ea("Elu",i,{alpha:c})},934445:i=>{a.Ea("Relu",i,void 0)},934497:(i,c)=>{a.Ea("LeakyRelu",i,{alpha:c})},934561:(i,c)=>{a.Ea("ThresholdedRelu",i,{alpha:c})},934631:(i,c)=>{a.Ea("Cast",i,{to:c})},934689:i=>{a.Ea("Add",i,void 0)},934740:i=>{a.Ea("Sub",i,void 0)},934791:i=>{a.Ea("Mul",i,void 0)},934842:i=>{a.Ea("Div",i,void 0)},934893:i=>{a.Ea("Pow",i,void 0)},934944:i=>{a.Ea("Equal",i,void 0)},934997:i=>{a.Ea("Greater",i,void 0)},935052:i=>{a.Ea("GreaterOrEqual",i,void 0)},935114:i=>{a.Ea("Less",i,void 0)},935166:i=>{a.Ea("LessOrEqual",i,void 0)},935225:(i,c,f,S,O)=>{a.Ea("ReduceMean",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935384:(i,c,f,S,O)=>{a.Ea("ReduceMax",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935542:(i,c,f,S,O)=>{a.Ea("ReduceMin",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935700:(i,c,f,S,O)=>{a.Ea("ReduceProd",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935859:(i,c,f,S,O)=>{a.Ea("ReduceSum",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936017:(i,c,f,S,O)=>{a.Ea("ReduceL1",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936174:(i,c,f,S,O)=>{a.Ea("ReduceL2",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936331:(i,c,f,S,O)=>{a.Ea("ReduceLogSum",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936492:(i,c,f,S,O)=>{a.Ea("ReduceSumSquare",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936656:(i,c,f,S,O)=>{a.Ea("ReduceLogSumExp",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936820:i=>{a.Ea("Where",i,void 0)},936873:(i,c,f)=>{a.Ea("Transpose",i,{perm:c?Array.from(n().subarray(c>>>0,f>>>0)):[]})},936981:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me)=>{a.Ea("ConvTranspose",i,{format:ne?"NHWC":"NCHW",autoPad:c,dilations:[f],group:S,kernel_shape:[O],pads:[D,W],strides:[ie],wIsConst:()=>!!r()[oe>>>0],outputPadding:pe?Array.from(n().subarray(pe>>>0,xe>>>0)):[],outputShape:Te?Array.from(n().subarray(Te>>>0,k>>>0)):[],activation:Ye(me)})},937383:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k)=>{a.Ea("ConvTranspose",i,{format:ie?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(f>>>0,(f>>>0)+2>>>0)),group:S,kernelShape:Array.from(n().subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(n().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ne>>>0],outputPadding:oe?Array.from(n().subarray(oe>>>0,pe>>>0)):[],outputShape:xe?Array.from(n().subarray(xe>>>0,Te>>>0)):[],activation:Ye(k)})},937948:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me)=>{a.Ea("ConvTranspose",i,{format:ne?"NHWC":"NCHW",autoPad:c,dilations:[f],group:S,kernel_shape:[O],pads:[D,W],strides:[ie],wIsConst:()=>!!r()[oe>>>0],outputPadding:pe?Array.from(n().subarray(pe>>>0,xe>>>0)):[],outputShape:Te?Array.from(n().subarray(Te>>>0,k>>>0)):[],activation:Ye(me)})},938350:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k)=>{a.Ea("ConvTranspose",i,{format:ie?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(f>>>0,(f>>>0)+2>>>0)),group:S,kernelShape:Array.from(n().subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(n().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ne>>>0],outputPadding:oe?Array.from(n().subarray(oe>>>0,pe>>>0)):[],outputShape:xe?Array.from(n().subarray(xe>>>0,Te>>>0)):[],activation:Ye(k)})},938915:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939006:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("AveragePool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},939290:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939381:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("AveragePool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},939665:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},939752:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("MaxPool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},940032:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},940119:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("MaxPool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},940399:(i,c,f,S,O)=>{a.Ea("Gemm",i,{alpha:c,beta:f,transA:S,transB:O})},940503:i=>{a.Ea("MatMul",i,void 0)},940557:(i,c,f,S)=>{a.Ea("ArgMax",i,{keepDims:!!c,selectLastIndex:!!f,axis:S})},940665:(i,c,f,S)=>{a.Ea("ArgMin",i,{keepDims:!!c,selectLastIndex:!!f,axis:S})},940773:(i,c)=>{a.Ea("Softmax",i,{axis:c})},940836:(i,c)=>{a.Ea("Concat",i,{axis:c})},940896:(i,c,f,S,O)=>{a.Ea("Split",i,{axis:c,numOutputs:f,splitSizes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},941036:i=>{a.Ea("Expand",i,void 0)},941090:(i,c)=>{a.Ea("Gather",i,{axis:Number(c)})},941161:(i,c)=>{a.Ea("GatherElements",i,{axis:Number(c)})},941240:(i,c,f,S,O,D,W,ie,ne,oe,pe)=>{a.Ea("Resize",i,{antialias:c,axes:f?Array.from(n().subarray(f>>>0,S>>>0)):[],coordinateTransformMode:Ye(O),cubicCoeffA:D,excludeOutside:W,extrapolationValue:ie,keepAspectRatioPolicy:Ye(ne),mode:Ye(oe),nearestMode:Ye(pe)})},941586:(i,c,f,S,O,D,W)=>{a.Ea("Slice",i,{starts:c?Array.from(n().subarray(c>>>0,f>>>0)):[],ends:S?Array.from(n().subarray(S>>>0,O>>>0)):[],axes:D?Array.from(n().subarray(D>>>0,W>>>0)):[]})},941802:i=>{a.Ea("Tile",i,void 0)},941854:(i,c,f)=>{a.Ea("LayerNormalization",i,{axis:Number(c),epsilon:Number(f)})},941961:(i,c,f)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:f?"NHWC":"NCHW"})},942075:(i,c,f)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:f?"NHWC":"NCHW"})},942189:i=>{a.Ea("Range",i,void 0)},942242:(i,c)=>{a.Ea("Einsum",i,{equation:Ye(c)})},942323:(i,c,f,S,O)=>{a.Ea("Pad",i,{mode:c,value:f,pads:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},942450:(i,c,f,S,O,D)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:f,spatial:!!O,trainingMode:!!S,format:D?"NHWC":"NCHW"})},942619:(i,c,f,S,O,D)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:f,spatial:!!O,trainingMode:!!S,format:D?"NHWC":"NCHW"})},942788:(i,c,f)=>{a.Ea("CumSum",i,{exclusive:Number(c),reverse:Number(f)})},942885:(i,c,f,S,O,D,W,ie,ne)=>{a.Ea("Attention",i,{numHeads:c,isUnidirectional:f,maskFilterValue:S,scale:O,doRotary:D,qkvHiddenSizes:W?Array.from(n().subarray(Number(ie)>>>0,Number(ie)+W>>>0)):[],pastPresentShareBuffer:!!ne})},943157:i=>{a.Ea("Gelu",i,void 0)},943209:(i,c,f,S,O,D)=>{a.Ea("MultiHeadAttention",i,{numHeads:c,isUnidirectional:f,maskFilterValue:S,scale:O,doRotary:D})},943368:i=>{a.Ea("BiasAdd",i,void 0)},943423:i=>{a.Ea("BiasSplitGelu",i,void 0)},943484:(i,c)=>{a.Ea("SkipLayerNormalization",i,{epsilon:c})},943565:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te)=>{a.Ea("Conv",i,{format:ne?"NHWC":"NCHW",auto_pad:c,dilations:[f],group:S,kernel_shape:[O],pads:D?Array.from(n().subarray(D>>>0,W>>>0)):[],strides:[ie],w_is_const:()=>!!r()[oe>>>0],activation:Ye(pe),activation_params:xe?Array.from(u().subarray(xe>>>0,Te>>>0)):[]})},943935:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("Conv",i,{format:xe?"NHWC":"NCHW",auto_pad:c,dilations:[f,S],group:O,kernel_shape:[D,W],pads:ie?Array.from(n().subarray(ie>>>0,ne>>>0)):[],strides:[oe,pe],w_is_const:()=>!!r()[Te>>>0],activation:Ye(k),activation_params:me?Array.from(u().subarray(me>>>0,Ce>>>0)):[]})},944326:i=>{a.zb(i)},944360:(i,c)=>a.Ab(i,c,a.bb.Cb,a.bb.errors)};function Ut(i){this.name="ExitStatus",this.message=`Program terminated with exit(${i})`,this.status=i}var Tt=i=>{i.terminate(),i.onmessage=()=>{}},Kt=i=>{de.Ya.length==0&&(ot(),de.lb(de.Ya[0]));var c=de.Ya.pop();if(!c)return 6;de.Za.push(c),de.Qa[i.Xa]=c,c.Xa=i.Xa;var f={cmd:"run",start_routine:i.Db,arg:i.tb,pthread_ptr:i.Xa};return I&&c.unref(),c.postMessage(f,i.Jb),0},nt=0,Yt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Vt=(i,c,f)=>{c>>>=0;var S=c+f;for(f=c;i[f]&&!(f>=S);)++f;if(16O?S+=String.fromCharCode(O):(O-=65536,S+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else S+=String.fromCharCode(O)}return S},Ye=(i,c)=>(i>>>=0)?Vt(o(),i,c):"",br=i=>{var c=mn();return i=i(),kr(c),i};function Oe(i,c){var f=arguments.length-2,S=arguments;return br(()=>{for(var O=fn(8*f),D=O>>>3,W=0;W>>0]=ie}return po(i,f,O,c)})}function wr(i){if($)return Oe(0,1,i);Pe=i,0{if(Pe=i,$)throw Zt(i),"unwind";wr(i)},St=i=>{i instanceof Ut||i=="unwind"||w(1,i)};function un(){for(var i=a.numThreads;i--;)ot();ee.unshift(()=>{ze++,tt(()=>wt())})}function ot(){var i=E("ort-wasm-simd-threaded.worker.js");i=new Worker(i),de.Ya.push(i)}function tt(i){$?i():Promise.all(de.Ya.map(de.lb)).then(i)}var de={Ya:[],Za:[],pb:[],Qa:{},hb(){$?(de.receiveObjectTransfer=de.Bb,de.threadInitTLS=de.ob,de.setExitStatus=de.nb):un()},nb:i=>Pe=i,Nb:["$terminateWorker"],Eb:()=>{for(var i of de.Za)Tt(i);for(i of de.Ya)Tt(i);de.Ya=[],de.Za=[],de.Qa=[]},mb:i=>{var c=i.Xa;delete de.Qa[c],de.Ya.push(i),de.Za.splice(de.Za.indexOf(i),1),i.Xa=0,cn(c)},Bb(){},ob(){de.pb.forEach(i=>i())},lb:i=>new Promise(c=>{i.onmessage=D=>{D=D.data;var W=D.cmd;if(D.targetThread&&D.targetThread!=Pr()){var ie=de.Qa[D.targetThread];ie?ie.postMessage(D,D.transferList):K(`Internal error! Worker sent a message "${W}" to target pthread ${D.targetThread}, but that thread no longer exists!`)}else W==="checkMailbox"?Et():W==="spawnThread"?Kt(D):W==="cleanupThread"?de.mb(de.Qa[D.thread]):W==="killThread"?(D=D.thread,W=de.Qa[D],delete de.Qa[D],Tt(W),cn(D),de.Za.splice(de.Za.indexOf(W),1),W.Xa=0):W==="cancelThread"?de.Qa[D.thread].postMessage({cmd:"cancel"}):W==="loaded"?(i.loaded=!0,I&&!i.Xa&&i.unref(),c(i)):W==="alert"?alert(`Thread ${D.threadId}: ${D.text}`):D.target==="setimmediate"?i.postMessage(D):W==="callHandler"?a[D.handler](...D.args):W&&K(`worker sent an unknown command ${W}`)},i.onerror=D=>{throw K(`worker sent an error! ${D.filename}:${D.lineno}: ${D.message}`),D},I&&(i.on("message",D=>i.onmessage({data:D})),i.on("error",D=>i.onerror(D)));var f=[],S=["onExit"],O;for(O of S)a.hasOwnProperty(O)&&f.push(O);i.postMessage({cmd:"load",handlers:f,urlOrBlob:a.mainScriptUrlOrBlob||e,wasmMemory:Q,wasmModule:Z})})};a.PThread=de;var bt=i=>{for(;0{var i=Pr(),c=s()[i+52>>>2>>>0];i=s()[i+56>>>2>>>0],ho(c,c-i),kr(c)};function Zt(i){if($)return Oe(1,0,i);Nt(i)}a.invokeEntryPoint=(i,c)=>{i=go.apply(null,[i,c]),0>>2>>>0]=c},this.rb=function(c){s()[this.gb+8>>>2>>>0]=c},this.hb=function(c,f){this.qb(),this.sb(c),this.rb(f)},this.qb=function(){s()[this.gb+16>>>2>>>0]=0}}var $r=0,Qt=0;function Sr(i,c,f,S){return $?Oe(2,1,i,c,f,S):xr(i,c,f,S)}function xr(i,c,f,S){if(i>>>=0,c>>>=0,f>>>=0,S>>>=0,typeof SharedArrayBuffer>"u")return K("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var O=[];return $&&O.length===0?Sr(i,c,f,S):(i={Db:f,Xa:i,tb:S,Jb:O},$?(i.Lb="spawnThread",postMessage(i,O),0):Kt(i))}function _r(i,c,f){return $?Oe(3,1,i,c,f):0}function Cr(i,c){if($)return Oe(4,1,i,c)}var Xt=i=>{for(var c=0,f=0;f=S?c++:2047>=S?c+=2:55296<=S&&57343>=S?(c+=4,++f):c+=3}return c},Ir=(i,c,f,S)=>{if(f>>>=0,!(0=W){var ie=i.charCodeAt(++D);W=65536+((W&1023)<<10)|ie&1023}if(127>=W){if(f>=S)break;c[f++>>>0]=W}else{if(2047>=W){if(f+1>=S)break;c[f++>>>0]=192|W>>6}else{if(65535>=W){if(f+2>=S)break;c[f++>>>0]=224|W>>12}else{if(f+3>=S)break;c[f++>>>0]=240|W>>18,c[f++>>>0]=128|W>>12&63}c[f++>>>0]=128|W>>6&63}c[f++>>>0]=128|W&63}}return c[f>>>0]=0,f-O},ae=(i,c,f)=>Ir(i,o(),c,f);function Jt(i,c){if($)return Oe(5,1,i,c)}function Wt(i,c,f){if($)return Oe(6,1,i,c,f)}function er(i,c,f){return $?Oe(7,1,i,c,f):0}function tr(i,c){if($)return Oe(8,1,i,c)}function rr(i,c,f){if($)return Oe(9,1,i,c,f)}function nr(i,c,f,S){if($)return Oe(10,1,i,c,f,S)}function or(i,c,f,S){if($)return Oe(11,1,i,c,f,S)}function ar(i,c,f,S){if($)return Oe(12,1,i,c,f,S)}function ir(i){if($)return Oe(13,1,i)}function sr(i,c){if($)return Oe(14,1,i,c)}function ur(i,c,f){if($)return Oe(15,1,i,c,f)}var Ar=()=>{if(!(0>>=0,typeof Atomics.Kb=="function"&&(Atomics.Kb(n(),i>>>2,i).value.then(Et),i+=128,Atomics.store(n(),i>>>2,1))}a.__emscripten_thread_mailbox_await=xt;var Et=()=>{var i=Pr();if(i&&(xt(i),!Ee))try{mo(),Ar()}catch(c){St(c)}};a.checkMailbox=Et;var d=[],m=i=>i%4===0&&(i%100!==0||i%400===0),v=[0,31,60,91,121,152,182,213,244,274,305,335],C=[0,31,59,90,120,151,181,212,243,273,304,334];function B(i,c,f,S,O,D,W,ie){return $?Oe(16,1,i,c,f,S,O,D,W,ie):-52}function H(i,c,f,S,O,D,W){if($)return Oe(17,1,i,c,f,S,O,D,W)}var q=i=>{var c=Xt(i)+1,f=ln(c);return f&&ae(i,f,c),f},le=[],J=(i,c)=>{le.length=0;for(var f;f=o()[i++>>>0];){var S=f!=105;S&=f!=112,c+=S&&c%8?4:0,le.push(f==112?s()[c>>>2>>>0]:f==105?n()[c>>>2>>>0]:l()[c>>>3>>>0]),c+=S?8:4}return le},re={},se=()=>{if(!we){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",_:b||"./this.program"},c;for(c in re)re[c]===void 0?delete i[c]:i[c]=re[c];var f=[];for(c in i)f.push(`${c}=${i[c]}`);we=f}return we},we;function _e(i,c){if($)return Oe(18,1,i,c);i>>>=0,c>>>=0;var f=0;return se().forEach((S,O)=>{var D=c+f;for(O=s()[i+4*O>>>2>>>0]=D,D=0;D>>0>>>0]=S.charCodeAt(D);r()[O>>>0>>>0]=0,f+=S.length+1}),0}function P(i,c){if($)return Oe(19,1,i,c);i>>>=0,c>>>=0;var f=se();s()[i>>>2>>>0]=f.length;var S=0;return f.forEach(O=>S+=O.length+1),s()[c>>>2>>>0]=S,0}function ue(i){return $?Oe(20,1,i):52}function Se(i,c,f,S){return $?Oe(21,1,i,c,f,S):52}function st(i,c,f,S,O){return $?Oe(22,1,i,c,f,S,O):70}var Tr=[null,[],[]];function to(i,c,f,S){if($)return Oe(23,1,i,c,f,S);c>>>=0,f>>>=0,S>>>=0;for(var O=0,D=0;D>>2>>>0],ie=s()[c+4>>>2>>>0];c+=8;for(var ne=0;ne>>0],pe=Tr[i];oe===0||oe===10?((i===1?Y:K)(Vt(pe,0)),pe.length=0):pe.push(oe)}O+=ie}return s()[S>>>2>>>0]=O,0}var ro=[31,29,31,30,31,30,31,31,30,31,30,31],no=[31,28,31,30,31,30,31,31,30,31,30,31];function Pu(i){var c=Array(Xt(i)+1);return Ir(i,c,0,c.length),c}var ku=(i,c)=>{r().set(i,c>>>0)};function oo(i,c,f,S){function O(k,me,Ce){for(k=typeof k=="number"?k.toString():k||"";k.lengthSo?-1:0Ot-k.getDate())me-=Ot-k.getDate()+1,k.setDate(1),11>Ce?k.setMonth(Ce+1):(k.setMonth(0),k.setFullYear(k.getFullYear()+1));else{k.setDate(k.getDate()+me);break}}return Ce=new Date(k.getFullYear()+1,0,4),me=ie(new Date(k.getFullYear(),0,4)),Ce=ie(Ce),0>=W(me,k)?0>=W(Ce,k)?k.getFullYear()+1:k.getFullYear():k.getFullYear()-1}i>>>=0,c>>>=0,f>>>=0,S>>>=0;var oe=s()[S+40>>>2>>>0];S={Hb:n()[S>>>2>>>0],Gb:n()[S+4>>>2>>>0],eb:n()[S+8>>>2>>>0],jb:n()[S+12>>>2>>>0],fb:n()[S+16>>>2>>>0],ab:n()[S+20>>>2>>>0],Wa:n()[S+24>>>2>>>0],$a:n()[S+28>>>2>>>0],Ob:n()[S+32>>>2>>>0],Fb:n()[S+36>>>2>>>0],Ib:oe?Ye(oe):""},f=Ye(f),oe={"%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 pe in oe)f=f.replace(new RegExp(pe,"g"),oe[pe]);var xe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Te="January February March April May June July August September October November December".split(" ");oe={"%a":k=>xe[k.Wa].substring(0,3),"%A":k=>xe[k.Wa],"%b":k=>Te[k.fb].substring(0,3),"%B":k=>Te[k.fb],"%C":k=>D((k.ab+1900)/100|0,2),"%d":k=>D(k.jb,2),"%e":k=>O(k.jb,2," "),"%g":k=>ne(k).toString().substring(2),"%G":k=>ne(k),"%H":k=>D(k.eb,2),"%I":k=>(k=k.eb,k==0?k=12:12{for(var me=0,Ce=0;Ce<=k.fb-1;me+=(m(k.ab+1900)?ro:no)[Ce++]);return D(k.jb+me,3)},"%m":k=>D(k.fb+1,2),"%M":k=>D(k.Gb,2),"%n":()=>`\n`,"%p":k=>0<=k.eb&&12>k.eb?"AM":"PM","%S":k=>D(k.Hb,2),"%t":()=>" ","%u":k=>k.Wa||7,"%U":k=>D(Math.floor((k.$a+7-k.Wa)/7),2),"%V":k=>{var me=Math.floor((k.$a+7-(k.Wa+6)%7)/7);if(2>=(k.Wa+371-k.$a-2)%7&&me++,me)me==53&&(Ce=(k.Wa+371-k.$a)%7,Ce==4||Ce==3&&m(k.ab)||(me=1));else{me=52;var Ce=(k.Wa+7-k.$a-1)%7;(Ce==4||Ce==5&&m(k.ab%400-1))&&me++}return D(me,2)},"%w":k=>k.Wa,"%W":k=>D(Math.floor((k.$a+7-(k.Wa+6)%7)/7),2),"%y":k=>(k.ab+1900).toString().substring(2),"%Y":k=>k.ab+1900,"%z":k=>{k=k.Fb;var me=0<=k;return k=Math.abs(k)/60,(me?"+":"-")+("0000"+(k/60*100+k%60)).slice(-4)},"%Z":k=>k.Ib,"%%":()=>"%"},f=f.replace(/%%/g,"\\0\\0");for(pe in oe)f.includes(pe)&&(f=f.replace(new RegExp(pe,"g"),oe[pe](S)));return f=f.replace(/\\0\\0/g,"%"),pe=Pu(f),pe.length>c?0:(ku(pe,i),pe.length-1)}var Er=i=>{try{i()}catch(c){rt(c)}};function Ru(){var i=X,c={};for(let[f,S]of Object.entries(i))c[f]=typeof S=="function"?function(){Or.push(f);try{return S.apply(null,arguments)}finally{Ee||(Or.pop(),ut&&_t===1&&Or.length===0&&(_t=0,nt+=1,Er(bo),typeof Fibers<"u"&&Fibers.Pb()))}}:S;return c}var _t=0,ut=null,ao=0,Or=[],io={},so={},Bu=0,dn=null,Du=[];function Mu(){return new Promise((i,c)=>{dn={resolve:i,reject:c}})}function zu(){var i=ln(65548),c=i+12;s()[i>>>2>>>0]=c,s()[i+4>>>2>>>0]=c+65536,c=Or[0];var f=io[c];return f===void 0&&(f=Bu++,io[c]=f,so[f]=c),c=f,n()[i+8>>>2>>>0]=c,i}function Uu(){var i=n()[ut+8>>>2>>>0];return i=X[so[i]],--nt,i()}function Vu(i){if(!Ee){if(_t===0){var c=!1,f=!1;i((S=0)=>{if(!Ee&&(ao=S,c=!0,f)){_t=2,Er(()=>wo(ut)),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.resume(),S=!1;try{var O=Uu()}catch(ie){O=ie,S=!0}var D=!1;if(!ut){var W=dn;W&&(dn=null,(S?W.reject:W.resolve)(O),D=!0)}if(S&&!D)throw O}}),f=!0,c||(_t=1,ut=zu(),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.pause(),Er(()=>yo(ut)))}else _t===2?(_t=0,Er(vo),lo(ut),ut=null,Du.forEach(S=>{if(!Ee)try{S(),Ar()}catch(O){St(O)}})):rt(`invalid state: ${_t}`);return ao}}function Nu(i){return Vu(c=>{i().then(c)})}de.hb();var Wu=[wr,Zt,Sr,_r,Cr,Jt,Wt,er,tr,rr,nr,or,ar,ir,sr,ur,B,H,_e,P,ue,Se,st,to],Hu={r:function(i,c,f){return Nu(async()=>{await a.xb(i,c,f)})},b:function(i,c,f){throw i>>>=0,new vr(i).hb(c>>>0,f>>>0),$r=i,Qt++,$r},N:function(i){co(i>>>0,!_,1,!y,131072,!1),de.ob()},l:function(i){i>>>=0,$?postMessage({cmd:"cleanupThread",thread:i}):de.mb(de.Qa[i])},J:xr,i:_r,T:Cr,F:Jt,H:Wt,U:er,R:tr,L:rr,Q:nr,p:or,G:ar,D:ir,S:sr,E:ur,q:()=>1,B:function(i,c){i>>>=0,i==c>>>0?setTimeout(()=>Et()):$?postMessage({targetThread:i,cmd:"checkMailbox"}):(i=de.Qa[i])&&i.postMessage({cmd:"checkMailbox"})},K:function(i,c,f,S){c>>>=0,d.length=f,S=S>>>0>>>3;for(var O=0;O>>0];return i=0>i?zt[-i-1]:Wu[i],de.ub=c,c=i.apply(null,d),de.ub=0,c},M:xt,W:function(i){I&&de.Qa[i>>>0].ref()},u:function(i,c,f){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,f>>>=0,i=new Date(1e3*i),n()[f>>>2>>>0]=i.getUTCSeconds(),n()[f+4>>>2>>>0]=i.getUTCMinutes(),n()[f+8>>>2>>>0]=i.getUTCHours(),n()[f+12>>>2>>>0]=i.getUTCDate(),n()[f+16>>>2>>>0]=i.getUTCMonth(),n()[f+20>>>2>>>0]=i.getUTCFullYear()-1900,n()[f+24>>>2>>>0]=i.getUTCDay(),i=(i.getTime()-Date.UTC(i.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,n()[f+28>>>2>>>0]=i},v:function(i,c,f){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,f>>>=0,i=new Date(1e3*i),n()[f>>>2>>>0]=i.getSeconds(),n()[f+4>>>2>>>0]=i.getMinutes(),n()[f+8>>>2>>>0]=i.getHours(),n()[f+12>>>2>>>0]=i.getDate(),n()[f+16>>>2>>>0]=i.getMonth(),n()[f+20>>>2>>>0]=i.getFullYear()-1900,n()[f+24>>>2>>>0]=i.getDay(),c=(m(i.getFullYear())?v:C)[i.getMonth()]+i.getDate()-1|0,n()[f+28>>>2>>>0]=c,n()[f+36>>>2>>>0]=-(60*i.getTimezoneOffset()),c=new Date(i.getFullYear(),6,1).getTimezoneOffset();var S=new Date(i.getFullYear(),0,1).getTimezoneOffset();i=(c!=S&&i.getTimezoneOffset()==Math.min(S,c))|0,n()[f+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),f=n()[i+32>>>2>>>0],S=c.getTimezoneOffset(),O=new Date(c.getFullYear(),6,1).getTimezoneOffset(),D=new Date(c.getFullYear(),0,1).getTimezoneOffset(),W=Math.min(D,O);return 0>f?n()[i+32>>>2>>>0]=+(O!=D&&W==S):0>>2>>>0]=c.getDay(),f=(m(c.getFullYear())?v:C)[c.getMonth()]+c.getDate()-1|0,n()[i+28>>>2>>>0]=f,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()[uo()>>>2>>>0]=61,i=-1):i/=1e3,fo((yt=i,1<=+Math.abs(yt)?0>>0:~~+Math.ceil((yt-+(~~yt>>>0))/4294967296)>>>0:0)),i>>>0},s:B,t:H,A:function(i,c,f){function S(oe){return(oe=oe.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?oe[1]:"GMT"}i>>>=0,c>>>=0,f>>>=0;var O=new Date().getFullYear(),D=new Date(O,0,1),W=new Date(O,6,1);O=D.getTimezoneOffset();var ie=W.getTimezoneOffset(),ne=Math.max(O,ie);s()[i>>>2>>>0]=60*ne,n()[c>>>2>>>0]=+(O!=ie),i=S(D),c=S(W),i=q(i),c=q(c),ie>>2>>>0]=i,s()[f+4>>>2>>>0]=c):(s()[f>>>2>>>0]=c,s()[f+4>>>2>>>0]=i)},d:()=>{rt("")},c:function(i,c,f){return i>>>=0,c=J(c>>>0,f>>>0),zt[i].apply(null,c)},k:function(i,c,f){return i>>>=0,c=J(c>>>0,f>>>0),zt[i].apply(null,c)},m:()=>{},j:()=>Date.now(),V:()=>{throw nt+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>I?(Oo(),Ht(Eo)).cpus().length:navigator.hardwareConcurrency,y:function(i){i>>>=0;var c=o().length;if(i<=c||4294901760=f;f*=2){var S=c*(1+.2/f);S=Math.min(S,i+100663296);var O=Math;S=Math.max(i,S);e:{O=(O.min.call(O,4294901760,S+(65536-S%65536)%65536)-Q.buffer.byteLength+65535)/65536;try{Q.grow(O),Ge();var D=1;break e}catch{}D=void 0}if(D)return!0}return!1},O:_e,P,I:Nt,h:ue,o:Se,x:st,n:to,a:Q||a.wasmMemory,z:oo,e:function(i,c,f,S){return oo(i>>>0,c>>>0,f>>>0,S>>>0)}},X=function(){function i(f,S){return X=f.exports,X=Ru(),X=Gu(),de.pb.push(X.Da),be.unshift(X.X),Z=S,wt(),X}var c={a:Hu};if(ze++,a.instantiateWasm)try{return a.instantiateWasm(c,i)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),h(f)}return $t(c,function(f){i(f.instance,f.module)}).catch(h),{}}();a._OrtInit=(i,c)=>(a._OrtInit=X.Y)(i,c),a._OrtGetLastError=(i,c)=>(a._OrtGetLastError=X.Z)(i,c),a._OrtCreateSessionOptions=(i,c,f,S,O,D,W,ie,ne,oe)=>(a._OrtCreateSessionOptions=X._)(i,c,f,S,O,D,W,ie,ne,oe),a._OrtAppendExecutionProvider=(i,c)=>(a._OrtAppendExecutionProvider=X.$)(i,c),a._OrtAddFreeDimensionOverride=(i,c,f)=>(a._OrtAddFreeDimensionOverride=X.aa)(i,c,f),a._OrtAddSessionConfigEntry=(i,c,f)=>(a._OrtAddSessionConfigEntry=X.ba)(i,c,f),a._OrtReleaseSessionOptions=i=>(a._OrtReleaseSessionOptions=X.ca)(i),a._OrtCreateSession=(i,c,f)=>(a._OrtCreateSession=X.da)(i,c,f),a._OrtReleaseSession=i=>(a._OrtReleaseSession=X.ea)(i),a._OrtGetInputOutputCount=(i,c,f)=>(a._OrtGetInputOutputCount=X.fa)(i,c,f),a._OrtGetInputName=(i,c)=>(a._OrtGetInputName=X.ga)(i,c),a._OrtGetOutputName=(i,c)=>(a._OrtGetOutputName=X.ha)(i,c),a._OrtFree=i=>(a._OrtFree=X.ia)(i),a._OrtCreateTensor=(i,c,f,S,O,D)=>(a._OrtCreateTensor=X.ja)(i,c,f,S,O,D),a._OrtGetTensorData=(i,c,f,S,O)=>(a._OrtGetTensorData=X.ka)(i,c,f,S,O),a._OrtReleaseTensor=i=>(a._OrtReleaseTensor=X.la)(i),a._OrtCreateRunOptions=(i,c,f,S)=>(a._OrtCreateRunOptions=X.ma)(i,c,f,S),a._OrtAddRunConfigEntry=(i,c,f)=>(a._OrtAddRunConfigEntry=X.na)(i,c,f),a._OrtReleaseRunOptions=i=>(a._OrtReleaseRunOptions=X.oa)(i),a._OrtCreateBinding=i=>(a._OrtCreateBinding=X.pa)(i),a._OrtBindInput=(i,c,f)=>(a._OrtBindInput=X.qa)(i,c,f),a._OrtBindOutput=(i,c,f,S)=>(a._OrtBindOutput=X.ra)(i,c,f,S),a._OrtClearBoundOutputs=i=>(a._OrtClearBoundOutputs=X.sa)(i),a._OrtReleaseBinding=i=>(a._OrtReleaseBinding=X.ta)(i),a._OrtRunWithBinding=(i,c,f,S,O)=>(a._OrtRunWithBinding=X.ua)(i,c,f,S,O),a._OrtRun=(i,c,f,S,O,D,W,ie)=>(a._OrtRun=X.va)(i,c,f,S,O,D,W,ie),a._OrtEndProfiling=i=>(a._OrtEndProfiling=X.wa)(i),a._JsepOutput=(i,c,f)=>(a._JsepOutput=X.xa)(i,c,f),a._JsepGetNodeName=i=>(a._JsepGetNodeName=X.ya)(i);var uo=()=>(uo=X.za)(),Pr=a._pthread_self=()=>(Pr=a._pthread_self=X.Aa)(),ln=a._malloc=i=>(ln=a._malloc=X.Ba)(i),lo=a._free=i=>(lo=a._free=X.Ca)(i);a.__emscripten_tls_init=()=>(a.__emscripten_tls_init=X.Da)();var co=a.__emscripten_thread_init=(i,c,f,S,O,D)=>(co=a.__emscripten_thread_init=X.Fa)(i,c,f,S,O,D);a.__emscripten_thread_crashed=()=>(a.__emscripten_thread_crashed=X.Ga)();var po=(i,c,f,S)=>(po=X.Ha)(i,c,f,S),cn=i=>(cn=X.Ia)(i),pn=a.__emscripten_thread_exit=i=>(pn=a.__emscripten_thread_exit=X.Ja)(i),mo=()=>(mo=X.Ka)(),fo=i=>(fo=X.La)(i),ho=(i,c)=>(ho=X.Ma)(i,c),mn=()=>(mn=X.Na)(),kr=i=>(kr=X.Oa)(i),fn=i=>(fn=X.Pa)(i),go=a.dynCall_ii=(i,c)=>(go=a.dynCall_ii=X.Ra)(i,c),yo=i=>(yo=X.Sa)(i),bo=()=>(bo=X.Ta)(),wo=i=>(wo=X.Ua)(i),vo=()=>(vo=X.Va)();a.___start_em_js=944472,a.___stop_em_js=944633;function Gu(){var i=X;i=Object.assign({},i);var c=S=>()=>S()>>>0,f=S=>O=>S(O)>>>0;return i.za=c(i.za),i.Aa=c(i.Aa),i.Ba=f(i.Ba),i.emscripten_main_runtime_thread_id=c(i.emscripten_main_runtime_thread_id),i.Na=c(i.Na),i.Pa=f(i.Pa),i}a.wasmMemory=Q,a.stackAlloc=fn,a.stackSave=mn,a.stackRestore=kr,a.keepRuntimeAlive=()=>0Po)});var Bo=dr((qc,Xu)=>{Xu.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 _n,Xe,cr,Mr,pr,No,Cn,Ne=j(()=>{"use strict";_n=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}`)}},Xe=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}`)}},cr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Mr=e=>{switch(e){case"float16":return 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}`)}},pr=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}`)}},No=e=>e==="float32"||e==="int32"||e==="int64"||e==="bool"||e==="float16"||e==="uint32",Cn=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 zr=j(()=>{"use strict"});var Ho=j(()=>{"use strict";zr()});var Go,Lo=j(()=>{"use strict";Go="1.17.1"});var Fo,Pt,In=j(()=>{"use strict";Lo();Fo="warning",Pt={wasm:{},webgl:{},webgpu:{},versions:{common:Go},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}`);Fo=e}},get logLevel(){return Fo}};Object.defineProperty(Pt,"logLevel",{enumerable:!0})});var Gt,jo=j(()=>{"use strict";In();Gt=Pt});var qo=j(()=>{"use strict"});var Ko=j(()=>{"use strict";Ur()});var Zo=j(()=>{"use strict"});var Qo=j(()=>{"use strict";Ur()});var Ur=j(()=>{"use strict";qo();Ko();Zo();Qo()});var Vr=j(()=>{"use strict";Ur()});var An,Xo,kt,Rt,Tn=j(()=>{"use strict";In();An=(e,t)=>{Pt.wasm.trace&&console.timeStamp(`${e}::ORT::${t}`)},Xo=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let n=0;n{Pt.wasm.trace&&Xo("BEGIN",e)},Rt=e=>{Pt.wasm.trace&&Xo("END",e)}});var Jo=j(()=>{"use strict";zr();Vr();Tn()});var ea=j(()=>{"use strict";Jo()});var ta=j(()=>{"use strict"});var ra=j(()=>{"use strict";zr();Vr()});var na=j(()=>{"use strict";ra()});var Lt=j(()=>{"use strict";Ho();jo();ea();Vr();Tn();ta();na()});var dd,ld,oa,aa,ia,cd,Be,Ct=j(()=>{"use strict";Ne();dd=["V","I","W","E","F"],ld=(e,t)=>{console.log(`[${dd[e]},${new Date().toISOString()}]${t}`)},ia=(e,t)=>{oa=e,aa=t},cd=(e,t)=>{let r=pr(e),o=pr(oa);r>=o&&ld(r,typeof t=="function"?t():t)},Be=(...e)=>{aa&&cd(...e)}});var sa,ua=j(()=>{"use strict";Ne();sa=(e,t)=>new(Mr(t))(e)});var Nr=j(()=>{"use strict"});var Wr,pd,da,On,En,ca,pa=j(()=>{"use strict";Ct();Nr();Wr=e=>Math.ceil(e/16)*16,pd=1,da=()=>pd++,On=async(e,t,r,o)=>{let n=Wr(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()}},En=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}upload(t,r){let o=r.buffer,n=r.byteOffset,s=r.byteLength,u=Wr(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 h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.copyBufferToBuffer(a,0,l.gpuData.buffer,0,u),Be("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=Wr(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 Be("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, buffer is the same, skip.`),n;this.externalBuffers.delete(o)}else n=da();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,n),Be("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),Be("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Wr(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:da(),type:0,buffer:n};return this.storageCache.set(l.id,{gpuData:l,originalSize:t}),Be("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 Be("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 On(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();this.buffersForUploadingPending=[];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=[]}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.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map}},ca=(...e)=>new En(...e)});var Pn,ge,je=j(()=>{"use strict";Pn=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}},ge=e=>new Pn(e)});var kn,dt,U,Bt,Hr,Gr,Lr,$e=j(()=>{"use strict";kn=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},dt=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=kn.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],h=s-a<0?1:r[s-a];if(p!==h&&p>1&&h>1)return;l[u-a]=Math.max(p,h)}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}},U=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}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])}},Bt=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";Ne();$e();md=64,Bn=(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}`)}},Le=(e,t=1)=>{let r=Bn(e,t);return typeof r=="string"?r:r[0]},lt=(e,t=1)=>{let r=Bn(e,t);return typeof r=="string"?r:r[1]},L=e=>e.length===0?[]:[{type:"uint32",data:e},{type:"uint32",data:U.computeStrides(e)}],Fe=e=>e%4===0?4:e%2===0?2:1,Ze=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,at=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}f(${r})`,Je=(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,ce=(e,t,r)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?`${e}[(${t}) / 4][(${t}) % 4]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Dn=(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=Bn(t,n),h=typeof p=="string"?p:p[1],g=typeof p=="string"?p:p[0],b={indices:a,value:h,storage:g,tensor:t},w=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`,$=`${_}${e}_strides`,x="";for(let G=0;G ${b.indices} {\n var indices: ${b.indices};\n var current = offset;\n ${x}\n return indices;\n }`,A=G=>(y.offsetToIndices=!0,u<2?G:`o2i_${e}(${G})`),z=[];if(u>=2)for(let G=u-1;G>=0;G--)z.push(`${ce($,G,u)} * (indices[${G}])`);let R=u<2?"":`\n fn i2o_${e}(indices: ${b.indices}) -> u32 {\n return ${z.join("+")};\n }`,V=G=>(y.indicesToOffset=!0,u<2?G:`i2o_${e}(${G})`),T=(...G)=>u===0?"0u":`${b.indices}(${G.map(w).join(",")})`,N=(G,ee)=>u<2?`${G}`:`${ce(G,ee,u)}`,te=(G,ee,be)=>u<2?`${G}=${be};`:`${ce(G,ee,u)}=${be};`,Y={},K=(G,ee)=>{y.broadcastedIndicesToOffset=!0;let be=`${ee.name}broadcastedIndicesTo${e}Offset`;if(be in Y)return`${be}(${G})`;let et=[];for(let ze=u-1;ze>=0;ze--){let Ue=ee.indicesGet("outputIndices",ze+ee.rank-u);et.push(`${N($,ze)} * (${Ue} % ${N(I,ze)})`)}return Y[be]=`fn ${be}(outputIndices: ${ee.type.indices}) -> u32 {\n return ${et.length>0?et.join("+"):"0u"};\n }`,`${be}(${G})`},Q=(G,ee)=>(()=>{if(b.storage===b.value)return`${e}[${G}]=${ee};`;if(b.storage==="vec2"&&b.value==="i32")return`${e}[${G}]=vec2(u32(${ee}), select(0u, 0xFFFFFFFFu, ${ee} < 0));`;if(b.storage==="vec2"&&b.value==="u32")return`${e}[${G}]=vec2(u32(${ee}), 0u);`;if(b.storage==="u32"&&b.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ee}));`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),Z=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`)})(),Ee=u<2?"":`\n fn get_${e}ByIndices(indices: ${b.indices}) -> ${h} {\n return ${Z(`i2o_${e}(indices)`)};\n }`,Pe=u<2?"":(()=>{let G=l.map(be=>`d${be}: u32`).join(", "),ee=l.map(be=>`d${be}`).join(", ");return`\n fn get_${e}(${G}) -> ${h} {\n return get_${e}ByIndices(${T(ee)});\n }`})(),fe=(...G)=>{if(G.length!==u)throw new Error(`indices length must be ${u}`);let ee=G.map(w).join(",");return u===0?Z("0u"):u===1?Z(ee[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${ee})`)},Ie=G=>u<2?Z(G):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${G})`),he=u<2?"":`\n fn set_${e}ByIndices(indices: ${b.indices}, value: ${h}) {\n ${Q(`i2o_${e}(indices)`,"value")}\n }`,ye=u<2?"":(()=>{let G=l.map(be=>`d${be}: u32`).join(", "),ee=l.map(be=>`d${be}`).join(", ");return`\n fn set_${e}(${G}, value: ${h}) {\n set_${e}ByIndices(${T(ee)}, value);\n }`})();return{impl:()=>{let G=[],ee=!1;return y.offsetToIndices&&(G.push(E),ee=!0),y.indicesToOffset&&(G.push(R),ee=!0),y.broadcastedIndicesToOffset&&(Object.values(Y).forEach(be=>G.push(be)),ee=!0),y.set&&(G.push(ye),ee=!0),y.setByIndices&&(G.push(he),ee=!0),y.get&&(G.push(Pe),ee=!0),y.getByIndices&&(G.push(Ee),ee=!0),!s&&ee&&G.unshift(`const ${I} = ${b.indices}(${r.join(",")});`,`const ${$} = ${b.indices}(${U.computeStrides(r).join(",")});`),G.join(`\n`)},type:b,offsetToIndices:A,indicesToOffset:V,broadcastedIndicesToOffset:K,indices:T,indicesGet:N,indicesSet:te,set:(...G)=>{if(G.length!==u+1)throw new Error(`indices length must be ${u}`);let ee=G[u];if(typeof ee!="string")throw new Error("value must be string");let be=G.slice(0,u).map(w).join(",");return u===0?Q("0u",ee):u===1?Q(be[0],ee):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${be}, ${ee})`)},setByOffset:Q,setByIndices:(G,ee)=>u<2?Q(G,ee):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${ee});`),get:fe,getByOffset:Z,getByIndices:Ie,usage:o,name:e,strides:$,shape:I,rank:u}},M=(e,t,r,o=1)=>Dn(e,t,r,"input",o),F=(e,t,r,o=1)=>Dn(e,t,r,"output",o),Fr=(e,t,r,o=1)=>Dn(e,t,r,"internal",o),Rn=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=md){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)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`)}},ma=e=>new Rn(e),Ft=(e,t)=>{let r=e.length,o=[];for(let n=0;n1&&u===1&&o.unshift(s)}return o},Re=e=>!0});var fd,fa,hd,gd,it,ha,ga,jt=j(()=>{"use strict";$e();je();ve();fd=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},fa=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,hd=(e,t)=>U.sortBasedOnPerm(e,fa(e.length,t)),gd=(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=fa(o,t),s=Re(o),u=hd(e.dims,n),l=s?u.length:u,a=s?o:e.dims,p=F("output",r,l),h=M("a",r,a),g=b=>`\n ${b.registerUniform("output_size","u32").declareVariables(h,p)}\n\n ${gd(n,o,h,p)}\n\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${p.setByOffset("global_idx",h.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:s?["rank"]:["dims"]},getRunData:b=>{let w=U.size(u);return{outputs:[{dims:u,dataType:b[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:s?[{type:"uint32",data:w},...L(b[0].dims),...L(u)]:[{type:"uint32",data:w}]}},getShaderSource:g}},ha=(e,t)=>{fd(e.inputs),e.compute(it(e.inputs[0],t.perm))},ga=e=>ge({perm:e.perm})});var yd,bd,wd,vd,$d,Sd,xd,_d,Cd,Id,ct,ya,ba,wa,va,$a,Sa,xa,_a,Ca,Ia,Aa=j(()=>{"use strict";$e();ve();jr();jt();yd={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"},bd={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"},wd={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},vd={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},$d=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let s=0;se[s]);return[r,n]},xd=(e,t)=>{let r=e.length+t.length,o=[],n=0;for(let s=0;s{for(let r=0;r{let r=[];if(!_d(e,t)){for(let o=0;or.push(o))}return r},Id=(e,t,r,o,n,s,u)=>{let l=r[0].dims,a=U.size(s),p=U.size(u),h=M("_A",r[0].dataType,l),g=F("output",n,s),b=32,w=`\n var aBestValues : array<${g.type.storage}, ${b}>;\n `;return{name:e,shaderCache:t,getShaderSource:_=>`\n ${_.registerUniform("reduceSize","u32").declareVariables(h,g)}\n ${w}\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 = ${g.type.storage}(${wd[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${b}) {\n let candidate = ${g.type.storage}(${h.getByOffset("offset + k")});\n bestValue = ${yd[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 = ${bd[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${g.setByOffset("outputIndex",`${o==="mean"?`bestValue / ${g.type.storage}(uniforms.reduceSize)`:`${vd[o]}`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:a},programUniforms:[{type:"uint32",data:p}]})}},ct=(e,t,r,o)=>{let n=e.inputs.length===1?r:Mn(e.inputs,r),s=n.axes;s.length===0&&!n.noopWithEmptyAxes&&(s=e.inputs[0].dims.map((w,y)=>y));let u=U.normalizeAxes(s,e.inputs[0].dims.length),l=u,a=e.inputs[0],p=Cd(l,e.inputs[0].dims.length);p.length>0&&(a=e.compute(it(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=$d(l.length,a.dims.length));let[h,g]=Sd(a.dims,l),b=h;n.keepDims&&(b=xd(h,u)),e.compute(Id(t,{hint:n.cacheKey,inputDependencies:["type"]},[a],o,e.inputs[0].dataType,b,g),{inputs:[a]})},ya=(e,t)=>{ct(e,"ReduceMeanShared",t,"mean")},ba=(e,t)=>{ct(e,"ReduceL1Shared",t,"l1")},wa=(e,t)=>{ct(e,"ReduceL2Shared",t,"l2")},va=(e,t)=>{ct(e,"ReduceLogSumExpShared",t,"logSumExp")},$a=(e,t)=>{ct(e,"ReduceMaxShared",t,"max")},Sa=(e,t)=>{ct(e,"ReduceMinShared",t,"min")},xa=(e,t)=>{ct(e,"ReduceProdShared",t,"prod")},_a=(e,t)=>{ct(e,"ReduceSumShared",t,"sum")},Ca=(e,t)=>{ct(e,"ReduceSumSquareShared",t,"sumSquare")},Ia=(e,t)=>{ct(e,"ReduceLogSumShared",t,"logSum")}});var pt,Ad,qr,Mn,mt,Td,Ed,Od,Pd,kd,Rd,Bd,Dd,Md,zd,ft,Ta,Ea,Oa,Pa,ka,Ra,Ba,Da,Ma,za,jr=j(()=>{"use strict";$e();je();ve();Aa();pt=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.")},Ad=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],qr=(e,t,r,o,n,s,u=!1,l=!1)=>{let a=[],p=r[0].dims,h=p.length,g=U.normalizeAxes(n,h),b=!l&&g.length===0;p.forEach((I,$)=>{b||g.indexOf($)>=0?u&&a.push(1):a.push(I)});let w=a.length,y=U.size(a);return{name:e,shaderCache:t,getShaderSource:I=>{let $=[],x=M("_A",r[0].dataType,h),E=F("output",s,w),A=o(x,E,g),z=A[2];for(let R=0,V=0;R=0?(u&&V++,z=`for(var j${R}: u32 = 0; j${R} < ${p[R]}; j${R}++) {\n ${A[2].includes("last_index")?`let last_index = j${R};`:""}\n ${x.indicesSet("input_indices",R,`j${R}`)}\n ${z}\n }`):($.push(`${x.indicesSet("input_indices",R,E.indicesGet("output_indices",V))};`),V++);return`\n\n ${I.registerUniform("output_size","u32").declareVariables(x,E)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${x.type.indices};\n let output_indices = ${E.offsetToIndices("global_idx")};\n\n ${$.join(`\n`)}\n ${A[0]} // init ops for reduce max/min\n ${A[1]}\n ${z}\n ${A[3]}\n ${A.length===4?E.setByOffset("global_idx","value"):A.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:"uint32",data:y},...L(p),...L(a)]})}},Mn=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),ge({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},mt=(e,t,r,o)=>{let n=e.inputs,s=n.length===1?r:Mn(n,r);e.compute(qr(t,{hint:s.cacheKey,inputDependencies:["rank"]},[n[0]],s.noopWithEmptyAxes&&s.axes.length===0?Ad:o,s.axes,n[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},Td=(e,t)=>{pt(e.inputs),mt(e,"ReduceLogSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Ed=(e,t)=>{pt(e.inputs),mt(e,"ReduceL1",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},Od=(e,t)=>{pt(e.inputs),mt(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);"])},Pd=(e,t)=>{pt(e.inputs),mt(e,"ReduceLogSumExp",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},kd=(e,t)=>{pt(e.inputs),mt(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")});`,""]})},Rd=(e,t)=>{pt(e.inputs),mt(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});`]})},Bd=(e,t)=>{pt(e.inputs),mt(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")});`,""]})},Dd=(e,t)=>{pt(e.inputs),mt(e,"ReduceProd",t,(o,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},Md=(e,t)=>{pt(e.inputs),mt(e,"ReduceSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},zd=(e,t)=>{pt(e.inputs),mt(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;`,""])},ft=(e,t,r)=>{if(t.length===0)return r;let o=1,n=1;for(let s=0;s1024},Ta=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Rd(e,t):ya(e,t)},Ea=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ed(e,t):ba(e,t)},Oa=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Od(e,t):wa(e,t)},Pa=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pd(e,t):va(e,t)},ka=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?kd(e,t):$a(e,t)},Ra=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bd(e,t):Sa(e,t)},Ba=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Dd(e,t):xa(e,t)},Da=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Md(e,t):_a(e,t)},Ma=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zd(e,t):Ca(e,t)},za=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Td(e,t):Ia(e,t)}});var Ua,Va,Na,zn,Wa=j(()=>{"use strict";Ne();je();jr();Ua=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.")},Va=(e,t)=>{Ua(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(qr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Na=(e,t)=>{Ua(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(qr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},zn=e=>ge(e)});var Ud,Vd,Nd,Wd,Kr,Hd,Ha,Un=j(()=>{"use strict";Ne();Nr();ve();Ud=(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],h=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]!==h)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 g=n.dims[0]/3,b=g,w=b;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let E of t.qkvHiddenSizes)if(E%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],b=t.qkvHiddenSizes[1],w=t.qkvHiddenSizes[2]}let y=p;if(g!==b)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==g+b+w)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!==w)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+_,$=-1,x=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:$,inputHiddenSize:h,hiddenSize:g,vHiddenSize:w,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(w/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Vd=(e,t,r,o)=>{let n=Fe(o),s=64,u=o/n;u{let w=F("x",t.dataType,t.dims,n),y="thread_max_vector";n===2?y="max(thread_max_vector.x, thread_max_vector.y)":n===4&&(y="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let _=lt(t.dataType),I=[{name:"d_inv",type:_},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return`\n var wgMax: array;\n var wgSum: array;\n ${b.registerUniforms(I).declareVariables(w)}\n ${b.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 = ${Ze("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(${at(_,n,"x[offset + i]")}, thread_max_vector);\n }\n wgMax[local_idx] = ${y};\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 = ${Ze("f32",n,"0")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n sumVector += exp(${at(_,n,"x[offset + i]")} - maxValue);\n }\n wgSum[local_idx] = ${Je("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] = ${Ze("f32",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 = ${at(_,n,"x[offset + i]")};\n x[offset + i] = ${w.type.value}(exp(f32input - maxValue) / sum);\n }\n }\n }`};e.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${h};${n}`},getShaderSource:g,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:p})},{inputs:[t],outputs:[]})},Nd=(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=Fe(n.headSize),p=n.headSize/a,h=12,g={x:Math.ceil(n.totalSequenceLength/h),y:Math.ceil(n.sequenceLength/h),z:n.batchSize*n.numHeads},b=Xe(t.dataType),w=[{type:"uint32",data:n.sequenceLength},{type:"uint32",data:p},{type:"uint32",data:n.totalSequenceLength},{type:"uint32",data:n.kvSequenceLength},{type:b,data:l}],y=[t,r],_=$=>{let x=M("q",t.dataType,t.dims,a),E=M("key",r.dataType,r.dims,a),A=F("output",t.dataType,u),z=Le(t.dataType),R=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:z}];return`\n const beta: ${z} = 1.0;\n const TILE_SIZE = ${h}u;\n\n var tileQ: array<${x.type.storage}, ${h*h}>;\n var tileK: array<${x.type.storage}, ${h*h}>;\n ${$.registerUniforms(R).declareVariables(x,E,A)}\n ${$.mainStart([h,h,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 = ${Ze(z,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:g,programUniforms:w}),getShaderSource:_},{inputs:y,outputs:[-1]})[0];return Vd(e,I,n.batchSize*n.numHeads*n.sequenceLength,n.totalSequenceLength),I},Wd=(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:"uint32",data:o.sequenceLength},{type:"uint32",data:o.totalSequenceLength},{type:"uint32",data:o.vHeadSize},{type:"uint32",data:o.numHeads},{type:"uint32",data:o.vHiddenSize}],a=p=>{let h=M("probs",t.dataType,t.dims),g=M("v",r.dataType,r.dims),b=F("output",t.dataType,n),w=[{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<${h.type.value}, ${s*s}>;\n var tileK: array<${h.type.value}, ${s*s}>;\n ${p.registerUniforms(w).declareVariables(h,g,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 = ${h.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]},Kr=(e,t,r,o,n,s,u,l,a,p,h)=>{let g=Nd(e,t,r,a,p,h);Wd(e,g,o,p)},Hd=(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:"uint32",data:o},{type:"uint32",data:n},{type:"uint32",data:s},{type:"uint32",data:t.numHeads},{type:"uint32",data:t.headSize},{type:"uint32",data:t.hiddenSize},{type:"uint32",data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],h=g=>{let b=F("output_q",a[0].dataType,r),w=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),$=M("bias",a[2].dataType,a[2].dims),x=_.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`\n const TILE_SIZE = ${u}u;\n var tileInput: array<${x}, ${u*u}>;\n var tileWeightQ: array<${x}, ${u*u}>;\n var tileWeightK: array<${x}, ${u*u}>;\n var tileWeightV: array<${x}, ${u*u}>;\n ${g.registerUniforms(E).declareVariables(_,I,$,b,w,y)}\n ${g.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 = ${x}(0);\n var valueK = ${x}(0);\n var valueV = ${x}(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:h},{inputs:a,outputs:[-1,-1,-1]})},Ha=(e,t)=>{let r=Ud(e.inputs,t),[o,n,s]=Hd(e,r);return Kr(e,o,n,s,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var Gd,Ld,Fd,Ga,La=j(()=>{"use strict";Lt();$e();je();ve();Gd=(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")},Ld=(e,t)=>{let{epsilon:r,spatial:o,format:n}=t,s=e[0].dims,u=o?Fe(s[s.length-1]):1,l=n==="NHWC"&&s.length>1?u:1,a=U.size(s)/u,p=Re(s.length)&&o,h=p?s.length:s,g=M("x",e[0].dataType,e[0].dims,u),b=M("scale",e[1].dataType,e[1].dims,l),w=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,h,u),$=()=>{let E="";if(o)E=`let cOffset = ${s.length===1?"0u":n==="NHWC"?`outputIndices[${s.length-1}] / ${u}`:"outputIndices[1]"};`;else if(n==="NCHW")E=`\n ${I.indicesSet("outputIndices","0","0")}\n let cOffset = ${I.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${b.type.indices}(0);\n cIndices[0] = outputIndices[${s.length-1}];`;for(let A=1;A`\n const epsilon = ${r};\n ${E.registerUniform("outputSize","u32").declareVariables(g,b,w,y,_,I)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${I.offsetToIndices(`global_idx * ${u}`)};\n ${$()}\n let scale = ${b.getByOffset("cOffset")};\n let bias = ${w.getByOffset("cOffset")};\n let inputMean = ${y.getByOffset("cOffset")};\n let inputVar = ${_.getByOffset("cOffset")};\n let x = ${g.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:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p?[{type:"uint32",data:a},...L(s)]:[{type:"uint32",data:a}]})}},Fd=e=>ge(e),Ga=(e,t)=>{let{inputs:r,outputCount:o}=e,n=Fd({...t,outputCount:o});if(Gt.webgpu.validateInputContent&&Gd(r,n),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ld(r,n))}});var jd,qd,Fa,ja=j(()=>{"use strict";$e();ve();jd=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")},qd=e=>{let t=e[0].dims,r=e[0].dims[2],o=U.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:h=>`\n const channels = ${r}u / 4;\n ${h.declareVariables(s,u,l,a)}\n\n ${h.mainStart()}\n ${h.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 }`}},Fa=e=>{jd(e.inputs),e.compute(qd(e.inputs))}});var Kd,Ae,qa,Ka,Ya,Za,Qa,Xa,Ja,ei,ti,Yd,ri,ni,oi,ai,Yr,ii,Zr,si,ui,di,li,ci,pi,mi,fi,hi,gi,yi,bi,wi,vi,$i,Si,xi,Vn=j(()=>{"use strict";Ne();$e();je();ve();Kd=(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 }`},Ae=(e,t,r,o,n,s=e.dataType)=>({name:t,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:u=>Kd(u,U.size(e.dims),e.dataType,s,r,o),getRunData:u=>({outputs:[{dims:e.dims,dataType:s}],dispatchGroup:{x:Math.ceil(U.size(u[0].dims)/64/4)},programUniforms:[{type:"uint32",data:Math.ceil(U.size(e.dims)/4)}]})}),qa=e=>{e.compute(Ae(e.inputs[0],"Abs","abs"))},Ka=e=>{e.compute(Ae(e.inputs[0],"Acos","acos"))},Ya=e=>{e.compute(Ae(e.inputs[0],"Acosh","acosh"))},Za=e=>{e.compute(Ae(e.inputs[0],"Asin","asin"))},Qa=e=>{e.compute(Ae(e.inputs[0],"Asinh","asinh"))},Xa=e=>{e.compute(Ae(e.inputs[0],"Atan","atan"))},Ja=e=>{e.compute(Ae(e.inputs[0],"Atanh","atanh"))},ei=e=>ge(e),ti=(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(Ae(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Yd=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Gr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:Lr;return ge({min:t,max:r})},ri=(e,t)=>{let r=e.inputs.length===1?t:Yd(e.inputs),o=lt(e.inputs[0].dataType);e.compute(Ae(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]})},ni=e=>{e.compute(Ae(e.inputs[0],"Ceil","ceil"))},oi=e=>{e.compute(Ae(e.inputs[0],"Cos","cos"))},ai=e=>{e.compute(Ae(e.inputs[0],"Cosh","cosh"))},Yr=e=>ge(e),ii=(e,t)=>{let r=lt(e.inputs[0].dataType);e.compute(Ae(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))},Zr=(e,t="f32")=>`\nconst r0: ${t} = 0.3275911;\nconst r1: ${t} = 0.254829592;\nconst r2: ${t} = -0.284496736;\nconst r3: ${t} = 1.421413741;\nconst r4: ${t} = -1.453152027;\nconst r5: ${t} = 1.061405429;\n\nfn erf_vf32(v: ${e}) -> ${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}`,si=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Zr(`vec4<${t}>`,t)))},ui=e=>{e.compute(Ae(e.inputs[0],"Exp","exp"))},di=e=>{e.compute(Ae(e.inputs[0],"Floor","floor"))},li=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Zr(`vec4<${t}>`,t)))},ci=(e,t)=>{let r=lt(e.inputs[0].dataType);e.compute(Ae(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))},pi=e=>{e.compute(Ae(e.inputs[0],"Not",t=>`!${t}`))},mi=e=>{e.compute(Ae(e.inputs[0],"Neg",t=>`-${t}`))},fi=e=>{e.compute(Ae(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},hi=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},gi=e=>{e.compute(Ae(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},yi=e=>{e.compute(Ae(e.inputs[0],"Sin","sin"))},bi=e=>{e.compute(Ae(e.inputs[0],"Sinh","sinh"))},wi=e=>{e.compute(Ae(e.inputs[0],"Sqrt","sqrt"))},vi=e=>{e.compute(Ae(e.inputs[0],"Tan","tan"))},$i=e=>{e.compute(Ae(e.inputs[0],"Tanh","tanh"))},Si=(e,t)=>{let r=lt(e.inputs[0].dataType);return e.compute(Ae(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},xi=e=>{e.compute(Ae(e.inputs[0],"Log","log"))}});var Qd,Xd,_i,Ci=j(()=>{"use strict";$e();ve();Vn();Qd=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")},Xd=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=U.size(t)/4,u=Le(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 ${Zr(`vec4<${u}>`,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 }`}},_i=e=>{Qd(e.inputs),e.compute(Xd(e.inputs))}});var Jd,el,ht,Ii,Ai,Ti,Ei,Oi,Pi,ki,Ri,Bi,Di,Mi=j(()=>{"use strict";Ne();$e();ve();Jd=(e,t,r,o,n,s,u,l,a,p,h,g,b)=>{let w,y;typeof l=="string"?w=y=(R,V)=>`${l}((${R}),(${V}))`:typeof l=="function"?w=y=l:(w=l.scalar,y=l.vector);let _=g?t.length:t,I=g?r.length:r,$=g?o.length:o,x=F("outputData",h,$,4),E=M("aData",a,_,4),A=M("bData",p,I,4),z;if(n)if(s){let R=U.size(t)===1,V=U.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,N=r.length>0&&r[r.length-1]%4===0;R||V?z=x.setByOffset("global_idx",y(R?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),V?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):z=`\n let outputIndices = ${x.offsetToIndices("global_idx * 4u")};\n let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",x)};\n let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",x)};\n ${x.setByOffset("global_idx",y(u||T?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||N?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else z=x.setByOffset("global_idx",y(E.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let R=(V,T,N="")=>{let te=`aData[indexA${T}][componentA${T}]`,Y=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${x.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${E.broadcastedIndicesToOffset(`outputIndices${T}`,x)};\n let offsetB${T} = ${A.broadcastedIndicesToOffset(`outputIndices${T}`,x)};\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 ${V}[${T}] = ${N}(${w(te,Y)});\n `};h===9?z=`\n var data = vec4(0);\n ${R("data",0,"u32")}\n ${R("data",1,"u32")}\n ${R("data",2,"u32")}\n ${R("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:z=`\n ${R("outputData[global_idx]",0)}\n ${R("outputData[global_idx]",1)}\n ${R("outputData[global_idx]",2)}\n ${R("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(E,A,x)}\n\n ${b??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${z}\n }`},el=(e,t,r,o,n,s,u=r.dataType)=>{let l=!U.areEqual(r.dims,o.dims),a=r.dims,p=U.size(r.dims),h=!1,g=!1,b=[l];if(l){let y=dt.calcShape(r.dims,o.dims,!1);if(!y)throw new Error("Can\'t perform binary op on the given tensors");a=y,p=U.size(a);let _=U.size(r.dims)===1,I=U.size(o.dims)===1,$=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,x=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;b.push(_),b.push(I),b.push($),b.push(x);let E=1;for(let A=1;Ay.toString()).join("_"),inputDependencies:w?["rank","rank"]:["dims","dims"]},getShaderSource:y=>Jd(y,r.dims,o.dims,a,h,l,g,n,r.dataType,o.dataType,u,w,s),getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:w?[{type:"uint32",data:Math.ceil(U.size(a)/4)},...L(r.dims),...L(o.dims),...L(a)]:[{type:"uint32",data:Math.ceil(U.size(a)/4)}]})}},ht=(e,t,r,o,n,s)=>{e.compute(el(t,n??"",e.inputs[0],e.inputs[1],r,o,s))},Ii=e=>{ht(e,"Add",(t,r)=>`${t}+${r}`)},Ai=e=>{ht(e,"Div",(t,r)=>`${t}/${r}`)},Ti=e=>{ht(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Ei=e=>{ht(e,"Mul",(t,r)=>`${t}*${r}`)},Oi=e=>{let t=M("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ht(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 `)},Pi=e=>{ht(e,"Sub",(t,r)=>`${t}-${r}`)},ki=e=>{ht(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Ri=e=>{ht(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Bi=e=>{ht(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Di=e=>{ht(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var rl,nl,ol,al,zi,Ui,Vi=j(()=>{"use strict";$e();je();ve();rl=e=>{if(!e||e.length<1)throw new Error("too few inputs");let t=e[0].dataType,r=e[0].dims.length;for(let o of e){if(o.dataType!==t)throw new Error("input tensors should be one type");if(o.dims.length!==r)throw new Error("input tensors should have the same shape")}},nl=(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 }`,ol=(e,t)=>{let r=e.length,o=[];for(let n=0;n{let r=e[0].dims.slice();if(t>=r.length||t<-1*r.length)throw new Error("axis specified for concat doesn\'t match input dimensionality");let o=t<0?r.length+t:t,n=r.slice(0);for(let A=1;A`uniforms.sizeInConcatAxis${A}`).join(","),E=A=>`\n\n ${(()=>{A.registerUniform("outputSize","u32");for(let z=0;z(${x});\n ${$} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${ol(l,I)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:w}),getShaderSource:E}},zi=(e,t)=>{rl(e.inputs),e.compute(al(e.inputs,t.axis))},Ui=e=>ge({axis:e.axis})});var gt,Qr,It=j(()=>{"use strict";$e();gt=(e,t)=>{switch(e.activation){case"Relu":return{activationFunction:"",applyActivation:`value = max(value, ${t}(0.0));`};case"Sigmoid":return{activationFunction:"",applyActivation:`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`};case"Clip":return{activationFunction:`const clip_min_=${t}(${e.clipMin});const clip_max_=${t}(${e.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},Qr=e=>{let t=e?.activation||"";if(t==="Clip"){let[r,o]=e?.activation_params||[Gr,Lr];return{activation:t,clipMax:o,clipMin:r,activationCacheKey:`${t}:${r},${o}`}}return{activation:t,activationCacheKey:t}}});var Ke,Xr,Jr=j(()=>{"use strict";Ke=(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.`)}},Xr=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var en,Nn=j(()=>{"use strict";en=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 il,sl,mr,Ni,ul,fr,dl,tn,hr=j(()=>{"use strict";$e();ve();It();Jr();il=(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 }`,mr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32)=>{let a=t[1]*e[1],p=t[0]*e[0],h=n?a:s,g=n?s:a,b=h/t[0],w=s/t[1];if(!((n&&b===4&&e[1]===4||!n&&(b===3||b===4))&&h%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 ${h} 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, ${h/b}>, ${g}>;\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 numTiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dimInner - 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 * ${w};\n for (var t = 0; t < numTiles; 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 ${il(n,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${w}; 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}`},Ni=(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 `,ul=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",fr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32,a=!1)=>{let p=e[1]*t[1],h=e[0]*t[0],g=n?p:s,b=n?s:p;if(!(b%t[1]===0&&g%t[0]===0&&s%t[1]===0))throw new Error(`tileAHight ${b} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${s} must be divisible by workgroupSize[1]${t[1]}`);let w=b/t[1],y=g/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) * ${h};\n\n // Loop over shared dimension.\n for (var t = 0; t < numTiles; 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 < ${g}; inputCol = inputCol + ${t[0]}) {\n ${Ni(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 < ${h}; 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) * ${w};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${_};\n// Loop over shared dimension.\nfor (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Ni(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 ${ul(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 numTiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dimInner - 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`},dl=(e,t,r,o,n,s=!1)=>{let[u,l,a]=n,[p,h,g,b]=o,w=Ft(u,a),y=Ft(l,a),_=Le(o[0].type.tensor),I=()=>{let E=h.rank,A=p.rank,z=`var aIndices: ${h.type.indices};`;for(let R=E-2-1,V=A-1;R>=0;R--,V--)z+=`\naIndices[${R}] = ${A>1?`batchIndices[${V}]`:"batchIndices"};`;return w.forEach(R=>{z+=`\naIndices[${R}] = 0;`}),z+=`\naIndices[${E-2}] = u32(row);\n aIndices[${E-1}] = u32(colIn);`,z},$=()=>{let E=g.rank,A=p.rank,z=`var bIndices: ${g.type.indices};`;for(let R=E-2-1,V=A-1;R>=0;R--,V--)z+=`\nbIndices[${R}] = ${A>1?`batchIndices[${V}]`:"batchIndices"};`;return y.forEach(R=>{z+=`\nbIndices[${R}] = 0;`}),z+=`\nbIndices[${E-2}] = u32(row);\n bIndices[${E-1}] = u32(colIn);`,z};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ke(e,_)} {\n var value = ${Ke(e,_)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dimAOuter && col < uniforms.dimInner)\n {\n ${I()}\n value = ${h.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ke(e,_)} {\n var value = ${Ke(e,_)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dimInner && col < uniforms.dimBOuter)\n {\n ${$()}\n value = ${g.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ke(e,_)}) {\n let col = colIn * ${e};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${s?"bias[colIn]":`${Ke(e,_)}(bias[row])`};`:""}\n ${r}\n ${b.setByIndices("vec3(coords)","value")}\n }\n }\n `},tn=(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),h=Re(p.length),g=h?p.length:p,b=Fr("batchDims",e[0].dataType,g,1),w=U.size(p),y=s[s.length-2],_=s[s.length-1],I=u[u.length-1],$=_%4===0&&I%4===0,x=y<=8?[4,1,1]:[4,4,1],E=[8,8,1],A=[Math.ceil(I/E[0]/x[0]),Math.ceil(y/E[1]/x[1]),Math.ceil(w/E[2]/x[2])],z=Le(e[0].dataType),R=$?4:1,V=[...l,y,_/R],T=Re(V.length),N=T?V.length:V,te=[...a,_,I/R],Y=Re(te.length),K=Y?te.length:te,Q=[w,y,I/R],Z=M("a",e[0].dataType,N,R),Ee=M("b",e[1].dataType,K,R),Pe=F("result",e[0].dataType,Q.length,R),fe=[Z,Ee],Ie=[{type:"int32",data:y},{type:"int32",data:I},{type:"int32",data:_}];h&&Ie.push(...L(p)),T&&Ie.push(...L(V)),Y&&Ie.push(...L(te));let he=[];he.push(T?"rank":"dims"),he.push(Y?"rank":"dims");let ye=e.length>2,{activationFunction:We,applyActivation:De}=gt(t,Pe.type.value),Ge=dl(R,ye,De,[b,Z,Ee,Pe],[l,a,p],n);if(ye){let ee=n?R:1;fe.push(M("bias",e[2].dataType,e[2].dims.length,ee)),Ie.push(...L(e[2].dims)),he.push("rank")}Ie.push(...L(Q));let G=ee=>`\n ${ee.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").registerInternalVariables(b).declareVariables(...fe,Pe)}\n ${We}\n ${Ge}\n ${$?mr(x,E,z,b):fr(x,E,z,b)}\n `;return{name:"MatMul",shaderCache:{hint:t.activationCacheKey+`${x}${$}${n}`,inputDependencies:he},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:Ie}),getShaderSource:G}}});var ll,Wi,Hi=j(()=>{"use strict";Ct();ve();It();Jr();Nn();hr();ll=(e,t,r,o,n=!1,s,u=4,l=4,a=4,p="f32")=>{let h=Y=>{switch(Y){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 ${Y} is not supported.`)}},g=Y=>{switch(Y){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Y} is not supported.`)}},b=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,w=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",$=e?"col":"row",x=`\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 = ${$} / (filterDims[1] * inChannels);\n let WCol = ${$} / inChannels % filterDims[1];\n let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0];\n let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1];\n let xCh = ${$} % inChannels;\n var resData = ${Ke(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 ${h(u)}\n }\n return resData;`,E=e?t&&o?`\n let col = colIn * ${u};\n ${x}`:`\n let col = colIn * ${u};\n if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n ${x}\n }\n return ${Ke(u,p)}(0.0);`:o&&r?`\n let col = colIn * ${u};\n ${x}`:`\n let col = colIn * ${u};\n if (row < uniforms.dimInner && col < uniforms.dimBOuter) {\n ${x}\n }\n return ${Ke(u,p)}(0.0);`,A=`${g(l)}`,z=Ke(a,p),R=e?Ke(u,p):Ke(l,p),V=e?Ke(l,p):Ke(u,p),{activationFunction:T,applyActivation:N}=gt(s,z);return`\n ${T}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${R} {\n ${e?E:A}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${V} {\n ${e?A:E}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${z}) {\n let col = colIn * ${a};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${w}\n ${Xr(n)}\n ${N}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Wi=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],h=r[0],g=a?r[2]:r[3],b=a?r[1]:r[2],w=a?r[3]:r[1],y=a&&(p%4===0||p%3===0)&&w%4===0,_=a?w:g*b,I=a?g*b:w,$=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(_/$[0]/x[0]),Math.ceil(I/$[1]/x[1]),Math.ceil(h/$[2]/x[2])];Be("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let A=y?a&&p%4!==0?3:4:1,z=$[1]*x[1],R=$[0]*x[0],V=Math.max($[0]*A,$[1]),T=o%z===0,N=n%R===0,te=s%V===0,Y=y?[A,4,4]:[1,1,1],K=Le(e[0].dataType),Q=y?4:1,Z=[{type:"int32",data:o},{type:"int32",data:n},{type:"int32",data:s}],Ee=M("x",e[0].dataType,e[0].dims.length,A===3?1:A),Pe=M("w",e[1].dataType,e[1].dims.length,Q),fe=[Ee,Pe];Z.push(...L(e[0].dims)),Z.push(...L(e[1].dims));let Ie=`\n fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${K}>`:K}) {\n result[flatIndex] = ${y?`vec4<${K}>`:K}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${y?`vec4<${K}>`:K}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${y?"/ 4":""}, value);\n }`;if(u){let ye=M("bias",e[2].dataType,e[2].dims.length,Q);fe.push(ye),Z.push(...L(e[2].dims)),Ie+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${K}>`:K} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}let he=F("result",e[0].dataType,r.length,Q);return Z.push(...L(r)),{name:"Conv2DMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:Z}),getShaderSource:ye=>`\n ${en("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 ${ye.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...fe,he)}\n const filterDims : vec2 = vec2(${t.kernelShape[0]}, ${t.kernelShape[1]});\n const pad : vec2 = vec2(${t.pads[0]}, ${t.pads[1]});\n const stride : vec2 = vec2(${t.strides[0]}, ${t.strides[1]});\n const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]});\n ${Ie}\n ${ll(a,T,N,te,u,t,Y[0],Y[1],Y[2],K)}\n ${y?mr(x,$,K,void 0,!a,V):fr(x,$,K,void 0,!a,V,!1,void 0,l)}`}}});var Wn,Gi=j(()=>{"use strict";$e();ve();Gn();It();Wn=(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=Hn(s,u,t.dilations,t.pads,t.strides,a),h=U.size(p),g=F("output",e[0].dataType,p),{activationFunction:b,applyActivation:w}=gt(t,g.type.value),y=M("x",e[0].dataType,s),_=M("w",e[1].dataType,u),I=[y,_];o&&I.push(M("b",e[2].dataType,e[2].dims));let $=x=>`\n const strides: vec2 = vec2(${t.strides[0]}u, ${t.strides[1]}u);\n const pads: vec2 = vec2(${t.pads[0]}u, ${t.pads[1]}u);\n\n ${x.declareVariables(...I,g)}\n\n ${b}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(h)}\n\n let outputIndices = ${g.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}]) * strides - pads;\n let group_id: u32 = output_channel / ${l}u;\n\n var value: ${g.type.value} = ${g.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < ${u[1]}u; wInChannel++) {\n let input_channel = group_id * ${u[1]}u + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < ${u[2]}u; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}u;\n\n if (xHeight < 0u || xHeight >= ${s[a?1:2]}u) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < ${u[3]}u; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}u;\n if (xWidth < 0u || xWidth >= ${s[a?2:3]}u) {\n continue;\n }\n\n let xVal = ${a?y.get("batch","xHeight","xWidth","input_channel"):y.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${_.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${n}\n ${w}\n ${g.setByOffset("global_idx","value")}\n }`;return{name:"GroupedConv",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r?r(p):p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)}}),getShaderSource:$}}});var Ln,cl,Li,Fn=j(()=>{"use strict";$e();hr();ve();It();Ln=(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],h=Fe(a),g=Fe(p),b=Fe(l),w=U.size(r)/h/b,y=e.length>2,_=o?o.slice(0,-2):r.slice(0,-2),$=[U.size(_),l,a],x=[{type:"uint32",data:w},{type:"uint32",data:l},{type:"uint32",data:a},{type:"uint32",data:p},...L(_),...L(s),...L(u)];y&&x.push(...L(e[2].dims)),x.push(...L($));let E=A=>{let z=Fr("batch_dims",e[0].dataType,_.length),R=M("a",e[0].dataType,s.length,g),V=M("b",e[1].dataType,u.length,h),T=F("output",e[0].dataType,$.length,h),{activationFunction:N,applyActivation:te}=gt(t,T.type.value),Y=[R,V],K="";if(y){let he=n?h:1;Y.push(M("bias",e[2].dataType,e[2].dims.length,he)),K=`${n?`value += bias[col / ${he}];`:`value += ${T.type.value}(bias[row + i]);`}`}let Q=s.slice(0,-2),Z=u.slice(0,-2),Ee=Ft(Q,_),Pe=Ft(Z,_),fe=(he,ye)=>{let We=he.rank,De=he.name;if(We===2)return`var ${De}_indices = ${he.type.indices}(0u, 0u);`;let Ge=z.rank,G=`var ${De}_indices: ${he.type.indices};`;for(let ee=We-2-1,be=Ge-1;ee>=0;ee--,be--)G+=`\n${De}_indices[${ee}] = ${Ge>1?`batch_indices[${be}]`:"batch_indices"};`;return ye.forEach(ee=>{G+=`\n${De}_indices[${ee}] = 0;`}),G+=`${De}_indices[${We-2}] = 0u;\n ${De}_indices[${We-1}] = 0u;`,G},Ie=()=>{let he=`var a_data: ${R.type.value};`;for(let ye=0;ye;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${g}) {\n ${Ie()}\n }\n for (var i = 0u; i < ${b}u; i++) {\n var value = values[i];\n ${K}\n ${te}\n let cur_indices = ${T.type.indices}(batch, row + i, col);\n let offset = ${T.indicesToOffset("cur_indices")};\n ${T.setByOffset(`offset / ${h}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activationCacheKey}_${h}_${g}_${b}_${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:x}),getShaderSource:E}},cl=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.")},Li=e=>{cl(e.inputs);let t=dt.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(Ln(e.inputs,{activation:"",activationCacheKey:""},t)):e.compute(tn(e.inputs,{activation:"",activationCacheKey:""},t))}});var Hn,Fi,pl,ji,jn,ml,fl,qn,Gn=j(()=>{"use strict";$e();je();Hi();hr();Gi();It();Fn();jt();Hn=(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],g=t.slice(2).map((y,_)=>y+(y-1)*(r[_]-1)),w=l.map((y,_)=>y+o[_]+o[_+a]).map((y,_)=>Math.floor((y-g[_]+n[_])/n[_]));return w.splice(0,0,u),w.splice(s?3:1,0,p),w},Fi=[2,3,1,0],pl=(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")},ji=(e,t)=>{let r=e.kernelShape.slice();for(let s=2;s{let t=Qr(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 ge({autoPad:o,format:r,dilations:n,group:s,kernelShape:u,pads:l,strides:a,wIsConst:p,...t})},ml=(e,t,r)=>{let o=ji(r,t),n=r.format==="NHWC";if(r.group!==1){e.compute(Wn(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],h=t[1].dims[3],g=Hn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,n),b=g[n?1:2],w=g[n?2:3],y=g[n?3:1],_=n&&p===u&&h===l&&r.pads[0]===0&&r.pads[1]===0;if(_||p===1&&h===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 R=g[0],V,T,N,te=[];if(n){let Q=e.kernelCustomData.wT??e.compute(it(t[1],Fi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Q),_){let Z=u*l*a;V=t[0].reshape([1,R,Z]),T=Q.reshape([1,Z,y]),N=[1,R,y]}else V=t[0].reshape([R,u*l,a]),T=Q.reshape([1,a,y]),N=[R,b*w,y];te.push(V),te.push(T)}else V=t[0].reshape([R,a,u*l]),T=t[1].reshape([1,y,a]),N=[R,y,b*w],te.push(T),te.push(V);s&&te.push(t[2]);let Y=N[2],K=te[0].dims[te[0].dims.length-1];Y<8&&K<8?e.compute(Ln(te,o,g,N,n),{inputs:te}):e.compute(tn(te,o,g,N,n),{inputs:te});return}let I=!0,$=e.kernelCustomData.wT??e.compute(it(t[1],Fi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let x=[t[0],$];s&&x.push(t[2]);let E=n?b*w:y,A=n?y:b*w,z=p*h*a;e.compute(Wi(x,o,g,E,A,z,s,I),{inputs:x})},fl=(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=ji({...t,pads:n,strides:s,dilations:u,kernelShape:l},o);e.compute(Wn(o,a,p=>r?[p[0],p[2],p[3]]:[]))},qn=(e,t)=>{pl(e.inputs,t),e.inputs[0].dims.length===3?fl(e,t):ml(e,e.inputs,t)}});var hl,qi,Ki=j(()=>{"use strict";Ct();ve();It();Jr();Nn();hr();hl=(e,t=!1,r,o=4)=>{let n=Ke(o,"f32"),s=x=>{switch(x){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 vec4(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${x} 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?"outBackprop[1]":"outBackprop[2]",p=e?"outBackprop[2]":"outBackprop[3]",h=e?"row":"col",g=e?"col":"row",b=`\n let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${h} / outWidth;\n let outCol = ${h} % outWidth;\n\n let WRow = ${g} / (filterDims[1] * inChannels);\n let WCol = ${g} / inChannels % filterDims[1];\n let xR = f32(outRow - pads[0] + dilation[0] * WRow) / f32(strides[0]);\n let xC = f32(outCol - pads[1] + dilation[1] * WCol) / f32(strides[1]);\n if (xR < 0.0 || xR >= f32(${a}) || fract(xR) > 0.0) {\n return ${n}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) {\n return ${n}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${g} % inChannels;\n ${u}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`,w=e?`\n let col = colIn * ${o};\n if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n ${b}\n }\n return ${n}(0.0);`:`\n let col = colIn * ${o};\n if (row < uniforms.dimInner && col < uniforms.dimBOuter) {\n ${b}\n }\n return ${n}(0.0);`,y=`\n let col = colIn * ${o};\n let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"};\n let coordX = filterDims.x - 1 - row / (filterDims[1] * inChannels);\n let coordY = filterDims.y - 1 - (row / inChannels) % filterDims[1];\n if (${e?"row < uniforms.dimInner && col < uniforms.dimBOuter":"row < uniforms.dimInner && col < uniforms.dimAOuter"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${s(o)}\n }\n return ${n}(0.0);\n `,{activationFunction:_,applyActivation:I}=gt(r,n);return`\n ${_}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?w:y}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?y:w}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) {\n let col = colIn * ${o};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${l}\n ${Xr(t)}\n ${I}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value;\n }\n }`},qi=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],h=r[0],g=a?r[2]:r[3],b=a?r[1]:r[2],w=a?r[3]:r[1],y=a?p%4===0&&w%4===0:g%4===0&&w%4===0,_=a?w:g*b,I=a?g*b:w,$=y?[8,8,1]:[_<=4||I<=4?4:16,_>4&&I<=4?4:16,1],x=y?[4,4,1]:[_<=4?1:4,_>4&&I<=4?1:4,1],E=[Math.ceil(_/$[0]/x[0]),Math.ceil(I/$[1]/x[1]),Math.ceil(h/$[2]/x[2])];Be("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let A=y?4:1,z=Math.max($[0]*A,$[1]),R=y?4:1,V=[{type:"int32",data:o},{type:"int32",data:n},{type:"int32",data:s}],T=M("x",e[0].dataType,e[0].dims.length,R),N=M("w",e[1].dataType,e[1].dims.length,1),te=F("result",e[0].dataType,r.length,R),Y=[T,N];V.push(...L(e[0].dims)),V.push(...L(e[1].dims));let K="";if(u){let Q=M("bias",e[2].dataType,e[2].dims.length,R);Y.push(Q),V.push(...L(e[2].dims)),K+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?"vec4":"f32"} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}return V.push(...L(r)),{name:"Conv2DTransposeMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:V}),getShaderSource:Q=>`\n ${en("uniforms.result_strides")}\n ${Q.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...Y,te)};\n const outBackprop : vec4 = vec4(${e[0].dims.join(",")});\n const filterDims : vec2 = vec2(${t.kernelShape[a?1:2]}, ${t.kernelShape[a?2:3]});\n const effectiveFilterDims : vec2 = filterDims + vec2(\n ${t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)},\n ${t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1)});\n const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${t.pads[0]+t.pads[2]})/2,\n i32(effectiveFilterDims[1]) - 1 - (${t.pads[1]+t.pads[3]})/2);\n const strides : vec2 = vec2(${t.strides[0]}, ${t.strides[1]});\n const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]});\n const dimAOuter : i32 = ${o};\n const dimBOuter : i32 = ${n};\n const dimInner : i32 = ${s};\n ${K}\n ${hl(a,u,t,A)}\n ${y?mr(x,$,"f32",void 0,!a,z):fr(x,$,"f32",void 0,!a,z,!1,void 0,l)}`}}});var gl,Kn,Yi=j(()=>{"use strict";Ct();$e();ve();gl=(e,t,r,o,n,s,u=!1,l)=>{let a=r.format==="NHWC",p=a?1:2,h=a?2:3,g=a?3:1,b=U.size(o),w=u?2:1,y=r.group,_=t[1].dims,I=_[0]/y,$=_[1],x=`\n fn setOutputAtIndex(flatIndex : u32, value : ${u?`vec4<${l}>`:l}) {\n result[flatIndex] = ${u?`vec4<${l}>`:l}(value);\n }`;n&&(x+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${u?`vec4<${l}>`:l} {\n return bias[coords.${a?"w":"y"}${u?"/ 4":""}];\n }`);let E=u?4:1,A=M("W",t[1].dataType,t[1].dims,E),z=M("Dy",t[0].dataType,t[0].dims,E),R=[z,A];n&&R.push(M("bias",t[2].dataType,[o[g]],E));let V=F("result",t[0].dataType,o,E),T=`{\n let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / outShape[1];\n let r = ${s?"global_id.z":"workgroup_id.z"} % outShape[1];\n let c = ${s?"global_id.y":"workgroup_id.y"} * ${w};\n let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(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, ${w}>;\n for (var i = 0; i < ${w}; i++) {\n dotProd[i] = vec4<${l}>(0.0);\n }\n for (var wR: u32 = 0; wR < filterDims[0]; wR = wR + 1) {\n var dyR = (${l}(dyCorner.x) + ${l}(wR)) / ${l}(strides.x);\n let wRPerm = filterDims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${l}(outBackprop[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 < filterDims[1]; wC = wC + 1) {\n let dyC = (${l}(dyCorner.y) + ${l}(wC)) / ${l}(strides.y);\n let dyC2 = (${l}(dyCorner.y) + 1.0 + ${l}(wC)) / ${l}(strides.y);\n let wCPerm = filterDims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${l}(outBackprop[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${l}(outBackprop[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 = outBackprop[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${z.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = outBackprop[${g}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${l}>(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 = outBackprop[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${l}>(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 < ${w}; i = i + 1) {\n let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${l}>(0.0)`};\n ${V.set("batch","r","c + i","d1","value")};\n }\n }`,N=`\n let outputIndices = ${V.offsetToIndices("global_idx")};\n let batch = ${V.indicesGet("outputIndices",0)};\n let d1 = ${V.indicesGet("outputIndices",g)};\n let r = ${V.indicesGet("outputIndices",p)};\n let c = ${V.indicesGet("outputIndices",h)};\n let dyCorner = vec2(i32(r), i32(c)) - pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / ${$};\n let wOutChannel = d1 - groupId * ${$};\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 = ${l}(0.0);\n for (var wR: u32 = 0; wR < effectiveFilterDims.x; wR = wR + 1) {\n if (wR % dilations.x != 0) {\n continue;\n }\n let dyR = (${l}(dyRCorner) + ${l}(wR)) / ${l}(strides[0]);\n let wRPerm = filterDims.x - 1 - wR / dilations.x;\n if (dyR < 0.0 || dyR >= ${l}(outBackprop[${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 < effectiveFilterDims.y; wC = wC + 1) {\n if (wC % dilations.y != 0) {\n continue;\n }\n let dyC = (${l}(dyCCorner) + ${l}(wC)) / ${l}(strides.y);\n let wCPerm = filterDims.y - 1 - wC / dilations.y;\n if (dyC < 0.0 || dyC >= ${l}(outBackprop[${h}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * ${I};\n for (var d2: u32 = 0; d2 < ${I}; d2 = d2 + 1) {\n let xValue = ${a?z.get("batch","idyR","idyC","inputChannel"):z.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${A.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${n?"bias[d1]":`${l}(0.0)`};\n ${V.setByOffset("global_idx","value")};\n `;return`\n ${e.declareVariables(...R,V)}\n ${x}\n const outShape : vec4 = vec4(${o.join(",")});\n const outBackprop : vec4 = vec4(${t[0].dims.join(",")});\n const strides : vec2 = vec2(${r.strides[0]}, ${r.strides[1]});\n const filterDims : vec2 = vec2(${r.kernelShape[a?1:2]}, ${r.kernelShape[a?2:3]});\n const dilations : vec2 = vec2(${r.dilations[0]}, ${r.dilations[1]});\n const effectiveFilterDims : vec2 = filterDims + vec2(\n ${r.dilations[0]<=1?0:(r.kernelShape[a?1:2]-1)*(r.dilations[0]-1)},\n ${r.dilations[1]<=1?0:(r.kernelShape[a?2:3]-1)*(r.dilations[1]-1)});\n const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${r.pads[0]+r.pads[2]})/2,\n i32(effectiveFilterDims[1]) - 1 - (${r.pads[1]+r.pads[3]})/2);\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(b)};\n ${u?T:N}}`},Kn=(e,t,r)=>{let o=e.length>2,n=t.outputShape,s=U.size(n),u=[Math.ceil(s/64),1,1];Be("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let l=Le(e[0].dataType);return{name:"ConvTranspose2D",shaderCache:{hint:t.cacheKey},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:r?r(n):n,dataType:e[0].dataType}]}),getShaderSource:a=>gl(a,e,t,n,o,u[1]===1&&u[2]===1,!1,l)}}});var yl,bl,wl,Zi,Qi,vl,$l,Sl,xl,Xi,Ji=j(()=>{"use strict";je();Ki();Yi();It();jt();yl=(e,t,r,o,n,s)=>(e-1)*t+r+(o-1)*n+1-s,bl=(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)},wl=(e,t,r,o,n,s,u,l,a,p)=>{let h=e.length-2,g=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((b,w)=>b*w,1)===0){r.length=0;for(let b=2;bb+w,0)===0){let b=t[0].dims.length-2;a=new Array(b).fill(1)}let p=e.strides.slice();if(p.reduce((b,w)=>b+w,0)===0){let b=t[0].dims.length-2;p=new Array(b).fill(1)}wl(l,r,a,e.autoPad,e.group,n,p,o,u,s);let h=Object.assign({},e),g=e.cacheKey+[r.join("n,"),n.join(","),p.join(","),u.join(","),s.join(","),a.join(",")].join("_");return Object.assign(h,{kernelShape:r,pads:n,outputPadding:u,outputShape:s,dilations:a,strides:p,cacheKey:g}),h},Qi=e=>{let t=Qr(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(),h=e.outputPadding,g=e.outputShape;return ge({autoPad:o,format:r,dilations:n,group:s,kernelShape:u,outputPadding:h,outputShape:g,pads:l,strides:a,wIsConst:p,...t})},vl=(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((h,g)=>h+g,0)>0&&t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.reduce((h,g)=>h+g,0)>0&&t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.reduce((h,g)=>h+g,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((h,g)=>h+g,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")},$l=[2,3,1,0],Sl=(e,t,r)=>{let o=Zi(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(Kn(t,o));return}let a=s[n?1:2],p=s[n?2:3],h=t[1].dims[2],g=t[1].dims[3],b=n?a*p:u,w=n?u:a*p,y=h*g*l,_=!0,I=e.kernelCustomData.wT??e.compute(it(t[1],$l),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let $=[t[0],I],x=t.length===3;x&&(!n&&t[2].dims.length===1?$.push(t[2].reshape([t[2].dims[0],1,1])):$.push(t[2])),e.compute(qi($,o,s,b,w,y,x,_),{inputs:$})},xl=(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=Zi({...t,pads:l,strides:u,dilations:s,kernelShape:n},o);e.compute(Kn(o,a,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},Xi=(e,t)=>{vl(e.inputs,t),e.inputs[0].dims.length===3?xl(e,t):Sl(e,e.inputs,t)}});var _l,es,ts,rs=j(()=>{"use strict";Ne();$e();je();ve();_l=(e,t,r,o)=>{let n=U.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=U.normalizeAxis(a,s),h=g=>{let b=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,w=ce("uniforms.input_shape","uniforms.axis",s),y=o.reverse?b+(o.exclusive?" + 1":""):"0",_=o.reverse?w:b+(o.exclusive?"":" + 1");return`\n ${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,l)}\n ${g.mainStart()}\n ${g.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:"uint32",data:n},{type:"int32",data:p},...L(t),...L(t)]}),getShaderSource:h}},es=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,n=e.inputs[1];e.compute(_l(o,r,n,t),{inputs:[0]})},ts=e=>{let t=e.exclusive===1,r=e.reverse===1;return ge({exclusive:t,reverse:r})}});var Yn,rn,ns,Cl,Il,Zn,Qn,os,Al,as,is,ss=j(()=>{"use strict";$e();je();ve();Yn="[a-zA-Z]|\\\\.\\\\.\\\\.",rn="("+Yn+")+",ns="^"+rn+"$",Cl="("+rn+",)*"+rn,Il="^"+Cl+"$",Zn=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)}},Qn=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(Il)))throw new Error("Invalid LHS term");if(o.split(",").forEach((l,a)=>{let p=t[a].dims.slice();if(!l.match(RegExp(ns)))throw new Error("Invalid LHS term");let h=this.processTerm(l,!0,p,a);this.lhs.push(h)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([l,a])=>a.count===1||l==="...").map(([l])=>l).join("");else if(!n.match(RegExp(rn)))throw new Error("Invalid RHS");n.match(RegExp(Yn,"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(ns))&&!r&&t!=="")throw new Error("Invalid LHS term");let p=t.match(RegExp(Yn,"g")),h=new Zn(n);return p?.forEach((g,b)=>{if(g==="..."){if(u)throw new Error("Only one ellipsis is allowed per input term");u=!0;let w=s-p.length+1;if(w<0)throw new Error("Ellipsis out of bounds");if(l=o.slice(a,a+w),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",Al=(e,t,r,o,n)=>{let u=t.map((w,y)=>e[y]?w.length:w).map((w,y)=>M(`input${y}`,r,w)),l=U.size(n),a=Re(n.length),p=a?n.length:n,h=F("output",r,p),g=[...o.symbolToInfo.keys()].filter(w=>!o.rhs.symbolToIndices.has(w)),b=w=>{let y=[],_="var prod = 1.0;",I="var sum = 0.0;",$="sum += prod;",x=[],E=[],A=[],z=[],R=o.symbolToInfo.size===o.rhs.symbolToIndices.size;o.symbolToInfo.forEach((T,N)=>{if(o.rhs.symbolToIndices.has(N)){let te=o.rhs.symbolToIndices.get(N)?.[0];te!==void 0&&o.lhs.forEach((Y,K)=>{if(T.inputIndices.includes(K)){let Q=Y.symbolToIndices.get(N);if(Q===void 0)throw new Error("Invalid symbol error");Q.forEach(Z=>{y.push(`${u[K].indicesSet(`input${K}Indices`,Z,h.indicesGet("outputIndices",te))}`)})}})}else o.lhs.forEach((te,Y)=>{if(T.inputIndices.includes(Y)){let K=te.symbolToIndices.get(N);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(Q=>{x.push(`${u[Y].indicesSet(`input${Y}Indices`,Q,`${N}`)}`)}),z.push(`prod *= ${u[Y].getByIndices(`input${Y}Indices`)};`)}}),E.push(`for(var ${N}: u32 = 0; ${N} < uniforms.${os(N)}; ${N}++) {`),A.push("}")});let V=R?[...y,`let sum = ${u.map((T,N)=>T.getByIndices(`input${N}Indices`)).join(" * ")};`]:[...y,I,...E,...x,_,...z,$,...A];return`\n ${w.registerUniforms(g.map(T=>({name:`${os(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,h)}\n\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${h.offsetToIndices("global_idx")};\n ${u.map((T,N)=>`var input${N}Indices: ${u[N].type.indices};`).join(`\n`)}\n ${V.join(`\n`)};\n ${h.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:o.equation,inputDependencies:e.map(w=>w?"rank":"dims")},getRunData:()=>{let w=g.filter(_=>o.symbolToInfo.has(_)).map(_=>({type:"uint32",data:o.symbolToInfo.get(_)?.dimValue||0}));w.push({type:"uint32",data:l});let y=t.filter((_,I)=>e[I]).map((_,I)=>[...L(_)]).reduce((_,I)=>_.concat(I),w);return a&&y.push(...L(n)),{outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:y}},getShaderSource:b}},as=(e,t)=>{let r=new Qn(e.inputs,t.equation),o=e.inputs.map((u,l)=>Re(u.dims.length)),n=r.outputDims,s=e.inputs.map((u,l)=>u.dims);e.compute(Al(o,s,e.inputs[0].dataType,r,n))},is=e=>{let t=e.equation.replace(/\\s+/g,"");return ge({equation:t})}});var Tl,us,El,Ol,ds,ls=j(()=>{"use strict";Ne();$e();ve();Tl=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?us(e,t):us(t,e),Ol=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=El(t,r),n=e[0].dataType,s=n===9?4:1,u=Math.ceil(U.size(o)/s),l=Re(t.length),a=Re(o.length),p=g=>{let b=l?t.length:t,w=a?o.length:o,y=M("input",n,b,s),_=F("output",n,w,s),I;if(n===9){let $=(x,E,A="")=>`\n let outputIndices${E} = ${_.offsetToIndices(`outputOffset + ${E}u`)};\n let offset${E} = ${y.broadcastedIndicesToOffset(`outputIndices${E}`,_)};\n let index${E} = offset${E} / 4u;\n let component${E} = offset${E} % 4u;\n ${x}[${E}] = ${A}(${y.getByOffset(`index${E}`)}[component${E}]);\n `;I=`\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 ${_.setByOffset("global_idx","data")}\n }`}else I=`\n let outputIndices = ${_.offsetToIndices("global_idx")};\n let inputOffset = ${y.broadcastedIndicesToOffset("outputIndices",_)};\n ${_.setByOffset("global_idx",y.getByOffset("inputOffset"))}\n }`;return`\n ${g.registerUniform("vec_size","u32").declareVariables(y,_)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${I}`},h=[{type:"uint32",data:u}];return l&&h.push(...L(t)),a&&h.push(...L(o)),{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:[l?"rank":"dims"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h})}},ds=e=>{Tl(e.inputs),e.compute(Ol(e.inputs),{inputs:[0]})}});var Pl,kl,cs,ps,ms=j(()=>{"use strict";Ne();$e();je();ve();Pl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},kl=(e,t)=>{let r=e[0].dims,o=e[1].dims,n=r.length,s=U.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(U.size(u)/a),h=Re(e[0].dims.length),g=h?e[0].dims.length:e[0].dims,b=Re(e[1].dims.length),w=b?e[1].dims.length:e[1].dims,y=Re(u.length),_=y?u.length:u,I=[{type:"uint32",data:p},{type:"int32",data:l},{type:"uint32",data:s}];h&&I.push(...L(e[0].dims)),b&&I.push(...L(e[1].dims)),y&&I.push(...L(u));let $=[];$.push(h?"rank":"dims"),$.push(b?"rank":"dims");let x=E=>{let A=M("data",e[0].dataType,g,a),z=M("inputIndices",e[1].dataType,w),R=F("output",e[0].dataType,_,a),V=N=>{let te=o.length,Y=`var indicesIndices${N} = ${z.type.indices}(0);`;for(let K=0;K1?`indicesIndices${N}[${K}]`:`indicesIndices${N}`} = ${u.length>1?`outputIndices${N}[uniforms.axis + ${K}]`:`outputIndices${N}`};`;Y+=`\n var idx${N} = ${z.getByIndices(`indicesIndices${N}`)};\n if (idx${N} < 0) {\n idx${N} = idx${N} + uniforms.axisDimLimit;\n }\n var dataIndices${N} = ${A.type.indices}(0);\n `;for(let K=0,Q=0;K1?`dataIndices${N}[${K}]`:`dataIndices${N}`} = u32(idx${N});`,Q+=te):(Y+=`${n>1?`dataIndices${N}[${K}]`:`dataIndices${N}`} = ${u.length>1?`outputIndices${N}[${Q}]`:`outputIndices${N}`};`,Q++);return Y},T;if(e[0].dataType===9){let N=(te,Y,K="")=>`\n let outputIndices${Y} = ${R.offsetToIndices(`outputOffset + ${Y}u`)};\n ${V(Y)};\n let offset${Y} = ${A.indicesToOffset(`dataIndices${Y}`)};\n let index${Y} = offset${Y} / 4u;\n let component${Y} = offset${Y} % 4u;\n ${te}[${Y}] = ${K}(${A.getByOffset(`index${Y}`)}[component${Y}]);\n `;T=`\n let outputOffset = global_idx * ${a};\n var value = vec4(0);\n ${N("value",0,"u32")}\n ${N("value",1,"u32")}\n ${N("value",2,"u32")}\n ${N("value",3,"u32")}\n ${R.setByOffset("global_idx","value")}\n `}else T=`\n let outputIndices = ${R.offsetToIndices("global_idx")};\n ${V("")};\n let value = ${A.getByIndices("dataIndices")};\n ${R.setByOffset("global_idx","value")};\n `;return`\n ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(A,z,R)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${T}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:$},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:I}),getShaderSource:x}},cs=e=>ge({axis:e.axis}),ps=(e,t)=>{let r=e.inputs;Pl(r),e.compute(kl(e.inputs,t))}});var Rl,Bl,fs,hs,gs=j(()=>{"use strict";$e();je();ve();Rl=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.`)},Bl=(e,t)=>{let r=e[0].dims,o=e[0].dataType,n=r.length,s=e[1].dims,u=e[1].dataType,l=U.normalizeAxis(t.axis,n),a=r[l],p=s.slice(0),h=U.size(p),g=M("input",o,n),b=M("indicesInput",u,s.length),w=F("output",o,p.length),y=[{type:"uint32",data:h},{type:"int32",data:a},{type:"uint32",data:l}];return y.push(...L(r)),y.push(...L(s)),y.push(...L(p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:y}),getShaderSource:$=>`\n ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,b,w)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${w.offsetToIndices("global_idx")};\n\n var idx = ${b.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${g.type.indices}(outputIndices);\n ${g.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${g.getByIndices("inputIndices")};\n\n ${w.setByOffset("global_idx","value")};\n }`}},fs=e=>ge({axis:e.axis}),hs=(e,t)=>{let r=e.inputs;Rl(r),e.compute(Bl(e.inputs,t))}});var Dl,Ml,ys,bs,ws=j(()=>{"use strict";$e();ve();Dl=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")},Ml=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[n,s,u]=Hr.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=U.size(l),p=[{type:"uint32",data:a},{type:"uint32",data:n},{type:"uint32",data:s},{type:"uint32",data:u},{type:"float32",data:t.alpha},{type:"float32",data:t.beta}],h=["type","type"];e.length===3&&(p.push(...L(e[2].dims)),h.push("rank")),p.push(...L(l));let g=b=>{let w="";t.transA&&t.transB?w="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?w="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?w="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(w="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),$=_.type.value,x=null,E=[_,I];e.length===3&&(x=M("c",e[2].dataType,e[2].dims.length),E.push(x));let A=F("output",e[0].dataType,l.length);E.push(A);let z=[{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(z).declareVariables(...E)}\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 = ${$}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${w}\n }\n\n ${y}\n ${(()=>x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${$}(uniforms.beta) * ${x.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:g}},ys=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}`}},bs=(e,t)=>{Dl(e.inputs),e.compute(Ml(e.inputs,t))}});var zl,Ul,Vl,vs,$s=j(()=>{"use strict";Ne();$e();ve();zl=(e,t)=>{let r=e[0].dims,o=r,n=2,s=U.sizeToDimension(r,n),u=U.sizeFromDimension(r,n),l=Fe(u),a=u/l,p=[r[0],r[1],a],h=["rank","type","type"],g=[{type:"uint32",data:u},{type:"uint32",data:a}];g.push(...L(p),...L(p));let b=w=>{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),$=F("output",e[0].dataType,p.length,l),x=[y,_,I,$],E=y.type.value,A=l===1?"f32":`vec${l}`,z=64,R=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${A}, ${z}>;\n const workgroupSize = ${z}u;\n ${w.registerUniforms(R).declareVariables(...x)}\n ${w.mainStart(z)}\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 = ${A}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${A}(${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 = ${Je("workgroupShared[0]",l)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${A}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${A}(${y.get("batch","channel","h")}) - ${A}(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 = ${Je("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")} * ${E}(${A}(channelScale)) + ${E}(${A}(channelShift));\n ${$.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${l}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:s},programUniforms:g}),getShaderSource:b}},Ul=(e,t,r,o,n,s,u,l)=>{let a=Fe(u),p=64,h=a===1?"vec2f":`mat2x${a}f`,g=a===1?"f32":`vec${a}f`,b=(R,V)=>`${h}(${R}, ${V})`,w=n*u/a,y=Math.ceil(s/p),_=["type"],I=[{type:"uint32",data:y},{type:"uint32",data:s},{type:"uint32",data:Math.floor(u/a)},{type:"uint32",data:Math.floor(s*u/a)}],$=R=>{let V=M("input",t.dataType,t.dims,a);return`\n ${R.declareVariables(V)}\n @group(0) @binding(1) var output : array<${h}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${R.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 = ${Ze("f32",a)};\n var squaredSum = ${Ze("f32",a)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${g}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${b("sum","squaredSum")};\n }`},x=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:$},{inputs:[t],outputs:[-1]})[0],E=[{type:"uint32",data:w},{type:"uint32",data:s},{type:"uint32",data:Math.floor(u/a)},{type:"uint32",data:Math.floor(p*u/a)}],A=["type","type","type"],z=R=>{let V=M("scale",r.dataType,r.dims,a),T=M("bias",o.dataType,o.dims,a);return`\n @group(0) @binding(0) var input : array<${h}>;\n @group(0) @binding(1) var scale : array<${V.type.storage}>;\n @group(0) @binding(2) var bias : array<${T.type.storage}>;\n @group(0) @binding(3) var output : array<${h}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${R.mainStart()}\n ${R.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 = ${Ze("f32",a)};\n var squaredSum = ${Ze("f32",a)};\n for (var i: u32 = 0; i < ${p}; 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 * ${g}(scale[currentChannelNumber]);\n let channelShift = ${g}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${b("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${a};${l}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:[n,u,2],dataType:1}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:E}),getShaderSource:z},{inputs:[x,r,o],outputs:[-1]})[0]},Vl=(e,t,r)=>{let o=t[0].dims,n=o,s=o[0],u=o[o.length-1],l=U.sizeFromDimension(o,1)/u,a=Fe(u),p=U.size(n)/a,h=[{type:"uint32",data:l},{type:"uint32",data:Math.floor(u/a)}],g=["type","type"],b=Ul(e,t[0],t[1],t[2],s,l,u,r.epsilon),w=y=>{let _=Le(t[0].dataType),I=a===1?"vec2f":`mat2x${a}f`,$=a===1?_:`vec${a}<${_}>`,x=M("input",t[0].dataType,t[0].dims,a),E=F("output",t[0].dataType,n,a);return`\n @group(0) @binding(0) var input : array<${x.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${I}>;\n @group(0) @binding(2) var output : array<${E.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], ${$}(scale[0]), ${$}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${a}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:w},{inputs:[t[0],b]})},vs=(e,t)=>{t.format==="NHWC"?Vl(e,e.inputs,t):e.compute(zl(e.inputs,t))}});var Nl,Wl,Ss,xs=j(()=>{"use strict";Ne();$e();ve();Nl=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Wl=(e,t,r)=>{let o=e[0].dims,n=e[1],s=e[2],u=o,l=U.normalizeAxis(t.axis,o.length),a=U.sizeToDimension(o,l),p=U.sizeFromDimension(o,l),h=U.size(n.dims),g=s?U.size(s.dims):0;if(h!==p||s&&g!==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 ${h} and bias size of ${g}`);let b=[];for(let A=0;A1,$=r>2,x=A=>{let z=Le(e[0].dataType),R=[M("x",e[0].dataType,e[0].dims,w),M("scale",n.dataType,n.dims,w)];s&&R.push(M("bias",s.dataType,s.dims,w)),R.push(F("output",e[0].dataType,u,w)),I&&R.push(F("mean_data_output",1,b)),$&&R.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 ${A.registerUniforms(V).declareVariables(...R)}\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var meanVector = ${Ze("f32",w)};\n var meanSquareVector = ${Ze("f32",w)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${at(z,w,"x[h + offset]")};\n meanVector += value;\n meanSquareVector += value * value;\n }\n let mean = ${Je("meanVector",w)} / uniforms.norm_size;\n let invStdDev =\n inverseSqrt(${Je("meanSquareVector",w)} / uniforms.norm_size - mean * mean + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${at(z,w,"x[j + offset]")};\n let f32scale = ${at(z,w,"scale[j]")};\n output[j + offset] = ${R[0].type.value}((f32input - mean) * invStdDev * f32scale\n ${s?`+ ${at(z,w,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${$?"inv_std_output[global_idx] = invStdDev":""};\n }`},E=[{dims:u,dataType:e[0].dataType}];return I&&E.push({dims:b,dataType:1}),$&&E.push({dims:b,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${w};${r}`,inputDependencies:y},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:_}),getShaderSource:x}},Ss=(e,t)=>{Nl(e.inputs),e.compute(Wl(e.inputs,t,e.outputCount))}});var Hl,Cs,_s,Gl,Xn,Is,As=j(()=>{"use strict";$e();je();Nr();Un();ve();jt();Hl=(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 h=!1,g=r.dims[0],b=r.dims[1],w=r.dims.length===3?h?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=b,_=0,I=0,$=Math.floor(w/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 x;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)\');x=2,y=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==$)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.\');x=5,y=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==$)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');x=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\');x=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 E=0;if(u){E=8;let T=u.dims;throw T.length===1?T[0]===g?E=1:T[0]===3*g+2&&(E=3):T.length===2&&T[0]===g&&T[1]===y&&(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 A=!1,z=w;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)\');z=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)\');z=n.dims[1]*n.dims[3],A=!0}}let R=_+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:g,sequenceLength:b,pastSequenceLength:_,kvSequenceLength:y,totalSequenceLength:R,maxSequenceLength:I,inputHiddenSize:0,hiddenSize:w,vHiddenSize:z,headSize:$,vHeadSize:Math.floor(z/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:E,scale:t.scale,broadcastResPosBias:V,passPastInKv:A,qkvFormat:x}},Cs=e=>ge({...e}),_s=ge({perm:[0,2,1,3]}),Gl=(e,t,r,o,n,s,u)=>{let l=[o,n,s],a=U.size(l),p=[{type:"uint32",data:a},{type:"uint32",data:u},{type:"uint32",data:s}],h=g=>{let b=F("qkv_with_bias",t.dataType,l),w=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 ${g.registerUniforms(_).declareVariables(w,y,b)}\n ${g.mainStart()}\n ${g.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:h},{inputs:[t,r],outputs:[-1]})[0]},Xn=(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=Gl(e,s,u,t,o,r*n,l),a=a.reshape([t,o,r,n]),e.compute(it(a,_s.perm),{inputs:[a],outputs:[-1]})[0]}else return s.dims.length===3&&(a=s.reshape([t,o,r,n])),e.compute(it(a,_s.perm),{inputs:[a],outputs:[-1]})[0]},Is=(e,t)=>{let r=Hl(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=Xn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],e.inputs[3],0);if(o)return Kr(e,n,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t);let s=Xn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,e.inputs[1],e.inputs[3],r.hiddenSize),u=Xn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,e.inputs[2],e.inputs[3],2*r.hiddenSize);Kr(e,n,s,u,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],r,t)}});var Ll,Fl,jl,ql,Kl,Yl,Zl,Ql,Ts,Es=j(()=>{"use strict";Ne();$e();ve();Ll=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1)throw new Error("Input type must be float.");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].")}},Fl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n break;\n }\n offset += k * i32(${ce("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 `},jl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${ce("uniforms.x_shape",n,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},ql=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k = i32(${ce("uniforms.x_shape",n,t)}) - 1;\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},Kl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k += i32(${ce("uniforms.x_shape",n,t)}]);\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k -= i32(${ce("uniforms.x_shape",n,t)});\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},Yl=(e,t,r)=>{switch(r.mode){case 0:return Fl(e,t,r.pads.length);case 1:return jl(e,t,r.pads.length);case 2:return ql(e,t,r.pads.length);case 3:return Kl(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Zl=(e,t)=>{let r=U.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,s=[{type:"uint32",data:U.size(r)},{type:"uint32",data:t.pads}];if(t.mode===0){let a=Xe(e[0].dataType);s.push({type:a,data:t.value})}s.push(...L(e[0].dims),...L(r));let u=["rank"],l=a=>{let p=F("output",e[0].dataType,r.length),h=M("x",e[0].dataType,o.length),g=h.type.value,b=Yl(p,o.length,t),w=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&w.push({name:"constant_value",type:g}),`\n ${a.registerUniforms(w).declareVariables(h,p)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n\n var value = ${g}(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(U.size(r)/64)},programUniforms:s}),getShaderSource:l}},Ql=(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},Ts=(e,t)=>{Ll(e.inputs);let r=Ql(e.inputs,t);e.compute(Zl(e.inputs,r),{inputs:[0]})}});var nn,Os,Ps,ks,Rs,Xl,Jl,Bs,Ds,Ms,zs,Us,Vs,Ns,Ws,Hs,Gs,Ls,Fs,js=j(()=>{"use strict";Lt();$e();ve();nn=e=>{if(Gt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Os=(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();Bt.adjustPoolAttributes(r,n,u,l,a,p);let h=Bt.computePoolOutputShape(r,n,l,a,u,p,t.autoPad),g=Object.assign({},t);s?Object.assign(g,{kernelShape:u,strides:l,pads:p,dilations:a,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:u,strides:l,pads:p,cacheKey:t.cacheKey});let b=h.slice();return b.push(b.splice(1,1)[0]),[g,o?b:h]},Ps=(e,t)=>{let r=t.format==="NHWC",o=U.size(e),n=U.size(t.kernelShape),s=[{type:"uint32",data:o},{type:"uint32",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],h=t.pads[t.pads.length-1],g=!!(p+h);s.push({type:"uint32",data:l},{type:"uint32",data:a},{type:"uint32",data:p},{type:"uint32",data:h}),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 w=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:"uint32",data:w},{type:"uint32",data:y},{type:"uint32",data:_},{type:"uint32",data:I}),u.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[s,u,!0,g,b]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=U.computeStrides(t.kernelShape);s.push({type:"uint32",data:l},{type:"uint32",data:t.pads},{type:"uint32",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,h)=>p+h);return[s,u,!!a,!1,!1]}},ks=(e,t,r,o,n,s,u,l,a,p,h,g)=>{let b=n.format==="NHWC",w=t.type.value,y=F("output",t.type.tensor,o);if(n.kernelShape.length<=2){let _="",I="",$="",x=r-(b?2:1);if(h?_=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${x}] < 0 || xIndices[${x}]\n >= uniforms.x_shape[${x}]) {\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[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`,n.kernelShape.length===2){let A=r-(b?3:2);g?I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${A}] = indices[${A}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${A}] < 0 || xIndices[${A}] >= uniforms.x_shape[${A}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${A}] = indices[${A}] * uniforms.sh - uniforms.phStart + j;\n `,$=`\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 = ${w}(${l});\n var pad = 0;\n ${I}\n ${_}\n ${$}\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,$="";return p?$=`\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 }`:$=`\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 = ${w}(${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 / ${ce("uniforms.kernelStrides","j",_)};\n offset -= offsets[j] * ${ce("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] * ${ce("uniforms.strides",`j - ${r-_}u`,_)}\n + offsets[j - ${r-_}u] - ${ce("uniforms.pads","j - 2u",I)};\n ${$}\n }\n ${u}\n\n output[global_idx] = value;\n }`}},Rs=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Xl=e=>`${Rs(e)};${e.countIncludePad}`,Jl=e=>`${Rs(e)};${e.storageOrder};${e.dilations}`,Bs=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}),Ds=(e,t,r,o)=>{let[n,s]=Os(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[h,g,b,w,y]=Ps(s,n);h.push(...L(t.dims),...L(s));let _=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${b};${w};${y}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(U.size(s)/64)},programUniforms:h}),getShaderSource:I=>ks(I,u,t.dims.length,s.length,n,a,p,0,g,b,w,y)}},Ms=e=>{let t=e.count_include_pad!==0,r=Bs(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:Xl(o)}},zs=(e,t)=>{nn(e.inputs),e.compute(Ds("AveragePool",e.inputs[0],!1,t))},Us={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Vs=e=>{let t=e.format;return{format:t,...Us,cacheKey:t}},Ns=(e,t)=>{nn(e.inputs),e.compute(Ds("GlobalAveragePool",e.inputs[0],!0,t))},Ws=(e,t,r,o)=>{let[n,s]=Os(t,o,r),u=`\n value = max(x_val, value);\n `,l="",a=M("x",t.dataType,t.dims.length),p=["rank"],[h,g,b,w,y]=Ps(s,n);return h.push(...L(t.dims),...L(s)),{name:e,shaderCache:{hint:`${o.cacheKey};${b};${w};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(U.size(s)/64)},programUniforms:h}),getShaderSource:_=>ks(_,a,t.dims.length,s.length,n,u,l,-1e5,g,b,w,y)}},Hs=(e,t)=>{nn(e.inputs),e.compute(Ws("MaxPool",e.inputs[0],!1,t))},Gs=e=>{let t=e.storage_order,r=e.dilations,o=Bs(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:Jl(n)}},Ls=e=>{let t=e.format;return{format:t,...Us,cacheKey:t}},Fs=(e,t)=>{nn(e.inputs),e.compute(Ws("GlobalMaxPool",e.inputs[0],!0,t))}});var tc,rc,qs,Ks=j(()=>{"use strict";Lt();Ne();ve();tc=(e,t,r)=>{let o=e===t,n=et&&r>0;if(o||n||s)throw new Error("Range these inputs\' contents are invalid.")},rc=(e,t,r,o)=>{let n=Math.abs(Math.ceil((t-e)/r)),s=[n],u=n,l=Xe(o),a=[{type:"uint32",data:u},{type:l,data:e},{type:l,data:r},...L(s)],p=h=>{let g=F("output",o,s.length),b=g.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:b},{name:"delta",type:b}];return`\n ${h.registerUniforms(w).declareVariables(g)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${b}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:s,dataType:o}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:a})}},qs=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]),Gt.webgpu.validateInputContent&&tc(t,r,o),e.compute(rc(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var nc,oc,ac,ic,sc,uc,dc,lc,cc,pc,mc,Ys,fc,hc,gc,yc,bc,Zs,Qs,Xs=j(()=>{"use strict";$e();je();ve();nc=(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")}},oc=(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},ac=(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(h=>s.push(h));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(h=>o.push(h)),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");nc(o,t),t.axes.length>0&&oc(o,t.axes,p).forEach((h,g)=>o[g]=h)}if(a>0&&e.length>a&&(e[a].getBigInt64Array().forEach(h=>n.push(Number(h))),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`)}})()+"}",sc=(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`)}})()+"}",uc=(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},dc=(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},lc=(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},cc=(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 = ${ce("uniforms.scales","i",o)};\n var roi_low = ${ce("uniforms.roi","i",n)};\n var roi_hi = ${ce("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 = ${ce("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${ce("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 }`,pc=(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 = ${ce("uniforms.scales","i",n)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${ce("uniforms.roi","i",s)};\n var roi_hi = ${ce("uniforms.roi",`i + ${r.length}`,s)};\n var input_shape_i = ${ce("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${ce("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 }`,mc=(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 >= ${ce("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Ys=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",fc=(e,t,r,o,n)=>{let[u,l,a,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} {\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 ${Ys(e,p,u,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${h} = originalIndices[${l}];\n var col:${h} = 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: ${h} = getInputValue(batch, channel, row1, col1);\n var x12: ${h} = getInputValue(batch, channel, row1, col2);\n var x21: ${h} = getInputValue(batch, channel, row2, col1);\n var x22: ${h} = getInputValue(batch, channel, row2, col2);\n var dx1: ${h} = abs(row - ${h}(row1));\n var dx2: ${h} = abs(${h}(row2) - row);\n var dy1: ${h} = abs(col - ${h}(col1));\n var dy2: ${h} = abs(${h}(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 }`},hc=(e,t,r,o,n,s,u,l,a,p)=>{let h=r.length===2,g=!0,[b,w]=h?[0,1]:g?[2,3]:[1,2],y=e.type.value,_=I=>{let $=I===b?"row":"col";return`\n fn ${$}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 ${$}: ${y} = originalIdx + ${y}(i);\n if (${$} < 0 || ${$} >= ${r[I]}) {\n ${(()=>p?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${a};`:`${$} = max(0, min(${$}, ${r[I]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",I,`u32(${$})`)};\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 ${_(w)};\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 `},gc=(e,t,r,o,n)=>{let[u,l,a,p,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} {\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 ${Ys(e,h,u,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${g} = originalIndices[${l}];\n var height:${g} = originalIndices[${a}];\n var width:${g} = 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[${h}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${u}])`:"0"};\n\n var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${g} = abs(depth - ${g}(depth1));\n var dx2: ${g} = abs(${g}(depth2) - depth);\n var dy1: ${g} = abs(height - ${g}(height1));\n var dy2: ${g} = abs(${g}(height2) - height);\n var dz1: ${g} = abs(width - ${g}(width1));\n var dz2: ${g} = abs(${g}(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 }`},yc=(e,t,r,o,n,s)=>{let u=e.dims,l=uc(s,t.axes,u.length),a=dc(u,o,n,t.axes),p=o.slice();o.length===0&&(p=u.map((x,E)=>x===0?1:a[E]/x),t.keepAspectRatioPolicy!=="stretch"&&(a=lc(u,p,t)));let h=F("output",e.dataType,a.length),g=M("input",e.dataType,u.length),b=U.size(a),w=u.length===a.length&&u.every((x,E)=>x===a[E]),y=t.coordinateTransformMode==="tf_crop_and_resize",_=t.extrapolationValue,I=g.type.value,$=x=>`\n ${w?"":`\n ${ic(t.coordinateTransformMode,I)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${mc(g,u)};\n ${sc(t.nearestMode,r,I)};\n ${pc(g,h,u,a,p.length,l.length,y)};\n `;case"linear":return`\n ${cc(h,u,a,p.length,l.length)};\n ${(()=>{if(u.length===2||u.length===4)return`${fc(g,h,u,y,_)}`;if(u.length===3||u.length===5)return`${gc(g,h,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`${hc(g,h,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 ${x.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",l.length).declareVariables(g,h)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${w?"output[global_idx] = input[global_idx];":`\n let output_indices = ${h.offsetToIndices("global_idx")};\n var input_indices: ${g.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${g.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:""}|${w}|${u}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:"uint32",data:b},{type:"float32",data:p},{type:"float32",data:l},...L(u),...L(a)]})}},bc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Zs=(e,t)=>{let r=[],o=[],n=[],s=bc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");ac(e.inputs,t,s,r,o,n),e.compute(yc(e.inputs[0],t,s,r,o,n),{inputs:[0]})},Qs=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 ge({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:n,excludeOutside:s,extrapolationValue:u,keepAspectRatioPolicy:l,mode:a,nearestMode:p})}});var wc,vc,Js,eu,tu=j(()=>{"use strict";Ne();$e();je();ve();wc=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")}},vc=(e,t,r,o)=>{let n=e[0].dims,s=U.size(n),u=n,l=s,a=n.slice(-1)[0],p=o?n.slice(0,-1).concat(1):[],h=e.length>3,g=e.length>4,b=o&&r>1,w=o&&r>2,y=r>3,_=Fe(a),I=[M("x",e[0].dataType,e[0].dims,_),M("skip",e[1].dataType,e[1].dims,_),M("gamma",e[2].dataType,e[2].dims,_)];h&&I.push(M("beta",e[3].dataType,e[3].dims,_)),g&&I.push(M("bias",e[4].dataType,e[4].dims,_)),I.push(F("output",e[0].dataType,u,_)),b&&I.push(F("meanOutput",1,p)),w&&I.push(F("invStdOutput",1,p)),y&&I.push(F("inputSkipBiasSum",e[0].dataType,u,_));let $=Le(e[0].dataType),x=A=>`\n const hiddenSize: f32 = ${a};\n const hiddenSizeVectorized: u32 = ${a/_};\n const epsilon: f32 = ${t.epsilon};\n\n ${A.declareVariables(...I)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes(l/a)}\n let offset = global_idx * hiddenSizeVectorized;\n var sum = ${Ze("f32",_)};\n var squareSum = ${Ze("f32",_)};\n for (var i: u32 = 0; i < hiddenSizeVectorized; i++) {\n let skipValue = skip[offset + i];\n let biasValue = ${g?"bias[i]":"0.0"};\n let inputValue = x[offset + i];\n let value = inputValue + skipValue + biasValue;\n ${y?"inputSkipBiasSum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32Value = ${at($,_,"value")};\n sum += f32Value;\n squareSum += f32Value * f32Value;\n }\n let mean = ${Je("sum",_)} / hiddenSize;\n let invStdDev = inverseSqrt(${Je("squareSum",_)} / hiddenSize - mean * mean + epsilon);\n ${b?"meanOutput[global_idx] = mean;":""}\n ${w?"invStdOutput[global_idx] = invStdDev;":""}\n for (var i: u32 = 0; i < hiddenSizeVectorized; i++) {\n output[offset + i] = (output[offset + i] - ${$}(mean)) * ${$}(invStdDev) * gamma[i]\n + ${h?"beta[i]":"0.0"};\n }\n }`,E=[{dims:u,dataType:e[0].dataType}];return r>1&&E.push({dims:p,dataType:1}),r>2&&E.push({dims:p,dataType:1}),r>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:t.cacheKey},getShaderSource:x,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/a/64)}})}},Js=(e,t)=>{wc(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(vc(e.inputs,t,e.outputCount,!1),{outputs:o})},eu=e=>{let t=e.epsilon;return ge({epsilon:t})}});var $c,on,Sc,ru,xc,_c,nu,ou,au=j(()=>{"use strict";Ne();$e();je();ve();$c=(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`)})},on=(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},Sc=(e,t)=>{if(e.length>1){let r=on(e,1),o=on(e,2),n=on(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),ge({starts:r,ends:o,axes:n})}else return t},ru=(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]]))},xc=(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 = ${ce("uniforms.input_shape","i",r.length)};\n let steps_i = ${ce("uniforms.steps","i",r.length)};\n let signs_i = ${ce("uniforms.signs","i",r.length)};\n let starts_i = ${ce("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 }`,_c=(e,t)=>{let r=e[0].dims,o=U.size(r),n=t.axes.length>0?U.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],s=on(e,4);s.forEach($=>$!==0||(()=>{throw new Error("step cannot be 0")})),s.length===0&&(s=Array(n.length).fill(1));let u=t.starts.map(($,x)=>ru($,x,r,n,s)),l=t.ends.map(($,x)=>ru($,x,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 $=0;$Math.sign($));s.forEach(($,x,E)=>{if($<0){let A=(l[x]-u[x])/$,z=u[x],R=z+A*s[x];u[x]=R,l[x]=z,E[x]=-$}});let p=r.slice(0);n.forEach(($,x)=>{p[$]=Math.ceil((l[$]-u[$])/s[$])});let h={dims:p,dataType:e[0].dataType},g=F("output",e[0].dataType,p.length),b=M("input",e[0].dataType,e[0].dims.length),w=U.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:"uint32",data:w},{type:"uint32",data:u},{type:"int32",data:a},{type:"uint32",data:s},...L(e[0].dims),...L(p)],I=$=>`\n ${$.registerUniforms(y).declareVariables(b,g)}\n ${xc(b,g,r)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${g.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${g.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:[h],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:_})}},nu=(e,t)=>{$c(e.inputs,t);let r=Sc(e.inputs,t);e.compute(_c(e.inputs,r),{inputs:[0]})},ou=e=>{let t=e.starts,r=e.ends,o=e.axes;return ge({starts:t,ends:r,axes:o})}});var Cc,Ic,iu,su,uu=j(()=>{"use strict";$e();je();ve();Cc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Ic=(e,t)=>{let r=e.dims,o=U.size(r),n=64,s=t.axis;if(s<0&&(s=r.length+s),s$===4?`max(max(${I}.x, ${I}.y), max(${I}.z, ${I}.w))`:$===2?`max(${I}.x, ${I}.y)`:$===3?`max(max(${I}.x, ${I}.y), ${I}.z)`:I,g=M("x",e.dataType,e.dims,a),b=F("result",e.dataType,e.dims,a),w=g.type.value,y=Le(e.dataType)==="f32"?`var threadMax = ${w}(-3.402823e+38f);`:`var threadMax = ${w}(-65504.0h);`,_=I=>`\n var rowMaxShared : ${w};\n var rowSumShared : ${w};\n var threadShared : array<${w}, ${n}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${w} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${w}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${I.registerUniform("packedCols","i32").declareVariables(g,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 = ${w}(${h("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${w}(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 = ${w}(${Je("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:"uint32",data:p}]}),getShaderSource:_}},iu=(e,t)=>{Cc(e.inputs),e.compute(Ic(e.inputs[0],t))},su=e=>ge({axis:e.axis})});var Ac,Tc,Ec,Oc,Pc,du,lu,cu=j(()=>{"use strict";$e();je();ve();Ac=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Tc=(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),ge({numOutputs:o,axis:t.axis,splitSizes:r})},Ec=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${ce("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Oc=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=U.size(r),n=e[0].dataType,s=U.normalizeAxis(t.axis,r.length),u=new Array(t.numOutputs),l=M("input",n,r),a=new Array(t.numOutputs),p=[],h=[],g=0,b=[{type:"uint32",data:o}];for(let y=0;yb.push(...L(y)));let w=y=>`\n ${y.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",a.length).declareVariables(l,...u)}\n ${Ec(a.length)}\n ${Oc(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 -= ${ce("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:w,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:b})}},du=(e,t)=>{Ac(e.inputs);let r=e.inputs.length===1?t:Tc(e.inputs,t);e.compute(Pc(e.inputs,r),{inputs:[0]})},lu=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 ge({axis:t,numOutputs:o,splitSizes:r})}});var pu,kc,Rc,Bc,mu,fu=j(()=>{"use strict";Ne();$e();ve();pu=e=>Array.from(e.getBigInt64Array(),Number),kc=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(pu(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")},Rc=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=pu(e[1]),o=Rc(t,r),n=U.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:"uint32",data:n},...L(e[0].dims),...L(o)]}),getShaderSource:a}},mu=e=>{kc(e.inputs),e.compute(Bc(e.inputs),{inputs:[0]})}});var Dc,Mc,hu,gu=j(()=>{"use strict";Ne();$e();ve();Dc=(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,h=(g,b,w)=>`select(${b}, ${g}, ${w})`;if(!o)p=s.setByOffset("global_idx",h(u.getByOffset("global_idx"),l.getByOffset("global_idx"),a.getByOffset("global_idx")));else{let g=(b,w,y="")=>{let _=`a_data[index_a${w}][component_a${w}]`,I=`b_data[index_b${w}][component_b${w}]`,$=`bool(c_data[index_c${w}] & ${4278190080>>>(3-w)*8}u)`;return`\n let output_indices${w} = ${s.offsetToIndices(`global_idx * 4u + ${w}u`)};\n let offset_a${w} = ${u.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let offset_b${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let offset_c${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let index_a${w} = offset_a${w} / 4u;\n let index_b${w} = offset_b${w} / 4u;\n let index_c${w} = offset_c${w} / 4u;\n let component_a${w} = offset_a${w} % 4u;\n let component_b${w} = offset_b${w} % 4u;\n ${b}[${w}] = ${y}(${h(_,I,$)});\n `};n===9?p=`\n var data = vec4(0);\n ${g("data",0,"u32")}\n ${g("data",1,"u32")}\n ${g("data",2,"u32")}\n ${g("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=`\n ${g("output_data[global_idx]",0)}\n ${g("output_data[global_idx]",1)}\n ${g("output_data[global_idx]",2)}\n ${g("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 }`},Mc=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,n=e[1].dataType,s=!(U.areEqual(t,r)&&U.areEqual(r,o)),u=t,l=U.size(t);if(s){let p=dt.calcShape(dt.calcShape(t,r,!1),o,!1);if(!p)throw new Error("Can\'t perform where op on the given tensors");u=p,l=U.size(u)}let a=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Dc(p,e,u,s,n),getRunData:()=>({outputs:[{dims:u,dataType:n}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:"uint32",data:a},...L(o),...L(t),...L(r),...L(u)]})}},hu=e=>{e.compute(Mc(e.inputs))}});var yu,bu=j(()=>{"use strict";Wa();Un();La();ja();Ci();Mi();Vi();Gn();Ji();rs();ss();ls();ms();gs();ws();$s();xs();Fn();As();Es();js();Ks();jr();Xs();tu();au();uu();cu();fu();jt();Vn();gu();yu=new Map([["Abs",[qa]],["Acos",[Ka]],["Acosh",[Ya]],["Add",[Ii]],["ArgMax",[Na,zn]],["ArgMin",[Va,zn]],["Asin",[Za]],["Asinh",[Qa]],["Atan",[Xa]],["Atanh",[Ja]],["Attention",[Ha]],["AveragePool",[zs,Ms]],["BatchNormalization",[Ga]],["BiasAdd",[Fa]],["BiasSplitGelu",[_i]],["Cast",[ti,ei]],["Ceil",[ni]],["Clip",[ri]],["Concat",[zi,Ui]],["Conv",[qn,jn]],["ConvTranspose",[Xi,Qi]],["Cos",[oi]],["Cosh",[ai]],["CumSum",[es,ts]],["Div",[Ai]],["Einsum",[as,is]],["Elu",[ii,Yr]],["Equal",[Ti]],["Erf",[si]],["Exp",[ui]],["Expand",[ds]],["Floor",[di]],["FusedConv",[qn,jn]],["Gather",[ps,cs]],["GatherElements",[hs,fs]],["Gelu",[li]],["Gemm",[bs,ys]],["GlobalAveragePool",[Ns,Vs]],["GlobalMaxPool",[Fs,Ls]],["Greater",[ki]],["GreaterOrEqual",[Bi]],["InstanceNormalization",[vs]],["LayerNormalization",[Ss]],["LeakyRelu",[ci,Yr]],["Less",[Ri]],["LessOrEqual",[Di]],["Log",[xi]],["MatMul",[Li]],["MaxPool",[Hs,Gs]],["Mul",[Ei]],["MultiHeadAttention",[Is,Cs]],["Neg",[mi]],["Not",[pi]],["Pad",[Ts]],["Pow",[Oi]],["Range",[qs]],["Reciprocal",[fi]],["ReduceMin",[Ra]],["ReduceMean",[Ta]],["ReduceMax",[ka]],["ReduceSum",[Da]],["ReduceProd",[Ba]],["ReduceL1",[Ea]],["ReduceL2",[Oa]],["ReduceLogSum",[za]],["ReduceLogSumExp",[Pa]],["ReduceSumSquare",[Ma]],["Relu",[hi]],["Resize",[Zs,Qs]],["Sigmoid",[gi]],["Sin",[yi]],["Sinh",[bi]],["Slice",[nu,ou]],["SkipLayerNormalization",[Js,eu]],["Split",[du,lu]],["Sqrt",[wi]],["Softmax",[iu,su]],["Sub",[Pi]],["Tan",[vi]],["Tanh",[$i]],["ThresholdedRelu",[Si,Yr]],["Tile",[mu]],["Transpose",[ha,ga]],["Where",[hu]]])});var an,wu=j(()=>{"use strict";Lt();Ct();ve();an=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){kt(t.programInfo.name);let u=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2),l.setPipeline(t.computePipeline);let a=[];for(let h of r)a.push({binding:a.length,resource:{buffer:h.buffer}});for(let h of o)a.push({binding:a.length,resource:{buffer:h.buffer}});s&&a.push({binding:a.length,resource:s});let p=u.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:a,label:t.programInfo.name});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(),Rt(t.programInfo.name)}dispose(){}build(t,r){kt(t.name);let o=this.backend.device,n=[];o.features.has("shader-f16")&&n.push("enable f16;");let s=ma(r),u=t.getShaderSource(s),l=`${n.join(`\n`)}\n${s.additionalImplementations}\n${u}`,a=o.createShaderModule({code:l,label:t.name});Be("verbose",()=>`[WebGPU] ${t.name} shader code: ${l}`);let p=o.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:t.name});return Rt(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 zc,Uc,sn,vu=j(()=>{"use strict";Lt();Ne();Ct();ua();pa();bu();wu();zc=(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+`:${zc(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},sn=class{constructor(){this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=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.gpuDataManager=ca(this),this.programManager=new an(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ia(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}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder(),this.setQueryType(),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}))),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=this.getCommandEncoder().beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;kt(),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=w);let _=Number(w-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:g.map($=>({dims:$.dims,dataType:Xe($.dataType)})),outputsMetadata:b.map($=>({dims:$.dims,dataType:Xe($.dataType)})),kernelId:u,kernelType:a,kernelName:p,programName:h,startTime:_,endTime:I});else{let $="";g.forEach((E,A)=>{$+=`input[${A}]: [${E.dims}] | ${Xe(E.dataType)}, `});let x="";b.forEach((E,A)=>{x+=`output[${A}]: [${E.dims}] | ${Xe(E.dataType)}, `}),console.log(`[profiling] kernel "${u}|${a}|${p}|${h}" ${$}${x}execution time: ${I-_} ns`)}An("GPU",`${h}::${w}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Rt()}run(t,r,o,n,s){kt(t.name);let u=[];for(let x=0;xE):o;if(h.length!==l.length)throw new Error(`Output size ${h.length} must be equal to ${l.length}.`);let g=[],b=[];for(let x=0;x=l.length)throw new Error(`Invalid output index: ${h[x]}`);if(h[x]===-3)continue;let E=h[x]===-1,A=h[x]===-2,z=E||A?s(l[x].dataType,l[x].dims):n(h[x],l[x].dataType,l[x].dims),R=this.gpuDataManager.get(z.data);if(!R)throw new Error(`no GPU data for output: ${z.data}`);if(E&&this.temporaryData.push(R),A){let V=this.kernelPersistentData.get(this.currentKernelId);V||(V=[],this.kernelPersistentData.set(this.currentKernelId,V)),V.push(R)}g.push(z),b.push(R)}let w;if(p){let x=0,E=[];p.forEach(V=>{let T=typeof V.data=="number"?[V.data]:V.data;if(T.length===0)return;let N=T.length<=2?T.length*4:16;x=Math.ceil(x/N)*N,E.push(x),x+=T.length>4?Math.ceil(T.length/4)*16:T.length*4});let A=16;x=Math.ceil(x/A)*A;let z=new ArrayBuffer(x);p.forEach((V,T)=>{let N=E[T],te=typeof V.data=="number"?[V.data]:V.data;V.type==="int32"?new Int32Array(z,N,te.length).set(te):V.type==="uint32"?new Uint32Array(z,N,te.length).set(te):new Float32Array(z,N,te.length).set(te)});let R=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(R.buffer,0,z,0,x),this.gpuDataManager.release(R.id),w={offset:0,size:x,buffer:R.buffer}}let y=this.programManager.normalizeDispatchGroupSize(a),_=y[1]===1&&y[2]===1,I=Uc(t,r,_),$=this.programManager.getArtifact(I);if($||($=this.programManager.build(t,y),this.programManager.setArtifact(I,$),Be("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),Be("info",()=>`[ProgramManager] run "${t.name}" (key=${I}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"){let x={kernelId:this.currentKernelId,programName:$.programInfo.name,inputTensorViews:r,outputTensorViews:g};this.pendingKernels.push(x)}return this.programManager.run($,u,b,y,w),Rt(t.name),g}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=yu.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),Be("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(h){return o.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${u}" failed. ${h}`)),1}finally{p&&o.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${s}] ${u}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.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 On(this,t,r);return sa(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"||this.env.wasm.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"))}}});var $u={};Br($u,{init:()=>Vc});var gr,Jn,Vc,Su=j(()=>{"use strict";Ne();vu();Ct();$e();gr=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=U.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=U.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=U.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(U.size(t)!==U.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Jn=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;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 gr(this.module,a,this.output(l,p),p),u=(l,a)=>{let p=cr(l);if(!p)throw new Error(`Unsupported data type: ${l}`);let h=p*U.size(a);return new gr(this.module,l,this.backend.gpuDataManager.create(h).id,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 o=e.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");let n=new sn;await n.initialize(t,r),o(n,s=>n.alloc(s),s=>n.free(s),(s,u,l,a=!1)=>{if(a)Be("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${u}, size=${l}`),n.memcpy(s,u);else{Be("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${u}, size=${l}`);let p=e.HEAPU8.subarray(s>>>0,(s>>>0)+l);n.upload(u,p)}},async(s,u,l)=>{Be("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${u}, size=${l}`),await n.download(s,()=>e.HEAPU8.subarray(u>>>0,(u>>>0)+l))},(s,u,l)=>n.createKernel(s,u,l,e.UTF8ToString(e._JsepGetNodeName(u))),s=>n.releaseKernel(s),(s,u,l,a)=>{Be("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${s}, contextDataOffset=${u}`);let p=new Jn(e,n,u);return n.computeKernel(s,p,a)})}});var Mo;Mo=Io();var Ju=Ro(),Sn,xn=!1,Dr=!1,Do=!1,ed=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}},td=()=>{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}},rd=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",zo=async e=>{if(xn)return Promise.resolve();if(Dr)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Do)throw new Error("previous call to \'initializeWebAssembly()\' failed.");Dr=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,n=ed(r),s=o&&td(),u=e.wasmPaths,l=typeof u=="string"?u:void 0,a=rd(s,n),p=typeof u=="object"?u[a]:void 0,h=!1,g=[];if(t>0&&g.push(new Promise(b=>{setTimeout(()=>{h=!0,b()},t)})),g.push(new Promise((b,w)=>{let y=n?Ju:Mo,_={locateFile:(I,$)=>{if(n&&I.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Bo()],{type:"text/javascript"}));if(I.endsWith(".wasm")){if(p)return p;let x=l??$;return a==="ort-wasm-simd.wasm"?x+"ort-wasm-simd.jsep.wasm":a==="ort-wasm-simd-threaded.wasm"?x+"ort-wasm-simd-threaded.jsep.wasm":x+a}return $+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=>{Dr=!1,xn=!0,Sn=I,b()},I=>{Dr=!1,Do=!0,w(I)})})),await Promise.race(g),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ve=()=>{if(xn&&Sn)return Sn;throw new Error("WebAssembly is not initialized yet.")};var He=(e,t)=>{let r=Ve(),o=r.lengthBytesUTF8(e)+1,n=r._malloc(o);return r.stringToUTF8(e,n,o),t.push(n),n},lr=(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")lr(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}`)})},ke=e=>{let t=Ve(),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 Uo=e=>{let t=Ve(),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=He(e.tag,o)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&ke("Can\'t create run options."),e?.extra!==void 0&&lr(e.extra,"",new WeakSet,(u,l)=>{let a=He(u,o),p=He(l,o);t._OrtAddRunConfigEntry(r,a,p)!==0&&ke(`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 nd=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}`)}},od=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ad=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)},id=(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=He("deviceType",r),a=He(u.deviceType,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`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=He("numThreads",r),p=He(l.toString(),r);Ve()._OrtAddSessionConfigEntry(e,a,p)!==0&&ke(`Can\'t set a session config entry: \'numThreads\' - ${u.numThreads}.`)}if(u?.powerPreference){let l=He("powerPreference",r),a=He(u.powerPreference,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`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=He("preferredLayout",r),a=He(u.preferredLayout,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`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=He(n,r);Ve()._OrtAppendExecutionProvider(e,s)!==0&&ke(`Can\'t append execution provider: ${n}.`)}},Vo=e=>{let t=Ve(),r=0,o=[],n=e||{};ad(n);try{let s=nd(n.graphOptimizationLevel??"all"),u=od(n.executionMode??"sequential"),l=typeof n.logId=="string"?He(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 h=typeof n.optimizedModelFilePath=="string"?He(n.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,u,!!n.enableProfiling,0,l,a,p,h),r===0&&ke("Can\'t create session options."),n.executionProviders&&id(r,n.executionProviders,o),n.freeDimensionOverrides)for(let[g,b]of Object.entries(n.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof b!="number"||!Number.isInteger(b)||b<0)throw new Error(`free dimension override value must be a non-negative integer: ${b}`);let w=He(g,o);t._OrtAddFreeDimensionOverride(r,w,b)!==0&&ke(`Can\'t set a free dimension override: ${g} - ${b}.`)}return n.extra!==void 0&&lr(n.extra,"",new WeakSet,(g,b)=>{let w=He(g,o),y=He(b,o);t._OrtAddSessionConfigEntry(r,w,y)!==0&&ke(`Can\'t set a session config entry: ${g} - ${b}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(u=>t._free(u)),s}};Ne();var Wo=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 Nc=(e,t)=>{Ve()._OrtInit(e,t)!==0&&ke("Can\'t initialize onnxruntime.")},_u=async e=>{Nc(e.wasm.numThreads,pr(e.logLevel))},Cu=async(e,t)=>{if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let r=await navigator.gpu.requestAdapter();if(!r)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");let o=(Su(),Ht($u)).init;await o(Ve(),e,r)}},yr=new Map,Wc=e=>{let t=Ve(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&ke("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},eo=e=>{let t=Ve(),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]},Iu=async(e,t)=>{let r,o,n=Ve();Array.isArray(e)?[r,o]=e:e.buffer===n.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=eo(e);let s=0,u=0,l=0,a=[],p=[],h=[];try{if([u,a]=Vo(t),t?.externalData&&n.mountExternalData){let $=[];for(let x of t.externalData){let E=typeof x=="string"?x:x.path;$.push(Wo(typeof x=="string"?x:x.data).then(A=>{n.mountExternalData(E,A)}))}await Promise.all($)}s=n._OrtCreateSession(r,o,u),s===0&&ke("Can\'t create a session.");let[g,b]=Wc(s),w=[],y=[],_=[];for(let $=0;$$==="gpu-buffer")&&(l=n._OrtCreateBinding(s),l===0&&ke("Can\'t create IO binding."),I={handle:l,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map($=>Cn($))}),yr.set(s,[s,p,h,I]),[s,w,y]}catch(g){throw p.forEach(b=>n._OrtFree(b)),h.forEach(b=>n._OrtFree(b)),l!==0&&n._OrtReleaseBinding(l),s!==0&&n._OrtReleaseSession(s),g}finally{n._free(r),u!==0&&n._OrtReleaseSessionOptions(u),a.forEach(g=>n._free(g)),n.unmountExternalData?.()}},Au=e=>{let t=Ve(),r=yr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,n,s,u]=r;u&&t._OrtReleaseBinding(u.handle),t.jsepUnregisterBuffers?.(e),n.forEach(l=>t._OrtFree(l)),s.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(o),yr.delete(e)},xu=(e,t,r,o,n)=>{if(!e){t.push(0);return}let s=Ve(),u=e[0],l=e[1],a=e[3],p,h;if(u==="string"&&a==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a==="gpu-buffer"){let w=e[2].gpuBuffer,y=cr(_n(u));h=l.reduce((_,I)=>_*I,1)*y,p=s.jsepRegisterBuffer(o,n,w,h)}else{let w=e[2];if(Array.isArray(w)){h=4*w.length,p=s._malloc(h),r.push(p);let y=p/4;for(let _=0;_s.HEAP32[w++]=_);let y=s._OrtCreateTensor(_n(u),p,h,b,l.length,Cn(a));y===0&&ke(`Can\'t create tensor for input/output. session=${o}, index=${n}.`),t.push(y)}finally{s.stackRestore(g)}},Tu=async(e,t,r,o,n,s)=>{let u=Ve(),l=yr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let[a,p,h,g]=l,b=t.length,w=o.length,y=0,_=[],I=[],$=[],x=[],E=u.stackSave(),A=u.stackAlloc(b*4),z=u.stackAlloc(b*4),R=u.stackAlloc(w*4),V=u.stackAlloc(w*4);try{[y,_]=Uo(s);for(let Z=0;ZUe*Me,1);he=Xe(Ge);let ze=g?.outputPreferredLocations[o[Z]];if(he==="string"){if(ze==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ue=[],Me=ye/4;for(let wt=0;wt0){let Ue=u.jsepGetBuffer(ye),Me=cr(Ge);if(Me===void 0||!No(he))throw new Error(`Unsupported data type: ${he}`);Ie=!0,Q.push([he,be,{gpuBuffer:Ue,download:u.jsepCreateDownloader(Ue,et*Me,he),dispose:()=>{u._OrtReleaseTensor(Ee)}},"gpu-buffer"])}else{let Ue=Mr(he),Me=new Ue(et);new Uint8Array(Me.buffer,Me.byteOffset,Me.byteLength).set(u.HEAPU8.subarray(ye,ye+Me.byteLength)),Q.push([he,be,Me,"cpu"])}}finally{u.stackRestore(Pe),he==="string"&&ye&&u._free(ye),Ie||u._OrtReleaseTensor(Ee)}}return g&&u._OrtClearBoundOutputs(g.handle),Q}finally{u.stackRestore(E),I.forEach(T=>u._OrtReleaseTensor(T)),$.forEach(T=>u._OrtReleaseTensor(T)),x.forEach(T=>u._free(T)),y!==0&&u._OrtReleaseRunOptions(y),_.forEach(T=>u._free(T))}},Eu=e=>{let t=Ve(),r=yr.get(e);if(!r)throw new Error("invalid session id");let o=r[0],n=t._OrtEndProfiling(o);n===0&&ke("Can\'t get an profile file name."),t._OrtFree(n)},Ou=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":zo(r.wasm).then(()=>{_u(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;Cu(n,o).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})});break}case"copy-from":{let{buffer:o}=r,n=eo(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=r;Iu(o,n).then(s=>{postMessage({type:t,out:s})},s=>{postMessage({type:t,err:s})});break}case"release":Au(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:s,outputIndices:u,options:l}=r;Tu(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},Ou(a))},a=>{postMessage({type:t,err:a})});break}case"end-profiling":Eu(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'}),pn,Tt,Un,kr,Cr,ls,Ba,xn,Sn,Vd,Tr,xf,Sf,Ef,kf,Cf,Tf,If,Af=X(()=>{Vt(),o0(),Gr(),pn=()=>!!Ne.wasm.proxy&&typeof document<"u",Un=!1,kr=!1,Cr=!1,Ba=new Map,xn=(t,e)=>{let n=Ba.get(t);n?n.push(e):Ba.set(t,[e])},Sn=()=>{if(Un||!kr||Cr||!Tt)throw new Error("worker not ready")},Vd=t=>{switch(t.data.type){case"init-wasm":Un=!1,t.data.err?(Cr=!0,ls[1](t.data.err)):(kr=!0,ls[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}}},Tr=typeof document<"u"?document?.currentScript?.src:void 0,xf=async()=>{if(!kr){if(Un)throw new Error("multiple calls to 'initWasm()' detected.");if(Cr)throw new Error("previous call to 'initWasm()' failed.");if(Un=!0,pn())return Ne.wasm.wasmPaths===void 0&&Tr&&Tr.indexOf("blob:")!==0&&(Ne.wasm.wasmPaths=Tr.substr(0,+Tr.lastIndexOf("/")+1)),new Promise((t,e)=>{Tt?.terminate();let n=URL.createObjectURL(new Blob([l0()],{type:"text/javascript"}));Tt=new Worker(n,{name:"ort-wasm-proxy-worker"}),Tt.onerror=a=>e(a),Tt.onmessage=Vd,URL.revokeObjectURL(n),ls=[t,e];let r={type:"init-wasm",in:Ne};Tt.postMessage(r)});try{await Gc(Ne.wasm),await gf(Ne),kr=!0}catch(t){throw Cr=!0,t}finally{Un=!1}}},Sf=async t=>{if(pn())return Sn(),new Promise((e,n)=>{xn("init-ep",[e,n]);let r={type:"init-ep",in:{epName:t,env:Ne}};Tt.postMessage(r)});await _f(Ne,t)},Ef=async t=>pn()?(Sn(),new Promise((e,n)=>{xn("copy-from",[e,n]);let r={type:"copy-from",in:{buffer:t}};Tt.postMessage(r,[t.buffer])})):Ms(t),kf=async(t,e)=>{if(pn()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sn(),new Promise((n,r)=>{xn("create",[n,r]);let a={type:"create",in:{model:t,options:e}},i=[];t instanceof Uint8Array&&i.push(t.buffer),Tt.postMessage(a,i)})}else return wf(t,e)},Cf=async t=>{if(pn())return Sn(),new Promise((e,n)=>{xn("release",[e,n]);let r={type:"release",in:t};Tt.postMessage(r)});yf(t)},Tf=async(t,e,n,r,a,i)=>{if(pn()){if(n.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 Sn(),new Promise((s,o)=>{xn("run",[s,o]);let l=n,d={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:r,options:i}};Tt.postMessage(d,$f(l))})}else return bf(t,e,n,r,a,i)},If=async t=>{if(pn())return Sn(),new Promise((e,n)=>{xn("end-profiling",[e,n]);let r={type:"end-profiling",in:t};Tt.postMessage(r)});vf(t)}}),us,Gd,Mf,u0=X(()=>{Vt(),Af(),Ye(),jc(),us=(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()}`)}},Gd=t=>{switch(t[3]){case"cpu":return new gt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Qs(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:a}=t[2];return gt.fromGpuBuffer(n,{dataType:e,dims:t[1],download:r,dispose:a})}default:throw new Error(`invalid data location: ${t[3]}`)}},Mf=class{async fetchModelAndCopyToWasmMemory(t){return Ef(await Xa(t))}async loadModel(t,e){Ut();let n;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?n=await Xa(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await kf(n,e),Wt()}async dispose(){return Cf(this.sessionId)}async run(t,e,n){Ut();let r=[],a=[];Object.entries(t).forEach(u=>{let h=u[0],f=u[1],g=this.inputNames.indexOf(h);if(g===-1)throw new Error(`invalid input '${h}'`);r.push(f),a.push(g)});let i=[],s=[];Object.entries(e).forEach(u=>{let h=u[0],f=u[1],g=this.outputNames.indexOf(h);if(g===-1)throw new Error(`invalid output '${h}'`);i.push(f),s.push(g)});let o=r.map((u,h)=>us(u,()=>`input "${this.inputNames[a[h]]}"`)),l=i.map((u,h)=>u?us(u,()=>`output "${this.outputNames[s[h]]}"`):null),d=await Tf(this.sessionId,a,o,s,l,n),c={};for(let u=0;u{Vt(),Af(),u0(),Hd=()=>{if((typeof Ne.wasm.initTimeout!="number"||Ne.wasm.initTimeout<0)&&(Ne.wasm.initTimeout=0),typeof Ne.wasm.simd!="boolean"&&(Ne.wasm.simd=!0),typeof Ne.wasm.proxy!="boolean"&&(Ne.wasm.proxy=!1),typeof Ne.wasm.trace!="boolean"&&(Ne.wasm.trace=!1),typeof Ne.wasm.numThreads!="number"||!Number.isInteger(Ne.wasm.numThreads)||Ne.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Ne.wasm.numThreads=1);let t=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Ne.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Of=class{async init(t){Hd(),await xf(),await Sf(t)}async createInferenceSessionHandler(t,e){let n=new Mf;return await n.loadModel(t,e),Promise.resolve(n)}}}),zf={};er(zf,{wasmBackend:()=>Rf});var Rf,c0=X(()=>{d0(),Rf=new Of});Vt();Vt();Vt();var p0="1.17.1",h0=Bc;{let t=(c0(),Cn(zf)).wasmBackend;jn("webgpu",t,5),jn("cpu",t,10),jn("wasm",t,10)}Object.defineProperty(Ne.versions,"web",{value:p0,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 f0=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Hs},get TRACE(){return Dr},get TRACE_FUNC_BEGIN(){return Ut},get TRACE_FUNC_END(){return Wt},get Tensor(){return gt},get TrainingSession(){return qs},default:h0,get env(){return Ne},get registerBackend(){return jn}},Symbol.toStringTag,{value:"Module"})),m0=(t,e)=>{const n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=t.dims[3],n.height=t.dims[2];const r=n.getContext("2d");if(r!=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,f=c*2,g=-1;s==="RGBA"?(u=0,h=c,f=c*2,g=c*3):s==="RGB"?(u=0,h=c,f=c*2):s==="RBG"&&(u=0,f=c,h=c*2);for(let w=0;w{const n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(n!=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 f=0,g=1,w=2,b=3,y=0,$=u,k=u*2,S=-1;o==="RGBA"?(y=0,$=u,k=u*2,S=u*3):o==="RGB"?(y=0,$=u,k=u*2):o==="RBG"&&(y=0,k=u,$=u*2),r=n.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:n,width:r}=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=n*r,c=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3);let u=4,h=0,f=1,g=2,w=3,b=0,y=d,$=d*2,k=-1;o==="RGB"&&(u=3,h=0,f=1,g=2,w=-1),l==="RGBA"?k=d*3:l==="RBG"?(b=0,$=d,y=d*2):l==="BGR"&&($=0,y=d,b=d*2);for(let T=0;T{const n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,r=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(n){const c=l();c.width=t.width,c.height=t.height;const u=d(c);if(u!=null){let h=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,f=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=f}else o.tensorFormat="RGBA",o.height=h,o.width=f;u.drawImage(t,0,0),s=u.getImageData(0,0,f,h).data}else throw new Error("Can not access image data")}else if(r){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 f=d(h);if(f!=null)f.putImageData(t,0,0),s=f.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,f=t.width;return u.drawImage(t,0,0,f,h),s=u.getImageData(0,0,f,h).data,o.height=h,o.width=f,ds(s,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((c,u)=>{const h=l(),f=d(h);if(!t||!f)return u();const g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{h.width=g.width,h.height=g.height,f.drawImage(g,0,0,h.width,h.height);const w=f.getImageData(0,0,h.width,h.height);o.height=h.height,o.width=h.width,c(ds(w.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return ds(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},w0=(t,e)=>{const{width:n,height:r,download:a,dispose:i}=e,s=[1,r,n,4];return new Xt({location:"texture",type:"float32",texture:t,dims:s,download:a,dispose:i})},y0=(t,e)=>{const{dataType:n,dims:r,download:a,dispose:i}=e;return new Xt({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:a,dispose:i})},b0=(t,e,n)=>new Xt({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]}),ni=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Os=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let qd=!1;const v0=()=>{if(!qd){qd=!0;const t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(ni.set("int64",BigInt64Array),Os.set(BigInt64Array,"int64")),e&&(ni.set("uint64",BigUint64Array),Os.set(BigUint64Array,"uint64"))}},$0=t=>{let e=1;for(let n=0;n{switch(t.location){case"cpu":return new Xt(t.type,t.data,e);case"cpu-pinned":return new Xt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Xt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Xt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let Xt=class{constructor(e,n,r){v0();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=ni.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=r,e==="string"){if(!Array.isArray(n))throw new TypeError("A string tensor's data must be a string array.");o=n}else{const d=ni.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(n)){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(n,BigInt):o=d.from(n)}else if(n instanceof d)o=n;else throw new TypeError(`A ${a} tensor's data must be type of ${d}`)}else if(l=n,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=Os.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=$0(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,n){return _0(e,n)}static fromTexture(e,n){return w0(e,n)}static fromGpuBuffer(e,n){return y0(e,n)}static fromPinnedBuffer(e,n,r){return b0(e,n,r)}toDataURL(e){return m0(this,e)}toImageData(e){return g0(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 n=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=n,e&&this.disposer&&(this.disposer(),this.disposer=void 0),n}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 x0(this,e)}};const S0=Xt,E0=typeof navigator<"u"&&"gpu"in navigator,k0=typeof process<"u"&&process?.release?.name==="node",zr=[];let zs,Fr;k0?(Fr=je??Ng,zr.push("cpu"),zs=["cpu"]):(Fr=f0,E0&&zr.push("webgpu"),zr.push("wasm"),zs=["wasm"]);const C0=Fr.InferenceSession;async function T0(t,e,n=null){let r=zs;if(n)if(zr.includes(n))r=[n];else throw new Error(`Unsupported device: "${n}". Should be one of: ${zr.join(", ")}.`);const a={executionProviders:r,...e};return await C0.create(t,a)}function Bf(t){return t instanceof Fr.Tensor}const Hn=Fr?.env;Hn?.wasm&&(Hn.wasm.wasmPaths=oi?je.join(at.__dirname,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${at.version}/dist/`,Hn.wasm.proxy=!0,typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(Hn.wasm.simd=!1));function I0(){return Hn?.wasm?.proxy}at.backends.onnx=Hn;const jd=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 ee{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 Bf(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new S0(e[0],e[1],e[2]),new Proxy(this,{get:(n,r)=>{if(typeof r=="string"){let a=Number(r);if(Number.isInteger(a))return n._getitem(a)}return n[r]},set:(n,r,a)=>n[r]=a})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...n]=this.dims;if(n.length>0){const r=n.reduce((a,i)=>a*i);for(let a=0;a0){const a=r.reduce((i,s)=>i*s);return this._subarray(e,a,r)}else return new ee(this.type,[this.data[e]],r)}indexOf(e){for(let n=0;nd[1])throw new Error(`Invalid slice: ${d}`);let c=[Math.max(d[0],0),Math.min(d[1],this.dims[l])];r.push(c),n.push(c[1]-c[0])}else throw new Error(`Invalid slice: ${d}`)}let a=r.map(([l,d])=>d-l),i=a.reduce((l,d)=>l*d),s=new this.data.constructor(i);const o=this.stride();for(let l=0;l=0;--c){const h=a[c];d+=(u%h+r[c][0])*o[c],u=Math.floor(u/h)}s[l]=this.data[d]}return new ee(this.type,s,n)}transpose(...e){return Pf(this,e)}sum(e=null,n=!1){return this.norm(1,e,n)}norm(e="fro",n=null,r=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);if(n===null){let s=this.data.reduce((o,l)=>o+l**e,0)**(1/e);return new ee(this.type,[s],[])}n=mn(n,this.dims.length);const a=this.dims.slice();a[n]=1;const i=new this.data.constructor(this.data.length/this.dims[n]);for(let s=0;s=0;--l){const u=this.dims[l];if(l!==n){const h=d%u;o+=h*c,c*=a[l]}d=Math.floor(d/u)}i[o]+=this.data[s]**e}if(e!==1)for(let s=0;s=0;--s){const d=this.dims[s];if(s!==n){const c=o%d;i+=c*l,l*=this.dims[s]}o=Math.floor(o/d)}this.data[a]/=r.data[i]}return this}normalize(e=2,n=1){return this.clone().normalize_(e,n)}stride(){return R0(this.dims)}squeeze(e=null){return new ee(this.type,this.data,Kd(this.dims,e))}squeeze_(e=null){return this.dims=Kd(this.dims,e),this}unsqueeze(e=null){return new ee(this.type,this.data,Yd(this.dims,e))}unsqueeze_(e=null){return this.dims=Yd(this.dims,e),this}flatten_(e=0,n=-1){n=(n+this.dims.length)%this.dims.length;let r=this.dims.slice(0,e),a=this.dims.slice(e,n+1),i=this.dims.slice(n+1);return this.dims=[...r,a.reduce((s,o)=>s*o,1),...i],this}flatten(e=0,n=-1){return this.clone().flatten_(e,n)}view(...e){let n=-1;for(let r=0;rs!==n?a*i:a,1);e[n]=this.data.length/r}return new ee(this.type,this.data,e)}neg_(){for(let e=0;ei*s);if(n!==r)throw Error(`cannot reshape array of size ${n} 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.lengthn!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((n,r)=>n!==1||!e.includes(r))),t}function Yd(t,e){return e=mn(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function mn(t,e,n=null){if(t<-e||t>=e)throw new Error(`IndexError: index ${t} is out of bounds for dimension${n===null?"":" "+n} with size ${e}`);return t<0&&(t=(t%e+e)%e),t}function di(t,e=0){e=mn(e,t[0].dims.length);const n=t[0].dims.slice();n[e]=t.reduce((s,o)=>s+o.dims[e],0);const r=n.reduce((s,o)=>s*o,1),a=new t[0].data.constructor(r),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 w=h%g;u===e&&(w+=s),c+=w*f,f*=n[u],h=Math.floor(h/g)}a[c]=l.data[d]}s+=l.dims[e]}}return new ee(i,a,n)}function ci(t,e=0){return di(t.map(n=>n.unsqueeze(e)),e)}function O0(t,e=null,n=1,r=!1){if(e===null){const d=t.data.reduce((f,g)=>f+g,0)/t.data.length,c=Math.sqrt(t.data.reduce((f,g)=>f+(g-d)**2,0)/(t.data.length-n)),u=new ee(t.type,[d],[]);return[new ee(t.type,[c],[]),u]}e=mn(e,t.dims.length);const a=Df(t,e,r),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 f=t.dims[c];if(c!==e){const g=u%f;d+=g*h,h*=i[c]}u=Math.floor(u/f)}s[d]+=(t.data[l]-a.data[d])**2}for(let l=0;ls+o,0);return new ee(t.type,[i/t.data.length],[])}e=mn(e,t.dims.length);const r=t.dims.slice();r[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*=r[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 R0(t){const e=new Array(t.length);for(let n=t.length-1,r=1;n>=0;--n)e[n]=r,r*=t[n];return e}function B0(t){const e=t.reduce((n,r)=>n*r,1);return new ee("int64",new BigInt64Array(e).fill(1n),t)}function P0(t){return B0(t.dims)}class D0{constructor(e=(n,r)=>n>r){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 n of e)this._heap.push(n),this._siftUp();return this.size}pop(){const e=this.peek(),n=this.size-1;return n>0&&this._swap(0,n),this._heap.pop(),this._siftDown(),e}replace(e){const n=this.peek();return this._heap[0]=e,this._siftDown(),n}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,n){return this._comparator(this._heap[e],this._heap[n])}_swap(e,n){const r=this._heap[e];this._heap[e]=this._heap[n],this._heap[n]=r}_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 Rr(this.bosTokenId,0,0,0,0),i=new Rr(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,n,r,a){const i=this.nodes.length,s=new Rr(a,i,e,n,r);this.beginNodes[e].push(s),this.endNodes[e+n].push(s),this.nodes.push(s)}viterbi(){const e=this.len;let n=0;for(;n<=e;){if(this.beginNodes[n].length==0)return[];for(let o of this.beginNodes[n]){o.prev=null;let l=0,d=null;for(let c of this.endNodes[n]){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[]}++n}const r=[],i=this.beginNodes[e][0].prev;if(i===null)return[];let s=i.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){return this.viterbi().map(n=>this.piece(n))}tokenIds(){return this.viterbi().map(n=>n.tokenId)}}class Rr{constructor(e,n,r,a,i){this.tokenId=e,this.nodeId=n,this.pos=r,this.length=a,this.score=i,this.prev=null,this.backtraceScore=0}clone(){const e=new Rr(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}var L=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"}),Xd=Object.freeze({set:L.Set,for:L.For,in:L.In,is:L.Is,if:L.If,else:L.Else,endif:L.EndIf,elif:L.ElseIf,endfor:L.EndFor,and:L.And,or:L.Or,not:L.Not,"not in":L.NotIn,true:L.BooleanLiteral,false:L.BooleanLiteral}),En=class{constructor(t,e){this.value=t,this.type=e}};function Qd(t){return/\w/.test(t)}function cs(t){return/[0-9]/.test(t)}var L0=[["{%",L.OpenStatement],["%}",L.CloseStatement],["{{",L.OpenExpression],["}}",L.CloseExpression],["(",L.OpenParen],[")",L.CloseParen],["{",L.OpenCurlyBracket],["}",L.CloseCurlyBracket],["[",L.OpenSquareBracket],["]",L.CloseSquareBracket],[",",L.Comma],[".",L.Dot],[":",L.Colon],["|",L.Pipe],["<=",L.ComparisonBinaryOperator],[">=",L.ComparisonBinaryOperator],["==",L.ComparisonBinaryOperator],["!=",L.ComparisonBinaryOperator],["<",L.ComparisonBinaryOperator],[">",L.ComparisonBinaryOperator],["+",L.AdditiveBinaryOperator],["-",L.AdditiveBinaryOperator],["*",L.MultiplicativeBinaryOperator],["/",L.MultiplicativeBinaryOperator],["%",L.MultiplicativeBinaryOperator],["=",L.Equals]],U0=new Map([["n",` -`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function W0(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 V0(t,e={}){const n=[],r=W0(t,e);let a=0;const i=s=>{let o="";for(;s(r[a]);){if(r[a]==="\\"){if(++a,a>=r.length)throw new SyntaxError("Unexpected end of input");const l=r[a++],d=U0.get(l);if(d===void 0)throw new SyntaxError(`Unexpected escaped character: ${l}`);o+=d;continue}if(o+=r[a++],a>=r.length)throw new SyntaxError("Unexpected end of input")}return o};e:for(;a0){n.push(new En(l,L.Text));continue}}i(l=>/\s/.test(l));const o=r[a];if(o==="-"||o==="+"){const l=n.at(-1)?.type;if(l===L.Text||l===void 0)throw new SyntaxError(`Unexpected character: ${o}`);switch(l){case L.Identifier:case L.NumericLiteral:case L.BooleanLiteral:case L.StringLiteral:case L.CloseParen:case L.CloseSquareBracket:break;default:{++a;const d=i(cs);n.push(new En(`${o}${d}`,d.length>0?L.NumericLiteral:L.UnaryOperator));continue}}}for(const[l,d]of L0)if(r.slice(a,a+l.length)===l){n.push(new En(l,d)),a+=l.length;continue e}if(o==="'"||o==='"'){++a;const l=i(d=>d!==o);n.push(new En(l,L.StringLiteral)),++a;continue}if(cs(o)){const l=i(cs);n.push(new En(l,L.NumericLiteral));continue}if(Qd(o)){const l=i(Qd),d=Object.hasOwn(Xd,l)?Xd[l]:L.Identifier;d===L.In&&n.at(-1)?.type===L.Not?(n.pop(),n.push(new En("not in",L.NotIn))):n.push(new En(l,d));continue}throw new SyntaxError(`Unexpected character: ${o}`)}return n}var qr=class{type="Statement"},G0=class extends qr{constructor(t){super(),this.body=t}type="Program"},Zd=class extends qr{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n}type="If"},H0=class extends qr{constructor(t,e,n){super(),this.loopvar=t,this.iterable=e,this.body=n}type="For"},q0=class extends qr{constructor(t,e){super(),this.assignee=t,this.value=e}type="Set"},Zt=class extends qr{type="Expression"},j0=class extends Zt{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n}type="MemberExpression"},K0=class extends Zt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Wn=class extends Zt{constructor(t){super(),this.value=t}type="Identifier"},jr=class extends Zt{constructor(t){super(),this.value=t}type="Literal"},Y0=class extends jr{type="NumericLiteral"},Jd=class extends jr{type="StringLiteral"},ec=class extends jr{type="BooleanLiteral"},X0=class extends jr{type="ArrayLiteral"},Q0=class extends jr{type="ObjectLiteral"},Ir=class extends Zt{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n}type="BinaryExpression"},Z0=class extends Zt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},J0=class extends Zt{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n}type="TestExpression"},ew=class extends Zt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},tw=class extends Zt{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n}type="SliceExpression"},nw=class extends Zt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"};function rw(t){const e=new G0([]);let n=0;function r(O,R){const H=t[n++];if(!H||H.type!==O)throw new Error(`Parser Error: ${R}. ${H.type} !== ${O}.`);return H}function a(){switch(t[n].type){case L.Text:return o();case L.OpenStatement:return l();case L.OpenExpression:return d();default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}}function i(...O){return n+O.length<=t.length&&O.some((R,H)=>R!==t[n+H].type)}function s(...O){return n+O.length<=t.length&&O.every((R,H)=>R===t[n+H].type)}function o(){return new Jd(r(L.Text,"Expected text token").value)}function l(){r(L.OpenStatement,"Expected opening statement token");let O;switch(t[n].type){case L.Set:++n,O=c(),r(L.CloseStatement,"Expected closing statement token");break;case L.If:++n,O=u(),r(L.OpenStatement,"Expected {% token"),r(L.EndIf,"Expected endif token"),r(L.CloseStatement,"Expected %} token");break;case L.For:++n,O=h(),r(L.OpenStatement,"Expected {% token"),r(L.EndFor,"Expected endfor token"),r(L.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type}`)}return O}function d(){r(L.OpenExpression,"Expected opening expression token");const O=f();return r(L.CloseExpression,"Expected closing expression token"),O}function c(){const O=f();if(s(L.Equals)){++n;const R=c();return new q0(O,R)}return O}function u(){const O=f();r(L.CloseStatement,"Expected closing statement token");const R=[],H=[];for(;!(t[n]?.type===L.OpenStatement&&(t[n+1]?.type===L.ElseIf||t[n+1]?.type===L.Else||t[n+1]?.type===L.EndIf));)R.push(a());if(t[n]?.type===L.OpenStatement&&t[n+1]?.type!==L.EndIf)if(++n,s(L.ElseIf))r(L.ElseIf,"Expected elseif token"),H.push(u());else for(r(L.Else,"Expected else token"),r(L.CloseStatement,"Expected closing statement token");!(t[n]?.type===L.OpenStatement&&t[n+1]?.type===L.EndIf);)H.push(a());return new Zd(O,R,H)}function h(){const O=G();if(!(O instanceof Wn))throw new SyntaxError("Expected identifier for the loop variable");r(L.In,"Expected `in` keyword following loop variable");const R=f();r(L.CloseStatement,"Expected closing statement token");const H=[];for(;i(L.OpenStatement,L.EndFor);)H.push(a());return new H0(O,R,H)}function f(){const O=g();if(s(L.If)){++n;const R=g();r(L.Else,"Expected else token");const H=g();return new Zd(R,[O],[H])}return O}function g(){let O=w();for(;s(L.Or);){const R=t[n];++n;const H=w();O=new Ir(R,O,H)}return O}function w(){let O=b();for(;s(L.And);){const R=t[n];++n;const H=b();O=new Ir(R,O,H)}return O}function b(){let O;for(;s(L.Not);){const R=t[n];++n;const H=b();O=new ew(R,H)}return O??y()}function y(){let O=$();for(;s(L.ComparisonBinaryOperator)||s(L.In)||s(L.NotIn);){const R=t[n];++n;const H=$();O=new Ir(R,O,H)}return O}function $(){let O=V();for(;s(L.AdditiveBinaryOperator);){const R=t[n];++n;const H=V();O=new Ir(R,O,H)}return O}function k(){const O=N();return s(L.OpenParen)?S(O):O}function S(O){let R=new K0(O,T());return s(L.OpenParen)&&(R=S(R)),R}function T(){r(L.OpenParen,"Expected opening parenthesis for arguments list");const O=A();return r(L.CloseParen,"Expected closing parenthesis for arguments list"),O}function A(){const O=[];for(;!s(L.CloseParen);){let R=f();if(s(L.Equals)){if(++n,!(R instanceof Wn))throw new SyntaxError("Expected identifier for keyword argument");const H=f();R=new nw(R,H)}O.push(R),s(L.Comma)&&++n}return O}function P(){const O=[];let R=!1;for(;!s(L.CloseSquareBracket);)s(L.Colon)?(O.push(void 0),++n,R=!0):(O.push(f()),s(L.Colon)&&(++n,R=!0));if(O.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(R){if(O.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new tw(...O)}return O[0]}function N(){let O=G();for(;s(L.Dot)||s(L.OpenSquareBracket);){const R=t[n];++n;let H;const te=R.type!==L.Dot;if(te)H=P(),r(L.CloseSquareBracket,"Expected closing square bracket");else if(H=G(),H.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");O=new j0(O,H,te)}return O}function V(){let O=j();for(;s(L.MultiplicativeBinaryOperator);){const R=t[n];++n;const H=j();O=new Ir(R,O,H)}return O}function j(){let O=M();for(;s(L.Is);){++n;const R=s(L.Not);R&&++n;let H=G();if(H instanceof ec&&(H=new Wn(H.value.toString())),!(H instanceof Wn))throw new SyntaxError("Expected identifier for the test");O=new J0(O,R,H)}return O}function M(){let O=k();for(;s(L.Pipe);){++n;let R=G();if(!(R instanceof Wn))throw new SyntaxError("Expected identifier for the filter");s(L.OpenParen)&&(R=S(R)),O=new Z0(O,R)}return O}function G(){const O=t[n];switch(O.type){case L.NumericLiteral:return++n,new Y0(Number(O.value));case L.StringLiteral:return++n,new Jd(O.value);case L.BooleanLiteral:return++n,new ec(O.value==="true");case L.Identifier:return++n,new Wn(O.value);case L.OpenParen:{++n;const R=f();if(t[n].type!==L.CloseParen)throw new SyntaxError("Expected closing parenthesis");return++n,R}case L.OpenSquareBracket:{++n;const R=[];for(;!s(L.CloseSquareBracket);)R.push(f()),s(L.Comma)&&++n;return++n,new X0(R)}case L.OpenCurlyBracket:{++n;const R=new Map;for(;!s(L.CloseCurlyBracket);){const H=f();r(L.Colon,"Expected colon between key and value in object literal");const te=f();R.set(H,te),s(L.Comma)&&++n}return++n,new Q0(R)}default:throw new SyntaxError(`Unexpected token: ${O.type}`)}}for(;n=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),n=(n??=t.length)<0?Math.max(t.length+n,0):Math.min(n,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),n=(n??=-1)<-1?Math.max(t.length+n,-1):Math.min(n,t.length-1));const i=[];for(let s=e;a*se.toUpperCase())}var an=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new Qe(!!this.value)}},Ge=class extends an{type="NumericValue"},Re=class extends an{type="StringValue";builtins=new Map([["upper",new gn(()=>new Re(this.value.toUpperCase()))],["lower",new gn(()=>new Re(this.value.toLowerCase()))],["strip",new gn(()=>new Re(this.value.trim()))],["title",new gn(()=>new Re(Nf(this.value)))],["length",new Ge(this.value.length)]])},Qe=class extends an{type="BooleanValue"},Kt=class extends an{type="ObjectValue";__bool__(){return new Qe(this.value.size>0)}builtins=new Map([["get",new gn(([t,e])=>{if(!(t instanceof Re))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Br})]])},ut=class extends an{type="ArrayValue";builtins=new Map([["length",new Ge(this.value.length)]]);__bool__(){return new Qe(this.value.length>0)}},gn=class extends an{type="FunctionValue"},Br=class extends an{type="NullValue"},Ft=class extends an{type="UndefinedValue"},Rs=class{constructor(t){this.parent=t}variables=new Map([["namespace",new gn(t=>{if(t.length===0)return new Kt(new Map);if(t.length!==1||!(t[0]instanceof Kt))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 gn],["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 ut||t instanceof Re],["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,Wa(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 Ft}catch{return new Ft}}},iw=class{global;constructor(t){this.global=t??new Rs}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const n=this.evaluate(t.left,e);switch(t.operator.value){case"and":return n.__bool__().value?this.evaluate(t.right,e):n;case"or":return n.__bool__().value?n:this.evaluate(t.right,e)}const r=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new Qe(n.value==r.value);case"!=":return new Qe(n.value!=r.value)}if(n instanceof Ft||r instanceof Ft)throw new Error("Cannot perform operation on undefined values");if(n instanceof Br||r instanceof Br)throw new Error("Cannot perform operation on null values");if(n instanceof Ge&&r instanceof Ge)switch(t.operator.value){case"+":return new Ge(n.value+r.value);case"-":return new Ge(n.value-r.value);case"*":return new Ge(n.value*r.value);case"/":return new Ge(n.value/r.value);case"%":return new Ge(n.value%r.value);case"<":return new Qe(n.value":return new Qe(n.value>r.value);case">=":return new Qe(n.value>=r.value);case"<=":return new Qe(n.value<=r.value)}else if(n instanceof ut&&r instanceof ut)switch(t.operator.value){case"+":return new ut(n.value.concat(r.value))}else if(r instanceof ut){const a=r.value.find(i=>i.value===n.value)!==void 0;switch(t.operator.value){case"in":return new Qe(a);case"not in":return new Qe(!a)}}if(n instanceof Re||r instanceof Re)switch(t.operator.value){case"+":return new Re(n.value.toString()+r.value.toString())}if(n instanceof Re&&r instanceof Re)switch(t.operator.value){case"in":return new Qe(r.value.includes(n.value));case"not in":return new Qe(!r.value.includes(n.value))}if(n instanceof Re&&r instanceof Kt)switch(t.operator.value){case"in":return new Qe(r.value.has(n.value));case"not in":return new Qe(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if(t.filter.type==="Identifier"){const r=t.filter;if(n instanceof ut)switch(r.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new Ge(n.value.length);case"reverse":return new ut(n.value.reverse());case"sort":return new ut(n.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: ${r.value}`)}else if(n instanceof Re)switch(r.value){case"length":return new Ge(n.value.length);case"upper":return new Re(n.value.toUpperCase());case"lower":return new Re(n.value.toLowerCase());case"title":return new Re(Nf(n.value));case"capitalize":return new Re(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new Re(n.value.trim());default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else if(n instanceof Ge)switch(r.value){case"abs":return new Ge(Math.abs(n.value));default:throw new Error(`Unknown NumericValue filter: ${r.value}`)}throw new Error(`Cannot apply filter "${r.value}" to type: ${n.type}`)}else if(t.filter.type==="CallExpression"){const r=t.filter;if(r.callee.type!=="Identifier")throw new Error(`Unknown filter: ${r.callee.type}`);const a=r.callee.value;if(n instanceof ut){switch(a){case"selectattr":{if(n.value.some(c=>!(c instanceof Kt)))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some(c=>c.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[i,s,o]=r.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=n.value.filter(c=>{const u=c.value.get(i.value);return u?l(u,o):!1});return new ut(d)}}throw new Error(`Unknown ArrayValue filter: ${a}`)}else throw new Error(`Cannot apply filter "${a}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const n=this.evaluate(t.operand,e),r=e.tests.get(t.test.value);if(!r)throw new Error(`Unknown test: ${t.test.value}`);const a=r(n);return new Qe(t.negate?!a:a)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);switch(t.operator.value){case"not":return new Qe(!n.value);default:throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const a=this.evaluate(r,e);a.type!=="NullValue"&&a.type!=="UndefinedValue"&&(n+=a.value)}return new Re(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const n=[],r=new Map;for(const i of t.args)if(i.type==="KeywordArgumentExpression"){const s=i;r.set(s.key.value,this.evaluate(s.value,e))}else n.push(this.evaluate(i,e));r.size>0&&n.push(new Kt(r));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(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof ut||t instanceof Re))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),a=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof Ge||r instanceof Ft))throw new Error("Slice start must be numeric or undefined");if(!(a instanceof Ge||a instanceof Ft))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof Ge||i instanceof Ft))throw new Error("Slice step must be numeric or undefined");return t instanceof ut?new ut(tc(t.value,r.value,a.value,i.value)):new Re(tc(Array.from(t.value),r.value,a.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new Re(t.property.value);let a;if(n instanceof Kt){if(!(r instanceof Re))throw new Error(`Cannot access property with non-string: got ${r.type}`);a=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof ut||n instanceof Re)if(r instanceof Ge)a=n.value.at(r.value),n instanceof Re&&(a=new Re(n.value.at(r.value)));else if(r instanceof Re)a=n.builtins.get(r.value);else throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof Re))throw new Error(`Cannot access property with non-string: got ${r.type}`);a=n.builtins.get(r.value)}return a instanceof an?a:new Ft}evaluateSet(t,e){const n=this.evaluate(t.value,e);if(t.assignee.type==="Identifier"){const r=t.assignee.value;e.setVariable(r,n)}else if(t.assignee.type==="MemberExpression"){const r=t.assignee,a=this.evaluate(r.object,e);if(!(a instanceof Kt))throw new Error("Cannot assign to member of non-object");if(r.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");a.value.set(r.property.value,n)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new Br}evaluateIf(t,e){const n=this.evaluate(t.test,e);return this.evaluateBlock(n.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const n=new Rs(e),r=this.evaluate(t.iterable,n);if(!(r instanceof ut))throw new Error(`Expected iterable type in for loop: got ${r.type}`);let a="";for(let i=0;i0?r.value[i-1]:new Ft],["nextitem",ithis.evaluate(n,e)));case"ObjectLiteral":{const n=new Map;for(const[r,a]of t.value){const i=this.evaluate(r,e);if(!(i instanceof Re))throw new Error(`Object keys must be strings: got ${i.type}`);n.set(i.value,this.evaluate(a,e))}return new Kt(n)}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 Wa(t){switch(typeof t){case"number":return new Ge(t);case"string":return new Re(t);case"boolean":return new Qe(t);case"object":return t===null?new Br:Array.isArray(t)?new ut(t.map(Wa)):new Kt(new Map(Object.entries(t).map(([e,n])=>[e,Wa(n)])));case"function":return new gn((e,n)=>{const r=t(...e.map(a=>a.value))??null;return Wa(r)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var sw=class{parsed;constructor(t){const e=V0(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=rw(e)}render(t){const e=new Rs;e.set("false",!1),e.set("true",!0),e.set("raise_exception",a=>{throw new Error(a)}),e.set("range",aw);for(const[a,i]of Object.entries(t))e.set(a,i);return new iw(e).run(this.parsed).value}};async function Ff(t,e){const n=await Promise.all([Yn(t,"tokenizer.json",!0,e),Yn(t,"tokenizer_config.json",!0,e)]);return e.legacy!==null&&(n[1].legacy=e.legacy),n}function ow(t,e){const n=[];let r=0;for(const a of t.matchAll(e)){const i=a[0];r0&&n.push(i),r=a.index+i.length}return rthis.tokens_to_ids.get(n)??this.unk_token_id)}convert_ids_to_tokens(e){return e.map(n=>this.vocab[n]??this.unk_token)}}class hw extends Kr{constructor(e){super(e),this.tokens_to_ids=lo(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[n,r]of this.tokens_to_ids)this.vocab[r]=n}encode(e){const n=[];for(const r of e){const a=[...r];if(a.length>this.max_input_chars_per_word){n.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?n.push(this.unk_token):n.push(...o)}return n}}class fw extends Kr{constructor(e,n){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let a=0;a[a,i])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=n.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=gc(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new N0,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const n=e.sentence,r=n.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 n=0;for(let a=0;a<256;++a)t.includes(a)||(t.push(a),e.push(256+n),n+=1);const r=e.map(a=>String.fromCharCode(a));return Object.fromEntries(t.map((a,i)=>[a,r[i]]))})(),mw=Rg(Wf);class gw extends Kr{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=lo(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[n,r]of this.tokens_to_ids)this.vocab[r]=n;this.bpe_ranks=new Map(e.merges.map((n,r)=>[n,r])),this.merges=e.merges.map(n=>n.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 n=this.cache.get(e);if(n!==void 0)return n;const r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let a=[];if(r.length>1){const i=new D0((l,d)=>l.score`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`)):n.push(this.unk_token)}return n}}class _w extends Kr{constructor(e,n){super(e),this.tokens_to_ids=lo(n.target_lang?e.vocab[n.target_lang]:e.vocab),this.bos_token=n.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=n.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=n.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=n.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[r,a]of this.tokens_to_ids)this.vocab[a]=r}encode(e){return e}}class xt extends Et{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new Cw(e);case"Precompiled":return new qw(e);case"Sequence":return new kw(e);case"Replace":return new ww(e);case"NFC":return new yw(e);case"NFKC":return new bw(e);case"NFKD":return new vw(e);case"Strip":return new $w(e);case"StripAccents":return new xw(e);case"Lowercase":return new Sw(e);case"Prepend":return new Ew(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 ww extends xt{normalize(e){const n=pi(this.config.pattern);return n===null?e:e.replaceAll(n,this.config.content)}}class yw extends xt{normalize(e){return e=e.normalize("NFC"),e}}class bw extends xt{normalize(e){return e=e.normalize("NFKC"),e}}class vw extends xt{normalize(e){return e=e.normalize("NFKD"),e}}class $w extends xt{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 xw extends xt{normalize(e){return e=Uf(e),e}}class Sw extends xt{normalize(e){return e=e.toLowerCase(),e}}class Ew extends xt{normalize(e){return e=this.config.prepend+e,e}}class kw extends xt{constructor(e){super(e),this.normalizers=e.normalizers.map(n=>xt.fromConfig(n))}normalize(e){return this.normalizers.reduce((n,r)=>r.normalize(n),e)}}class Cw extends xt{_tokenize_chinese_chars(e){const n=[];for(let r=0;r=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 n=[];for(const r of e){const a=r.charCodeAt(0);a===0||a===65533||this._is_control(r)||(/^\s$/.test(r)?n.push(" "):n.push(r))}return n.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 Mt extends Et{static fromConfig(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new Tw(e);case"Sequence":return new jw(e);case"Whitespace":return new Kw(e);case"WhitespaceSplit":return new Yw(e);case"Metaspace":return new Hf(e);case"ByteLevel":return new Iw(e);case"Split":return new Aw(e);case"Punctuation":return new Mw(e);case"Digits":return new Ow(e);case"Replace":return new Xw(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e,n){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e,n){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,n)):this.pre_tokenize_text(e,n)).flat()}_call(e,n){return this.pre_tokenize(e,n)}}class Tw extends Mt{constructor(e){super(),this.pattern=new RegExp(`[^\\s${Ur}]+|[${Ur}]`,"gu")}pre_tokenize_text(e,n){return e.trim().match(this.pattern)||[]}}class Iw extends Mt{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=Wf,this.text_encoder=new TextEncoder}pre_tokenize_text(e,n){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 Aw extends Mt{constructor(e){super(),this.config=e,this.pattern=pi(this.config.pattern,this.config.invert)}pre_tokenize_text(e,n){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:ow(e,this.pattern)}}class Mw extends Mt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Ur}]+|[${Ur}]+`,"gu")}pre_tokenize_text(e,n){return e.match(this.pattern)||[]}}class Ow extends Mt{constructor(e){super(),this.config=e;const n=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(n,"gu")}pre_tokenize_text(e,n){return e.match(this.pattern)||[]}}class hi extends Et{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new zw(e);case"ByteLevel":return new Rw(e);case"RobertaProcessing":return new Gf(e);case"BertProcessing":return new Vf(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...n){throw Error("post_process should be implemented in subclass.")}_call(e,...n){return this.post_process(e,...n)}}class Vf extends hi{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,n=null,{add_special_tokens:r=!0}={}){r&&(e=dt([this.cls],e,[this.sep]));let a=new Array(e.length).fill(0);if(n!==null){const i=r&&this instanceof Gf?[this.sep]:[],s=r?[this.sep]:[];e=dt(e,i,n,s),a=dt(a,new Array(n.length+i.length+s.length).fill(1))}return{tokens:e,token_type_ids:a}}}class Gf extends Vf{}class zw extends hi{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,n=null,{add_special_tokens:r=!0}={}){const a=n===null?this.single:this.pair;let i=[],s=[];for(const o of a)"SpecialToken"in o?r&&(i.push(o.SpecialToken.id),s.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(i=dt(i,e),s=dt(s,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(i=dt(i,n),s=dt(s,new Array(n.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:s}}}class Rw extends hi{post_process(e,n=null){return n&&(e=dt(e,n)),{tokens:e}}}class St extends Et{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 Fw(e);case"Metaspace":return new Hw(e);case"ByteLevel":return new Lw(e);case"Replace":return new Bw(e);case"ByteFallback":return new Pw(e);case"Fuse":return new Dw(e);case"Strip":return new Nw(e);case"Sequence":return new Ww(e);case"CTC":return new Uw(e);case"BPEDecoder":return new Vw(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 Bw extends St{decode_chain(e){const n=pi(this.config.pattern);return n===null?e:e.map(r=>r.replaceAll(n,this.config.content))}}class Pw extends St{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const n=[];let r=[];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)r.push(i);else{if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));n.push(s),r=[]}n.push(a)}}if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));n.push(a),r=[]}return n}}class Dw extends St{decode_chain(e){return[e.join("")]}}class Nw extends St{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(n=>{let r=0;for(let i=0;i(r!==0&&(n.startsWith(this.config.prefix)?n=n.replace(this.config.prefix,""):n=" "+n),this.cleanup&&(n=uo(n)),n))}}class Lw extends St{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 n=e.join(""),r=new Uint8Array([...n].map(i=>this.byte_decoder[i]));return this.text_decoder.decode(r)}decode_chain(e){const n=[];let r=[];for(const a of e)this.added_tokens.find(i=>i.content===a)!==void 0?(r.length>0&&(n.push(this.convert_tokens_to_string(r)),r=[]),n.push(a)):r.push(a);return r.length>0&&n.push(this.convert_tokens_to_string(r)),n}}class Uw extends St{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 n=[e[0]];for(let i=1;ii!==this.pad_token).join("");return this.cleanup&&(a=uo(a).replaceAll(this.word_delimiter_token," ").trim()),a}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class Ww extends St{constructor(e){super(e),this.decoders=e.decoders.map(n=>St.fromConfig(n))}decode_chain(e){return this.decoders.reduce((n,r)=>r.decode_chain(n),e)}}class Vw extends St{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map((n,r)=>n.replaceAll(this.suffix,r===e.length-1?"":" "))}}class Gw extends St{decode_chain(e){let n="";for(let r=1;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}}class jw extends Mt{constructor(e){super(),this.tokenizers=e.pretokenizers.map(n=>Mt.fromConfig(n))}pre_tokenize_text(e,n){return this.tokenizers.reduce((r,a)=>a.pre_tokenize(r,n),[e])}}class Kw extends Mt{constructor(e){super()}pre_tokenize_text(e,n){return e.match(/\w+|[^\w\s]+/g)||[]}}class Yw extends Mt{constructor(e){super()}pre_tokenize_text(e,n){return dw(e)}}class Xw extends Mt{constructor(e){super(),this.config=e,this.pattern=pi(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,n){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const Qw=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Zw(t,e,n,r){for(const a of Object.keys(t)){const i=e-t[a].length,s=n(a),o=new Array(i).fill(s);t[a]=r==="right"?dt(t[a],o):dt(o,t[a])}}function Jw(t,e){for(const n of Object.keys(t))t[n].length=e}class Ee extends Et{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 %}`;constructor(e,n){super(),this._tokenizer_config=n,this.normalizer=xt.fromConfig(e.normalizer),this.pre_tokenizer=Mt.fromConfig(e.pre_tokenizer),this.model=Kr.fromConfig(e.model,n),this.post_processor=hi.fromConfig(e.post_processor),this.decoder=St.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const r of e.added_tokens){const a=new pw(r);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))}this.additional_special_tokens=n.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(r=>`${r.lstrip?"\\s*":""}(${pc(r.content)})${r.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=n.model_max_length,this.remove_space=n.remove_space,this.clean_up_tokenization_spaces=n.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=n.do_lowercase_and_remove_accent??!1,this.padding_side="right",this.legacy=!1,this.chat_template=n.chat_template??null,this._compiled_template_cache=new Map}getToken(...e){for(const n of e){const r=this._tokenizer_config[n];if(r)if(typeof r=="object"){if(r.__type==="AddedToken")return r.content;throw Error(`Unknown token: ${r}`)}else return r}return null}static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main",legacy:o=null}={}){const l=await Ff(e,{progress_callback:n,config:r,cache_dir:a,local_files_only:i,revision:s,legacy:o});return new this(...l)}_call(e,{text_pair:n=null,add_special_tokens:r=!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(n!==null){if(Array.isArray(n)){if(e.length!==n.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,n[h],{add_special_tokens:r}))}else d=e.map(u=>this._encode_plus(u,null,{add_special_tokens:r}))}else{if(e===null)throw Error("text may not be null");if(Array.isArray(n))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,n,{add_special_tokens:r})]}if(s===null?a==="max_length"?s=this.model_max_length:s=Ot(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&&Jw(d[u],s):a&&Zw(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 f of Object.keys(h))if(h[f].length!==d[0][f]?.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 ee("int64",BigInt64Array.from(d.flatMap(f=>f[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=lw(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,n=null,{add_special_tokens:r=!0}={}){const a=this._encode_text(e),i=this._encode_text(n),s=this.post_processor?this.post_processor(a,i,{add_special_tokens:r}):{tokens:dt(a??[],i??[])},o=this.model.convert_tokens_to_ids(s.tokens),l={input_ids:o,attention_mask:new Array(o.length).fill(1)};return this.return_token_type_ids&&s.token_type_ids&&(l.token_type_ids=s.token_type_ids),l}encode(e,n=null,{add_special_tokens:r=!0}={}){const{input_ids:a}=this._encode_plus(e,n,{add_special_tokens:r});return a}batch_decode(e,n={}){return e instanceof ee&&(e=e.tolist()),e.map(r=>this.decode(r,n))}decode(e,n={}){if(e instanceof ee&&(e=Lf(e)),!Array.isArray(e)||e.length===0||!hc(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,n)}decode_single(e,{skip_special_tokens:n=!1,clean_up_tokenization_spaces:r=null}){let a=this.model.convert_ids_to_tokens(e);n&&(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," "),n&&(i=i.trim())),(r??this.clean_up_tokenization_spaces)&&(i=uo(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:n=null,add_generation_prompt:r=!1,tokenize:a=!0,padding:i=!1,truncation:s=!1,max_length:o=null,return_tensor:l=!0}={}){n??=this.chat_template??this.default_chat_template;let d=this._compiled_template_cache.get(n);d===void 0&&(d=new sw(n),this._compiled_template_cache.set(n,d));const c=Object.create(null);for(const h of Qw){const f=this.getToken(h);f&&(c[h]=f)}const u=d.render({messages:e,add_generation_prompt:r,...c});return a?this._call(u,{add_special_tokens:!1,padding:i,truncation:s,max_length:o,return_tensor:l}).input_ids:u}}class ey extends Ee{return_token_type_ids=!0}class ty extends Ee{return_token_type_ids=!0}class ny extends Ee{return_token_type_ids=!0}class ry extends Ee{return_token_type_ids=!0}class ay extends Ee{return_token_type_ids=!0}class iy extends Ee{return_token_type_ids=!0}class sy extends Ee{return_token_type_ids=!0}class oy extends Ee{return_token_type_ids=!0}class ly extends Ee{return_token_type_ids=!0}class uy extends Ee{}class dy extends Ee{}class cy extends Ee{return_token_type_ids=!0;constructor(e,n){super(e,n),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class py extends Ee{return_token_type_ids=!0}class hy extends Ee{}class qf extends Ee{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}'}class fy extends Ee{}class jf extends Ee{constructor(e,n){super(e,n),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,n,r){return co(this,e,n,r)}}class my extends jf{}class gy extends Ee{}class _y extends qf{constructor(e,n){const r=".,!?…。,、।۔،",a=e.pre_tokenizer?.pretokenizers[0]?.pattern;a&&a.Regex===` ?[^(\\s|[${r}])]+`&&(a.Regex=` ?[^\\s${r}]+`),super(e,n)}}const Pa="▁";class Kf extends Ee{_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.`;constructor(e,n){super(e,n),this.use_default_system_prompt=n.use_default_system_prompt??!1,this.legacy=n.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Hf({replacement:Pa,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 n=super._encode_text(Pa+e.replaceAll(Pa," "));return n.length>1&&n[0]===Pa&&this.special_tokens.includes(n[1])&&(n=n.slice(1)),n}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 wy extends Kf{}class yy extends Ee{}class by extends Ee{}class vy extends Ee{}class $y extends Ee{}class xy extends Ee{}class Sy extends Ee{}class Ey extends Ee{_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 %}`}function co(t,e,n,r){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=r.src_lang,i=r.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 r.forced_bos_token_id=t.model.convert_tokens_to_ids([t.lang_to_token(i)])[0],t._call(e,n)}class ky extends Ee{constructor(e,n){super(e,n),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,n,r){return co(this,e,n,r)}}class Cy extends Ee{constructor(e,n){super(e,n),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,n,r){return co(this,e,n,r)}}const Yf=[["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"]],Da=new Map(Yf),Ty=new Map([...Yf.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 Iy extends Ee{_default_chat_template='{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}';_decode_asr(e,{return_timestamps:n=!1,return_language:r=!1,time_precision:a=null,force_full_sequences:i=!0}={}){if(a===null)throw Error("Must specify time_precision");let s=null;const o=n==="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 f=[],g=[],w=!1,b=null;const y=new Set(this.all_special_ids);for(const S of e){const T=S.tokens,A=o?S.token_timestamps:null;let P=null,N=h;if("stride"in S){const[M,G,O]=S.stride;if(u-=G,b=M-O,G&&(N=G/a+h),O)for(let R=T.length-1;R>=0;--R){const H=T[R];if(H>=h){if(P!==null&&(H-h)*a=h){const O=(G-h)*a+u,R=Ar(O,2);if(P!==null&&G>=P)w=!0;else if(w||f.length>0&&G0?(f.push(V),o&&g.push(j)):f.every(M=>M.length===0)&&(c=l(),f=[],V=[],g=[],j=[])}if(f.length>0){if(i&&n)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[S,T]=this.findLongestCommonSequence(f,g),A=this.decode(S);c.text=A,o&&(c.words=this.collateWordTimestamps(S,T,s)),d.push(c)}let $=Object.create(null);const k=d.map(S=>S.text).join("");if(n||r){for(let S=0;S0;let o=s?[]:null,l=s?n[0]:null;for(let d=1;dR===M[H]).length,O=G/S+T;G>1&&O>u&&(u=O,h=[A,P,V,j])}const[g,w,b,y]=h,$=Math.floor((w+g)/2),k=Math.floor((y+b)/2);i.push(...r.slice(0,$)),r=c.slice(k),a=r.length,s&&(o.push(...l.slice(0,$)),l=n[d].slice(k))}return i.push(...r),s?(o.push(...l),[i,o]):[i,[]]}collateWordTimestamps(e,n,r){const[a,i,s]=this.combineTokensIntoWords(e,r),o=[];for(let l=0;l=a){const o=Ar((s-a)*r,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,n)),i.join("")}splitTokensOnUnicode(e){const n=this.decode(e,{decode_with_timestamps:!0}),r="�",a=[],i=[],s=[];let o=[],l=[],d=0;for(let c=0;c=this.model.tokens_to_ids.get("<|endoftext|>"),g=c.startsWith(" "),w=c.trim(),b=l.test(w);if(f||g||b||i.length===0)i.push(c),s.push(u),o.push(h);else{const y=i.length-1;i[y]+=c,s[y].push(...u),o[y].push(...h)}}return[i,s,o]}mergePunctuations(e,n,r,a,i){const s=structuredClone(e),o=structuredClone(n),l=structuredClone(r);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]=dt(o[d],o[c]),l[c]=dt(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:n=null,no_timestamps:r=!0}={}){const a=[];if(e){e=e.toLowerCase();let i=Ty.get(e);if(i===void 0)if(Da.has(e))i=e;else{const l=e.length===2?Da.keys():Da.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(n){if(n=n.toLowerCase(),n!=="transcribe"&&n!=="translate")throw new Error(`Task "${n}" is not supported. Must be one of: ["transcribe", "translate"]`);const i=this.model.tokens_to_ids.get(`<|${n}|>`);if(i===void 0)throw new Error(`Unable to find task "${n}" 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(r){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 Ay extends Ee{}class My extends Ee{}class Oy extends Ee{}class zy extends Ee{constructor(e,n){super(e,n),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(r=>this.languageRegex.test(r)),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[n,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(n);if(r.length===2){const[a,i]=r;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)}`),dt([a],super._encode_text(i))}}}class Ry extends Ee{}class Xf extends Ee{_default_chat_template="{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}"}class By extends Xf{}class Py extends Ee{}class Dy extends Ee{}class Ny extends Ee{constructor(e,n){super(e,n),this.decoder=new Gw({})}}class lt{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:hy,DistilBertTokenizer:uy,CamembertTokenizer:dy,DebertaTokenizer:ay,DebertaV2Tokenizer:iy,BertTokenizer:ey,HerbertTokenizer:sy,ConvBertTokenizer:oy,RoFormerTokenizer:ly,XLMTokenizer:cy,ElectraTokenizer:py,MobileBertTokenizer:ny,SqueezeBertTokenizer:ry,AlbertTokenizer:ty,GPT2Tokenizer:qf,BartTokenizer:fy,MBartTokenizer:jf,MBart50Tokenizer:my,RobertaTokenizer:gy,WhisperTokenizer:Iy,CodeGenTokenizer:Ay,CLIPTokenizer:My,SiglipTokenizer:Oy,MarianTokenizer:zy,BloomTokenizer:_y,NllbTokenizer:ky,M2M100Tokenizer:Cy,LlamaTokenizer:Kf,CodeLlamaTokenizer:wy,XLMRobertaTokenizer:yy,MPNetTokenizer:by,FalconTokenizer:vy,GPTNeoXTokenizer:$y,EsmTokenizer:xy,Wav2Vec2CTCTokenizer:Ry,BlenderbotTokenizer:Xf,BlenderbotSmallTokenizer:By,SpeechT5Tokenizer:Py,NougatTokenizer:Dy,VitsTokenizer:Ny,Qwen2Tokenizer:Sy,GemmaTokenizer:Ey,PreTrainedTokenizer:Ee};static async from_pretrained(e,{quantized:n=!0,progress_callback:r=null,config:a=null,cache_dir:i=null,local_files_only:s=!1,revision:o="main",legacy:l=null}={}){const[d,c]=await Ff(e,{quantized:n,progress_callback:r,config:a,cache_dir:i,local_files_only:s,revision:o,legacy:l}),u=c.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let h=this.TOKENIZER_CLASS_MAPPING[u];return h||(console.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),h=Ee),new h(d,c)}}async function Fy(t,e){return await Yn(t,"config.json",!0,e)}class Ly{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:a=null,local_files_only:i=!1,revision:s="main"}={}){let o=r??await Fy(e,{progress_callback:n,config:r,cache_dir:a,local_files_only:i,revision:s});return new this(o)}}class Gn{static async from_pretrained(...e){return Ly.from_pretrained(...e)}}class nc extends Et{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,n){for(let r of n)this.processors.forEach(a=>a(e,r))}[Symbol.iterator](){return this.processors.values()}}class Jt extends Et{_call(e,n){throw Error("`_call` should be implemented in a subclass")}}class Uy extends Jt{constructor(e){super(),this.force_token_map=Object.fromEntries(e??[])}_call(e,n){let r=this.force_token_map[e.length];return Pg(r)&&(n.data.fill(-1/0),n.data[r]=0),n}}class Wy extends Jt{constructor(e){super(),this.bos_token_id=e}_call(e,n){return e.length===1&&(n.data.fill(-1/0),n.data[this.bos_token_id]=0),n}}class Vy extends Jt{constructor(e,n){super(),this.max_length=e,this.forced_eos_token_id=n}_call(e,n){}}class Gy extends Jt{constructor(e,n){super(),this.begin_suppress_tokens=e,this.begin_index=n}_call(e,n){if(e.length===this.begin_index)for(let r of this.begin_suppress_tokens)n.data[r]=-1/0;return n}}class Hy extends Jt{constructor(e){super(),this.eos_token_id=e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(e.forced_decoder_ids||[]).length+2,e.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,n){const r=n.data;if(r[this.no_timestamps_token_id]=-1/0,e.length===this.begin_index-1)return r.fill(-1/0),r[this.timestamp_begin]=0,n;const a=e.slice(this.begin_index),i=a.length>=1&&a[a.length-1]>=this.timestamp_begin,s=a.length<2||a[a.length-2]>=this.timestamp_begin;if(i&&(s?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e.length===this.begin_index&&this.max_initial_timestamp_index!==null){const c=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(c+1).fill(-1/0)}const o=Xg(r),l=Math.log(o.subarray(this.timestamp_begin).map(Math.exp).reduce((c,u)=>c+u)),d=Ot(o.subarray(0,this.timestamp_begin))[0];return l>d&&r.subarray(0,this.timestamp_begin).fill(-1/0),n}}class qy extends Jt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const n=e.length,r=[];for(let i=0;i0&&(a=a.map(i=>i/this.generation_config.temperature)),a}randomSelect(e){let n=e.reduce((a,i)=>a+i,0),r=Math.random()*n;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 Zy(e)}}class Zy extends fi{sample(e,n=-1){let r=this.getLogits(e,n);return[[Ot(r)[1],0]]}}class Jy extends fi{sample(e,n=-1){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const a=this.getLogits(e,n),i=Zn(a,r),s=ht(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 fi{sample(e,n=-1){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const a=this.getLogits(e,n),i=Zn(a,r),s=ht(i.map(o=>o[1]));return Array.from({length:this.generation_config.num_beams},(o,l)=>[i[l][0],Math.log(s[l])])}}const ps=Object.freeze({fp32:"fp32",fp16:"fp16",int8:"int8",uint8:"uint8",float32:"fp32",float16:"fp16"}),Se={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5},ai=new Map,Qf=new Map,Pr=new Map;async function hn(t,e,n){let r="";if(n.dtype){if(!ps.hasOwnProperty(n.dtype))throw new Error(`Invalid dtype: ${n.dtype}. Should be one of: ${Object.keys(ps).join(", ")}`);ps[n.dtype]!=="fp32"&&(r=`_${n.dtype}`)}else n.quantized&&(r="_quantized");const a=`onnx/${e}${r}.onnx`,i=await ys(t,a,!0,n),s=n.session_options??{};if(s.externalData!==void 0)for(let o=0;o0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.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 n}async function Qn(t,e){const n=tb(t,e);try{const r=Object.fromEntries(Object.entries(n).map(([i,s])=>[i,s.ort_tensor]));let a=await t.run(r);a=Zf(a);for(const[i,s]of Object.entries(n))i.startsWith("past_key_values")&&s.dispose();return a}catch(r){throw console.error(`An error occurred during model execution: "${r}".`),console.error("Inputs given to model:",n),r}}function Zf(t){for(let e in t)Bf(t[e])?t[e]=new ee(t[e]):typeof t[e]=="object"&&Zf(t[e]);return t}function nb(t){if(t instanceof ee)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 ee("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new ee("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function po(t,e){let n=t.config.pad_token_id??null,r=t.config.eos_token_id??null;hc(r)&&(r=[r]);let a=e.indexOf(n)!==-1,i=r===null||!r.includes(n);if(a&&i){let s=BigInt64Array.from(e.data.map(o=>o!=n));return new ee("int64",s,e.dims)}else return P0(e)}function Jf(t,e,n){if(!t.inputNames.includes("position_ids"))return;const r=new BigInt64Array(e.attention_mask.data.length);for(let a=0;a0&&a.push(new qy(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&a.push(new Xy(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&a.push(new Ky(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 Yy(n,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&a.push(new Wy(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&a.push(new Vy(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let i=n>1||e.forced_bos_token_id===null?n:n+1;e.forced_decoder_ids!==null&&(i+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),a.push(new Gy(e.begin_suppress_tokens,i))}return e.forced_decoder_ids!==null&&a.push(new Uy(e.forced_decoder_ids)),r!==null&&a.extend(r),a}_get_generation_config(e){let n=new Qy(this.config);return"generation_config"in this&&Object.assign(n,this.generation_config),e!==null&&Object.assign(n,e),n}async generate(e,n=null,r=null,{inputs_attention_mask:a=null}={}){if(!this.can_generate){let b=`The current model class (${Pr.get(this.constructor)}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;const y=this.config.model_type,$=$i.get(y)??bo.get(y)??yo.get(y)??vo.get(y);throw $&&(b+=` Please use the following class instead: '${$[0]}'`),Error(b)}if(!(e instanceof ee)&&!Bg(e)&&!Array.isArray(e))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${e.constructor.name}".`);let i;if(this.config.is_encoder_decoder)i=0;else if(i=e instanceof ee?e.dims.at(-1):e.length,i===0)throw Error("Must supply a non-empty array of input token ids.");n=this._get_generation_config(n),r=r??new nc,r=this._get_logits_processor(n,i,r);let s=n.eos_token_id;s!==null&&!Array.isArray(s)&&(s=[s]);let o=1;const l=o+(n.max_new_tokens??1/0),d=Number.isInteger(n.max_length)&&(n.max_new_tokens??null)===null;let c=fi.getSampler(n),u=this.getStartBeams(e,n,o,a);for(;u.some(w=>!w.done)&&o=n.max_length){b.done=!0,w.push(b);continue}let y=await this.runBeam(b);n.output_attentions&&this.addAttentionsToBeam(b,y),n.output_scores;let $=y.logits.slice(null,-1,null);r(b.output_token_ids,$);let k=c($);for(let[S,T]of k){let A={...b};this.updateBeam(A,S),A.score+=T,s&&s.includes(S)&&(A.done=!0),w.push(A)}}++o,w=this.groupBeams(w).map(b=>b.sort((y,$)=>$.score-y.score).slice(0,n.num_beams)),u=w.flat(),n.callback_function&&n.callback_function(u)}const h=this.groupBeams(u),f=w=>h.map(b=>n.num_return_sequences>1?b.slice(0,n.num_return_sequences).map(y=>y[w]):[b[0][w]]).flat(),g=f("output_token_ids");if(n.return_dict_in_generate){const w=f("decoder_attentions"),b=f("cross_attentions");return{sequences:g,decoder_attentions:w,cross_attentions:b}}else return g}addAttentionsToBeam(e,n){if(this.config.is_encoder_decoder){if(!n.cross_attentions||n.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(n.cross_attentions)}if(!n.decoder_attentions||n.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(n.decoder_attentions)}groupBeams(e){const n=Object.create(null);for(const r of e)n[r.id]===void 0?n[r.id]=[r]:n[r.id].push(r);return Object.values(n)}getPastKeyValues(e,n){const r=Object.create(null);for(const a in e)if(a.startsWith("present")){let i=a.replace("present","past_key_values");n&&a.includes("encoder")?r[i]=n[i]:r[i]=e[a]}return r}getAttentions(e){const n=Object.create(null);for(const r of["cross_attentions","decoder_attentions"]){const a=[];for(const i in e)if(i.startsWith(r)){const s=i.split(".").pop();a[s]=e[i]}n[r]=a}return n}addPastKeyValues(e,n){if(n)Object.assign(e,n);else{const a=this.config.precision||"float32",i=a==="float16"?new Uint16Array:[];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,y)=>di(d.map($=>$[y]),2)),u=ci(n.map(([b,y])=>r?c[b].slice(null,y,null,[0,r]):c[b].slice(null,y)));u=u.transpose(1,0,2,3);let[h,f]=O0(u,-2,0,!0),g=u.clone();for(let b=0;bu[y+1]-u[y]),g=dt([1],f).map(b=>!!b),w=[];for(let b=0;ba*i,1);e.input_labels=new ee("int64",new BigInt64Array(r).fill(1n),n)}return await Qn(this.prompt_encoder_mask_decoder,{input_points:e.input_points,input_labels:e.input_labels,image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings})}async _call(e){return new T$(await super._call(e))}}class T$ extends kt{constructor({iou_scores:e,pred_masks:n}){super(),this.iou_scores=e,this.pred_masks=n}}class Fm extends Z{}class I$ extends Fm{}class A$ extends Fm{constructor(e,n,r,a){super(e,n),this.decoder_merged_session=r,this.generation_config=a,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 Lm extends Z{}class M$ extends Lm{}class O$ extends Lm{constructor(e,n,r,a){super(e,n),this.decoder_merged_session=r,this.generation_config=a,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 Mn extends Z{}class z$ extends Mn{}class R$ extends Mn{async _call(e){return new nr(await super._call(e))}}class B$ extends Mn{async _call(e){return new Me(await super._call(e))}}class P$ extends Mn{async _call(e){return new ft(await super._call(e))}}class go extends Z{}class D$ extends go{}class N$ extends go{async _call(e){return new nr(await super._call(e))}}class F$ extends go{async _call(e){return new Me(await super._call(e))}}class vi extends Z{}class L$ extends vi{}class U$ extends vi{async _call(e){return new nr(await super._call(e))}}class W$ extends vi{async _call(e){return new Me(await super._call(e))}}class V$ extends vi{async _call(e){return new ft(await super._call(e))}}class _o extends Z{}class G$ extends _o{}class H$ extends _o{async _call(e){return new nr(await super._call(e))}}class q$ extends _o{async _call(e){return new Me(await super._call(e))}}class j$ extends Mn{}class K$ extends Mn{async _call(e){return new nr(await super._call(e))}}class Y$ extends Mn{async _call(e){return new Me(await super._call(e))}}class oa extends Z{}class X$ extends oa{}class Q$ extends oa{async _call(e){return new nr(await super._call(e))}}class Z$ extends oa{async _call(e){return new Me(await super._call(e))}}class J$ extends oa{async _call(e){return new q1(await super._call(e))}}class e1 extends oa{async _call(e){return new ft(await super._call(e))}}class Um extends Z{}class t1 extends Um{}class n1 extends Um{constructor(e,n,r,a){super(e,n),this.decoder_merged_session=r,this.generation_config=a,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}async generate_speech(e,n,{threshold:r=.5,minlenratio:a=0,maxlenratio:i=20,vocoder:s=null}={}){const o={input_ids:e},{encoder_outputs:l,encoder_attention_mask:d}=await Wr(this,o),c=l.dims[1]/this.config.reduction_factor,u=Math.floor(c*i),h=Math.floor(c*a),f=this.config.num_mel_bins;let g=[],w=null,b=null,y=0;for(;;){++y;const S=ho(!!b);let T;b?T=b.output_sequence_out:T=new ee("float32",new Float32Array(f),[1,1,f]);let A={use_cache_branch:S,output_sequence:T,encoder_attention_mask:d,speaker_embeddings:n,encoder_hidden_states:l};this.addPastKeyValues(A,w),b=await Qn(this.decoder_merged_session,A),w=this.getPastKeyValues(b,w);const{prob:P,spectrum:N}=b;if(g.push(N),y>=h&&(Array.from(P.data).filter(V=>V>=r).length>0||y>=u))break}const $=di(g),{waveform:k}=await Qn(s.session,{spectrogram:$});return{spectrogram:$,waveform:k}}}class r1 extends Z{main_input_name="spectrogram"}class a1 extends Z{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,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 i1 extends a1{}class Wm extends Z{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,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 s1 extends Wm{}class o1 extends Wm{}class Vm extends Z{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,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 l1 extends Vm{}class u1 extends Vm{}class Gm extends Z{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,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 d1 extends Gm{}class c1 extends Gm{}class wo extends Z{}class p1 extends wo{}class h1 extends wo{static async from_pretrained(e,n={}){return n.model_file_name??="text_model",super.from_pretrained(e,n)}}class f1 extends wo{static async from_pretrained(e,n={}){return n.model_file_name??="audio_model",super.from_pretrained(e,n)}}class m1 extends Z{}class Hm extends m1{async _call(e){return new K1(await super._call(e))}}class qm extends Z{}class g1 extends qm{}class _1 extends qm{}class w1 extends Z{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,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 y1 extends w1{}class Ze{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{quantized:n=!0,progress_callback:r=null,config:a=null,cache_dir:i=null,local_files_only:s=!1,revision:o="main",model_file_name:l=null,device:d=null,dtype:c=null,session_options:u={}}={}){let h={quantized:n,progress_callback:r,config:a,cache_dir:i,local_files_only:s,revision:o,model_file_name:l,device:d,dtype:c,session_options:u};if(a=await Gn.from_pretrained(e,h),h.config||(h.config=a),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let f of this.MODEL_CLASS_MAPPINGS){const g=f.get(a.model_type);if(g)return await g[1].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${a.model_type}", attempting to construct from base class.`),await Z.from_pretrained(e,h);throw Error(`Unsupported model type: ${a.model_type}`)}}const jm=new Map([["bert",["BertModel",cb]],["nomic_bert",["NomicBertModel",_b]],["roformer",["RoFormerModel",wb]],["electra",["ElectraModel",Tb]],["esm",["EsmModel",Jb]],["convbert",["ConvBertModel",xb]],["camembert",["CamembertModel",zb]],["deberta",["DebertaModel",Nb]],["deberta-v2",["DebertaV2Model",Vb]],["mpnet",["MPNetModel",ov]],["albert",["AlbertModel",gv]],["distilbert",["DistilBertModel",Kb]],["roberta",["RobertaModel",Dv]],["xlm",["XLMModel",Wv]],["xlm-roberta",["XLMRobertaModel",jv]],["clap",["ClapModel",p1]],["clip",["CLIPModel",n2]],["clipseg",["CLIPSegModel",d2]],["chinese_clip",["ChineseCLIPModel",u2]],["siglip",["SiglipModel",i2]],["mobilebert",["MobileBertModel",rv]],["squeezebert",["SqueezeBertModel",pv]],["wav2vec2",["Wav2Vec2Model",z$]],["wav2vec2-bert",["Wav2Vec2BertModel",G$]],["unispeech",["UniSpeechModel",D$]],["unispeech-sat",["UniSpeechSatModel",L$]],["hubert",["HubertModel",j$]],["wavlm",["WavLMModel",X$]],["audio-spectrogram-transformer",["ASTModel",Zv]],["vits",["VitsModel",Hm]],["detr",["DetrModel",K2]],["table-transformer",["TableTransformerModel",Z2]],["vit",["ViTModel",P2]],["mobilevit",["MobileViTModel",L2]],["owlvit",["OwlViTModel",W2]],["owlv2",["Owlv2Model",G2]],["beit",["BeitModel",q2]],["deit",["DeiTModel",t$]],["convnext",["ConvNextModel",_$]],["convnextv2",["ConvNextV2Model",y$]],["dinov2",["Dinov2Model",v$]],["resnet",["ResNetModel",r$]],["swin",["SwinModel",i$]],["swin2sr",["Swin2SRModel",o$]],["donut-swin",["DonutSwinModel",g$]],["yolos",["YolosModel",x$]],["dpt",["DPTModel",u$]],["glpn",["GLPNModel",h$]],["hifigan",["SpeechT5HifiGan",r1]]]),Km=new Map([["t5",["T5Model",bv]],["longt5",["LongT5Model",$v]],["mt5",["MT5Model",Sv]],["bart",["BartModel",kv]],["mbart",["MBartModel",Iv]],["marian",["MarianModel",I$]],["whisper",["WhisperModel",e2]],["m2m_100",["M2M100Model",M$]],["blenderbot",["BlenderbotModel",zv]],["blenderbot-small",["BlenderbotSmallModel",Bv]]]),b1=new Map([["bloom",["BloomModel",A2]],["gpt2",["GPT2Model",p2]],["gptj",["GPTJModel",w2]],["gpt_bigcode",["GPTBigCodeModel",b2]],["gpt_neo",["GPTNeoModel",f2]],["gpt_neox",["GPTNeoXModel",g2]],["codegen",["CodeGenModel",$2]],["llama",["LlamaModel",S2]],["qwen2",["Qwen2Model",k2]],["phi",["PhiModel",T2]],["mpt",["MptModel",O2]],["opt",["OPTModel",R2]],["mistral",["MistralModel",s1]],["starcoder2",["Starcoder2Model",l1]],["falcon",["FalconModel",d1]]]),yo=new Map([["speecht5",["SpeechT5ForSpeechToText",t1]],["whisper",["WhisperForConditionalGeneration",t2]]]),Ym=new Map([["speecht5",["SpeechT5ForTextToSpeech",n1]]]),Xm=new Map([["vits",["VitsModel",Hm]]]),Qm=new Map([["bert",["BertForSequenceClassification",hb]],["roformer",["RoFormerForSequenceClassification",bb]],["electra",["ElectraForSequenceClassification",Ab]],["esm",["EsmForSequenceClassification",tv]],["convbert",["ConvBertForSequenceClassification",Eb]],["camembert",["CamembertForSequenceClassification",Bb]],["deberta",["DebertaForSequenceClassification",Lb]],["deberta-v2",["DebertaV2ForSequenceClassification",Hb]],["mpnet",["MPNetForSequenceClassification",uv]],["albert",["AlbertForSequenceClassification",_v]],["distilbert",["DistilBertForSequenceClassification",Yb]],["roberta",["RobertaForSequenceClassification",Fv]],["xlm",["XLMForSequenceClassification",Gv]],["xlm-roberta",["XLMRobertaForSequenceClassification",Yv]],["bart",["BartForSequenceClassification",Tv]],["mbart",["MBartForSequenceClassification",Mv]],["mobilebert",["MobileBertForSequenceClassification",iv]],["squeezebert",["SqueezeBertForSequenceClassification",fv]]]),Zm=new Map([["bert",["BertForTokenClassification",fb]],["roformer",["RoFormerForTokenClassification",vb]],["electra",["ElectraForTokenClassification",Mb]],["esm",["EsmForTokenClassification",nv]],["convbert",["ConvBertForTokenClassification",kb]],["camembert",["CamembertForTokenClassification",Pb]],["deberta",["DebertaForTokenClassification",Ub]],["deberta-v2",["DebertaV2ForTokenClassification",qb]],["mpnet",["MPNetForTokenClassification",dv]],["distilbert",["DistilBertForTokenClassification",Xb]],["roberta",["RobertaForTokenClassification",Lv]],["xlm",["XLMForTokenClassification",Hv]],["xlm-roberta",["XLMRobertaForTokenClassification",Xv]]]),bo=new Map([["t5",["T5ForConditionalGeneration",vv]],["longt5",["LongT5ForConditionalGeneration",xv]],["mt5",["MT5ForConditionalGeneration",Ev]],["bart",["BartForConditionalGeneration",Cv]],["mbart",["MBartForConditionalGeneration",Av]],["marian",["MarianMTModel",A$]],["m2m_100",["M2M100ForConditionalGeneration",O$]],["blenderbot",["BlenderbotForConditionalGeneration",Rv]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Pv]]]),$i=new Map([["bloom",["BloomForCausalLM",M2]],["gpt2",["GPT2LMHeadModel",h2]],["gptj",["GPTJForCausalLM",y2]],["gpt_bigcode",["GPTBigCodeForCausalLM",v2]],["gpt_neo",["GPTNeoForCausalLM",m2]],["gpt_neox",["GPTNeoXForCausalLM",_2]],["codegen",["CodeGenForCausalLM",x2]],["llama",["LlamaForCausalLM",E2]],["qwen2",["Qwen2ForCausalLM",C2]],["phi",["PhiForCausalLM",I2]],["mpt",["MptForCausalLM",z2]],["opt",["OPTForCausalLM",B2]],["mbart",["MBartForCausalLM",Ov]],["mistral",["MistralForCausalLM",o1]],["starcoder2",["Starcoder2ForCausalLM",u1]],["falcon",["FalconForCausalLM",c1]],["trocr",["TrOCRForCausalLM",i1]],["stablelm",["StableLmForCausalLM",y1]]]),Jm=new Map([["bert",["BertForMaskedLM",pb]],["roformer",["RoFormerForMaskedLM",yb]],["electra",["ElectraForMaskedLM",Ib]],["esm",["EsmForMaskedLM",ev]],["convbert",["ConvBertForMaskedLM",Sb]],["camembert",["CamembertForMaskedLM",Rb]],["deberta",["DebertaForMaskedLM",Fb]],["deberta-v2",["DebertaV2ForMaskedLM",Gb]],["mpnet",["MPNetForMaskedLM",lv]],["albert",["AlbertForMaskedLM",yv]],["distilbert",["DistilBertForMaskedLM",Zb]],["roberta",["RobertaForMaskedLM",Nv]],["xlm",["XLMWithLMHeadModel",Vv]],["xlm-roberta",["XLMRobertaForMaskedLM",Kv]],["mobilebert",["MobileBertForMaskedLM",av]],["squeezebert",["SqueezeBertForMaskedLM",hv]]]),eg=new Map([["bert",["BertForQuestionAnswering",mb]],["roformer",["RoFormerForQuestionAnswering",$b]],["electra",["ElectraForQuestionAnswering",Ob]],["convbert",["ConvBertForQuestionAnswering",Cb]],["camembert",["CamembertForQuestionAnswering",Db]],["deberta",["DebertaForQuestionAnswering",Wb]],["deberta-v2",["DebertaV2ForQuestionAnswering",jb]],["mpnet",["MPNetForQuestionAnswering",cv]],["albert",["AlbertForQuestionAnswering",wv]],["distilbert",["DistilBertForQuestionAnswering",Qb]],["roberta",["RobertaForQuestionAnswering",Uv]],["xlm",["XLMForQuestionAnswering",qv]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Qv]],["mobilebert",["MobileBertForQuestionAnswering",sv]],["squeezebert",["SqueezeBertForQuestionAnswering",mv]]]),vo=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",om]]]),v1=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",om]]]),tg=new Map([["vit",["ViTForImageClassification",D2]],["mobilevit",["MobileViTForImageClassification",U2]],["beit",["BeitForImageClassification",j2]],["deit",["DeiTForImageClassification",n$]],["convnext",["ConvNextForImageClassification",w$]],["convnextv2",["ConvNextV2ForImageClassification",b$]],["dinov2",["Dinov2ForImageClassification",$$]],["resnet",["ResNetForImageClassification",a$]],["swin",["SwinForImageClassification",s$]],["segformer",["SegformerForImageClassification",g1]]]),ng=new Map([["detr",["DetrForObjectDetection",Y2]],["table-transformer",["TableTransformerForObjectDetection",J2]],["yolos",["YolosForObjectDetection",S$]]]),rg=new Map([["owlvit",["OwlViTForObjectDetection",V2]],["owlv2",["Owlv2ForObjectDetection",H2]]]),ag=new Map([["detr",["DetrForSegmentation",X2]],["clipseg",["CLIPSegForImageSegmentation",c2]]]),ig=new Map([["segformer",["SegformerForSemanticSegmentation",_1]]]),$1=new Map([["sam",["SamModel",C$]]]),sg=new Map([["wav2vec2",["Wav2Vec2ForCTC",R$]],["wav2vec2-bert",["Wav2Vec2BertForCTC",H$]],["unispeech",["UniSpeechForCTC",N$]],["unispeech-sat",["UniSpeechSatForCTC",U$]],["wavlm",["WavLMForCTC",Q$]],["hubert",["HubertForCTC",K$]]]),og=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",B$]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",q$]],["unispeech",["UniSpeechForSequenceClassification",F$]],["unispeech-sat",["UniSpeechSatForSequenceClassification",W$]],["wavlm",["WavLMForSequenceClassification",Z$]],["hubert",["HubertForSequenceClassification",Y$]],["audio-spectrogram-transformer",["ASTForAudioClassification",Jv]]]),x1=new Map([["wavlm",["WavLMForXVector",J$]]]),S1=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",V$]],["wavlm",["WavLMForAudioFrameClassification",e1]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",P$]]]),E1=new Map([["vitmatte",["VitMatteForImageMatting",F2]]]),lg=new Map([["swin2sr",["Swin2SRForImageSuperResolution",l$]]]),ug=new Map([["dpt",["DPTForDepthEstimation",d$]],["depth_anything",["DepthAnythingForDepthEstimation",p$]],["glpn",["GLPNForDepthEstimation",f$]]]),dg=[[jm,Se.EncoderOnly],[Km,Se.EncoderDecoder],[b1,Se.DecoderOnly],[Qm,Se.EncoderOnly],[Zm,Se.EncoderOnly],[bo,Se.Seq2Seq],[yo,Se.Seq2Seq],[$i,Se.DecoderOnly],[Jm,Se.EncoderOnly],[eg,Se.EncoderOnly],[vo,Se.Vision2Seq],[tg,Se.EncoderOnly],[ag,Se.EncoderOnly],[ig,Se.EncoderOnly],[E1,Se.EncoderOnly],[lg,Se.EncoderOnly],[ug,Se.EncoderOnly],[ng,Se.EncoderOnly],[rg,Se.EncoderOnly],[$1,Se.MaskGeneration],[sg,Se.EncoderOnly],[og,Se.EncoderOnly],[Ym,Se.Seq2Seq],[Xm,Se.EncoderOnly],[x1,Se.EncoderOnly],[S1,Se.EncoderOnly]];for(const[t,e]of dg)for(const[n,r]of t.values())ai.set(n,e),Pr.set(r,n),Qf.set(n,r);const k1=[["CLIPTextModelWithProjection",r2,Se.EncoderOnly],["CLIPVisionModelWithProjection",a2,Se.EncoderOnly],["SiglipTextModel",s2,Se.EncoderOnly],["SiglipVisionModel",o2,Se.EncoderOnly],["ClapTextModelWithProjection",h1,Se.EncoderOnly],["ClapAudioModelWithProjection",f1,Se.EncoderOnly]];for(const[t,e,n]of k1)ai.set(t,n),Pr.set(e,t),Qf.set(t,e);class Va extends Ze{static MODEL_CLASS_MAPPINGS=dg.map(e=>e[0]);static BASE_IF_FAIL=!0}class rc extends Ze{static MODEL_CLASS_MAPPINGS=[Qm]}class C1 extends Ze{static MODEL_CLASS_MAPPINGS=[Zm]}class hs extends Ze{static MODEL_CLASS_MAPPINGS=[bo]}class T1 extends Ze{static MODEL_CLASS_MAPPINGS=[yo]}class I1 extends Ze{static MODEL_CLASS_MAPPINGS=[Ym]}class A1 extends Ze{static MODEL_CLASS_MAPPINGS=[Xm]}class M1 extends Ze{static MODEL_CLASS_MAPPINGS=[$i]}class O1 extends Ze{static MODEL_CLASS_MAPPINGS=[Jm]}class z1 extends Ze{static MODEL_CLASS_MAPPINGS=[eg]}class R1 extends Ze{static MODEL_CLASS_MAPPINGS=[vo]}class B1 extends Ze{static MODEL_CLASS_MAPPINGS=[tg]}class P1 extends Ze{static MODEL_CLASS_MAPPINGS=[ag]}class D1 extends Ze{static MODEL_CLASS_MAPPINGS=[ig]}class N1 extends Ze{static MODEL_CLASS_MAPPINGS=[ng]}class F1 extends Ze{static MODEL_CLASS_MAPPINGS=[rg]}class L1 extends Ze{static MODEL_CLASS_MAPPINGS=[sg]}class U1 extends Ze{static MODEL_CLASS_MAPPINGS=[og]}class W1 extends Ze{static MODEL_CLASS_MAPPINGS=[v1]}class V1 extends Ze{static MODEL_CLASS_MAPPINGS=[lg]}class G1 extends Ze{static MODEL_CLASS_MAPPINGS=[ug]}class H1 extends kt{constructor({logits:e,past_key_values:n,encoder_outputs:r,decoder_attentions:a=null,cross_attentions:i=null}){super(),this.logits=e,this.past_key_values=n,this.encoder_outputs=r,this.decoder_attentions=a,this.cross_attentions=i}}class Me extends kt{constructor({logits:e}){super(),this.logits=e}}class q1 extends kt{constructor({logits:e,embeddings:n}){super(),this.logits=e,this.embeddings=n}}class ft extends kt{constructor({logits:e}){super(),this.logits=e}}class mt extends kt{constructor({logits:e}){super(),this.logits=e}}class _t extends kt{constructor({start_logits:e,end_logits:n}){super(),this.start_logits=e,this.end_logits=n}}class nr extends kt{constructor({logits:e}){super(),this.logits=e}}class j1 extends kt{constructor({alphas:e}){super(),this.alphas=e}}class K1 extends kt{constructor({waveform:e,spectrogram:n}){super(),this.waveform=e,this.spectrogram=n}}const It=typeof self<"u",Y1=It&&self.constructor.name==="DedicatedWorkerGlobalScope";let kn,cg,fn;if(It)kn=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},fn=self.createImageBitmap,cg=self.ImageData;else if(je)fn=async t=>{const n=(await t.metadata()).channels,{data:r,info:a}=await t.raw().toBuffer({resolveWithObject:!0}),i=new pt(new Uint8ClampedArray(r),a.width,a.height,a.channels);return n!==void 0&&n!==a.channels&&i.convert(n),i};else throw new Error("Unable to load image processing library.");const X1={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},Q1=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class pt{constructor(e,n,r,a){this.data=e,this.width=n,this.height=r,this.channels=a}get size(){return[this.width,this.height]}static async read(e){if(e instanceof pt)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(!It)throw new Error("fromCanvas() is only supported in browser environments.");const r=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new pt(r,e.width,e.height,4)}static async fromURL(e){const n=await qa(e);if(n.status!==200)throw new Error(`Unable to read image from "${e}" (${n.status} ${n.statusText})`);const r=await n.blob();return this.fromBlob(r)}static async fromBlob(e){if(It){const n=await fn(e),r=kn(n.width,n.height).getContext("2d");return r.drawImage(n,0,0),new this(r.getImageData(0,0,n.width,n.height).data,n.width,n.height,4)}else{const n=je(await e.arrayBuffer());return await fn(n)}}static fromTensor(e,n="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(n==="CHW")e=e.transpose(1,2,0);else if(n!=="HWC")throw new Error(`Unsupported channel format: ${n}`);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 pt(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 n=0,r=0;n=0?l=r:c=-r,a>=0?d=a:u=-a,o.drawImage(s,l,d,e,n,c,u,e,n),new pt(o.getImageData(0,0,e,n).data,e,n,4).convert(i)}else{let i=this.toSharp();if(r>=0&&a>=0)i=i.extract({left:Math.floor(r),top:Math.floor(a),width:e,height:n});else if(r<=0&&a<=0){const s=Math.floor(-a),o=Math.floor(-r);i=i.extend({top:s,left:o,right:e-this.width-o,bottom:n-this.height-s})}else{let s=[0,0],o=0;a<0?(s[0]=Math.floor(-a),s[1]=n-this.height-s[0]):o=Math.floor(a);let l=[0,0],d=0;r<0?(l[0]=Math.floor(-r),l[1]=e-this.width-l[0]):d=Math.floor(r),i=i.extend({top:s[0],bottom:s[1],left:l[0],right:l[1]}).extract({left:d,top:o,width:e,height:n})}return await fn(i)}}async toBlob(e="image/png",n=1){if(!It)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:n})}toCanvas(){if(!It)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),n=kn(e.width,e.height),r=new cg(e.data,e.width,e.height);return n.getContext("2d").putImageData(r,0,0),n}_update(e,n,r,a=null){return this.data=e,this.width=n,this.height=r,a!==null&&(this.channels=a),this}clone(){return new pt(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(It){if(Y1)throw new Error("Unable to save an image from a Web Worker.");const n=e.split(".").pop().toLowerCase(),r=Q1.get(n)??"image/png",a=await this.toBlob(r),i=URL.createObjectURL(a),s=document.createElement("a");s.href=i,s.download=e,s.click(),s.remove()}else{if(at.useFS)return await this.toSharp().toFile(e);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(It)throw new Error("toSharp() is only supported in server-side environments.");return je(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}async function Z1(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const n=await(await qa(t)).arrayBuffer(),r=new AudioContext({sampleRate:e});typeof e>"u"&&console.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);const a=await r.decodeAudioData(n);let i;if(a.numberOfChannels===2){const s=Math.sqrt(2),o=a.getChannelData(0),l=a.getChannelData(1);i=new Float32Array(o.length);for(let d=0;d2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,n=15,r=27/Math.log(6.4))=>t>=e?n+Math.log(t/e)*r:3*t/200};function fs(t,e="htk"){const n=J1[e];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?n(t):t.map(r=>n(r))}const ex={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,n=15,r=Math.log(6.4)/27)=>t>=n?e*Math.exp(r*(t-n)):200*t/3};function tx(t,e="htk"){const n=ex[e];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?n(t):t.map(r=>n(r))}function nx(t,e){const n=Float64Array.from({length:e.length-1},(s,o)=>e[o+1]-e[o]),r=Array.from({length:t.length},()=>new Array(e.length));for(let s=0;snew Array(t.length));for(let s=0;st+r*i)}function Vr(t,e,n,r,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(n,s),d=fs(r,s),c=ic(l,d,e+2);let u=tx(c,s),h;if(o){const g=a/(t*2);h=fs(Float64Array.from({length:t},(w,b)=>b*g),s),u=c}else h=ic(0,Math.floor(a/2),t);const f=nx(h,u);if(i!==null&&i==="slaney")for(let g=0;ga)throw Error(`frame_length (${n}) may not be larger than fft_length (${a})`);if(S!==n)throw new Error(`Length of the window (${S}) must equal frame_length (${n})`);if(r<=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 te=Math.floor((a-1)/2)+1;t=rx(t,te,te)}const T=Math.floor(1+Math.floor((t.length-n)/r)),A=l?Math.floor(a/2)+1:a;let P=T,N=T;y!==null&&(y>T?$&&(N=y):N=P=y);const V=new Zg(a),j=new Float64Array(a),M=new Float64Array(V.outputBufferSize),G=new Array(P);for(let te=0;te=1;--Y)j[Y]-=d*j[Y-1];j[0]*=1-d}for(let Y=0;YMath.pow(o,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(n&&(s=s.subarray(0,t)),r===null)return s;if(t>r)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${r})`);return s}function sx([t,e,n,r]){return[t-n/2,e-r/2,t+n/2,e+r/2]}function $o(t,e=.5,n=null,r=!1){const a=t.logits,i=t.pred_boxes,[s,o,l]=a.dims;if(n!==null&&n.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&&y.push(k)}else{let k=Ot(b.data)[1];if(k===l-1||($=ht(b.data),$[k]T*u[(A+1)%2])),h.boxes.push(S),h.classes.push(k),h.scores.push($[k])}}d.push(h)}return d}function la(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 sc(t,e,n=0,r=null){let a=Math.round(t/e)*e;return r!==null&&a>r&&(a=Math.floor(t/e)*e),ai?d=Math.floor(i*l/a):i>a&&(l=Math.floor(a*d/i)),await e.resize(d,l,{resample:r}))}async crop_margin(e,n=200){const r=e.clone().grayscale(),a=gc(r.data)[0],s=Ot(r.data)[0]-a;if(s===0)return e;const o=n/255;let l=r.width,d=r.height,c=0,u=0;for(let h=0;hthis.preprocess(i)));return{pixel_values:ci(r.map(i=>i.pixel_values),0),original_sizes:r.map(i=>i.original_size),reshaped_input_sizes:r.map(i=>i.reshaped_input_size)}}}class ox extends Ke{post_process_semantic_segmentation(e,n=null){const r=e.logits,a=r.dims[0];if(n!==null&&n.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[$]&&(h[$]=y[$],u.data[$]=b)}const f=new Array(l.dims[0]),g=u.data;for(let b=0;bb!==void 0);i.push({segmentation:u,labels:w})}return i}}class lx extends Ke{}class ux extends Ke{}class dx extends Ke{}class cx extends Ke{}class px extends Ke{}class hx extends Ke{}class fx extends Ke{}class hg extends Ke{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const n=this.size?.shortest_edge;if(n===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(n<384){const r=Math.floor(n/this.crop_pct),[a,i]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(a,i,{resample:this.resample}),e=await e.center_crop(n,n)}else e=await e.resize(n,n,{resample:this.resample});return e}}class mx extends hg{}class gx extends Ke{}class _x extends Ke{}class wx extends Ke{}class fg extends Ke{post_process_object_detection(...e){return $o(...e)}}class yx extends fg{}class bx extends Ke{}class vx extends Ke{}class mg extends Ke{pad_image(e,n,r,a={}){const[i,s,o]=n;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/this.image_std[h]);return super.pad_image(e,n,r,{center:!0,constant_values:c,...a})}}class $x extends mg{}class xx extends Ke{async _call(e){const n=await super._call(e),r=[n.pixel_values.dims[0],64,64],a=new ee("int64",new BigInt64Array(r.reduce((i,s)=>i*s)).fill(1n),r);return{...n,pixel_mask:a}}post_process_object_detection(...e){return $o(...e)}remove_low_and_no_objects(e,n,r,a){let i=[],s=[],o=[];for(let l=0;lr&&(i.push(c),s.push(f),o.push(u))}return[i,s,o]}check_segment_validity(e,n,r,a=.5,i=.8){let s=[],o=0,l=0;for(let c=0;c=a&&++l;let d=o>0&&l>0;return d&&(d=o/l>i),[d,s]}compute_segments(e,n,r,a,i,s=null,o=null){let[l,d]=o??e[0].dims,c=new ee("int32",new Int32Array(l*d),[l,d]),u=[];if(o!==null)for(let w=0;wf[y]&&(h[y]=w,f[y]=e[w].data[y])}let g=0;for(let w=0;wa!==n.dims[i]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new ee("int64",e.flat(1/0).map(BigInt),r)}async _call(e,n=null,r=null){const a=await super._call(e);if(n&&(a.input_points=this.reshape_input_points(n,a.original_sizes,a.reshaped_input_sizes)),r){if(!a.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");a.input_labels=this.add_input_labels(r,a.input_points)}return a}post_process_masks(e,n,r,{mask_threshold:a=0,binarize:i=!0,pad_size:s=null}={}){const o=[];s=s??this.pad_size;const l=[s.height,s.width];for(let d=0;da&&(y[$]=1);b=new ee("bool",y,b.dims)}f.push(b)}o.push(ci(f))}return o}generate_crop_boxes(e,n,{crop_n_layers:r=0,overlap_ratio:a=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:s=1}={}){}}class kx extends Ke{pad_image(e,n,r,a={}){const[i,s,o]=n;return super.pad_image(e,n,{width:i+(r-i%r)%r,height:s+(r-s%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...a})}}class Cx extends Ke{async _call(e,n){Array.isArray(e)||(e=[e]),Array.isArray(n)||(n=[n]);const r=await Promise.all(e.map(s=>this.preprocess(s))),a=await Promise.all(n.map(s=>this.preprocess(s,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:ci(r.map((s,o)=>di([s.pixel_values,a[o].pixel_values],0)),0),original_sizes:r.map(s=>s.original_size),reshaped_input_sizes:r.map(s=>s.reshaped_input_size)}}}class Tx extends On{constructor(e){super(e),this.config.mel_filters??=Vr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Si(this.config.n_fft,"hann")}_extract_fbank_features(e){const{data:n,dims:r}=xi(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=Ot(n)[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`."),n=e.slice(0,this.config.n_samples)):(n=new Float32Array(this.config.n_samples),n.set(e));const{data:r,dims:a}=this._extract_fbank_features(n);return{input_features:new ee("float32",r,[1,...a])}}}class Ix extends On{_zero_mean_unit_var_norm(e){const r=e.reduce((i,s)=>i+s,0)/e.length,a=e.reduce((i,s)=>i+(s-r)**2,0)/e.length;return e.map(i=>(i-r)/Math.sqrt(a+1e-7))}async _call(e){la(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let n=e;this.config.do_normalize&&(n=this._zero_mean_unit_var_norm(n));const r=[1,n.length];return{input_values:new ee("float32",n,r),attention_mask:new ee("int64",new BigInt64Array(n.length).fill(1n),r)}}}class Ax extends On{constructor(e){super(e);const n=this.config.sampling_rate,r=Vr(256,this.config.num_mel_bins,20,Math.floor(n/2),n,null,"kaldi",!0);for(let a=0;ar*32768),xi(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:n,transpose:!0})}async _call(e,{padding:n=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:a=!0,return_attention_mask:i=!0}={}){la(e,"SeamlessM4TFeatureExtractor");let s=this._extract_fbank_features(e,this.config.max_length);if(a){const[g,w]=s.dims;for(let b=0;b0){const y=new Float32Array(w*(g+b));y.set(s.data),y.fill(this.config.padding_value,s.data.length);const $=g+b;s={data:y,dims:[$,w]},i&&(o=new ee("int64",new BigInt64Array($),[1,$]),o.data.fill(1n,0,g))}}const[l,d]=s.dims,c=this.config.stride;if(l%c!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${c}).`);const h=new ee("float32",s.data,s.dims).view(1,Math.floor(l/c),d*c),f={input_features:h};if(i){const g=h.dims[1],w=new ee("int64",new BigInt64Array(g),[1,g]);if(o)for(let b=1,y=0;b0)if(r==="rand_trunc"){s=!0;const l=Math.floor(Math.random()*(o+1));e=e.subarray(l,l+n),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 "${r}" not implemented`);else{if(o<0){let l=new Float64Array(n);if(l.set(e),a==="repeat")for(let d=e.length;dpt.read(e)))}async function ii(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(n=>typeof n=="string"||n instanceof URL?Z1(n,e):n instanceof Float64Array?new Float32Array(n):n))}function gg(t,e){e&&(t=t.map(s=>s|0));const[n,r,a,i]=t;return{xmin:n,ymin:r,xmax:a,ymax:i}}class Je extends Et{constructor({task:e,model:n,tokenizer:r=null,processor:a=null}){super(),this.task=e,this.model=n,this.tokenizer=r,this.processor=a}async dispose(){await this.model.dispose()}}class Fx extends Je{constructor(e){super(e)}async _call(e,{topk:n=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),a=await this.model(r),i=this.model.config.problem_type==="multi_label_classification"?l=>l.sigmoid().data:l=>ht(l.data),s=this.model.config.id2label,o=[];for(const l of a.logits){const d=i(l),u=Zn(d,n).map(h=>({label:s[h[0]],score:h[1]}));n===1?o.push(...u):o.push(u)}return Array.isArray(e)||n===1?o:o[0]}}class Lx extends Je{constructor(e){super(e)}async _call(e,{ignore_labels:n=["O"]}={}){const r=Array.isArray(e),a=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),s=(await this.model(a)).logits,o=this.model.config.id2label,l=[];for(let d=0;d[f,g]).filter(f=>f[1]>d),u=Array.from(ht(i.end_logits[o].data)).map((f,g)=>[f,g]).filter(f=>f[1]>d),h=Dg(c,u).filter(f=>f[0][1]<=f[1][1]).map(f=>[f[0][1],f[1][1],f[0][0]*f[1][0]]).sort((f,g)=>g[2]-f[2]);for(let f=0;f{const f=[...o];return f[l]=h[0],{score:h[1],token:h[0],token_str:this.tokenizer.model.vocab[h[0]],sequence:this.tokenizer.decode(f,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}}class xo extends Je{_key="generated_text";constructor(e){super(e)}async _call(e,n={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));const r=this.model.config.task_specific_params;r&&r[this.task]&&r[this.task].prefix&&(e=e.map(l=>r[this.task].prefix+l));const a=this.tokenizer,i={padding:!0,truncation:!0};let s;this instanceof _g&&"_build_translation_inputs"in a?s=a._build_translation_inputs(e,i,n).input_ids:s=a(e,i).input_ids;const o=await this.model.generate(s,n);return a.batch_decode(o,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}}class Vx extends xo{_key="summary_text";constructor(e){super(e)}}class _g extends xo{_key="translation_text";constructor(e){super(e)}}class Gx extends Je{constructor(e){super(e)}async _call(e,n={}){const r=Array.isArray(e);r||(e=[e]);const a=n.add_special_tokens??!1;this.tokenizer.padding_side="left";const{input_ids:i,attention_mask:s}=this.tokenizer(e,{add_special_tokens:a,padding:!0,truncation:!0}),o=await this.model.generate(i,n,null,{inputs_attention_mask:s}),l=this.tokenizer.batch_decode(o,{skip_special_tokens:!0}),d=Array.from({length:e.length},c=>[]);for(let c=0;c[n.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,n,{hypothesis_template:r="This example is {}.",multi_label:a=!1}={}){const i=Array.isArray(e);i||(e=[e]),Array.isArray(n)||(n=[n]);const s=n.map(d=>r.replace("{}",d)),o=a||n.length===1,l=[];for(const d of e){const c=[];for(const f of s){const g=this.tokenizer(d,{text_pair:f,padding:!0,truncation:!0}),w=await this.model(g);o?c.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):c.push(w.logits.data[this.entailment_id])}const h=(o?c.map(f=>ht(f)[1]):ht(c)).map((f,g)=>[f,g]).sort((f,g)=>g[0]-f[0]);l.push({sequence:d,labels:h.map(f=>n[f[1]]),scores:h.map(f=>f[0])})}return i?l:l[0]}}class qx extends Je{constructor(e){super(e)}async _call(e,{pooling:n="none",normalize:r=!1}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(a);let s=i.last_hidden_state??i.logits;if(n!=="none")if(n==="mean")s=M0(s,a.attention_mask);else if(n==="cls")s=s.slice(null,0);else throw Error(`Pooling method '${n}' not supported.`);return r&&(s=s.normalize(2,-1)),s}}class jx extends Je{constructor(e){super(e)}async _call(e,{topk:n=null}={}){const r=!Array.isArray(e),a=this.processor.feature_extractor.config.sampling_rate,i=await ii(e,a),s=this.model.config.id2label,o=[];for(const l of i){const d=await this.processor(l),u=(await this.model(d)).logits[0],f=Zn(ht(u.data),n).map(g=>({label:s[g[0]],score:g[1]}));n===1?o.push(...f):o.push(f)}return!r||n===1?o:o[0]}}class Kx extends Je{constructor(e){super(e)}async _call(e,n,{hypothesis_template:r="This is a sound of {}."}={}){const a=!Array.isArray(e);a&&(e=[e]);const i=n.map(c=>r.replace("{}",c)),s=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,l=await ii(e,o),d=[];for(const c of l){const u=await this.processor(c),h=await this.model({...s,...u}),f=ht(h.logits_per_audio.data);d.push([...f].map((g,w)=>({score:g,label:n[w]})))}return a?d[0]:d}}class Yx extends Je{constructor(e){super(e)}async _call(e,n={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,n);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,n);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,n={}){n.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),n.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const r=!Array.isArray(e);r&&(e=[e]);const a=this.processor.feature_extractor.config.sampling_rate,i=await ii(e,a),s=[];for(const o of i){const l=await this.processor(o),c=(await this.model(l)).logits[0],u=[];for(const f of c)u.push(Ot(f.data)[1]);const h=this.tokenizer.decode(u);s.push({text:h})}return r?s[0]:s}async _call_whisper(e,n={}){const r=n.return_timestamps??!1,a=n.chunk_length_s??0,i=n.chunk_callback??null,s=n.force_full_sequences??!1;let o=n.stride_length_s??null;r==="word"&&(n.return_token_timestamps=!0);const l=qo(n,"language",null),d=qo(n,"task",null);if(l||d||r){if(n.forced_decoder_ids)throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.");const b=this.tokenizer.get_decoder_prompt_ids({language:l,task:d,no_timestamps:!r});b.length>0&&(n.forced_decoder_ids=b)}const c=!Array.isArray(e);c&&(e=[e]);const u=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,h=this.processor.feature_extractor.config.hop_length,f=this.processor.feature_extractor.config.sampling_rate,g=await ii(e,f),w=[];for(const b of g){let y=[];if(a>0){if(o===null)o=a/6;else if(a<=o)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const S=f*a,T=f*o,A=S-2*T;let P=0;for(;P=b.length;y.push({stride:[N.length,j?0:T,M?0:T],input_features:V.input_features,is_last:M}),P+=A}}else y=[{stride:[b.length,0,0],input_features:(await this.processor(b)).input_features,is_last:!0}];for(const S of y){n.num_frames=Math.floor(S.stride[0]/h);const T=await this.model.generate(S.input_features,n);r==="word"?(S.tokens=T.sequences[0],S.token_timestamps=T.token_timestamps.tolist()[0].map(A=>Ar(A,2))):S.tokens=T[0],S.stride=S.stride.map(A=>A/f),i!==null&&i(S)}const[$,k]=this.tokenizer._decode_asr(y,{time_precision:u,return_timestamps:r,force_full_sequences:s});w.push({text:$,...k})}return c?w[0]:w}}class Xx extends Je{constructor(e){super(e)}async _call(e,n={}){const r=Array.isArray(e),a=await sn(e),{pixel_values:i}=await this.processor(a),s=[];for(const o of i){o.dims=[1,...o.dims];const l=await this.model.generate(o,n),d=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));s.push(d)}return r?s:s[0]}}class Qx extends Je{constructor(e){super(e)}async _call(e,{topk:n=1}={}){const r=Array.isArray(e),a=await sn(e),{pixel_values:i}=await this.processor(a),s=await this.model({pixel_values:i}),o=this.model.config.id2label,l=[];for(const d of s.logits){const u=Zn(ht(d.data),n).map(h=>({label:o[h[0]],score:h[1]}));n===1?l.push(...u):l.push(u)}return r||n===1?l:l[0]}}class Zx extends Je{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:n=.5,mask_threshold:r=.5,overlap_mask_area_threshold:a=.8,label_ids_to_fuse:i=null,target_sizes:s=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const d=await sn(e),c=d.map(y=>[y.height,y.width]),{pixel_values:u,pixel_mask:h}=await this.processor(d),f=await this.model({pixel_values:u,pixel_mask:h});let g=null;if(o!==null)g=this.subtasks_mapping[o];else for(let[y,$]of Object.entries(this.subtasks_mapping))if($ in this.processor.feature_extractor){g=this.processor.feature_extractor[$].bind(this.processor.feature_extractor),o=y;break}const w=this.model.config.id2label,b=[];if(o==="panoptic"||o==="instance"){const y=g(f,n,r,a,i,s??c)[0],$=y.segmentation;for(const k of y.segments_info){const S=new Uint8ClampedArray($.data.length);for(let A=0;A<$.data.length;++A)$.data[A]===k.id&&(S[A]=255);const T=new pt(S,$.dims[1],$.dims[0],1);b.push({score:k.score,label:w[k.label_id],mask:T})}}else if(o==="semantic"){const{segmentation:y,labels:$}=g(f,s??c)[0];for(const k of $){const S=new Uint8ClampedArray(y.data.length);for(let A=0;Ar.replace("{}",h)),o=this.tokenizer(s,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(i),d=await this.model({...o,pixel_values:l}),c=this.model.config.model_type==="siglip"?h=>h.sigmoid().data:h=>ht(h.data),u=[];for(const h of d.logits_per_image){const g=[...c(h)].map((w,b)=>({score:w,label:n[b]}));g.sort((w,b)=>b.score-w.score),u.push(g)}return a?u:u[0]}}class e3 extends Je{constructor(e){super(e)}async _call(e,{threshold:n=.9,percentage:r=!1}={}){const a=Array.isArray(e);if(a&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const i=await sn(e),s=r?null:i.map(f=>[f.height,f.width]),{pixel_values:o,pixel_mask:l}=await this.processor(i),d=await this.model({pixel_values:o,pixel_mask:l}),c=this.processor.feature_extractor.post_process_object_detection(d,n,s),u=this.model.config.id2label,h=c.map(f=>f.boxes.map((g,w)=>({score:f.scores[w],label:u[f.classes[w]],box:gg(g,!r)})));return a?h:h[0]}}class t3 extends Je{constructor(e){super(e)}async _call(e,n,{threshold:r=.1,topk:a=null,percentage:i=!1}={}){const s=Array.isArray(e),o=await sn(e),l=this.tokenizer(n,{padding:!0,truncation:!0}),d=await this.processor(o),c=[];for(let u=0;u({score:b.scores[k],label:n[b.classes[k]],box:gg($,!i)})).sort(($,k)=>k.score-$.score);a!==null&&(y=y.slice(0,a)),c.push(y)}return s?c:c[0]}}class n3 extends Je{constructor(e){super(e)}async _call(e,n,r={}){const a=(await sn(e))[0],{pixel_values:i}=await this.processor(a),s=`${n}`,o=this.tokenizer(s,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate(i,{...r,decoder_input_ids:o,max_length:this.model.config.decoder.max_position_embeddings}),c=this.tokenizer.batch_decode(l)[0].match(/(.*?)<\/s_answer>/);let u=null;return c&&c.length>=2&&(u=c[1].trim()),[{answer:u}]}}class r3 extends Je{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:n=null}={}){return this.processor?this._call_text_to_spectrogram(e,{speaker_embeddings:n}):this._call_text_to_waveform(e)}async _call_text_to_waveform(e){const n=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model(n),a=this.model.config.sampling_rate;return{audio:r.data,sampling_rate:a}}async _call_text_to_spectrogram(e,{speaker_embeddings:n}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Va.from_pretrained(this.DEFAULT_VOCODER_ID,{quantized:!1})),(typeof n=="string"||n instanceof URL)&&(n=new Float32Array(await(await fetch(n)).arrayBuffer())),n instanceof Float32Array)n=new ee("float32",n,[1,n.length]);else if(!(n instanceof ee))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:r}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:a}=await this.model.generate_speech(r,n,{vocoder:this.vocoder}),i=this.processor.feature_extractor.config.sampling_rate;return{audio:a.data,sampling_rate:i}}}class a3 extends Je{constructor(e){super(e)}async _call(e){const n=await sn(e),r=await this.processor(n),a=await this.model(r),i=[];for(const s of a.reconstruction){const o=s.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");i.push(pt.fromTensor(o))}return i.length>1?i:i[0]}}class i3 extends Je{constructor(e){super(e)}async _call(e){const n=await sn(e),r=await this.processor(n),{predicted_depth:a}=await this.model(r),i=[];for(let s=0;s1?i:i[0]}}const lc=Object.freeze({"text-classification":{tokenizer:lt,pipeline:Fx,model:rc,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:lt,pipeline:Lx,model:C1,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:lt,pipeline:Ux,model:z1,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:lt,pipeline:Wx,model:O1,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:lt,pipeline:Vx,model:hs,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:lt,pipeline:_g,model:hs,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:lt,pipeline:xo,model:hs,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:lt,pipeline:Gx,model:M1,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:lt,pipeline:Hx,model:rc,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:jx,model:U1,processor:bt,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:lt,pipeline:Kx,model:Va,processor:bt,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:lt,pipeline:Yx,model:[T1,L1],processor:bt,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:lt,pipeline:r3,model:[A1,I1],processor:[bt,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:lt,pipeline:Xx,model:R1,processor:bt,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Qx,model:B1,processor:bt,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Zx,model:[P1,D1],processor:bt,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:lt,pipeline:Jx,model:Va,processor:bt,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:e3,model:N1,processor:bt,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:lt,pipeline:t3,model:F1,processor:bt,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:lt,pipeline:n3,model:W1,processor:bt,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:a3,model:V1,processor:bt,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:i3,model:G1,processor:bt,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:lt,pipeline:qx,model:Va,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"}}),s3=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function o3(t,e=null,{quantized:n=!0,progress_callback:r=null,config:a=null,cache_dir:i=null,local_files_only:s=!1,revision:o="main",device:l=null,dtype:d=null,session_options:c={}}={}){t=s3[t]??t;const u=lc[t.split("_",1)[0]];if(!u)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(lc)}]`);e||(e=u.default.model,console.log(`No model specified. Using default model: "${e}".`));const h={quantized:n,progress_callback:r,config:a,cache_dir:i,local_files_only:s,revision:o,device:l,dtype:d,session_options:c},f=new Map([["tokenizer",u.tokenizer],["model",u.model],["processor",u.processor]]),g=await l3(f,e,h);g.task=t,Vn(r,{status:"ready",task:t,model:e});const w=u.pipeline;return new w(g)}async function l3(t,e,n){const r=Object.create(null),a=[];for(let[i,s]of t.entries()){if(!s)continue;let o;Array.isArray(s)?o=new Promise(async(l,d)=>{let c;for(let u of s){if(u===null){l(null);return}try{l(await u.from_pretrained(e,n));return}catch(h){if(h.message?.includes("Unsupported model type"))c=h;else{d(h);return}}}d(c)}):o=s.from_pretrained(e,n),r[i]=o,a.push(o)}await Promise.all(a);for(let[i,s]of Object.entries(r))r[i]=await s;return r}at.backends.onnx.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.1/dist/";at.backends.onnx.wasm.numThreads=1;const Ei=document.getElementById("status"),uc=document.getElementById("container"),wg=document.getElementById("overlay"),si=document.getElementById("canvas"),Tn=document.getElementById("video"),Bs=document.getElementById("threshold"),u3=document.getElementById("threshold-value"),Ps=document.getElementById("size"),d3=document.getElementById("size-value"),Ds=document.getElementById("scale"),c3=document.getElementById("scale-value");function yg(t,e){Tn.width=si.width=Math.round(t),Tn.height=si.height=Math.round(e)}Ei.textContent="Loading model...";async function p3(){try{return(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{return!1}}const h3=await p3()?"fp16":"fp32";let ua;try{ua=await o3("object-detection","Xenova/yolos-tiny",{device:"webgpu",dtype:h3})}catch(t){throw Ei.textContent=t.message,alert(t.message),t}let Ns=.7;Bs.addEventListener("input",()=>{Ns=Number(Bs.value),u3.textContent=Ns.toFixed(2)});Bs.disabled=!1;let Ga=256;ua.processor.feature_extractor.size={longest_edge:Ga};Ps.addEventListener("input",()=>{Ga=Number(Ps.value),ua.processor.feature_extractor.size={longest_edge:Ga},d3.textContent=Ga});Ps.disabled=!1;let qn=.5;Ds.addEventListener("input",()=>{qn=Number(Ds.value),yg(Tn.videoWidth*qn,Tn.videoHeight*qn),c3.textContent=qn});Ds.disabled=!1;Ei.textContent="Ready";const dc=["#EF4444","#4299E1","#059669","#FBBF24","#4B52B1","#7B3AC2","#ED507A","#1DD1A1","#F3873A","#4B5563","#DC2626","#1852B4","#18A35D","#F59E0B","#4059BE","#6027A5","#D63D60","#00AC9B","#E64A19","#272A34"];function f3({box:t,label:e,score:n}){const{xmax:r,xmin:a,ymax:i,ymin:s}=t,o=dc[ua.model.config.label2id[e]%dc.length],l=document.createElement("div");l.className="bounding-box",Object.assign(l.style,{borderColor:o,left:100*a+"%",top:100*s+"%",width:100*(r-a)+"%",height:100*(i-s)+"%"});const d=document.createElement("span");d.textContent=e,d.className="bounding-box-label",d.style.backgroundColor=o,l.appendChild(d),wg.appendChild(l)}let ms=!1,gs;const cc=si.getContext("2d",{willReadFrequently:!0});function bg(){const{width:t,height:e}=si;cc.drawImage(Tn,0,0,t,e),ms||(ms=!0,async function(){const n=cc.getImageData(0,0,t,e).data,r=new pt(n,t,e,4),a=await ua(r,{threshold:Ns,percentage:!0});if(wg.innerHTML="",a.forEach(f3),gs!==void 0){const i=1e3/(performance.now()-gs);Ei.textContent=`FPS: ${i.toFixed(2)}`}gs=performance.now(),ms=!1}()),window.requestAnimationFrame(bg)}navigator.mediaDevices.getUserMedia({video:!0}).then(t=>{Tn.srcObject=t,Tn.play();const e=t.getVideoTracks()[0],{width:n,height:r}=e.getSettings();yg(n*qn,r*qn);const a=n/r,[i,s]=a>720/405?[720,720/a]:[405*a,405];uc.style.width=`${i}px`,uc.style.height=`${s}px`,window.requestAnimationFrame(bg)}).catch(t=>{alert(t)});