diff --git "a/assets/worker-DVeN6rca.js" "b/assets/worker-DVeN6rca.js" new file mode 100644--- /dev/null +++ "b/assets/worker-DVeN6rca.js" @@ -0,0 +1,2623 @@ +var EC=Object.defineProperty;var TC=(ke,Wt,Nn)=>Wt in ke?EC(ke,Wt,{enumerable:!0,configurable:!0,writable:!0,value:Nn}):ke[Wt]=Nn;var A=(ke,Wt,Nn)=>TC(ke,typeof Wt!="symbol"?Wt+"":Wt,Nn);(function(){"use strict";var G_;var ke={},Wt=Object.freeze({__proto__:null,default:ke});const Nn="3.0.0-alpha.14",Qr=typeof self<"u",hy=Qr&&self.constructor.name==="DedicatedWorkerGlobalScope",Lo=Qr&&"caches"in self,fy=typeof navigator<"u"&&"gpu"in navigator,my=typeof navigator<"u"&&"ml"in navigator,Uo=typeof process<"u",gy=Uo&&((G_=process==null?void 0:process.release)==null?void 0:G_.name)==="node",Yr=!Go(ke),Vo=!Go(ke),bn=Object.freeze({IS_BROWSER_ENV:Qr,IS_WEBWORKER_ENV:hy,IS_WEB_CACHE_AVAILABLE:Lo,IS_WEBGPU_AVAILABLE:fy,IS_WEBNN_AVAILABLE:my,IS_PROCESS_AVAILABLE:Uo,IS_NODE_ENV:gy,IS_FS_AVAILABLE:Yr,IS_PATH_AVAILABLE:Vo}),da=Yr&&Vo,jo=da?ke.dirname(ke.dirname(ke.fileURLToPath(self.location.href))):"./",_y=da?ke.join(jo,"/.cache/"):null,qo="/models/",wy=da?ke.join(jo,qo):qo,tt={version:Nn,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Qr,localModelPath:wy,useFS:Yr,useBrowserCache:Lo,useFSCache:Yr,cacheDir:_y,useCustomCache:!1,customCache:null};function Go(t){return Object.keys(t).length===0}const Ye=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 Ln(t,e){t&&t(e)}function yy(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e]))}function Wo(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function by(t){return Number.isInteger(t)||typeof t=="bigint"}function Ho(t){const e=[];let n=t;for(;Array.isArray(n);)e.push(n.length),n=n[0];return e}function We(...t){return Array.prototype.concat.apply([],t)}function vy(...t){return t.reduce((e,n)=>e.flatMap(r=>n.map(s=>[r,s])))}function Zr(t,e){return Math.abs((t+e)%(2*e)-e)}function Ht(t,e){return Object.assign({},...e.map(n=>{if(t[n]!==void 0)return{[n]:t[n]}}))}var Kt={};const xy={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"};class Jr{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=ke.existsSync(e),this.exists){this.status=200,this.statusText="OK";let n=ke.statSync(e);this.headers.set("content-length",n.size.toString()),this.updateContentType();let r=this;this.body=new ReadableStream({start(s){r.arrayBuffer().then(i=>{s.enqueue(new Uint8Array(i)),s.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",xy[e]??"application/octet-stream")}clone(){let e=new Jr(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 ke.promises.readFile(this.filePath)).buffer}async blob(){const e=await ke.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await ke.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function ca(t,e=null,n=null){let r;try{r=new URL(t)}catch{return!1}return!(e&&!e.includes(r.protocol)||n&&!n.includes(r.hostname))}async function es(t){var e;if(tt.useFS&&!ca(t,["http:","https:","blob:"]))return new Jr(t);if(typeof process<"u"&&((e=process==null?void 0:process.release)==null?void 0:e.name)==="node"){const n=!!(Kt!=null&&Kt.TESTING_REMOTELY),r=tt.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${r}; is_ci/${n};`),ca(t,["http:","https:"],["huggingface.co","hf.co"])){const a=(Kt==null?void 0:Kt.HF_TOKEN)??(Kt==null?void 0:Kt.HF_ACCESS_TOKEN);a&&s.set("Authorization",`Bearer ${a}`)}return fetch(t,{headers:s})}else return fetch(t)}const $y={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 ky(t,e,n){if(!n)return null;const r=$y[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=ke.join(this.path,e),r=new Jr(n);if(r.exists)return r}async put(e,n){const r=Buffer.from(await n.arrayBuffer());let s=ke.join(this.path,e);try{await ke.promises.mkdir(ke.dirname(s),{recursive:!0}),await ke.promises.writeFile(s,r)}catch(i){console.warn("An error occurred while writing the file to cache:",i)}}}async function Sy(t,...e){for(let n of e)try{let r=await t.match(n);if(r)return r}catch{continue}}async function ts(t,e,n=!0,r={}){if(!tt.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`).");Ln(r.progress_callback,{status:"initiate",name:t,file:e});let s;if(!s&&tt.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{s=await caches.open("transformers-cache")}catch(v){console.warn("An error occurred while opening the browser cache:",v)}}if(!s&&tt.useFSCache&&(s=new Ko(r.cache_dir??tt.cacheDir)),!s&&tt.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const i=r.revision??"main";let a=ns(t,e),o=ns(tt.localModelPath,a),l=ns(tt.remoteHost,tt.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(i)),e),u=i==="main"?a:ns(t,i,e),c,p=s instanceof Ko?u:l,d=!1,f;s&&(f=await Sy(s,o,p));const m=f!==void 0;if(f===void 0){if(tt.allowLocalModels)if(ca(a,["http:","https:"])){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`)}else try{f=await es(o),c=o}catch(y){console.warn(`Unable to load from local path "${o}": "${y}"`)}if(f===void 0||f.status===404){if(r.local_files_only||!tt.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 es(l),f.status!==200)return ky(f.status,l,n);c=p}d=s&&typeof Response<"u"&&f instanceof Response&&f.status===200}Ln(r.progress_callback,{status:"download",name:t,file:e});const g={status:"progress",name:t,file:e};let w;return r.progress_callback?m&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(w=new Uint8Array(await f.arrayBuffer()),Ln(r.progress_callback,{...g,progress:100,loaded:w.length,total:w.length})):w=await Ey(f,v=>{Ln(r.progress_callback,{...g,...v})}):w=new Uint8Array(await f.arrayBuffer()),d&&c&&await s.match(c)===void 0&&await s.put(c,new Response(w,{headers:f.headers})).catch(v=>{console.warn(`Unable to add response to browser cache: ${v}.`)}),Ln(r.progress_callback,{status:"done",name:t,file:e}),w}async function tn(t,e,n=!0,r={}){let s=await ts(t,e,n,r);if(s===null)return{};let a=new TextDecoder("utf-8").decode(s);return JSON.parse(a)}async function Ey(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"),s=new Uint8Array(r),i=0;const a=t.body.getReader();async function o(){const{done:l,value:u}=await a.read();if(l)return;let c=i+u.length;if(c>r){r=c;let d=new Uint8Array(r);d.set(s),s=d}s.set(u,i),i=c;const p=i/r*100;return e({progress:p,loaded:i,total:r}),o()}return await o(),s}function ns(...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 Ty(t,[e,n,r],[s,i],a="bilinear",o=!1){const l=i/r,u=s/n,c=new t.constructor(s*i*e),p=n*r,d=s*i;for(let f=0;f=0;--o)s[o]=l,r[o]=e[n[o]],l*=r[o];const i=n.map((o,l)=>s[n.indexOf(l)]),a=new t.constructor(t.length);for(let o=0;o=0;--u)l+=c%e[u]*i[u],c=Math.floor(c/e[u]);a[l]=t[o]}return[a,r]}function He(t){const e=dt(t)[0],n=t.map(i=>Math.exp(i-e)),r=n.reduce((i,a)=>i+a,0);return n.map(i=>i/r)}function Cy(t){return He(t).map(r=>Math.log(r))}function Xo(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 Qo(t){return t>0&&(t&t-1)===0}class Yo{constructor(e){if(this.size=e|0,this.size<=1||!Qo(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<>>s&3)<>>1);for(let s=0;s>>1]=e[s];return r}toComplexArray(e,n){const r=n||this.createComplexArray();for(let s=0;s>>1],r[s+1]=0;return r}transform(e,n){if(e===n)throw new Error("Input and output buffers must be different");this._transform4(e,n,1)}realTransform(e,n){if(e===n)throw new Error("Input and output buffers must be different");this._realTransform4(e,n,1)}inverseTransform(e,n){if(e===n)throw new Error("Input and output buffers must be different");this._transform4(e,n,-1);for(let r=0;r>=2;a>=2;a>>=2){o=s/a<<1;const d=o>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,u=0;l>>1,a>>>1,r)}const p=this.table;for(a>>=2;a>=2;a>>=2){o=s/a<<1;const f=o>>>1,m=f>>>1,g=m>>>1;for(l=0;l>>1;for(let f=2;f>1;++c){const p=(c+1-e)**2/2,d=Math.sqrt(l**2+u**2)**p,f=p*Math.atan2(u,l),m=2*c;i[m]=d*Math.cos(f),i[m+1]=d*Math.sin(f),a[m]=i[m],a[m+1]=-i[m+1]}this._slicedChirpBuffer=i.subarray(n,r),this._f=new Yo(s>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,n,r){const s=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,l=this._chirpBuffer,u=this._slicedChirpBuffer,c=this._a;if(r)for(let p=0;p>1,m=n[f];s[p]=m*u[p],s[d]=m*u[d]}else for(let p=0;p=t.length&&(l=2*(t.length-1)-l),r[a++]=t[l]}r.sort(),n[i]=r[s]}return n}function ur(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}function Oy(t){const e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function Py(t){const e=t.length,n=t[0].length,r=[e+1,n+1],s=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));s[0][0]=0;const i=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let c=1;c0||o>0;)switch(l.push(a-1),u.push(o-1),i[a][o]){case 0:--a,--o;break;case 1:--a;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${o}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}/*! + * ONNX Runtime Web v1.20.0-dev.20240827-1d059b8702 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var pa=Object.defineProperty,By=Object.getOwnPropertyDescriptor,Ry=Object.getOwnPropertyNames,Fy=Object.prototype.hasOwnProperty,Dy=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),W=(t,e)=>()=>(t&&(e=t(t=0)),e),dr=(t,e)=>{for(var n in e)pa(t,n,{get:e[n],enumerable:!0})},Ny=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ry(e))!Fy.call(t,s)&&s!==n&&pa(t,s,{get:()=>e[s],enumerable:!(r=By(e,s))||r.enumerable});return t},rs=t=>Ny(pa({},"__esModule",{value:!0}),t),cr,nn,vn,Zo,ha,fa=W(()=>{cr=new Map,nn=[],vn=(t,e,n)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let r=cr.get(t);if(r===void 0)cr.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 s=nn.indexOf(t);s!==-1&&nn.splice(s,1);for(let i=0;i{let e=cr.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let n=!!e.initPromise;try{return n||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(r){return n||(e.error=`${r}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},ha=async t=>{let e=t.executionProviders||[],n=e.map(l=>typeof l=="string"?l:l.name),r=n.length===0?nn:n,s,i=[],a=new Set;for(let l of r){let u=await Zo(l);typeof u=="string"?i.push({name:l,err:u}):(s||(s=u),s===u&&a.add(l))}if(!s)throw new Error(`no available backend found. ERR: ${i.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of i)n.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let o=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[s,new Proxy(t,{get:(l,u)=>u==="executionProviders"?o:Reflect.get(l,u)})]}}),Ly=W(()=>{fa()}),Jo,Uy=W(()=>{Jo="1.20.0-dev.20240827-5d54dc1462"}),ma,gt,el=W(()=>{Uy(),ma="warning",gt={wasm:{},webgl:{},webgpu:{},versions:{common:Jo},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}`);ma=t}},get logLevel(){return ma}},Object.defineProperty(gt,"logLevel",{enumerable:!0})}),Te,Vy=W(()=>{el(),Te=gt}),tl,nl,jy=W(()=>{tl=(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 s,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[3]):(s=t.dims[3],i=t.dims[2]);let a=(e==null?void 0:e.format)!==void 0?e.format:"RGB",o=e==null?void 0:e.norm,l,u;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?u=[0,0,0,0]:typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:(u=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(u[3]=o.bias[3]));let c=i*s,p=0,d=c,f=c*2,m=-1;a==="RGBA"?(p=0,d=c,f=c*2,m=c*3):a==="RGB"?(p=0,d=c,f=c*2):a==="RBG"&&(p=0,f=c,d=c*2);for(let g=0;g{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(n!=null){let s,i,a;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[1],a=t.dims[3]):(s=t.dims[3],i=t.dims[2],a=t.dims[1]);let o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e==null?void 0:e.norm,u,c;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 p=i*s;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,f=0,m=1,g=2,w=3,v=0,y=p,$=p*2,k=-1;o==="RGBA"?(v=0,y=p,$=p*2,k=p*3):o==="RGB"?(v=0,y=p,$=p*2):o==="RBG"&&(v=0,$=p,y=p*2),r=n.createImageData(s,i);for(let E=0;E{_a(),ss=(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,s=e.norm??{mean:255,bias:0},i,a;typeof s.mean=="number"?i=[s.mean,s.mean,s.mean,s.mean]:i=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?a=[s.bias,s.bias,s.bias,s.bias]:a=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=n*r,c=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),p=4,d=0,f=1,m=2,g=3,w=0,v=u,y=u*2,$=-1;o==="RGB"&&(p=3,d=0,f=1,m=2,g=-1),l==="RGBA"?$=u*3:l==="RBG"?(w=0,y=u,v=u*2):l==="BGR"&&(y=0,v=u,w=u*2);for(let k=0;k{let n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,r=typeof ImageData<"u"&&t instanceof ImageData,s=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,i=typeof t=="string",a,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")},u=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 p=u(c);if(p!=null){let d=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(d=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=d,o.width=f}else o.tensorFormat="RGBA",o.height=d,o.width=f;p.drawImage(t,0,0),a=p.getImageData(0,0,f,d).data}else throw new Error("Can not access image data")}else if(r){let c,p;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,p=e.resizedWidth):(c=t.height,p=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=c,o.width=p,e!==void 0){let d=l();d.width=p,d.height=c;let f=u(d);if(f!=null)f.putImageData(t,0,0),a=f.getImageData(0,0,p,c).data;else throw new Error("Can not access image data")}else a=t.data}else if(s){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 p=u(c);if(p!=null){let d=t.height,f=t.width;return p.drawImage(t,0,0,f,d),a=p.getImageData(0,0,f,d).data,o.height=d,o.width=f,ss(a,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((c,p)=>{let d=l(),f=u(d);if(!t||!f)return p();let m=new Image;m.crossOrigin="Anonymous",m.src=t,m.onload=()=>{d.width=m.width,d.height=m.height,f.drawImage(m,0,0,d.width,d.height);let g=f.getImageData(0,0,d.width,d.height);o.height=d.height,o.width=d.width,c(ss(g.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return ss(a,o);throw new Error("Input data provided is not supported - aborted tensor creation")},sl=(t,e)=>{let{width:n,height:r,download:s,dispose:i}=e,a=[1,r,n,4];return new kt({location:"texture",type:"float32",texture:t,dims:a,download:s,dispose:i})},al=(t,e)=>{let{dataType:n,dims:r,download:s,dispose:i}=e;return new kt({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:s,dispose:i})},il=(t,e,n)=>new kt({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]})}),xn,pr,ga,ol,Gy=W(()=>{xn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),pr=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ga=!1,ol=()=>{if(!ga){ga=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,n=typeof Float16Array<"u"&&Float16Array.from;t&&(xn.set("int64",BigInt64Array),pr.set(BigInt64Array,"int64")),e&&(xn.set("uint64",BigUint64Array),pr.set(BigUint64Array,"uint64")),n?(xn.set("float16",Float16Array),pr.set(Float16Array,"float16")):xn.set("float16",Uint16Array)}}}),ll,ul,Wy=W(()=>{_a(),ll=t=>{let e=1;for(let n=0;n{switch(t.location){case"cpu":return new kt(t.type,t.data,e);case"cpu-pinned":return new kt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new kt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new kt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),kt,_a=W(()=>{jy(),qy(),Gy(),Wy(),kt=class{constructor(t,e,n){ol();let r,s;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,r=t.type,s=t.dims,t.location){case"cpu-pinned":{let a=xn.get(r);if(!a)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.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!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")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 a,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.");a=e}else{let l=xn.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=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",a=t;else if(l==="boolean")r="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else{let l=pr.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);r=l,a=t}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");s=o,this.cpuData=a,this.dataLocation="cpu"}let i=ll(s);if(this.cpuData&&i!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=s,this.size=i}static async fromImage(t,e){return rl(t,e)}static fromTexture(t,e){return sl(t,e)}static fromGpuBuffer(t,e){return al(t,e)}static fromPinnedBuffer(t,e,n){return il(t,e,n)}toDataURL(t){return tl(this,t)}toImageData(t){return nl(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 ul(this,t)}}}),nt,wa=W(()=>{_a(),nt=kt}),hr,ya,St,_t,dl=W(()=>{el(),hr=(t,e)=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||console.timeStamp(`${t}::ORT::${e}`)},ya=(t,e)=>{var s;let n=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],r=!1;for(let i=0;i{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||ya("BEGIN",t)},_t=t=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||ya("END",t)}}),cl,Hy=W(()=>{fa(),wa(),dl(),cl=class dy{constructor(e){this.handler=e}async run(e,n,r){St();let s={},i={};if(typeof e!="object"||e===null||e instanceof nt||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof nt)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.");a=!1;for(let u of n){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);s[u]=null}if(typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,c=Object.getOwnPropertyNames(n);for(let p of this.outputNames)if(c.indexOf(p)!==-1){let d=n[p];(d===null||d instanceof nt)&&(u=!0,a=!1,s[p]=d)}if(u){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 u of this.inputNames)if(typeof e[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(a)for(let u of this.outputNames)s[u]=null;let o=await this.handler.run(e,s,i),l={};for(let u in o)if(Object.hasOwnProperty.call(o,u)){let c=o[u];c instanceof nt?l[u]=c:l[u]=new nt(c.type,c.data,c.dims)}return _t(),l}async release(){return this.handler.dispose()}static async create(e,n,r,s){St();let i,a={};if(typeof e=="string"){if(i=e,typeof n=="object"&&n!==null)a=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)a=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 c=e,p=0,d=e.byteLength;if(typeof n=="object"&&n!==null)a=n;else if(typeof n=="number"){if(p=n,!Number.isSafeInteger(p))throw new RangeError("'byteOffset' must be an integer.");if(p<0||p>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.byteLength}).`);if(d=e.byteLength-p,typeof r=="number"){if(d=r,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||p+d>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.byteLength-p}].`);if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"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(c,p,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await ha(a),u=await o.createInferenceSessionHandler(i,l);return _t(),new dy(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ba,Ky=W(()=>{Hy(),ba=cl}),Xy=W(()=>{}),Qy=W(()=>{}),Yy=W(()=>{}),Zy=W(()=>{}),pl,hl,Jy=W(()=>{fa(),wa(),pl="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",hl=class cy{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||"",s=e.optimizerModel||"",i=n||{},[a,o]=await ha(i);if(a.createTrainingSessionHandler){let l=await a.createTrainingSessionHandler(e.checkpointState,e.trainModel,r,s,o);return new cy(l,!!e.optimizerModel,!!e.evalModel)}else throw new Error(pl)}typeNarrowingForRunStep(e,n,r,s,i){let a={},o={};if(typeof r!="object"||r===null||r instanceof nt||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 s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof nt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(let u of s){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(n.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);a[u]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,c=Object.getOwnPropertyNames(s);for(let p of n)if(c.indexOf(p)!==-1){let d=s[p];(d===null||d instanceof nt)&&(u=!0,l=!1,a[p]=d)}if(u){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of e)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(l)for(let u of n)a[u]=null;return[a,o]}convertHandlerReturnTypeToMapOfTensors(e){let n={};for(let r in e)if(Object.hasOwnProperty.call(e,r)){let s=e[r];s instanceof nt?n[r]=s:n[r]=new nt(s.type,s.data,s.dims)}return n}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,n,r){let[s,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,n,r),a=await this.handler.runTrainStep(e,s,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}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[s,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,n,r),a=await this.handler.runEvalStep(e,s,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}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()}}}),va,e0=W(()=>{Jy(),va=hl}),fl={};dr(fl,{InferenceSession:()=>ba,TRACE:()=>hr,TRACE_FUNC_BEGIN:()=>St,TRACE_FUNC_END:()=>_t,Tensor:()=>nt,TrainingSession:()=>va,env:()=>Te,registerBackend:()=>vn});var Et=W(()=>{Ly(),Vy(),Ky(),wa(),Xy(),Qy(),dl(),Yy(),Zy(),e0()}),xa=W(()=>{}),ml={};dr(ml,{default:()=>gl});var $a,ka,gl,t0=W(()=>{var t;$f(),Vn(),as(),$a="ort-wasm-proxy-worker",ka=((t=globalThis.self)==null?void 0:t.name)===$a,ka&&(self.onmessage=e=>{let{type:n,in:r}=e.data;try{switch(n){case"init-wasm":Aa(r.wasm).then(()=>{Ii(r).then(()=>{postMessage({type:n})},s=>{postMessage({type:n,err:s})})},s=>{postMessage({type:n,err:s})});break;case"init-ep":{let{epName:s,env:i}=r;zi(i,s).then(()=>{postMessage({type:n})},a=>{postMessage({type:n,err:a})});break}case"copy-from":{let{buffer:s}=r,i=Es(s);postMessage({type:n,out:i});break}case"create":{let{model:s,options:i}=r;Oi(s,i).then(a=>{postMessage({type:n,out:a})},a=>{postMessage({type:n,err:a})});break}case"release":Pi(r),postMessage({type:n});break;case"run":{let{sessionId:s,inputIndices:i,inputs:a,outputIndices:o,options:l}=r;Ri(s,i,a,o,new Array(o.length).fill(null),l).then(u=>{u.some(c=>c[3]!=="cpu")?postMessage({type:n,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:n,out:u},Di([...a,...u]))},u=>{postMessage({type:n,err:u})});break}case"end-profiling":Fi(r),postMessage({type:n});break;default:}}catch(s){postMessage({type:n,err:s})}}),gl=ka?null:e=>new Worker(e??Un,{type:"module",name:$a})}),_l={};dr(_l,{default:()=>wl});var Sa,Ea,wl,n0=W(()=>{var t;Ea=(Sa=self.location.href,async function(e={}){function n(){return I.buffer!=Y.buffer&&Oe(),Y}function r(){return I.buffer!=Y.buffer&&Oe(),te}function s(){return I.buffer!=Y.buffer&&Oe(),O}function i(){return I.buffer!=Y.buffer&&Oe(),q}function a(){return I.buffer!=Y.buffer&&Oe(),ie}function o(){return I.buffer!=Y.buffer&&Oe(),ge}function l(){return I.buffer!=Y.buffer&&Oe(),xe}function u(){return I.buffer!=Y.buffer&&Oe(),Ot}var c,p,d=Object.assign({},e),f=new Promise((h,_)=>{c=h,p=_}),m=typeof window=="object",g=typeof importScripts=="function",w=g&&self.name=="em-pthread";d.mountExternalData=(h,_)=>{h.startsWith("./")&&(h=h.substring(2)),(d.Fb||(d.Fb=new Map)).set(h,_)},d.unmountExternalData=()=>{delete d.Fb};var v=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let y=()=>{let h=(b,x,S)=>(...M)=>{let F=qt,V=x==null?void 0:x();M=b(...M);let Q=x==null?void 0:x();return V!==Q&&(b=Q,S(V),x=S=null),qt!=F?new Promise((Z,le)=>{zo={resolve:Z,reject:le}}):M},_=b=>async(...x)=>{var S;try{if(d.Eb)throw Error("Session already started");let M=d.Eb={bc:x[0],errors:[]},F=await b(...x);if(d.Eb!==M)throw Error("Session mismatch");(S=d.Mb)==null||S.flush();let V=M.errors;if(0Z),0d._OrtCreateSession,b=>d._OrtCreateSession=b),d._OrtRun=_(h(d._OrtRun,()=>d._OrtRun,b=>d._OrtRun=b)),d._OrtRunWithBinding=_(h(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,b=>d._OrtRunWithBinding=b)),d._OrtBindInput=h(d._OrtBindInput,()=>d._OrtBindInput,b=>d._OrtBindInput=b),y=void 0};d.jsepInit=(h,_)=>{if(y==null||y(),h==="webgpu"){[d.Mb,d.Tb,d.Xb,d.Nb,d.Wb,d.jb,d.Yb,d.$b,d.Ub,d.Vb,d.Zb]=_;let b=d.Mb;d.jsepRegisterBuffer=(x,S,M,F)=>b.registerBuffer(x,S,M,F),d.jsepGetBuffer=x=>b.getBuffer(x),d.jsepCreateDownloader=(x,S,M)=>b.createDownloader(x,S,M),d.jsepOnReleaseSession=x=>{b.onReleaseSession(x)},d.jsepOnRunStart=x=>b.onRunStart(x)}};var $,k,E=Object.assign({},d),T="./this.program",C=(h,_)=>{throw _},B="";(m||g)&&(g?B=self.location.href:typeof document<"u"&&document.currentScript&&(B=document.currentScript.src),Sa&&(B=Sa),B=B.startsWith("blob:")?"":B.substr(0,B.replace(/[?#].*/,"").lastIndexOf("/")+1),g&&(k=h=>{var _=new XMLHttpRequest;return _.open("GET",h,!1),_.responseType="arraybuffer",_.send(null),new Uint8Array(_.response)}),$=(h,_,b)=>{var x=new XMLHttpRequest;x.open("GET",h,!0),x.responseType="arraybuffer",x.onload=()=>{x.status==200||x.status==0&&x.response?_(x.response):b()},x.onerror=b,x.send(null)});var U,G=console.log.bind(console),K=console.error.bind(console),X=G,H=K;if(Object.assign(d,E),E=null,w){let h=function(_){try{var b=_.data,x=b.cmd;if(x==="load"){let S=[];self.onmessage=M=>S.push(M),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let M of S)h(M);self.onmessage=h};for(let M of b.handlers)d[M]&&!d[M].proxy||(d[M]=(...F)=>{postMessage({Lb:"callHandler",kc:M,args:F})},M=="print"&&(X=d[M]),M=="printErr"&&(H=d[M]));I=b.wasmMemory,Oe(),J(b.wasmModule)}else if(x==="run"){Ro(b.pthread_ptr,0,0,1,0,0),Co(b.pthread_ptr),cM(),tw(),ne||(Zw(),ne=!0);try{pM(b.start_routine,b.arg)}catch(S){if(S!="unwind")throw S}}else x==="cancel"?lr()&&oa(-1):b.target!=="setimmediate"&&(x==="checkMailbox"?ne&&Zs():x&&(H(`worker: received unknown command ${x}`),H(b)))}catch(S){throw Jw(),S}};var J,ne=!1;H=function(..._){_=_.join(" "),console.error(_)},self.alert=function(..._){postMessage({Lb:"alert",text:_.join(" "),mc:lr()})},d.instantiateWasm=(_,b)=>new Promise(x=>{J=S=>{S=new WebAssembly.Instance(S,Q_()),b(S),x()}}),self.onunhandledrejection=_=>{throw _.reason||_},self.onmessage=h}d.wasmBinary&&(U=d.wasmBinary);var I,N,R,Y,te,O,q,ie,ge,xe,Ee,ut,Ot,Ne=!1;function Oe(){var h=I.buffer;d.HEAP8=Y=new Int8Array(h),d.HEAP16=O=new Int16Array(h),d.HEAPU8=te=new Uint8Array(h),d.HEAPU16=q=new Uint16Array(h),d.HEAP32=ie=new Int32Array(h),d.HEAPU32=ge=new Uint32Array(h),d.HEAPF32=xe=new Float32Array(h),d.HEAPF64=Ot=new Float64Array(h),d.HEAP64=Ee=new BigInt64Array(h),d.HEAPU64=ut=new BigUint64Array(h)}if(!w){if(!((I=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof v))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"),Error("bad memory");Oe()}var Pt=[],De=[],Ve=[],it=0,Bt=null;function Bn(){if(--it==0&&Bt){var h=Bt;Bt=null,h()}}function Zt(h){throw H(h="Aborted("+h+")"),Ne=!0,R=1,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),p(h),h}var _o,W_=h=>h.startsWith("data:application/octet-stream;base64,"),H_=h=>h.startsWith("file://");function K_(h){if(h==_o&&U)return new Uint8Array(U);if(k)return k(h);throw"both async and sync fetching of the wasm failed"}function X_(h,_,b){return function(x){if(!U&&(m||g)){if(typeof fetch=="function"&&!H_(x))return fetch(x,{credentials:"same-origin"}).then(S=>{if(!S.ok)throw`failed to load wasm binary file at '${x}'`;return S.arrayBuffer()}).catch(()=>K_(x));if($)return new Promise((S,M)=>{$(x,F=>S(new Uint8Array(F)),M)})}return Promise.resolve().then(()=>K_(x))}(h).then(x=>WebAssembly.instantiate(x,_)).then(b,x=>{H(`failed to asynchronously prepare wasm: ${x}`),Zt(x)})}function Q_(){return{a:{M:dM,za:uM,b:fM,$:aw,z:lw,pa:uw,X:cw,Z:pw,qa:hw,na:fw,ga:mw,ma:gw,J:_w,Y:ww,V:yw,oa:bw,W:vw,va:mM,D:gM,P:_M,O:yM,C:vM,s:xM,p:$M,E:kM,y:IM,Q:zM,ta:OM,ja:PM,T:BM,aa:RM,F:FM,ia:Co,sa:DM,u:NM,B:VM,o:jM,m:GM,c:To,n:WM,k:XM,Aa:QM,r:YM,g:ZM,v:JM,l:eC,f:tC,i:nC,j:rC,h:sC,e:aC,da:iC,ea:oC,fa:lC,ba:Bw,ca:Rw,S:uC,d:dC,N:cC,G:pC,K:hC,w:fC,ra:mC,U:gC,t:Dw,x:_C,L:wC,R:yC,ya:bC,xa:vC,ka:Uw,la:Vw,_:xo,A:jw,I:qw,ha:Gw,H:Ww,a:I,wa:vo,ua:Xw,q:kC}}}var wo={858916:(h,_,b,x)=>{if(d===void 0||!d.Fb)return 1;if((h=Ge(h>>>0)).startsWith("./")&&(h=h.substring(2)),!(h=d.Fb.get(h)))return 2;if(x>>>=0,(_>>>=0)+(b>>>=0)>h.byteLength)return 3;try{return r().set(h.subarray(_,_+b),x>>>0),0}catch{return 4}},859417:()=>{d.Ub()},859448:()=>{d.Vb()},859477:()=>{d.Zb()},859502:h=>d.Tb(h),859535:h=>d.Xb(h),859567:(h,_,b)=>{d.Nb(h,_,b,!0)},859606:(h,_,b)=>{d.Nb(h,_,b)},859639:()=>typeof wasmOffsetConverter<"u",859696:h=>{d.jb("Abs",h,void 0)},859747:h=>{d.jb("Neg",h,void 0)},859798:h=>{d.jb("Floor",h,void 0)},859851:h=>{d.jb("Ceil",h,void 0)},859903:h=>{d.jb("Reciprocal",h,void 0)},859961:h=>{d.jb("Sqrt",h,void 0)},860013:h=>{d.jb("Exp",h,void 0)},860064:h=>{d.jb("Erf",h,void 0)},860115:h=>{d.jb("Sigmoid",h,void 0)},860170:(h,_,b)=>{d.jb("HardSigmoid",h,{alpha:_,beta:b})},860249:h=>{d.jb("Log",h,void 0)},860300:h=>{d.jb("Sin",h,void 0)},860351:h=>{d.jb("Cos",h,void 0)},860402:h=>{d.jb("Tan",h,void 0)},860453:h=>{d.jb("Asin",h,void 0)},860505:h=>{d.jb("Acos",h,void 0)},860557:h=>{d.jb("Atan",h,void 0)},860609:h=>{d.jb("Sinh",h,void 0)},860661:h=>{d.jb("Cosh",h,void 0)},860713:h=>{d.jb("Asinh",h,void 0)},860766:h=>{d.jb("Acosh",h,void 0)},860819:h=>{d.jb("Atanh",h,void 0)},860872:h=>{d.jb("Tanh",h,void 0)},860924:h=>{d.jb("Not",h,void 0)},860975:(h,_,b)=>{d.jb("Clip",h,{min:_,max:b})},861044:h=>{d.jb("Clip",h,void 0)},861096:(h,_)=>{d.jb("Elu",h,{alpha:_})},861154:h=>{d.jb("Gelu",h,void 0)},861206:h=>{d.jb("Relu",h,void 0)},861258:(h,_)=>{d.jb("LeakyRelu",h,{alpha:_})},861322:(h,_)=>{d.jb("ThresholdedRelu",h,{alpha:_})},861392:(h,_)=>{d.jb("Cast",h,{to:_})},861450:h=>{d.jb("Add",h,void 0)},861501:h=>{d.jb("Sub",h,void 0)},861552:h=>{d.jb("Mul",h,void 0)},861603:h=>{d.jb("Div",h,void 0)},861654:h=>{d.jb("Pow",h,void 0)},861705:h=>{d.jb("Equal",h,void 0)},861758:h=>{d.jb("Greater",h,void 0)},861813:h=>{d.jb("GreaterOrEqual",h,void 0)},861875:h=>{d.jb("Less",h,void 0)},861927:h=>{d.jb("LessOrEqual",h,void 0)},861986:(h,_,b,x,S)=>{d.jb("ReduceMean",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},862145:(h,_,b,x,S)=>{d.jb("ReduceMax",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},862303:(h,_,b,x,S)=>{d.jb("ReduceMin",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},862461:(h,_,b,x,S)=>{d.jb("ReduceProd",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},862620:(h,_,b,x,S)=>{d.jb("ReduceSum",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},862778:(h,_,b,x,S)=>{d.jb("ReduceL1",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},862935:(h,_,b,x,S)=>{d.jb("ReduceL2",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},863092:(h,_,b,x,S)=>{d.jb("ReduceLogSum",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},863253:(h,_,b,x,S)=>{d.jb("ReduceSumSquare",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},863417:(h,_,b,x,S)=>{d.jb("ReduceLogSumExp",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},863581:h=>{d.jb("Where",h,void 0)},863634:(h,_,b)=>{d.jb("Transpose",h,{perm:_?Array.from(a().subarray(_>>>0,b>>>0)):[]})},863742:(h,_,b,x)=>{d.jb("DepthToSpace",h,{blocksize:_,mode:Ge(b),format:x?"NHWC":"NCHW"})},863875:(h,_,b,x)=>{d.jb("DepthToSpace",h,{blocksize:_,mode:Ge(b),format:x?"NHWC":"NCHW"})},864008:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P,_e)=>{d.jb("ConvTranspose",h,{format:Q?"NHWC":"NCHW",autoPad:_,dilations:[b],group:x,kernelShape:[S],pads:[M,F],strides:[V],wIsConst:()=>!!n()[Z>>>0],outputPadding:le?Array.from(a().subarray(le>>>0,we>>>0)):[],outputShape:be?Array.from(a().subarray(be>>>0,P>>>0)):[],activation:Ge(_e)})},864409:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P)=>{d.jb("ConvTranspose",h,{format:V?"NHWC":"NCHW",autoPad:_,dilations:Array.from(a().subarray(b>>>0,2+(b>>>0)>>>0)),group:x,kernelShape:Array.from(a().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(a().subarray(M>>>0,4+(M>>>0)>>>0)),strides:Array.from(a().subarray(F>>>0,2+(F>>>0)>>>0)),wIsConst:()=>!!n()[Q>>>0],outputPadding:Z?Array.from(a().subarray(Z>>>0,le>>>0)):[],outputShape:we?Array.from(a().subarray(we>>>0,be>>>0)):[],activation:Ge(P)})},864974:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P,_e)=>{d.jb("ConvTranspose",h,{format:Q?"NHWC":"NCHW",autoPad:_,dilations:[b],group:x,kernelShape:[S],pads:[M,F],strides:[V],wIsConst:()=>!!n()[Z>>>0],outputPadding:le?Array.from(a().subarray(le>>>0,we>>>0)):[],outputShape:be?Array.from(a().subarray(be>>>0,P>>>0)):[],activation:Ge(_e)})},865375:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P)=>{d.jb("ConvTranspose",h,{format:V?"NHWC":"NCHW",autoPad:_,dilations:Array.from(a().subarray(b>>>0,2+(b>>>0)>>>0)),group:x,kernelShape:Array.from(a().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(a().subarray(M>>>0,4+(M>>>0)>>>0)),strides:Array.from(a().subarray(F>>>0,2+(F>>>0)>>>0)),wIsConst:()=>!!n()[Q>>>0],outputPadding:Z?Array.from(a().subarray(Z>>>0,le>>>0)):[],outputShape:we?Array.from(a().subarray(we>>>0,be>>>0)):[],activation:Ge(P)})},865940:(h,_)=>{d.jb("GlobalAveragePool",h,{format:_?"NHWC":"NCHW"})},866031:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P)=>{d.jb("AveragePool",h,{format:P?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:x,storage_order:S,dilations:M?Array.from(a().subarray(M>>>0,F>>>0)):[],kernel_shape:V?Array.from(a().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(a().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(a().subarray(we>>>0,be>>>0)):[]})},866446:(h,_)=>{d.jb("GlobalAveragePool",h,{format:_?"NHWC":"NCHW"})},866537:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P)=>{d.jb("AveragePool",h,{format:P?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:x,storage_order:S,dilations:M?Array.from(a().subarray(M>>>0,F>>>0)):[],kernel_shape:V?Array.from(a().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(a().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(a().subarray(we>>>0,be>>>0)):[]})},866952:(h,_)=>{d.jb("GlobalMaxPool",h,{format:_?"NHWC":"NCHW"})},867039:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P)=>{d.jb("MaxPool",h,{format:P?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:x,storage_order:S,dilations:M?Array.from(a().subarray(M>>>0,F>>>0)):[],kernel_shape:V?Array.from(a().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(a().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(a().subarray(we>>>0,be>>>0)):[]})},867450:(h,_)=>{d.jb("GlobalMaxPool",h,{format:_?"NHWC":"NCHW"})},867537:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P)=>{d.jb("MaxPool",h,{format:P?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:x,storage_order:S,dilations:M?Array.from(a().subarray(M>>>0,F>>>0)):[],kernel_shape:V?Array.from(a().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(a().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(a().subarray(we>>>0,be>>>0)):[]})},867948:(h,_,b,x,S)=>{d.jb("Gemm",h,{alpha:_,beta:b,transA:x,transB:S})},868052:h=>{d.jb("MatMul",h,void 0)},868106:(h,_,b,x)=>{d.jb("ArgMax",h,{keepDims:!!_,selectLastIndex:!!b,axis:x})},868214:(h,_,b,x)=>{d.jb("ArgMin",h,{keepDims:!!_,selectLastIndex:!!b,axis:x})},868322:(h,_)=>{d.jb("Softmax",h,{axis:_})},868385:(h,_)=>{d.jb("Concat",h,{axis:_})},868445:(h,_,b,x,S)=>{d.jb("Split",h,{axis:_,numOutputs:b,splitSizes:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},868585:h=>{d.jb("Expand",h,void 0)},868639:(h,_)=>{d.jb("Gather",h,{axis:Number(_)})},868710:(h,_)=>{d.jb("GatherElements",h,{axis:Number(_)})},868789:(h,_,b,x,S,M,F,V,Q,Z,le)=>{d.jb("Resize",h,{antialias:_,axes:b?Array.from(a().subarray(b>>>0,x>>>0)):[],coordinateTransformMode:Ge(S),cubicCoeffA:M,excludeOutside:F,extrapolationValue:V,keepAspectRatioPolicy:Ge(Q),mode:Ge(Z),nearestMode:Ge(le)})},869135:(h,_,b,x,S,M,F)=>{d.jb("Slice",h,{starts:_?Array.from(a().subarray(_>>>0,b>>>0)):[],ends:x?Array.from(a().subarray(x>>>0,S>>>0)):[],axes:M?Array.from(a().subarray(M>>>0,F>>>0)):[]})},869351:h=>{d.jb("Tile",h,void 0)},869403:(h,_,b)=>{d.jb("InstanceNormalization",h,{epsilon:_,format:b?"NHWC":"NCHW"})},869517:(h,_,b)=>{d.jb("InstanceNormalization",h,{epsilon:_,format:b?"NHWC":"NCHW"})},869631:h=>{d.jb("Range",h,void 0)},869684:(h,_)=>{d.jb("Einsum",h,{equation:Ge(_)})},869765:(h,_,b,x,S)=>{d.jb("Pad",h,{mode:_,value:b,pads:x?Array.from(a().subarray(x>>>0,S>>>0)):[]})},869892:(h,_,b,x,S,M)=>{d.jb("BatchNormalization",h,{epsilon:_,momentum:b,spatial:!!S,trainingMode:!!x,format:M?"NHWC":"NCHW"})},870061:(h,_,b,x,S,M)=>{d.jb("BatchNormalization",h,{epsilon:_,momentum:b,spatial:!!S,trainingMode:!!x,format:M?"NHWC":"NCHW"})},870230:(h,_,b)=>{d.jb("CumSum",h,{exclusive:Number(_),reverse:Number(b)})},870327:(h,_,b)=>{d.jb("DequantizeLinear",h,{axis:_,blockSize:b})},870417:(h,_,b,x,S,M,F,V,Q)=>{d.jb("Attention",h,{numHeads:_,isUnidirectional:b,maskFilterValue:x,scale:S,doRotary:M,qkvHiddenSizes:F?Array.from(a().subarray(Number(V)>>>0,Number(V)+F>>>0)):[],pastPresentShareBuffer:!!Q})},870689:h=>{d.jb("BiasAdd",h,void 0)},870744:h=>{d.jb("BiasSplitGelu",h,void 0)},870805:h=>{d.jb("FastGelu",h,void 0)},870861:(h,_,b,x,S,M,F,V,Q,Z,le,we,be,P,_e,Pe)=>{d.jb("Conv",h,{format:we?"NHWC":"NCHW",auto_pad:_,dilations:b?Array.from(a().subarray(b>>>0,x>>>0)):[],group:S,kernel_shape:M?Array.from(a().subarray(M>>>0,F>>>0)):[],pads:V?Array.from(a().subarray(V>>>0,Q>>>0)):[],strides:Z?Array.from(a().subarray(Z>>>0,le>>>0)):[],w_is_const:()=>!!n()[be>>>0],activation:Ge(P),activation_params:_e?Array.from(l().subarray(_e>>>0,Pe>>>0)):[]})},871357:h=>{d.jb("Gelu",h,void 0)},871409:(h,_,b,x)=>{d.jb("GroupQueryAttention",h,{numHeads:_,kvNumHeads:b,scale:x})},871522:(h,_,b,x)=>{d.jb("LayerNormalization",h,{axis:_,epsilon:b,simplified:!!x})},871633:(h,_,b,x)=>{d.jb("LayerNormalization",h,{axis:_,epsilon:b,simplified:!!x})},871744:(h,_,b,x,S,M)=>{d.jb("MatMulNBits",h,{k:_,n:b,accuracyLevel:x,bits:S,blockSize:M})},871871:(h,_,b,x,S,M)=>{d.jb("MultiHeadAttention",h,{numHeads:_,isUnidirectional:b,maskFilterValue:x,scale:S,doRotary:M})},872030:(h,_)=>{d.jb("QuickGelu",h,{alpha:_})},872094:(h,_,b,x,S)=>{d.jb("RotaryEmbedding",h,{interleaved:!!_,numHeads:b,rotaryEmbeddingDim:x,scale:S})},872233:(h,_,b)=>{d.jb("SkipLayerNormalization",h,{epsilon:_,simplified:!!b})},872335:(h,_,b)=>{d.jb("SkipLayerNormalization",h,{epsilon:_,simplified:!!b})},872437:(h,_,b,x)=>{d.jb("GatherBlockQuantized",h,{gatherAxis:_,quantizeAxis:b,blockSize:x})},872558:h=>{d.Yb(h)},872592:(h,_)=>d.$b(h,_,d.Eb.bc,d.Eb.errors)};function uM(h,_,b){return Aw(async()=>{await d.Wb(h,_,b)})}function dM(){return typeof wasmOffsetConverter<"u"}function yo(h){this.name="ExitStatus",this.message=`Program terminated with exit(${h})`,this.status=h}var bo=h=>{h.terminate(),h.onmessage=()=>{}},Y_=h=>{gn.length==0&&(rw(),nw(gn[0]));var _=gn.pop();if(!_)return 6;Fn.push(_),Vt[h.Ab]=_,_.Ab=h.Ab;var b={cmd:"run",start_routine:h.cc,arg:h.Pb,pthread_ptr:h.Ab};return _.postMessage(b,h.ic),0},Rn=0,Ce=(h,_,...b)=>{for(var x=2*b.length,S=No(),M=Do(8*x),F=M>>>3,V=0;V>>0]=Q)}return h=ey(h,0,x,M,_),la(S),h};function vo(h){if(w)return Ce(0,1,h);if(R=h,!(0{if(R=h,w)throw Z_(h),"unwind";vo(h)},gn=[],Fn=[],J_=[],Vt={},ew=h=>{var _=h.Ab;delete Vt[_],gn.push(h),Fn.splice(Fn.indexOf(h),1),h.Ab=0,Fo(_)};function tw(){J_.forEach(h=>h())}var nw=h=>new Promise(_=>{h.onmessage=S=>{var M=(S=S.data).cmd;if(S.targetThread&&S.targetThread!=lr()){var F=Vt[S.targetThread];F?F.postMessage(S,S.transferList):H(`Internal error! Worker sent a message "${M}" to target pthread ${S.targetThread}, but that thread no longer exists!`)}else M==="checkMailbox"?Zs():M==="spawnThread"?Y_(S):M==="cleanupThread"?ew(Vt[S.thread]):M==="killThread"?(S=S.thread,M=Vt[S],delete Vt[S],bo(M),Fo(S),Fn.splice(Fn.indexOf(M),1),M.Ab=0):M==="cancelThread"?Vt[S.thread].postMessage({cmd:"cancel"}):M==="loaded"?(h.loaded=!0,_(h)):M==="alert"?alert(`Thread ${S.threadId}: ${S.text}`):S.target==="setimmediate"?h.postMessage(S):M==="callHandler"?d[S.handler](...S.args):M&&H(`worker sent an unknown command ${M}`)},h.onerror=S=>{throw H(`worker sent an error! ${S.filename}:${S.lineno}: ${S.message}`),S};var b,x=[];for(b of[])d.hasOwnProperty(b)&&x.push(b);h.postMessage({cmd:"load",handlers:x,wasmMemory:I,wasmModule:N})});function rw(){var h=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});gn.push(h)}var Ys=h=>{for(;0{var h=lr(),_=o()[h+52>>>2>>>0];h=o()[h+56>>>2>>>0],ny(_,_-h),la(_)},pM=(h,_)=>{Rn=0,h=ry(h,_),0>>=0);throw _>>>=0,b>>>=0,o()[x.Ib+16>>>2>>>0]=0,o()[x.Ib+4>>>2>>>0]=_,o()[x.Ib+8>>>2>>>0]=b,h}function sw(h,_,b,x){return w?Ce(2,1,h,_,b,x):aw(h,_,b,x)}function aw(h,_,b,x){if(h>>>=0,_>>>=0,b>>>=0,x>>>=0,v===void 0)return H("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var S=[];return w&&S.length===0?sw(h,_,b,x):(h={cc:b,Ab:h,Pb:x,ic:S},w?(h.Lb="spawnThread",postMessage(h,S),0):Y_(h))}var iw=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ow=(h,_,b)=>{var x=(_>>>=0)+b;for(b=_;h[b]&&!(b>=x);)++b;if(16(S=(240&S)==224?(15&S)<<12|M<<6|F:(7&S)<<18|M<<12|F<<6|63&h[_++])?x+=String.fromCharCode(S):(S-=65536,x+=String.fromCharCode(55296|S>>10,56320|1023&S))}}else x+=String.fromCharCode(S)}return x},Ge=(h,_)=>(h>>>=0)?ow(r(),h,_):"";function lw(h,_,b){return w?Ce(3,1,h,_,b):0}function uw(h,_){if(w)return Ce(4,1,h,_)}var $o=h=>{for(var _=0,b=0;b=x?_++:2047>=x?_+=2:55296<=x&&57343>=x?(_+=4,++b):_+=3}return _},dw=(h,_,b,x)=>{if(!(0>>=0;x=b+x-1;for(var M=0;M=F&&(F=65536+((1023&F)<<10)|1023&h.charCodeAt(++M)),127>=F){if(b>=x)break;_[b++>>>0]=F}else{if(2047>=F){if(b+1>=x)break;_[b++>>>0]=192|F>>6}else{if(65535>=F){if(b+2>=x)break;_[b++>>>0]=224|F>>12}else{if(b+3>=x)break;_[b++>>>0]=240|F>>18,_[b++>>>0]=128|F>>12&63}_[b++>>>0]=128|F>>6&63}_[b++>>>0]=128|63&F}}return _[b>>>0]=0,b-S},ir=(h,_,b)=>dw(h,r(),_,b);function cw(h,_){if(w)return Ce(5,1,h,_)}function pw(h,_,b){if(w)return Ce(6,1,h,_,b)}function hw(h,_,b){return w?Ce(7,1,h,_,b):0}function fw(h,_){if(w)return Ce(8,1,h,_)}function mw(h,_,b){if(w)return Ce(9,1,h,_,b)}function gw(h,_,b,x){if(w)return Ce(10,1,h,_,b,x)}function _w(h,_,b,x){if(w)return Ce(11,1,h,_,b,x)}function ww(h,_,b,x){if(w)return Ce(12,1,h,_,b,x)}function yw(h){if(w)return Ce(13,1,h)}function bw(h,_){if(w)return Ce(14,1,h,_)}function vw(h,_,b){if(w)return Ce(15,1,h,_,b)}var xw,_n,mM=()=>{Zt("")},jt=h=>{for(var _="";r()[h>>>0];)_+=xw[r()[h++>>>0]];return _},ko={},So={};function Jt(h,_,b={}){if(!("argPackAdvance"in _))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(x,S,M={}){var F=S.name;if(!x)throw new _n(`type "${F}" must have a positive integer typeid pointer`);if(So.hasOwnProperty(x)){if(M.Rb)return;throw new _n(`Cannot register type '${F}' twice`)}So[x]=S,ko.hasOwnProperty(x)&&(S=ko[x],delete ko[x],S.forEach(V=>V()))}(h,_,b)}var $w=(h,_,b)=>{switch(_){case 1:return b?x=>n()[x>>>0]:x=>r()[x>>>0];case 2:return b?x=>s()[x>>>1>>>0]:x=>i()[x>>>1>>>0];case 4:return b?x=>a()[x>>>2>>>0]:x=>o()[x>>>2>>>0];case 8:return b?x=>Ee[x>>>3]:x=>ut[x>>>3];default:throw new TypeError(`invalid integer width (${_}): ${h}`)}};function gM(h,_,b){b>>>=0,Jt(h>>>=0,{name:_=jt(_>>>0),fromWireType:x=>x,toWireType:function(x,S){if(typeof S!="bigint"&&typeof S!="number")throw S=S===null?"null":(x=typeof S)=="object"||x==="array"||x==="function"?S.toString():""+S,new TypeError(`Cannot convert "${S}" to ${this.name}`);return typeof S=="number"&&(S=BigInt(S)),S},argPackAdvance:wn,readValueFromPointer:$w(_,b,_.indexOf("u")==-1),Db:null})}var wn=8;function _M(h,_,b,x){Jt(h>>>=0,{name:_=jt(_>>>0),fromWireType:function(S){return!!S},toWireType:function(S,M){return M?b:x},argPackAdvance:wn,readValueFromPointer:function(S){return this.fromWireType(r()[S>>>0])},Db:null})}var Eo=[],en=[];function To(h){9<(h>>>=0)&&--en[h+1]==0&&(en[h]=void 0,Eo.push(h))}var xt=h=>{if(!h)throw new _n("Cannot use deleted val. handle = "+h);return en[h]},$t=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let _=Eo.pop()||en.length;return en[_]=h,en[_+1]=1,_}};function Mo(h){return this.fromWireType(o()[h>>>2>>>0])}var wM={name:"emscripten::val",fromWireType:h=>{var _=xt(h);return To(h),_},toWireType:(h,_)=>$t(_),argPackAdvance:wn,readValueFromPointer:Mo,Db:null};function yM(h){return Jt(h>>>0,wM)}var bM=(h,_)=>{switch(_){case 4:return function(b){return this.fromWireType(l()[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(u()[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${_}): ${h}`)}};function vM(h,_,b){b>>>=0,Jt(h>>>=0,{name:_=jt(_>>>0),fromWireType:x=>x,toWireType:(x,S)=>S,argPackAdvance:wn,readValueFromPointer:bM(_,b),Db:null})}function xM(h,_,b,x,S){if(h>>>=0,b>>>=0,_=jt(_>>>0),S===-1&&(S=4294967295),S=V=>V,x===0){var M=32-8*b;S=V=>V<>>M}var F=_.includes("unsigned")?function(V,Q){return Q>>>0}:function(V,Q){return Q};Jt(h,{name:_,fromWireType:S,toWireType:F,argPackAdvance:wn,readValueFromPointer:$w(_,b,x!==0),Db:null})}function $M(h,_,b){function x(M){var F=o()[M>>>2>>>0];return M=o()[M+4>>>2>>>0],new S(n().buffer,M,F)}var S=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][_];Jt(h>>>=0,{name:b=jt(b>>>0),fromWireType:x,argPackAdvance:wn,readValueFromPointer:x},{Rb:!0})}function kM(h,_){h>>>=0;var b=(_=jt(_>>>0))==="std::string";Jt(h,{name:_,fromWireType:function(x){var S=o()[x>>>2>>>0],M=x+4;if(b)for(var F=M,V=0;V<=S;++V){var Q=M+V;if(V==S||r()[Q>>>0]==0){if(F=Ge(F,Q-F),Z===void 0)var Z=F;else Z+="\0",Z+=F;F=Q+1}}else{for(Z=Array(S),V=0;V>>0]);Z=Z.join("")}return Gt(x),Z},toWireType:function(x,S){S instanceof ArrayBuffer&&(S=new Uint8Array(S));var M=typeof S=="string";if(!(M||S instanceof Uint8Array||S instanceof Uint8ClampedArray||S instanceof Int8Array))throw new _n("Cannot pass non-string to std::string");var F=b&&M?$o(S):S.length,V=ia(4+F+1),Q=V+4;if(o()[V>>>2>>>0]=F,b&&M)ir(S,Q,F+1);else if(M)for(M=0;M>>0]=Z}else for(M=0;M>>0]=S[M];return x!==null&&x.push(Gt,V),V},argPackAdvance:wn,readValueFromPointer:Mo,Db(x){Gt(x)}})}var kw=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,SM=(h,_)=>{for(var b=h>>1,x=b+_/2;!(b>=x)&&i()[b>>>0];)++b;if(32<(b<<=1)-h&&kw)return kw.decode(r().slice(h,b));for(b="",x=0;!(x>=_/2);++x){var S=s()[h+2*x>>>1>>>0];if(S==0)break;b+=String.fromCharCode(S)}return b},EM=(h,_,b)=>{if(b??(b=2147483647),2>b)return 0;var x=_;b=(b-=2)<2*h.length?b/2:h.length;for(var S=0;S>>1>>>0]=M,_+=2}return s()[_>>>1>>>0]=0,_-x},TM=h=>2*h.length,MM=(h,_)=>{for(var b=0,x="";!(b>=_/4);){var S=a()[h+4*b>>>2>>>0];if(S==0)break;++b,65536<=S?(S-=65536,x+=String.fromCharCode(55296|S>>10,56320|1023&S)):x+=String.fromCharCode(S)}return x},CM=(h,_,b)=>{if(_>>>=0,b??(b=2147483647),4>b)return 0;var x=_;b=x+b-4;for(var S=0;S=M&&(M=65536+((1023&M)<<10)|1023&h.charCodeAt(++S)),a()[_>>>2>>>0]=M,(_+=4)+4>b)break}return a()[_>>>2>>>0]=0,_-x},AM=h=>{for(var _=0,b=0;b=x&&++b,_+=4}return _};function IM(h,_,b){if(h>>>=0,_>>>=0,b=jt(b>>>=0),_===2)var x=SM,S=EM,M=TM,F=V=>i()[V>>>1>>>0];else _===4&&(x=MM,S=CM,M=AM,F=V=>o()[V>>>2>>>0]);Jt(h,{name:b,fromWireType:V=>{for(var Q,Z=o()[V>>>2>>>0],le=V+4,we=0;we<=Z;++we){var be=V+4+we*_;we!=Z&&F(be)!=0||(le=x(le,be-le),Q===void 0?Q=le:(Q+="\0",Q+=le),le=be+_)}return Gt(V),Q},toWireType:(V,Q)=>{if(typeof Q!="string")throw new _n(`Cannot pass non-string to C++ string type ${b}`);var Z=M(Q),le=ia(4+Z+_);return o()[le>>>2>>>0]=Z/_,S(Q,le+4,Z+_),V!==null&&V.push(Gt,le),le},argPackAdvance:wn,readValueFromPointer:Mo,Db(V){Gt(V)}})}function zM(h,_){Jt(h>>>=0,{Sb:!0,name:_=jt(_>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var OM=()=>1;function PM(h){Ro(h>>>0,!g,1,!m,131072,!1),tw()}var Sw=h=>{if(!Ne)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(a(),h>>>2,h).value.then(Zs),h+=128,Atomics.store(a(),h>>>2,1))}var Zs=()=>{var h=lr();h&&(Co(h),Sw(ty))};function BM(h,_){(h>>>=0)==_>>>0?setTimeout(Zs):w?postMessage({targetThread:h,cmd:"checkMailbox"}):(h=Vt[h])&&h.postMessage({cmd:"checkMailbox"})}var Ao=[];function RM(h,_,b,x,S){for(_>>>=0,x/=2,Ao.length=x,b=S>>>0>>>3,S=0;S>>0];return(_?wo[_]:SC[h])(...Ao)}function FM(h){h>>>=0,w?postMessage({cmd:"cleanupThread",thread:h}):ew(Vt[h])}function DM(h){}var Io=(h,_)=>{var b=So[h];if(b===void 0)throw h=Yw(h),b=jt(h),Gt(h),new _n(`${_} has unknown type ${b}`);return b},Ew=(h,_,b)=>{var x=[];return h=h.toWireType(x,b),x.length&&(o()[_>>>2>>>0]=$t(x)),h};function NM(h,_,b){return _>>>=0,b>>>=0,h=xt(h>>>0),_=Io(_,"emval::as"),Ew(_,b,h)}var Js=h=>{try{h()}catch(_){Zt(_)}},yn=0,qt=null,Tw=0,ea=[],Mw={},Cw={},LM=0,zo=null,UM=[];function Aw(h){return function(_){if(!Ne){if(yn===0){var b=!1,x=!1;_((S=0)=>{if(!Ne&&(Tw=S,b=!0,x)){yn=2,Js(()=>iy(qt)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),S=!1;try{var M=function(){var Q=a()[qt+8>>>2>>>0];return Q=oe[Cw[Q]],--Rn,Q()}()}catch(Q){M=Q,S=!0}var F=!1;if(!qt){var V=zo;V&&(zo=null,(S?V.reject:V.resolve)(M),F=!0)}if(S&&!F)throw M}}),x=!0,b||(yn=1,qt=function(){var S=ia(65548),M=S+12;o()[S>>>2>>>0]=M,o()[S+4>>>2>>>0]=M+65536,M=ea[0];var F=Mw[M];return F===void 0&&(F=LM++,Mw[M]=F,Cw[F]=M),M=F,a()[S+8>>>2>>>0]=M,S}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),Js(()=>sy(qt)))}else yn===2?(yn=0,Js(oy),Gt(qt),qt=null,UM.forEach(Sw)):Zt(`invalid state: ${yn}`);return Tw}}(_=>{h().then(_)})}function VM(h){return h>>>=0,Aw(()=>(h=xt(h)).then($t))}var ta=[];function jM(h,_,b,x){return b>>>=0,x>>>=0,(h=ta[h>>>0])(null,_=xt(_>>>0),b,x)}var qM={},na=h=>{var _=qM[h];return _===void 0?jt(h):_};function GM(h,_,b,x,S){return b>>>=0,x>>>=0,S>>>=0,(h=ta[h>>>0])(_=xt(_>>>0),_[b=na(b)],x,S)}var Iw=()=>typeof globalThis=="object"?globalThis:Function("return this")();function WM(h){return(h>>>=0)==0?$t(Iw()):(h=na(h),$t(Iw()[h]))}var HM=h=>{var _=ta.length;return ta.push(h),_},KM=(h,_)=>{for(var b=Array(h),x=0;x>>2>>>0],"parameter "+x);return b},zw=(h,_)=>Object.defineProperty(_,"name",{value:h});function XM(h,_,b){var x=(_=KM(h,_>>>0)).shift();h--;var S=`return function (obj, func, destructorsRef, args) { +`,M=0,F=[];b===0&&F.push("obj");for(var V=["retType"],Q=[x],Z=0;Zle.name).join(", ")}) => ${x.name}>`,HM(zw(b,h))}function QM(h){return h=na(h>>>0),$t(d[h])}function YM(h,_){return _>>>=0,h=xt(h>>>0),_=xt(_),$t(h[_])}function ZM(h){9<(h>>>=0)&&(en[h+1]+=1)}function JM(){return $t([])}function eC(h){h=xt(h>>>0);for(var _=Array(h.length),b=0;b>>0))}function nC(){return $t({})}function rC(h){for(var _=xt(h>>>=0);_.length;){var b=_.pop();_.pop()(b)}To(h)}function sC(h,_,b){_>>>=0,b>>>=0,h=xt(h>>>0),_=xt(_),b=xt(b),h[_]=b}function aC(h,_){return _>>>=0,h=(h=Io(h>>>0,"_emval_take_value")).readValueFromPointer(_),$t(h)}function iC(h,_){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),a()[_>>>2>>>0]=h.getUTCSeconds(),a()[_+4>>>2>>>0]=h.getUTCMinutes(),a()[_+8>>>2>>>0]=h.getUTCHours(),a()[_+12>>>2>>>0]=h.getUTCDate(),a()[_+16>>>2>>>0]=h.getUTCMonth(),a()[_+20>>>2>>>0]=h.getUTCFullYear()-1900,a()[_+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[_+28>>>2>>>0]=h}var or=h=>h%4==0&&(h%100!=0||h%400==0),Ow=[0,31,60,91,121,152,182,213,244,274,305,335],Pw=[0,31,59,90,120,151,181,212,243,273,304,334];function oC(h,_){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),a()[_>>>2>>>0]=h.getSeconds(),a()[_+4>>>2>>>0]=h.getMinutes(),a()[_+8>>>2>>>0]=h.getHours(),a()[_+12>>>2>>>0]=h.getDate(),a()[_+16>>>2>>>0]=h.getMonth(),a()[_+20>>>2>>>0]=h.getFullYear()-1900,a()[_+24>>>2>>>0]=h.getDay();var b=(or(h.getFullYear())?Ow:Pw)[h.getMonth()]+h.getDate()-1|0;a()[_+28>>>2>>>0]=b,a()[_+36>>>2>>>0]=-60*h.getTimezoneOffset(),b=new Date(h.getFullYear(),6,1).getTimezoneOffset();var x=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(b!=x&&h.getTimezoneOffset()==Math.min(x,b)),a()[_+32>>>2>>>0]=h}function lC(h){h>>>=0;var _=new Date(a()[h+20>>>2>>>0]+1900,a()[h+16>>>2>>>0],a()[h+12>>>2>>>0],a()[h+8>>>2>>>0],a()[h+4>>>2>>>0],a()[h>>>2>>>0],0),b=a()[h+32>>>2>>>0],x=_.getTimezoneOffset(),S=new Date(_.getFullYear(),6,1).getTimezoneOffset(),M=new Date(_.getFullYear(),0,1).getTimezoneOffset(),F=Math.min(M,S);return 0>b?a()[h+32>>>2>>>0]=+(S!=M&&F==x):0>>2>>>0]=_.getDay(),b=(or(_.getFullYear())?Ow:Pw)[_.getMonth()]+_.getDate()-1|0,a()[h+28>>>2>>>0]=b,a()[h>>>2>>>0]=_.getSeconds(),a()[h+4>>>2>>>0]=_.getMinutes(),a()[h+8>>>2>>>0]=_.getHours(),a()[h+12>>>2>>>0]=_.getDate(),a()[h+16>>>2>>>0]=_.getMonth(),a()[h+20>>>2>>>0]=_.getYear(),h=_.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Bw(h,_,b,x,S,M,F){return w?Ce(16,1,h,_,b,x,S,M,F):-52}function Rw(h,_,b,x,S,M){if(w)return Ce(17,1,h,_,b,x,S,M)}function uC(h,_,b,x){h>>>=0,_>>>=0,b>>>=0,x>>>=0;var S=new Date().getFullYear(),M=new Date(S,0,1),F=new Date(S,6,1);S=M.getTimezoneOffset();var V=F.getTimezoneOffset(),Q=Math.max(S,V);o()[h>>>2>>>0]=60*Q,a()[_>>>2>>>0]=+(S!=V),M=(h=Z=>Z.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(M),F=h(F),V{Oo.length=0;for(var b;b=r()[h++>>>0];){var x=b!=105;_+=(x&=b!=112)&&_%8?4:0,Oo.push(b==112?o()[_>>>2>>>0]:b==106?Ee[_>>>3]:b==105?a()[_>>>2>>>0]:u()[_>>>3>>>0]),_+=x?8:4}return Oo};function dC(h,_,b){return h>>>=0,_=Fw(_>>>0,b>>>0),wo[h](..._)}function cC(h,_,b){return h>>>=0,_=Fw(_>>>0,b>>>0),wo[h](..._)}var pC=()=>{},hC=()=>Date.now();function fC(h,_){return H(Ge(h>>>0,_>>>0))}var Dw,mC=()=>{throw Rn+=1,"unwind"};function gC(){return 4294901760}Dw=()=>performance.timeOrigin+performance.now();var _C=()=>navigator.hardwareConcurrency;function wC(){return Zt("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function yC(h){h>>>=0;var _=r().length;if(h<=_||4294901760=b;b*=2){var x=_*(1+.2/b);x=Math.min(x,h+100663296);var S=Math;x=Math.max(h,x);e:{S=(S.min.call(S,4294901760,x+(65536-x%65536)%65536)-I.buffer.byteLength+65535)/65536;try{I.grow(S),Oe();var M=1;break e}catch{}M=void 0}if(M)return!0}return!1}var ra=()=>(Zt("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Kr={},Nw=h=>{h.forEach(_=>{ra()})};function bC(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),Nw(h),Kr.Ob=ra(),Kr.ac=h,Kr.Ob}function vC(h,_,b){if(h>>>=0,_>>>=0,Kr.Ob==h)var x=Kr.ac;else(x=Error().stack.toString().split(` +`))[0]=="Error"&&x.shift(),Nw(x);for(var S=3;x[S]&&ra()!=h;)++S;for(h=0;h>>2>>>0]=ra();return h}var Po,Bo={},Lw=()=>{if(!Po){var h,_={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",_:T};for(h in Bo)Bo[h]===void 0?delete _[h]:_[h]=Bo[h];var b=[];for(h in _)b.push(`${h}=${_[h]}`);Po=b}return Po};function Uw(h,_){if(w)return Ce(18,1,h,_);h>>>=0,_>>>=0;var b=0;return Lw().forEach((x,S)=>{var M=_+b;for(S=o()[h+4*S>>>2>>>0]=M,M=0;M>>0]=x.charCodeAt(M);n()[S>>>0]=0,b+=x.length+1}),0}function Vw(h,_){if(w)return Ce(19,1,h,_);h>>>=0,_>>>=0;var b=Lw();o()[h>>>2>>>0]=b.length;var x=0;return b.forEach(S=>x+=S.length+1),o()[_>>>2>>>0]=x,0}function jw(h){return w?Ce(20,1,h):52}function qw(h,_,b,x){return w?Ce(21,1,h,_,b,x):52}function Gw(h,_,b,x){return w?Ce(22,1,h,_,b,x):70}var xC=[null,[],[]];function Ww(h,_,b,x){if(w)return Ce(23,1,h,_,b,x);_>>>=0,b>>>=0,x>>>=0;for(var S=0,M=0;M>>2>>>0],V=o()[_+4>>>2>>>0];_+=8;for(var Q=0;Q>>0],le=xC[h];Z===0||Z===10?((h===1?X:H)(ow(le,0)),le.length=0):le.push(Z)}S+=V}return o()[x>>>2>>>0]=S,0}var Hw=[31,29,31,30,31,30,31,31,30,31,30,31],Kw=[31,28,31,30,31,30,31,31,30,31,30,31],$C=(h,_)=>{n().set(h,_>>>0)};function Xw(h,_,b,x){function S(P,_e,Pe){for(P=typeof P=="number"?P.toString():P||"";P.length<_e;)P=Pe[0]+P;return P}function M(P,_e){return S(P,_e,"0")}function F(P,_e){function Pe(uy){return 0>uy?-1:0Dn-P.getDate())){P.setDate(P.getDate()+_e);break}_e-=Dn-P.getDate()+1,P.setDate(1),11>Pe?P.setMonth(Pe+1):(P.setMonth(0),P.setFullYear(P.getFullYear()+1))}return Pe=new Date(P.getFullYear()+1,0,4),_e=V(new Date(P.getFullYear(),0,4)),Pe=V(Pe),0>=F(_e,P)?0>=F(Pe,P)?P.getFullYear()+1:P.getFullYear():P.getFullYear()-1}h>>>=0,_>>>=0,b>>>=0,x>>>=0;var Z=o()[x+40>>>2>>>0];for(var le in x={fc:a()[x>>>2>>>0],ec:a()[x+4>>>2>>>0],Gb:a()[x+8>>>2>>>0],Kb:a()[x+12>>>2>>>0],Hb:a()[x+16>>>2>>>0],Cb:a()[x+20>>>2>>>0],ub:a()[x+24>>>2>>>0],Bb:a()[x+28>>>2>>>0],nc:a()[x+32>>>2>>>0],dc:a()[x+36>>>2>>>0],hc:Z?Ge(Z):""},b=Ge(b),Z={"%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"})b=b.replace(new RegExp(le,"g"),Z[le]);var we="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),be="January February March April May June July August September October November December".split(" ");for(le in Z={"%a":P=>we[P.ub].substring(0,3),"%A":P=>we[P.ub],"%b":P=>be[P.Hb].substring(0,3),"%B":P=>be[P.Hb],"%C":P=>M((P.Cb+1900)/100|0,2),"%d":P=>M(P.Kb,2),"%e":P=>S(P.Kb,2," "),"%g":P=>Q(P).toString().substring(2),"%G":Q,"%H":P=>M(P.Gb,2),"%I":P=>((P=P.Gb)==0?P=12:12{for(var _e=0,Pe=0;Pe<=P.Hb-1;_e+=(or(P.Cb+1900)?Hw:Kw)[Pe++]);return M(P.Kb+_e,3)},"%m":P=>M(P.Hb+1,2),"%M":P=>M(P.ec,2),"%n":()=>` +`,"%p":P=>0<=P.Gb&&12>P.Gb?"AM":"PM","%S":P=>M(P.fc,2),"%t":()=>" ","%u":P=>P.ub||7,"%U":P=>M(Math.floor((P.Bb+7-P.ub)/7),2),"%V":P=>{var _e=Math.floor((P.Bb+7-(P.ub+6)%7)/7);if(2>=(P.ub+371-P.Bb-2)%7&&_e++,_e)_e==53&&((Pe=(P.ub+371-P.Bb)%7)==4||Pe==3&&or(P.Cb)||(_e=1));else{_e=52;var Pe=(P.ub+7-P.Bb-1)%7;(Pe==4||Pe==5&&or(P.Cb%400-1))&&_e++}return M(_e,2)},"%w":P=>P.ub,"%W":P=>M(Math.floor((P.Bb+7-(P.ub+6)%7)/7),2),"%y":P=>(P.Cb+1900).toString().substring(2),"%Y":P=>P.Cb+1900,"%z":P=>{var _e=0<=(P=P.dc);return P=Math.abs(P)/60,(_e?"+":"-")+("0000"+(P/60*100+P%60)).slice(-4)},"%Z":P=>P.hc,"%%":()=>"%"},b=b.replace(/%%/g,"\0\0"),Z)b.includes(le)&&(b=b.replace(new RegExp(le,"g"),Z[le](x)));return le=function(P){var _e=Array($o(P)+1);return dw(P,_e,0,_e.length),_e}(b=b.replace(/\0\0/g,"%")),le.length>_?0:($C(le,h),le.length-1)}function kC(h,_,b,x){return Xw(h>>>0,_>>>0,b>>>0,x>>>0)}w||function(){for(var h=d.numThreads-1;h--;)rw();Pt.unshift(()=>{it++,function(_){w?_():Promise.all(gn.map(nw)).then(_)}(()=>Bn())})}();for(var Qw=Array(256),sa=0;256>sa;++sa)Qw[sa]=String.fromCharCode(sa);xw=Qw,_n=d.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},d.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},en.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>en.length/2-5-Eo.length;var SC=[vo,Z_,sw,lw,uw,cw,pw,hw,fw,mw,gw,_w,ww,yw,bw,vw,Bw,Rw,Uw,Vw,jw,qw,Gw,Ww],oe=function(){function h(b,x){return oe=b.exports,oe=function(){var S=oe,M={};for(let[F,V]of Object.entries(S))M[F]=typeof V=="function"?(...Q)=>{ea.push(F);try{return V(...Q)}finally{Ne||(ea.pop(),qt&&yn===1&&ea.length===0&&(yn=0,Rn+=1,Js(ay),typeof Fibers<"u"&&Fibers.oc()))}}:V;return M}(),oe=function(){var S=oe,M=V=>Q=>V(Q)>>>0,F=V=>()=>V()>>>0;return(S=Object.assign({},S)).Ca=M(S.Ca),S.fb=F(S.fb),S.gb=M(S.gb),S.emscripten_main_runtime_thread_id=F(S.emscripten_main_runtime_thread_id),S.sb=M(S.sb),S.tb=F(S.tb),S}(),J_.push(oe.ib),De.unshift(oe.Ba),N=x,Bn(),oe}var _=Q_();if(it++,d.instantiateWasm)try{return d.instantiateWasm(_,h)}catch(b){H(`Module.instantiateWasm callback failed with error: ${b}`),p(b)}return _o||(_o=d.locateFile?W_("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",B):B+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-BnU-vluZ.wasm",self.location.href).href),function(b,x){var S=_o;return U||typeof WebAssembly.instantiateStreaming!="function"||W_(S)||H_(S)||typeof fetch!="function"?X_(S,b,x):fetch(S,{credentials:"same-origin"}).then(M=>WebAssembly.instantiateStreaming(M,b).then(x,function(F){return H(`wasm streaming compile failed: ${F}`),H("falling back to ArrayBuffer instantiation"),X_(S,b,x)}))}(_,function(b){h(b.instance,b.module)}).catch(p),{}}(),Yw=h=>(Yw=oe.Ca)(h),Zw=()=>(Zw=oe.Da)();d._OrtInit=(h,_)=>(d._OrtInit=oe.Ea)(h,_),d._OrtGetLastError=(h,_)=>(d._OrtGetLastError=oe.Fa)(h,_),d._OrtCreateSessionOptions=(h,_,b,x,S,M,F,V,Q,Z)=>(d._OrtCreateSessionOptions=oe.Ga)(h,_,b,x,S,M,F,V,Q,Z),d._OrtAppendExecutionProvider=(h,_)=>(d._OrtAppendExecutionProvider=oe.Ha)(h,_),d._OrtAddFreeDimensionOverride=(h,_,b)=>(d._OrtAddFreeDimensionOverride=oe.Ia)(h,_,b),d._OrtAddSessionConfigEntry=(h,_,b)=>(d._OrtAddSessionConfigEntry=oe.Ja)(h,_,b),d._OrtReleaseSessionOptions=h=>(d._OrtReleaseSessionOptions=oe.Ka)(h),d._OrtCreateSession=(h,_,b)=>(d._OrtCreateSession=oe.La)(h,_,b),d._OrtReleaseSession=h=>(d._OrtReleaseSession=oe.Ma)(h),d._OrtGetInputOutputCount=(h,_,b)=>(d._OrtGetInputOutputCount=oe.Na)(h,_,b),d._OrtGetInputName=(h,_)=>(d._OrtGetInputName=oe.Oa)(h,_),d._OrtGetOutputName=(h,_)=>(d._OrtGetOutputName=oe.Pa)(h,_),d._OrtFree=h=>(d._OrtFree=oe.Qa)(h),d._OrtCreateTensor=(h,_,b,x,S,M)=>(d._OrtCreateTensor=oe.Ra)(h,_,b,x,S,M),d._OrtGetTensorData=(h,_,b,x,S)=>(d._OrtGetTensorData=oe.Sa)(h,_,b,x,S),d._OrtReleaseTensor=h=>(d._OrtReleaseTensor=oe.Ta)(h),d._OrtCreateRunOptions=(h,_,b,x)=>(d._OrtCreateRunOptions=oe.Ua)(h,_,b,x),d._OrtAddRunConfigEntry=(h,_,b)=>(d._OrtAddRunConfigEntry=oe.Va)(h,_,b),d._OrtReleaseRunOptions=h=>(d._OrtReleaseRunOptions=oe.Wa)(h),d._OrtCreateBinding=h=>(d._OrtCreateBinding=oe.Xa)(h),d._OrtBindInput=(h,_,b)=>(d._OrtBindInput=oe.Ya)(h,_,b),d._OrtBindOutput=(h,_,b,x)=>(d._OrtBindOutput=oe.Za)(h,_,b,x),d._OrtClearBoundOutputs=h=>(d._OrtClearBoundOutputs=oe._a)(h),d._OrtReleaseBinding=h=>(d._OrtReleaseBinding=oe.$a)(h),d._OrtRunWithBinding=(h,_,b,x,S)=>(d._OrtRunWithBinding=oe.ab)(h,_,b,x,S),d._OrtRun=(h,_,b,x,S,M,F,V)=>(d._OrtRun=oe.bb)(h,_,b,x,S,M,F,V),d._OrtEndProfiling=h=>(d._OrtEndProfiling=oe.cb)(h),d._JsepOutput=(h,_,b)=>(d._JsepOutput=oe.db)(h,_,b),d._JsepGetNodeName=h=>(d._JsepGetNodeName=oe.eb)(h);var aa,lr=()=>(lr=oe.fb)(),ia=d._malloc=h=>(ia=d._malloc=oe.gb)(h),Gt=d._free=h=>(Gt=d._free=oe.hb)(h),Ro=(h,_,b,x,S,M)=>(Ro=oe.kb)(h,_,b,x,S,M),Jw=()=>(Jw=oe.lb)(),ey=(h,_,b,x,S)=>(ey=oe.mb)(h,_,b,x,S),Fo=h=>(Fo=oe.nb)(h),oa=h=>(oa=oe.ob)(h),ty=()=>(ty=oe.pb)(),ny=(h,_)=>(ny=oe.qb)(h,_),la=h=>(la=oe.rb)(h),Do=h=>(Do=oe.sb)(h),No=()=>(No=oe.tb)(),ry=d.dynCall_ii=(h,_)=>(ry=d.dynCall_ii=oe.vb)(h,_),sy=h=>(sy=oe.wb)(h),ay=()=>(ay=oe.xb)(),iy=h=>(iy=oe.yb)(h),oy=()=>(oy=oe.zb)();function ly(){0No(),d.stackRestore=h=>la(h),d.stackAlloc=h=>Do(h),d.UTF8ToString=Ge,d.stringToUTF8=ir,d.lengthBytesUTF8=$o,Bt=function h(){aa||ly(),aa||(Bt=h)},ly(),f}),wl=Ea,((t=globalThis.self)==null?void 0:t.name)==="em-pthread"&&Ea()}),Un,yl,bl,vl,Ta,xl,$l,kl,as=W(()=>{var t,e;xa(),Un=self.location.href??(typeof document<"u"?(t=document.currentScript)==null?void 0:t.src:typeof self<"u"?(e=self.location)==null?void 0:e.href:void 0),yl=typeof location>"u"?void 0:location.origin,bl=(n,r)=>{try{let s=r??Un;return(s?new URL(n,s):new URL(n)).origin===yl}catch{return!1}},vl=async n=>{let r=await(await fetch(n,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},Ta=(t0(),rs(ml)).default,xl=async()=>{if(!Un)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(bl(Un))return[void 0,Ta()];let n=await vl(Un);return[n,Ta(n)]},$l=(n0(),rs(_l)).default,kl=async(n,r,s)=>[void 0,$l]}),Ma,is,fr,Ca,Sl,El,Aa,je,Vn=W(()=>{as(),is=!1,fr=!1,Ca=!1,Sl=()=>{if(typeof SharedArrayBuffer>"u")return!1;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}},El=()=>{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}},Aa=async t=>{if(is)return Promise.resolve();if(fr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ca)throw new Error("previous call to 'initializeWebAssembly()' failed.");fr=!0;let e=t.initTimeout,n=t.numThreads;if(!El())throw new Error("WebAssembly SIMD is not supported in the current environment.");let r=Sl();n>1&&!r&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=n=1);let s=t.wasmPaths,i=typeof s=="string"?s:void 0,a=s==null?void 0:s.mjs,o=(a==null?void 0:a.href)??a,l=s==null?void 0:s.wasm,u=(l==null?void 0:l.href)??l,c=t.wasmBinary,[p,d]=await kl(o,i,n>1),f=!1,m=[];if(e>0&&m.push(new Promise(g=>{setTimeout(()=>{f=!0,g()},e)})),m.push(new Promise((g,w)=>{let v={numThreads:n};c?v.wasmBinary=c:(u||i)&&(v.locateFile=(y,$)=>u??(i??$)+y),d(v).then(y=>{fr=!1,is=!0,Ma=y,g(),p&&URL.revokeObjectURL(p)},y=>{fr=!1,Ca=!0,w(y)})})),await Promise.race(m),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},je=()=>{if(is&&Ma)return Ma;throw new Error("WebAssembly is not initialized yet.")}}),Ke,os,Ae,Ia=W(()=>{Vn(),Ke=(t,e)=>{let n=je(),r=n.lengthBytesUTF8(t)+1,s=n._malloc(r);return n.stringToUTF8(t,s,r),e.push(s),s},os=(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(([s,i])=>{let a=e?e+s:s;if(typeof i=="object")os(i,a+".",n,r);else if(typeof i=="string"||typeof i=="number")r(a,i.toString());else if(typeof i=="boolean")r(a,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},Ae=t=>{let e=je(),n=e.stackSave();try{let r=e.stackAlloc(8);e._OrtGetLastError(r,r+4);let s=e.HEAP32[r/4],i=e.HEAPU32[r/4+1],a=i?e.UTF8ToString(i):"";throw new Error(`${t} ERROR_CODE: ${s}, ERROR_MESSAGE: ${a}`)}finally{e.stackRestore(n)}}}),Tl,r0=W(()=>{Vn(),Ia(),Tl=t=>{let e=je(),n=0,r=[],s=t||{};try{if((t==null?void 0:t.logSeverityLevel)===void 0)s.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==null?void 0:t.logVerbosityLevel)===void 0)s.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);(t==null?void 0:t.terminate)===void 0&&(s.terminate=!1);let i=0;return(t==null?void 0:t.tag)!==void 0&&(i=Ke(t.tag,r)),n=e._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,i),n===0&&Ae("Can't create run options."),(t==null?void 0:t.extra)!==void 0&&os(t.extra,"",new WeakSet,(a,o)=>{let l=Ke(a,r),u=Ke(o,r);e._OrtAddRunConfigEntry(n,l,u)!==0&&Ae(`Can't set a run config entry: ${a} - ${o}.`)}),[n,r]}catch(i){throw n!==0&&e._OrtReleaseRunOptions(n),r.forEach(a=>e._free(a)),i}}}),Ml,Cl,Al,Il,zl,s0=W(()=>{Vn(),Ia(),Ml=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}`)}},Cl=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},Al=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)},Il=(t,e,n)=>{for(let r of e){let s=typeof r=="string"?r:r.name;switch(s){case"webnn":if(s="WEBNN",typeof r!="string"){let a=r==null?void 0:r.deviceType;if(a){let o=Ke("deviceType",n),l=Ke(a,n);je()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ae(`Can't set a session config entry: 'deviceType' - ${a}.`)}}break;case"webgpu":if(s="JS",typeof r!="string"){let a=r;if(a!=null&&a.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let o=Ke("preferredLayout",n),l=Ke(a.preferredLayout,n);je()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ae(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let i=Ke(s,n);je()._OrtAppendExecutionProvider(t,i)!==0&&Ae(`Can't append execution provider: ${s}.`)}},zl=t=>{let e=je(),n=0,r=[],s=t||{};Al(s);try{let i=Ml(s.graphOptimizationLevel??"all"),a=Cl(s.executionMode??"sequential"),o=typeof s.logId=="string"?Ke(s.logId,r):0,l=s.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=s.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let c=typeof s.optimizedModelFilePath=="string"?Ke(s.optimizedModelFilePath,r):0;if(n=e._OrtCreateSessionOptions(i,!!s.enableCpuMemArena,!!s.enableMemPattern,a,!!s.enableProfiling,0,o,l,u,c),n===0&&Ae("Can't create session options."),s.executionProviders&&Il(n,s.executionProviders,r),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let p=Ke("enableGraphCapture",r),d=Ke(s.enableGraphCapture.toString(),r);e._OrtAddSessionConfigEntry(n,p,d)!==0&&Ae(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[p,d]of Object.entries(s.freeDimensionOverrides)){if(typeof p!="string")throw new Error(`free dimension override name must be a string: ${p}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let f=Ke(p,r);e._OrtAddFreeDimensionOverride(n,f,d)!==0&&Ae(`Can't set a free dimension override: ${p} - ${d}.`)}return s.extra!==void 0&&os(s.extra,"",new WeakSet,(p,d)=>{let f=Ke(p,r),m=Ke(d,r);e._OrtAddSessionConfigEntry(n,f,m)!==0&&Ae(`Can't set a session config entry: ${p} - ${d}.`)}),[n,r]}catch(i){throw n!==0&&e._OrtReleaseSessionOptions(n),r.forEach(a=>e._free(a)),i}}}),za,$n,ls,Oa,us,Pa,Ba,ue=W(()=>{za=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;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},$n=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";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},ls=(t,e)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],r=typeof e=="number"?e:e.reduce((s,i)=>s*i,1);return n>0?Math.ceil(r*n):void 0},Oa=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},us=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}`)}},Pa=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Ba=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}`)}}}),Ra,Ol=W(()=>{xa(),Ra=async t=>{if(typeof t=="string"){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 s=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 a=0;for(;;){let{done:o,value:l}=await s.read();if(o)break;let u=l.byteLength;new Uint8Array(i,a,u).set(l),a+=u}return new Uint8Array(i,0,r)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),Pl,Bl,Rl,Fl,Dl,Nl,Be,rn=W(()=>{ue(),Pl=["V","I","W","E","F"],Bl=(t,e)=>{console.log(`[${Pl[t]},${new Date().toISOString()}]${e}`)},Dl=(t,e)=>{Rl=t,Fl=e},Nl=(t,e)=>{let n=us(t),r=us(Rl);n>=r&&Bl(n,typeof e=="function"?e():e)},Be=(...t)=>{Fl&&Nl(...t)}}),Ll,a0=W(()=>{ue(),Ll=(t,e)=>new(Oa(e))(t)}),Fa=W(()=>{}),Da,ds,cs,Ul,Vl,Na,La,jl,ql,i0=W(()=>{rn(),Fa(),Da=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),ds=[],cs=t=>Math.ceil(t/16)*16,Ul=t=>{for(let e=0;eVl++,La=async(t,e,n,r)=>{let s=cs(n),i=t.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=t.getCommandEncoder();t.endComputePass(),a.copyBufferToBuffer(e,0,i,0,s),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()}},jl=class{constructor(t){this.backend=t,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[e]of Da)ds.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[])}upload(t,e){let n=e.buffer,r=e.byteOffset,s=e.byteLength,i=cs(s),a=this.storageCache.get(t);if(!a)throw new Error("gpu data for uploading does not exist");if(a.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${s}`);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,s)),o.unmap();let u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o,0,a.gpuData.buffer,0,i),Be("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 s=cs(n.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,s)}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 Be("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${r}, buffer is the same, skip.`),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`);this.externalBuffers.delete(n)}else r=Na();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:t},originalSize:e}),this.externalBuffers.set(t,r),Be("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),Be("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(t,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=Ul(t),r,s=(e&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(e&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||i){let o=(s?this.freeBuffers:this.freeUniformBuffers).get(n);o?o.length>0?r=o.pop():r=this.backend.device.createBuffer({size:n,usage:e}):r=this.backend.device.createBuffer({size:n,usage:e})}else r=this.backend.device.createBuffer({size:n,usage:e});let a={id:Na(),type:0,buffer:r};return this.storageCache.set(a.id,{gpuData:a,originalSize:t}),Be("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${a.id}`),a}get(t){var e;return(e=this.storageCache.get(t))==null?void 0:e.gpuData}release(t){let e=this.storageCache.get(t);if(!e)throw new Error("releasing data does not exist");return Be("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 La(this.backend,n.gpuData.buffer,n.originalSize,e)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let e=Da.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];e===void 0||n.length>=e?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];e===void 0||n.length>=e?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let e of this.buffersPending)t.push(e);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let e=this.capturedPendingBuffers.get(t);e&&(e.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t))}},ql=(...t)=>new jl(...t)}),Gl,$e,Fe=W(()=>{Gl=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},$e=t=>new Gl(t)}),Wl,jn,D,ps,Hl,Ua,Va,pe=W(()=>{Wl=class{static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}},jn=class{static calcShape(t,e,n=!1){let r=t.length,s=e.length;if(r===0)return e;if(s===0)return t;let i=Math.max(t.length,e.length),a=new Array(i);if(n){if(r<2||s<2)return;let o=Wl.calcMatMulShape([t[r-2],t[r-1]],[e[s-2],e[s-1]]);if(o===void 0)return;[a[i-2],a[i-1]]=o}for(let o=n?3:1;o<=i;o++){let l=r-o<0?1:t[r-o],u=s-o<0?1:e[s-o];if(l!==u&&l>1&&u>1)return;let c=Math.max(l,u);if(l&&u)a[i-o]=Math.max(l,u);else{if(c>1)return;a[i-o]=0}}return a}static isValidBroadcast(t,e){let n=t.length,r=e.length;if(n>r)return!1;for(let s=1;s<=n;s++)if(t[n-s]!==1&&t[n-s]!==e[r-s])return!1;return!0}},D=class ua{static size(e){return ua.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,n=4){let r=e.length;if(r===0)return[];let s=new Array(r),i=r-1;for(;i>=0;){if(e[i]%n===0){s[i]=e[i]/n;break}if(n%e[i]!==0)throw new Error("cannot convert shape");s[i]=1,n/=e[i],i--}for(i--;i>=0;i--)s[i]=e[i];return s}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 ua.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 ua.getSizeFromDimensionRange(e,0,n)}static getSizeFromDimensionRange(e,n,r){let s=1;for(let i=n;i=0;--s)r[s]=r[s+1]*e[s+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((s,i)=>s+n[i]+n[i+r])}static areEqual(e,n){return e.length!==n.length?!1:e.every((r,s)=>r===n[s])}},ps=class Xr{static adjustPoolAttributes(e,n,r,s,i,a){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]||a[o+r.length]>=r[o])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,n,r,s,i,a,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(s.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ue(),pe(),qn=64,hs=(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"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${t}`)}},Le=(t,e=1)=>{let n=hs(t,e);return typeof n=="string"?n:n[0]},Ze=(t,e=1)=>{let n=hs(t,e);return typeof n=="string"?n:n[1]},se=(...t)=>{let e=[];return t.forEach(n=>{n.length!==0&&e.push({type:12,data:n},{type:12,data:D.computeStrides(n)})}),e},Ue=t=>t%4===0?4:t%2===0?2:1,kn=(t="f32",e,n="0")=>!e||e===1?`${t}(${n})`:`vec${e}<${t}>(${n})`,Gn=(t,e,n)=>t==="f32"?n:e===1?`f32(${n})`:`vec${e}(${n})`,sn=(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,re=(t,e,n,r)=>t.startsWith("uniforms.")&&n>4?typeof e=="string"?r==="f16"?`${t}[(${e}) / 8][(${e}) % 8 / 4][(${e}) % 8 % 4]`:`${t}[(${e}) / 4][(${e}) % 4]`:r==="f16"?`${t}[${Math.floor(e/8)}][${Math.floor(e%8/4)}][${e%8%4}]`:`${t}[${Math.floor(e/4)}][${e%4}]`:n>1?`${t}[${e}]`:t,fs=(t,e,n,r,s)=>{let i=typeof n=="number",a=i?n:n.length,o=[...new Array(a).keys()],l=a<2?"u32":a<=4?`vec${a}`:`array`,u=hs(e,s),c=typeof u=="string"?u:u[1],p=typeof u=="string"?u:u[0],d={indices:l,value:c,storage:p,tensor:e},f=O=>typeof O=="string"?O:`${O}u`,m={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=i?"uniforms.":"",w=`${g}${t}_shape`,v=`${g}${t}_strides`,y="";for(let O=0;O ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${y} + return indices; + }`,k=O=>(m.offsetToIndices=!0,a<2?O:`o2i_${t}(${O})`),E=[];if(a>=2)for(let O=a-1;O>=0;O--)E.push(`${re(v,O,a)} * (indices[${O}])`);let T=a<2?"":` + fn i2o_${t}(indices: ${d.indices}) -> u32 { + return ${E.join("+")}; + }`,C=O=>(m.indicesToOffset=!0,a<2?O:`i2o_${t}(${O})`),B=(...O)=>a===0?"0u":`${d.indices}(${O.map(f).join(",")})`,U=(O,q)=>a<2?`${O}`:`${re(O,q,a)}`,G=(O,q,ie)=>a<2?`${O}=${ie};`:`${re(O,q,a)}=${ie};`,K={},X=(O,q)=>{m.broadcastedIndicesToOffset=!0;let ie=`${q.name}broadcastedIndicesTo${t}Offset`;if(ie in K)return`${ie}(${O})`;let ge=[];for(let xe=a-1;xe>=0;xe--){let Ee=q.indicesGet("outputIndices",xe+q.rank-a);ge.push(`${U(v,xe)} * (${Ee} % ${U(w,xe)})`)}return K[ie]=`fn ${ie}(outputIndices: ${q.type.indices}) -> u32 { + return ${ge.length>0?ge.join("+"):"0u"}; + }`,`${ie}(${O})`},H=(O,q)=>(()=>{if(d.storage===d.value)return`${t}[${O}]=${q};`;if(d.storage==="vec2"&&d.value==="i32")return`${t}[${O}]=vec2(u32(${q}), select(0u, 0xFFFFFFFFu, ${q} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${t}[${O}]=vec2(u32(${q}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${t}[${O}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${q}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),J=O=>(()=>{if(d.storage===d.value)return`${t}[${O}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${t}[${O}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${t}[${O}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${t}[${O}] & 0xFFu), bool(${t}[${O}] & 0xFF00u), bool(${t}[${O}] & 0xFF0000u), bool(${t}[${O}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),ne=a<2?"":` + fn get_${t}ByIndices(indices: ${d.indices}) -> ${c} { + return ${J(`i2o_${t}(indices)`)}; + }`,I=a<2?"":(()=>{let O=o.map(ie=>`d${ie}: u32`).join(", "),q=o.map(ie=>`d${ie}`).join(", ");return` + fn get_${t}(${O}) -> ${c} { + return get_${t}ByIndices(${B(q)}); + }`})(),N=(...O)=>{if(O.length!==a)throw new Error(`indices length must be ${a}`);let q=O.map(f).join(",");return a===0?J("0u"):a===1?J(q[0]):(m.get=!0,m.getByIndices=!0,m.indicesToOffset=!0,`get_${t}(${q})`)},R=O=>a<2?J(O):(m.getByIndices=!0,m.indicesToOffset=!0,`get_${t}ByIndices(${O})`),Y=a<2?"":` + fn set_${t}ByIndices(indices: ${d.indices}, value: ${c}) { + ${H(`i2o_${t}(indices)`,"value")} + }`,te=a<2?"":(()=>{let O=o.map(ie=>`d${ie}: u32`).join(", "),q=o.map(ie=>`d${ie}`).join(", ");return` + fn set_${t}(${O}, value: ${c}) { + set_${t}ByIndices(${B(q)}, value); + }`})();return{impl:()=>{let O=[],q=!1;return m.offsetToIndices&&(O.push($),q=!0),m.indicesToOffset&&(O.push(T),q=!0),m.broadcastedIndicesToOffset&&(Object.values(K).forEach(ie=>O.push(ie)),q=!0),m.set&&(O.push(te),q=!0),m.setByIndices&&(O.push(Y),q=!0),m.get&&(O.push(I),q=!0),m.getByIndices&&(O.push(ne),q=!0),!i&&q&&O.unshift(`const ${w} = ${d.indices}(${n.join(",")});`,`const ${v} = ${d.indices}(${D.computeStrides(n).join(",")});`),O.join(` +`)},type:d,offsetToIndices:k,indicesToOffset:C,broadcastedIndicesToOffset:X,indices:B,indicesGet:U,indicesSet:G,set:(...O)=>{if(O.length!==a+1)throw new Error(`indices length must be ${a}`);let q=O[a];if(typeof q!="string")throw new Error("value must be string");let ie=O.slice(0,a).map(f).join(",");return a===0?H("0u",q):a===1?H(ie[0],q):(m.set=!0,m.setByIndices=!0,m.indicesToOffset=!0,`set_${t}(${ie}, ${q})`)},setByOffset:H,setByIndices:(O,q)=>a<2?H(O,q):(m.setByIndices=!0,m.indicesToOffset=!0,`set_${t}ByIndices(${O}, ${q});`),get:N,getByOffset:J,getByIndices:R,usage:r,name:t,strides:v,shape:w,rank:a}},L=(t,e,n,r=1)=>fs(t,e,n,"input",r),ae=(t,e,n,r=1)=>fs(t,e,n,"output",r),ja=(t,e,n,r=1)=>fs(t,e,n,"internal",r),Kl=class{constructor(t,e){this.normalizedDispatchGroup=t,this.limits=e,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=qn){let e=typeof t=="number"?t:t[0],n=typeof t=="number"?1:t[1],r=typeof t=="number"?1:t[2];if(e>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${e}, ${n}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(e*n*r>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${e}, ${n}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,i=s?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,a=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] + + 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}) { + ${a} + `}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)n==="f16"?t.push(`@align(16) ${e}:array, ${Math.ceil(r/8)}>`):t.push(`${e}:array, ${Math.ceil(r/4)}>`);else{let s=r==null||r===1?n:`vec${r}<${n}>`;t.push(`${e}:${s}`)}return` + struct Uniforms { ${t.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(` +`)+this.internalVariables.map(t=>t.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map(e=>[t(e.type),e.length??1])}},Xl=(t,e)=>new Kl(t,e),mr=(t,e)=>{let n=t.length,r=[];for(let s=0;s1&&a===1&&r.unshift(i)}return r}}),Ql,qa,Yl,Zl,Rt,Jl,eu,Wn=W(()=>{ue(),pe(),Fe(),he(),Ql=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},qa=(t,e)=>e&&e.length!==t?[...new Array(t).keys()].reverse():e,Yl=(t,e)=>D.sortBasedOnPerm(t,qa(t.length,e)),Zl=(t,e,n,r)=>{let s=[];s.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,s=qa(r,e),i=Yl(t.dims,s),a=ae("output",n,i.length),o=L("a",n,r),l;if(s.length===2&&s[0]===1&&s[1]===0){let u=a.type.value,c=[16,16,1];l=p=>` + ${p.registerUniform("output_size","u32").declareVariables(o,a)} + var tile : array, ${c[0]}>; + ${p.mainStart(c)} + var x = workgroup_id.x * ${c[0]}u + local_id.x; + var y = workgroup_id.y * ${c[0]}u + local_id.y; + let width = uniforms.output_shape[0]; + let height = uniforms.output_shape[1]; + if (x < width && y < height) { + tile[local_id.y][local_id.x] = ${o.getByOffset("y * width + x")}; + } + workgroupBarrier(); + x = workgroup_id.y * ${c[0]}u + local_id.x; + y = workgroup_id.x * ${c[0]}u + local_id.y; + if (x < height && y < width) { + ${a.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} + } + }`}else l=u=>` + ${u.registerUniform("output_size","u32").declareVariables(o,a)} + + ${Zl(s,r,o,a)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${a.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${a.setByOffset("global_idx",o.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:["rank"]},getRunData:()=>{let u=D.size(i);return{outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},...se(t.dims,i)]}},getShaderSource:l}},Jl=(t,e)=>{Ql(t.inputs),t.compute(Rt(t.inputs[0],e.perm))},eu=t=>$e({perm:t.perm})}),tu,nu,ru,su,au,iu,ou,lu,uu,du,Tt,cu,pu,hu,fu,mu,gu,_u,wu,yu,bu,o0=W(()=>{ue(),pe(),he(),Wa(),Wn(),tu={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"},nu={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"},ru={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},su={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},au=(t,e)=>{let n=[];for(let r=e-t;r{let n=[],r=t.length;for(let i=0;it[i]);return[n,s]},ou=(t,e)=>{let n=t.length+e.length,r=[],s=0;for(let i=0;i{for(let n=0;n{let n=[];if(!lu(t,e)){for(let r=0;rn.push(r))}return n},du=(t,e,n,r,s,i,a)=>{let o=n[0].dims,l=D.size(i),u=D.size(a),c=L("_A",n[0].dataType,o),p=ae("output",s,i),d=32,f=` + var aBestValues : array; + `;return{name:t,shaderCache:e,getShaderSource:m=>` + ${m.registerUniform("reduceSize","u32").declareVariables(c,p)} + ${f} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${m.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${ru[r]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${c.getByOffset("offset + k")}); + bestValue = ${tu[r]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${d}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 = ${nu[r]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${p.setByOffset("outputIndex",`${r==="mean"?`${p.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${p.type.storage}(${su[r]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},Tt=(t,e,n,r)=>{let s=t.inputs.length===1?n:Ga(t.inputs,n),i=s.axes;i.length===0&&!s.noopWithEmptyAxes&&(i=t.inputs[0].dims.map((f,m)=>m));let a=D.normalizeAxes(i,t.inputs[0].dims.length),o=a,l=t.inputs[0],u=uu(o,t.inputs[0].dims.length);u.length>0&&(l=t.compute(Rt(t.inputs[0],u),{inputs:[0],outputs:[-1]})[0],o=au(o.length,l.dims.length));let[c,p]=iu(l.dims,o),d=c;s.keepDims&&(d=ou(c,a)),t.compute(du(e,{hint:s.cacheKey,inputDependencies:["type"]},[l],r,t.inputs[0].dataType,d,p),{inputs:[l]})},cu=(t,e)=>{Tt(t,"ReduceMeanShared",e,"mean")},pu=(t,e)=>{Tt(t,"ReduceL1Shared",e,"l1")},hu=(t,e)=>{Tt(t,"ReduceL2Shared",e,"l2")},fu=(t,e)=>{Tt(t,"ReduceLogSumExpShared",e,"logSumExp")},mu=(t,e)=>{Tt(t,"ReduceMaxShared",e,"max")},gu=(t,e)=>{Tt(t,"ReduceMinShared",e,"min")},_u=(t,e)=>{Tt(t,"ReduceProdShared",e,"prod")},wu=(t,e)=>{Tt(t,"ReduceSumShared",e,"sum")},yu=(t,e)=>{Tt(t,"ReduceSumSquareShared",e,"sumSquare")},bu=(t,e)=>{Tt(t,"ReduceLogSumShared",e,"logSum")}}),Mt,vu,ms,Ga,Ct,xu,$u,ku,Su,Eu,Tu,Mu,Cu,Au,Iu,At,zu,Ou,Pu,Bu,Ru,Fu,Du,Nu,Lu,Uu,Wa=W(()=>{ue(),pe(),Fe(),he(),o0(),Mt=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.")},vu=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],ms=(t,e,n,r,s,i,a=!1,o=!1)=>{let l=[],u=n[0].dims,c=u.length,p=D.normalizeAxes(s,c),d=!o&&p.length===0;u.forEach((g,w)=>{d||p.indexOf(w)>=0?a&&l.push(1):l.push(g)});let f=l.length,m=D.size(l);return{name:t,shaderCache:e,getShaderSource:g=>{let w=[],v=L("_A",n[0].dataType,c),y=ae("output",i,f),$=r(v,y,p),k=$[2];for(let E=0,T=0;E=0?(a&&T++,k=`for(var j${E}: u32 = 0; j${E} < ${u[E]}; j${E}++) { + ${$[2].includes("last_index")?`let last_index = j${E};`:""} + ${v.indicesSet("input_indices",E,`j${E}`)} + ${k} + }`):(w.push(`${v.indicesSet("input_indices",E,y.indicesGet("output_indices",T))};`),T++);return` + + ${g.registerUniform("output_size","u32").declareVariables(v,y)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${v.type.indices}; + let output_indices = ${y.offsetToIndices("global_idx")}; + + ${w.join(` +`)} + ${$[0]} // init ops for reduce max/min + ${$[1]} + ${k} + ${$[3]} + ${$.length===4?y.setByOffset("global_idx","value"):$.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...se(u,l)]})}},Ga=(t,e)=>{let n=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(r=>n.push(Number(r))),$e({axes:n,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},Ct=(t,e,n,r)=>{let s=t.inputs,i=s.length===1?n:Ga(s,n);t.compute(ms(e,{hint:i.cacheKey,inputDependencies:["rank"]},[s[0]],i.noopWithEmptyAxes&&i.axes.length===0?vu:r,i.axes,s[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},xu=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceLogSum",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},$u=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceL1",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},ku=(t,e)=>{Mt(t.inputs),Ct(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);"])},Su=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceLogSumExp",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Eu=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceMax",e,(n,r,s)=>{let i=[];for(let a=0;a=0||s.length===0)&&i.push(n.indicesSet("input_indices",a,0));return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Tu=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceMean",e,(n,r,s)=>{let i=1;for(let a=0;a=0||s.length===0)&&(i*=t.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${r.type.value}(sum / ${i});`]})},Mu=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceMin",e,(n,r,s)=>{let i=[];for(let a=0;a=0||s.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Cu=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceProd",e,(n,r)=>[`var value = ${r.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Au=(t,e)=>{Mt(t.inputs),Ct(t,"ReduceSum",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Iu=(t,e)=>{Mt(t.inputs),Ct(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;`,""])},At=(t,e,n)=>{if(e.length===0)return n;let r=1,s=1;for(let i=0;i1024},zu=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Tu(t,e):cu(t,e)},Ou=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?$u(t,e):pu(t,e)},Pu=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?ku(t,e):hu(t,e)},Bu=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Su(t,e):fu(t,e)},Ru=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Eu(t,e):mu(t,e)},Fu=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Mu(t,e):gu(t,e)},Du=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Cu(t,e):_u(t,e)},Nu=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Au(t,e):wu(t,e)},Lu=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Iu(t,e):yu(t,e)},Uu=(t,e)=>{At(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?xu(t,e):bu(t,e)}}),Ha,Vu,ju,Ka,l0=W(()=>{ue(),Fe(),Wa(),Ha=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.")},Vu=(t,e)=>{Ha(t.inputs);let n=(r,s,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(`input_indices[${o}] = 0;`);return[`${a.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); + }`,"",s.setByOffset("global_idx","best_index")]};t.compute(ms("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],n,[e.axis],7,e.keepDims),{inputs:[0]})},ju=(t,e)=>{Ha(t.inputs);let n=(r,s,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(`input_indices[${o}] = 0;`);return[`${a.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); + }`,"",s.setByOffset("global_idx","best_index")]};t.compute(ms("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],n,[e.axis],7,e.keepDims),{inputs:[0]})},Ka=t=>$e(t)}),qu,Gu,Wu,Hu,gr,Ku,Xu,Xa=W(()=>{ue(),pe(),Fa(),he(),qu=(t,e)=>{let n=t[0],r=t[1],s=t[2],i=t[3],a=t[4],o=t[5];if(a&&o)throw new Error("Attention cannot have both past and attention_bias");if(n.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=n.dims[0],u=n.dims[1],c=n.dims[2];if(s.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(s.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let p=s.dims[0]/3,d=p,f=d;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let $ of e.qkvHiddenSizes)if($%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");p=e.qkvHiddenSizes[0],d=e.qkvHiddenSizes[1],f=e.qkvHiddenSizes[2]}let m=u;if(p!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==p+d+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(a){if(d!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==e.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==d/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(g=a.dims[3])}let w=m+g,v=-1,y=0;if(i)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(o){if(o.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(o.dims[0]!==l||o.dims[1]!==e.numHeads||o.dims[2]!==u||o.dims[3]!==w)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:g,kvSequenceLength:m,totalSequenceLength:w,maxSequenceLength:v,inputHiddenSize:c,hiddenSize:p,vHiddenSize:f,headSize:Math.floor(p/e.numHeads),vHeadSize:Math.floor(f/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:y,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Gu=(t,e,n)=>{let r=Ue(n),s=64,i=n/r;i{let f=ae("x",t.dataType,t.dims,r),m=Ze(t.dataType),g=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${d.registerUniforms(g).declareVariables(f)} + ${d.mainStart([s,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${s}) * uniforms.d_comp + local_offset; + + var thread_max_vector = ${u}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${u}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(r){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${r}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${s}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${u}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${u}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(r){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${r}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${s}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + x[offset + i] = ${f.type.value}(${m}(uniforms.d_inv)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${u}(x[offset + i]); + x[offset + i] = ${f.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${l};${r}`,inputDependencies:c},getShaderSource:p,getRunData:()=>({outputs:[],dispatchGroup:{x:e},programUniforms:o})}},Wu=(t,e,n,r,s,i,a,o)=>{let l=o+i.kvSequenceLength,u=[i.batchSize,i.numHeads,i.sequenceLength,l],c=i.kvNumHeads===void 0&&t>1&&r,p=c?[i.batchSize,i.numHeads,l,i.headSize]:void 0,d=a.scale===0?1/Math.sqrt(i.headSize):a.scale,f=Ue(i.headSize),m=i.headSize/f,g=12,w={x:Math.ceil(l/g),y:Math.ceil(i.sequenceLength/g),z:i.batchSize*i.numHeads},v=[{type:12,data:i.sequenceLength},{type:12,data:m},{type:12,data:l},{type:12,data:i.numHeads},{type:1,data:d},{type:12,data:o},{type:12,data:i.kvSequenceLength}],y=c&&r&&D.size(r.dims)>0,$=["type","type"];y&&$.push("type"),s&&$.push("type");let k=[{dims:u,dataType:e.dataType,gpuDataType:0}];c&&k.push({dims:p,dataType:e.dataType,gpuDataType:0});let E=T=>{let C=L("q",e.dataType,e.dims,f),B=L("key",n.dataType,n.dims,f),U=[C,B];if(y){let J=L("past_key",r.dataType,r.dims,f);U.push(J)}s&&U.push(L("attention_bias",s.dataType,s.dims));let G=ae("output",e.dataType,u),K=[G];c&&K.push(ae("present_key",e.dataType,p,f));let X=Ze(1,f),H=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${g}u; + + var tileQ: array<${C.type.storage}, ${g*g}>; + var tileK: array<${C.type.storage}, ${g*g}>; + ${T.registerUniforms(H).declareVariables(...U,...K)} + ${T.mainStart([g,g,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 qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + ${y&&c?` + let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; + let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` + let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} + ${c?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${X}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${y&&c?` + if (n + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else { + tileK[idx] = + key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; + }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} + ${c?"present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];":""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${X}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + let headOffset = headIdx * uniforms.M * uniforms.N; + if (global_id.y < uniforms.M && global_id.x < uniforms.N) { + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(f){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${f}`)}})()}; + output[outputIdx] = ${G.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${f};${s!==void 0};${r!==void 0};${t}`,inputDependencies:$},getRunData:()=>({outputs:k,dispatchGroup:w,programUniforms:v}),getShaderSource:E}},Hu=(t,e,n,r,s,i)=>{let a=i+s.kvSequenceLength,o=s.nReps?s.nReps:1,l=s.vHiddenSize*o,u=s.kvNumHeads==null&&t>1&&r,c=u?[s.batchSize,s.numHeads,a,s.headSize]:void 0,p=[s.batchSize,s.sequenceLength,l],d=12,f={x:Math.ceil(s.vHeadSize/d),y:Math.ceil(s.sequenceLength/d),z:s.batchSize*s.numHeads},m=[{type:12,data:s.sequenceLength},{type:12,data:a},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:l},{type:12,data:i},{type:12,data:s.kvSequenceLength}],g=u&&r&&D.size(r.dims)>0,w=["type","type"];g&&w.push("type");let v=[{dims:p,dataType:e.dataType,gpuDataType:0}];u&&v.push({dims:c,dataType:e.dataType,gpuDataType:0});let y=$=>{let k=L("probs",e.dataType,e.dims),E=L("v",n.dataType,n.dims),T=[k,E];g&&T.push(L("past_value",r.dataType,r.dims));let C=[ae("output",e.dataType,p)];u&&C.push(ae("present_value",e.dataType,c));let B=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${d}u; + var tileQ: array<${k.type.value}, ${d*d}>; + var tileK: array<${k.type.value}, ${d*d}>; + ${$.registerUniforms(B).declareVariables(...T,...C)} + ${$.mainStart([d,d,1])} + let headIdx = workgroup_id.z; + let m = global_id.y; + let n = global_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + ${g&&u?` + let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; + let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; + `:` + let offsetB = headIdx * uniforms.N * uniforms.K + n; + `} + ${u?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${k.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${g&&u?` + if (w + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else { + tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; + } + `:` + tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; + `} + ${u?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + let batchIdx = workgroup_id.z / uniforms.num_heads; + let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + currentBatchHeadNumber * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${r!==void 0};${t}`,inputDependencies:w},getRunData:()=>({outputs:v,dispatchGroup:f,programUniforms:m}),getShaderSource:y}},gr=(t,e,n,r,s,i,a,o,l,u,c)=>{let p=Math.min(t.outputCount,1+(a?1:0)+(o?1:0)),d=u.kvNumHeads!==void 0||p>1?u.pastSequenceLength:0,f=d+u.kvSequenceLength,m=l&&D.size(l.dims)>0?l:void 0,g=[e,n];u.kvNumHeads===void 0&&p>1&&a&&D.size(a.dims)>0&&g.push(a),m&&g.push(m);let w=t.compute(Wu(p,e,n,a,m,u,c,d),{inputs:g,outputs:u.kvNumHeads===void 0&&p>1?[-1,1]:[-1]})[0];t.compute(Gu(w,u.batchSize*u.numHeads*u.sequenceLength,f),{inputs:[w],outputs:[]});let v=[w,r];u.kvNumHeads===void 0&&p>1&&o&&D.size(o.dims)>0&&v.push(o),t.compute(Hu(p,w,r,o,u,d),{inputs:v,outputs:u.kvNumHeads===void 0&&p>1?[0,2]:[0]})},Ku=(t,e)=>{let n=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],r=e.sequenceLength,s=e.inputHiddenSize,i=e.headSize,a=12,o={x:Math.ceil(e.headSize/a),y:Math.ceil(e.sequenceLength/a),z:e.batchSize*e.numHeads},l=[t.inputs[0],t.inputs[1],t.inputs[2]],u=[{type:12,data:r},{type:12,data:s},{type:12,data:i},{type:12,data:e.numHeads},{type:12,data:e.headSize},{type:12,data:e.hiddenSize},{type:12,data:e.hiddenSize+e.hiddenSize+e.vHiddenSize}],c=p=>{let d=ae("output_q",l[0].dataType,n),f=ae("output_k",l[0].dataType,n),m=ae("output_v",l[0].dataType,n),g=L("input",l[0].dataType,l[0].dims),w=L("weight",l[1].dataType,l[1].dims),v=L("bias",l[2].dataType,l[2].dims),y=g.type.storage,$=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${a}u; + var tileInput: array<${y}, ${a*a}>; + var tileWeightQ: array<${y}, ${a*a}>; + var tileWeightK: array<${y}, ${a*a}>; + var tileWeightV: array<${y}, ${a*a}>; + ${p.registerUniforms($).declareVariables(g,w,v,d,f,m)} + ${p.mainStart([a,a,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${y}(0); + var valueK = ${y}(0); + var valueV = ${y}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims: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:u}),getShaderSource:c},{inputs:l,outputs:[-1,-1,-1]})},Xu=(t,e)=>{let n=qu(t.inputs,e),[r,s,i]=Ku(t,n);return gr(t,r,s,i,t.inputs[4],void 0,void 0,void 0,t.inputs[5],n,e)}}),Qu,Yu,Zu,Ju,u0=W(()=>{Et(),ue(),pe(),Fe(),he(),Qu=(t,e)=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(r,s,i)=>{let a=s.length;if(a!==r.length)throw new Error(`${i}: num dimensions != ${a}`);s.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")},Yu=(t,e)=>{let{epsilon:n,spatial:r,format:s}=e,i=t[0].dims,a=r?Ue(i[i.length-1]):1,o=s==="NHWC"&&i.length>1?a:1,l=D.size(i)/a,u=r,c=u?i.length:i,p=L("x",t[0].dataType,t[0].dims,a),d=L("scale",t[1].dataType,t[1].dims,o),f=L("bias",t[2].dataType,t[2].dims,o),m=L("inputMean",t[3].dataType,t[3].dims,o),g=L("inputVar",t[4].dataType,t[4].dims,o),w=ae("y",t[0].dataType,c,a),v=()=>{let $="";if(r)$=`let cOffset = ${i.length===1?"0u":s==="NHWC"?`outputIndices[${i.length-1}] / ${a}`:"outputIndices[1]"};`;else if(s==="NCHW")$=` + ${w.indicesSet("outputIndices","0","0")} + let cOffset = ${w.indicesToOffset("outputIndices")};`;else{$=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${i.length-1}];`;for(let k=1;k` + const epsilon = ${n}; + ${$.registerUniform("outputSize","u32").declareVariables(p,d,f,m,g,w)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${w.offsetToIndices(`global_idx * ${a}`)}; + ${v()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${f.getByOffset("cOffset")}; + let inputMean = ${m.getByOffset("cOffset")}; + let inputVar = ${g.getByOffset("cOffset")}; + let x = ${p.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${w.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${e.epsilon}_${e.format}_${r}_${a}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...se(i)]:[{type:12,data:l}]})}},Zu=t=>$e(t),Ju=(t,e)=>{let{inputs:n,outputCount:r}=t,s=Zu({...e,outputCount:r});if(Te.webgpu.validateInputContent&&Qu(n,s),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(Yu(n,s))}}),ed,td,nd,d0=W(()=>{pe(),he(),ed=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")},td=t=>{let e=t[0].dims,n=t[0].dims[2],r=D.size(e)/4,s=t[0].dataType,i=L("input",s,e,4),a=L("bias",s,[n],4),o=L("residual",s,e,4),l=ae("output",s,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:u=>` + const channels = ${n}u / 4; + ${u.declareVariables(i,a,o,l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(r)} + let value = ${i.getByOffset("global_idx")} + + ${a.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},nd=t=>{ed(t.inputs),t.compute(td(t.inputs))}}),rd,ye,sd,ad,id,od,ld,ud,dd,cd,pd,hd,fd,md,gd,_d,_r,wd,gs,yd,bd,vd,xd,$d,kd,Sd,Ed,Td,Md,Cd,Ad,Id,zd,Od,Pd,Qa,Bd,Ya,Za,Rd,Fd,Dd,Nd,Ld,Ud,Ja=W(()=>{ue(),pe(),Fe(),he(),rd=(t,e,n,r,s,i)=>{let a=Math.ceil(e/4),o="";typeof s=="string"?o=`${s}(a)`:o=s("a");let l=L("inputData",n,[a],4),u=ae("outputData",r,[a],4);return` + ${t.registerUniform("vec_size","u32").declareVariables(l,u)} + + ${i??""} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${l.getByOffset("global_idx")}; + ${u.setByOffset("global_idx",o)} + }`},ye=(t,e,n,r,s,i=t.dataType)=>({name:e,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:a=>rd(a,D.size(t.dims),t.dataType,i,n,r),getRunData:a=>({outputs:[{dims:t.dims,dataType:i}],dispatchGroup:{x:Math.ceil(D.size(a[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(D.size(t.dims)/4)}]})}),sd=t=>{t.compute(ye(t.inputs[0],"Abs","abs"))},ad=t=>{t.compute(ye(t.inputs[0],"Acos","acos"))},id=t=>{t.compute(ye(t.inputs[0],"Acosh","acosh"))},od=t=>{t.compute(ye(t.inputs[0],"Asin","asin"))},ld=t=>{t.compute(ye(t.inputs[0],"Asinh","asinh"))},ud=t=>{t.compute(ye(t.inputs[0],"Atan","atan"))},dd=t=>{t.compute(ye(t.inputs[0],"Atanh","atanh"))},cd=t=>$e(t),pd=(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(ye(t.inputs[0],"Cast",n,void 0,e.cacheKey,e.to))},hd=t=>{let e=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:Ua,n=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:Va;return $e({min:e,max:n})},fd=(t,e)=>{let n=t.inputs.length===1?e:hd(t.inputs),r=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"Clip",s=>`clamp(${s}, 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]})},md=t=>{t.compute(ye(t.inputs[0],"Ceil","ceil"))},gd=t=>{t.compute(ye(t.inputs[0],"Cos","cos"))},_d=t=>{t.compute(ye(t.inputs[0],"Cosh","cosh"))},_r=t=>$e(t),wd=(t,e)=>{let n=Ze(t.inputs[0].dataType);t.compute(ye(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))},gs=(t="f32")=>` +const r0: ${t} = 0.3275911; +const r1: ${t} = 0.254829592; +const r2: ${t} = -0.284496736; +const r3: ${t} = 1.421413741; +const r4: ${t} = -1.453152027; +const r5: ${t} = 1.061405429; + +fn erf_vf32(v: vec4<${t}>) -> vec4<${t}> { + let absv = abs(v); + let x = 1.0 / (1.0 + r0 * absv); + return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); +}`,yd=t=>{let e=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"Erf",n=>`erf_vf32(${n})`,gs(e)))},bd=t=>{t.compute(ye(t.inputs[0],"Exp","exp"))},vd=t=>{t.compute(ye(t.inputs[0],"Floor","floor"))},xd=t=>{let e=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,gs(e)))},$d=(t,e)=>{let n=Ze(t.inputs[0].dataType);t.compute(ye(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))},kd=t=>{t.compute(ye(t.inputs[0],"Not",e=>`!${e}`))},Sd=t=>{t.compute(ye(t.inputs[0],"Neg",e=>`-${e}`))},Ed=t=>{t.compute(ye(t.inputs[0],"Reciprocal",e=>`1.0/${e}`))},Td=t=>{let e=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"Relu",n=>`select(vec4<${e}>(0.0), ${n}, ${n} > vec4<${e}>(0.0))`))},Md=t=>{t.compute(ye(t.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},Cd=t=>$e(t),Ad=(t,e)=>{let n=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"HardSigmoid",r=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${e.alpha} * ${r} + vec4<${n}>(${e.beta})))`,void 0,e.cacheKey))},Id=t=>{t.compute(ye(t.inputs[0],"Sin","sin"))},zd=t=>{t.compute(ye(t.inputs[0],"Sinh","sinh"))},Od=t=>{t.compute(ye(t.inputs[0],"Sqrt","sqrt"))},Pd=t=>{t.compute(ye(t.inputs[0],"Tan","tan"))},Qa=t=>`sign(${t}) * (1 - exp(-2 * abs(${t}))) / (1 + exp(-2 * abs(${t})))`,Bd=t=>{t.compute(ye(t.inputs[0],"Tanh",Qa))},Ya=(t="f32")=>` +const fast_gelu_a: ${t} = 0.5; +const fast_gelu_b: ${t} = 0.7978845608028654; +const fast_gelu_c: ${t} = 0.035677408136300125; + +fn tanh_v(v: vec4<${t}>) -> vec4<${t}> { + return ${Qa("v")}; +} +`,Za=t=>`(fast_gelu_a + fast_gelu_a * tanh_v(${t} * (fast_gelu_c * ${t} * ${t} + fast_gelu_b))) * ${t}`,Rd=t=>{let e=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"FastGelu",Za,Ya(e),void 0,t.inputs[0].dataType))},Fd=(t,e)=>{let n=Ze(t.inputs[0].dataType);return t.compute(ye(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},Dd=t=>{t.compute(ye(t.inputs[0],"Log","log"))},Nd=(t,e)=>` +const alpha = vec4<${t}>(${e}); +const one = ${t}(1.0); +const zero = ${t}(0.0); + +fn quick_gelu_impl(x: vec4<${t}>) -> vec4<${t}> { + let v = x *alpha; + var x1 : vec4<${t}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,Ld=t=>`quick_gelu_impl(${t})`,Ud=(t,e)=>{let n=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"QuickGelu",Ld,Nd(n,e.alpha),e.cacheKey,t.inputs[0].dataType))}}),Vd,jd,qd,c0=W(()=>{pe(),he(),Ja(),Vd=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")},jd=t=>{let e=t[0].dims.slice();e[2]=e[2]/2;let n=L("input",t[0].dataType,t[0].dims,4),r=L("bias",t[0].dataType,[t[0].dims[2]],4),s=ae("output",t[0].dataType,e,4),i=D.size(e)/4,a=Le(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,s)} + + ${gs(a)} + + ${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); + + ${s.setByOffset("global_idx","valueLeft * geluRight")} + }`}},qd=t=>{Vd(t.inputs),t.compute(jd(t.inputs))}}),Gd,Wd,It,Hd,Kd,Xd,Qd,Yd,Zd,Jd,ec,tc,nc,p0=W(()=>{ue(),pe(),he(),Gd=(t,e,n,r,s,i,a,o,l,u,c,p)=>{let d,f;typeof o=="string"?d=f=(y,$)=>`${o}((${y}),(${$}))`:typeof o=="function"?d=f=o:(d=o.scalar,f=o.vector);let m=ae("outputData",c,r.length,4),g=L("aData",l,e.length,4),w=L("bData",u,n.length,4),v;if(s)if(i){let y=D.size(e)===1,$=D.size(n)===1,k=e.length>0&&e[e.length-1]%4===0,E=n.length>0&&n[n.length-1]%4===0;y||$?v=m.setByOffset("global_idx",f(y?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),$?`${w.type.value}(${w.getByOffset("0")}.x)`:w.getByOffset("global_idx"))):v=` + let outputIndices = ${m.offsetToIndices("global_idx * 4u")}; + let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",m)}; + let offsetB = ${w.broadcastedIndicesToOffset("outputIndices",m)}; + ${m.setByOffset("global_idx",f(a||k?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||E?w.getByOffset("offsetB / 4u"):`${w.type.value}(${w.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else v=m.setByOffset("global_idx",f(g.getByOffset("global_idx"),w.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=($,k,E="")=>{let T=`aData[indexA${k}][componentA${k}]`,C=`bData[indexB${k}][componentB${k}]`;return` + let outputIndices${k} = ${m.offsetToIndices(`global_idx * 4u + ${k}u`)}; + let offsetA${k} = ${g.broadcastedIndicesToOffset(`outputIndices${k}`,m)}; + let offsetB${k} = ${w.broadcastedIndicesToOffset(`outputIndices${k}`,m)}; + let indexA${k} = offsetA${k} / 4u; + let indexB${k} = offsetB${k} / 4u; + let componentA${k} = offsetA${k} % 4u; + let componentB${k} = offsetB${k} % 4u; + ${$}[${k}] = ${E}(${d(T,C)}); + `};c===9?v=` + var data = vec4(0); + ${y("data",0,"u32")} + ${y("data",1,"u32")} + ${y("data",2,"u32")} + ${y("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:v=` + ${y("outputData[global_idx]",0)} + ${y("outputData[global_idx]",1)} + ${y("outputData[global_idx]",2)} + ${y("outputData[global_idx]",3)} + `}return` + ${t.registerUniform("vec_size","u32").declareVariables(g,w,m)} + + ${p??""} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${v} + }`},Wd=(t,e,n,r,s,i,a=n.dataType)=>{let o=!D.areEqual(n.dims,r.dims),l=n.dims,u=D.size(n.dims),c=!1,p=!1,d=[o];if(o){let f=jn.calcShape(n.dims,r.dims,!1);if(!f)throw new Error("Can't perform binary op on the given tensors");l=f,u=D.size(l);let m=D.size(n.dims)===1,g=D.size(r.dims)===1,w=n.dims.length>0&&n.dims[n.dims.length-1]%4===0,v=r.dims.length>0&&r.dims[r.dims.length-1]%4===0;d.push(m),d.push(g),d.push(w),d.push(v);let y=1;for(let $=1;$f.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:f=>Gd(f,n.dims,r.dims,l,c,o,p,s,n.dataType,r.dataType,a,i),getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(D.size(l)/4)},...se(n.dims,r.dims,l)]})}},It=(t,e,n,r,s,i)=>{t.compute(Wd(e,s??"",t.inputs[0],t.inputs[1],n,r,i))},Hd=t=>{It(t,"Add",(e,n)=>`${e}+${n}`)},Kd=t=>{It(t,"Div",(e,n)=>`${e}/${n}`)},Xd=t=>{It(t,"Equal",{scalar:(e,n)=>`u32(${e}==${n})`,vector:(e,n)=>`vec4(${e}==${n})`},void 0,void 0,9)},Qd=t=>{It(t,"Mul",(e,n)=>`${e}*${n}`)},Yd=t=>{let e=L("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;It(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)); + } + `)},Zd=t=>{It(t,"Sub",(e,n)=>`${e}-${n}`)},Jd=t=>{It(t,"Greater",{scalar:(e,n)=>`u32(${e}>${n})`,vector:(e,n)=>`vec4(${e}>${n})`},void 0,void 0,9)},ec=t=>{It(t,"Less",{scalar:(e,n)=>`u32(${e}<${n})`,vector:(e,n)=>`vec4(${e}<${n})`},void 0,void 0,9)},tc=t=>{It(t,"GreaterOrEqual",{scalar:(e,n)=>`u32(${e}>=${n})`,vector:(e,n)=>`vec4(${e}>=${n})`},void 0,void 0,9)},nc=t=>{It(t,"LessOrEqual",{scalar:(e,n)=>`u32(${e}<=${n})`,vector:(e,n)=>`vec4(${e}<=${n})`},void 0,void 0,9)}}),rc,sc,ac,ic,oc,lc,h0=W(()=>{ue(),pe(),Fe(),he(),rc=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");let n=0,r=t[n],s=r.dataType,i=r.dims.length;t.forEach((a,o)=>{if(o!==n){if(a.dataType!==s)throw new Error("input tensors should be one type");if(a.dims.length!==i)throw new Error("input tensors should have the same shape");a.dims.forEach((l,u)=>{if(u!==e&&l!==r.dims[u])throw new Error("non concat dimensions must match")})}})},sc=(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; + }`,ac=(t,e)=>{let n=t.length,r=[];for(let s=0;s{let s=D.size(n),i=new Array(t.length),a=new Array(t.length),o=0,l=[],u=[],c=[{type:12,data:s}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(","),m=g=>` + + ${(()=>{g.registerUniform("outputSize","u32");for(let w=0;w(${f}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${ac(a,p)} + }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c}),getShaderSource:m}},oc=(t,e)=>{let n=t.inputs,r=n[0].dims,s=D.normalizeAxis(e.axis,r.length);rc(n,s);let i=r.slice();i[s]=n.reduce((o,l)=>o+(l.dims.length>s?l.dims[s]:0),0);let a=n.filter(o=>D.size(o.dims)>0);t.compute(ic(a,s,i,n[0].dataType),{inputs:a})},lc=t=>$e({axis:t.axis})}),an,on,ln,ei,un=W(()=>{ue(),pe(),an=(t,e,n="f32")=>{switch(t.activation){case"Relu":return`value = max(value, ${e}(0.0));`;case"Sigmoid":return`value = (${e}(1.0) / (${e}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${e}(${n}(uniforms.clip_min)), ${e}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${e}(0.0), min(${e}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${e}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${t.activation}`)}},on=(t,e)=>{t.activation==="Clip"?e.push({type:1,data:t.clipMax},{type:1,data:t.clipMin}):t.activation==="HardSigmoid"?e.push({type:1,data:t.alpha},{type:1,data:t.beta}):t.activation==="LeakyRelu"&&e.push({type:1,data:t.alpha})},ln=(t,e)=>{t.activation==="Clip"?e.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):t.activation==="HardSigmoid"?e.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):t.activation==="LeakyRelu"&&e.push({name:"alpha",type:"f32"})},ei=t=>{let e=(t==null?void 0:t.activation)||"";if(e==="HardSigmoid"){let[n,r]=(t==null?void 0:t.activation_params)||[.2,.5];return{activation:e,alpha:n,beta:r}}else if(e==="Clip"){let[n,r]=(t==null?void 0:t.activation_params)||[Ua,Va];return{activation:e,clipMax:r,clipMin:n}}else if(e==="LeakyRelu"){let[n]=(t==null?void 0:t.activation_params)||[.01];return{activation:e,alpha:n}}return{activation:e}}}),Je,ti,_s=W(()=>{Je=(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.`)}},ti=t=>` + ${t?"value = value + getBiasByOutputCoords(coords);":""} + `}),ni,uc=W(()=>{ni=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)); +} +`}),dc,cc,ws,ri,pc,ys,hc,si,bs=W(()=>{ue(),pe(),he(),un(),_s(),dc=(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":""}); + `,cc=(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];"} + }`,ws=(t,e,n="f32",r,s=!1,i=32,a=!1,o=32)=>{let l=e[1]*t[1],u=e[0]*t[0],c=s?l:i,p=s?i:l,d=c/e[0],f=i/e[1];if(!((s&&d===4&&t[1]===4||!s&&(d===3||d===4))&&c%e[0]===0&&i%e[1]===0&&t[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${d} and workPerThread[1] ${t[1]} must be 4. + Otherwise, innerElementSize ${d} 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/d}>, ${p}>; +var mm_Bsub: array, ${u/t[0]}>, ${i}>; + +const rowPerThread = ${t[1]}; +const colPerThread = ${t[0]}; +const innerElementSize = ${d}; +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 = ${a?"0":"i32(globalId.z)"}; + ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${a?`${Math.ceil(o/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${o}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${f}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${dc(s,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]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${cc(s,d)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},ri=(t,e)=>t?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${e?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${e?", batchIndices":""}); + `,pc=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ys=(t,e,n="f32",r,s=!1,i=32,a=!1,o=32,l=!1)=>{let u=t[1]*e[1],c=t[0]*e[0],p=s?u:i,d=s?i:u;if(!(d%e[1]===0&&p%e[0]===0&&i%e[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${p} must be divisible by workgroupSize[0]${e[0]}, tileInner ${i} must be divisible by workgroupSize[1]${e[1]}`);let f=d/e[1],m=p/e[0],g=i/e[1],w=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${u}; + let globalColStart = i32(workgroupId.x) * ${c}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${e[0]}) { + ${ri(s,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 = ${s?`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) * ${u}; + +let tileRowA = i32(localId.y) * ${f}; +let tileColA = i32(localId.x) * ${m}; +let tileRowB = i32(localId.y) * ${g}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${m}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${ri(s,r)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${g}; 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) { + ${pc(s)} + 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, ${d}>; + 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 = ${a?"0":"i32(globalId.z)"}; + ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${a?`${Math.ceil(o/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${o}`:"0"}; + + var acc : array, rowPerThread>; + ${w} + } +`},hc=(t,e,n,r,s,i=!1)=>{let[a,o,l]=s,[u,c,p,d]=r,f=mr(a,l),m=mr(o,l),g=Le(r[0].type.tensor),w=()=>{let y=c.rank,$=u.rank,k=`var aIndices: ${c.type.indices};`;for(let E=y-2-1,T=$-1;E>=0;E--,T--)k+=` +aIndices[${E}] = ${$>1?`batchIndices[${T}]`:"batchIndices"};`;return f.forEach(E=>{k+=` +aIndices[${E}] = 0;`}),k+=` +aIndices[${y-2}] = u32(row); + aIndices[${y-1}] = u32(colIn);`,k},v=()=>{let y=p.rank,$=u.rank,k=`var bIndices: ${p.type.indices};`;for(let E=y-2-1,T=$-1;E>=0;E--,T--)k+=` +bIndices[${E}] = ${$>1?`batchIndices[${T}]`:"batchIndices"};`;return m.forEach(E=>{k+=` +bIndices[${E}] = 0;`}),k+=` +bIndices[${y-2}] = u32(row); + bIndices[${y-1}] = u32(colIn);`,k};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${Je(t,g)} { + var value = ${Je(t,g)}(0.0); + let col = colIn * ${t}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${w()} + value = ${c.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${Je(t,g)} { + var value = ${Je(t,g)}(0.0); + let col = colIn * ${t}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${v()} + value = ${p.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Je(t,g)}) { + let col = colIn * ${t}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${e?`value = value + ${i?"bias[colIn]":`${Je(t,g)}(bias[row])`};`:""} + ${n} + ${d.setByIndices("vec3(coords)","value")} + } + } + `},si=(t,e,n,r,s=!1,i)=>{let a=t[0].dims,o=t[1].dims,l=a.slice(0,-2),u=o.slice(0,-2),c=r?r.slice(0,-2):n.slice(0,-2),p=D.size(c),d=a[a.length-2],f=a[a.length-1],m=o[o.length-1],g=f%4===0&&m%4===0,w=d<=8?[4,1,1]:[4,4,1],v=[8,8,1],y=[Math.ceil(m/v[0]/w[0]),Math.ceil(d/v[1]/w[1]),Math.ceil(p/v[2]/w[2])],$=g?4:1,k=[...l,d,f/$],E=k.length,T=[...u,f,m/$],C=T.length,B=[p,d,m/$],U=[{type:6,data:d},{type:6,data:m},{type:6,data:f}];on(e,U),U.push(...se(c,k,T));let G=["rank","rank"],K=t.length>2;K&&(U.push(...se(t[2].dims)),G.push("rank")),U.push(...se(B));let X=H=>{let J=c.length,ne=ja("batchDims",t[0].dataType,J,1),I=Le(t[0].dataType),N=L("a",t[0].dataType,E,$),R=L("b",t[1].dataType,C,$),Y=ae("result",t[0].dataType,B.length,$),te=[N,R];if(K){let xe=s?$:1;te.push(L("bias",t[2].dataType,t[2].dims.length,xe))}let O=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ln(e,O);let q=Le(Y.type.tensor),ie=an(e,Y.type.value,q),ge=hc($,K,ie,[ne,N,R,Y],[l,u,c],s);return` + ${H.registerUniforms(O).registerInternalVariables(ne).declareVariables(...te,Y)} + ${ge} + ${g?ws(w,v,I,ne):ys(w,v,I,ne)} + `};return{name:"MatMul",shaderCache:{hint:`${w};${e.activation};${g};${s}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:t[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:U}),getShaderSource:X}}}),fc,mc,f0=W(()=>{ue(),rn(),he(),un(),_s(),uc(),bs(),fc=(t,e,n,r,s=!1,i,a=4,o=4,l=4,u="f32")=>{let c=U=>{switch(U){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${U} is not supported.`)}},p=U=>{switch(U){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 ${U} is not supported.`)}},d=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); + `,m=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",g=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",w=t?"row":"col",v=t?"col":"row",y=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${w} / outWidth; + let outCol = ${w} % outWidth; + + let WRow = ${v} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${v} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${v} % inChannels; + var resData = ${Je(a,u)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${m} && xCol >= 0 && xCol < ${g}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${c(a)} + } + return resData;`,$=t?e&&r?` + let col = colIn * ${a}; + ${y}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${y} + } + return ${Je(a,u)}(0.0);`:r&&n?` + let col = colIn * ${a}; + ${y}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${y} + } + return ${Je(a,u)}(0.0);`,k=`${p(o)}`,E=Je(l,u),T=Je(t?a:o,u),C=Je(t?o:a,u),B=an(i,E,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${T} { + ${t?$:k} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${C} { + ${t?k:$} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${E}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${f} + ${ti(s)} + ${B} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},mc=(t,e,n,r,s,i,a,o,l)=>{let u=e.format==="NHWC",c=u?t[0].dims[3]:t[0].dims[1],p=n[0],d=u?n[2]:n[3],f=u?n[1]:n[2],m=u?n[3]:n[1],g=u&&(c%4===0||c%3===0)&&m%4===0,w=u?m:d*f,v=u?d*f:m,y=[8,8,1],$=r<=8?[4,1,1]:[4,4,1],k=[Math.ceil(w/y[0]/$[0]),Math.ceil(v/y[1]/$[1]),Math.ceil(p/y[2]/$[2])];Be("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${k}`);let E=g?u&&c%4!==0?3:4:1,T=y[1]*$[1],C=y[0]*$[0],B=Math.max(y[0]*E,y[1]),U=r%T===0,G=s%C===0,K=i%B===0,X=g?[E,4,4]:[1,1,1],H=[{type:6,data:r},{type:6,data:s},{type:6,data:i},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];on(e,H),H.push(...se(t[0].dims,t[1].dims));let J=["rank","rank"];a&&(H.push(...se(t[2].dims)),J.push("rank")),H.push(...se(n));let ne=I=>{let N=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];ln(e,N);let R=g?4:1,Y=Le(t[0].dataType),te=` + fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${Y}>`:Y}) { + result[flatIndex] = ${g?`vec4<${Y}>`:Y}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${Y}>`:Y}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${g?"/ 4":""}, value); + }`,O=L("x",t[0].dataType,t[0].dims.length,E===3?1:E),q=L("w",t[1].dataType,t[1].dims.length,R),ie=[O,q],ge=ae("result",t[0].dataType,n.length,R);if(a){let xe=L("bias",t[2].dataType,t[2].dims.length,R);ie.push(xe),te+=` + fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${Y}>`:Y} { + return bias[coords.${u?"w":"y"}${g?"/ 4":""}]; + }`}return` + ${ni("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 }; + ${I.registerUniforms(N).declareVariables(...ie,ge)} + ${te} + ${fc(u,U,G,K,a,e,X[0],X[1],X[2],Y)} + ${g?ws($,y,Y,void 0,!u,B):ys($,y,Y,void 0,!u,B,!1,void 0,o)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${E};${g};${U};${G};${K};${T};${C};${B}`,inputDependencies:J},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:t[0].dataType}],dispatchGroup:{x:k[0],y:k[1],z:k[2]},programUniforms:H}),getShaderSource:ne}}}),gc,ai,wr,_c,ii,wc,yc,bc,m0=W(()=>{ue(),rn(),pe(),he(),un(),_s(),gc=t=>{let e=1;for(let n=0;ntypeof t=="number"?[t,t,t]:t,wr=(t,e)=>e<=1?t:t+(t-1)*(e-1),_c=(t,e,n,r=1)=>{let s=wr(e,r);return Math.floor((t[0]*(n-1)-n+s)/2)},ii=(t,e,n,r,s)=>{s==null&&(s=_c(t,e[0],r[0]));let i=[0,0,0,n];for(let a=0;a<3;a++)t[a]+2*s>=e[a]&&(i[a]=Math.trunc((t[a]-e[a]+2*s)/r[a]+1));return i},wc=(t,e,n,r,s,i,a,o,l,u)=>{let c,p,d,f;if(t==="VALID"&&(t=0),typeof t=="number"){c={top:t,bottom:t,left:t,right:t,front:t,back:t};let m=ii([e,n,r,1],[o,l,u],1,[s,i,a],t);p=m[0],d=m[1],f=m[2]}else if(Array.isArray(t)){if(!t.every((g,w,v)=>g===v[0]))throw Error(`Unsupported padding parameter: ${t}`);c={top:t[0],bottom:t[1],left:t[2],right:t[3],front:t[4],back:t[5]};let m=ii([e,n,r,1],[o,l,u],1,[s,i,a],t[0]);p=m[0],d=m[1],f=m[2]}else if(t==="SAME_UPPER"){p=Math.ceil(e/s),d=Math.ceil(n/i),f=Math.ceil(r/a);let m=(p-1)*s+o-e,g=(d-1)*i+l-n,w=(f-1)*a+u-r,v=Math.floor(m/2),y=m-v,$=Math.floor(g/2),k=g-$,E=Math.floor(w/2),T=w-E;c={top:$,bottom:k,left:E,right:T,front:v,back:y}}else throw Error(`Unknown padding parameter: ${t}`);return{padInfo:c,outDepth:p,outHeight:d,outWidth:f}},yc=(t,e,n,r,s,i=!1,a="channelsLast")=>{let o,l,u,c,p;if(a==="channelsLast")[o,l,u,c,p]=t;else if(a==="channelsFirst")[o,p,l,u,c]=t;else throw new Error(`Unknown dataFormat ${a}`);let[d,,f,m,g]=e,[w,v,y]=ai(n),[$,k,E]=ai(r),T=wr(f,$),C=wr(m,k),B=wr(g,E),{padInfo:U,outDepth:G,outHeight:K,outWidth:X}=wc(s,l,u,c,w,v,y,T,C,B),H=i?d*p:d,J=[0,0,0,0,0];return a==="channelsFirst"?J=[o,H,G,K,X]:a==="channelsLast"&&(J=[o,G,K,X,H]),{batchSize:o,dataFormat:a,inDepth:l,inHeight:u,inWidth:c,inChannels:p,outDepth:G,outHeight:K,outWidth:X,outChannels:H,padInfo:U,strideDepth:w,strideHeight:v,strideWidth:y,filterDepth:f,filterHeight:m,filterWidth:g,effectiveFilterDepth:T,effectiveFilterHeight:C,effectiveFilterWidth:B,dilationDepth:$,dilationHeight:k,dilationWidth:E,inShape:t,outShape:J,filterShape:e}},bc=(t,e,n,r,s,i)=>{let a=i==="channelsLast";a?t[0].dims[3]:t[0].dims[1];let o=[64,1,1],l={x:n.map((w,v)=>v)},u=[Math.ceil(gc(l.x.map(w=>n[w]))/o[0]),1,1];Be("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let c=1,p=D.size(n),d=[{type:12,data:p},{type:12,data:r},{type:12,data:s},{type:12,data:e.strides},{type:12,data:e.dilations}];on(e,d),d.push(...se(t[0].dims,t[1].dims));let f=["rank","rank"],m=t.length===3;m&&(d.push(...se(t[2].dims)),f.push("rank")),d.push(...se(n));let g=w=>{let v=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:r.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:e.strides.length},{name:"dilations",type:"u32",length:e.dilations.length}];ln(e,v);let y=1,$=Le(t[0].dataType),k=L("x",t[0].dataType,t[0].dims.length,c),E=L("W",t[1].dataType,t[1].dims.length,y),T=[k,E],C=ae("result",t[0].dataType,n.length,y),B="";if(m){let K=L("bias",t[2].dataType,t[2].dims.length,y);T.push(K),B+=` + fn getBiasByOutputCoords(coords : array) -> ${$} { + return bias[${a?re("coords",4,5):re("coords",1,5)}]; + }`}let U=Je(c,$),G=an(e,U,$);return` + ${B} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${k.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${E.getByIndices("aIndices")}; + } + ${w.registerUniforms(v).declareVariables(...T,C)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${C.offsetToIndices("global_idx")}; + let batch = ${re("coords",0,k.rank)}; + let d2 = ${a?re("coords",k.rank-1,k.rank):re("coords",1,k.rank)}; + let xFRCCorner = vec3(${a?re("coords",1,k.rank):re("coords",2,k.rank)}, + ${a?re("coords",2,k.rank):re("coords",3,k.rank)}, + ${a?re("coords",3,k.rank):re("coords",4,k.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${a?re("uniforms.x_shape",1,k.rank):re("uniforms.x_shape",2,k.rank)}; + let xShapeZ = ${a?re("uniforms.x_shape",2,k.rank):re("uniforms.x_shape",3,k.rank)}; + let xShapeW = ${a?re("uniforms.x_shape",3,k.rank):re("uniforms.x_shape",4,k.rank)}; + let xShapeU = ${a?re("uniforms.x_shape",4,k.rank):re("uniforms.x_shape",1,k.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${a?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${a?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${a?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${m?"value = value + getBiasByOutputCoords(coords)":""}; + ${G} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${e.cacheKey};${a};${c};${m}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:d}),getShaderSource:g}}}),vc,xc,g0=W(()=>{ue(),pe(),he(),Cc(),un(),vc=(t,e,n)=>{let r=t.length>2,s=r?"value += b[output_channel];":"",i=t[0].dims,a=t[1].dims,o=a[0]/e.group,l=e.format==="NHWC",u=vs(i,a,e.dilations,e.pads,e.strides,l),c=D.size(u),p=[{type:12,data:c},{type:12,data:e.dilations},{type:12,data:[e.strides[0],e.strides[1]]},{type:12,data:[e.pads[0],e.pads[1]]},{type:12,data:o}];on(e,p),p.push(...se(i,a));let d=["rank","rank"];r&&(p.push(...se(t[2].dims)),d.push("rank")),p.push(...se(u));let f=m=>{let g=ae("output",t[0].dataType,u.length),w=Le(g.type.tensor),v=an(e,g.type.value,w),y=L("x",t[0].dataType,i.length),$=L("w",t[1].dataType,a.length),k=[y,$];r&&k.push(L("b",t[2].dataType,t[2].dims.length));let E=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:e.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return ln(e,E),` + ${m.registerUniforms(E).declareVariables(...k,g)} + + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${g.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${l?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${g.type.value} = ${g.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = group_id * uniforms.w_shape[1] + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[${l?1:2}]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[${l?2:3}]) { + continue; + } + + let xVal = ${l?y.get("batch","xHeight","xWidth","input_channel"):y.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${$.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${s} + ${v} + ${g.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:e.cacheKey,inputDependencies:d},getRunData:()=>({outputs:[{dims:n?n(u):u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:f}},xc=(t,e,n,r)=>{let s=t.length>2,i=Ue(n[3]),a=Ue(n[2]),o=D.size(n)/i/a,l=[t[0].dims[0],t[0].dims[1],t[0].dims[2],t[0].dims[3]/i],u=[t[1].dims[0],t[1].dims[1],t[1].dims[2],t[1].dims[3]/i],c=[n[0],n[1],n[2],n[3]/i],p=[{type:12,data:o},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];on(e,p),p.push(...se(l,u,c));let d=(a-1)*e.strides[1]+u[1],f=m=>{let g=ae("output",t[0].dataType,c.length,i),w=Le(g.type.tensor),v=an(e,g.type.value,w),y=L("x",t[0].dataType,l.length,i),$=L("w",t[1].dataType,u.length,i),k=[y,$];s&&k.push(L("b",t[2].dataType,t[2].dims,i));let E=s?"value += b[output_channel];":"",T=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ln(e,T),` + ${m.registerUniforms(T).declareVariables(...k,g)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${a}u; + let col = (index1 % width1) * ${a}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${y.type.value}, ${d}>; + var values: array<${g.type.value}, ${a}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${d}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${y.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${y.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${$.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${a}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${a}u; i++) { + var value = values[i]; + ${E} + ${v} + ${g.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${i};${a};${d};${u[0]};${u[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:f}}}),oi,$c,kc,Sc=W(()=>{ue(),pe(),bs(),he(),un(),oi=(t,e,n,r,s=!1,i)=>{let a=t[0].dims,o=t[1].dims,l=a[a.length-2],u=o[o.length-1],c=a[a.length-1],p=Ue(u),d=Ue(c),f=Ue(l),m=D.size(n)/p/f,g=t.length>2,w=r?r.slice(0,-2):n.slice(0,-2),v=[D.size(w),l,u],y=[{type:12,data:m},{type:12,data:l},{type:12,data:u},{type:12,data:c}];on(e,y),y.push(...se(w,a,o)),g&&y.push(...se(t[2].dims)),y.push(...se(v));let $=k=>{let E=ja("batch_dims",t[0].dataType,w.length),T=L("a",t[0].dataType,a.length,d),C=L("b",t[1].dataType,o.length,p),B=ae("output",t[0].dataType,v.length,p),U=Le(B.type.tensor),G=an(e,B.type.value,U),K=[T,C],X="";if(g){let te=s?p:1;K.push(L("bias",t[2].dataType,t[2].dims.length,te)),X=`${s?`value += bias[col / ${te}];`:`value += ${B.type.value}(bias[row + i]);`}`}let H=a.slice(0,-2),J=o.slice(0,-2),ne=mr(H,w),I=mr(J,w),N=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ln(e,N);let R=(te,O)=>{let q=te.rank,ie=te.name;if(q===2)return`var ${ie}_indices = ${te.type.indices}(0u, 0u);`;let ge=E.rank,xe=`var ${ie}_indices: ${te.type.indices};`;for(let Ee=q-2-1,ut=ge-1;Ee>=0;Ee--,ut--)xe+=` +${ie}_indices[${Ee}] = ${ge>1?`batch_indices[${ut}]`:"batch_indices"};`;return O.forEach(Ee=>{xe+=` +${ie}_indices[${Ee}] = 0;`}),xe+=`${ie}_indices[${q-2}] = 0u; + ${ie}_indices[${q-1}] = 0u;`,xe},Y=()=>{let te=`var a_data: ${T.type.value};`;for(let O=0;O; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${Y()} + } + for (var i = 0u; i < ${f}u; i++) { + var value = values[i]; + ${X} + ${G} + let cur_indices = ${B.type.indices}(batch, row + i, col); + let offset = ${B.indicesToOffset("cur_indices")}; + ${B.setByOffset(`offset / ${p}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${p};${d};${f};${s}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$}},$c=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.")},kc=t=>{$c(t.inputs);let e=jn.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(oi(t.inputs,{activation:""},e)):t.compute(si(t.inputs,{activation:""},e))}}),vs,xs,Ec,$s,li,ui,Tc,Mc,di,Cc=W(()=>{pe(),f0(),m0(),bs(),g0(),un(),Sc(),Wn(),vs=(t,e,n,r,s,i)=>{let a=t[0],o=t.slice(i?1:2,i?3:4),l=o.length,u=e[0],c=e.slice(2).map((d,f)=>d+(d-1)*(n[f]-1)),p=o.map((d,f)=>d+r[f]+r[f+l]).map((d,f)=>Math.floor((d-c[f]+s[f])/s[f]));return p.splice(0,0,a),p.splice(i?3:1,0,u),p},xs=[2,3,1,0],Ec=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length>5)throw new Error("greater than 5D is not supported");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 s=t[0].dims.length-2;if(e.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(e.strides.length!==s)throw new Error(`strides should be ${s}D`);if(e.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape")},$s=(t,e)=>{let n=t.kernelShape.slice();for(let i=2;i{let e=ei(t),n=t.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],s=t.dilations,i=t.group,a=t.kernel_shape,o=t.pads,l=t.strides,u=t.w_is_const();return{autoPad:r,format:n,dilations:s,group:i,kernelShape:a,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${t.format};${e.activation};`}},ui=(t,e,n,r)=>{let s=n.format==="NHWC";if(n.group!==1){if(!t.adapterInfo.isArchitecture("ampere")&&s&&e[1].dims[0]===n.group&&e[1].dims[1]===1&&n.dilations[0]===1&&n.dilations[1]===1){let T=vs(e[0].dims,e[1].dims,n.dilations,n.pads,n.strides,s),C=t.kernelCustomData.wT??t.compute(Rt(e[1],xs),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=C);let B=[e[0],C];e.length===3&&B.push(e[2]),t.compute(xc(B,n,T,r),{inputs:B})}else t.compute(vc(e,n,r));return}let i=e.length===3,a=e[0].dims[s?1:2],o=e[0].dims[s?2:3],l=e[0].dims[s?3:1],u=e[1].dims[2],c=e[1].dims[3],p=vs(e[0].dims,e[1].dims,n.dilations,n.pads,n.strides,s),d=p[s?1:2],f=p[s?2:3],m=p[s?3:1],g=s&&u===a&&c===o&&n.pads[0]===0&&n.pads[1]===0;if(g||u===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 T=p[0],C,B,U,G=[];if(s){let H=t.kernelCustomData.wT??t.compute(Rt(e[1],xs),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=H),g){let J=a*o*l;C=e[0].reshape([1,T,J]),B=H.reshape([1,J,m]),U=[1,T,m]}else C=e[0].reshape([T,a*o,l]),B=H.reshape([1,l,m]),U=[T,d*f,m];G.push(C),G.push(B)}else C=e[0].reshape([T,l,a*o]),B=e[1].reshape([1,m,l]),U=[T,m,d*f],G.push(B),G.push(C);i&&G.push(e[2]);let K=U[2],X=G[0].dims[G[0].dims.length-1];K<8&&X<8?t.compute(oi(G,n,p,U,s,r),{inputs:G}):t.compute(si(G,n,p,U,s,r),{inputs:G});return}let w=!0,v=t.kernelCustomData.wT??t.compute(Rt(e[1],xs),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=v);let y=[e[0],v];i&&y.push(e[2]);let $=s?d*f:m,k=s?m:d*f,E=u*c*l;t.compute(mc(y,n,p,$,k,E,i,w,r),{inputs:y})},Tc=(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 s=[0,e.pads[0],0,e.pads[1]],i=[1].concat(e.strides),a=[1].concat(e.dilations),o=[1].concat(e.kernelShape),l=$s({...e,pads:s,strides:i,dilations:a,kernelShape:o},r);ui(t,r,l,u=>n?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},Mc=(t,e,n)=>{let r=n.format==="NHWC"?"channelsLast":"channelsFirst",s=$s(n,e),i=n.autoPad==="NOTSET"?n.pads:n.autoPad,a=yc(e[0].dims,e[1].dims,n.strides,n.dilations,i,!1,r);t.compute(bc(e,s,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],r))},di=(t,e)=>{if(Ec(t.inputs,e),t.inputs[0].dims.length===3)Tc(t,e);else if(t.inputs[0].dims.length===5)Mc(t,t.inputs,e);else{let n=$s(e,t.inputs);ui(t,t.inputs,n)}}}),Ac,Ic,_0=W(()=>{ue(),rn(),he(),un(),_s(),uc(),bs(),Ac=(t,e=!1,n,r,s=4)=>{let i=w=>{switch(w){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 ${r}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${w} is not supported.`)}},a=t?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,o=t?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,l=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",u=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",c=t?"row":"col",p=t?"col":"row",d=` + let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${c} / outWidth; + let outCol = ${c} % outWidth; + + let WRow = ${p} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${p} / inChannels % uniforms.filter_dims[1]; + let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(${l}) || fract(xR) > 0.0) { + return ${r}(0.0); + } + if (xC < 0.0 || xC >= f32(${u}) || fract(xC) > 0.0) { + return ${r}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${p} % inChannels; + ${a} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,f=t?` + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${d} + } + return ${r}(0.0);`:` + let col = colIn * ${s}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${d} + } + return ${r}(0.0);`,m=` + let col = colIn * ${s}; + let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); + let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; + if (${t?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4(coordX, coordY, col, rowInner); + ${i(s)} + } + return ${r}(0.0); + `,g=an(n,r);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${r} { + ${t?f:m} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${r} { + ${t?m:f} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${r}) { + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${o} + ${ti(e)} + ${g} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; + } + }`},Ic=(t,e,n,r,s,i,a,o)=>{let l=e.format==="NHWC",u=l?t[0].dims[3]:t[0].dims[1],c=n[0],p=l?n[2]:n[3],d=l?n[1]:n[2],f=l?n[3]:n[1],m=l&&u%4===0&&u%3&&f%4===0,g=l?f:p*d,w=l?p*d:f,v=[8,8,1],y=r<=8?[4,1,1]:[4,4,1],$=[Math.ceil(g/v[0]/y[0]),Math.ceil(w/v[1]/y[1]),Math.ceil(c/v[2]/y[2])];Be("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${$}`);let k=m?4:1,E=Math.max(v[0]*k,v[1]),T=m?4:1,C=[e.kernelShape[l?1:2],e.kernelShape[l?2:3]],B=[C[0]+(e.dilations[0]<=1?0:(C[0]-1)*(e.dilations[0]-1)),C[1]+(e.dilations[1]<=1?0:(C[1]-1)*(e.dilations[1]-1))],U=[B[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),B[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],G=[{type:6,data:r},{type:6,data:s},{type:6,data:i},{type:6,data:e.strides},{type:6,data:e.dilations},{type:6,data:C},{type:6,data:U}];on(e,G),G.push(...se(t[0].dims,t[1].dims));let K=["rank","rank"];a&&(G.push(...se(t[2].dims)),K.push("rank")),G.push(...se(n));let X=H=>{let J=L("x",t[0].dataType,t[0].dims.length,T),ne=L("w",t[1].dataType,t[1].dims.length,1),I=ae("result",t[0].dataType,n.length,T),N=[J,ne],R="";if(a){let O=L("bias",t[2].dataType,t[2].dims.length,T);N.push(O),R+=` + fn getBiasByOutputCoords(coords : vec4) -> ${O.type.value} { + return bias[coords.${l?"w":"y"}${m?"/ 4":""}]; + }`}let Y=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:C.length},{name:"pads",type:"i32",length:U.length}];ln(e,Y);let te=Le(t[0].dataType,1);if(te!=="f16"&&te!=="f32")throw new Error(`elemType ${te} is not supported.`);return` + ${ni("uniforms.result_strides")} + ${H.registerUniforms(Y).declareVariables(...N,I)}; + ${R} + ${Ac(l,a,e,J.type.value,k)} + ${m?ws(y,v,te,void 0,!l,E):ys(y,v,te,void 0,!l,E,!1,void 0,o)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${e.cacheKey};${y};${v};${m}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:G}),getShaderSource:X}}}),zc,ci,w0=W(()=>{ue(),rn(),pe(),he(),zc=(t,e,n,r,s,i=!1,a,o,l=!1)=>{let u=l?1:2,c=l?2:3,p=l?3:1,d=i?2:1,f=` + fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${a}>`:a}) { + result[flatIndex] = ${i?`vec4<${a}>`:a}(value); + }`;r&&(f+=` + fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${a}>`:a} { + return bias[coords.${l?"w":"y"}${i?"/ 4":""}]; + }`);let m=i?4:1,g=L("W",e[1].dataType,e[1].dims.length,m),w=L("Dy",e[0].dataType,e[0].dims.length,m),v=[w,g];r&&v.push(L("bias",e[2].dataType,[n[p]].length,m));let y=ae("result",e[0].dataType,n.length,m),$=`{ + let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${s?"global_id.y":"workgroup_id.y"} * ${d}; + let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${d}>; + for (var i = 0; i < ${d}; i++) { + dotProd[i] = vec4<${a}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { + let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y); + let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${w.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${w.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${p}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${w.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${w.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${d}; i = i + 1) { + let value = dotProd[i] + ${r?"bias[c+i]":`vec4<${a}>(0.0)`}; + ${y.set("batch","r","c + i","d1","value")}; + } + }`,k=` + let outputIndices = ${y.offsetToIndices("global_idx")}; + let batch = ${y.indicesGet("outputIndices",0)}; + let d1 = ${y.indicesGet("outputIndices",p)}; + let r = ${y.indicesGet("outputIndices",u)}; + let c = ${y.indicesGet("outputIndices",c)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${a}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${u}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${c}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { + let xValue = ${l?w.get("batch","idyR","idyC","inputChannel"):w.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${g.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${r?"bias[d1]":`${a}(0.0)`}; + ${y.setByOffset("global_idx","value")}; + `;return` + ${t.registerUniforms(o).declareVariables(...v,y)} + ${f} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${i?$:k}}`},ci=(t,e,n)=>{let r=t.length>2,s=e.outputShape,i=D.size(s),a=[Math.ceil(i/64),1,1];Be("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let o=e.format==="NHWC",l=["rank","rank"],u=[e.strides[0],e.strides[1]],c=[e.kernelShape[o?1:2],e.kernelShape[o?2:3]],p=[e.dilations[0],e.dilations[1]],d=[c[0]+(e.dilations[0]<=1?0:(e.kernelShape[o?1:2]-1)*(e.dilations[0]-1)),c[1]+(e.dilations[1]<=1?0:(e.kernelShape[o?2:3]-1)*(e.dilations[1]-1))],f=[d[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),d[1]-1-Math.floor(e.pads[1]+e.pads[3])/2],m=!1,g=e.group,w=t[1].dims,v=w[0]/g,y=w[1],$=[{type:12,data:i},{type:12,data:u},{type:12,data:c},{type:12,data:p},{type:12,data:d},{type:6,data:f},{type:12,data:v},{type:12,data:y},...se(t[0].dims,t[1].dims)];r&&($.push(...se(t[2].dims)),l.push("rank")),$.push(...se(s));let k=a[1]===1&&a[2]===1,E=T=>{let C=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:u.length},{name:"filter_dims",type:"u32",length:c.length},{name:"dilations",type:"u32",length:c.length},{name:"effective_filter_dims",type:"u32",length:d.length},{name:"pads",type:"i32",length:f.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],B=Le(t[0].dataType);return`${zc(T,t,s,r,k,m,B,C,o)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:n?n(s):s,dataType:t[0].dataType}],programUniforms:$}),getShaderSource:E}}}),Oc,Pc,Bc,pi,Rc,Fc,Dc,Nc,Lc,Uc,y0=W(()=>{_0(),w0(),un(),Wn(),Oc=(t,e,n,r,s,i)=>(t-1)*e+n+(r-1)*s+1-i,Pc=(t,e,n,r,s)=>{let i=Math.floor(t/2);e==="SAME_UPPER"?(n[r]=i,n[s]=t-i):e==="SAME_LOWER"&&(n[r]=t-i,n[s]=i)},Bc=(t,e,n,r,s,i,a,o,l,u)=>{let c=t.length-2,p=u.length===0;if(l.length===0)for(let m=0;m{let n=t.kernelShape.slice();if(t.kernelShape.length===0||t.kernelShape.reduce((p,d)=>p*d,1)===0){n.length=0;for(let p=2;pp+d,0)===0){let p=e[0].dims.length-2;l=new Array(p).fill(1)}let u=t.strides.slice();if(u.reduce((p,d)=>p+d,0)===0){let p=e[0].dims.length-2;u=new Array(p).fill(1)}Bc(o,n,l,t.autoPad,t.group,s,u,r,a,i);let c=Object.assign({},t);return Object.assign(c,{kernelShape:n,pads:s,outputPadding:a,outputShape:i,dilations:l,strides:u}),c},Rc=t=>{let e=ei(t),n=t.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof t.autoPad>"u"?0:t.autoPad],s=t.dilations,i=t.group,a=t.kernelShape,o=t.pads,l=t.strides,u=t.wIsConst(),c=t.outputPadding,p=t.outputShape;return{autoPad:r,format:n,dilations:s,group:i,kernelShape:a,outputPadding:c,outputShape:p,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${t.format};${e.activation};`}},Fc=(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 s=t[1].dims[1]*e.group;if(t.length===3&&(t[2].dims.length!==1||t[2].dims[0]!==s))throw new Error("invalid bias");let i=t[0].dims.length-2;if(e.dilations.reduce((a,o)=>a+o,0)>0&&e.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(e.strides.reduce((a,o)=>a+o,0)>0&&e.strides.length!==i)throw new Error(`strides should be ${i}D`);if(e.pads.reduce((a,o)=>a+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((a,o)=>a+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")},Dc=[2,3,1,0],Nc=(t,e,n)=>{let r=pi(n,e),s=n.format==="NHWC",i=r.outputShape,a=i[s?3:1],o=e[0].dims[s?3:1];if(r.group!==1||a===1&&o===1){t.compute(ci(e,r));return}let l=i[s?1:2],u=i[s?2:3],c=e[1].dims[2],p=e[1].dims[3],d=s?l*u:a,f=s?a:l*u,m=c*p*o,g=!0,w=t.kernelCustomData.wT??t.compute(Rt(e[1],Dc),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=w);let v=[e[0],w],y=e.length===3;y&&(!s&&e[2].dims.length===1?v.push(e[2].reshape([e[2].dims[0],1,1])):v.push(e[2])),t.compute(Ic(v,r,i,d,f,m,y,g),{inputs:v})},Lc=(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 s=e.kernelShape;(s.length===0||s[0]===0)&&(s=[t.inputs[1].dims[2]]);let i=e.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=e.strides;(a.length===0||a[0]===0)&&(a=[1]);let o=e.pads;o.length===0&&(o=[0,0]),o=[0,o[0],0,o[1]],a=[1].concat(a),i=[1].concat(i),s=[1].concat(s);let l=pi({...e,pads:o,strides:a,dilations:i,kernelShape:s},r);t.compute(ci(r,l,u=>n?[u[0],u[2],u[3]]:[u[0],u[1],u[3]]))},Uc=(t,e)=>{Fc(t.inputs,e),t.inputs[0].dims.length===3?Lc(t,e):Nc(t,t.inputs,e)}}),Vc,jc,qc,b0=W(()=>{ue(),pe(),Fe(),he(),Vc=(t,e,n,r)=>{let s=D.size(e),i=e.length,a=L("input",t,i),o=ae("output",t,i),l=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),u=D.normalizeAxis(l,i),c=p=>{let d=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,f=re("uniforms.input_shape","uniforms.axis",i),m=r.reverse?d+(r.exclusive?" + 1":""):"0",g=r.reverse?f:d+(r.exclusive?"":" + 1");return` + ${p.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,o)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${o.offsetToIndices("global_idx")}; + var sum = ${o.type.value}(0); + let first : i32 = ${m}; + let last : i32 = ${g}; + for (var i : i32 = first; i < last; i++) { + ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${a.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(s/64)},programUniforms:[{type:12,data:s},{type:12,data:u},...se(e,e)]}),getShaderSource:c}},jc=(t,e)=>{let n=t.inputs[0].dims,r=t.inputs[0].dataType,s=t.inputs[1];t.compute(Vc(r,n,s,e),{inputs:[0]})},qc=t=>{let e=t.exclusive===1,n=t.reverse===1;return $e({exclusive:e,reverse:n})}}),Gc,Wc,Hc,Kc,Xc,v0=W(()=>{ue(),pe(),Fe(),he(),Gc=t=>{if(!t||t.length!==1)throw new Error("DepthToSpace requires 1 input.");if(t[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Wc=(t,e,n,r)=>{let s=[];s.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} { + var a: ${n.type.indices};`);for(let i=0;i{let n,r,s,i,a,o,l=e.format==="NHWC",u=e.blocksize,c=e.mode==="DCR";l?([n,r,s,i]=t.dims,a=c?[n,r,s,u,u,i/u**2]:[n,r,s,i/u**2,u,u],o=c?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,r,s,i]=[t.dims[0],t.dims[2],t.dims[3],t.dims[1]],a=c?[n,u,u,i/u**2,r,s]:[n,i/u**2,u,u,r,s],o=c?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let p=t.reshape(a),d=p.dims.length,f=t.dataType,m=L("a",f,d),g=ae("output",f,d),w=v=>` + ${v.registerUniform("output_size","u32").declareVariables(m,g)} + + ${Wc(o,d,m,g)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${g.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${g.setByOffset("global_idx",m.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${t.dims};${e.blocksize};${e.mode}`,inputDependencies:["rank"]},getRunData:v=>{let y=l?[n,r*u,s*u,i/u**2]:[n,i/u**2,r*u,s*u],$=D.size(y),k=p.dims,E=D.sortBasedOnPerm(k,o);return{outputs:[{dims:y,dataType:v[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...se(k,E)]}},getShaderSource:w}},Kc=(t,e)=>{Gc(t.inputs),t.compute(Hc(t.inputs[0],e))},Xc=t=>$e({blocksize:t.blocksize,mode:t.mode,format:t.format})}),ks,yr,hi,Qc,Yc,Zc,Jc,fi,ep,tp,np,x0=W(()=>{ue(),pe(),Fe(),he(),ks="[a-zA-Z]|\\.\\.\\.",yr="("+ks+")+",hi="^"+yr+"$",Qc="("+yr+",)*"+yr,Yc="^"+Qc+"$",Zc=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)}},Jc=class{constructor(t,e){var s;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(Yc)))throw new Error("Invalid LHS term");if(n.split(",").forEach((i,a)=>{let o=t[a].dims.slice();if(!i.match(RegExp(hi)))throw new Error("Invalid LHS term");let l=this.processTerm(i,!0,o,a);this.lhs.push(l)}),r==="")r+=[...this.symbolToInfo.entries()].filter(([i,a])=>a.count===1||i==="...").map(([i])=>i).join("");else if(!r.match(RegExp(yr)))throw new Error("Invalid RHS");(s=r.match(RegExp(ks,"g")))==null||s.forEach(i=>{if(i==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(i);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.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 s=n.length,i=!1,a=[],o=0;if(!t.match(RegExp(hi))&&!e&&t!=="")throw new Error("Invalid LHS term");let l=t.match(RegExp(ks,"g")),u=new Zc(r);return l==null||l.forEach((c,p)=>{if(c==="..."){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let d=s-l.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(a=n.slice(o,o+d),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(e)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;ft+"_max",ep=(t,e,n,r)=>{let s=t.map(u=>u.length).map((u,c)=>L(`input${c}`,e,u)),i=D.size(r),a=ae("output",e,r.length),o=[...n.symbolToInfo.keys()].filter(u=>!n.rhs.symbolToIndices.has(u)),l=u=>{let c=[],p="var prod = 1.0;",d="var sum = 0.0;",f="sum += prod;",m=[],g=[],w=[],v=[],y=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach((k,E)=>{var T;if(n.rhs.symbolToIndices.has(E)){let C=(T=n.rhs.symbolToIndices.get(E))==null?void 0:T[0];C!==void 0&&n.lhs.forEach((B,U)=>{if(k.inputIndices.includes(U)){let G=B.symbolToIndices.get(E);if(G===void 0)throw new Error("Invalid symbol error");G.forEach(K=>{c.push(`${s[U].indicesSet(`input${U}Indices`,K,a.indicesGet("outputIndices",C))}`)})}})}else n.lhs.forEach((C,B)=>{if(k.inputIndices.includes(B)){let U=C.symbolToIndices.get(E);if(U===void 0)throw new Error("Invalid symbol error");U.forEach(G=>{m.push(`${s[B].indicesSet(`input${B}Indices`,G,`${E}`)}`)}),v.push(`prod *= ${s[B].getByIndices(`input${B}Indices`)};`)}}),g.push(`for(var ${E}: u32 = 0; ${E} < uniforms.${fi(E)}; ${E}++) {`),w.push("}")});let $=y?[...c,`let sum = ${s.map((k,E)=>k.getByIndices(`input${E}Indices`)).join(" * ")};`]:[...c,d,...g,...m,p,...v,f,...w];return` + ${u.registerUniforms(o.map(k=>({name:`${fi(k)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,a)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${a.offsetToIndices("global_idx")}; + ${s.map((k,E)=>`var input${E}Indices: ${s[E].type.indices};`).join(` +`)} + ${$.join(` +`)}; + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:t.map(()=>"rank")},getRunData:()=>{let u=o.filter(p=>n.symbolToInfo.has(p)).map(p=>{var d;return{type:12,data:((d=n.symbolToInfo.get(p))==null?void 0:d.dimValue)||0}});u.push({type:12,data:i});let c=t.map((p,d)=>[...se(p)]).reduce((p,d)=>p.concat(d),u);return c.push(...se(r)),{outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c}},getShaderSource:l}},tp=(t,e)=>{let n=new Jc(t.inputs,e.equation),r=n.outputDims,s=t.inputs.map((i,a)=>i.dims);t.compute(ep(s,t.inputs[0].dataType,n,r))},np=t=>{let e=t.equation.replace(/\s+/g,"");return $e({equation:e})}}),rp,mi,sp,ap,ip,$0=W(()=>{ue(),pe(),he(),rp=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 s=0;st.length>e.length?mi(t,e):mi(e,t),ap=t=>{let e=t[0].dims,n=Array.from(t[1].getBigInt64Array(),Number),r=sp(e,n),s=t[0].dataType,i=s===9?4:1,a=Math.ceil(D.size(r)/i),o=u=>{let c=L("input",s,e.length,i),p=ae("output",s,r.length,i),d;if(s===9){let f=(m,g,w="")=>` + let outputIndices${g} = ${p.offsetToIndices(`outputOffset + ${g}u`)}; + let offset${g} = ${c.broadcastedIndicesToOffset(`outputIndices${g}`,p)}; + let index${g} = offset${g} / 4u; + let component${g} = offset${g} % 4u; + ${m}[${g}] = ${w}(${c.getByOffset(`index${g}`)}[component${g}]); + `;d=` + let outputOffset = global_idx * ${i}; + var data = vec4(0); + ${f("data",0,"u32")} + ${f("data",1,"u32")} + ${f("data",2,"u32")} + ${f("data",3,"u32")} + ${p.setByOffset("global_idx","data")} + }`}else d=` + let outputIndices = ${p.offsetToIndices("global_idx")}; + let inputOffset = ${c.broadcastedIndicesToOffset("outputIndices",p)}; + ${p.setByOffset("global_idx",c.getByOffset("inputOffset"))} + }`;return` + ${u.registerUniform("vec_size","u32").declareVariables(c,p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${d}`},l=[{type:12,data:a},...se(e,r)];return{name:"Expand",shaderCache:{hint:`${r.length}`,inputDependencies:["rank"]},getShaderSource:o,getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},ip=t=>{rp(t.inputs),t.compute(ap(t.inputs),{inputs:[0]})}}),op,lp,k0=W(()=>{ue(),pe(),he(),Ja(),op=t=>{let e=t[0].dataType,n=D.size(t[0].dims),r=D.size(t[1].dims),s=r%4===0,i=a=>{let o=L("x",e,[1],4),l=L("bias",e,[1],4),u=ae("y",e,[1],4),c=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],p=f=>` + let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; + let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,d=s?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${p(0)}${p(1)}${p(2)}${p(3)} + let bias = ${o.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(c).declareVariables(o,l,u)} + + ${Ya(Ze(e))} + + ${a.mainStart(qn)} + ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${o.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${u.setByOffset("global_idx",Za("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/qn/4)}})}},lp=t=>{t.inputs.length<2||D.size(t.inputs[1].dims)===0?Rd(t):t.compute(op(t.inputs))}}),up,dp,cp,pp,S0=W(()=>{ue(),pe(),Fe(),he(),up=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},dp=(t,e)=>{let n=t[0].dims,r=t[1].dims,s=n.length,i=D.normalizeAxis(e.axis,s),a=n.slice(0);a.splice(i,1,...r);let o=n[i],l=t[0].dataType===9?4:1,u=Math.ceil(D.size(a)/l),c=[{type:12,data:u},{type:6,data:o},{type:12,data:i},...se(t[0].dims,t[1].dims,a)],p=d=>{let f=L("data",t[0].dataType,t[0].dims.length,l),m=L("inputIndices",t[1].dataType,t[1].dims.length),g=ae("output",t[0].dataType,a.length,l),w=y=>{let $=r.length,k=`var indicesIndices${y} = ${m.type.indices}(0);`;for(let E=0;E<$;E++)k+=`${$>1?`indicesIndices${y}[${E}]`:`indicesIndices${y}`} = ${a.length>1?`outputIndices${y}[uniforms.axis + ${E}]`:`outputIndices${y}`};`;k+=` + var idx${y} = ${m.getByIndices(`indicesIndices${y}`)}; + if (idx${y} < 0) { + idx${y} = idx${y} + uniforms.axisDimLimit; + } + var dataIndices${y} : ${f.type.indices}; + `;for(let E=0,T=0;E1?`dataIndices${y}[${E}]`:`dataIndices${y}`} = u32(idx${y});`,T+=$):(k+=`${s>1?`dataIndices${y}[${E}]`:`dataIndices${y}`} = ${a.length>1?`outputIndices${y}[${T}]`:`outputIndices${y}`};`,T++);return k},v;if(t[0].dataType===9){let y=($,k,E="")=>` + let outputIndices${k} = ${g.offsetToIndices(`outputOffset + ${k}u`)}; + ${w(k)}; + let offset${k} = ${f.indicesToOffset(`dataIndices${k}`)}; + let index${k} = offset${k} / 4u; + let component${k} = offset${k} % 4u; + ${$}[${k}] = ${E}(${f.getByOffset(`index${k}`)}[component${k}]); + `;v=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${y("value",0,"u32")} + ${y("value",1,"u32")} + ${y("value",2,"u32")} + ${y("value",3,"u32")} + ${g.setByOffset("global_idx","value")} + `}else v=` + let outputIndices = ${g.offsetToIndices("global_idx")}; + ${w("")}; + let value = ${f.getByIndices("dataIndices")}; + ${g.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,m,g)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${v} + }`};return{name:"Gather",shaderCache:{hint:e.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}),getShaderSource:p}},cp=t=>$e({axis:t.axis}),pp=(t,e)=>{let n=t.inputs;up(n),t.compute(dp(t.inputs,e))}}),hp,fp,mp,gp,E0=W(()=>{ue(),pe(),Fe(),he(),hp=(t,e)=>{if(t.length<3||t.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=D.normalizeAxis(e.quantizeAxis,t[0].dims.length),r=e.blockSize,s=t[0],i=t[2],a=t.length===4?t[3]:void 0;if(i.dims.length!==s.dims.length||!s.dims.map((o,l)=>l===n?Math.ceil(o/r)===i.dims[l]:o===i.dims[l]).reduce((o,l)=>o&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==i.dims.length||!a.dims.map((o,l)=>o===i.dims[l]).reduce((o,l)=>o&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},fp=(t,e)=>{let n=t[0].dims,r=t[1].dims,s=n.length,i=D.normalizeAxis(e.gatherAxis,s),a=D.normalizeAxis(e.quantizeAxis,s),o=n.slice(0);o.splice(i,1,...r);let l=D.size(o),u=t[2].dataType,c=t[0].dataType===22,p=[{type:12,data:l},{type:12,data:a},{type:12,data:i},{type:12,data:e.blockSize},...se(...t.map((f,m)=>f.dims),o)],d=f=>{let m=L("data",t[0].dataType,t[0].dims.length),g=L("inputIndices",t[1].dataType,t[1].dims.length),w=L("scales",t[2].dataType,t[2].dims.length),v=t.length>3?L("zeroPoint",t[3].dataType,t[3].dims.length):void 0,y=ae("output",u,o.length),$=[m,g,w];v&&$.push(v);let k=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${f.registerUniforms(k).declareVariables(...$,y)} + ${f.mainStart()} + let output_indices = ${y.offsetToIndices("global_idx")}; + var indices_indices = ${g.type.indices}(0); + ${r.length>1?` + for (var i: u32 = 0; i < ${r.length}; i++) { + let index = ${y.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${g.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${y.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${m.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${y.indicesGet("output_indices","i")}; + ${m.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${g.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${n[i]}; + } + ${m.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${o.length}; i++) { + let index = ${y.indicesGet("output_indices",`i + ${r.length} - 1`)}; + ${m.indicesSet("data_indices","i","index")}; + } + let data_offset = ${m.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${m.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${c?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${w.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${w.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${w.getByIndices("scale_indices")}; + ${v?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${v.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${v.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${c?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Ze(u)}(quantized_data - zero_point) * scale; + ${y.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${e.cacheKey};${t.filter((f,m)=>m!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:t.length},(f,m)=>"rank")},getRunData:()=>({outputs:[{dims:o,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p}),getShaderSource:d}},mp=(t,e)=>{let n=t.inputs;hp(n,e),t.compute(fp(t.inputs,e))},gp=t=>$e({blockSize:t.blockSize,gatherAxis:t.gatherAxis,quantizeAxis:t.quantizeAxis})}),_p,wp,yp,bp,T0=W(()=>{ue(),pe(),Fe(),he(),_p=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.`)},wp=(t,e)=>{let n=t[0].dims,r=t[0].dataType,s=n.length,i=t[1].dims,a=t[1].dataType,o=D.normalizeAxis(e.axis,s),l=n[o],u=i.slice(0),c=D.size(u),p=L("input",r,s),d=L("indicesInput",a,i.length),f=ae("output",r,u.length),m=[{type:12,data:c},{type:6,data:l},{type:12,data:o}];return m.push(...se(n,i,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:g=>` + ${g.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(p,d,f)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${f.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${p.type.indices}(outputIndices); + ${p.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${p.getByIndices("inputIndices")}; + + ${f.setByOffset("global_idx","value")}; + }`}},yp=t=>$e({axis:t.axis}),bp=(t,e)=>{let n=t.inputs;_p(n),t.compute(wp(t.inputs,e))}}),vp,xp,$p,kp,M0=W(()=>{ue(),pe(),he(),vp=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")},xp=(t,e)=>{let n=t[0].dims.slice(),r=t[1].dims.slice(),[s,i,a]=Hl.getShapeOfGemmResult(n,e.transA,r,e.transB,t.length===3?t[2].dims:void 0),o=[s,i];if(!o)throw new Error("Can't use gemm on the given tensors");let l=D.size(o),u=[{type:12,data:l},{type:12,data:s},{type:12,data:i},{type:12,data:a},{type:1,data:e.alpha},{type:1,data:e.beta}],c=["type","type"];t.length===3&&(u.push(...se(t[2].dims)),c.push("rank")),u.push(...se(o));let p=d=>{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 m=e.alpha===1?"":"value *= uniforms.alpha;",g=L("a",t[0].dataType,t[0].dims),w=L("b",t[1].dataType,t[1].dims),v=g.type.value,y=null,$=[g,w];t.length===3&&(y=L("c",t[2].dataType,t[2].dims.length),$.push(y));let k=ae("output",t[0].dataType,o.length);$.push(k);let E=[{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` + ${d.registerUniforms(E).declareVariables(...$)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${v}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${f} + } + + ${m} + ${y!=null?`let cOffset = ${y.broadcastedIndicesToOffset("vec2(m, n)",k)}; value += ${v}(uniforms.beta) * ${y.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:p}},$p=t=>{let e=t.transA,n=t.transB,r=t.alpha,s=t.beta;return{transA:e,transB:n,alpha:r,beta:s,cacheKey:`${t.transA};${t.transB};${t.alpha===1}`}},kp=(t,e)=>{vp(t.inputs),t.compute(xp(t.inputs,e))}}),rt,Sp,Ep,gi,Tp,br,Mp,Cp=W(()=>{ue(),pe(),Fe(),Fa(),Xa(),he(),Wn(),rt=(t,e)=>t.length>e&&t[e].dims.length>0?t[e]:void 0,Sp=(t,e)=>{let n=t[0],r=rt(t,1),s=rt(t,2),i=rt(t,3),a=rt(t,4),o=rt(t,5),l=rt(t,6),u=rt(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=n.dims[0],p=n.dims[1],d=n.dims.length===3?n.dims[2]:e.numHeads*n.dims[4],f=p,m=0,g=0,w=Math.floor(d/e.numHeads);if(l&&u&&D.size(l.dims)&&D.size(u.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==c||l.dims[1]!==e.numHeads||l.dims[3]!==w)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==c||u.dims[1]!==e.numHeads||u.dims[3]!==w)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');m=l.dims[2],g=l.dims[2]}else if(l&&D.size(l.dims)||u&&D.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v;if(r&&D.size(r.dims)>0){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)');v=2,f=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==e.numHeads||r.dims[3]!==2||r.dims[4]!==w)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');v=5,f=r.dims[1]}else{if(r.dims[1]!==e.numHeads||r.dims[3]!==w)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');v=0,f=r.dims[2]}}else{if(n.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(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');v=3}if(i&&D.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(r&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let y=m+f,$=0;if(a&&D.size(a.dims)>0){$=8;let C=a.dims;throw C.length===1?C[0]===c?$=1:C[0]===3*c+2&&($=3):C.length===2&&C[0]===c&&C[1]===y&&($=5),$===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let k=!1,E=d;if(s&&D.size(s.dims)>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(f!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=s.dims[2]}else{if(f!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');E=s.dims[1]*s.dims[3],k=!0}}let T=!1;if(a&&D.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(o&&D.size(o.dims)>0){if(o.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(o.dims[0]!==c||o.dims[1]!==e.numHeads||o.dims[2]!==p||o.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:c,sequenceLength:p,pastSequenceLength:m,kvSequenceLength:f,totalSequenceLength:y,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:d,vHiddenSize:E,headSize:w,vHeadSize:Math.floor(E/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:$,scale:e.scale,broadcastResPosBias:T,passPastInKv:k,qkvFormat:v}},Ep=t=>$e({...t}),gi=$e({perm:[0,2,1,3]}),Tp=(t,e,n,r,s,i,a)=>{let o=[r,s,i],l=D.size(o),u=[{type:12,data:l},{type:12,data:a},{type:12,data:i}],c=p=>{let d=ae("qkv_with_bias",e.dataType,o),f=L("qkv",e.dataType,o),m=L("bias",n.dataType,o),g=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${p.registerUniforms(g).declareVariables(f,m,d)} + ${p.mainStart()} + ${p.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:u}),getShaderSource:c},{inputs:[e,n],outputs:[-1]})[0]},br=(t,e,n,r,s,i,a,o)=>{let l=i;if(a&&D.size(a.dims)>0){if(r===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Tp(t,i,a,e,r,n*s,o),l=l.reshape([e,r,n,s]),t.compute(Rt(l,gi.perm),{inputs:[l],outputs:[-1]})[0]}else return i.dims.length===3&&(l=i.reshape([e,r,n,s])),t.compute(Rt(l,gi.perm),{inputs:[l],outputs:[-1]})[0]},Mp=(t,e)=>{let n=Sp(t.inputs,e),r=t.inputs[0],s=rt(t.inputs,1),i=rt(t.inputs,2),a=rt(t.inputs,3),o=rt(t.inputs,4),l=rt(t.inputs,5),u=rt(t.inputs,6),c=rt(t.inputs,7);if(r.dims.length===5)throw new Error("Packed QKV is not implemented");if((s==null?void 0:s.dims.length)===5)throw new Error("Packed KV is not implemented");let p=s&&i&&s.dims.length===4&&i.dims.length===4,d=br(t,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,a,0);if(p)return gr(t,d,s,i,o,void 0,u,c,l,n,e);if(!s||!i)throw new Error("key and value must be provided");let f=br(t,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,s,a,n.hiddenSize),m=br(t,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,i,a,2*n.hiddenSize);gr(t,d,f,m,o,void 0,u,c,l,n,e)}}),_i,Ap,Ip,wi,zp,Op=W(()=>{ue(),pe(),he(),_i=t=>Array.from(t.getBigInt64Array(),Number),Ap=t=>{if(!t||t.length!==2)throw new Error("Tile requires 2 inputs.");if(t[0].dataType!==1&&t[0].dataType!==10&&t[0].dataType!==6&&t[0].dataType!==12)throw new Error("Tile only support float, float16, 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(_i(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")},Ip=(t,e)=>{let n=[];for(let r=0;r{let n=t[0].dims,r=e??_i(t[1]),s=Ip(n,r),i=D.size(s),a=t[0].dataType,o=L("input",a,n.length),l=ae("output",a,s.length),u=c=>` + const inputShape = ${o.indices(...n)}; + ${c.registerUniform("output_size","u32").declareVariables(o,l)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${o.type.indices}; + for (var i = 0; i < ${n.length}; i++) { + let input_dim_i = ${o.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${o.indicesSet("input_indices","i","input_dim_value")} + } + ${l.setByOffset("global_idx",o.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...se(t[0].dims,s)]}),getShaderSource:u}},zp=t=>{Ap(t.inputs),t.compute(wi(t.inputs),{inputs:[0]})}}),Pp,yi,Bp,Rp,bi,Fp,C0=W(()=>{ue(),pe(),Fe(),Xa(),he(),Cp(),Op(),Wn(),Pp=(t,e)=>{let n=t[0],r=t[1],s=t[2],i=t[3],a=t[4];if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let o=!1,l=n.dims[0],u=n.dims[1],c=n.dims.length===3?o?n.dims[2]/3:n.dims[2]:e.numHeads*n.dims[4],p=u,d=0,f=0,m=Math.floor(c/e.numHeads),g=i&&i.dims.length!==0,w=a&&a.dims.length!==0,v=!0;if(g&&w){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=i.dims[1],f=i.dims[1]}else if(g||w)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let y;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(n.dims[2]%r.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');y=2,p=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==e.numHeads||r.dims[3]!==2||r.dims[4]!==m)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');y=5,p=r.dims[1]}else{if(r.dims[1]!==e.numHeads||r.dims[3]!==m)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');y=0,p=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');y=3}let $=0,k=!1,E=c;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(p!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=s.dims[2]}else{if(p!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=s.dims[1]*s.dims[3],k=!0}}let T=d+p;return{batchSize:l,sequenceLength:u,pastSequenceLength:d,kvSequenceLength:p,totalSequenceLength:T,maxSequenceLength:f,inputHiddenSize:0,hiddenSize:c,vHiddenSize:E,headSize:m,vHeadSize:Math.floor(E/e.kvNumHeads),numHeads:e.numHeads,kvNumHeads:e.kvNumHeads,nReps:e.numHeads/e.kvNumHeads,pastPresentShareBuffer:!1,maskType:$,scale:e.scale,broadcastResPosBias:!1,passPastInKv:k,qkvFormat:y,isPastkvBSNH:v}},yi=(t,e,n,r)=>{let s=[r.batchSize,r.totalSequenceLength,r.kvNumHeads,r.headSize],i=4,a=D.size(s)/i,o=r.totalSequenceLength,l=ae("present_kv",n,s.length,i),u=L("new_kv",t.dataType,t.dims.length,i),c=e?L("past_kv",e.dataType,e.dims.length,i):void 0,p=Math.ceil(r.headSize/i),d={x:o,y:t.dims[0],z:1},f=e?["rank","rank"]:["rank"],m=[{type:12,data:a},{type:12,data:r.pastSequenceLength},{type:12,data:r.kvSequenceLength},{type:12,data:r.totalSequenceLength}],g=[u];c?(m.push(...se(t.dims),...se(e.dims),...se(s)),g.push(c)):m.push(...se(t.dims),...se(s));let w=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],v=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; + var past_head_stride = uniforms.past_seqlen * H; + if (is_bsnh) { + past_head_stride = H; + } + let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; + present_kv[out_offset] = past_kv[in_offset];`,y=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; + let new_row_stride = num_heads * H; + let new_head_stride = H; + let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; + present_kv[out_offset] = new_kv[in_offset];`,$=e?`if (s < past_seqlen) { + ${v} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${y} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${y} + }`,k=E=>` + + ${E.registerUniforms(w).declareVariables(...g,l)} + ${E.mainStart([p,r.kvNumHeads,1])} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${l.offsetToIndices("global_idx")}; + let h = local_id.x; + let n = local_id.y; + let s = workgroup_id.x; + let b = workgroup_id.y; + let num_heads = ${r.kvNumHeads}u; + let H = ${p}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${r.isPastkvBSNH}; + + if (is_bsnh) { + row_stride = num_heads * H; + } + var present_head_stride = present_seqlen * H; + if (is_bsnh) { + present_head_stride = H; + } + + let past_seqlen = uniforms.past_seqlen; + + let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; + ${$} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${r.kvNumHeads}${p}${!!e}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:d,programUniforms:m}),getShaderSource:k}},Bp=t=>$e({...t}),Rp=$e({perm:[0,2,1,3]}),bi=(t,e,n,r,s)=>{let i=e,a=r.kvNumHeads,o=r.nReps;return e.dims.length===3&&r.kvSequenceLength!==0&&(i=e.reshape([r.batchSize,r.kvSequenceLength,a,r.headSize])),n?i=t.compute(yi(i,n,i.dataType,r),{inputs:[i,n],outputs:[r.isPastkvBSNH?s:-1]})[0]:i=t.compute(yi(i,void 0,i.dataType,r),{inputs:[i],outputs:[r.isPastkvBSNH?s:-1]})[0],o!==1&&(i=t.compute(wi([i],[1,1,1,o]),{inputs:[i],outputs:[-1]})[0],i=i.reshape([r.batchSize,r.totalSequenceLength,a*o,r.headSize])),t.compute(Rt(i,Rp.perm),{inputs:[i],outputs:[-1]})[0]},Fp=(t,e)=>{var l;let n=Pp(t.inputs,e);if(t.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((l=t.inputs[1])==null?void 0:l.dims.length)===5)throw new Error("Packed KV is not implemented");let r=br(t,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.inputs[0],void 0,0),s=t.inputs[3]&&t.inputs[3].dims.length!==0?t.inputs[3]:void 0,i=t.inputs[4]&&t.inputs[4].dims.length!==0?t.inputs[4]:void 0,a=bi(t,t.inputs[1],s,n,1),o=bi(t,t.inputs[2],i,n,2);gr(t,r,a,o,void 0,void 0,void 0,void 0,void 0,n,e)}}),Dp,Np,Lp,Up,A0=W(()=>{ue(),pe(),he(),Dp=(t,e)=>{let n=t[0].dims,r=n,s=2,i=D.sizeToDimension(n,s),a=D.sizeFromDimension(n,s),o=Ue(a),l=a/o,u=[n[0],n[1],l],c=["rank","type","type"],p=[{type:12,data:a},{type:12,data:l}];p.push(...se(u,u));let d=f=>{let m=L("x",t[0].dataType,u.length,o),g=L("scale",t[1].dataType,t[1].dims),w=L("bias",t[2].dataType,t[2].dims),v=ae("output",t[0].dataType,u.length,o),y=[m,g,w,v],$=m.type.value,k=o===1?"f32":`vec${o}`,E=64,T=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${k}, ${E}>; + const workgroupSize = ${E}u; + ${f.registerUniforms(T).declareVariables(...y)} + ${f.mainStart(E)} + let norm = global_idx / workgroupSize; + let batch = norm / uniforms.x_shape[1]; + let channel = norm % uniforms.x_shape[1]; + let localIndex = local_id.x; + + // initialize workgroup memory + var initial = ${k}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${k}(${m.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 = ${sn("workgroupShared[0]",o)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${k}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${k}(${m.get("batch","channel","h")}) - ${k}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${sn("workgroupShared[0]",o)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); + let channelScale = invStdDev * f32(${g.getByOffset("channel")}); + let channelShift = f32(${w.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${m.get("batch","channel","h")} * ${$}(${k}(channelScale)) + ${$}(${k}(channelShift)); + ${v.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:p}),getShaderSource:d}},Np=(t,e,n,r,s,i,a,o)=>{let l=Ue(a),u=64,c=l===1?"vec2f":`mat2x${l}f`,p=l===1?"f32":`vec${l}f`,d=(T,C)=>`${c}(${T}, ${C})`,f=s*a/l,m=Math.ceil(i/u),g=["type"],w=[{type:12,data:m},{type:12,data:i},{type:12,data:Math.floor(a/l)},{type:12,data:Math.floor(i*a/l)}],v=T=>{let C=L("input",e.dataType,e.dims,l);return` + ${T.declareVariables(C)} + @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; + + ${T.mainStart(u)} + let currentImageNumber = global_idx / ${u} / uniforms.C; + let currentChannelNumber = (global_idx / ${u}) % uniforms.C; + let wgOffset = local_id.x * 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 = ${kn("f32",l)}; + var squaredSum = ${kn("f32",l)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${p}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${d("sum","squaredSum")}; + }`},y=t.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:[s,a,u,2],dataType:1}],dispatchGroup:{x:s*a/l},programUniforms:w}),getShaderSource:v},{inputs:[e],outputs:[-1]})[0],$=[{type:12,data:f},{type:12,data:i},{type:12,data:Math.floor(a/l)},{type:12,data:Math.floor(u*a/l)}],k=["type","type","type"],E=T=>{let C=L("scale",n.dataType,n.dims,l),B=L("bias",r.dataType,r.dims,l);return` + @group(0) @binding(0) var input : array<${c}>; + @group(0) @binding(1) var scale : array<${C.type.storage}>; + @group(0) @binding(2) var bias : array<${B.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; + + ${T.mainStart()} + ${T.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 = ${kn("f32",l)}; + var squaredSum = ${kn("f32",l)}; + for (var i: u32 = 0; i < min(${u}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${u}]; + 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 * ${p}(scale[currentChannelNumber]); + let channelShift = ${p}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${d("channelScale","channelShift")}; + }`};return t.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:[s,a,2],dataType:1}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:$}),getShaderSource:E},{inputs:[y,n,r],outputs:[-1]})[0]},Lp=(t,e,n)=>{let r=e[0].dims,s=r,i=r[0],a=r[r.length-1],o=D.sizeFromDimension(r,1)/a,l=Ue(a),u=D.size(s)/l,c=[{type:12,data:o},{type:12,data:Math.floor(a/l)}],p=["type","type"],d=Np(t,e[0],e[1],e[2],i,o,a,n.epsilon),f=m=>{let g=Le(e[0].dataType),w=l===1?"vec2f":`mat2x${l}f`,v=l===1?g:`vec${l}<${g}>`,y=L("input",e[0].dataType,e[0].dims,l),$=ae("output",e[0].dataType,s,l);return` + @group(0) @binding(0) var input : array<${y.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${w}>; + @group(0) @binding(2) var output : array<${$.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${m.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], ${v}(scale[0]), ${v}(scale[1])); + }`};t.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}),getShaderSource:f},{inputs:[e[0],d]})},Up=(t,e)=>{e.format==="NHWC"?Lp(t,t.inputs,e):t.compute(Dp(t.inputs,e))}}),Vp,jp,qp,I0=W(()=>{ue(),pe(),he(),Vp=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},jp=(t,e,n)=>{let r=e.simplified,s=t[0].dims,i=t[1],a=!r&&t[2],o=s,l=D.normalizeAxis(e.axis,s.length),u=D.sizeToDimension(s,l),c=D.sizeFromDimension(s,l),p=D.size(i.dims),d=a?D.size(a.dims):0;if(p!==c||a&&d!==c)throw new Error(`Size of X.shape()[axis:] == ${c}. + Size of scale and bias (if provided) must match this. + Got scale size of ${p} and bias size of ${d}`);let f=[];for(let E=0;E1,y=n>2,$=E=>{let T=Le(t[0].dataType),C=[L("x",t[0].dataType,t[0].dims,m),L("scale",i.dataType,i.dims,m)];a&&C.push(L("bias",a.dataType,a.dims,m)),C.push(ae("output",t[0].dataType,o,m)),v&&C.push(ae("mean_data_output",1,f)),y&&C.push(ae("inv_std_output",1,f));let B=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${E.registerUniforms(B).declareVariables(...C)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${kn("f32",m)}; + var mean_square_vector = ${kn("f32",m)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Gn(T,m,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${sn("mean_vector",m)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${sn("mean_square_vector",m)} / uniforms.norm_size ${r?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Gn(T,m,"x[j + offset]")}; + let f32scale = ${Gn(T,m,"scale[j]")}; + output[j + offset] = ${C[0].type.value}((f32input ${r?"":"- mean"}) * inv_std_dev * f32scale + ${a?`+ ${Gn(T,m,"bias[j]")}`:""} + ); + } + + ${v?"mean_data_output[global_idx] = mean":""}; + ${y?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},k=[{dims:o,dataType:t[0].dataType}];return v&&k.push({dims:f,dataType:1}),y&&k.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${m};${n};${r}`,inputDependencies:g},getRunData:()=>({outputs:k,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:w}),getShaderSource:$}},qp=(t,e)=>{Vp(t.inputs),t.compute(jp(t.inputs,e,t.outputCount))}}),Gp,Wp,Hp,Kp,z0=W(()=>{ue(),pe(),Fe(),he(),Gp=(t,e)=>{if(t.length<3||t.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=t[0],r=n.dims.length;if(n.dims[r-1]!==e.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((e.k+e.blockSize-1)/e.blockSize),i=e.blockSize/8*e.bits,a=t[1];if(!D.areEqual(a.dims,[e.n,s,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=t[2].dims;if(D.size(o)!==e.n*s)throw new Error("scales input size error.");if(t.length===4){let l=t[3].dims,u=e.bits>4?e.n*s:e.n*Math.floor((s+1)/2);if(D.size(l)!==u)throw new Error("zeroPoints input size error.")}},Wp=(t,e)=>{let n=t[0].dims,r=n.length,s=n[r-2],i=e.k,a=e.n,o=n.slice(0,r-2),l=D.size(o),u=t[1].dims[2]/4,c=t[0].dataType,p=Ue(e.k),d=Ue(u),f=Ue(a),m=o.concat([s,a]),g=s>1&&a/f%2===0?2:1,w=D.size(m)/f/g,v=64,y=[],$=[l,s,i/p],k=D.convertShape(t[1].dims).slice();k.splice(-1,1,u/d),y.push(...se($)),y.push(...se(k)),y.push(...se(t[2].dims)),t.length===4&&y.push(...se(D.convertShape(t[3].dims)));let E=[l,s,a/f];y.push(...se(E));let T=C=>{let B=$.length,U=L("a",t[0].dataType,B,p),G=L("b",12,k.length,d),K=L("scales",t[2].dataType,t[2].dims.length),X=[U,G,K],H=t.length===4?L("zero_points",12,t[3].dims.length):void 0;H&&X.push(H);let J=E.length,ne=ae("output",t[0].dataType,J,f),I=Le(t[0].dataType),N=(()=>{switch(p){case 1:return`array<${I}, 8>`;case 2:return`mat4x2<${I}>`;case 4:return`mat2x4<${I}>`;default:throw new Error(`${p}-component is not supported.`)}})(),R=()=>{let O=` + // reuse a data + var input_offset = ${U.indicesToOffset(`${U.type.indices}(batch, row, word_offset)`)}; + var a_data: ${N}; + for (var j: u32 = 0; j < ${8/p}; j++) { + a_data[j] = ${U.getByOffset("input_offset")}; + input_offset++; + } + `;for(let q=0;q> 4) & b_mask); + b_quantized_values = ${N}(${Array.from({length:4},(ie,ge)=>`${I}(b_value_lower[${ge}]), ${I}(b_value_upper[${ge}])`).join(", ")}); + b_dequantized_values = ${p===1?`${N}(${Array.from({length:8},(ie,ge)=>`(b_quantized_values[${ge}] - ${H?`zero_point${q}`:"zero_point"}) * scale${q}`).join(", ")});`:`(b_quantized_values - ${N}(${Array(8).fill(`${H?`zero_point${q}`:"zero_point"}`).join(",")})) * scale${q};`}; + workgroup_shared[local_id.x * ${g} + ${Math.floor(q/f)}]${f>1?`[${q%f}]`:""} += ${Array.from({length:8/p},(ie,ge)=>`${p===1?`a_data[${ge}] * b_dequantized_values[${ge}]`:`dot(a_data[${ge}], b_dequantized_values[${ge}])`}`).join(" + ")}; + `;return O},Y=()=>{let O=` + var col_index = col * ${f}; + ${H?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${I}(8);`} + `;for(let q=0;q> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${H.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${q} = ${I}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return O},te=()=>{let O=`col_index = col * ${f};`;for(let q=0;q; + var b_value_upper: vec4; + var b_quantized_values: ${N}; + var b_dequantized_values: ${N};`,O};return` + var workgroup_shared: array<${ne.type.value}, ${g*v}>; + ${C.declareVariables(...X,ne)} + ${C.mainStart([v,1,1])} + let output_indices = ${ne.offsetToIndices(`(global_idx / ${v}) * ${g}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) { + //process one block + var word_offset: u32 = block * ${e.blockSize/p}; + ${Y()} + for (var word: u32 = 0; word < ${u}; word += ${d}) { + ${te()} + for (var i: u32 = 0; i < ${d}; i++) { + ${R()} + word_offset += ${8/p}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${g}) { + var output_value: ${ne.type.value} = ${ne.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${v}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${g}; + } + ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${e.blockSize};${e.bits};${p};${d};${f};${g};${v}`,inputDependencies:Array(t.length).fill("rank")},getRunData:()=>({outputs:[{dims:m,dataType:c}],dispatchGroup:{x:w},programUniforms:y}),getShaderSource:T}},Hp=(t,e)=>{Gp(t.inputs,e),t.compute(Wp(t.inputs,e))},Kp=t=>$e(t)}),Xp,Qp,Yp,Zp,Jp,eh,th,nh,rh,O0=W(()=>{ue(),pe(),he(),Xp=t=>{if(!t||t.length<1)throw new Error("Too few inputs");if(t[0].dataType!==1&&t[0].dataType!==10)throw new Error("Input type must be float or float16.");if(t.length>=2){let e=t[0].dims.length*2===t[1].dims[0];if(t.length===4&&(e=t[3].dims[0]*2===t[1].dims[0]),!e)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Qp=(t,e,n)=>{let r="";for(let s=e-1;s>=0;--s)r+=` + k = i32(${t.indicesGet("indices",s)}) - ${re("uniforms.pads",s,n)}; + if (k < 0) { + break; + } + if (k >= i32(${re("uniforms.x_shape",s,e)})) { + break; + } + offset += k * i32(${re("uniforms.x_strides",s,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]; + } + `},Yp=(t,e,n)=>{let r="";for(let s=e-1;s>=0;--s)r+=` + k = i32(${t.indicesGet("indices",s)}) - ${re("uniforms.pads",s,n)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${re("uniforms.x_shape",s,e)}) - 1); + k = k % _2n_1; + if(k >= i32(${re("uniforms.x_shape",s,e)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${re("uniforms.x_strides",s,e)}); + `;return` + var offset = 0; + var k = 0; + ${r} + value = x[offset]; + `},Zp=(t,e,n)=>{let r="";for(let s=e-1;s>=0;--s)r+=` + k = i32(${t.indicesGet("indices",s)}) - ${re("uniforms.pads",s,n)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${re("uniforms.x_shape",s,e)})) { + k = i32(${re("uniforms.x_shape",s,e)}) - 1; + } + offset += k * i32(${re("uniforms.x_strides",s,e)}); + `;return` + var offset = 0; + var k = 0; + ${r} + value = x[offset]; + `},Jp=(t,e,n)=>{let r="";for(let s=e-1;s>=0;--s)r+=` + k = i32(${t.indicesGet("indices",s)}) - ${re("uniforms.pads",s,n)}; + if (k < 0) { + k += i32(${re("uniforms.x_shape",s,e)}]); + } + if (k >= i32(${re("uniforms.x_shape",s,e)})) { + k -= i32(${re("uniforms.x_shape",s,e)}); + } + offset += k * i32(${re("uniforms.x_strides",s,e)}); + `;return` + var offset = 0; + var k = 0; + ${r} + value = x[offset]; + `},eh=(t,e,n)=>{switch(n.mode){case 0:return Qp(t,e,n.pads.length);case 1:return Yp(t,e,n.pads.length);case 2:return Zp(t,e,n.pads.length);case 3:return Jp(t,e,n.pads.length);default:throw new Error("Invalid mode")}},th=(t,e)=>{let n=D.padShape(t[0].dims.slice(),e.pads),r=t[0].dims,s=D.size(n),i=[{type:12,data:s},{type:6,data:e.pads}],a=t.length>=3&&t[2].data;e.mode===0&&i.push({type:a?t[2].dataType:1,data:e.value}),i.push(...se(t[0].dims,n));let o=["rank"],l=u=>{let c=ae("output",t[0].dataType,n.length),p=L("x",t[0].dataType,r.length),d=p.type.value,f=eh(c,r.length,e),m=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&m.push({name:"constant_value",type:a?d:"f32"}),` + ${u.registerUniforms(m).declareVariables(p,c)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${c.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${f} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${e.mode}${a}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(D.size(n)/64)},programUniforms:i}),getShaderSource:l}},nh=(t,e)=>{if(t.length>1){let n=t[1].getBigInt64Array(),r=t.length>=3&&t[2].data?t[2].dataType===10?t[2].getUint16Array()[0]:t[2].getFloat32Array()[0]:0,s=t[0].dims.length,i=new Int32Array(2*s).fill(0);if(t.length>=4){let o=t[3].getBigInt64Array();for(let l=0;li[Number(l)]=Number(o));let a=[];return i.forEach(o=>a.push(o)),{mode:e.mode,value:r,pads:a}}else return e},rh=(t,e)=>{Xp(t.inputs);let n=nh(t.inputs,e);t.compute(th(t.inputs,n),{inputs:[0]})}}),vr,vi,xi,$i,ki,sh,ah,Si,Ei,ih,oh,Ti,lh,uh,Mi,dh,ch,ph,hh,P0=W(()=>{Et(),ue(),pe(),he(),vr=t=>{if(Te.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},vi=(t,e,n)=>{let r=e.format==="NHWC",s=t.dims.slice();r&&s.splice(1,0,s.pop());let i=Object.hasOwnProperty.call(e,"dilations"),a=e.kernelShape.slice(),o=e.strides.slice(),l=i?e.dilations.slice():[],u=e.pads.slice();ps.adjustPoolAttributes(n,s,a,o,l,u);let c=ps.computePoolOutputShape(n,s,o,l,a,u,e.autoPad),p=Object.assign({},e);i?Object.assign(p,{kernelShape:a,strides:o,pads:u,dilations:l,cacheKey:e.cacheKey}):Object.assign(p,{kernelShape:a,strides:o,pads:u,cacheKey:e.cacheKey});let d=c.slice();return d.push(d.splice(1,1)[0]),[p,r?d:c]},xi=(t,e)=>{let n=e.format==="NHWC",r=D.size(t),s=D.size(e.kernelShape),i=[{type:12,data:r},{type:12,data:s}],a=[{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],u=e.pads[e.pads.length/2-1],c=e.pads[e.pads.length-1],p=!!(u+c);i.push({type:12,data:o},{type:12,data:l},{type:12,data:u},{type:12,data:c}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(e.kernelShape.length===2){let f=e.kernelShape[e.kernelShape.length-2],m=e.strides[e.strides.length-2],g=e.pads[e.pads.length/2-2],w=e.pads[e.pads.length-2];d=!!(g+w),i.push({type:12,data:f},{type:12,data:m},{type:12,data:g},{type:12,data:w}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,a,!0,p,d]}else{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let o=D.computeStrides(e.kernelShape);i.push({type:12,data:o},{type:12,data:e.pads},{type:12,data:e.strides}),a.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((u,c)=>u+c);return[i,a,!!l,!1,!1]}},$i=(t,e,n,r,s,i,a,o,l,u,c,p)=>{let d=s.format==="NHWC",f=e.type.value,m=ae("output",e.type.tensor,r);if(s.kernelShape.length<=2){let g="",w="",v="",y=n-(d?2:1);if(c?g=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${y}] < 0 || xIndices[${y}] + >= uniforms.x_shape[${y}]) { + pad++; + continue; + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + }`:g=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + }`,s.kernelShape.length===2){let $=n-(d?3:2);p?w=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${$}] < 0 || xIndices[${$}] >= uniforms.x_shape[${$}]) { + pad += i32(uniforms.kw); + continue; + } + `:w=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + `,v=` + } + `}return` + ${t.registerUniforms(l).declareVariables(e,m)} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${m.offsetToIndices("global_idx")}; + var xIndices = ${m.offsetToIndices("global_idx")}; + + var value = ${f}(${o}); + var pad = 0; + ${w} + ${g} + ${v} + ${a} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let g=s.kernelShape.length,w=s.pads.length,v="";return u?v=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + }`:v=` + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${i} + `,` + ${t.registerUniforms(l).declareVariables(e,m)} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${m.offsetToIndices("global_idx")}; + var xIndices = ${m.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 < ${g-1}u; j++) { + offsets[j] = offset / ${re("uniforms.kernelStrides","j",g)}; + offset -= offsets[j] * ${re("uniforms.kernelStrides","j",g)}; + } + offsets[${g-1}] = offset; + + isPad = false; + for (var j = ${n-g}u; j < ${n}u; j++) { + xIndices[j] = indices[j] * ${re("uniforms.strides",`j - ${n-g}u`,g)} + + offsets[j - ${n-g}u] - ${re("uniforms.pads","j - 2u",w)}; + ${v} + } + ${a} + + output[global_idx] = value; + }`}},ki=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,sh=t=>`${ki(t)};${t.countIncludePad}`,ah=t=>`${ki(t)};${t.storageOrder};${t.dilations}`,Si=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}),Ei=(t,e,n,r)=>{let[s,i]=vi(e,r,n),a=L("x",e.dataType,e.dims.length),o=a.type.value,l="value += x_val;",u="";s.countIncludePad?u+=`value /= ${o}(uniforms.kernelSize);`:u+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[c,p,d,f,m]=xi(i,s);c.push(...se(e.dims,i));let g=["rank"];return{name:t,shaderCache:{hint:`${r.cacheKey};${d};${f};${m}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(D.size(i)/64)},programUniforms:c}),getShaderSource:w=>$i(w,a,e.dims.length,i.length,s,l,u,0,p,d,f,m)}},ih=t=>{let e=t.count_include_pad!==0,n=Si(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:sh(r)}},oh=(t,e)=>{vr(t.inputs),t.compute(Ei("AveragePool",t.inputs[0],!1,e))},Ti={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},lh=t=>{let e=t.format;return{format:e,...Ti,cacheKey:e}},uh=(t,e)=>{vr(t.inputs),t.compute(Ei("GlobalAveragePool",t.inputs[0],!0,e))},Mi=(t,e,n,r)=>{let[s,i]=vi(e,r,n),a=` + value = max(x_val, value); + `,o="",l=L("x",e.dataType,e.dims.length),u=["rank"],[c,p,d,f,m]=xi(i,s);return c.push(...se(e.dims,i)),{name:t,shaderCache:{hint:`${r.cacheKey};${d};${f};${m}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(D.size(i)/64)},programUniforms:c}),getShaderSource:g=>$i(g,l,e.dims.length,i.length,s,a,o,e.dataType===10?-65504:-1e5,p,d,f,m)}},dh=(t,e)=>{vr(t.inputs),t.compute(Mi("MaxPool",t.inputs[0],!1,e))},ch=t=>{let e=t.storage_order,n=t.dilations,r=Si(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 s={storageOrder:e,dilations:n,...r,cacheKey:""};return{...s,cacheKey:ah(s)}},ph=t=>{let e=t.format;return{format:e,...Ti,cacheKey:e}},hh=(t,e)=>{vr(t.inputs),t.compute(Mi("GlobalMaxPool",t.inputs[0],!0,e))}}),fh,mh,gh,_h,B0=W(()=>{ue(),pe(),Fe(),he(),fh=(t,e)=>{if(t.length<2||t.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(t.length===3&&t[1].dims===t[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(t.length===3&&t[0].dataType!==t[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(t[0].dataType===6&&t.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(t[1].dims.length!==0&&t[1].dims.length!==1&&t[1].dims.length!==t[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(t.length>2){if(t[0].dataType!==t[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(t[1].dims.length!==t[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!t[1].dims.map((n,r)=>n===t[2].dims[r]).reduce((n,r)=>n&&r,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(e.blockSize>0){if(t[1].dims.length===0||t[1].dims.length===1&&t[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!t[1].dims.map((s,i)=>i===e.axis||s===t[0].dims[i]).reduce((s,i)=>s&&i,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(t[1].dims.length!==t[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let n=t[0].dims[e.axis],r=t[1].dims[e.axis];if(e.blockSizeMath.ceil(n/(r-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},mh=(t,e)=>{let n=D.normalizeAxis(e.axis,t[0].dims.length),r=t[0].dataType,s=r===3,i=t[0].dims,a=t[1].dataType,o=D.size(i),l=r===3||r===2,u=l?[Math.ceil(D.size(t[0].dims)/4)]:t[0].dims,c=t[1].dims,p=t.length>2?t[2]:void 0,d=p?l?[Math.ceil(D.size(p.dims)/4)]:p.dims:void 0,f=c.length===0||c.length===1&&c[0]===1,m=f===!1&&c.length===1,g=Ue(o),w=f&&(!l||g===4),v=w?g:1,y=w&&!l?g:1,$=L("input",l?12:r,u.length,y),k=L("scale",a,c.length),E=p?L("zero_point",l?12:r,d.length):void 0,T=ae("output",a,i.length,v),C=[$,k];E&&C.push(E);let B=[u,c];p&&B.push(d);let U=[{type:12,data:o/v},{type:12,data:n},{type:12,data:e.blockSize},...se(...B,i)],G=K=>{let X=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${K.registerUniforms(X).declareVariables(...C,T)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${T.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${$.getByOffset("global_idx / 4")}; + let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${v===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${$.getByOffset("global_idx")};`}; + + // Set scale input + ${f?`let scale_value= ${k.getByOffset("0")}`:m?` + let scale_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${k.getByOffset("scale_index")};`:` + var scale_indices: ${k.type.indices} = output_indices; + let index = ${k.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${k.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${k.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${E?f?l?` + let zero_point_input = ${E.getByOffset("0")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${E.getByOffset("0")}`:m?l?` + let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${E.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${E.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${k.indicesToOffset("scale_indices")}; + let zero_point_input = ${E.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${E.getByIndices("scale_indices")};`:`let zero_point_value = ${l?s?"i32":"u32":$.type.value}(0);`}; + // Compute and write output + ${T.setByOffset("global_idx",`${T.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:e.cacheKey,inputDependencies:E?["rank","rank","rank"]:["rank","rank"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(o/v/64),y:1,z:1},programUniforms:U})}},gh=(t,e)=>{fh(t.inputs,e),t.compute(mh(t.inputs,e))},_h=t=>$e({axis:t.axis,blockSize:t.blockSize})}),wh,yh,bh,R0=W(()=>{Et(),ue(),he(),wh=(t,e,n)=>{let r=t===e,s=te&&n>0;if(r||s||i)throw new Error("Range these inputs' contents are invalid.")},yh=(t,e,n,r)=>{let s=Math.abs(Math.ceil((e-t)/n)),i=[s],a=s,o=[{type:12,data:a},{type:r,data:t},{type:r,data:n},...se(i)],l=u=>{let c=ae("output",r,i.length),p=c.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:p},{name:"delta",type:p}];return` + ${u.registerUniforms(d).declareVariables(c)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${p}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:i,dataType:r}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:o})}},bh=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]),Te.webgpu.validateInputContent&&wh(e,n,r),t.compute(yh(e,n,r,t.inputs[0].dataType),{inputs:[]})}}),vh,xh,$h,kh,Sh,Eh,Th,Mh,Ch,Ah,Ih,Ci,zh,Oh,Ph,Bh,Rh,Fh,Dh,F0=W(()=>{ue(),pe(),Fe(),he(),vh=(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")}},xh=(t,e,n)=>{e.every(s=>s>=0&&s{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((s,i)=>r[s]=t[i]),r},$h=(t,e,n,r,s,i)=>{let[a,o,l]=n>10?[1,2,3]:[-1,t.length>1?1:-1,-1],u=t[0].dims.length;if(a>0&&t.length>a&&t[a].dims.length>0)t[a].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!==u&&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");vh(r,e),e.axes.length>0&&xh(r,e.axes,u).forEach((c,p)=>r[p]=c)}if(l>0&&t.length>l&&(t[l].getBigInt64Array().forEach(c=>s.push(Number(c))),s.length!==u||n>=18&&s.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(s.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 s<"u"&&r.length>0&&s.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},kh=(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`)}})()+"}",Sh=(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`)}})()+"}",Eh=(t,e,n)=>{let r=new Array(n).fill(0).concat(new Array(n).fill(1)),s=t.length===0?r:t.slice();return e.length>0?(e.forEach((i,a)=>{r[i]=s[a],r[a+n]=s[e.length+a]}),r):s},Th=(t,e,n,r)=>{let s=[];if(n.length>0)if(r.length>0){if(t.forEach(i=>s.push(i)),Math.max(...r)>t.length)throw new Error("axes is out of bound");r.forEach((i,a)=>s[i]=n[a])}else n.forEach(i=>s.push(i));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");s=t.map((i,a)=>Math.round(i*e[a]))}return s},Mh=(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 s=t.slice();return n.axes.length>0?(n.axes.forEach(i=>e[i]=r),n.axes.forEach(i=>s[i]=Math.round(t[i]*e[i]))):(e.fill(r,0,e.length),s.forEach((i,a)=>s[a]=Math.round(i*e[a]))),s},Ch=(t,e,n,r,s)=>` + 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 = ${re("uniforms.scales","i",r)}; + var roi_low = ${re("uniforms.roi","i",s)}; + var roi_hi = ${re("uniforms.roi",`i + ${e.length}`,s)}; + if (scale == 1.0) { + original_indices[i] = ${t.type.value}(output_index); + } else { + var input_shape_i = ${re("uniforms.input_shape","i",e.length)}; + var output_shape_i = ${re("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; + }`,Ah=(t,e,n,r,s,i,a)=>` + 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 = ${re("uniforms.scales","i",s)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${re("uniforms.roi","i",i)}; + var roi_hi = ${re("uniforms.roi",`i + ${n.length}`,i)}; + var input_shape_i = ${re("uniforms.input_shape","i",n.length)}; + var output_shape_i = ${re("uniforms.output_shape","i",r.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${a} || (original_idx >= 0 && original_idx < ${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; + }`,Ih=(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 >= ${re("uniforms.input_shape","i",e.length)}) { + return false; + } + } + return true; + }`,Ci=(t,e,n,r)=>t.rank>r?` + ${t.indicesSet("input_indices",e,"channel")}; + ${t.indicesSet("input_indices",n,"batch")}; +`:"",zh=(t,e,n,r,s)=>{let[i,a,o,l]=n.length===2?[-1,0,1,-1]:[0,2,3,1],u=t.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { + var input_indices: ${t.type.indices}; + ${t.indicesSet("input_indices",a,`max(0, min(row, ${n[a]} - 1))`)}; + ${t.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)}; + ${Ci(t,l,i,2)} + return ${t.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${e.type.indices}) -> ${u} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${u} = originalIndices[${a}]; + var col:${u} = originalIndices[${o}]; + ${r?`if (row < 0 || row > (${n[a]} - 1) || col < 0 || col > (${n[o]} - 1)) { + return ${s}; + }`:""}; + row = max(0, min(row, ${n[a]} - 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: ${u} = getInputValue(batch, channel, row1, col1); + var x12: ${u} = getInputValue(batch, channel, row1, col2); + var x21: ${u} = getInputValue(batch, channel, row2, col1); + var x22: ${u} = getInputValue(batch, channel, row2, col2); + var dx1: ${u} = abs(row - ${u}(row1)); + var dx2: ${u} = abs(${u}(row2) - row); + var dy1: ${u} = abs(col - ${u}(col1)); + var dy2: ${u} = abs(${u}(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); + }`},Oh=(t,e,n,r,s,i,a,o,l,u)=>{let c=n.length===2,[p,d]=c?[0,1]:[2,3],f=t.type.value,m=g=>{let w=g===p?"row":"col";return` + fn ${w}CubicInterpolation(input_indices: ${t.type.indices}, output_indices: ${e.type.indices}) -> ${f} { + var output_index = ${e.indicesGet("output_indices",g)}; + var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[g]}, + ${r[g]}, ${n[g]}, ${i[g]}, ${i[g]} + ${n.length}); + var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${o} && (originalIdx < 0 || originalIdx > (${n[g]} - 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 ${w}: ${f} = originalIdx + ${f}(i); + if (${w} < 0 || ${w} >= ${n[g]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:o?`return ${l};`:`${w} = max(0, min(${w}, ${n[g]} - 1));`}; + } + var input_indices_copy: ${t.type.indices} = input_indices; + ${t.indicesSet("input_indices_copy",g,`u32(${w})`)}; + data[i + 1] = ${g===p?t.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${m(p)}; + ${m(d)}; + 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] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; + coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; + coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${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); + } + `},Ph=(t,e,n,r,s)=>{let[i,a,o,l,u]=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",a,`max(0, min(depth, ${n[a]} - 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))`)}; + ${Ci(t,u,i,3)} + return ${t.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${c} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${c} = originalIndices[${a}]; + var height:${c} = originalIndices[${o}]; + var width:${c} = originalIndices[${l}]; + ${r?`if (depth < 0 || depth > (${n[a]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[l]} - 1)) { + return ${s}; + }`:""}; + + depth = max(0, min(depth, ${n[a]} - 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[${u}])`:"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); + }`},Bh=(t,e,n,r,s,i)=>{let a=t.dims,o=Eh(i,e.axes,a.length),l=Th(a,r,s,e.axes),u=r.slice();r.length===0&&(u=a.map((y,$)=>y===0?1:l[$]/y),e.keepAspectRatioPolicy!=="stretch"&&(l=Mh(a,u,e)));let c=ae("output",t.dataType,l.length),p=L("input",t.dataType,a.length),d=D.size(l),f=a.length===l.length&&a.every((y,$)=>y===l[$]),m=e.coordinateTransformMode==="tf_crop_and_resize",g=e.extrapolationValue,w=p.type.value,v=y=>` + ${f?"":` + ${kh(e.coordinateTransformMode,w)}; + ${(()=>{switch(e.mode){case"nearest":return` + ${Ih(p,a)}; + ${Sh(e.nearestMode,n,w)}; + ${Ah(p,c,a,l,u.length,o.length,m)}; + `;case"linear":return` + ${Ch(c,a,l,u.length,o.length)}; + ${(()=>{if(a.length===2||a.length===4)return`${zh(p,c,a,m,g)}`;if(a.length===3||a.length===5)return`${Ph(p,c,a,m,g)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(a.length===2||a.length===4)return`${Oh(p,c,a,l,u,o,e.cubicCoeffA,m,e.extrapolationValue,e.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${y.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",o.length).declareVariables(p,c)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${f?"output[global_idx] = input[global_idx];":` + let output_indices = ${c.offsetToIndices("global_idx")}; + var input_indices: ${p.type.indices}; + ${(()=>{switch(e.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${p.getByIndices("input_indices")}; + } else { + output[global_idx] = ${e.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${e.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${e.cacheKey}|${n}|${u.length>0?u:""}|${s.length>0?s:""}|${o.length>0?o:""}|${f}|${a}`,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:u},{type:1,data:o},...se(a,l)]})}},Rh=t=>{let e=t.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},Fh=(t,e)=>{let n=[],r=[],s=[],i=Rh(t);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");$h(t.inputs,e,i,n,r,s),t.compute(Bh(t.inputs[0],e,i,n,r,s),{inputs:[0]})},Dh=t=>{let e=t.antialias,n=t.axes,r=t.coordinateTransformMode,s=t.cubicCoeffA,i=t.excludeOutside!==0,a=t.extrapolationValue,o=t.keepAspectRatioPolicy,l=t.mode,u=t.nearestMode===""?"simple":t.nearestMode;return $e({antialias:e,axes:n,coordinateTransformMode:r,cubicCoeffA:s,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:o,mode:l,nearestMode:u})}}),Nh,Lh,Uh,D0=W(()=>{ue(),pe(),Fe(),he(),Nh=(t,e)=>{let[n,r,s,i]=t,{numHeads:a,rotaryEmbeddingDim:o}=e;if(n.dims.length!==3&&n.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!D.areEqual(r.dims,[])&&!D.areEqual(r.dims,[1])&&r.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${r.dims.length}`);if(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!D.areEqual(s.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(o>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=n.dims[0],u=n.dims[n.dims.length-2],c=s.dims[0],p=D.sizeFromDimension(n.dims,1)/u,d=o===0?s.dims[1]*2:p/a;if(o>d)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(r.dims.length===2){if(l!==r.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${r.dims[0]}`);if(u!==r.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${r.dims[1]}`)}if(d/2!==s.dims[1]&&o/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(u>c)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Lh=(t,e)=>{let{interleaved:n,numHeads:r,rotaryEmbeddingDim:s,scale:i}=e,a=t[0].dims[0],o=D.sizeFromDimension(t[0].dims,1),l=t[0].dims[t[0].dims.length-2],u=o/l,c=t[2].dims[1],p=s===0?c*2:u/r,d=new Array(a,l,u/p,p-c),f=D.computeStrides(d),m=[{type:1,data:i},{type:12,data:d},{type:12,data:f},...t[0].dims.length===3?new Array({type:12,data:[o,u,p,1]}):[],...t[0].dims.length===4?new Array({type:12,data:[o,p,l*p,1]}):[],...se(t[0].dims,t[1].dims,t[2].dims,t[3].dims,t[0].dims)],g=w=>{let v=L("input",t[0].dataType,t[0].dims.length),y=L("position_ids",t[1].dataType,t[1].dims.length),$=L("cos_cache",t[2].dataType,t[2].dims.length),k=L("sin_cache",t[3].dataType,t[3].dims.length),E=ae("output",t[0].dataType,t[0].dims.length);return w.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` + ${w.declareVariables(v,y,$,k,E)} + + ${w.mainStart(qn)} + let half_rotary_emb_dim = uniforms.${$.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${w.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${y.broadcastedIndicesToOffset("bsnh.xy",ae("",y.type.tensor,2))}; + let position_id = + u32(${y.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n}); + let j = i + select(half_rotary_emb_dim, 1, ${n}); + let re = ${v.getByOffset("i")} * ${$.get("position_id","bsnh[3]")} - + ${v.getByOffset("j")} * ${k.get("position_id","bsnh[3]")}; + ${E.setByOffset("i","re")} + let im = ${v.getByOffset("i")} * ${k.get("position_id","bsnh[3]")} + + ${v.getByOffset("j")} * ${$.get("position_id","bsnh[3]")}; + ${E.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${E.setByOffset("k",v.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:$e({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(D.size(d)/qn)},programUniforms:m})}},Uh=(t,e)=>{Nh(t.inputs,e),t.compute(Lh(t.inputs,e))}}),Vh,jh,qh,N0=W(()=>{ue(),pe(),he(),Vh=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 s=e.dims[e.dims.length-1],i=e.dims[e.dims.length-2];if(n.dims[n.dims.length-1]!==s)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]!==s)throw new Error("Gamma must have the same hidden size as input");if(t.length>3){let a=t[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(t.length>4){let a=t[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},jh=(t,e,n,r)=>{let s=e.simplified,i=t[0].dims,a=D.size(i),o=i,l=a,u=i.slice(-1)[0],c=r?i.slice(0,-1).concat(1):[],p=!s&&t.length>3,d=t.length>4,f=r&&n>1,m=r&&n>2,g=n>3,w=64,v=Ue(u),y=[{type:12,data:l},{type:12,data:v},{type:12,data:u},{type:1,data:e.epsilon}],$=E=>{let T=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],C=[L("x",t[0].dataType,t[0].dims,v),L("skip",t[1].dataType,t[1].dims,v),L("gamma",t[2].dataType,t[2].dims,v)];p&&C.push(L("beta",t[3].dataType,t[3].dims,v)),d&&C.push(L("bias",t[4].dataType,t[4].dims,v)),C.push(ae("output",t[0].dataType,o,v)),f&&C.push(ae("mean_output",1,c)),m&&C.push(ae("inv_std_output",1,c)),g&&C.push(ae("input_skip_bias_sum",t[0].dataType,o,v));let B=Le(t[0].dataType),U=Le(1,v);return` + + ${E.registerUniforms(T).declareVariables(...C)} + var sum_shared : array<${U}, ${w}>; + var sum_squared_shared : array<${U}, ${w}>; + + ${E.mainStart([w,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${w}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${w}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${w-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${d?"bias[offset1d + i]":B+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${g?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Gn(B,v,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${w}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${sn("sum",v)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${sn("square_sum",v)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); + ${f?"mean_output[global_idx] = mean;":""} + ${m?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${s?"":`- ${B}(mean)`}) * + ${B}(inv_std_dev) * gamma[offset1d + i] + ${p?"+ beta[offset1d + i]":""}; + } + }`},k=[{dims:o,dataType:t[0].dataType}];return n>1&&k.push({dims:c,dataType:1}),n>2&&k.push({dims:c,dataType:1}),n>3&&k.push({dims:i,dataType:t[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${v};${f};${m};${g}`,inputDependencies:t.map((E,T)=>"type")},getShaderSource:$,getRunData:()=>({outputs:k,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:y})}},qh=(t,e)=>{Vh(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(jh(t.inputs,e,t.outputCount,!1),{outputs:n})}}),Gh,xr,Wh,Ai,Hh,Kh,Xh,Qh,L0=W(()=>{ue(),pe(),Fe(),he(),Gh=(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`)})},xr=(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},Wh=(t,e)=>{if(t.length>1){let n=xr(t,1),r=xr(t,2),s=xr(t,3);return s.length===0&&(s=[...Array(t[0].dims.length).keys()]),$e({starts:n,ends:r,axes:s})}else return e},Ai=(t,e,n,r,s)=>{let i=t;return t<0&&(i+=n[r[e]]),s[e]<0?Math.max(0,Math.min(i,n[r[e]]-1)):Math.max(0,Math.min(i,n[r[e]]))},Hh=(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 = ${re("uniforms.input_shape","i",n.length)}; + let steps_i = ${re("uniforms.steps","i",n.length)}; + let signs_i = ${re("uniforms.signs","i",n.length)}; + let starts_i = ${re("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; + }`,Kh=(t,e)=>{let n=t[0].dims,r=D.size(n),s=e.axes.length>0?D.normalizeAxes(e.axes,n.length):[...Array(n.length).keys()],i=xr(t,4);i.forEach(v=>v!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(s.length).fill(1));let a=e.starts.map((v,y)=>Ai(v,y,n,s,i)),o=e.ends.map((v,y)=>Ai(v,y,n,s,i));if(s.length!==a.length||s.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==n.length)for(let v=0;vMath.sign(v));i.forEach((v,y,$)=>{if(v<0){let k=(o[y]-a[y])/v,E=a[y],T=E+k*i[y];a[y]=T,o[y]=E,$[y]=-v}});let u=n.slice(0);s.forEach((v,y)=>{u[v]=Math.ceil((o[v]-a[v])/i[v])});let c={dims:u,dataType:t[0].dataType},p=ae("output",t[0].dataType,u.length),d=L("input",t[0].dataType,t[0].dims.length),f=D.size(u),m=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:i.length}],g=[{type:12,data:f},{type:12,data:a},{type:6,data:l},{type:12,data:i},...se(t[0].dims,u)],w=v=>` + ${v.registerUniforms(m).declareVariables(d,p)} + ${Hh(d,p,n)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${p.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${p.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${a.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[c],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:g})}},Xh=(t,e)=>{Gh(t.inputs,e);let n=Wh(t.inputs,e);t.compute(Kh(t.inputs,n),{inputs:[0]})},Qh=t=>{let e=t.starts,n=t.ends,r=t.axes;return $e({starts:e,ends:n,axes:r})}}),Yh,Zh,Jh,ef,U0=W(()=>{ue(),pe(),Fe(),he(),Yh=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},Zh=(t,e)=>{let n=t.dims,r=D.size(n),s=64,i=e.axis;if(i<0&&(i=n.length+i),iv===4?`max(max(${w}.x, ${w}.y), max(${w}.z, ${w}.w))`:v===2?`max(${w}.x, ${w}.y)`:v===3?`max(max(${w}.x, ${w}.y), ${w}.z)`:w,p=L("x",t.dataType,t.dims,l),d=ae("result",t.dataType,t.dims,l),f=p.type.value,m=Le(t.dataType)==="f32"?`var threadMax = ${f}(-3.402823e+38f);`:`var threadMax = ${f}(-65504.0h);`,g=w=>` + var rowMaxShared : ${f}; + var rowSumShared : ${f}; + var threadShared : array<${f}, ${s}>; + + 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; + } + ${w.registerUniform("packedCols","i32").declareVariables(p,d)} + ${w.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${s}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${m} + 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}(${sn("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:6,data:u}]}),getShaderSource:g}},Jh=(t,e)=>{Yh(t.inputs),t.compute(Zh(t.inputs[0],e))},ef=t=>$e({axis:t.axis})}),tf,nf,rf,sf,af,of,lf,V0=W(()=>{ue(),pe(),Fe(),he(),tf=t=>{if(!t||t.length<1)throw new Error("too few inputs")},nf=(t,e)=>{let n=[],r=e.numOutputs;return t[1].dims[0]>0&&(t[1].getBigInt64Array().forEach(s=>n.push(Number(s))),r=n.length),$e({numOutputs:r,axis:e.axis,splitSizes:n})},rf=t=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${t}u; i += 1u ) { + if (index < ${re("uniforms.size_in_split_axis","i",t)}) { + return i; + } + } + return ${t}u; +}`,sf=t=>{let e=t.length,n=[];for(let r=0;r{let n=t[0].dims,r=D.size(n),s=t[0].dataType,i=D.normalizeAxis(e.axis,n.length),a=new Array(e.numOutputs),o=L("input",s,n.length),l=new Array(e.numOutputs),u=[],c=[],p=0,d=[{type:12,data:r}];for(let m=0;m` + ${m.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...a)} + ${rf(l.length)} + ${sf(a)} + + ${m.mainStart()} + ${m.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 -= ${re("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:u,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:d})}},of=(t,e)=>{tf(t.inputs);let n=t.inputs.length===1?e:nf(t.inputs,e);t.compute(af(t.inputs,n),{inputs:[0]})},lf=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 $e({axis:e,numOutputs:r,splitSizes:n})}}),uf,df,cf,j0=W(()=>{ue(),pe(),he(),uf=(t,e,n,r,s)=>{let i=ae("output_data",s,n.length,4),a=L("a_data",e[1].dataType,e[1].dims.length,4),o=L("b_data",e[2].dataType,e[2].dims.length,4),l=L("c_data",e[0].dataType,e[0].dims.length,4),u,c=(p,d,f)=>`select(${d}, ${p}, ${f})`;if(!r)u=i.setByOffset("global_idx",c(a.getByOffset("global_idx"),o.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let p=(d,f,m="")=>{let g=`a_data[index_a${f}][component_a${f}]`,w=`b_data[index_b${f}][component_b${f}]`,v=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` + let output_indices${f} = ${i.offsetToIndices(`global_idx * 4u + ${f}u`)}; + let offset_a${f} = ${a.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; + let component_c${f} = offset_c${f} % 4u; + ${d}[${f}] = ${m}(${c(g,w,v)}); + `};s===9?u=` + var data = vec4(0); + ${p("data",0,"u32")} + ${p("data",1,"u32")} + ${p("data",2,"u32")} + ${p("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` + ${p("output_data[global_idx]",0)} + ${p("output_data[global_idx]",1)} + ${p("output_data[global_idx]",2)} + ${p("output_data[global_idx]",3)} + `}return` + ${t.registerUniform("vec_size","u32").declareVariables(l,a,o,i)} + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u} + }`},df=t=>{let e=t[1].dims,n=t[2].dims,r=t[0].dims,s=t[1].dataType,i=!(D.areEqual(e,n)&&D.areEqual(n,r)),a=e,o=D.size(e);if(i){let u=jn.calcShape(jn.calcShape(e,n,!1),r,!1);if(!u)throw new Error("Can't perform where op on the given tensors");a=u,o=D.size(a)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>uf(u,t,a,i,s),getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...se(r,e,n,a)]})}},cf=t=>{t.compute(df(t.inputs))}}),pf,q0=W(()=>{l0(),Xa(),u0(),d0(),c0(),p0(),h0(),Cc(),y0(),b0(),v0(),x0(),$0(),k0(),S0(),E0(),T0(),M0(),C0(),A0(),I0(),Sc(),z0(),Cp(),O0(),P0(),B0(),R0(),Wa(),F0(),D0(),N0(),L0(),U0(),V0(),Op(),Wn(),Ja(),j0(),pf=new Map([["Abs",[sd]],["Acos",[ad]],["Acosh",[id]],["Add",[Hd]],["ArgMax",[ju,Ka]],["ArgMin",[Vu,Ka]],["Asin",[od]],["Asinh",[ld]],["Atan",[ud]],["Atanh",[dd]],["Attention",[Xu]],["AveragePool",[oh,ih]],["BatchNormalization",[Ju]],["BiasAdd",[nd]],["BiasSplitGelu",[qd]],["Cast",[pd,cd]],["Ceil",[md]],["Clip",[fd]],["Concat",[oc,lc]],["Conv",[di,li]],["ConvTranspose",[Uc,Rc]],["Cos",[gd]],["Cosh",[_d]],["CumSum",[jc,qc]],["DepthToSpace",[Kc,Xc]],["DequantizeLinear",[gh,_h]],["Div",[Kd]],["Einsum",[tp,np]],["Elu",[wd,_r]],["Equal",[Xd]],["Erf",[yd]],["Exp",[bd]],["Expand",[ip]],["FastGelu",[lp]],["Floor",[vd]],["FusedConv",[di,li]],["Gather",[pp,cp]],["GatherElements",[bp,yp]],["GatherBlockQuantized",[mp,gp]],["Gelu",[xd]],["Gemm",[kp,$p]],["GlobalAveragePool",[uh,lh]],["GlobalMaxPool",[hh,ph]],["Greater",[Jd]],["GreaterOrEqual",[tc]],["GroupQueryAttention",[Fp,Bp]],["HardSigmoid",[Ad,Cd]],["InstanceNormalization",[Up]],["LayerNormalization",[qp]],["LeakyRelu",[$d,_r]],["Less",[ec]],["LessOrEqual",[nc]],["Log",[Dd]],["MatMul",[kc]],["MatMulNBits",[Hp,Kp]],["MaxPool",[dh,ch]],["Mul",[Qd]],["MultiHeadAttention",[Mp,Ep]],["Neg",[Sd]],["Not",[kd]],["Pad",[rh]],["Pow",[Yd]],["QuickGelu",[Ud,_r]],["Range",[bh]],["Reciprocal",[Ed]],["ReduceMin",[Fu]],["ReduceMean",[zu]],["ReduceMax",[Ru]],["ReduceSum",[Nu]],["ReduceProd",[Du]],["ReduceL1",[Ou]],["ReduceL2",[Pu]],["ReduceLogSum",[Uu]],["ReduceLogSumExp",[Bu]],["ReduceSumSquare",[Lu]],["Relu",[Td]],["Resize",[Fh,Dh]],["RotaryEmbedding",[Uh]],["Sigmoid",[Md]],["Sin",[Id]],["Sinh",[zd]],["Slice",[Xh,Qh]],["SkipLayerNormalization",[qh]],["Split",[of,lf]],["Sqrt",[Od]],["Softmax",[Jh,ef]],["Sub",[Zd]],["Tan",[Pd]],["Tanh",[Bd]],["ThresholdedRelu",[Fd,_r]],["Tile",[zp]],["Transpose",[Jl,eu]],["Where",[cf]]])}),hf,G0=W(()=>{Et(),rn(),he(),hf=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,s){St(t.programInfo.name);let i=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let o=[];for(let u of e)o.push({binding:o.length,resource:{buffer:u.buffer}});for(let u of n)o.push({binding:o.length,resource:{buffer:u.buffer}});s&&o.push({binding:o.length,resource:s});let l=i.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:o,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}a.setPipeline(t.computePipeline),a.setBindGroup(0,l),a.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(),_t(t.programInfo.name)}dispose(){}build(t,e){St(t.name);let n=this.backend.device,r=[];n.features.has("shader-f16")&&r.push("enable f16;");let s=Xl(e,this.backend.device.limits),i=t.getShaderSource(s),a=`${r.join(` +`)} +${s.additionalImplementations} +${i}`,o=n.createShaderModule({code:a,label:t.name});Be("verbose",()=>`[WebGPU] ${t.name} shader code: ${a}`);let l=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:t.name});return _t(t.name),{programInfo:t,computePipeline:l,uniformVariablesInfo:s.variablesInfo}}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,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=s&&n<=s&&r<=s)return[e,n,r];let i=e*n*r,a=Math.ceil(Math.sqrt(i));if(a>s){if(a=Math.ceil(Math.cbrt(i)),a>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),ff,mf,gf,_f,W0=W(()=>{Et(),ue(),rn(),a0(),i0(),q0(),G0(),ff=(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{var s,i;let r=t.name;return(s=t.shaderCache)!=null&&s.hint&&(r+="["+t.shaderCache.hint+"]"),r+=":"+n+`:${ff(e,((i=t.shaderCache)==null?void 0:i.inputDependencies)??new Array(e.length).fill("dims"))}`,r},gf=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},_f=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,e){this.env=t;let 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.adapterInfo=new gf(e.info||await e.requestAdapterInfo()),this.gpuDataManager=ql(this),this.programManager=new hf(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Dl(t.logLevel,!!t.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;St(),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(()=>{var r;let e=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let s=0;s"u"&&(this.queryTimeBase=f);let g=Number(f-this.queryTimeBase),w=Number(m-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(w))throw new RangeError("incorrect timestamp range");if((r=this.env.webgpu.profiling)!=null&&r.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:p.map(v=>({dims:v.dims,dataType:$n(v.dataType)})),outputsMetadata:d.map(v=>({dims:v.dims,dataType:$n(v.dataType)})),kernelId:a,kernelType:l,kernelName:u,programName:c,startTime:g,endTime:w});else{let v="";p.forEach(($,k)=>{v+=`input[${k}]: [${$.dims}] | ${$n($.dataType)}, `});let y="";d.forEach(($,k)=>{y+=`output[${k}]: [${$.dims}] | ${$n($.dataType)}, `}),console.log(`[profiling] kernel "${a}|${l}|${u}|${c}" ${v}${y}execution time: ${w-g} ns`)}hr("GPU",`${c}::${f}::${m}`)}t.unmap(),this.pendingQueries.delete(t)}),_t()}run(t,e,n,r,s,i){St(t.name);let a=[];for(let y=0;y$):n;if(c.length!==o.length)throw new Error(`Output size ${c.length} must be equal to ${o.length}.`);let p=[],d=[];for(let y=0;y=i)throw new Error(`Invalid output index: ${c[y]}`);if(c[y]===-3)continue;let $=c[y]===-1,k=c[y]===-2,E=$||k?s(o[y].dataType,o[y].dims):r(c[y],o[y].dataType,o[y].dims);if(p.push(E),E.data===0)continue;let T=this.gpuDataManager.get(E.data);if(!T)throw new Error(`no GPU data for output: ${E.data}`);if($&&this.temporaryData.push(T),k){let C=this.kernelPersistentData.get(this.currentKernelId);C||(C=[],this.kernelPersistentData.set(this.currentKernelId,C)),C.push(T)}d.push(T)}if(a.length!==e.length||d.length!==p.length){if(d.length===0)return _t(t.name),p;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(u){let y=0,$=[];u.forEach(C=>{let B=typeof C.data=="number"?[C.data]:C.data;if(B.length===0)return;let U=C.type===10?2:4,G,K;C.type===10?(K=B.length>4?16:B.length>2?8:B.length*U,G=B.length>4?16:U*B.length):(K=B.length<=2?B.length*U:16,G=16),y=Math.ceil(y/K)*K,$.push(y);let X=C.type===10?8:4;y+=B.length>4?Math.ceil(B.length/X)*G:B.length*U});let k=16;y=Math.ceil(y/k)*k;let E=new ArrayBuffer(y);u.forEach((C,B)=>{let U=$[B],G=typeof C.data=="number"?[C.data]:C.data;if(C.type===6)new Int32Array(E,U,G.length).set(G);else if(C.type===12)new Uint32Array(E,U,G.length).set(G);else if(C.type===10)new Uint16Array(E,U,G.length).set(G);else if(C.type===1)new Float32Array(E,U,G.length).set(G);else throw new Error(`Unsupported uniform type: ${$n(C.type)}`)});let T=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(T.buffer,0,E,0,y),this.gpuDataManager.release(T.id),f={offset:0,size:y,buffer:T.buffer}}let m=this.programManager.normalizeDispatchGroupSize(l),g=m[1]===1&&m[2]===1,w=mf(t,e,g),v=this.programManager.getArtifact(w);if(v||(v=this.programManager.build(t,m),this.programManager.setArtifact(w,v),Be("info",()=>`[artifact] key: ${w}, programName: ${t.name}`)),u&&v.uniformVariablesInfo){if(u.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${u.length} in program "${v.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${t.name}" (key=${w}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:e,outputTensorViews:p};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(v,a,d,m,f),_t(t.name),p}upload(t,e){this.gpuDataManager.upload(t,e)}memcpy(t,e){this.gpuDataManager.memcpy(t,e)}async download(t,e){await this.gpuDataManager.download(t,e)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,e,n,r){let s=pf.get(t);if(!s)throw new Error(`kernel not implemented: ${t}`);let i={kernelType:t,kernelName:r,kernelEntry:s[0],attributes:[s[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 s=r.kernelType,i=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${i}" is not allowed to be called recursively`);this.currentKernelId=t,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),Be("info",()=>`[WebGPU] Start to run kernel "[${s}] ${i}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(u){return n.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${i}" failed. ${u}`)),1}finally{l&&n.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${s}] ${i}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,e,n,r){let s=this.sessionExternalDataMapping.get(t);s||(s=new Map,this.sessionExternalDataMapping.set(t,s));let i=s.get(e),a=this.gpuDataManager.registerExternalBuffer(n,r,i==null?void 0:i[1]);return s.set(e,[a,n]),a}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 La(this,t,e);return Ll(r.buffer,n)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){var t;this.queryType="none",(((t=this.env.webgpu.profiling)==null?void 0:t.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Be("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Be("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Be("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let r=0;r=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}}),wf={};dr(wf,{init:()=>bf});var Ss,yf,bf,H0=W(()=>{ue(),W0(),rn(),pe(),Ss=class py{constructor(e,n,r,s){this.module=e,this.dataType=n,this.data=r,this.dims=s}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=D.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=D.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=D.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=D.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(D.size(e)!==D.size(this.dims))throw new Error("Invalid new shape");return new py(this.module,this.dataType,this.data,e)}},yf=class{constructor(t,e,n){this.module=t,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=t.HEAPU32,s=n>>>2;this.opKernelContext=r[s++];let i=r[s++];this.outputCount=r[s++],this.customDataOffset=r[s++],this.customDataSize=r[s++];let a=[];for(let o=0;otypeof o=="number"?this.inputs[o]:o))??this.inputs,r=(e==null?void 0:e.outputs)??[],s=(o,l,u)=>new Ss(this.module,l,this.output(o,u),u),i=(o,l)=>{let u=ls(o,l);if(!u)throw new Error(`Unsupported data type: ${o}`);let c=u>0?this.backend.gpuDataManager.create(u).id:0;return new Ss(this.module,o,c,l)};return this.backend.run(t,n,r,s,i,this.outputCount)}output(t,e){let n=this.module.stackSave();try{let r=this.module.stackAlloc((1+e.length)*4),s=r>>2;this.module.HEAPU32[s++]=e.length;for(let i=0;i{let s=e.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(t==="webgpu"){let i=new _f;await i.initialize(n,r),s("webgpu",[i,a=>i.alloc(a),a=>i.free(a),(a,o,l,u=!1)=>{if(u)Be("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${o}, size=${l}`),i.memcpy(a,o);else{Be("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${o}, size=${l}`);let c=e.HEAPU8.subarray(a>>>0,(a>>>0)+l);i.upload(o,c)}},async(a,o,l)=>{Be("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${o}, size=${l}`),await i.download(a,()=>e.HEAPU8.subarray(o>>>0,(o>>>0)+l))},(a,o,l)=>i.createKernel(a,o,l,e.UTF8ToString(e._JsepGetNodeName(o))),a=>i.releaseKernel(a),(a,o,l,u)=>{Be("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${a}, contextDataOffset=${o}`);let c=new yf(e,i,o);return i.computeKernel(a,c,u)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else s("webnn")}}),vf,Ii,zi,dn,xf,Es,Oi,Pi,Bi,Ri,Fi,Di,$f=W(()=>{r0(),s0(),ue(),Vn(),Ia(),Ol(),vf=(t,e)=>{je()._OrtInit(t,e)!==0&&Ae("Can't initialize onnxruntime.")},Ii=async t=>{vf(t.wasm.numThreads,us(t.logLevel))},zi=async(t,e)=>{{let n=(H0(),rs(wf)).init;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let r=t.webgpu.adapter;if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let i=t.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:i}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await n("webgpu",je(),t,r)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await n("webnn",je(),t)}}},dn=new Map,xf=t=>{let e=je(),n=e.stackSave();try{let r=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,r,r+4)!==0&&Ae("Can't get session input/output count."),[e.HEAP32[r/4],e.HEAP32[r/4+1]]}finally{e.stackRestore(n)}},Es=t=>{let e=je(),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]},Oi=async(t,e)=>{var p,d;let n,r,s=je();Array.isArray(t)?[n,r]=t:t.buffer===s.HEAPU8.buffer?[n,r]=[t.byteOffset,t.byteLength]:[n,r]=Es(t);let i=0,a=0,o=0,l=[],u=[],c=[];try{if([a,l]=zl(e),(e==null?void 0:e.externalData)&&s.mountExternalData){let k=[];for(let E of e.externalData){let T=typeof E=="string"?E:E.path;k.push(Ra(typeof E=="string"?E:E.data).then(C=>{s.mountExternalData(T,C)}))}await Promise.all(k)}for(let k of(e==null?void 0:e.executionProviders)??[])if((typeof k=="string"?k:k.name)==="webnn"){if(s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof k!="string"){let E=k,T=E==null?void 0:E.context,C=E==null?void 0:E.gpuDevice,B=E==null?void 0:E.deviceType,U=E==null?void 0:E.numThreads,G=E==null?void 0:E.powerPreference;T?s.currentContext=T:C?s.currentContext=await navigator.ml.createContext(C):s.currentContext=await navigator.ml.createContext({deviceType:B,numThreads:U,powerPreference:G})}else s.currentContext=await navigator.ml.createContext();break}i=await s._OrtCreateSession(n,r,a),i===0&&Ae("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[f,m]=xf(i),g=!!(e!=null&&e.enableGraphCapture),w=[],v=[],y=[];for(let k=0;kk==="gpu-buffer")&&(o=s._OrtCreateBinding(i),o===0&&Ae("Can't create IO binding."),$={handle:o,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(k=>Ba(k))}),dn.set(i,[i,u,c,$,g,!1]),[i,w,v]}catch(f){throw u.forEach(m=>s._OrtFree(m)),c.forEach(m=>s._OrtFree(m)),o!==0&&s._OrtReleaseBinding(o),i!==0&&s._OrtReleaseSession(i),f}finally{s._free(n),a!==0&&s._OrtReleaseSessionOptions(a),l.forEach(f=>s._free(f)),(d=s.unmountExternalData)==null||d.call(s)}},Pi=t=>{var l;let e=je(),n=dn.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[r,s,i,a,o]=n;a&&(o&&e._OrtClearBoundOutputs(a.handle),e._OrtReleaseBinding(a.handle)),(l=e.jsepOnReleaseSession)==null||l.call(e,t),s.forEach(u=>e._OrtFree(u)),i.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(r),dn.delete(t)},Bi=(t,e,n,r,s,i=!1)=>{if(!t){e.push(0);return}let a=je(),o=t[0],l=t[1],u=t[3],c,p;if(o==="string"&&u==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(i&&u!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(u==="gpu-buffer"){let m=t[2].gpuBuffer;p=ls(za(o),l);let g=a.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');c=g(r,s,m,p)}else{let m=t[2];if(Array.isArray(m)){p=4*m.length,c=a._malloc(p),n.push(c);let g=c/4;for(let w=0;wa.HEAP32[m++]=w);let g=a._OrtCreateTensor(za(o),c,p,f,l.length,Ba(u));g===0&&Ae(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{a.stackRestore(d)}},Ri=async(t,e,n,r,s,i)=>{var G,K;let a=je(),o=dn.get(t);if(!o)throw new Error(`cannot run inference. invalid session id: ${t}`);let l=o[0],u=o[1],c=o[2],p=o[3],d=o[4],f=o[5],m=e.length,g=r.length,w=0,v=[],y=[],$=[],k=[],E=a.stackSave(),T=a.stackAlloc(m*4),C=a.stackAlloc(m*4),B=a.stackAlloc(g*4),U=a.stackAlloc(g*4);try{[w,v]=Tl(i);for(let R=0;RDe*Ve,1);ie=$n(Ee);let Pt=p==null?void 0:p.outputPreferredLocations[r[R]];if(ie==="string"){if(Pt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let De=[],Ve=ge/4;for(let it=0;it0){let De=a.jsepGetBuffer;if(!De)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ve=De(ge),it=ls(Ee,Oe);if(it===void 0||!Pa(ie))throw new Error(`Unsupported data type: ${ie}`);q=!0,N.push([ie,Ne,{gpuBuffer:Ve,download:a.jsepCreateDownloader(Ve,it,ie),dispose:()=>{a._OrtReleaseTensor(Y)}},"gpu-buffer"])}else{let De=Oa(ie),Ve=new De(Oe);new Uint8Array(Ve.buffer,Ve.byteOffset,Ve.byteLength).set(a.HEAPU8.subarray(ge,ge+Ve.byteLength)),N.push([ie,Ne,Ve,"cpu"])}}finally{a.stackRestore(te),ie==="string"&&ge&&a._free(ge),q||a._OrtReleaseTensor(Y)}}return p&&!d&&(a._OrtClearBoundOutputs(p.handle),dn.set(t,[l,u,c,p,d,!1])),N}finally{a.stackRestore(E),y.forEach(X=>a._OrtReleaseTensor(X)),$.forEach(X=>a._OrtReleaseTensor(X)),k.forEach(X=>a._free(X)),w!==0&&a._OrtReleaseRunOptions(w),v.forEach(X=>a._free(X))}},Fi=t=>{let e=je(),n=dn.get(t);if(!n)throw new Error("invalid session id");let r=n[0],s=e._OrtEndProfiling(r);s===0&&Ae("Can't get an profile file name."),e._OrtFree(s)},Di=t=>{let e=[];for(let n of t){let r=n[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),cn,ot,Hn,$r,kr,Ts,Ni,Ms,Sn,En,kf,Sf,Ef,Tf,Mf,Cf,Af,If,zf=W(()=>{Et(),$f(),Vn(),as(),cn=()=>!!Te.wasm.proxy&&typeof document<"u",Hn=!1,$r=!1,kr=!1,Ms=new Map,Sn=(t,e)=>{let n=Ms.get(t);n?n.push(e):Ms.set(t,[e])},En=()=>{if(Hn||!$r||kr||!ot)throw new Error("worker not ready")},kf=t=>{switch(t.data.type){case"init-wasm":Hn=!1,t.data.err?(kr=!0,Ni[1](t.data.err)):($r=!0,Ni[0]()),Ts&&(URL.revokeObjectURL(Ts),Ts=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Ms.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},Sf=async()=>{if(!$r){if(Hn)throw new Error("multiple calls to 'initWasm()' detected.");if(kr)throw new Error("previous call to 'initWasm()' failed.");if(Hn=!0,cn())return new Promise((t,e)=>{ot==null||ot.terminate(),xl().then(([n,r])=>{try{ot=r,ot.onerror=i=>e(i),ot.onmessage=kf,Ni=[t,e];let s={type:"init-wasm",in:Te};ot.postMessage(s),Ts=n}catch(s){e(s)}},e)});try{await Aa(Te.wasm),await Ii(Te),$r=!0}catch(t){throw kr=!0,t}finally{Hn=!1}}},Ef=async t=>{if(cn())return En(),new Promise((e,n)=>{Sn("init-ep",[e,n]);let r={type:"init-ep",in:{epName:t,env:Te}};ot.postMessage(r)});await zi(Te,t)},Tf=async t=>cn()?(En(),new Promise((e,n)=>{Sn("copy-from",[e,n]);let r={type:"copy-from",in:{buffer:t}};ot.postMessage(r,[t.buffer])})):Es(t),Mf=async(t,e)=>{if(cn()){if(e!=null&&e.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return En(),new Promise((n,r)=>{Sn("create",[n,r]);let s={type:"create",in:{model:t,options:{...e}}},i=[];t instanceof Uint8Array&&i.push(t.buffer),ot.postMessage(s,i)})}else return Oi(t,e)},Cf=async t=>{if(cn())return En(),new Promise((e,n)=>{Sn("release",[e,n]);let r={type:"release",in:t};ot.postMessage(r)});Pi(t)},Af=async(t,e,n,r,s,i)=>{if(cn()){if(n.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return En(),new Promise((a,o)=>{Sn("run",[a,o]);let l=n,u={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:r,options:i}};ot.postMessage(u,Di(l))})}else return Ri(t,e,n,r,s,i)},If=async t=>{if(cn())return En(),new Promise((e,n)=>{Sn("end-profiling",[e,n]);let r={type:"end-profiling",in:t};ot.postMessage(r)});Fi(t)}}),Li,Of,Pf,K0=W(()=>{Et(),zf(),ue(),xa(),Ol(),Li=(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()}`)}},Of=t=>{switch(t[3]){case"cpu":return new nt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Pa(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:s}=t[2];return nt.fromGpuBuffer(n,{dataType:e,dims:t[1],download:r,dispose:s})}default:throw new Error(`invalid data location: ${t[3]}`)}},Pf=class{async fetchModelAndCopyToWasmMemory(t){return Tf(await Ra(t))}async loadModel(t,e){St();let n;typeof t=="string"?n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await Mf(n,e),_t()}async dispose(){return Cf(this.sessionId)}async run(t,e,n){St();let r=[],s=[];Object.entries(t).forEach(p=>{let d=p[0],f=p[1],m=this.inputNames.indexOf(d);if(m===-1)throw new Error(`invalid input '${d}'`);r.push(f),s.push(m)});let i=[],a=[];Object.entries(e).forEach(p=>{let d=p[0],f=p[1],m=this.outputNames.indexOf(d);if(m===-1)throw new Error(`invalid output '${d}'`);i.push(f),a.push(m)});let o=r.map((p,d)=>Li(p,()=>`input "${this.inputNames[s[d]]}"`)),l=i.map((p,d)=>p?Li(p,()=>`output "${this.outputNames[a[d]]}"`):null),u=await Af(this.sessionId,s,o,a,l,n),c={};for(let p=0;p{Et(),zf(),K0(),as(),Bf=()=>{if((typeof Te.wasm.initTimeout!="number"||Te.wasm.initTimeout<0)&&(Te.wasm.initTimeout=0),Te.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof Te.wasm.proxy!="boolean"&&(Te.wasm.proxy=!1),typeof Te.wasm.trace!="boolean"&&(Te.wasm.trace=!1),typeof Te.wasm.numThreads!="number"||!Number.isInteger(Te.wasm.numThreads)||Te.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Te.wasm.numThreads=1;else{let t=typeof navigator>"u"?Dy("node:os").cpus().length:navigator.hardwareConcurrency;Te.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Rf=class{async init(t){Bf(),await Sf(),await Ef(t)}async createInferenceSessionHandler(t,e){let n=new Pf;return await n.loadModel(t,e),Promise.resolve(n)}}}),Ff={};dr(Ff,{wasmBackend:()=>Df});var Df,Q0=W(()=>{X0(),Df=new Rf});Et(),Et(),Et();var Y0="1.20.0-dev.20240827-1d059b8702",Z0=fl;{let t=(Q0(),rs(Ff)).wasmBackend;vn("webgpu",t,5),vn("webnn",t,5),vn("cpu",t,10),vn("wasm",t,10)}Object.defineProperty(Te.versions,"web",{value:Y0,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var J0=Object.freeze({__proto__:null,get InferenceSession(){return ba},get TRACE(){return hr},get TRACE_FUNC_BEGIN(){return St},get TRACE_FUNC_END(){return _t},get Tensor(){return nt},get TrainingSession(){return va},default:Z0,get env(){return Te},get registerBackend(){return vn}});const eb=(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 s,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[3]):(s=t.dims[3],i=t.dims[2]);const a=(e==null?void 0:e.format)!==void 0?e.format:"RGB",o=e==null?void 0:e.norm;let l,u;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?u=[0,0,0,0]:typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:(u=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(u[3]=o.bias[3]));const c=i*s;let p=0,d=c,f=c*2,m=-1;a==="RGBA"?(p=0,d=c,f=c*2,m=c*3):a==="RGB"?(p=0,d=c,f=c*2):a==="RBG"&&(p=0,f=c,d=c*2);for(let g=0;g{const n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(n!=null){let s,i,a;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[1],a=t.dims[3]):(s=t.dims[3],i=t.dims[2],a=t.dims[1]);const o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e==null?void 0:e.norm;let u,c;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 p=i*s;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const d=4;let f=0,m=1,g=2,w=3,v=0,y=p,$=p*2,k=-1;o==="RGBA"?(v=0,y=p,$=p*2,k=p*3):o==="RGB"?(v=0,y=p,$=p*2):o==="RBG"&&(v=0,$=p,y=p*2),r=n.createImageData(s,i);for(let E=0;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");const{height:n,width:r}=e,s=e.norm??{mean:255,bias:0};let i,a;typeof s.mean=="number"?i=[s.mean,s.mean,s.mean,s.mean]:i=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?a=[s.bias,s.bias,s.bias,s.bias]:a=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];const o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=n*r,c=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let p=4,d=0,f=1,m=2,g=3,w=0,v=u,y=u*2,$=-1;o==="RGB"&&(p=3,d=0,f=1,m=2,g=-1),l==="RGBA"?$=u*3:l==="RBG"?(w=0,y=u,v=u*2):l==="BGR"&&(y=0,v=u,w=u*2);for(let E=0;E{const n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,r=typeof ImageData<"u"&&t instanceof ImageData,s=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,i=typeof t=="string";let a,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")},u=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 p=u(c);if(p!=null){let d=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(d=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=d,o.width=f}else o.tensorFormat="RGBA",o.height=d,o.width=f;p.drawImage(t,0,0),a=p.getImageData(0,0,f,d).data}else throw new Error("Can not access image data")}else if(r){let c,p;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,p=e.resizedWidth):(c=t.height,p=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=c,o.width=p,e!==void 0){const d=l();d.width=p,d.height=c;const f=u(d);if(f!=null)f.putImageData(t,0,0),a=f.getImageData(0,0,p,c).data;else throw new Error("Can not access image data")}else a=t.data}else if(s){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 p=u(c);if(p!=null){const d=t.height,f=t.width;return p.drawImage(t,0,0,f,d),a=p.getImageData(0,0,f,d).data,o.height=d,o.width=f,Ui(a,o)}else throw new Error("Can not access image data")}else{if(i)return new Promise((c,p)=>{const d=l(),f=u(d);if(!t||!f)return p();const m=new Image;m.crossOrigin="Anonymous",m.src=t,m.onload=()=>{d.width=m.width,d.height=m.height,f.drawImage(m,0,0,d.width,d.height);const g=f.getImageData(0,0,d.width,d.height);o.height=d.height,o.width=d.width,c(Ui(g.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Ui(a,o);throw new Error("Input data provided is not supported - aborted tensor creation")},rb=(t,e)=>{const{width:n,height:r,download:s,dispose:i}=e,a=[1,r,n,4];return new Ft({location:"texture",type:"float32",texture:t,dims:a,download:s,dispose:i})},sb=(t,e)=>{const{dataType:n,dims:r,download:s,dispose:i}=e;return new Ft({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:s,dispose:i})},ab=(t,e,n)=>new Ft({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]}),Kn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Cs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Nf=!1;const ib=()=>{if(!Nf){Nf=!0;const t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,n=typeof Float16Array<"u"&&Float16Array.from;t&&(Kn.set("int64",BigInt64Array),Cs.set(BigInt64Array,"int64")),e&&(Kn.set("uint64",BigUint64Array),Cs.set(BigUint64Array,"uint64")),n?(Kn.set("float16",Float16Array),Cs.set(Float16Array,"float16")):Kn.set("float16",Uint16Array)}},ob=t=>{let e=1;for(let n=0;n{switch(t.location){case"cpu":return new Ft(t.type,t.data,e);case"cpu-pinned":return new Ft({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Ft({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Ft({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let Ft=class{constructor(e,n,r){ib();let s,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,i=e.dims,e.location){case"cpu-pinned":{const o=Kn.get(s);if(!o)throw new TypeError(`unsupported type "${s}" 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(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool")throw new TypeError(`unsupported type "${s}" 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(s=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 u=Kn.get(e);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(n)){if(e==="float16"&&u===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?o=u.from(n,BigInt):o=u.from(n)}else if(n instanceof u)o=n;else throw new TypeError(`A ${s} tensor's data must be type of ${u}`)}else if(l=n,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof e[0];if(u==="string")s="string",o=e;else if(u==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else{const u=Cs.get(e.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=u,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 a=ob(i);if(this.cpuData&&a!==this.cpuData.length)throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=i,this.size=a}static async fromImage(e,n){return nb(e,n)}static fromTexture(e,n){return rb(e,n)}static fromGpuBuffer(e,n){return sb(e,n)}static fromPinnedBuffer(e,n,r){return ab(e,n,r)}toDataURL(e){return eb(this,e)}toImageData(e){return tb(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 lb(this,e)}};const ub=Ft,db=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),Dt=[];let Vi,Tn;if(bn.IS_NODE_ENV){switch(Tn=ke??Wt,process.platform){case"win32":Dt.push("dml");break;case"linux":process.arch==="x64"&&Dt.push("cuda");break}Dt.push("cpu"),Vi=["cpu"]}else Tn=J0,bn.IS_WEBNN_AVAILABLE&&Dt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),bn.IS_WEBGPU_AVAILABLE&&Dt.push("webgpu"),Dt.push("wasm"),Vi=["wasm"];const cb=Tn.InferenceSession;function pb(t=null){if(!t)return Vi;switch(t){case"auto":return Dt;case"gpu":return Dt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Dt.includes(t))return[db[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Dt.join(", ")}.`)}let ji=null;async function Lf(t,e){ji&&await ji;const n=cb.create(t,e);return ji??(ji=n),await n}function Uf(t){return t instanceof Tn.Tensor}const lt=Tn==null?void 0:Tn.env;lt!=null&<.wasm&&(lt.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${tt.version}/dist/`,lt.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(lt.wasm.numThreads=1)),lt!=null&<.webgpu&&(lt.webgpu.powerPreference="high-performance");function Vf(){var t;return(t=lt==null?void 0:lt.wasm)==null?void 0:t.proxy}tt.backends.onnx=lt;const Xn=async(t,e,n)=>{const r=await Lf(new Uint8Array(t),e);return async s=>{const i=Object.fromEntries(Object.entries(s).map(([o,l])=>[o,l.ort_tensor])),a=await r.run(i);return Array.isArray(n)?n.map(o=>new ee(a[o])):new ee(a[n])}};class Sr{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Xn([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Xn([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Xn([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Xn([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Xn([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Xn([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}A(Sr,"session_options",{});const jf=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{constructor(...e){A(this,"ort_tensor");return Uf(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new ub(e[0],e[1],e[2]),new Proxy(this,{get:(n,r)=>{if(typeof r=="string"){let s=Number(r);if(Number.isInteger(s))return n._getitem(s)}return n[r]},set:(n,r,s)=>n[r]=s})}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}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...n]=this.dims;if(n.length>0){const r=n.reduce((s,i)=>s*i);for(let s=0;s0){const s=r.reduce((i,a)=>i*a);return this._subarray(e,s,r)}else return new ee(this.type,[this.data[e]],r)}indexOf(e){const n=this.data;for(let r=0;rd)throw new Error(`Invalid slice: ${c}`);const f=[Math.max(p,0),Math.min(d,this.dims[u])];r.push(f),n.push(f[1]-f[0])}else throw new Error(`Invalid slice: ${c}`)}const s=r.map(([u,c])=>c-u),i=s.reduce((u,c)=>u*c),a=this.data,o=new a.constructor(i),l=this.stride();for(let u=0;u=0;--p){const f=s[p];c+=(d%f+r[p][0])*l[p],d=Math.floor(d/f)}o[u]=a[c]}return new ee(this.type,o,n)}permute(...e){return fb(this,e)}transpose(...e){return this.permute(...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}`);const s=this.data;if(n===null){let o=s.reduce((l,u)=>l+u**e,0)**(1/e);return new ee(this.type,[o],[])}n=Nt(n,this.dims.length);const i=this.dims.slice();i[n]=1;const a=new s.constructor(s.length/this.dims[n]);for(let o=0;o=0;--u){const d=this.dims[u];if(u!==n){const f=c%d;l+=f*p,p*=i[u]}c=Math.floor(c/d)}a[l]+=s[o]**e}if(e!==1)for(let o=0;o=0;--l){const p=this.dims[l];if(l!==n){const d=u%p;o+=d*c,c*=this.dims[l]}u=Math.floor(u/p)}s[a]/=i[o]}return this}normalize(e=2,n=1){return this.clone().normalize_(e,n)}stride(){return wb(this.dims)}squeeze(e=null){return new ee(this.type,this.data,Gf(this.dims,e))}squeeze_(e=null){return this.dims=Gf(this.dims,e),this}unsqueeze(e=null){return new ee(this.type,this.data,Wf(this.dims,e))}unsqueeze_(e=null){return this.dims=Wf(this.dims,e),this}flatten_(e=0,n=-1){n=(n+this.dims.length)%this.dims.length;let r=this.dims.slice(0,e),s=this.dims.slice(e,n+1),i=this.dims.slice(n+1);return this.dims=[...r,s.reduce((a,o)=>a*o,1),...i],this}flatten(e=0,n=-1){return this.clone().flatten_(e,n)}view(...e){let n=-1;for(let s=0;so!==n?i*a:i,1);e[n]=r.length/s}return new ee(this.type,r,e)}neg_(){const e=this.data;for(let n=0;ni*a);if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${e})`);let s=t;for(let i=e.length-1;i>=0;i--)s=s.reduce((a,o)=>{let l=a[a.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 Wf(t,e){return e=Nt(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function Nt(t,e,n=null,r=!0){if(r&&(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 ct(t,e=0){e=Nt(e,t[0].dims.length);const n=t[0].dims.slice();n[e]=t.reduce((a,o)=>a+o.dims[e],0);const r=n.reduce((a,o)=>a*o,1),s=new t[0].data.constructor(r),i=t[0].type;if(e===0){let a=0;for(const o of t){const l=o.data;s.set(l,a),a+=l.length}}else{let a=0;for(let o=0;o=0;--d){const g=u[d];let w=f%g;d===e&&(w+=a),p+=w*m,m*=n[d],f=Math.floor(f/g)}s[p]=l[c]}a+=u[e]}}return new ee(i,s,n)}function Er(t,e=0){return ct(t.map(n=>n.unsqueeze(e)),e)}function _b(t,e=null,n=1,r=!1){const s=t.data,i=t.dims;if(e===null){const d=s.reduce((w,v)=>w+v,0)/s.length,f=Math.sqrt(s.reduce((w,v)=>w+(v-d)**2,0)/(s.length-n)),m=new ee(t.type,[d],[]);return[new ee(t.type,[f],[]),m]}e=Nt(e,i.length);const a=Gi(t,e,r),o=a.data,l=i.slice();l[e]=1;const u=new s.constructor(s.length/i[e]);for(let p=0;p=0;--f){const w=i[f];if(f!==e){const v=m%w;d+=v*g,g*=l[f]}m=Math.floor(m/w)}u[d]+=(s[p]-o[d])**2}for(let p=0;pl+u,0);return new ee(t.type,[o/r.length],[])}const s=t.dims;e=Nt(e,s.length);const i=s.slice();i[e]=1;const a=new r.constructor(r.length/s[e]);for(let o=0;o=0;--u){const d=s[u];if(u!==e){const f=c%d;l+=f*p,p*=i[u]}c=Math.floor(c/d)}a[l]+=r[o]}if(s[e]!==1)for(let o=0;o=0;--n)e[n]=r,r*=t[n];return e}function Wi(t,e,n,r){const s=t.reduce((i,a)=>i*a,1);return new ee(n,new r(s).fill(e),t)}function Hf(t,e){let n,r;if(typeof e=="number")n="float32",r=Float32Array;else if(typeof e=="bigint")n="int64",r=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof e}`);return Wi(t,e,n,r)}function yb(t,e){return Hf(t.dims,e)}function Yn(t){return Wi(t,1n,"int64",BigInt64Array)}function bb(t){return Yn(t.dims)}function vb(t){return Wi(t,0n,"int64",BigInt64Array)}function xb(t){return vb(t.dims)}function $b(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");const n=e==="binary",r=n?"int8":"uint8",s=n?Int8Array:Uint8Array,i=t.data,a=new s(i.length/8);for(let o=0;o0?1:0,u=Math.floor(o/8),c=o%8;a[u]|=l<<7-c,n&&c===0&&(a[u]-=128)}return new ee(r,a,[t.dims[0],t.dims[1]/8])}class kb{constructor(e=(r,s)=>r>s,n=1/0){this._heap=[],this._comparator=e,this._maxSize=n}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)if(this.size0&&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(){this._siftUpFrom(this.size-1)}_siftUpFrom(e){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 s=new Tr(this.bosTokenId,0,0,0,0),i=new Tr(this.eosTokenId,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(i.clone()),this.beginNodes[this.len].push(i),this.endNodes[0].push(s)}insert(e,n,r,s){const i=this.nodes.length,a=new Tr(s,i,e,n,r);this.beginNodes[e].push(a),this.endNodes[e+n].push(a),this.nodes.push(a)}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,u=null;for(let c of this.endNodes[n]){const p=c.backtraceScore+o.score;(u===null||p>l)&&(u=c.clone(),l=p)}if(u!==null)o.prev=u,o.backtraceScore=l;else return[]}++n}const r=[],i=this.beginNodes[e][0].prev;if(i===null)return[];let a=i.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.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 Tr{constructor(e,n,r,s,i){this.tokenId=e,this.nodeId=n,this.pos=r,this.length=s,this.score=i,this.prev=null,this.backtraceScore=0}clone(){const e=new Tr(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}var z=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",Macro:"Macro",EndMacro:"EndMacro"}),Kf=Object.freeze({set:z.Set,for:z.For,in:z.In,is:z.Is,if:z.If,else:z.Else,endif:z.EndIf,elif:z.ElseIf,endfor:z.EndFor,and:z.And,or:z.Or,not:z.Not,"not in":z.NotIn,macro:z.Macro,endmacro:z.EndMacro,true:z.BooleanLiteral,false:z.BooleanLiteral,True:z.BooleanLiteral,False:z.BooleanLiteral}),Mn=class{constructor(t,e){this.value=t,this.type=e}};function Xf(t){return/\w/.test(t)}function Hi(t){return/[0-9]/.test(t)}var Tb=[["{%",z.OpenStatement],["%}",z.CloseStatement],["{{",z.OpenExpression],["}}",z.CloseExpression],["(",z.OpenParen],[")",z.CloseParen],["{",z.OpenCurlyBracket],["}",z.CloseCurlyBracket],["[",z.OpenSquareBracket],["]",z.CloseSquareBracket],[",",z.Comma],[".",z.Dot],[":",z.Colon],["|",z.Pipe],["<=",z.ComparisonBinaryOperator],[">=",z.ComparisonBinaryOperator],["==",z.ComparisonBinaryOperator],["!=",z.ComparisonBinaryOperator],["<",z.ComparisonBinaryOperator],[">",z.ComparisonBinaryOperator],["+",z.AdditiveBinaryOperator],["-",z.AdditiveBinaryOperator],["*",z.MultiplicativeBinaryOperator],["/",z.MultiplicativeBinaryOperator],["%",z.MultiplicativeBinaryOperator],["=",z.Equals]],Mb=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function Cb(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 Ab(t,e={}){var a,o,l;const n=[],r=Cb(t,e);let s=0;const i=u=>{let c="";for(;u(r[s]);){if(r[s]==="\\"){if(++s,s>=r.length)throw new SyntaxError("Unexpected end of input");const p=r[s++],d=Mb.get(p);if(d===void 0)throw new SyntaxError(`Unexpected escaped character: ${p}`);c+=d;continue}if(c+=r[s++],s>=r.length)throw new SyntaxError("Unexpected end of input")}return c};e:for(;s0){n.push(new Mn(p,z.Text));continue}}i(p=>/\s/.test(p));const c=r[s];if(c==="-"||c==="+"){const p=(o=n.at(-1))==null?void 0:o.type;if(p===z.Text||p===void 0)throw new SyntaxError(`Unexpected character: ${c}`);switch(p){case z.Identifier:case z.NumericLiteral:case z.BooleanLiteral:case z.StringLiteral:case z.CloseParen:case z.CloseSquareBracket:break;default:{++s;const d=i(Hi);n.push(new Mn(`${c}${d}`,d.length>0?z.NumericLiteral:z.UnaryOperator));continue}}}for(const[p,d]of Tb)if(r.slice(s,s+p.length)===p){n.push(new Mn(p,d)),s+=p.length;continue e}if(c==="'"||c==='"'){++s;const p=i(d=>d!==c);n.push(new Mn(p,z.StringLiteral)),++s;continue}if(Hi(c)){const p=i(Hi);n.push(new Mn(p,z.NumericLiteral));continue}if(Xf(c)){const p=i(Xf),d=Object.hasOwn(Kf,p)?Kf[p]:z.Identifier;d===z.In&&((l=n.at(-1))==null?void 0:l.type)===z.Not?(n.pop(),n.push(new Mn("not in",z.NotIn))):n.push(new Mn(p,d));continue}throw new SyntaxError(`Unexpected character: ${c}`)}return n}var Zn=class{constructor(){A(this,"type","Statement")}},Ib=class extends Zn{constructor(e){super();A(this,"type","Program");this.body=e}},Qf=class extends Zn{constructor(e,n,r){super();A(this,"type","If");this.test=e,this.body=n,this.alternate=r}},zb=class extends Zn{constructor(e,n,r,s){super();A(this,"type","For");this.loopvar=e,this.iterable=n,this.body=r,this.defaultBlock=s}},Ob=class extends Zn{constructor(e,n){super();A(this,"type","Set");this.assignee=e,this.value=n}},Pb=class extends Zn{constructor(e,n,r){super();A(this,"type","Macro");this.name=e,this.args=n,this.body=r}},zt=class extends Zn{constructor(){super(...arguments);A(this,"type","Expression")}},Bb=class extends zt{constructor(e,n,r){super();A(this,"type","MemberExpression");this.object=e,this.property=n,this.computed=r}},Rb=class extends zt{constructor(e,n){super();A(this,"type","CallExpression");this.callee=e,this.args=n}},Jn=class extends zt{constructor(e){super();A(this,"type","Identifier");this.value=e}},er=class extends zt{constructor(e){super();A(this,"type","Literal");this.value=e}},Fb=class extends er{constructor(){super(...arguments);A(this,"type","NumericLiteral")}},Yf=class extends er{constructor(){super(...arguments);A(this,"type","StringLiteral")}},Zf=class extends er{constructor(){super(...arguments);A(this,"type","BooleanLiteral")}},Db=class extends er{constructor(){super(...arguments);A(this,"type","ArrayLiteral")}},Jf=class extends er{constructor(){super(...arguments);A(this,"type","TupleLiteral")}},Nb=class extends er{constructor(){super(...arguments);A(this,"type","ObjectLiteral")}},Mr=class extends zt{constructor(e,n,r){super();A(this,"type","BinaryExpression");this.operator=e,this.left=n,this.right=r}},Lb=class extends zt{constructor(e,n){super();A(this,"type","FilterExpression");this.operand=e,this.filter=n}},Ub=class extends zt{constructor(e,n){super();A(this,"type","SelectExpression");this.iterable=e,this.test=n}},Vb=class extends zt{constructor(e,n,r){super();A(this,"type","TestExpression");this.operand=e,this.negate=n,this.test=r}},jb=class extends zt{constructor(e,n){super();A(this,"type","UnaryExpression");this.operator=e,this.argument=n}},qb=class extends zt{constructor(e=void 0,n=void 0,r=void 0){super();A(this,"type","SliceExpression");this.start=e,this.stop=n,this.step=r}},Gb=class extends zt{constructor(e,n){super();A(this,"type","KeywordArgumentExpression");this.key=e,this.value=n}};function Wb(t){const e=new Ib([]);let n=0;function r(I,N){const R=t[n++];if(!R||R.type!==I)throw new Error(`Parser Error: ${N}. ${R.type} !== ${I}.`);return R}function s(){switch(t[n].type){case z.Text:return o();case z.OpenStatement:return l();case z.OpenExpression:return u();default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}}function i(...I){return n+I.length<=t.length&&I.some((N,R)=>N!==t[n+R].type)}function a(...I){return n+I.length<=t.length&&I.every((N,R)=>N===t[n+R].type)}function o(){return new Yf(r(z.Text,"Expected text token").value)}function l(){r(z.OpenStatement,"Expected opening statement token");let I;switch(t[n].type){case z.Set:++n,I=c(),r(z.CloseStatement,"Expected closing statement token");break;case z.If:++n,I=p(),r(z.OpenStatement,"Expected {% token"),r(z.EndIf,"Expected endif token"),r(z.CloseStatement,"Expected %} token");break;case z.Macro:++n,I=d(),r(z.OpenStatement,"Expected {% token"),r(z.EndMacro,"Expected endmacro token"),r(z.CloseStatement,"Expected %} token");break;case z.For:++n,I=m(),r(z.OpenStatement,"Expected {% token"),r(z.EndFor,"Expected endfor token"),r(z.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type}`)}return I}function u(){r(z.OpenExpression,"Expected opening expression token");const I=g();return r(z.CloseExpression,"Expected closing expression token"),I}function c(){const I=g();if(a(z.Equals)){++n;const N=c();return new Ob(I,N)}return I}function p(){var Y,te,O,q,ie,ge,xe,Ee;const I=g();r(z.CloseStatement,"Expected closing statement token");const N=[],R=[];for(;!(((Y=t[n])==null?void 0:Y.type)===z.OpenStatement&&(((te=t[n+1])==null?void 0:te.type)===z.ElseIf||((O=t[n+1])==null?void 0:O.type)===z.Else||((q=t[n+1])==null?void 0:q.type)===z.EndIf));)N.push(s());if(((ie=t[n])==null?void 0:ie.type)===z.OpenStatement&&((ge=t[n+1])==null?void 0:ge.type)!==z.EndIf)if(++n,a(z.ElseIf))r(z.ElseIf,"Expected elseif token"),R.push(p());else for(r(z.Else,"Expected else token"),r(z.CloseStatement,"Expected closing statement token");!(((xe=t[n])==null?void 0:xe.type)===z.OpenStatement&&((Ee=t[n+1])==null?void 0:Ee.type)===z.EndIf);)R.push(s());return new Qf(I,N,R)}function d(){const I=ne();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const N=B();r(z.CloseStatement,"Expected closing statement token");const R=[];for(;i(z.OpenStatement,z.EndMacro);)R.push(s());return new Pb(I,N,R)}function f(I=!1){const N=I?ne:g,R=[N()],Y=a(z.Comma);for(;Y&&(++n,R.push(N()),!!a(z.Comma)););return Y?new Jf(R):R[0]}function m(){const I=f(!0);if(!(I instanceof Jn||I instanceof Jf))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${I.type} instead`);r(z.In,"Expected `in` keyword following loop variable");const N=g();r(z.CloseStatement,"Expected closing statement token");const R=[];for(;i(z.OpenStatement,z.EndFor)&&i(z.OpenStatement,z.Else);)R.push(s());const Y=[];if(a(z.OpenStatement,z.Else))for(++n,++n,r(z.CloseStatement,"Expected closing statement token");i(z.OpenStatement,z.EndFor);)Y.push(s());return new zb(I,N,R,Y)}function g(){return w()}function w(){const I=v();if(a(z.If)){++n;const N=v();if(a(z.Else)){++n;const R=v();return new Qf(N,[I],[R])}else return new Ub(I,N)}return I}function v(){let I=y();for(;a(z.Or);){const N=t[n];++n;const R=y();I=new Mr(N,I,R)}return I}function y(){let I=$();for(;a(z.And);){const N=t[n];++n;const R=$();I=new Mr(N,I,R)}return I}function $(){let I;for(;a(z.Not);){const N=t[n];++n;const R=$();I=new jb(N,R)}return I??k()}function k(){let I=E();for(;a(z.ComparisonBinaryOperator)||a(z.In)||a(z.NotIn);){const N=t[n];++n;const R=E();I=new Mr(N,I,R)}return I}function E(){let I=X();for(;a(z.AdditiveBinaryOperator);){const N=t[n];++n;const R=X();I=new Mr(N,I,R)}return I}function T(){const I=K();return a(z.OpenParen)?C(I):I}function C(I){let N=new Rb(I,B());return a(z.OpenParen)&&(N=C(N)),N}function B(){r(z.OpenParen,"Expected opening parenthesis for arguments list");const I=U();return r(z.CloseParen,"Expected closing parenthesis for arguments list"),I}function U(){const I=[];for(;!a(z.CloseParen);){let N=g();if(a(z.Equals)){if(++n,!(N instanceof Jn))throw new SyntaxError("Expected identifier for keyword argument");const R=g();N=new Gb(N,R)}I.push(N),a(z.Comma)&&++n}return I}function G(){const I=[];let N=!1;for(;!a(z.CloseSquareBracket);)a(z.Colon)?(I.push(void 0),++n,N=!0):(I.push(g()),a(z.Colon)&&(++n,N=!0));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(I.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new qb(...I)}return I[0]}function K(){let I=ne();for(;a(z.Dot)||a(z.OpenSquareBracket);){const N=t[n];++n;let R;const Y=N.type!==z.Dot;if(Y)R=G(),r(z.CloseSquareBracket,"Expected closing square bracket");else if(R=ne(),R.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new Bb(I,R,Y)}return I}function X(){let I=H();for(;a(z.MultiplicativeBinaryOperator);){const N=t[n];++n;const R=H();I=new Mr(N,I,R)}return I}function H(){let I=J();for(;a(z.Is);){++n;const N=a(z.Not);N&&++n;let R=ne();if(R instanceof Zf&&(R=new Jn(R.value.toString())),!(R instanceof Jn))throw new SyntaxError("Expected identifier for the test");I=new Vb(I,N,R)}return I}function J(){let I=T();for(;a(z.Pipe);){++n;let N=ne();if(!(N instanceof Jn))throw new SyntaxError("Expected identifier for the filter");a(z.OpenParen)&&(N=C(N)),I=new Lb(I,N)}return I}function ne(){const I=t[n];switch(I.type){case z.NumericLiteral:return++n,new Fb(Number(I.value));case z.StringLiteral:return++n,new Yf(I.value);case z.BooleanLiteral:return++n,new Zf(I.value.toLowerCase()==="true");case z.Identifier:return++n,new Jn(I.value);case z.OpenParen:{++n;const N=f();if(t[n].type!==z.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,N}case z.OpenSquareBracket:{++n;const N=[];for(;!a(z.CloseSquareBracket);)N.push(g()),a(z.Comma)&&++n;return++n,new Db(N)}case z.OpenCurlyBracket:{++n;const N=new Map;for(;!a(z.CloseCurlyBracket);){const R=g();r(z.Colon,"Expected colon between key and value in object literal");const Y=g();N.set(R,Y),a(z.Comma)&&++n}return++n,new Nb(N)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;n=0?(e=(e??(e=0))<0?Math.max(t.length+e,0):Math.min(e,t.length),n=(n??(n=t.length))<0?Math.max(t.length+n,0):Math.min(n,t.length)):(e=(e??(e=t.length-1))<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),n=(n??(n=-1))<-1?Math.max(t.length+n,-1):Math.min(n,t.length-1));const i=[];for(let a=e;s*ae.toUpperCase())}var Xt=class{constructor(t=void 0){A(this,"type","RuntimeValue");A(this,"value");A(this,"builtins",new Map);this.value=t}__bool__(){return new Ie(!!this.value)}},Se=class extends Xt{constructor(){super(...arguments);A(this,"type","NumericValue")}},me=class extends Xt{constructor(){super(...arguments);A(this,"type","StringValue");A(this,"builtins",new Map([["upper",new Lt(()=>new me(this.value.toUpperCase()))],["lower",new Lt(()=>new me(this.value.toLowerCase()))],["strip",new Lt(()=>new me(this.value.trim()))],["title",new Lt(()=>new me(tm(this.value)))],["length",new Se(this.value.length)]]))}},Ie=class extends Xt{constructor(){super(...arguments);A(this,"type","BooleanValue")}},wt=class extends Xt{constructor(){super(...arguments);A(this,"type","ObjectValue");A(this,"builtins",new Map([["get",new Lt(([e,n])=>{if(!(e instanceof me))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??n??new pn})],["items",new Lt(()=>new ze(Array.from(this.value.entries()).map(([e,n])=>new ze([new me(e),n]))))]]))}__bool__(){return new Ie(this.value.size>0)}},Kb=class extends wt{constructor(){super(...arguments);A(this,"type","KeywordArgumentsValue")}},ze=class extends Xt{constructor(){super(...arguments);A(this,"type","ArrayValue");A(this,"builtins",new Map([["length",new Se(this.value.length)]]))}__bool__(){return new Ie(this.value.length>0)}},Xb=class extends ze{constructor(){super(...arguments);A(this,"type","TupleValue")}},Lt=class extends Xt{constructor(){super(...arguments);A(this,"type","FunctionValue")}},pn=class extends Xt{constructor(){super(...arguments);A(this,"type","NullValue")}},pt=class extends Xt{constructor(){super(...arguments);A(this,"type","UndefinedValue")}},Cr=class{constructor(t){A(this,"variables",new Map([["namespace",new Lt(t=>{if(t.length===0)return new wt(new Map);if(t.length!==1||!(t[0]instanceof wt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]));A(this,"tests",new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Lt],["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],["string",t=>t.type==="StringValue"],["number",t=>t.type==="NumericValue"],["integer",t=>t.type==="NumericValue"&&Number.isInteger(t.value)],["iterable",t=>t instanceof ze||t instanceof me],["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],["eq",(t,e)=>t.value===e.value]]));this.parent=t}set(t,e){return this.declareVariable(t,Is(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 pt}catch{return new pt}}},Qb=class{constructor(t){A(this,"global");this.global=t??new Cr}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 Ie(n.value==r.value);case"!=":return new Ie(n.value!=r.value)}if(n instanceof pt||r instanceof pt)throw new Error("Cannot perform operation on undefined values");if(n instanceof pn||r instanceof pn)throw new Error("Cannot perform operation on null values");if(n instanceof Se&&r instanceof Se)switch(t.operator.value){case"+":return new Se(n.value+r.value);case"-":return new Se(n.value-r.value);case"*":return new Se(n.value*r.value);case"/":return new Se(n.value/r.value);case"%":return new Se(n.value%r.value);case"<":return new Ie(n.value":return new Ie(n.value>r.value);case">=":return new Ie(n.value>=r.value);case"<=":return new Ie(n.value<=r.value)}else if(n instanceof ze&&r instanceof ze)switch(t.operator.value){case"+":return new ze(n.value.concat(r.value))}else if(r instanceof ze){const s=r.value.find(i=>i.value===n.value)!==void 0;switch(t.operator.value){case"in":return new Ie(s);case"not in":return new Ie(!s)}}if(n instanceof me||r instanceof me)switch(t.operator.value){case"+":return new me(n.value.toString()+r.value.toString())}if(n instanceof me&&r instanceof me)switch(t.operator.value){case"in":return new Ie(r.value.includes(n.value));case"not in":return new Ie(!r.value.includes(n.value))}if(n instanceof me&&r instanceof wt)switch(t.operator.value){case"in":return new Ie(r.value.has(n.value));case"not in":return new Ie(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(t,e){const n=[],r=new Map;for(const s of t)if(s.type==="KeywordArgumentExpression"){const i=s;r.set(i.key.value,this.evaluate(i.value,e))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");n.push(this.evaluate(s,e))}return[n,r]}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if(t.filter.type==="Identifier"){const r=t.filter;if(r.value==="tojson")return new me(zs(n));if(n instanceof ze)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 Se(n.value.length);case"reverse":return new ze(n.value.reverse());case"sort":return new ze(n.value.sort((s,i)=>{if(s.type!==i.type)throw new Error(`Cannot compare different types: ${s.type} and ${i.type}`);switch(s.type){case"NumericValue":return s.value-i.value;case"StringValue":return s.value.localeCompare(i.value);default:throw new Error(`Cannot compare type: ${s.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof me)switch(r.value){case"length":return new Se(n.value.length);case"upper":return new me(n.value.toUpperCase());case"lower":return new me(n.value.toLowerCase());case"title":return new me(tm(n.value));case"capitalize":return new me(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new me(n.value.trim());case"indent":return new me(n.value.split(` +`).map((s,i)=>i===0||s.length===0?s:" "+s).join(` +`));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else if(n instanceof Se)switch(r.value){case"abs":return new Se(Math.abs(n.value));default:throw new Error(`Unknown NumericValue filter: ${r.value}`)}else if(n instanceof wt)switch(r.value){case"items":return new ze(Array.from(n.value.entries()).map(([s,i])=>new ze([new me(s),i])));case"length":return new Se(n.value.size);default:throw new Error(`Unknown ObjectValue 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 s=r.callee.value;if(s==="tojson"){const[,i]=this.evaluateArguments(r.args,e),a=i.get("indent")??new pn;if(!(a instanceof Se||a instanceof pn))throw new Error("If set, indent must be a number");return new me(zs(n,a.value))}if(n instanceof ze){switch(s){case"selectattr":{if(n.value.some(c=>!(c instanceof wt)))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,a,o]=r.args.map(c=>this.evaluate(c,e));let l;if(a){const c=e.tests.get(a.value);if(!c)throw new Error(`Unknown test: ${a.value}`);l=c}else l=(...c)=>c[0].__bool__().value;const u=n.value.filter(c=>{const p=c.value.get(i.value);return p?l(p,o):!1});return new ze(u)}case"map":{const[,i]=this.evaluateArguments(r.args,e);if(i.has("attribute")){const a=i.get("attribute");if(!(a instanceof me))throw new Error("attribute must be a string");const o=i.get("default"),l=n.value.map(u=>{if(!(u instanceof wt))throw new Error("items in map must be an object");return u.value.get(a.value)??o??new pt});return new ze(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}else if(n instanceof me){switch(s){case"indent":{const[i,a]=this.evaluateArguments(r.args,e),o=i.at(0)??a.get("width")??new Se(4);if(!(o instanceof Se))throw new Error("width must be a number");const l=i.at(1)??a.get("first")??new Ie(!1),u=i.at(2)??a.get("blank")??new Ie(!1),c=n.value.split(` +`),p=" ".repeat(o.value),d=c.map((f,m)=>!l.value&&m===0||!u.value&&f.length===0?f:p+f);return new me(d.join(` +`))}}throw new Error(`Unknown StringValue filter: ${s}`)}else throw new Error(`Cannot apply filter "${s}" 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 s=r(n);return new Ie(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);switch(t.operator.value){case"not":return new Ie(!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 s=this.evaluate(r,e);s.type!=="NullValue"&&s.type!=="UndefinedValue"&&(n+=s.value)}return new me(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[n,r]=this.evaluateArguments(t.args,e);r.size>0&&n.push(new Kb(r));const s=this.evaluate(t.callee,e);if(s.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof ze||t instanceof me))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof Se||r instanceof pt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof Se||s instanceof pt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof Se||i instanceof pt))throw new Error("Slice step must be numeric or undefined");return t instanceof ze?new ze(em(t.value,r.value,s.value,i.value)):new me(em(Array.from(t.value),r.value,s.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 me(t.property.value);let s;if(n instanceof wt){if(!(r instanceof me))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof ze||n instanceof me)if(r instanceof Se)s=n.value.at(r.value),n instanceof me&&(s=new me(n.value.at(r.value)));else if(r instanceof me)s=n.builtins.get(r.value);else throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof me))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof Xt?s:new pt}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,s=this.evaluate(r.object,e);if(!(s instanceof wt))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");s.value.set(r.property.value,n)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new pn}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 Cr(e);let r,s;if(t.iterable.type==="SelectExpression"){const u=t.iterable;s=this.evaluate(u.iterable,n),r=u.test}else s=this.evaluate(t.iterable,n);if(!(s instanceof ze))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],a=[];for(let u=0;uf.setVariable(t.loopvar.value,p);else if(t.loopvar.type==="TupleLiteral"){const f=t.loopvar;if(p.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${p.type}`);const m=p;if(f.value.length!==m.value.length)throw new Error(`Too ${f.value.length>m.value.length?"few":"many"} items to unpack`);d=g=>{for(let w=0;w0?i[u-1]:new pt],["nextitem",u{var a;const s=new Cr(r);n=n.slice();let i;((a=n.at(-1))==null?void 0:a.type)==="KeywordArgumentsValue"&&(i=n.pop());for(let o=0;othis.evaluate(n,e)));case"TupleLiteral":return new Xb(t.value.map(n=>this.evaluate(n,e)));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const i=this.evaluate(r,e);if(!(i instanceof me))throw new Error(`Object keys must be strings: got ${i.type}`);n.set(i.value,this.evaluate(s,e))}return new wt(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 Is(t){switch(typeof t){case"number":return new Se(t);case"string":return new me(t);case"boolean":return new Ie(t);case"undefined":return new pt;case"object":return t===null?new pn:Array.isArray(t)?new ze(t.map(Is)):new wt(new Map(Object.entries(t).map(([e,n])=>[e,Is(n)])));case"function":return new Lt((e,n)=>{const r=t(...e.map(s=>s.value))??null;return Is(r)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function zs(t,e,n){const r=n??0;switch(t.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(t.value);case"ArrayValue":case"ObjectValue":{const s=e?" ".repeat(e):"",i=` +`+s.repeat(r),a=i+s;if(t.type==="ArrayValue"){const o=t.value.map(l=>zs(l,e,r+1));return e?`[${a}${o.join(`,${a}`)}${i}]`:`[${o.join(", ")}]`}else{const o=Array.from(t.value.entries()).map(([l,u])=>{const c=`"${l}": ${zs(u,e,r+1)}`;return e?`${a}${c}`:c});return e?`{${o.join(",")}${i}}`:`{${o.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var Yb=class{constructor(t){A(this,"parsed");const e=Ab(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Wb(e)}render(t){const e=new Cr;e.set("false",!1),e.set("true",!0),e.set("raise_exception",s=>{throw new Error(s)}),e.set("range",Hb);for(const[s,i]of Object.entries(t))e.set(s,i);return new Qb(e).run(this.parsed).value}};const nm=[["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"]],Os=new Map(nm),Zb=new Map([...nm.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"]]);function rm(t){t=t.toLowerCase();let e=Zb.get(t);if(e===void 0)if(Os.has(t))e=t;else{const r=t.length===2?Os.keys():Os.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(r)}`)}return e}const Ki="https://github.com/xenova/transformers.js/issues/new/choose";async function sm(t,e){const n=await Promise.all([tn(t,"tokenizer.json",!0,e),tn(t,"tokenizer_config.json",!0,e)]);return e.legacy!==null&&(n[1].legacy=e.legacy),n}function Jb(t,e){const n=[];let r=0;for(const s of t.matchAll(e)){const i=s[0];r0&&n.push(i),r=s.index+i.length}return r=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103}function n1(t,e,n){const r=[];let s=0;for(;sthis.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 o1 extends Ar{constructor(e){super(e),this.tokens_to_ids=Xi(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 s=[...r];if(s.length>this.max_input_chars_per_word){n.push(this.unk_token);continue}let i=!1,a=0;const o=[];for(;a0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){u=c;break}--l}if(u===null){i=!0;break}o.push(u),a=l}i?n.push(this.unk_token):n.push(...o)}return n}}class l1 extends Ar{constructor(e,n){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s[s,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=Xo(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new Sb,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const n=e.sentence,r=n.length;let s=0;for(;s{const t=[...Array.from({length:94},(s,i)=>i+33),...Array.from({length:12},(s,i)=>i+161),...Array.from({length:82},(s,i)=>i+174)],e=t.slice();let n=0;for(let s=0;s<256;++s)t.includes(s)||(t.push(s),e.push(256+n),n+=1);const r=e.map(s=>String.fromCharCode(s));return Object.fromEntries(t.map((s,i)=>[s,r[i]]))})(),u1=yy(om);class d1 extends Ar{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=Xi(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.ignore_merges=this.config.ignore_merges??!1,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 s=[];if(r.length>1){const i=new kb((l,u)=>l.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`)):n.push(this.unk_token)}return n}}class c1 extends Ar{constructor(e,n){super(e),this.tokens_to_ids=Xi(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,s]of this.tokens_to_ids)this.vocab[s]=r}encode(e){return e}}class ht extends Ye{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new v1(e);case"Precompiled":return new L1(e);case"Sequence":return new b1(e);case"Replace":return new p1(e);case"NFC":return new h1(e);case"NFKC":return new f1(e);case"NFKD":return new m1(e);case"Strip":return new g1(e);case"StripAccents":return new _1(e);case"Lowercase":return new w1(e);case"Prepend":return new y1(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 p1 extends ht{normalize(e){const n=Ps(this.config.pattern);return n===null?e:e.replaceAll(n,this.config.content)}}class h1 extends ht{normalize(e){return e=e.normalize("NFC"),e}}class f1 extends ht{normalize(e){return e=e.normalize("NFKC"),e}}class m1 extends ht{normalize(e){return e=e.normalize("NFKD"),e}}class g1 extends ht{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 _1 extends ht{normalize(e){return e=im(e),e}}class w1 extends ht{normalize(e){return e=e.toLowerCase(),e}}class y1 extends ht{normalize(e){return e=this.config.prepend+e,e}}class b1 extends ht{constructor(e){super(e),this.normalizers=e.normalizers.map(n=>ht.fromConfig(n))}normalize(e){return this.normalizers.reduce((n,r)=>r.normalize(n),e)}}class v1 extends ht{_tokenize_chinese_chars(e){const n=[];for(let r=0;rthis.pre_tokenize_text(r,n)):this.pre_tokenize_text(e,n)).flat()}_call(e,n){return this.pre_tokenize(e,n)}}class x1 extends yt{constructor(e){super(),this.pattern=new RegExp(`[^\\s${tr}]+|[${tr}]`,"gu")}pre_tokenize_text(e,n){return e.trim().match(this.pattern)||[]}}class $1 extends yt{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=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=om,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(s=>Array.from(this.text_encoder.encode(s),i=>this.byte_encoder[i]).join(""))}}class k1 extends yt{constructor(e){super(),this.config=e,this.pattern=Ps(this.config.pattern,this.config.invert)}pre_tokenize_text(e,n){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:Jb(e,this.pattern)}}class S1 extends yt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${tr}]+|[${tr}]+`,"gu")}pre_tokenize_text(e,n){return e.match(this.pattern)||[]}}class E1 extends yt{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 nr extends Ye{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new T1(e);case"ByteLevel":return new dm(e);case"RobertaProcessing":return new um(e);case"BertProcessing":return new lm(e);case"Sequence":return new M1(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 lm extends nr{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=We([this.cls],e,[this.sep]));let s=new Array(e.length).fill(0);if(n!==null){const i=r&&this instanceof um?[this.sep]:[],a=r?[this.sep]:[];e=We(e,i,n,a),s=We(s,new Array(n.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:s}}}class um extends lm{}class T1 extends nr{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,n=null,{add_special_tokens:r=!0}={}){const s=n===null?this.single:this.pair;let i=[],a=[];for(const o of s)"SpecialToken"in o?r&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(i=We(i,e),a=We(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(i=We(i,n),a=We(a,new Array(n.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}}class dm extends nr{post_process(e,n=null){return n&&(e=We(e,n)),{tokens:e}}}class M1 extends nr{constructor(e){super(e),this.processors=e.processors.map(n=>nr.fromConfig(n))}post_process(e,n=null,r={}){let s;for(const i of this.processors)if(i instanceof dm)e=i.post_process(e).tokens,n&&(n=i.post_process(n).tokens);else{const a=i.post_process(e,n,r);e=a.tokens,s=a.token_type_ids}return{tokens:e,token_type_ids:s}}}class ft extends Ye{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 O1(e);case"Metaspace":return new N1(e);case"ByteLevel":return new P1(e);case"Replace":return new C1(e);case"ByteFallback":return new A1(e);case"Fuse":return new I1(e);case"Strip":return new z1(e);case"Sequence":return new R1(e);case"CTC":return new B1(e);case"BPEDecoder":return new F1(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 C1 extends ft{decode_chain(e){const n=Ps(this.config.pattern);return n===null?e:e.map(r=>r.replaceAll(n,this.config.content))}}class A1 extends ft{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const n=[];let r=[];for(const s of e){let i=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){const a=parseInt(s.slice(3,5),16);isNaN(a)||(i=a)}if(i!==null)r.push(i);else{if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));n.push(a),r=[]}n.push(s)}}if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));n.push(s),r=[]}return n}}class I1 extends ft{decode_chain(e){return[e.join("")]}}class z1 extends ft{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=Qi(n)),n))}}class P1 extends ft{constructor(e){super(e),this.byte_decoder=u1,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 s of e)this.added_tokens.find(i=>i.content===s)!==void 0?(r.length>0&&(n.push(this.convert_tokens_to_string(r)),r=[]),n.push(s)):r.push(s);return r.length>0&&n.push(this.convert_tokens_to_string(r)),n}}class B1 extends ft{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&&(s=Qi(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class R1 extends ft{constructor(e){super(e),this.decoders=e.decoders.map(n=>ft.fromConfig(n))}decode_chain(e){return this.decoders.reduce((n,r)=>r.decode_chain(n),e)}}class F1 extends ft{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 D1 extends ft{decode_chain(e){let n="";for(let r=1;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}}class U1 extends yt{constructor(e){super(),this.tokenizers=e.pretokenizers.map(n=>yt.fromConfig(n))}pre_tokenize_text(e,n){return this.tokenizers.reduce((r,s)=>s.pre_tokenize(r,n),[e])}}class V1 extends yt{constructor(e){super()}pre_tokenize_text(e,n){return e.match(/\w+|[^\w\s]+/g)||[]}}class j1 extends yt{constructor(e){super()}pre_tokenize_text(e,n){return r1(e)}}class q1 extends yt{constructor(e){super(),this.config=e,this.pattern=Ps(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 G1=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function W1(t,e,n,r){for(const s of Object.keys(t)){const i=e-t[s].length,a=n(s),o=new Array(i).fill(a);t[s]=r==="right"?We(t[s],o):We(o,t[s])}}function H1(t,e){for(const n of Object.keys(t))t[n].length=e}class ce extends Ye{constructor(n,r){super();A(this,"return_token_type_ids",!1);A(this,"padding_side","right");this._tokenizer_config=r,this.normalizer=ht.fromConfig(n.normalizer),this.pre_tokenizer=yt.fromConfig(n.pre_tokenizer),this.model=Ar.fromConfig(n.model,r),this.post_processor=nr.fromConfig(n.post_processor),this.decoder=ft.fromConfig(n.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const s of n.added_tokens){const i=new i1(s);this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id))}if(this.additional_special_tokens=r.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.toSorted((s,i)=>i.content.length-s.content.length).map(s=>`${s.lstrip?"\\s*":""}(${Wo(s.content)})${s.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=r.model_max_length,this.remove_space=r.remove_space,this.clean_up_tokenization_spaces=r.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=r.do_lowercase_and_remove_accent??!1,r.padding_side&&(this.padding_side=r.padding_side),this.legacy=!1,this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){const s=Object.create(null);for(const{name:i,template:a}of this.chat_template){if(typeof i!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');s[i]=a}this.chat_template=s}this._compiled_template_cache=new Map}getToken(...n){for(const r of n){const s=this._tokenizer_config[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}static async from_pretrained(n,{progress_callback:r=null,config:s=null,cache_dir:i=null,local_files_only:a=!1,revision:o="main",legacy:l=null}={}){const u=await sm(n,{progress_callback:r,config:s,cache_dir:i,local_files_only:a,revision:o,legacy:l});return new this(...u)}_call(n,{text_pair:r=null,add_special_tokens:s=!0,padding:i=!1,truncation:a=null,max_length:o=null,return_tensor:l=!0,return_token_type_ids:u=null}={}){const c=Array.isArray(n);let p;if(c){if(n.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(n.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");p=n.map((f,m)=>this._encode_plus(f,{text_pair:r[m],add_special_tokens:s,return_token_type_ids:u}))}else p=n.map(f=>this._encode_plus(f,{add_special_tokens:s,return_token_type_ids:u}))}else{if(n==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");p=[this._encode_plus(n,{text_pair:r,add_special_tokens:s,return_token_type_ids:u})]}if(o===null?i==="max_length"?o=this.model_max_length:o=dt(p.map(f=>f.input_ids.length))[0]:a||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),o=Math.min(o,this.model_max_length??1/0),i||a)for(let f=0;fo?a&&H1(p[f],o):i&&W1(p[f],o,m=>m==="input_ids"?this.pad_token_id:0,this.padding_side));const d={};if(l){if(!(i&&a)&&p.some(m=>{var g;for(const w of Object.keys(m))if(m[w].length!==((g=p[0][w])==null?void 0:g.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 f=[p.length,p[0].input_ids.length];for(const m of Object.keys(p[0]))d[m]=new ee("int64",BigInt64Array.from(p.flatMap(g=>g[m]).map(BigInt)),f)}else{for(const f of Object.keys(p[0]))d[f]=p.map(m=>m[f]);if(!c)for(const f of Object.keys(d))d[f]=d[f][0]}return d}_encode_text(n){return n===null?null:(this.added_tokens_regex?n.split(this.added_tokens_regex).filter(i=>i):[n]).map((i,a)=>{if(this.added_tokens.find(l=>l.content===i)!==void 0)return i;{if(this.remove_space===!0&&(i=i.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(i=e1(i)),this.normalizer!==null&&(i=this.normalizer(i)),i.length===0)return[];const l=this.pre_tokenizer!==null?this.pre_tokenizer(i,{section_index:a}):[i];return this.model(l)}}).flat()}_encode_plus(n,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:i=null}={}){const{tokens:a,token_type_ids:o}=this._tokenize_helper(n,{pair:r,add_special_tokens:s}),l=this.model.convert_tokens_to_ids(a),u={input_ids:l,attention_mask:new Array(l.length).fill(1)};return(i??this.return_token_type_ids)&&o&&(u.token_type_ids=o),u}_tokenize_helper(n,{pair:r=null,add_special_tokens:s=!1}={}){const i=this._encode_text(n),a=this._encode_text(r);return this.post_processor?this.post_processor(i,a,{add_special_tokens:s}):{tokens:We(i??[],a??[])}}tokenize(n,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenize_helper(n,{pair:r,add_special_tokens:s}).tokens}encode(n,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:i=null}={}){return this._encode_plus(n,{text_pair:r,add_special_tokens:s,return_token_type_ids:i}).input_ids}batch_decode(n,r={}){return n instanceof ee&&(n=n.tolist()),n.map(s=>this.decode(s,r))}decode(n,r={}){if(n instanceof ee&&(n=am(n)),!Array.isArray(n)||n.length===0||!by(n[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(n,r)}decode_single(n,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){let i=this.model.convert_ids_to_tokens(n);r&&(i=i.filter(o=>!this.special_tokens.includes(o)));let a=this.decoder?this.decoder(i):i.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(a=a.replaceAll(this.decoder.end_of_word_suffix," "),r&&(a=a.trim())),(s??this.clean_up_tokenization_spaces)&&(a=Qi(a)),a}apply_chat_template(n,{tools:r=null,documents:s=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:l=!1,truncation:u=!1,max_length:c=null,return_tensor:p=!0,return_dict:d=!1,tokenizer_kwargs:f={},...m}={}){if(this.chat_template&&typeof this.chat_template=="object"){const y=this.chat_template;if(i!==null&&Object.hasOwn(y,i))i=y[i];else if(i===null)if(r!==null&&"tool_use"in y)i=y.tool_use;else if("default"in y)i=y.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(y).sort()}.`)}else if(this.chat_template)i=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");if(typeof i!="string")throw Error(`chat_template must be a string, but got ${typeof i}`);let g=this._compiled_template_cache.get(i);g===void 0&&(g=new Yb(i),this._compiled_template_cache.set(i,g));const w=Object.create(null);for(const y of G1){const $=this.getToken(y);$&&(w[y]=$)}const v=g.render({messages:n,add_generation_prompt:a,tools:r,documents:s,...w,...m});if(o){const y=this._call(v,{add_special_tokens:!1,padding:l,truncation:u,max_length:c,return_tensor:p,...f});return d?y:y.input_ids}return v}}class K1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class X1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class Q1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class Y1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class Z1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class J1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class ev extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class tv extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class nv extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class rv extends ce{}class sv extends ce{}class av extends ce{constructor(n,r){super(n,r);A(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class iv extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class ov extends ce{}class lv extends ce{}class uv extends ce{}class pm extends ce{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 Yi(this,e,n,r)}}class dv extends pm{}class cv extends ce{}class pv extends ce{constructor(e,n){var i,a;const r=".,!?…。,、।۔،",s=(a=(i=e.pre_tokenizer)==null?void 0:i.pretokenizers[0])==null?void 0:a.pattern;s&&s.Regex===` ?[^(\\s|[${r}])]+`&&(s.Regex=` ?[^\\s${r}]+`),super(e,n)}}const Bs="▁";class hv extends ce{constructor(n,r){super(n,r);A(this,"padding_side","left");this.legacy=r.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new cm({replacement:Bs,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(n){if(n===null)return null;if(this.legacy||n.length===0)return super._encode_text(n);let r=super._encode_text(Bs+n.replaceAll(Bs," "));return r.length>1&&r[0]===Bs&&this.special_tokens.includes(r[1])&&(r=r.slice(1)),r}}class fv extends ce{}class mv extends ce{}class gv extends ce{}class _v extends ce{}class wv extends ce{}class yv extends ce{}class bv extends ce{}class vv extends ce{}class xv extends ce{}function Yi(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 s=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(s!==void 0){if(!t.language_codes.includes(s))throw new Error(`Source language code "${s}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(const a of t.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(s);break}}return r.forced_bos_token_id=t.model.convert_tokens_to_ids([t.lang_to_token(i)])[0],t._call(e,n)}class $v extends ce{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 Yi(this,e,n,r)}}class kv extends ce{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 Yi(this,e,n,r)}}class Sv extends ce{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(e,{return_timestamps:n=!1,return_language:r=!1,time_precision:s=null,force_full_sequences:i=!0}={}){if(s===null)throw Error("Must specify time_precision");let a=null;const o=n==="word";function l(){return{language:a,timestamp:[null,null],text:""}}const u=[];let c=l(),p=0;const d=this.timestamp_begin;let f=[],m=[],g=!1,w=null;const v=new Set(this.all_special_ids);for(const k of e){const E=k.tokens,T=o?k.token_timestamps:null;let C=null,B=d;if("stride"in k){const[K,X,H]=k.stride;if(p-=X,w=K-H,X&&(B=X/s+d),H)for(let J=E.length-1;J>=0;--J){const ne=Number(E[J]);if(ne>=d){if(C!==null&&(ne-d)*s=d){const H=(X-d)*s+p,J=ur(H,2);if(C!==null&&X>=C)g=!0;else if(g||f.length>0&&X0?(f.push(U),o&&m.push(G)):f.every(K=>K.length===0)&&(c=l(),f=[],U=[],m=[],G=[])}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[k,E]=this.findLongestCommonSequence(f,m),T=this.decode(k);c.text=T,o&&(c.words=this.collateWordTimestamps(k,E,a)),u.push(c)}let y=Object.create(null);const $=u.map(k=>k.text).join("");if(n||r){for(let k=0;k0;let o=a?[]:null,l=a?n[0]:null;for(let u=1;uJ===G[ne]&&l[E+ne]<=n[u][B+ne]).length:K=C.filter((J,ne)=>J===G[ne]).length;const X=k/1e4,H=K/k+X;K>1&&H>p&&(p=H,d=[E,T,B,U])}const[m,g,w,v]=d,y=Math.floor((g+m)/2),$=Math.floor((v+w)/2);i.push(...r.slice(0,y)),r=c.slice($),s=r.length,a&&(o.push(...l.slice(0,y)),l=n[u].slice($))}return i.push(...r),a?(o.push(...l),[i,o]):[i,[]]}collateWordTimestamps(e,n,r){const[s,i,a]=this.combineTokensIntoWords(e,r),o=[];for(let l=0;l=s){const o=((a-s)*r).toFixed(2);i.push(`<|${o}|>`),i.push([])}else i[i.length-1].push(a);return i=i.map(a=>typeof a=="string"?a:super.decode(a,n)),i.join("")}splitTokensOnUnicode(e){const n=this.decode(e,{decode_with_timestamps:!0}),r="�",s=[],i=[],a=[];let o=[],l=[],u=0;for(let c=0;c=this.model.tokens_to_ids.get("<|endoftext|>"),m=c.startsWith(" "),g=c.trim(),w=l.test(g);if(f||m||w||i.length===0)i.push(c),a.push(p),o.push(d);else{const v=i.length-1;i[v]+=c,a[v].push(...p),o[v].push(...d)}}return[i,a,o]}mergePunctuations(e,n,r,s,i){const a=structuredClone(e),o=structuredClone(n),l=structuredClone(r);let u=a.length-2,c=a.length-1;for(;u>=0;)a[u].startsWith(" ")&&s.includes(a[u].trim())?(a[c]=a[u]+a[c],o[c]=We(o[u],o[c]),l[c]=We(l[u],l[c]),a[u]="",o[u]=[],l[u]=[]):c=u,--u;for(u=0,c=1;cp),o.filter(p=>p.length>0),l.filter(p=>p.length>0)]}get_decoder_prompt_ids({language:e=null,task:n=null,no_timestamps:r=!0}={}){const s=[];if(e){const i=rm(e),a=this.model.tokens_to_ids.get(`<|${i}|>`);if(a===void 0)throw new Error(`Unable to find language "${i}" in model vocabulary. Please report this issue at ${Ki}.`);s.push(a)}else s.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 ${Ki}.`);s.push(i)}else s.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 ${Ki}.`);s.push(i)}return s.map((i,a)=>[a+1,i]).filter(i=>i[1]!==null)}}class Ev extends ce{}class Tv extends ce{}class Mv extends ce{}class Cv extends ce{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[s,i]=r;return this.supported_language_codes.includes(s)||console.warn(`Unsupported language code "${s}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),We([s],super._encode_text(i))}}}class Av extends ce{}class Iv extends ce{}class zv extends ce{}class Ov extends ce{}class Pv extends ce{}class Bv extends ce{constructor(e,n){super(e,n),this.decoder=new D1({})}}class Rv extends ce{}class qe{static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:i=!1,revision:a="main",legacy:o=null}={}){var d;const[l,u]=await sm(e,{progress_callback:n,config:r,cache_dir:s,local_files_only:i,revision:a,legacy:o}),c=((d=u.tokenizer_class)==null?void 0:d.replace(/Fast$/,""))??"PreTrainedTokenizer";let p=this.TOKENIZER_CLASS_MAPPING[c];return p||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=ce),new p(l,u)}}A(qe,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:ov,DistilBertTokenizer:rv,CamembertTokenizer:sv,DebertaTokenizer:Z1,DebertaV2Tokenizer:J1,BertTokenizer:K1,HerbertTokenizer:ev,ConvBertTokenizer:tv,RoFormerTokenizer:nv,XLMTokenizer:av,ElectraTokenizer:iv,MobileBertTokenizer:Q1,SqueezeBertTokenizer:Y1,AlbertTokenizer:X1,GPT2Tokenizer:lv,BartTokenizer:uv,MBartTokenizer:pm,MBart50Tokenizer:dv,RobertaTokenizer:cv,WhisperTokenizer:Sv,CodeGenTokenizer:Ev,CLIPTokenizer:Tv,SiglipTokenizer:Mv,MarianTokenizer:Cv,BloomTokenizer:pv,NllbTokenizer:$v,M2M100Tokenizer:kv,LlamaTokenizer:hv,CodeLlamaTokenizer:fv,XLMRobertaTokenizer:mv,MPNetTokenizer:gv,FalconTokenizer:_v,GPTNeoXTokenizer:wv,EsmTokenizer:yv,Wav2Vec2CTCTokenizer:Av,BlenderbotTokenizer:Iv,BlenderbotSmallTokenizer:zv,SpeechT5Tokenizer:Ov,NougatTokenizer:Pv,VitsTokenizer:Bv,Qwen2Tokenizer:bv,GemmaTokenizer:vv,Grok1Tokenizer:xv,CohereTokenizer:Rv,PreTrainedTokenizer:ce});async function Fv(t,e){return await tn(t,"config.json",!0,e)}function Ir(t){const e={};let n={};switch(t.model_type){case"llava":case"paligemma":case"florence2":n=Ir(t.text_config);break;case"moondream1":n=Ir(t.phi_config);break;case"musicgen":n=Ir(t.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":e.num_heads="num_attention_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size",e.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="head_dim";break;case"openelm":e.num_heads="num_kv_heads",e.num_layers="num_transformer_layers",e.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":e.num_heads="num_heads",e.num_layers="num_layers",e.hidden_size="hidden_size";break;case"bloom":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="hidden_size";break;case"mpt":e.num_heads="n_heads",e.num_layers="n_layers",e.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":e.num_decoder_layers="num_decoder_layers",e.num_decoder_heads="num_heads",e.decoder_dim_kv="d_kv",e.num_encoder_layers="num_layers",e.num_encoder_heads="num_heads",e.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="d_model",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="d_model";break;case"speecht5":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="hidden_size",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="hidden_size";break;case"trocr":e.num_encoder_layers=e.num_decoder_layers="decoder_layers",e.num_encoder_heads=e.num_decoder_heads="decoder_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="d_model";break;case"musicgen_decoder":e.num_encoder_layers=e.num_decoder_layers="num_hidden_layers",e.num_encoder_heads=e.num_decoder_heads="num_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const s=Ir(t.decoder),i="num_decoder_layers"in s,a=Ht(t,["model_type","is_encoder_decoder"]);return i?(a.num_decoder_layers=s.num_decoder_layers,a.num_decoder_heads=s.num_decoder_heads,a.decoder_hidden_size=s.decoder_hidden_size,a.num_encoder_layers=s.num_encoder_layers,a.num_encoder_heads=s.num_encoder_heads,a.encoder_hidden_size=s.encoder_hidden_size):(a.num_layers=s.num_layers,a.num_heads=s.num_heads,a.hidden_size=s.hidden_size),a}const r={...n,...Ht(t,["model_type","multi_query","is_encoder_decoder"])};for(const s in e)r[s]=t[e[s]];return r}function hm(t,{prefix:e="past_key_values"}={}){const n={},r=t.normalized_config,s=1;if(r.is_encoder_decoder&&"num_encoder_heads"in r&&"num_decoder_heads"in r){const i=r.encoder_dim_kv??r.encoder_hidden_size/r.num_encoder_heads,a=r.decoder_dim_kv??r.decoder_hidden_size/r.num_decoder_heads,o=[s,r.num_encoder_heads,0,i],l=[s,r.num_decoder_heads,0,a];for(let u=0;u=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?s.subarray(this.timestamp_begin).fill(-1/0):s.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const p=this.timestamp_begin+this.max_initial_timestamp_index;s.subarray(p+1).fill(-1/0)}const l=Cy(s),u=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((p,d)=>p+d)),c=dt(l.subarray(0,this.timestamp_begin))[0];u>c&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return n}}class qv extends Ut{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const n=e.length,r=[];for(let i=0;i1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,n){if(n.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${n.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,s=n.slice([0,r],null),i=n.slice([r,n.dims[0]],null);for(let a=0;a1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(r)||r<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${r}`);this.top_p=e,this.filter_value=n,this.min_tokens_to_keep=r}}class Zv extends Zi{constructor(e,{filter_value:n=-1/0,min_tokens_to_keep:r=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,r),this.filter_value=n}}class _m{constructor(e){A(this,"max_length",20);A(this,"max_new_tokens",null);A(this,"min_length",0);A(this,"min_new_tokens",null);A(this,"early_stopping",!1);A(this,"max_time",null);A(this,"do_sample",!1);A(this,"num_beams",1);A(this,"num_beam_groups",1);A(this,"penalty_alpha",null);A(this,"use_cache",!0);A(this,"temperature",1);A(this,"top_k",50);A(this,"top_p",1);A(this,"typical_p",1);A(this,"epsilon_cutoff",0);A(this,"eta_cutoff",0);A(this,"diversity_penalty",0);A(this,"repetition_penalty",1);A(this,"encoder_repetition_penalty",1);A(this,"length_penalty",1);A(this,"no_repeat_ngram_size",0);A(this,"bad_words_ids",null);A(this,"force_words_ids",null);A(this,"renormalize_logits",!1);A(this,"constraints",null);A(this,"forced_bos_token_id",null);A(this,"forced_eos_token_id",null);A(this,"remove_invalid_values",!1);A(this,"exponential_decay_length_penalty",null);A(this,"suppress_tokens",null);A(this,"begin_suppress_tokens",null);A(this,"forced_decoder_ids",null);A(this,"guidance_scale",null);A(this,"num_return_sequences",1);A(this,"output_attentions",!1);A(this,"output_hidden_states",!1);A(this,"output_scores",!1);A(this,"return_dict_in_generate",!1);A(this,"pad_token_id",null);A(this,"bos_token_id",null);A(this,"eos_token_id",null);A(this,"encoder_no_repeat_ngram_size",0);A(this,"decoder_start_token_id",null);A(this,"generation_kwargs",{});Object.assign(this,Ht(e,Object.getOwnPropertyNames(this)))}}class Ji extends Ye{_call(e,n){throw Error("StoppingCriteria needs to be subclassed")}}class eo extends Ye{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof eo?e=e.criteria:e instanceof Ji&&(e=[e]),this.criteria.push(...e)}_call(e,n){const r=new Array(e.length).fill(!1);for(const s of this.criteria){const i=s(e,n);for(let a=0;an.length>=this.max_length)}}class ex extends Ji{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,n){return e.map(r=>{const s=r.at(-1);return this.eos_token_id.some(i=>s==i)})}}class Ds extends Ye{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,n){let r=e.dims.at(-1),s=e.data;if(n===-1)s=s.slice(-r);else{let i=n*r;s=s.slice(i,i+r)}return s}randomSelect(e){let n=0;for(let s=0;s1)return new rx(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 tx(e)}}class tx extends Ds{async sample(e){const n=dt(e.data)[1];return[[BigInt(n),0]]}}class nx extends Ds{async sample(e){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const[r,s]=await Qn(e,n),i=He(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(i);return[s.data[a],Math.log(i[a])]})}}class rx extends Ds{async sample(e){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const[r,s]=await Qn(e,n),i=He(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[s.data[o],Math.log(i[o])])}}class sx extends _m{constructor(){super(...arguments);A(this,"return_timestamps",null);A(this,"return_token_timestamps",null);A(this,"num_frames",null);A(this,"alignment_heads",null);A(this,"task",null);A(this,"language",null);A(this,"no_timestamps_token_id",null);A(this,"prompt_ids",null);A(this,"is_multilingual",null);A(this,"lang_to_id",null);A(this,"task_to_id",null);A(this,"max_initial_timestamp_index",1)}}const de={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},Ns=new Map,wm=new Map,zr=new Map;async function ax(t,e,n){let r=n.device;r&&typeof r!="string"&&(r.hasOwnProperty(e)?r=r[e]:(console.warn(`device not specified for "${e}". Using the default device.`),r=null));const s=r??(bn.IS_NODE_ENV?"cpu":"wasm"),i=pb(s);let a=n.dtype;typeof a!="string"&&(a&&a.hasOwnProperty(e)?a=a[e]:(a=Lv[s]??bt.fp32,console.warn(`dtype not specified for "${e}". Using the default dtype (${a}) for this device (${s}).`)));const o=a;if(mm.hasOwnProperty(o)){if(o===bt.fp16&&s==="webgpu"&&!await Nv())throw new Error(`The device (${s}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${o}. Should be one of: ${Object.keys(bt).join(", ")}`);const l=mm[o],u=`${n.subfolder??""}/${e}${l}.onnx`,c={...n.session_options};c.executionProviders??(c.executionProviders=i);const p=ts(t,u,!0,n);let d=[];if(n.use_external_data_format&&(n.use_external_data_format===!0||typeof n.use_external_data_format=="object"&&n.use_external_data_format.hasOwnProperty(e)&&n.use_external_data_format[e]===!0)){if(bn.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const m=`${e}${l}.onnx_data`,g=`${n.subfolder??""}/${m}`;d.push(new Promise(async(w,v)=>{const y=await ts(t,g,!0,n);w({path:m,data:y})}))}else c.externalData!==void 0&&(d=c.externalData.map(async m=>{if(typeof m.data=="string"){const g=await ts(t,m.data,!0,n);return{...m,data:g}}return m}));if(d.length>0&&(c.externalData=await Promise.all(d)),s==="webgpu"){const m=hm(n.config,{prefix:"present"});if(Object.keys(m).length>0&&!Vf()){const g={};for(const w in m)g[w]="gpu-buffer";c.preferredOutputLocation=g}}return{buffer:await p,session_options:c}}async function Cn(t,e,n){return Object.fromEntries(await Promise.all(Object.keys(e).map(async r=>{const{buffer:s,session_options:i}=await ax(t,e[r],n),a=await Lf(s,i);return[r,a]})))}function ix(t,e){const n=Object.create(null),r=[];for(const a of t.inputNames){const o=e[a];if(!(o instanceof ee)){r.push(a);continue}n[a]=Vf()?o.clone():o}if(r.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const s=Object.keys(e).length,i=t.inputNames.length;if(s>i){let a=Object.keys(e).filter(o=>!t.inputNames.includes(o));console.warn(`WARNING: Too many inputs were provided (${s} > ${i}). The following inputs will be ignored: "${a.join(", ")}".`)}return n}async function hn(t,e){const n=ix(t,e);try{const r=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,a.ort_tensor]));let s=await t.run(r);return s=ym(s),s}catch(r){throw console.error(`An error occurred during model execution: "${r}".`),console.error("Inputs given to model:",n),r}}function ym(t){for(let e in t)Uf(t[e])?t[e]=new ee(t[e]):typeof t[e]=="object"&&ym(t[e]);return t}function to(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 bm(t){return new ee("bool",[t],[1])}async function vm(t,e){let{encoder_outputs:n,input_ids:r,decoder_input_ids:s,...i}=e;if(!n){const o=Ht(e,t.sessions.model.inputNames);n=(await rr(t,o)).last_hidden_state}return i.input_ids=s,i.encoder_hidden_states=n,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=e.attention_mask),await Ls(t,i,!0)}async function rr(t,e){const n=t.sessions.model,r=Ht(e,n.inputNames);if(n.inputNames.includes("inputs_embeds")&&!r.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}return n.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new ee("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await hn(n,r)}async function Ls(t,e,n=!1){const r=t.sessions[n?"decoder_model_merged":"model"],{past_key_values:s,...i}=e;r.inputNames.includes("use_cache_branch")&&(i.use_cache_branch=bm(!!s)),r.inputNames.includes("position_ids")&&i.attention_mask&&!i.position_ids&&(i.position_ids=lx(i,s)),t.addPastKeyValues(i,s);const a=Ht(i,r.inputNames);return await hn(r,a)}async function ox(t,{input_ids:e=null,attention_mask:n=null,pixel_values:r=null,position_ids:s=null,inputs_embeds:i=null,past_key_values:a=null,generation_config:o=null,logits_processor:l=null,...u}){if(!i){if(i=await t.encode_text({input_ids:e}),r&&e.dims[1]!==1){const p=await t.encode_image({pixel_values:r});({inputs_embeds:i,attention_mask:n}=t._merge_input_ids_with_image_features({image_features:p,inputs_embeds:i,input_ids:e,attention_mask:n}))}else if(a&&r&&e.dims[1]===1){const p=e.dims[1],d=Object.values(a)[0].dims.at(-2);n=ct([Yn([e.dims[0],d]),n.slice(null,[n.dims[1]-p,n.dims[1]])],1)}}return await Ls(t,{inputs_embeds:i,past_key_values:a,attention_mask:n,position_ids:s,generation_config:o,logits_processor:l},!0)}function lx(t,e=null){const{input_ids:n,inputs_embeds:r,attention_mask:s}=t,[i,a]=s.dims,o=new BigInt64Array(s.data.length);for(let u=0;ui.dims[1])){if(so==t.config.image_token_index)){const o=t.config.num_image_tokens;if(!o)throw new Error("`num_image_tokens` is missing in the model configuration.");const l=i.dims[1]-(s-o);n.input_ids=i.slice(null,[-l,null]),n.attention_mask=Yn([1,s+l])}}}return n}function $m(t,e,n,r){return n.past_key_values&&(e=e.map(s=>[s.at(-1)])),{...n,decoder_input_ids:to(e)}}function ux(t,...e){return t.config.is_encoder_decoder?$m(t,...e):xm(t,...e)}class j extends Ye{constructor(n,r){super();A(this,"main_input_name","input_ids");A(this,"forward_params",["input_ids","attention_mask"]);this.config=n,this.sessions=r;const s=zr.get(this.constructor),i=Ns.get(s);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,i){case de.DecoderOnly:this.can_generate=!0,this._forward=Ls,this._prepare_inputs_for_generation=xm;break;case de.Seq2Seq:case de.Vision2Seq:case de.Musicgen:this.can_generate=!0,this._forward=vm,this._prepare_inputs_for_generation=$m;break;case de.EncoderDecoder:this._forward=vm;break;case de.ImageTextToText:this.can_generate=!0,this._forward=ox,this._prepare_inputs_for_generation=ux;break;default:this._forward=rr;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var r;const n=[];for(const s of Object.values(this.sessions))(r=s==null?void 0:s.handler)!=null&&r.dispose&&n.push(s.handler.dispose());return await Promise.all(n)}static async from_pretrained(n,{progress_callback:r=null,config:s=null,cache_dir:i=null,local_files_only:a=!1,revision:o="main",model_file_name:l=null,subfolder:u="onnx",device:c=null,dtype:p=null,use_external_data_format:d=null,session_options:f={}}={}){let m={progress_callback:r,config:s,cache_dir:i,local_files_only:a,revision:o,model_file_name:l,subfolder:u,device:c,dtype:p,use_external_data_format:d,session_options:f};const g=zr.get(this),w=Ns.get(g);s=m.config=await fm.from_pretrained(n,m);let v;if(w===de.DecoderOnly)v=await Promise.all([Cn(n,{model:m.model_file_name??"model"},m),tn(n,"generation_config.json",!1,m)]);else if(w===de.Seq2Seq||w===de.Vision2Seq)v=await Promise.all([Cn(n,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m),tn(n,"generation_config.json",!1,m)]);else if(w===de.MaskGeneration)v=await Promise.all([Cn(n,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},m)]);else if(w===de.EncoderDecoder)v=await Promise.all([Cn(n,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m)]);else if(w===de.ImageTextToText){const y={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(y.model="encoder_model"),v=await Promise.all([Cn(n,y,m),tn(n,"generation_config.json",!1,m)])}else w===de.Musicgen?v=await Promise.all([Cn(n,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},m),tn(n,"generation_config.json",!1,m)]):(w!==de.EncoderOnly&&console.warn(`Model type for '${g??(s==null?void 0:s.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),v=await Promise.all([Cn(n,{model:m.model_file_name??"model"},m)]));return new this(s,...v)}async _call(n){return await this.forward(n)}async forward(n){return await this._forward(this,n)}_get_logits_warper(n){const r=new Fs;return n.temperature!==null&&n.temperature!==1&&r.push(new Qv(n.temperature)),n.top_k!==null&&n.top_k!==0&&r.push(new Zv(n.top_k)),n.top_p!==null&&n.top_p<1&&r.push(new Yv(n.top_p)),r}_get_logits_processor(n,r,s=null){const i=new Fs;if(n.repetition_penalty!==null&&n.repetition_penalty!==1&&i.push(new Gv(n.repetition_penalty)),n.no_repeat_ngram_size!==null&&n.no_repeat_ngram_size>0&&i.push(new qv(n.no_repeat_ngram_size)),n.bad_words_ids!==null&&i.push(new Kv(n.bad_words_ids,n.eos_token_id)),n.min_length!==null&&n.eos_token_id!==null&&n.min_length>0&&i.push(new Wv(n.min_length,n.eos_token_id)),n.min_new_tokens!==null&&n.eos_token_id!==null&&n.min_new_tokens>0&&i.push(new Hv(r,n.min_new_tokens,n.eos_token_id)),n.forced_bos_token_id!==null&&i.push(new Uv(n.forced_bos_token_id)),n.forced_eos_token_id!==null&&i.push(new Vv(n.max_length,n.forced_eos_token_id)),n.begin_suppress_tokens!==null){const a=r>1||n.forced_bos_token_id===null?r:r+1;i.push(new gm(n.begin_suppress_tokens,a))}return n.guidance_scale!==null&&n.guidance_scale>1&&i.push(new Xv(n.guidance_scale)),s!==null&&i.extend(s),i}_prepare_generation_config(n,r,s=_m){const i={...this.config};for(const o of["decoder","generator","text_config"])o in i&&Object.assign(i,i[o]);const a=new s(i);return"generation_config"in this&&Object.assign(a,this.generation_config),n&&Object.assign(a,n),r&&Object.assign(a,Ht(r,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(n,r=null){const s=new eo;return n.max_length!==null&&s.push(new Jv(n.max_length,this.config.max_position_embeddings??null)),n.eos_token_id!==null&&s.push(new ex(n.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){const n=[co,po,uo,lo],r=zr.get(this.constructor),s=new Set,i=this.config.model_type;for(const o of n){const l=o.get(i);l&&s.add(l[0])}let a=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(a+=` Please use the following class instead: ${[...s].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...n){return this._prepare_inputs_for_generation(this,...n)}_update_model_kwargs_for_generation({generated_input_ids:n,outputs:r,model_inputs:s,is_encoder_decoder:i}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new ee("int64",n.flat(),[n.length,1]),i||(s.attention_mask=ct([s.attention_mask,Yn([s.attention_mask.dims[0],1])],1)),s.position_ids=null,s}_prepare_model_inputs({inputs:n,bos_token_id:r,model_kwargs:s}){const i=Ht(s,this.forward_params),a=this.main_input_name;if(a in i){if(n)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else i[a]=n;return{inputs_tensor:i[a],model_inputs:i,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:n,model_inputs:r,model_input_name:s,generation_config:i}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:o,pixel_values:l,attention_mask:u,...c}=r,p=await this._prepare_inputs_embeds(r);r={...c,...Ht(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:a}=await rr(this,r);if(i.guidance_scale!==null&&i.guidance_scale>1)a=ct([a,yb(a,0)],0),"attention_mask"in r&&(r.attention_mask=ct([r.attention_mask,xb(r.attention_mask)],0));else if(r.decoder_input_ids){const o=to(r.decoder_input_ids).dims[0];if(o!==a.dims[0]){if(a.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${a.dims[0]}) than the decoder inputs (${o}).`);a=ct(Array.from({length:o},()=>a),0)}}return r.encoder_outputs=a,r}_prepare_decoder_input_ids_for_generation({batch_size:n,model_input_name:r,model_kwargs:s,decoder_start_token_id:i,bos_token_id:a,generation_config:o}){let{decoder_input_ids:l,...u}=s;if(l)Array.isArray(l[0])||(l=Array.from({length:n},()=>l));else if(i??(i=a),this.config.model_type==="musicgen")l=Array.from({length:n*this.config.decoder.num_codebooks},()=>[i]);else if(Array.isArray(i)){if(i.length!==n)throw new Error(`\`decoder_start_token_id\` expcted to have length ${n} but got ${i.length}`);l=i}else l=Array.from({length:n},()=>[i]);return l=to(l),s.decoder_attention_mask=bb(l),{input_ids:l,model_inputs:u}}async generate({inputs:n=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:i=null,streamer:a=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:l,model_inputs:u,model_input_name:c}=this._prepare_model_inputs({inputs:n,model_kwargs:o});const p=this.config.is_encoder_decoder;p&&("encoder_outputs"in u||(u=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:l,model_inputs:u,model_input_name:c,generation_config:r})));let d;p?{input_ids:d,model_inputs:u}=this._prepare_decoder_input_ids_for_generation({batch_size:u[c].dims.at(0),model_input_name:c,model_kwargs:u,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):d=u[c];let f=d.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=f+r.max_new_tokens);const m=this._get_logits_processor(r,f,s),g=this._get_stopping_criteria(r,i),w=u[c].dims.at(0),v=Ds.getSampler(r),y=new Array(w).fill(0),$=d.tolist();a&&a.put($);let k=null,E={};for(;;){u=this.prepare_inputs_for_generation($,u,r);const C=await this.forward(u);if(r.output_attentions&&r.return_dict_in_generate){const X=this.getAttentions(C);for(const H in X)H in E||(E[H]=[]),E[H].push(X[H])}const B=C.logits.slice(null,-1,null),U=m($,B),G=[];for(let X=0;XX)){r.return_dict_in_generate&&(k=this.getPastKeyValues(C,u.past_key_values,!1));break}u=this._update_model_kwargs_for_generation({generated_input_ids:G,outputs:C,model_inputs:u,is_encoder_decoder:p})}a&&a.end();const T=new ee("int64",$.flat(),[$.length,$[0].length]);return r.return_dict_in_generate?{sequences:T,past_key_values:k,...E}:T}getPastKeyValues(n,r,s=!0){const i=Object.create(null);for(const a in n)if(a.startsWith("present")){const o=a.replace("present","past_key_values");if(r&&a.includes("encoder"))i[o]=r[o];else{if(s&&r){const l=r[o];l.location==="gpu-buffer"&&l.dispose()}i[o]=n[a]}}return i}getAttentions(n){const r={};for(const s of["cross_attentions","encoder_attentions","decoder_attentions"])for(const i in n)i.startsWith(s)&&(s in r||(r[s]=[]),r[s].push(n[i]));return r}addPastKeyValues(n,r){if(r)Object.assign(n,r);else{const s=this.custom_config.kv_cache_dtype??"float32",i=s==="float16"?new Uint16Array:[],a=hm(this.config);for(const o in a)n[o]=new ee(s,i,a[o])}}async encode_image({pixel_values:n}){const r=(await hn(this.sessions.vision_encoder,{pixel_values:n})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${r.dims[1]}).`),this.config.num_image_tokens=r.dims[1]),r}async encode_text({input_ids:n}){return(await hn(this.sessions.embed_tokens,{input_ids:n})).inputs_embeds}}class mt{}class Or extends j{}class dx extends Or{}class cx extends Or{async _call(e){return new et(await super._call(e))}}class px extends Or{async _call(e){return new fe(await super._call(e))}}class hx extends Or{async _call(e){return new Xe(await super._call(e))}}class fx extends Or{async _call(e){return new st(await super._call(e))}}class mx extends j{}class gx extends mx{}class Pr extends j{}class _x extends Pr{}class wx extends Pr{async _call(e){return new et(await super._call(e))}}class yx extends Pr{async _call(e){return new fe(await super._call(e))}}class bx extends Pr{async _call(e){return new Xe(await super._call(e))}}class vx extends Pr{async _call(e){return new st(await super._call(e))}}class Br extends j{}class xx extends Br{}class $x extends Br{async _call(e){return new et(await super._call(e))}}class kx extends Br{async _call(e){return new fe(await super._call(e))}}class Sx extends Br{async _call(e){return new Xe(await super._call(e))}}class Ex extends Br{async _call(e){return new st(await super._call(e))}}class Rr extends j{}class Tx extends Rr{}class Mx extends Rr{async _call(e){return new et(await super._call(e))}}class Cx extends Rr{async _call(e){return new fe(await super._call(e))}}class Ax extends Rr{async _call(e){return new Xe(await super._call(e))}}class Ix extends Rr{async _call(e){return new st(await super._call(e))}}class Fr extends j{}class zx extends Fr{}class Ox extends Fr{async _call(e){return new et(await super._call(e))}}class Px extends Fr{async _call(e){return new fe(await super._call(e))}}class Bx extends Fr{async _call(e){return new Xe(await super._call(e))}}class Rx extends Fr{async _call(e){return new st(await super._call(e))}}class Dr extends j{}class Fx extends Dr{}class Dx extends Dr{async _call(e){return new et(await super._call(e))}}class Nx extends Dr{async _call(e){return new fe(await super._call(e))}}class Lx extends Dr{async _call(e){return new Xe(await super._call(e))}}class Ux extends Dr{async _call(e){return new st(await super._call(e))}}class Nr extends j{}class Vx extends Nr{}class jx extends Nr{async _call(e){return new et(await super._call(e))}}class qx extends Nr{async _call(e){return new fe(await super._call(e))}}class Gx extends Nr{async _call(e){return new Xe(await super._call(e))}}class Wx extends Nr{async _call(e){return new st(await super._call(e))}}class Lr extends j{}class Hx extends Lr{}class Kx extends Lr{async _call(e){return new fe(await super._call(e))}}class Xx extends Lr{async _call(e){return new Xe(await super._call(e))}}class Qx extends Lr{async _call(e){return new st(await super._call(e))}}class Yx extends Lr{async _call(e){return new et(await super._call(e))}}class Us extends j{}class Zx extends Us{}class Jx extends Us{async _call(e){return new et(await super._call(e))}}class e2 extends Us{async _call(e){return new fe(await super._call(e))}}class t2 extends Us{async _call(e){return new Xe(await super._call(e))}}class Vs extends j{}class n2 extends Vs{}class r2 extends Vs{async _call(e){return new et(await super._call(e))}}class s2 extends Vs{async _call(e){return new fe(await super._call(e))}}class a2 extends Vs{async _call(e){return new st(await super._call(e))}}class Ur extends j{}class i2 extends Ur{}class o2 extends Ur{async _call(e){return new et(await super._call(e))}}class l2 extends Ur{async _call(e){return new fe(await super._call(e))}}class u2 extends Ur{async _call(e){return new Xe(await super._call(e))}}class d2 extends Ur{async _call(e){return new st(await super._call(e))}}class js extends j{}class c2 extends js{}class p2 extends js{async _call(e){return new et(await super._call(e))}}class h2 extends js{async _call(e){return new fe(await super._call(e))}}class f2 extends js{async _call(e){return new st(await super._call(e))}}class qs extends j{}class m2 extends qs{}class g2 extends qs{async _call(e){return new fe(await super._call(e))}}class _2 extends qs{async _call(e){return new st(await super._call(e))}}class w2 extends qs{async _call(e){return new et(await super._call(e))}}class km extends j{constructor(n,r,s){super(n,r);A(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=s}}class y2 extends km{}class b2 extends km{}class Sm extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class v2 extends Sm{}class x2 extends Sm{}class Em extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class $2 extends Em{}class k2 extends Em{}class no extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class S2 extends no{}class E2 extends no{}class T2 extends no{async _call(e){return new fe(await super._call(e))}}class Gs extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class M2 extends Gs{}class C2 extends Gs{}class A2 extends Gs{async _call(e){return new fe(await super._call(e))}}class I2 extends Gs{}class Tm extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class z2 extends Tm{}class O2 extends Tm{}class Mm extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class P2 extends Mm{}class B2 extends Mm{}class Vr extends j{}class R2 extends Vr{}class F2 extends Vr{async _call(e){return new et(await super._call(e))}}class D2 extends Vr{async _call(e){return new fe(await super._call(e))}}class N2 extends Vr{async _call(e){return new Xe(await super._call(e))}}class L2 extends Vr{async _call(e){return new st(await super._call(e))}}class jr extends j{}class U2 extends jr{}class V2 extends jr{async _call(e){return new et(await super._call(e))}}class j2 extends jr{async _call(e){return new fe(await super._call(e))}}class q2 extends jr{async _call(e){return new Xe(await super._call(e))}}class G2 extends jr{async _call(e){return new st(await super._call(e))}}class qr extends j{}class W2 extends qr{}class H2 extends qr{async _call(e){return new et(await super._call(e))}}class K2 extends qr{async _call(e){return new fe(await super._call(e))}}class X2 extends qr{async _call(e){return new Xe(await super._call(e))}}class Q2 extends qr{async _call(e){return new st(await super._call(e))}}class Cm extends j{}class Y2 extends Cm{}class Z2 extends Cm{}class Am extends j{constructor(n,r,s){super(n,r);A(this,"requires_attention_mask",!1);A(this,"main_input_name","input_features");A(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=s}}class J2 extends Am{}class e$ extends Am{_prepare_generation_config(e,n){return super._prepare_generation_config(e,n,sx)}_retrieve_init_tokens(e){const n=[e.decoder_start_token_id];let r=e.language;const s=e.task;if(e.is_multilingual){r||(console.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${rm(r)}|>`;n.push(e.lang_to_id[a]),n.push(e.task_to_id[s??"transcribe"])}else if(r||s)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&n.at(-1)!==e.no_timestamps_token_id?n.push(e.no_timestamps_token_id):e.return_timestamps&&n.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),n.pop()),n.filter(i=>i!=null)}async generate({inputs:e=null,generation_config:n=null,logits_processor:r=null,stopping_criteria:s=null,...i}){n=this._prepare_generation_config(n,i);const a=i.decoder_input_ids??this._retrieve_init_tokens(n);if(n.return_timestamps&&(r??(r=new Fs),r.push(new jv(n,a))),n.begin_suppress_tokens&&(r??(r=new Fs),r.push(new gm(n.begin_suppress_tokens,a.length))),n.return_token_timestamps){if(!n.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");n.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),n.output_attentions=!0,n.return_dict_in_generate=!0}const o=await super.generate({inputs:e,generation_config:n,logits_processor:r,decoder_input_ids:a,...i});return n.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,n.alignment_heads,n.num_frames)),o}_extract_token_timestamps(e,n,r=null,s=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let i=this.config.median_filter_width;i===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),i=7);const a=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(g,w)=>ct(a.map(v=>v[w]),2)),l=Er(n.map(([g,w])=>{if(g>=o.length)throw new Error(`Layer index ${g} is out of bounds for cross attentions (length ${o.length}).`);return r?o[g].slice(null,w,null,[0,r]):o[g].slice(null,w)})).transpose(1,0,2,3),[u,c]=_b(l,-2,0,!0),p=l.clone();for(let g=0;gv[C+1]-v[C]),k=We([1],$).map(T=>!!T),E=[];for(let T=0;Td.findIndex(f=>f==i)),l=o.every(d=>d===-1),u=o.every(d=>d!==-1);if(!l&&!u)throw new Error("Every input should contain either 0 or 1 image token.");if(l)return{inputs_embeds:e,attention_mask:s};const c=[],p=[];for(let d=0;di*a,1);e.input_labels=new ee("int64",new BigInt64Array(s).fill(1n),r)}const n={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(n.input_points=e.input_points),e.input_labels&&(n.input_labels=e.input_labels),e.input_boxes&&(n.input_boxes=e.input_boxes),await hn(this.sessions.prompt_encoder_mask_decoder,n)}async _call(e){return new dS(await super._call(e))}}class dS extends mt{constructor({iou_scores:e,pred_masks:n}){super(),this.iou_scores=e,this.pred_masks=n}}class kg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class cS extends kg{}class pS extends kg{}class Sg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class hS extends Sg{}class fS extends Sg{}class An extends j{}class mS extends An{}class gS extends An{async _call(e){return new sr(await super._call(e))}}class _S extends An{async _call(e){return new fe(await super._call(e))}}class wS extends An{async _call(e){return new Xe(await super._call(e))}}class Eg extends j{}class yS extends Eg{}class bS extends Eg{async _call(e){return new Xe(await super._call(e))}}class vS extends j{}class xS extends vS{}class ao extends j{}class $S extends ao{}class kS extends ao{async _call(e){return new sr(await super._call(e))}}class SS extends ao{async _call(e){return new fe(await super._call(e))}}class Hs extends j{}class ES extends Hs{}class TS extends Hs{async _call(e){return new sr(await super._call(e))}}class MS extends Hs{async _call(e){return new fe(await super._call(e))}}class CS extends Hs{async _call(e){return new Xe(await super._call(e))}}class io extends j{}class AS extends io{}class IS extends io{async _call(e){return new sr(await super._call(e))}}class zS extends io{async _call(e){return new fe(await super._call(e))}}class OS extends An{}class PS extends An{async _call(e){return new sr(await super._call(e))}}class BS extends An{async _call(e){return new fe(await super._call(e))}}class Gr extends j{}class RS extends Gr{}class FS extends Gr{async _call(e){return new sr(await super._call(e))}}class DS extends Gr{async _call(e){return new fe(await super._call(e))}}class NS extends Gr{async _call(e){return new EE(await super._call(e))}}class LS extends Gr{async _call(e){return new Xe(await super._call(e))}}class Tg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class US extends Tg{}class VS extends Tg{async generate_speech(e,n,{threshold:r=.5,minlenratio:s=0,maxlenratio:i=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:l,encoder_attention_mask:u}=await rr(this,o),c=l.dims[1]/this.config.reduction_factor,p=Math.floor(c*i),d=Math.floor(c*s),f=this.config.num_mel_bins;let m=[],g=null,w=null,v=0;for(;;){++v;const k=bm(!!w);let E;w?E=w.output_sequence_out:E=new ee("float32",new Float32Array(f),[1,1,f]);let T={use_cache_branch:k,output_sequence:E,encoder_attention_mask:u,speaker_embeddings:n,encoder_hidden_states:l};this.addPastKeyValues(T,g),w=await hn(this.sessions.decoder_model_merged,T),g=this.getPastKeyValues(w,g);const{prob:C,spectrum:B}=w;if(m.push(B),v>=d&&(Array.from(C.data).filter(U=>U>=r).length>0||v>=p))break}const y=ct(m),{waveform:$}=await hn(a.sessions.model,{spectrogram:y});return{spectrogram:y,waveform:$}}}class jS extends j{constructor(){super(...arguments);A(this,"main_input_name","spectrogram")}}class qS extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class GS extends qS{}class Mg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class WS extends Mg{}class HS extends Mg{}class Cg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class KS extends Cg{}class XS extends Cg{}class Ag extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class QS extends Ag{}class YS extends Ag{}class oo extends j{}class ZS extends oo{}class JS extends oo{static async from_pretrained(e,n={}){return n.model_file_name??(n.model_file_name="text_model"),super.from_pretrained(e,n)}}class eE extends oo{static async from_pretrained(e,n={}){return n.model_file_name??(n.model_file_name="audio_model"),super.from_pretrained(e,n)}}class tE extends j{}class Ig extends tE{async _call(e){return new ME(await super._call(e))}}class zg extends j{}class nE extends zg{}class rE extends zg{}class Og extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class sE extends Og{}class aE extends Og{}class Pg extends j{}class iE extends Pg{}class oE extends Pg{async _call(e){return new fe(await super._call(e))}}class Bg extends j{constructor(n,r,s){super(n,r);A(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=s}_apply_and_filter_by_delay_pattern_mask(n){const[r,s]=n.dims,i=this.config.decoder.num_codebooks,a=s-i;let o=0;for(let c=0;c0&&f<=a&&(n.data[o++]=n.data[c])}const l=Math.floor(r/i),u=o/(l*i);return new ee(n.type,n.data.slice(0,o),[l,i,u])}prepare_inputs_for_generation(n,r,s){let i=structuredClone(n);for(let o=0;o=l&&(i[o][l]=BigInt(this.config.decoder.pad_token_id));return s.guidance_scale!==null&&s.guidance_scale>1&&(i=i.concat(i)),super.prepare_inputs_for_generation(i,r,s)}async generate(n){const r=await super.generate(n),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:i}=await hn(this.sessions.encodec_decode,{audio_codes:s});return i}}class Rg extends j{}class lE extends Rg{}class uE extends Rg{async _call(e){return new fe(await super._call(e))}}class Fg extends j{}class dE extends Fg{}class cE extends Fg{async _call(e){return new fe(await super._call(e))}}class Dg extends j{}class pE extends Dg{}class hE extends Dg{async _call(e){return new fe(await super._call(e))}}class Ng extends j{}class fE extends Ng{}class mE extends Ng{async _call(e){return new fe(await super._call(e))}}class Me{static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:i=!1,revision:a="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:c=null,use_external_data_format:p=null,session_options:d={}}={}){const f={progress_callback:n,config:r,cache_dir:s,local_files_only:i,revision:a,model_file_name:o,subfolder:l,device:u,dtype:c,use_external_data_format:p,session_options:d};if(f.config=await fm.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const m of this.MODEL_CLASS_MAPPINGS){const g=m.get(f.config.model_type);if(g)return await g[1].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${f.config.model_type}", attempting to construct from base class.`),await j.from_pretrained(e,f);throw Error(`Unsupported model type: ${f.config.model_type}`)}}A(Me,"MODEL_CLASS_MAPPINGS",null),A(Me,"BASE_IF_FAIL",!1);const gE=new Map([["bert",["BertModel",dx]],["nomic_bert",["NomicBertModel",gx]],["roformer",["RoFormerModel",_x]],["electra",["ElectraModel",Tx]],["esm",["EsmModel",Zx]],["convbert",["ConvBertModel",xx]],["camembert",["CamembertModel",zx]],["deberta",["DebertaModel",Fx]],["deberta-v2",["DebertaV2Model",Vx]],["mpnet",["MPNetModel",i2]],["albert",["AlbertModel",m2]],["distilbert",["DistilBertModel",Hx]],["roberta",["RobertaModel",R2]],["xlm",["XLMModel",U2]],["xlm-roberta",["XLMRobertaModel",W2]],["clap",["ClapModel",ZS]],["clip",["CLIPModel",a$]],["clipseg",["CLIPSegModel",h$]],["chinese_clip",["ChineseCLIPModel",p$]],["siglip",["SiglipModel",l$]],["mobilebert",["MobileBertModel",n2]],["squeezebert",["SqueezeBertModel",c2]],["wav2vec2",["Wav2Vec2Model",mS]],["wav2vec2-bert",["Wav2Vec2BertModel",AS]],["unispeech",["UniSpeechModel",$S]],["unispeech-sat",["UniSpeechSatModel",ES]],["hubert",["HubertModel",OS]],["wavlm",["WavLMModel",RS]],["audio-spectrogram-transformer",["ASTModel",Y2]],["vits",["VitsModel",Ig]],["pyannote",["PyAnnoteModel",yS]],["wespeaker-resnet",["WeSpeakerResNetModel",xS]],["detr",["DetrModel",vk]],["rt_detr",["RTDetrModel",kk]],["table-transformer",["TableTransformerModel",Tk]],["vit",["ViTModel",Y$]],["pvt",["PvtModel",J$]],["vit_msn",["ViTMSNModel",rk]],["vit_mae",["ViTMAEModel",nk]],["groupvit",["GroupViTModel",ik]],["fastvit",["FastViTModel",ok]],["mobilevit",["MobileViTModel",ck]],["mobilevitv2",["MobileViTV2Model",hk]],["owlvit",["OwlViTModel",mk]],["owlv2",["Owlv2Model",_k]],["beit",["BeitModel",yk]],["deit",["DeiTModel",Ak]],["hiera",["HieraModel",zk]],["convnext",["ConvNextModel",Jk]],["convnextv2",["ConvNextV2Model",tS]],["dinov2",["Dinov2Model",rS]],["resnet",["ResNetModel",Pk]],["swin",["SwinModel",Rk]],["swin2sr",["Swin2SRModel",Dk]],["donut-swin",["DonutSwinModel",Zk]],["yolos",["YolosModel",aS]],["dpt",["DPTModel",Lk]],["glpn",["GLPNModel",Xk]],["hifigan",["SpeechT5HifiGan",jS]],["efficientnet",["EfficientNetModel",iE]],["mobilenet_v1",["MobileNetV1Model",lE]],["mobilenet_v2",["MobileNetV2Model",dE]],["mobilenet_v3",["MobileNetV3Model",pE]],["mobilenet_v4",["MobileNetV4Model",fE]],["maskformer",["MaskFormerModel",Hk]]]),_E=new Map([["t5",["T5Model",y2]],["longt5",["LongT5Model",v2]],["mt5",["MT5Model",$2]],["bart",["BartModel",S2]],["mbart",["MBartModel",M2]],["marian",["MarianModel",cS]],["whisper",["WhisperModel",J2]],["m2m_100",["M2M100Model",hS]],["blenderbot",["BlenderbotModel",z2]],["blenderbot-small",["BlenderbotSmallModel",P2]]]),wE=new Map([["bloom",["BloomModel",G$]],["jais",["JAISModel",_$]],["gpt2",["GPT2Model",m$]],["gptj",["GPTJModel",$$]],["gpt_bigcode",["GPTBigCodeModel",S$]],["gpt_neo",["GPTNeoModel",y$]],["gpt_neox",["GPTNeoXModel",v$]],["codegen",["CodeGenModel",T$]],["llama",["LlamaModel",C$]],["cohere",["CohereModel",I$]],["gemma",["GemmaModel",O$]],["gemma2",["Gemma2Model",B$]],["openelm",["OpenELMModel",F$]],["qwen2",["Qwen2Model",N$]],["phi",["PhiModel",U$]],["phi3",["Phi3Model",j$]],["mpt",["MptModel",H$]],["opt",["OPTModel",X$]],["mistral",["MistralModel",WS]],["starcoder2",["Starcoder2Model",KS]],["falcon",["FalconModel",QS]],["stablelm",["StableLmModel",sE]]]),lo=new Map([["speecht5",["SpeechT5ForSpeechToText",US]],["whisper",["WhisperForConditionalGeneration",e$]]]),Lg=new Map([["speecht5",["SpeechT5ForTextToSpeech",VS]]]),Ug=new Map([["vits",["VitsModel",Ig]],["musicgen",["MusicgenForConditionalGeneration",Bg]]]),Vg=new Map([["bert",["BertForSequenceClassification",px]],["roformer",["RoFormerForSequenceClassification",yx]],["electra",["ElectraForSequenceClassification",Cx]],["esm",["EsmForSequenceClassification",e2]],["convbert",["ConvBertForSequenceClassification",kx]],["camembert",["CamembertForSequenceClassification",Px]],["deberta",["DebertaForSequenceClassification",Nx]],["deberta-v2",["DebertaV2ForSequenceClassification",qx]],["mpnet",["MPNetForSequenceClassification",l2]],["albert",["AlbertForSequenceClassification",g2]],["distilbert",["DistilBertForSequenceClassification",Kx]],["roberta",["RobertaForSequenceClassification",D2]],["xlm",["XLMForSequenceClassification",j2]],["xlm-roberta",["XLMRobertaForSequenceClassification",K2]],["bart",["BartForSequenceClassification",T2]],["mbart",["MBartForSequenceClassification",A2]],["mobilebert",["MobileBertForSequenceClassification",s2]],["squeezebert",["SqueezeBertForSequenceClassification",h2]]]),jg=new Map([["bert",["BertForTokenClassification",hx]],["roformer",["RoFormerForTokenClassification",bx]],["electra",["ElectraForTokenClassification",Ax]],["esm",["EsmForTokenClassification",t2]],["convbert",["ConvBertForTokenClassification",Sx]],["camembert",["CamembertForTokenClassification",Bx]],["deberta",["DebertaForTokenClassification",Lx]],["deberta-v2",["DebertaV2ForTokenClassification",Gx]],["mpnet",["MPNetForTokenClassification",u2]],["distilbert",["DistilBertForTokenClassification",Xx]],["roberta",["RobertaForTokenClassification",N2]],["xlm",["XLMForTokenClassification",q2]],["xlm-roberta",["XLMRobertaForTokenClassification",X2]]]),uo=new Map([["t5",["T5ForConditionalGeneration",b2]],["longt5",["LongT5ForConditionalGeneration",x2]],["mt5",["MT5ForConditionalGeneration",k2]],["bart",["BartForConditionalGeneration",E2]],["mbart",["MBartForConditionalGeneration",C2]],["marian",["MarianMTModel",pS]],["m2m_100",["M2M100ForConditionalGeneration",fS]],["blenderbot",["BlenderbotForConditionalGeneration",O2]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",B2]]]),co=new Map([["bloom",["BloomForCausalLM",W$]],["gpt2",["GPT2LMHeadModel",g$]],["jais",["JAISLMHeadModel",w$]],["gptj",["GPTJForCausalLM",k$]],["gpt_bigcode",["GPTBigCodeForCausalLM",E$]],["gpt_neo",["GPTNeoForCausalLM",b$]],["gpt_neox",["GPTNeoXForCausalLM",x$]],["codegen",["CodeGenForCausalLM",M$]],["llama",["LlamaForCausalLM",A$]],["cohere",["CohereForCausalLM",z$]],["gemma",["GemmaForCausalLM",P$]],["gemma2",["Gemma2ForCausalLM",R$]],["openelm",["OpenELMForCausalLM",D$]],["qwen2",["Qwen2ForCausalLM",L$]],["phi",["PhiForCausalLM",V$]],["phi3",["Phi3ForCausalLM",q$]],["mpt",["MptForCausalLM",K$]],["opt",["OPTForCausalLM",Q$]],["mbart",["MBartForCausalLM",I2]],["mistral",["MistralForCausalLM",HS]],["starcoder2",["Starcoder2ForCausalLM",XS]],["falcon",["FalconForCausalLM",YS]],["trocr",["TrOCRForCausalLM",GS]],["stablelm",["StableLmForCausalLM",aE]]]),qg=new Map([["bert",["BertForMaskedLM",cx]],["roformer",["RoFormerForMaskedLM",wx]],["electra",["ElectraForMaskedLM",Mx]],["esm",["EsmForMaskedLM",Jx]],["convbert",["ConvBertForMaskedLM",$x]],["camembert",["CamembertForMaskedLM",Ox]],["deberta",["DebertaForMaskedLM",Dx]],["deberta-v2",["DebertaV2ForMaskedLM",jx]],["mpnet",["MPNetForMaskedLM",o2]],["albert",["AlbertForMaskedLM",w2]],["distilbert",["DistilBertForMaskedLM",Yx]],["roberta",["RobertaForMaskedLM",F2]],["xlm",["XLMWithLMHeadModel",V2]],["xlm-roberta",["XLMRobertaForMaskedLM",H2]],["mobilebert",["MobileBertForMaskedLM",r2]],["squeezebert",["SqueezeBertForMaskedLM",p2]]]),Gg=new Map([["bert",["BertForQuestionAnswering",fx]],["roformer",["RoFormerForQuestionAnswering",vx]],["electra",["ElectraForQuestionAnswering",Ix]],["convbert",["ConvBertForQuestionAnswering",Ex]],["camembert",["CamembertForQuestionAnswering",Rx]],["deberta",["DebertaForQuestionAnswering",Ux]],["deberta-v2",["DebertaV2ForQuestionAnswering",Wx]],["mpnet",["MPNetForQuestionAnswering",d2]],["albert",["AlbertForQuestionAnswering",_2]],["distilbert",["DistilBertForQuestionAnswering",Qx]],["roberta",["RobertaForQuestionAnswering",L2]],["xlm",["XLMForQuestionAnswering",G2]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Q2]],["mobilebert",["MobileBertForQuestionAnswering",a2]],["squeezebert",["SqueezeBertForQuestionAnswering",f2]]]),po=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Im]]]),yE=new Map([["llava",["LlavaForConditionalGeneration",zm]],["moondream1",["Moondream1ForConditionalGeneration",n$]],["florence2",["Florence2ForConditionalGeneration",s$]]]),bE=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Im]]]),Wg=new Map([["vit",["ViTForImageClassification",Z$]],["pvt",["PvtForImageClassification",ek]],["vit_msn",["ViTMSNForImageClassification",sk]],["fastvit",["FastViTForImageClassification",lk]],["mobilevit",["MobileViTForImageClassification",pk]],["mobilevitv2",["MobileViTV2ForImageClassification",fk]],["beit",["BeitForImageClassification",bk]],["deit",["DeiTForImageClassification",Ik]],["hiera",["HieraForImageClassification",Ok]],["convnext",["ConvNextForImageClassification",eS]],["convnextv2",["ConvNextV2ForImageClassification",nS]],["dinov2",["Dinov2ForImageClassification",sS]],["resnet",["ResNetForImageClassification",Bk]],["swin",["SwinForImageClassification",Fk]],["segformer",["SegformerForImageClassification",nE]],["efficientnet",["EfficientNetForImageClassification",oE]],["mobilenet_v1",["MobileNetV1ForImageClassification",uE]],["mobilenet_v2",["MobileNetV2ForImageClassification",cE]],["mobilenet_v3",["MobileNetV3ForImageClassification",hE]],["mobilenet_v4",["MobileNetV4ForImageClassification",mE]]]),Hg=new Map([["detr",["DetrForObjectDetection",xk]],["rt_detr",["RTDetrForObjectDetection",Sk]],["table-transformer",["TableTransformerForObjectDetection",Mk]],["yolos",["YolosForObjectDetection",iS]]]),Kg=new Map([["owlvit",["OwlViTForObjectDetection",gk]],["owlv2",["Owlv2ForObjectDetection",wk]]]),Xg=new Map([["detr",["DetrForSegmentation",lg]],["clipseg",["CLIPSegForImageSegmentation",f$]]]),Qg=new Map([["segformer",["SegformerForSemanticSegmentation",rE]],["sapiens",["SapiensForSemanticSegmentation",qk]]]),Yg=new Map([["detr",["DetrForSegmentation",lg]],["maskformer",["MaskFormerForInstanceSegmentation",Kk]]]),vE=new Map([["sam",["SamModel",uS]]]),Zg=new Map([["wav2vec2",["Wav2Vec2ForCTC",gS]],["wav2vec2-bert",["Wav2Vec2BertForCTC",IS]],["unispeech",["UniSpeechForCTC",kS]],["unispeech-sat",["UniSpeechSatForCTC",TS]],["wavlm",["WavLMForCTC",FS]],["hubert",["HubertForCTC",PS]]]),Jg=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",_S]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",zS]],["unispeech",["UniSpeechForSequenceClassification",SS]],["unispeech-sat",["UniSpeechSatForSequenceClassification",MS]],["wavlm",["WavLMForSequenceClassification",DS]],["hubert",["HubertForSequenceClassification",BS]],["audio-spectrogram-transformer",["ASTForAudioClassification",Z2]]]),xE=new Map([["wavlm",["WavLMForXVector",NS]]]),e_=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",CS]],["wavlm",["WavLMForAudioFrameClassification",LS]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",wS]],["pyannote",["PyAnnoteForAudioFrameClassification",bS]]]),$E=new Map([["vitmatte",["VitMatteForImageMatting",dk]]]),t_=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Nk]]]),n_=new Map([["dpt",["DPTForDepthEstimation",Uk]],["depth_anything",["DepthAnythingForDepthEstimation",jk]],["glpn",["GLPNForDepthEstimation",Qk]],["sapiens",["SapiensForDepthEstimation",Gk]]]),kE=new Map([["sapiens",["SapiensForNormalEstimation",Wk]]]),r_=new Map([["clip",["CLIPVisionModelWithProjection",o$]],["siglip",["SiglipVisionModel",d$]]]),s_=[[gE,de.EncoderOnly],[_E,de.EncoderDecoder],[wE,de.DecoderOnly],[Vg,de.EncoderOnly],[jg,de.EncoderOnly],[uo,de.Seq2Seq],[lo,de.Seq2Seq],[co,de.DecoderOnly],[qg,de.EncoderOnly],[Gg,de.EncoderOnly],[po,de.Vision2Seq],[yE,de.ImageTextToText],[Wg,de.EncoderOnly],[Xg,de.EncoderOnly],[Yg,de.EncoderOnly],[Qg,de.EncoderOnly],[$E,de.EncoderOnly],[t_,de.EncoderOnly],[n_,de.EncoderOnly],[kE,de.EncoderOnly],[Hg,de.EncoderOnly],[Kg,de.EncoderOnly],[vE,de.MaskGeneration],[Zg,de.EncoderOnly],[Jg,de.EncoderOnly],[Lg,de.Seq2Seq],[Ug,de.EncoderOnly],[xE,de.EncoderOnly],[e_,de.EncoderOnly],[r_,de.EncoderOnly]];for(const[t,e]of s_)for(const[n,r]of t.values())Ns.set(n,e),zr.set(r,n),wm.set(n,r);const SE=[["MusicgenForConditionalGeneration",Bg,de.Musicgen],["CLIPTextModelWithProjection",i$,de.EncoderOnly],["SiglipTextModel",u$,de.EncoderOnly],["ClapTextModelWithProjection",JS,de.EncoderOnly],["ClapAudioModelWithProjection",eE,de.EncoderOnly]];for(const[t,e,n]of SE)Ns.set(t,n),zr.set(e,t),wm.set(t,e);class In extends Me{}A(In,"MODEL_CLASS_MAPPINGS",s_.map(e=>e[0])),A(In,"BASE_IF_FAIL",!0);class ho extends Me{}A(ho,"MODEL_CLASS_MAPPINGS",[Vg]);class a_ extends Me{}A(a_,"MODEL_CLASS_MAPPINGS",[jg]);class Ks extends Me{}A(Ks,"MODEL_CLASS_MAPPINGS",[uo]);class i_ extends Me{}A(i_,"MODEL_CLASS_MAPPINGS",[lo]);class o_ extends Me{}A(o_,"MODEL_CLASS_MAPPINGS",[Lg]);class l_ extends Me{}A(l_,"MODEL_CLASS_MAPPINGS",[Ug]);class u_ extends Me{}A(u_,"MODEL_CLASS_MAPPINGS",[co]);class d_ extends Me{}A(d_,"MODEL_CLASS_MAPPINGS",[qg]);class c_ extends Me{}A(c_,"MODEL_CLASS_MAPPINGS",[Gg]);class p_ extends Me{}A(p_,"MODEL_CLASS_MAPPINGS",[po]);class h_ extends Me{}A(h_,"MODEL_CLASS_MAPPINGS",[Wg]);class f_ extends Me{}A(f_,"MODEL_CLASS_MAPPINGS",[Xg]);class m_ extends Me{}A(m_,"MODEL_CLASS_MAPPINGS",[Qg]);class g_ extends Me{}A(g_,"MODEL_CLASS_MAPPINGS",[Yg]);class __ extends Me{}A(__,"MODEL_CLASS_MAPPINGS",[Hg]);class w_ extends Me{}A(w_,"MODEL_CLASS_MAPPINGS",[Kg]);class y_ extends Me{}A(y_,"MODEL_CLASS_MAPPINGS",[Zg]);class b_ extends Me{}A(b_,"MODEL_CLASS_MAPPINGS",[Jg]);class v_ extends Me{}A(v_,"MODEL_CLASS_MAPPINGS",[e_]);class x_ extends Me{}A(x_,"MODEL_CLASS_MAPPINGS",[bE]);class $_ extends Me{}A($_,"MODEL_CLASS_MAPPINGS",[t_]);class k_ extends Me{}A(k_,"MODEL_CLASS_MAPPINGS",[n_]);class S_ extends Me{}A(S_,"MODEL_CLASS_MAPPINGS",[r_]);class fe extends mt{constructor({logits:e}){super(),this.logits=e}}class EE extends mt{constructor({logits:e,embeddings:n}){super(),this.logits=e,this.embeddings=n}}class Xe extends mt{constructor({logits:e}){super(),this.logits=e}}class et extends mt{constructor({logits:e}){super(),this.logits=e}}class st extends mt{constructor({start_logits:e,end_logits:n}){super(),this.start_logits=e,this.end_logits=n}}class sr extends mt{constructor({logits:e}){super(),this.logits=e}}class TE extends mt{constructor({alphas:e}){super(),this.alphas=e}}class ME extends mt{constructor({waveform:e,spectrogram:n}){super(),this.waveform=e,this.spectrogram=n}}const vt=typeof self<"u",CE=vt&&self.constructor.name==="DedicatedWorkerGlobalScope";let zn,E_,fn;if(vt)zn=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},fn=self.createImageBitmap,E_=self.ImageData;else if(ke)fn=async t=>{const n=(await t.metadata()).channels,{data:r,info:s}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),i=new at(new Uint8ClampedArray(r),s.width,s.height,s.channels);return n!==void 0&&n!==s.channels&&i.convert(n),i};else throw new Error("Unable to load image processing library.");const AE={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},IE=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class at{constructor(e,n,r,s){this.data=e,this.width=n,this.height=r,this.channels=s}get size(){return[this.width,this.height]}static async read(e){if(e instanceof at)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(!vt)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 at(r,e.width,e.height,4)}static async fromURL(e){const n=await es(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(vt){const n=await fn(e),r=zn(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=ke(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 at(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,s>=0?u=s:p=-s,o.drawImage(a,l,u,e,n,c,p,e,n),new at(o.getImageData(0,0,e,n).data,e,n,4).convert(i)}else{let i=this.toSharp();if(r>=0&&s>=0)i=i.extract({left:Math.floor(r),top:Math.floor(s),width:e,height:n});else if(r<=0&&s<=0){const a=Math.floor(-s),o=Math.floor(-r);i=i.extend({top:a,left:o,right:e-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;s<0?(a[0]=Math.floor(-s),a[1]=n-this.height-a[0]):o=Math.floor(s);let l=[0,0],u=0;r<0?(l[0]=Math.floor(-r),l[1]=e-this.width-l[0]):u=Math.floor(r),i=i.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:u,top:o,width:e,height:n})}return await fn(i)}}async toBlob(e="image/png",n=1){if(!vt)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:n})}toTensor(e="CHW"){let n=new ee("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")n=n.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return n}toCanvas(){if(!vt)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),n=zn(e.width,e.height),r=new E_(e.data,e.width,e.height);return n.getContext("2d").putImageData(r,0,0),n}_update(e,n,r,s=null){return this.data=e,this.width=n,this.height=r,s!==null&&(this.channels=s),this}clone(){return new at(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(vt){if(CE)throw new Error("Unable to save an image from a Web Worker.");const n=e.split(".").pop().toLowerCase(),r=IE.get(n)??"image/png",s=await this.toBlob(r),i=URL.createObjectURL(s),a=document.createElement("a");a.href=i,a.download=e,a.click(),a.remove()}else{if(tt.useFS)return await this.toSharp().toFile(e);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(vt)throw new Error("toSharp() is only supported in server-side environments.");return ke(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}async function zE(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 es(t)).arrayBuffer(),r=new AudioContext({sampleRate:e});typeof e>"u"&&console.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);const s=await r.decodeAudioData(n);let i;if(s.numberOfChannels===2){const a=Math.sqrt(2),o=s.getChannelData(0),l=s.getChannelData(1);i=new Float32Array(o.length);for(let u=0;u2595*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 fo(t,e="htk"){const n=PE[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 BE={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 RE(t,e="htk"){const n=BE[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 FE(t,e){const n=Float64Array.from({length:e.length-1},(a,o)=>e[o+1]-e[o]),r=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+r*i)}function ar(t,e,n,r,s,i=null,a="htk",o=!1){if(i!==null&&i!=="slaney")throw new Error('norm must be one of null or "slaney"');const l=fo(n,a),u=fo(r,a),c=C_(l,u,e+2);let p=RE(c,a),d;if(o){const m=s/(t*2);d=fo(Float64Array.from({length:t},(g,w)=>w*m),a),p=c}else d=C_(0,Math.floor(s/2),t);const f=FE(d,p);if(i!==null&&i==="slaney")for(let m=0;ms)throw Error(`frame_length (${n}) may not be larger than fft_length (${s})`);if(E!==n)throw new Error(`Length of the window (${E}) must equal frame_length (${n})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(i===null&&c!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(a){if(o!=="reflect")throw new Error(`pad_mode="${o}" not implemented yet.`);const N=Math.floor((s-1)/2)+1;t=DE(t,N,N)}let T=Math.floor(1+Math.floor((t.length-n)/r));v!==null&&TT?$&&(U=y):U=B=y);const G=new Iy(s),K=new Float64Array(s),X=new Float64Array(G.outputBufferSize),H=new Float32Array(C*U);for(let N=0;N=1;--te)K[te]-=u*K[te-1];K[0]*=1-u}for(let te=0;teMath.pow(o,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(n&&(a=a.subarray(0,t)),r===null)return a;if(t>r)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${r})`);return a}function UE([t,e,n,r]){return[t-n/2,e-r/2,t+n/2,e+r/2]}function Xs(t,e=.5,n=null,r=!1){const s=t.logits,i=t.pred_boxes,[a,o,l]=s.dims;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");let u=[];for(let c=0;ce&&v.push($)}else{let $=dt(w.data)[1];if($===l-1||(y=He(w.data),y[$]E*p[(T+1)%2])),d.boxes.push(k),d.classes.push($),d.scores.push(y[$])}}u.push(d)}return u}function I_(t,e=null){const n=t.logits,r=n.dims[0];if(e!==null&&e.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const s=[];for(let i=0;ip[v]&&(p[v]=w[v],d[v]=g)}const f=new Array(o.dims[0]);for(let g=0;gg!==void 0);s.push({segmentation:c,labels:m})}return s}function VE(t,e,n,r){const s=[],i=[],a=[];for(let o=0;on&&(s.push(u),i.push(d),a.push(c))}return[s,i,a]}function jE(t,e,n,r=.5,s=.8){const i=[];let a=0,o=0;const l=e[n].data;for(let c=0;c=r&&++o;let u=a>0&&o>0;return u&&(u=a/o>s),[u,i]}function qE(t,e,n,r,s,i=null,a=null){const[o,l]=a??t[0].dims,u=new ee("int32",new Int32Array(o*l),[o,l]),c=[];if(a!==null)for(let g=0;gd[y]&&(p[y]=g,d[y]=v[y])}let f=0;const m=u.data;for(let g=0;gr&&(i=Math.floor(s)*e),ii?u=Math.floor(i*l/s):i>s&&(l=Math.floor(s*u/i)),await e.resize(u,l,{resample:r}))}async crop_margin(e,n=200){const r=e.clone().grayscale(),s=Xo(r.data)[0],a=dt(r.data)[0]-s;if(a===0)return e;const o=n/255;let l=r.width,u=r.height,c=0,p=0;const d=r.data;for(let f=0;fthis.preprocess(i)));return{pixel_values:Er(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 GE extends ve{post_process_semantic_segmentation(...e){return I_(...e)}}class WE extends ve{post_process_semantic_segmentation(...e){return I_(...e)}}class HE extends ve{}class P_ extends ve{}class KE extends P_{}class XE extends ve{}class QE extends ve{}class B_ extends ve{}class YE extends B_{}class ZE extends ve{}class JE extends ve{}class R_ extends ve{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){var r;const n=(r=this.size)==null?void 0:r.shortest_edge;if(n===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(n<384){const s=Math.floor(n/this.crop_pct),[i,a]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(i,a,{resample:this.resample}),e=await e.center_crop(n,n)}else e=await e.resize(n,n,{resample:this.resample});return e}}class eT extends R_{}class tT extends ve{}class nT extends ve{}class rT extends ve{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(n=>n*n))}}class sT extends ve{}class aT extends ve{}class iT extends ve{}class oT extends ve{}class F_ extends ve{}class lT extends F_{}class D_ extends ve{post_process_object_detection(...e){return Xs(...e)}}class uT extends D_{}class dT extends ve{post_process_object_detection(...e){return Xs(...e)}}class cT extends ve{}class pT extends ve{}class N_ extends ve{pad_image(e,n,r,s={}){const[i,a,o]=n;let l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(o).fill(l));let u=this.image_std;Array.isArray(u)||(u=new Array(o).fill(l));const c=l.map((p,d)=>-p/u[d]);return super.pad_image(e,n,r,{center:!0,constant_values:c,...s})}}class hT extends N_{}class fT extends ve{async _call(e){const n=await super._call(e),r=[n.pixel_values.dims[0],64,64],s=Hf(r,1n);return{...n,pixel_mask:s}}post_process_object_detection(...e){return Xs(...e)}post_process_panoptic_segmentation(...e){return z_(...e)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class mT extends ve{post_process_panoptic_segmentation(...e){return z_(...e)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class gT extends ve{post_process_object_detection(...e){return Xs(...e)}}class _T extends ve{reshape_input_points(e,n,r,s=!1){e=structuredClone(e);let i=Ho(e);if(i.length===3)s||(i=[1,...i]),e=[e];else if(i.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;as!==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,{input_points:n=null,input_labels:r=null,input_boxes:s=null}={}){const i=await super._call(e);if(n&&(i.input_points=this.reshape_input_points(n,i.original_sizes,i.reshaped_input_sizes)),r){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(r,i.input_points)}return s&&(i.input_boxes=this.reshape_input_points(s,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,n,r,{mask_threshold:s=0,binarize:i=!0,pad_size:a=null}={}){const o=[];a=a??this.pad_size;const l=[a.height,a.width];for(let u=0;us&&(m[g]=1);d=new ee("bool",m,d.dims)}o.push(d)}return o}generate_crop_boxes(e,n,{crop_n_layers:r=0,overlap_ratio:s=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}}class wT extends ve{pad_image(e,n,r,s={}){const[i,a,o]=n;return super.pad_image(e,n,{width:a+(r-a%r)%r,height:i+(r-i%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...s})}}class yT extends ve{async _call(e,n){Array.isArray(e)||(e=[e]),Array.isArray(n)||(n=[n]);const r=await Promise.all(e.map(a=>this.preprocess(a))),s=await Promise.all(n.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Er(r.map((a,o)=>ct([a.pixel_values,s[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}}class bT extends Qt{constructor(e){var n;super(e),(n=this.config).mel_filters??(n.mel_filters=ar(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=Hr(this.config.n_fft,"hann")}async _extract_fbank_features(e){const n=await Wr(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),r=n.data,s=dt(r)[0];for(let i=0;ithis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),n=e.slice(0,this.config.n_samples)):(n=new Float32Array(this.config.n_samples),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}}class vT extends Qt{_zero_mean_unit_var_norm(e){const r=e.reduce((i,a)=>i+a,0)/e.length,s=e.reduce((i,a)=>i+(a-r)**2,0)/e.length;return e.map(i=>(i-r)/Math.sqrt(s+1e-7))}async _call(e){On(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 xT extends Qt{constructor(e){super(e);const n=this.config.sampling_rate,r=ar(256,this.config.num_mel_bins,20,Math.floor(n/2),n,null,"kaldi",!0);for(let s=0;sr*32768),Wr(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:s=!0,return_attention_mask:i=!0}={}){On(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(s){const[m,g]=a.dims,w=a.data;for(let v=0;v0){const y=new Float32Array(g*(m+v));y.set(w),y.fill(this.config.padding_value,w.length);const $=m+v;a=new ee(a.type,y,[$,g]),i&&(o=new ee("int64",new BigInt64Array($),[1,$]),o.data.fill(1n,0,m))}}const[l,u]=a.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 d=a.view(1,Math.floor(l/c),u*c),f={input_features:d};if(i){const m=d.dims[1],g=new BigInt64Array(m);if(o){const w=o.data;for(let v=1,y=0;v0)if(r==="rand_trunc"){const o=Math.floor(Math.random()*(a+1));e=e.subarray(o,o+n),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let o=new Float64Array(n);if(o.set(e),s==="repeat")for(let l=e.length;l({id:l,start:u*r,end:c*r,confidence:p/(c-u)})))}return s}}class ET extends Qt{constructor(e){super(e);const n=this.config.sampling_rate,r=ar(256,this.config.num_mel_bins,20,Math.floor(n/2),n,null,"kaldi",!0);for(let s=0;sn*32768),Wr(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,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){On(e,"WeSpeakerFeatureExtractor");const n=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=n.mean(1).data,s=n.data,[i,a,o]=n.dims;for(let l=0;l/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const n=[];for(const r of e)if(this.task_prompts_without_inputs.has(r))n.push(this.task_prompts_without_inputs.get(r));else{for(const[s,i]of this.task_prompts_with_input)if(r.includes(s)){n.push(i.replaceAll("{input}",r).replaceAll(s,""));break}n.length!==e.length&&n.push(r)}return n}post_process_generation(e,n,r){const s=this.tasks_answer_post_processing_type.get(n)??"pure_text";e=e.replaceAll("","").replaceAll("","");let i;switch(s){case"pure_text":i=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=s==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),l=[],u=[];for(const[c,p,...d]of o)l.push(p?p.trim():l.at(-1)??""),u.push(d.map((f,m)=>(Number(f)+.5)/this.size_per_bin*r[m%2]));i={labels:l,[a]:u};break;default:throw new Error(`Task "${n}" (of type "${s}") not yet implemented.`)}return{[n]:i}}}class Qe{static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:i=!1,revision:a="main"}={}){let o=r??await tn(e,"preprocessor_config.json",!0,{progress_callback:n,config:r,cache_dir:s,local_files_only:i,revision:a}),l=o.feature_extractor_type??o.image_processor_type,u=this.FEATURE_EXTRACTOR_CLASS_MAPPING[l];if(!u)if(o.size!==void 0)console.warn(`Feature extractor type "${l}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),u=ve;else throw new Error(`Unknown Feature Extractor type: ${l}`);let c=this.PROCESSOR_CLASS_MAPPING[o.processor_class]??mn,p=new u(o);return new c(p)}}A(Qe,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:ve,WhisperFeatureExtractor:bT,ViTFeatureExtractor:tT,MobileViTFeatureExtractor:F_,MobileViTImageProcessor:lT,MobileNetV1FeatureExtractor:sT,MobileNetV2FeatureExtractor:aT,MobileNetV3FeatureExtractor:iT,MobileNetV4FeatureExtractor:oT,OwlViTFeatureExtractor:D_,Owlv2ImageProcessor:uT,CLIPFeatureExtractor:B_,CLIPImageProcessor:YE,Florence2Processor:L_,ChineseCLIPFeatureExtractor:ZE,SiglipImageProcessor:JE,ConvNextFeatureExtractor:R_,ConvNextImageProcessor:eT,SegformerFeatureExtractor:WE,SapiensFeatureExtractor:GE,BitImageProcessor:XE,DPTImageProcessor:KE,DPTFeatureExtractor:P_,PvtImageProcessor:HE,GLPNFeatureExtractor:QE,BeitFeatureExtractor:pT,DeiTFeatureExtractor:cT,DetrFeatureExtractor:fT,RTDetrImageProcessor:dT,MaskFormerFeatureExtractor:mT,YolosFeatureExtractor:gT,DonutFeatureExtractor:N_,NougatImageProcessor:hT,EfficientNetImageProcessor:rT,ViTImageProcessor:nT,VitMatteImageProcessor:yT,SamImageProcessor:_T,Swin2SRImageProcessor:wT,Wav2Vec2FeatureExtractor:vT,SeamlessM4TFeatureExtractor:xT,SpeechT5FeatureExtractor:TT,ASTFeatureExtractor:$T,ClapFeatureExtractor:kT,PyAnnoteFeatureExtractor:ST,WeSpeakerFeatureExtractor:ET}),A(Qe,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:CT,Wav2Vec2ProcessorWithLM:AT,PyAnnoteProcessor:IT,SamProcessor:MT,SpeechT5Processor:zT,OwlViTProcessor:OT,Florence2Processor:L_});async function Yt(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>at.read(e)))}async function Qs(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(n=>typeof n=="string"||n instanceof URL?zE(n,e):n instanceof Float64Array?new Float32Array(n):n))}function U_(t,e){e&&(t=t.map(a=>a|0));const[n,r,s,i]=t;return{xmin:n,ymin:r,xmax:s,ymax:i}}class Re extends Ye{constructor({task:e,model:n,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=n,this.tokenizer=r,this.processor=s}async dispose(){await this.model.dispose()}}class PT extends Re{constructor(e){super(e)}async _call(e,{top_k:n=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(r),i=this.model.config.problem_type==="multi_label_classification"?l=>l.sigmoid():l=>new ee("float32",He(l.data),l.dims),a=this.model.config.id2label,o=[];for(const l of s.logits){const u=i(l),c=await Qn(u,n),p=c[0].tolist(),f=c[1].tolist().map((m,g)=>({label:a?a[m]:`LABEL_${m}`,score:p[g]}));n===1?o.push(...f):o.push(f)}return Array.isArray(e)||n===1?o:o[0]}}class BT extends Re{constructor(e){super(e)}async _call(e,{ignore_labels:n=["O"]}={}){const r=Array.isArray(e),s=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(s)).logits,o=this.model.config.id2label,l=[];for(let u=0;u$==this.tokenizer.sep_token_id);l[p].map(($,k)=>$==1&&(k===0||k>f&&u.findIndex(E=>E==d[k])===-1));const m=i[p].tolist(),g=a[p].tolist();for(let $=1;$k==d[$])!==-1)&&(m[$]=-1/0,g[$]=-1/0);const w=He(m).map(($,k)=>[$,k]),v=He(g).map(($,k)=>[$,k]);w[0][0]=0,v[0][0]=0;const y=vy(w,v).filter($=>$[0][1]<=$[1][1]).map($=>[$[0][1],$[1][1],$[0][0]*$[1][0]]).sort(($,k)=>k[2]-$[2]);for(let $=0;$m==this.tokenizer.mask_token_id);if(u===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const c=s[o][u],p=await Qn(new ee("float32",He(c.data),c.dims),n),d=p[0].tolist(),f=p[1].tolist();i.push(f.map((m,g)=>{const w=l.slice();return w[u]=m,{score:d[g],token:Number(m),token_str:this.tokenizer.model.vocab[m],sequence:this.tokenizer.decode(w,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}}class go extends Re{constructor(n){super(n);A(this,"_key","generated_text")}async _call(n,r={}){Array.isArray(n)||(n=[n]),this.model.config.prefix&&(n=n.map(u=>this.model.config.prefix+u));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(n=n.map(u=>s[this.task].prefix+u));const i=this.tokenizer,a={padding:!0,truncation:!0};let o;this instanceof V_&&"_build_translation_inputs"in i?o=i._build_translation_inputs(n,a,r):o=i(n,a);const l=await this.model.generate({...o,...r});return i.batch_decode(l,{skip_special_tokens:!0}).map(u=>({[this._key]:u}))}}class DT extends go{constructor(n){super(n);A(this,"_key","summary_text")}}class V_ extends go{constructor(n){super(n);A(this,"_key","translation_text")}}function j_(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}class NT extends Re{constructor(e){super(e)}async _call(e,n={}){let r=!1,s=!1,i;if(typeof e=="string")i=e=[e];else if(Array.isArray(e)&&e.every(f=>typeof f=="string"))r=!0,i=e;else{if(j_(e))e=[e];else if(Array.isArray(e)&&e.every(j_))r=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");s=!0,i=e.map(f=>this.tokenizer.apply_chat_template(f,{tokenize:!1,add_generation_prompt:!0}))}const a=n.add_special_tokens??!1,o=s?!1:n.return_full_text??!0;this.tokenizer.padding_side="left";const l=this.tokenizer(i,{add_special_tokens:a,padding:!0,truncation:!0}),u=await this.model.generate({...l,...n}),c=this.tokenizer.batch_decode(u,{skip_special_tokens:!0});let p;!o&&l.input_ids.dims.at(-1)>0&&(p=this.tokenizer.batch_decode(l.input_ids,{skip_special_tokens:!0}).map(f=>f.length));const d=Array.from({length:e.length},f=>[]);for(let f=0;f[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:s=!1}={}){const i=Array.isArray(e);i||(e=[e]),Array.isArray(n)||(n=[n]);const a=n.map(u=>r.replace("{}",u)),o=s||n.length===1,l=[];for(const u of e){const c=[];for(const f of a){const m=this.tokenizer(u,{text_pair:f,padding:!0,truncation:!0}),g=await this.model(m);o?c.push([g.logits.data[this.contradiction_id],g.logits.data[this.entailment_id]]):c.push(g.logits.data[this.entailment_id])}const d=(o?c.map(f=>He(f)[1]):He(c)).map((f,m)=>[f,m]).sort((f,m)=>m[0]-f[0]);l.push({sequence:u,labels:d.map(f=>n[f[1]]),scores:d.map(f=>f[0])})}return i?l:l[0]}}class UT extends Re{constructor(e){super(e)}async _call(e,{pooling:n="none",normalize:r=!1,quantize:s=!1,precision:i="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a);let l=o.last_hidden_state??o.logits??o.token_embeddings;if(n!=="none")if(n==="mean")l=gb(l,a.attention_mask);else if(n==="cls")l=l.slice(null,0);else throw Error(`Pooling method '${n}' not supported.`);return r&&(l=l.normalize(2,-1)),s&&(l=$b(l,i)),l}}class VT extends Re{constructor(e){super(e)}async _call(e,{pool:n=null}={}){const r=await Yt(e),{pixel_values:s}=await this.processor(r),i=await this.model({pixel_values:s});let a;if(n){if(!("pooler_output"in i))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=i.pooler_output}else a=i.last_hidden_state??i.logits??i.image_embeds;return a}}class jT extends Re{constructor(e){super(e)}async _call(e,{top_k:n=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,s=await Qs(e,r),i=this.model.config.id2label,a=[];for(const o of s){const l=await this.processor(o),c=(await this.model(l)).logits[0],p=await Qn(new ee("float32",He(c.data),c.dims),n),d=p[0].tolist(),m=p[1].tolist().map((g,w)=>({label:i?i[g]:`LABEL_${g}`,score:d[w]}));a.push(m)}return Array.isArray(e)?a:a[0]}}class qT extends Re{constructor(e){super(e)}async _call(e,n,{hypothesis_template:r="This is a sound of {}."}={}){const s=!Array.isArray(e);s&&(e=[e]);const i=n.map(c=>r.replace("{}",c)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,l=await Qs(e,o),u=[];for(const c of l){const p=await this.processor(c),d=await this.model({...a,...p}),f=He(d.logits_per_audio.data);u.push([...f].map((m,g)=>({score:m,label:n[g]})))}return s?u[0]:u}}class GT extends Re{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 s=this.processor.feature_extractor.config.sampling_rate,i=await Qs(e,s),a=[];for(const o of i){const l=await this.processor(o),c=(await this.model(l)).logits[0],p=[];for(const f of c)p.push(dt(f.data)[1]);const d=this.tokenizer.decode(p);a.push({text:d})}return r?a[0]:a}async _call_whisper(e,n){const r=n.return_timestamps??!1,s=n.chunk_length_s??0,i=n.force_full_sequences??!1;let a=n.stride_length_s??null;const o={...n};r==="word"&&(o.return_token_timestamps=!0,o.return_timestamps=!1);const l=!Array.isArray(e);l&&(e=[e]);const u=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,c=this.processor.feature_extractor.config.hop_length,p=this.processor.feature_extractor.config.sampling_rate,d=await Qs(e,p),f=[];for(const m of d){let g=[];if(s>0){if(a===null)a=s/6;else if(s<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const y=p*s,$=p*a,k=y-2*$;let E=0;for(;;){const T=E+y,C=m.subarray(E,T),B=await this.processor(C),U=E===0,G=T>=m.length;if(g.push({stride:[C.length,U?0:$,G?0:$],input_features:B.input_features,is_last:G}),G)break;E+=k}}else g=[{stride:[m.length,0,0],input_features:(await this.processor(m)).input_features,is_last:!0}];for(const y of g){o.num_frames=Math.floor(y.stride[0]/c);const $=await this.model.generate({inputs:y.input_features,...o});r==="word"?(y.tokens=$.sequences.tolist()[0],y.token_timestamps=$.token_timestamps.tolist()[0].map(k=>ur(k,2))):y.tokens=$[0].tolist(),y.stride=y.stride.map(k=>k/p)}const[w,v]=this.tokenizer._decode_asr(g,{time_precision:u,return_timestamps:r,force_full_sequences:i});f.push({text:w,...v})}return l?f[0]:f}}class WT extends Re{constructor(e){super(e)}async _call(e,n={}){const r=Array.isArray(e),s=await Yt(e),{pixel_values:i}=await this.processor(s),a=[];for(const o of i){o.dims=[1,...o.dims];const l=await this.model.generate({inputs:o,...n}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));a.push(u)}return r?a:a[0]}}class HT extends Re{constructor(e){super(e)}async _call(e,{top_k:n=5}={}){const r=await Yt(e),{pixel_values:s}=await this.processor(r),i=await this.model({pixel_values:s}),a=this.model.config.id2label,o=[];for(const l of i.logits){const u=await Qn(new ee("float32",He(l.data),l.dims),n),c=u[0].tolist(),d=u[1].tolist().map((f,m)=>({label:a?a[f]:`LABEL_${f}`,score:c[m]}));o.push(d)}return Array.isArray(e)?o:o[0]}}class KT extends Re{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:s=.8,label_ids_to_fuse:i=null,target_sizes:a=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 u=await Yt(e),c=u.map(v=>[v.height,v.width]),{pixel_values:p,pixel_mask:d}=await this.processor(u),f=await this.model({pixel_values:p,pixel_mask:d});let m=null;if(o!==null)m=this.subtasks_mapping[o];else for(let[v,y]of Object.entries(this.subtasks_mapping))if(y in this.processor.feature_extractor){m=this.processor.feature_extractor[y].bind(this.processor.feature_extractor),o=v;break}const g=this.model.config.id2label,w=[];if(o==="panoptic"||o==="instance"){const v=m(f,n,r,s,i,a??c)[0],y=v.segmentation;for(const $ of v.segments_info){const k=new Uint8ClampedArray(y.data.length);for(let T=0;Tr.replace("{}",d)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(i),u=await this.model({...o,pixel_values:l}),c=this.model.config.model_type==="siglip"?d=>d.sigmoid().data:d=>He(d.data),p=[];for(const d of u.logits_per_image){const m=[...c(d)].map((g,w)=>({score:g,label:n[w]}));m.sort((g,w)=>w.score-g.score),p.push(m)}return s?p:p[0]}}class QT extends Re{constructor(e){super(e)}async _call(e,{threshold:n=.9,percentage:r=!1}={}){const s=Array.isArray(e);if(s&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const i=await Yt(e),a=r?null:i.map(f=>[f.height,f.width]),{pixel_values:o,pixel_mask:l}=await this.processor(i),u=await this.model({pixel_values:o,pixel_mask:l}),c=this.processor.feature_extractor.post_process_object_detection(u,n,a),p=this.model.config.id2label,d=c.map(f=>f.boxes.map((m,g)=>({score:f.scores[g],label:p[f.classes[g]],box:U_(m,!r)})));return s?d:d[0]}}class YT extends Re{constructor(e){super(e)}async _call(e,n,{threshold:r=.1,top_k:s=null,percentage:i=!1}={}){const a=Array.isArray(e),o=await Yt(e),l=this.tokenizer(n,{padding:!0,truncation:!0}),u=await this.processor(o),c=[];for(let p=0;p({score:w.scores[$],label:n[w.classes[$]],box:U_(y,!i)})).sort((y,$)=>$.score-y.score);s!==null&&(v=v.slice(0,s)),c.push(v)}return a?c:c[0]}}class ZT extends Re{constructor(e){super(e)}async _call(e,n,r={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class JT extends Re{constructor(n){super(n);A(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=n.vocoder??null}async _call(n,{speaker_embeddings:r=null}={}){return this.processor?this._call_text_to_spectrogram(n,{speaker_embeddings:r}):this._call_text_to_waveform(n)}async _call_text_to_waveform(n){const r=this.tokenizer(n,{padding:!0,truncation:!0}),{waveform:s}=await this.model(r),i=this.model.config.sampling_rate;return{audio:s.data,sampling_rate:i}}async _call_text_to_spectrogram(n,{speaker_embeddings:r}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await In.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof r=="string"||r instanceof URL)&&(r=new Float32Array(await(await fetch(r)).arrayBuffer())),r instanceof Float32Array)r=new ee("float32",r,[1,r.length]);else if(!(r instanceof ee))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:s}=this.tokenizer(n,{padding:!0,truncation:!0}),{waveform:i}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return{audio:i.data,sampling_rate:a}}}class eM extends Re{constructor(e){super(e)}async _call(e){const n=await Yt(e),r=await this.processor(n),s=await this.model(r),i=[];for(const a of s.reconstruction){const o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");i.push(at.fromTensor(o))}return i.length>1?i:i[0]}}class tM extends Re{constructor(e){super(e)}async _call(e){const n=await Yt(e),r=await this.processor(n),{predicted_depth:s}=await this.model(r),i=[];for(let a=0;a1?i:i[0]}}const q_=Object.freeze({"text-classification":{tokenizer:qe,pipeline:PT,model:ho,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:qe,pipeline:BT,model:a_,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:qe,pipeline:RT,model:c_,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:qe,pipeline:FT,model:d_,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:qe,pipeline:DT,model:Ks,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:qe,pipeline:V_,model:Ks,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:qe,pipeline:go,model:Ks,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:qe,pipeline:NT,model:u_,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:qe,pipeline:LT,model:ho,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:jT,model:b_,processor:Qe,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:qe,pipeline:qT,model:In,processor:Qe,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:qe,pipeline:GT,model:[i_,y_],processor:Qe,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:qe,pipeline:JT,model:[l_,o_],processor:[Qe,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:qe,pipeline:WT,model:p_,processor:Qe,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:HT,model:h_,processor:Qe,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:KT,model:[f_,m_,g_],processor:Qe,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:qe,pipeline:XT,model:In,processor:Qe,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:QT,model:__,processor:Qe,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:qe,pipeline:YT,model:w_,processor:Qe,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:qe,pipeline:ZT,model:x_,processor:Qe,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:eM,model:$_,processor:Qe,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:tM,model:k_,processor:Qe,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:qe,pipeline:UT,model:In,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:Qe,pipeline:VT,model:[S_,In],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),nM=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function rM(t,e=null,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:i=!1,revision:a="main",device:o=null,dtype:l=null,model_file_name:u=null,session_options:c={}}={}){t=nM[t]??t;const p=q_[t.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(q_)}]`);e||(e=p.default.model,console.log(`No model specified. Using default model: "${e}".`));const d={progress_callback:n,config:r,cache_dir:s,local_files_only:i,revision:a,device:o,dtype:l,model_file_name:u,session_options:c},f=new Map([["tokenizer",p.tokenizer],["model",p.model],["processor",p.processor]]),m=await sM(f,e,d);m.task=t,Ln(n,{status:"ready",task:t,model:e});const g=p.pipeline;return new g(m)}async function sM(t,e,n){const r=Object.create(null),s=[];for(const[i,a]of t.entries()){if(!a)continue;let o;Array.isArray(a)?o=new Promise(async(l,u)=>{var p,d;let c;for(const f of a){if(f===null){l(null);return}try{l(await f.from_pretrained(e,n));return}catch(m){if((p=m.message)!=null&&p.includes("Unsupported model type"))c=m;else if((d=m.message)!=null&&d.includes("Could not locate file"))c=m;else{u(m);return}}}u(c)}):o=a.from_pretrained(e,n),r[i]=o,s.push(o)}await Promise.all(s);for(const[i,a]of Object.entries(r))r[i]=await a;return r}bn.IS_PROCESS_AVAILABLE;const aM={webgpu:{dtype:{encoder_model:"fp32",decoder_model_merged:"q4"},device:"webgpu"},wasm:{dtype:"q8",device:"wasm"}};class Pn{static async getInstance(e=null,n="webgpu"){return this.asr_instance??(this.asr_instance=rM("automatic-speech-recognition",this.asr_model_id,{...aM[n],progress_callback:e})),this.segmentation_processor??(this.segmentation_processor=Qe.from_pretrained(this.segmentation_model_id,{progress_callback:e})),this.segmentation_instance??(this.segmentation_instance=v_.from_pretrained(this.segmentation_model_id,{device:"wasm",dtype:"fp32",progress_callback:e})),Promise.all([this.asr_instance,this.segmentation_processor,this.segmentation_instance])}}A(Pn,"asr_model_id","onnx-community/whisper-base_timestamped"),A(Pn,"asr_instance",null),A(Pn,"segmentation_model_id","onnx-community/pyannote-segmentation-3.0"),A(Pn,"segmentation_instance",null),A(Pn,"segmentation_processor",null);async function iM({device:t}){self.postMessage({status:"loading",data:`Loading models (${t})...`});const[e,n,r]=await Pn.getInstance(s=>{self.postMessage(s)},t);console.log("helllllo"),t==="webgpu"&&(self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."}),await e(new Float32Array(16e3),{language:"en"})),self.postMessage({status:"loaded"})}async function oM(t,e,n){const r=await t(n),{logits:s}=await e(r),i=t.post_process_speaker_diarization(s,n.length)[0];for(const a of i)a.label=e.config.id2label[a.id];return i}async function lM({audio:t,language:e}){const[n,r,s]=await Pn.getInstance(),i=performance.now(),[a,o]=await Promise.all([n(t,{language:e,return_timestamps:"word",chunk_length_s:30}),oM(r,s,t)]);console.table(o,["start","end","id","label","confidence"]);const l=performance.now();self.postMessage({status:"complete",result:{transcript:a,segments:o},time:l-i})}self.addEventListener("message",async t=>{const{type:e,data:n}=t.data;switch(e){case"load":iM(n);break;case"run":lM(n);break}})})();