var ZC=Object.defineProperty;var JC=(ke,Wt,Un)=>Wt in ke?ZC(ke,Wt,{enumerable:!0,configurable:!0,writable:!0,value:Un}):ke[Wt]=Un;var A=(ke,Wt,Un)=>JC(ke,typeof Wt!="symbol"?Wt+"":Wt,Un);(function(){"use strict";var R_;var ke={},Wt=Object.freeze({__proto__:null,default:ke});const Un="3.0.0-alpha.10",Qr=typeof self<"u",sy=Qr&&self.constructor.name==="DedicatedWorkerGlobalScope",No=Qr&&"caches"in self,iy=typeof navigator<"u"&&"gpu"in navigator,ay=typeof navigator<"u"&&"ml"in navigator,Lo=typeof process<"u",oy=Lo&&((R_=process==null?void 0:process.release)==null?void 0:R_.name)==="node",Yr=!qo(ke),Uo=!qo(ke),bn=Object.freeze({IS_BROWSER_ENV:Qr,IS_WEBWORKER_ENV:sy,IS_WEB_CACHE_AVAILABLE:No,IS_WEBGPU_AVAILABLE:iy,IS_WEBNN_AVAILABLE:ay,IS_PROCESS_AVAILABLE:Lo,IS_NODE_ENV:oy,IS_FS_AVAILABLE:Yr,IS_PATH_AVAILABLE:Uo}),di=Yr&&Uo,Vo=di?ke.dirname(ke.dirname(ke.fileURLToPath(self.location.href))):"./",ly=di?ke.join(Vo,"/.cache/"):null,jo="/models/",uy=di?ke.join(Vo,jo):jo,tt={version:Un,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Qr,localModelPath:uy,useFS:Yr,useBrowserCache:No,useFSCache:Yr,cacheDir:ly,useCustomCache:!1,customCache:null};function qo(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 Vn(t,e){t&&t(e)}function dy(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e]))}function Go(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cy(t){return Number.isInteger(t)||typeof t=="bigint"}function Wo(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 py(...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 hy={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(a=>{s.enqueue(new Uint8Array(a)),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",hy[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 ci(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&&!ci(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};`),ci(t,["http:","https:"],["huggingface.co","hf.co"])){const i=(Kt==null?void 0:Kt.HF_TOKEN)??(Kt==null?void 0:Kt.HF_ACCESS_TOKEN);i&&s.set("Authorization",`Bearer ${i}`)}return fetch(t,{headers:s})}else return fetch(t)}const fy={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 my(t,e,n){if(!n)return null;const r=fy[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${r}: "${e}".`)}class Ho{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(a){console.warn("An error occurred while writing the file to cache:",a)}}}async function gy(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`).");Vn(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 Ho(r.cache_dir??tt.cacheDir)),!s&&tt.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const a=r.revision??"main";let i=ns(t,e),o=ns(tt.localModelPath,i),l=ns(tt.remoteHost,tt.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(a)),e),u=a==="main"?i:ns(t,a,e),c,p=s instanceof Ho?u:l,d=!1,f;s&&(f=await gy(s,o,p));const m=f!==void 0;if(f===void 0){if(tt.allowLocalModels)if(ci(i,["http:","https:"])){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`)}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 my(f.status,l,n);c=p}d=s&&typeof Response<"u"&&f instanceof Response&&f.status===200}Vn(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()),Vn(r.progress_callback,{...g,progress:100,loaded:w.length,total:w.length})):w=await _y(f,v=>{Vn(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}.`)}),Vn(r.progress_callback,{status:"done",name:t,file:e}),w}async function nn(t,e,n=!0,r={}){let s=await ts(t,e,n,r);if(s===null)return{};let i=new TextDecoder("utf-8").decode(s);return JSON.parse(i)}async function _y(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),a=0;const i=t.body.getReader();async function o(){const{done:l,value:u}=await i.read();if(l)return;let c=a+u.length;if(c>r){r=c;let d=new Uint8Array(r);d.set(s),s=d}s.set(u,a),a=c;const p=a/r*100;return e({progress:p,loaded:a,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 wy(t,[e,n,r],[s,a],i="bilinear",o=!1){const l=a/r,u=s/n,c=new t.constructor(s*a*e),p=n*r,d=s*a;for(let f=0;f=0;--o)s[o]=l,r[o]=e[n[o]],l*=r[o];const a=n.map((o,l)=>s[n.indexOf(l)]),i=new t.constructor(t.length);for(let o=0;o=0;--u)l+=c%e[u]*a[u],c=Math.floor(c/e[u]);i[l]=t[o]}return[i,r]}function He(t){const e=dt(t)[0],n=t.map(a=>Math.exp(a-e)),r=n.reduce((a,i)=>a+i,0);return n.map(a=>a/r)}function by(t){return He(t).map(r=>Math.log(r))}function Ko(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 Xo(t){return t>0&&(t&t-1)===0}class Qo{constructor(e){if(this.size=e|0,this.size<=1||!Xo(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;i>=2;i>>=2){o=s/i<<1;const d=o>>>2;for(l=0;l>>1,i>>>1)}else for(l=0,u=0;l>>1,i>>>1,r)}const p=this.table;for(i>>=2;i>=2;i>>=2){o=s/i<<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;a[m]=d*Math.cos(f),a[m+1]=d*Math.sin(f),i[m]=a[m],i[m+1]=-a[m+1]}this._slicedChirpBuffer=a.subarray(n,r),this._f=new Qo(s>>1),this._f.transform(this._chirpBuffer,i)}_transform(e,n,r){const s=this._buffer1,a=this._buffer2,i=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[i++]=t[l]}r.sort(),n[a]=r[s]}return n}function ur(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}function ky(t){const e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function Sy(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 a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let c=1;c0||o>0;)switch(l.push(i-1),u.push(o-1),a[i][o]){case 0:--i,--o;break;case 1:--i;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${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 pi=Object.defineProperty,Ey=Object.getOwnPropertyDescriptor,Ty=Object.getOwnPropertyNames,Cy=Object.prototype.hasOwnProperty,My=(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)pi(t,n,{get:e[n],enumerable:!0})},Ay=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ty(e))!Cy.call(t,s)&&s!==n&&pi(t,s,{get:()=>e[s],enumerable:!(r=Ey(e,s))||r.enumerable});return t},rs=t=>Ay(pi({},"__esModule",{value:!0}),t),cr,rn,vn,Yo,hi,fi=W(()=>{cr=new Map,rn=[],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=rn.indexOf(t);s!==-1&&rn.splice(s,1);for(let a=0;a{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}}},hi=async t=>{let e=t.executionProviders||[],n=e.map(l=>typeof l=="string"?l:l.name),r=n.length===0?rn:n,s,a=[],i=new Set;for(let l of r){let u=await Yo(l);typeof u=="string"?a.push({name:l,err:u}):(s||(s=u),s===u&&i.add(l))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of a)n.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let o=e.filter(l=>i.has(typeof l=="string"?l:l.name));return[s,new Proxy(t,{get:(l,u)=>u==="executionProviders"?o:Reflect.get(l,u)})]}}),Iy=W(()=>{fi()}),Zo,zy=W(()=>{Zo="1.20.0-dev.20240827-5d54dc1462"}),mi,gt,Jo=W(()=>{zy(),mi="warning",gt={wasm:{},webgl:{},webgpu:{},versions:{common:Zo},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}`);mi=t}},get logLevel(){return mi}},Object.defineProperty(gt,"logLevel",{enumerable:!0})}),Te,Oy=W(()=>{Jo(),Te=gt}),el,tl,Py=W(()=>{el=(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,a;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],a=t.dims[3]):(s=t.dims[3],a=t.dims[2]);let i=(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=a*s,p=0,d=c,f=c*2,m=-1;i==="RGBA"?(p=0,d=c,f=c*2,m=c*3):i==="RGB"?(p=0,d=c,f=c*2):i==="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,a,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],a=t.dims[1],i=t.dims[3]):(s=t.dims[3],a=t.dims[2],i=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=a*s;if(e!==void 0&&(e.format!==void 0&&i===4&&e.format!=="RGBA"||i===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,a);for(let E=0;E{_i(),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},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[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,a=typeof t=="string",i,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),i=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),i=f.getImageData(0,0,p,c).data;else throw new Error("Can not access image data")}else i=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),i=p.getImageData(0,0,f,d).data,o.height=d,o.width=f,ss(i,o)}else throw new Error("Can not access image data")}else{if(a)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(i!==void 0)return ss(i,o);throw new Error("Input data provided is not supported - aborted tensor creation")},rl=(t,e)=>{let{width:n,height:r,download:s,dispose:a}=e,i=[1,r,n,4];return new St({location:"texture",type:"float32",texture:t,dims:i,download:s,dispose:a})},sl=(t,e)=>{let{dataType:n,dims:r,download:s,dispose:a}=e;return new St({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:s,dispose:a})},il=(t,e,n)=>new St({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]})}),xn,pr,gi,al,Ry=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"]]),gi=!1,al=()=>{if(!gi){gi=!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)}}}),ol,ll,Dy=W(()=>{_i(),ol=t=>{let e=1;for(let n=0;n{switch(t.location){case"cpu":return new St(t.type,t.data,e);case"cpu-pinned":return new St({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new St({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new St({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),St,_i=W(()=>{Py(),By(),Ry(),Dy(),St=class{constructor(t,e,n){al();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 i=xn.get(r);if(!i)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,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.");i=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"?i=l.from(e,BigInt):i=l.from(e)}else if(e instanceof l)i=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",i=t;else if(l==="boolean")r="bool",i=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,i=t}if(o===void 0)o=[i.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");s=o,this.cpuData=i,this.dataLocation="cpu"}let a=ol(s);if(this.cpuData&&a!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=s,this.size=a}static async fromImage(t,e){return nl(t,e)}static fromTexture(t,e){return rl(t,e)}static fromGpuBuffer(t,e){return sl(t,e)}static fromPinnedBuffer(t,e,n){return il(t,e,n)}toDataURL(t){return el(this,t)}toImageData(t){return tl(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 ll(this,t)}}}),nt,wi=W(()=>{_i(),nt=St}),hr,yi,Et,_t,ul=W(()=>{Jo(),hr=(t,e)=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||console.timeStamp(`${t}::ORT::${e}`)},yi=(t,e)=>{var s;let n=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],r=!1;for(let a=0;a{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||yi("BEGIN",t)},_t=t=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||yi("END",t)}}),dl,Fy=W(()=>{fi(),wi(),ul(),dl=class ty{constructor(e){this.handler=e}async run(e,n,r){Et();let s={},a={};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 i=!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.");i=!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)a=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,i=!1,s[p]=d)}if(u){if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else a=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(i)for(let u of this.outputNames)s[u]=null;let o=await this.handler.run(e,s,a),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){Et();let a,i={};if(typeof e=="string"){if(a=e,typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(a=e,typeof n=="object"&&n!==null)i=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)i=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)i=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.");a=new Uint8Array(c,p,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await hi(i),u=await o.createInferenceSessionHandler(a,l);return _t(),new ty(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),bi,Ny=W(()=>{Fy(),bi=dl}),Ly=W(()=>{}),Uy=W(()=>{}),Vy=W(()=>{}),jy=W(()=>{}),cl,pl,qy=W(()=>{fi(),wi(),cl="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",pl=class ny{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||"",a=n||{},[i,o]=await hi(a);if(i.createTrainingSessionHandler){let l=await i.createTrainingSessionHandler(e.checkpointState,e.trainModel,r,s,o);return new ny(l,!!e.optimizerModel,!!e.evalModel)}else throw new Error(cl)}typeNarrowingForRunStep(e,n,r,s,a){let i={},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}.`);i[u]=null}if(typeof a=="object"&&a!==null)o=a;else if(typeof a<"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,i[p]=d)}if(u){if(typeof a=="object"&&a!==null)o=a;else if(typeof a<"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)i[u]=null;return[i,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,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,n,r),i=await this.handler.runTrainStep(e,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}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,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,n,r),i=await this.handler.runEvalStep(e,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}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()}}}),vi,Gy=W(()=>{qy(),vi=pl}),hl={};dr(hl,{InferenceSession:()=>bi,TRACE:()=>hr,TRACE_FUNC_BEGIN:()=>Et,TRACE_FUNC_END:()=>_t,Tensor:()=>nt,TrainingSession:()=>vi,env:()=>Te,registerBackend:()=>vn});var Tt=W(()=>{Iy(),Oy(),Ny(),wi(),Ly(),Uy(),ul(),Vy(),jy(),Gy()}),xi=W(()=>{}),fl={};dr(fl,{default:()=>ml});var $i,ki,ml,Wy=W(()=>{var t;xf(),qn(),is(),$i="ort-wasm-proxy-worker",ki=((t=globalThis.self)==null?void 0:t.name)===$i,ki&&(self.onmessage=e=>{let{type:n,in:r}=e.data;try{switch(n){case"init-wasm":Ai(r.wasm).then(()=>{Ia(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:a}=r;za(a,s).then(()=>{postMessage({type:n})},i=>{postMessage({type:n,err:i})});break}case"copy-from":{let{buffer:s}=r,a=Es(s);postMessage({type:n,out:a});break}case"create":{let{model:s,options:a}=r;Oa(s,a).then(i=>{postMessage({type:n,out:i})},i=>{postMessage({type:n,err:i})});break}case"release":Pa(r),postMessage({type:n});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:o,options:l}=r;Ra(s,a,i,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},Fa([...i,...u]))},u=>{postMessage({type:n,err:u})});break}case"end-profiling":Da(r),postMessage({type:n});break;default:}}catch(s){postMessage({type:n,err:s})}}),ml=ki?null:e=>new Worker(e??jn,{type:"module",name:$i})}),gl={};dr(gl,{default:()=>_l});var Si,Ei,_l,Hy=W(()=>{var t;Ei=(Si=self.location.href,async function(e={}){function n(){return z.buffer!=Y.buffer&&Oe(),Y}function r(){return z.buffer!=Y.buffer&&Oe(),te}function s(){return z.buffer!=Y.buffer&&Oe(),O}function a(){return z.buffer!=Y.buffer&&Oe(),q}function i(){return z.buffer!=Y.buffer&&Oe(),ae}function o(){return z.buffer!=Y.buffer&&Oe(),ge}function l(){return z.buffer!=Y.buffer&&Oe(),ve}function u(){return z.buffer!=Y.buffer&&Oe(),Pt}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)=>(...C)=>{let D=qt,V=x==null?void 0:x();C=b(...C);let Q=x==null?void 0:x();return V!==Q&&(b=Q,S(V),x=S=null),qt!=D?new Promise((Z,le)=>{Io={resolve:Z,reject:le}}):C},_=b=>async(...x)=>{var S;try{if(d.Eb)throw Error("Session already started");let C=d.Eb={bc:x[0],errors:[]},D=await b(...x);if(d.Eb!==C)throw Error("Session mismatch");(S=d.Mb)==null||S.flush();let V=C.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,C,D)=>b.registerBuffer(x,S,C,D),d.jsepGetBuffer=x=>b.getBuffer(x),d.jsepCreateDownloader=(x,S,C)=>b.createDownloader(x,S,C),d.jsepOnReleaseSession=x=>{b.onReleaseSession(x)},d.jsepOnRunStart=x=>b.onRunStart(x)}};var $,k,E=Object.assign({},d),T="./this.program",M=(h,_)=>{throw _},R="";(m||g)&&(g?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),Si&&(R=Si),R=R.startsWith("blob:")?"":R.substr(0,R.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 L,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=C=>S.push(C),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let C of S)h(C);self.onmessage=h};for(let C of b.handlers)d[C]&&!d[C].proxy||(d[C]=(...D)=>{postMessage({Lb:"callHandler",kc:C,args:D})},C=="print"&&(X=d[C]),C=="printErr"&&(H=d[C]));z=b.wasmMemory,Oe(),ee(b.wasmModule)}else if(x==="run"){Bo(b.pthread_ptr,0,0,1,0,0),Co(b.pthread_ptr),DT(),W_(),ne||(jw(),ne=!0);try{FT(b.start_routine,b.arg)}catch(S){if(S!="unwind")throw S}}else x==="cancel"?lr()&&oi(-1):b.target!=="setimmediate"&&(x==="checkMailbox"?ne&&Zs():x&&(H(`worker: received unknown command ${x}`),H(b)))}catch(S){throw qw(),S}};var ee,ne=!1;H=function(..._){_=_.join(" "),console.error(_)},self.alert=function(..._){postMessage({Lb:"alert",text:_.join(" "),mc:lr()})},d.instantiateWasm=(_,b)=>new Promise(x=>{ee=S=>{S=new WebAssembly.Instance(S,U_()),b(S),x()}}),self.onunhandledrejection=_=>{throw _.reason||_},self.onmessage=h}d.wasmBinary&&(L=d.wasmBinary);var z,N,B,Y,te,O,q,ae,ge,ve,Ee,ut,Pt,Ne=!1;function Oe(){var h=z.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=ae=new Int32Array(h),d.HEAPU32=ge=new Uint32Array(h),d.HEAPF32=ve=new Float32Array(h),d.HEAPF64=Pt=new Float64Array(h),d.HEAP64=Ee=new BigInt64Array(h),d.HEAPU64=ut=new BigUint64Array(h)}if(!w){if(!((z=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 Bt=[],Fe=[],Ve=[],at=0,Rt=null;function Dn(){if(--at==0&&Rt){var h=Rt;Rt=null,h()}}function Jt(h){throw H(h="Aborted("+h+")"),Ne=!0,B=1,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),p(h),h}var go,D_=h=>h.startsWith("data:application/octet-stream;base64,"),F_=h=>h.startsWith("file://");function N_(h){if(h==go&&L)return new Uint8Array(L);if(k)return k(h);throw"both async and sync fetching of the wasm failed"}function L_(h,_,b){return function(x){if(!L&&(m||g)){if(typeof fetch=="function"&&!F_(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(()=>N_(x));if($)return new Promise((S,C)=>{$(x,D=>S(new Uint8Array(D)),C)})}return Promise.resolve().then(()=>N_(x))}(h).then(x=>WebAssembly.instantiate(x,_)).then(b,x=>{H(`failed to asynchronously prepare wasm: ${x}`),Jt(x)})}function U_(){return{a:{M:RT,za:BT,b:LT,$:Q_,z:J_,pa:ew,X:nw,Z:rw,qa:sw,na:iw,ga:aw,ma:ow,J:lw,Y:uw,V:dw,oa:cw,W:pw,va:UT,D:VT,P:jT,O:GT,C:HT,s:KT,p:XT,E:QT,y:rC,Q:sC,ta:iC,ja:aC,T:oC,aa:lC,F:uC,ia:Co,sa:dC,u:cC,B:fC,o:mC,m:_C,c:Eo,n:wC,k:vC,Aa:xC,r:$C,g:kC,v:SC,l:EC,f:TC,i:CC,j:MC,h:AC,e:IC,da:zC,ea:OC,fa:PC,ba:Ew,ca:Tw,S:BC,d:RC,N:DC,G:FC,K:NC,w:LC,ra:UC,U:VC,t:Mw,x:jC,L:qC,R:GC,ya:WC,xa:HC,ka:zw,la:Ow,_:vo,A:Pw,I:Bw,ha:Rw,H:Dw,a:z,wa:bo,ua:Lw,q:QC}}}var _o={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(i().subarray(x>>>0,S>>>0)):[]})},862145:(h,_,b,x,S)=>{d.jb("ReduceMax",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},862303:(h,_,b,x,S)=>{d.jb("ReduceMin",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},862461:(h,_,b,x,S)=>{d.jb("ReduceProd",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},862620:(h,_,b,x,S)=>{d.jb("ReduceSum",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},862778:(h,_,b,x,S)=>{d.jb("ReduceL1",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},862935:(h,_,b,x,S)=>{d.jb("ReduceL2",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},863092:(h,_,b,x,S)=>{d.jb("ReduceLogSum",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},863253:(h,_,b,x,S)=>{d.jb("ReduceSumSquare",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},863417:(h,_,b,x,S)=>{d.jb("ReduceLogSumExp",h,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:x?Array.from(i().subarray(x>>>0,S>>>0)):[]})},863581:h=>{d.jb("Where",h,void 0)},863634:(h,_,b)=>{d.jb("Transpose",h,{perm:_?Array.from(i().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,C,D,V,Q,Z,le,we,be,P,_e)=>{d.jb("ConvTranspose",h,{format:Q?"NHWC":"NCHW",autoPad:_,dilations:[b],group:x,kernelShape:[S],pads:[C,D],strides:[V],wIsConst:()=>!!n()[Z>>>0],outputPadding:le?Array.from(i().subarray(le>>>0,we>>>0)):[],outputShape:be?Array.from(i().subarray(be>>>0,P>>>0)):[],activation:Ge(_e)})},864409:(h,_,b,x,S,C,D,V,Q,Z,le,we,be,P)=>{d.jb("ConvTranspose",h,{format:V?"NHWC":"NCHW",autoPad:_,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:x,kernelShape:Array.from(i().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(i().subarray(C>>>0,4+(C>>>0)>>>0)),strides:Array.from(i().subarray(D>>>0,2+(D>>>0)>>>0)),wIsConst:()=>!!n()[Q>>>0],outputPadding:Z?Array.from(i().subarray(Z>>>0,le>>>0)):[],outputShape:we?Array.from(i().subarray(we>>>0,be>>>0)):[],activation:Ge(P)})},864974:(h,_,b,x,S,C,D,V,Q,Z,le,we,be,P,_e)=>{d.jb("ConvTranspose",h,{format:Q?"NHWC":"NCHW",autoPad:_,dilations:[b],group:x,kernelShape:[S],pads:[C,D],strides:[V],wIsConst:()=>!!n()[Z>>>0],outputPadding:le?Array.from(i().subarray(le>>>0,we>>>0)):[],outputShape:be?Array.from(i().subarray(be>>>0,P>>>0)):[],activation:Ge(_e)})},865375:(h,_,b,x,S,C,D,V,Q,Z,le,we,be,P)=>{d.jb("ConvTranspose",h,{format:V?"NHWC":"NCHW",autoPad:_,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:x,kernelShape:Array.from(i().subarray(S>>>0,2+(S>>>0)>>>0)),pads:Array.from(i().subarray(C>>>0,4+(C>>>0)>>>0)),strides:Array.from(i().subarray(D>>>0,2+(D>>>0)>>>0)),wIsConst:()=>!!n()[Q>>>0],outputPadding:Z?Array.from(i().subarray(Z>>>0,le>>>0)):[],outputShape:we?Array.from(i().subarray(we>>>0,be>>>0)):[],activation:Ge(P)})},865940:(h,_)=>{d.jb("GlobalAveragePool",h,{format:_?"NHWC":"NCHW"})},866031:(h,_,b,x,S,C,D,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:C?Array.from(i().subarray(C>>>0,D>>>0)):[],kernel_shape:V?Array.from(i().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(i().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(i().subarray(we>>>0,be>>>0)):[]})},866446:(h,_)=>{d.jb("GlobalAveragePool",h,{format:_?"NHWC":"NCHW"})},866537:(h,_,b,x,S,C,D,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:C?Array.from(i().subarray(C>>>0,D>>>0)):[],kernel_shape:V?Array.from(i().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(i().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(i().subarray(we>>>0,be>>>0)):[]})},866952:(h,_)=>{d.jb("GlobalMaxPool",h,{format:_?"NHWC":"NCHW"})},867039:(h,_,b,x,S,C,D,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:C?Array.from(i().subarray(C>>>0,D>>>0)):[],kernel_shape:V?Array.from(i().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(i().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(i().subarray(we>>>0,be>>>0)):[]})},867450:(h,_)=>{d.jb("GlobalMaxPool",h,{format:_?"NHWC":"NCHW"})},867537:(h,_,b,x,S,C,D,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:C?Array.from(i().subarray(C>>>0,D>>>0)):[],kernel_shape:V?Array.from(i().subarray(V>>>0,Q>>>0)):[],pads:Z?Array.from(i().subarray(Z>>>0,le>>>0)):[],strides:we?Array.from(i().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(i().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,C,D,V,Q,Z,le)=>{d.jb("Resize",h,{antialias:_,axes:b?Array.from(i().subarray(b>>>0,x>>>0)):[],coordinateTransformMode:Ge(S),cubicCoeffA:C,excludeOutside:D,extrapolationValue:V,keepAspectRatioPolicy:Ge(Q),mode:Ge(Z),nearestMode:Ge(le)})},869135:(h,_,b,x,S,C,D)=>{d.jb("Slice",h,{starts:_?Array.from(i().subarray(_>>>0,b>>>0)):[],ends:x?Array.from(i().subarray(x>>>0,S>>>0)):[],axes:C?Array.from(i().subarray(C>>>0,D>>>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(i().subarray(x>>>0,S>>>0)):[]})},869892:(h,_,b,x,S,C)=>{d.jb("BatchNormalization",h,{epsilon:_,momentum:b,spatial:!!S,trainingMode:!!x,format:C?"NHWC":"NCHW"})},870061:(h,_,b,x,S,C)=>{d.jb("BatchNormalization",h,{epsilon:_,momentum:b,spatial:!!S,trainingMode:!!x,format:C?"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,C,D,V,Q)=>{d.jb("Attention",h,{numHeads:_,isUnidirectional:b,maskFilterValue:x,scale:S,doRotary:C,qkvHiddenSizes:D?Array.from(i().subarray(Number(V)>>>0,Number(V)+D>>>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,C,D,V,Q,Z,le,we,be,P,_e,Pe)=>{d.jb("Conv",h,{format:we?"NHWC":"NCHW",auto_pad:_,dilations:b?Array.from(i().subarray(b>>>0,x>>>0)):[],group:S,kernel_shape:C?Array.from(i().subarray(C>>>0,D>>>0)):[],pads:V?Array.from(i().subarray(V>>>0,Q>>>0)):[],strides:Z?Array.from(i().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,C)=>{d.jb("MatMulNBits",h,{k:_,n:b,accuracyLevel:x,bits:S,blockSize:C})},871871:(h,_,b,x,S,C)=>{d.jb("MultiHeadAttention",h,{numHeads:_,isUnidirectional:b,maskFilterValue:x,scale:S,doRotary:C})},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 BT(h,_,b){return vw(async()=>{await d.Wb(h,_,b)})}function RT(){return typeof wasmOffsetConverter<"u"}function wo(h){this.name="ExitStatus",this.message=`Program terminated with exit(${h})`,this.status=h}var yo=h=>{h.terminate(),h.onmessage=()=>{}},V_=h=>{gn.length==0&&(K_(),H_(gn[0]));var _=gn.pop();if(!_)return 6;Nn.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},Fn=0,Me=(h,_,...b)=>{for(var x=2*b.length,S=Fo(),C=Do(8*x),D=C>>>3,V=0;V>>0]=Q)}return h=Gw(h,0,x,C,_),li(S),h};function bo(h){if(w)return Me(0,1,h);if(B=h,!(0{if(B=h,w)throw j_(h),"unwind";bo(h)},gn=[],Nn=[],q_=[],Vt={},G_=h=>{var _=h.Ab;delete Vt[_],gn.push(h),Nn.splice(Nn.indexOf(h),1),h.Ab=0,Ro(_)};function W_(){q_.forEach(h=>h())}var H_=h=>new Promise(_=>{h.onmessage=S=>{var C=(S=S.data).cmd;if(S.targetThread&&S.targetThread!=lr()){var D=Vt[S.targetThread];D?D.postMessage(S,S.transferList):H(`Internal error! Worker sent a message "${C}" to target pthread ${S.targetThread}, but that thread no longer exists!`)}else C==="checkMailbox"?Zs():C==="spawnThread"?V_(S):C==="cleanupThread"?G_(Vt[S.thread]):C==="killThread"?(S=S.thread,C=Vt[S],delete Vt[S],yo(C),Ro(S),Nn.splice(Nn.indexOf(C),1),C.Ab=0):C==="cancelThread"?Vt[S.thread].postMessage({cmd:"cancel"}):C==="loaded"?(h.loaded=!0,_(h)):C==="alert"?alert(`Thread ${S.threadId}: ${S.text}`):S.target==="setimmediate"?h.postMessage(S):C==="callHandler"?d[S.handler](...S.args):C&&H(`worker sent an unknown command ${C}`)},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:z,wasmModule:N})});function K_(){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],Hw(_,_-h),li(_)},FT=(h,_)=>{Fn=0,h=Kw(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 X_(h,_,b,x){return w?Me(2,1,h,_,b,x):Q_(h,_,b,x)}function Q_(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?X_(h,_,b,x):(h={cc:b,Ab:h,Pb:x,ic:S},w?(h.Lb="spawnThread",postMessage(h,S),0):V_(h))}var Y_=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Z_=(h,_,b)=>{var x=(_>>>=0)+b;for(b=_;h[b]&&!(b>=x);)++b;if(16(S=(240&S)==224?(15&S)<<12|C<<6|D:(7&S)<<18|C<<12|D<<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)?Z_(r(),h,_):"";function J_(h,_,b){return w?Me(3,1,h,_,b):0}function ew(h,_){if(w)return Me(4,1,h,_)}var xo=h=>{for(var _=0,b=0;b=x?_++:2047>=x?_+=2:55296<=x&&57343>=x?(_+=4,++b):_+=3}return _},tw=(h,_,b,x)=>{if(!(0>>=0;x=b+x-1;for(var C=0;C=D&&(D=65536+((1023&D)<<10)|1023&h.charCodeAt(++C)),127>=D){if(b>=x)break;_[b++>>>0]=D}else{if(2047>=D){if(b+1>=x)break;_[b++>>>0]=192|D>>6}else{if(65535>=D){if(b+2>=x)break;_[b++>>>0]=224|D>>12}else{if(b+3>=x)break;_[b++>>>0]=240|D>>18,_[b++>>>0]=128|D>>12&63}_[b++>>>0]=128|D>>6&63}_[b++>>>0]=128|63&D}}return _[b>>>0]=0,b-S},ar=(h,_,b)=>tw(h,r(),_,b);function nw(h,_){if(w)return Me(5,1,h,_)}function rw(h,_,b){if(w)return Me(6,1,h,_,b)}function sw(h,_,b){return w?Me(7,1,h,_,b):0}function iw(h,_){if(w)return Me(8,1,h,_)}function aw(h,_,b){if(w)return Me(9,1,h,_,b)}function ow(h,_,b,x){if(w)return Me(10,1,h,_,b,x)}function lw(h,_,b,x){if(w)return Me(11,1,h,_,b,x)}function uw(h,_,b,x){if(w)return Me(12,1,h,_,b,x)}function dw(h){if(w)return Me(13,1,h)}function cw(h,_){if(w)return Me(14,1,h,_)}function pw(h,_,b){if(w)return Me(15,1,h,_,b)}var hw,_n,UT=()=>{Jt("")},jt=h=>{for(var _="";r()[h>>>0];)_+=hw[r()[h++>>>0]];return _},$o={},ko={};function en(h,_,b={}){if(!("argPackAdvance"in _))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(x,S,C={}){var D=S.name;if(!x)throw new _n(`type "${D}" must have a positive integer typeid pointer`);if(ko.hasOwnProperty(x)){if(C.Rb)return;throw new _n(`Cannot register type '${D}' twice`)}ko[x]=S,$o.hasOwnProperty(x)&&(S=$o[x],delete $o[x],S.forEach(V=>V()))}(h,_,b)}var fw=(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=>a()[x>>>1>>>0];case 4:return b?x=>i()[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 VT(h,_,b){b>>>=0,en(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:fw(_,b,_.indexOf("u")==-1),Db:null})}var wn=8;function jT(h,_,b,x){en(h>>>=0,{name:_=jt(_>>>0),fromWireType:function(S){return!!S},toWireType:function(S,C){return C?b:x},argPackAdvance:wn,readValueFromPointer:function(S){return this.fromWireType(r()[S>>>0])},Db:null})}var So=[],tn=[];function Eo(h){9<(h>>>=0)&&--tn[h+1]==0&&(tn[h]=void 0,So.push(h))}var $t=h=>{if(!h)throw new _n("Cannot use deleted val. handle = "+h);return tn[h]},kt=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let _=So.pop()||tn.length;return tn[_]=h,tn[_+1]=1,_}};function To(h){return this.fromWireType(o()[h>>>2>>>0])}var qT={name:"emscripten::val",fromWireType:h=>{var _=$t(h);return Eo(h),_},toWireType:(h,_)=>kt(_),argPackAdvance:wn,readValueFromPointer:To,Db:null};function GT(h){return en(h>>>0,qT)}var WT=(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 HT(h,_,b){b>>>=0,en(h>>>=0,{name:_=jt(_>>>0),fromWireType:x=>x,toWireType:(x,S)=>S,argPackAdvance:wn,readValueFromPointer:WT(_,b),Db:null})}function KT(h,_,b,x,S){if(h>>>=0,b>>>=0,_=jt(_>>>0),S===-1&&(S=4294967295),S=V=>V,x===0){var C=32-8*b;S=V=>V<>>C}var D=_.includes("unsigned")?function(V,Q){return Q>>>0}:function(V,Q){return Q};en(h,{name:_,fromWireType:S,toWireType:D,argPackAdvance:wn,readValueFromPointer:fw(_,b,x!==0),Db:null})}function XT(h,_,b){function x(C){var D=o()[C>>>2>>>0];return C=o()[C+4>>>2>>>0],new S(n().buffer,C,D)}var S=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][_];en(h>>>=0,{name:b=jt(b>>>0),fromWireType:x,argPackAdvance:wn,readValueFromPointer:x},{Rb:!0})}function QT(h,_){h>>>=0;var b=(_=jt(_>>>0))==="std::string";en(h,{name:_,fromWireType:function(x){var S=o()[x>>>2>>>0],C=x+4;if(b)for(var D=C,V=0;V<=S;++V){var Q=C+V;if(V==S||r()[Q>>>0]==0){if(D=Ge(D,Q-D),Z===void 0)var Z=D;else Z+="\0",Z+=D;D=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 C=typeof S=="string";if(!(C||S instanceof Uint8Array||S instanceof Uint8ClampedArray||S instanceof Int8Array))throw new _n("Cannot pass non-string to std::string");var D=b&&C?xo(S):S.length,V=ai(4+D+1),Q=V+4;if(o()[V>>>2>>>0]=D,b&&C)ar(S,Q,D+1);else if(C)for(C=0;C>>0]=Z}else for(C=0;C>>0]=S[C];return x!==null&&x.push(Gt,V),V},argPackAdvance:wn,readValueFromPointer:To,Db(x){Gt(x)}})}var mw=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,YT=(h,_)=>{for(var b=h>>1,x=b+_/2;!(b>=x)&&a()[b>>>0];)++b;if(32<(b<<=1)-h&&mw)return mw.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},ZT=(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]=C,_+=2}return s()[_>>>1>>>0]=0,_-x},JT=h=>2*h.length,eC=(h,_)=>{for(var b=0,x="";!(b>=_/4);){var S=i()[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},tC=(h,_,b)=>{if(_>>>=0,b??(b=2147483647),4>b)return 0;var x=_;b=x+b-4;for(var S=0;S=C&&(C=65536+((1023&C)<<10)|1023&h.charCodeAt(++S)),i()[_>>>2>>>0]=C,(_+=4)+4>b)break}return i()[_>>>2>>>0]=0,_-x},nC=h=>{for(var _=0,b=0;b=x&&++b,_+=4}return _};function rC(h,_,b){if(h>>>=0,_>>>=0,b=jt(b>>>=0),_===2)var x=YT,S=ZT,C=JT,D=V=>a()[V>>>1>>>0];else _===4&&(x=eC,S=tC,C=nC,D=V=>o()[V>>>2>>>0]);en(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&&D(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=C(Q),le=ai(4+Z+_);return o()[le>>>2>>>0]=Z/_,S(Q,le+4,Z+_),V!==null&&V.push(Gt,le),le},argPackAdvance:wn,readValueFromPointer:To,Db(V){Gt(V)}})}function sC(h,_){en(h>>>=0,{Sb:!0,name:_=jt(_>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var iC=()=>1;function aC(h){Bo(h>>>0,!g,1,!m,131072,!1),W_()}var gw=h=>{if(!Ne)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(i(),h>>>2,h).value.then(Zs),h+=128,Atomics.store(i(),h>>>2,1))}var Zs=()=>{var h=lr();h&&(Co(h),gw(Ww))};function oC(h,_){(h>>>=0)==_>>>0?setTimeout(Zs):w?postMessage({targetThread:h,cmd:"checkMailbox"}):(h=Vt[h])&&h.postMessage({cmd:"checkMailbox"})}var Mo=[];function lC(h,_,b,x,S){for(_>>>=0,x/=2,Mo.length=x,b=S>>>0>>>3,S=0;S>>0];return(_?_o[_]:YC[h])(...Mo)}function uC(h){h>>>=0,w?postMessage({cmd:"cleanupThread",thread:h}):G_(Vt[h])}function dC(h){}var Ao=(h,_)=>{var b=ko[h];if(b===void 0)throw h=Vw(h),b=jt(h),Gt(h),new _n(`${_} has unknown type ${b}`);return b},_w=(h,_,b)=>{var x=[];return h=h.toWireType(x,b),x.length&&(o()[_>>>2>>>0]=kt(x)),h};function cC(h,_,b){return _>>>=0,b>>>=0,h=$t(h>>>0),_=Ao(_,"emval::as"),_w(_,b,h)}var Js=h=>{try{h()}catch(_){Jt(_)}},yn=0,qt=null,ww=0,ei=[],yw={},bw={},pC=0,Io=null,hC=[];function vw(h){return function(_){if(!Ne){if(yn===0){var b=!1,x=!1;_((S=0)=>{if(!Ne&&(ww=S,b=!0,x)){yn=2,Js(()=>Yw(qt)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),S=!1;try{var C=function(){var Q=i()[qt+8>>>2>>>0];return Q=oe[bw[Q]],--Fn,Q()}()}catch(Q){C=Q,S=!0}var D=!1;if(!qt){var V=Io;V&&(Io=null,(S?V.reject:V.resolve)(C),D=!0)}if(S&&!D)throw C}}),x=!0,b||(yn=1,qt=function(){var S=ai(65548),C=S+12;o()[S>>>2>>>0]=C,o()[S+4>>>2>>>0]=C+65536,C=ei[0];var D=yw[C];return D===void 0&&(D=pC++,yw[C]=D,bw[D]=C),C=D,i()[S+8>>>2>>>0]=C,S}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),Js(()=>Xw(qt)))}else yn===2?(yn=0,Js(Zw),Gt(qt),qt=null,hC.forEach(gw)):Jt(`invalid state: ${yn}`);return ww}}(_=>{h().then(_)})}function fC(h){return h>>>=0,vw(()=>(h=$t(h)).then(kt))}var ti=[];function mC(h,_,b,x){return b>>>=0,x>>>=0,(h=ti[h>>>0])(null,_=$t(_>>>0),b,x)}var gC={},ni=h=>{var _=gC[h];return _===void 0?jt(h):_};function _C(h,_,b,x,S){return b>>>=0,x>>>=0,S>>>=0,(h=ti[h>>>0])(_=$t(_>>>0),_[b=ni(b)],x,S)}var xw=()=>typeof globalThis=="object"?globalThis:Function("return this")();function wC(h){return(h>>>=0)==0?kt(xw()):(h=ni(h),kt(xw()[h]))}var yC=h=>{var _=ti.length;return ti.push(h),_},bC=(h,_)=>{for(var b=Array(h),x=0;x>>2>>>0],"parameter "+x);return b},$w=(h,_)=>Object.defineProperty(_,"name",{value:h});function vC(h,_,b){var x=(_=bC(h,_>>>0)).shift();h--;var S=`return function (obj, func, destructorsRef, args) { `,C=0,D=[];b===0&&D.push("obj");for(var V=["retType"],Q=[x],Z=0;Zle.name).join(", ")}) => ${x.name}>`,yC($w(b,h))}function xC(h){return h=ni(h>>>0),kt(d[h])}function $C(h,_){return _>>>=0,h=$t(h>>>0),_=$t(_),kt(h[_])}function kC(h){9<(h>>>=0)&&(tn[h+1]+=1)}function SC(){return kt([])}function EC(h){h=$t(h>>>0);for(var _=Array(h.length),b=0;b>>0))}function CC(){return kt({})}function MC(h){for(var _=$t(h>>>=0);_.length;){var b=_.pop();_.pop()(b)}Eo(h)}function AC(h,_,b){_>>>=0,b>>>=0,h=$t(h>>>0),_=$t(_),b=$t(b),h[_]=b}function IC(h,_){return _>>>=0,h=(h=Ao(h>>>0,"_emval_take_value")).readValueFromPointer(_),kt(h)}function zC(h,_){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),i()[_>>>2>>>0]=h.getUTCSeconds(),i()[_+4>>>2>>>0]=h.getUTCMinutes(),i()[_+8>>>2>>>0]=h.getUTCHours(),i()[_+12>>>2>>>0]=h.getUTCDate(),i()[_+16>>>2>>>0]=h.getUTCMonth(),i()[_+20>>>2>>>0]=h.getUTCFullYear()-1900,i()[_+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[_+28>>>2>>>0]=h}var or=h=>h%4==0&&(h%100!=0||h%400==0),kw=[0,31,60,91,121,152,182,213,244,274,305,335],Sw=[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),i()[_>>>2>>>0]=h.getSeconds(),i()[_+4>>>2>>>0]=h.getMinutes(),i()[_+8>>>2>>>0]=h.getHours(),i()[_+12>>>2>>>0]=h.getDate(),i()[_+16>>>2>>>0]=h.getMonth(),i()[_+20>>>2>>>0]=h.getFullYear()-1900,i()[_+24>>>2>>>0]=h.getDay();var b=(or(h.getFullYear())?kw:Sw)[h.getMonth()]+h.getDate()-1|0;i()[_+28>>>2>>>0]=b,i()[_+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)),i()[_+32>>>2>>>0]=h}function PC(h){h>>>=0;var _=new Date(i()[h+20>>>2>>>0]+1900,i()[h+16>>>2>>>0],i()[h+12>>>2>>>0],i()[h+8>>>2>>>0],i()[h+4>>>2>>>0],i()[h>>>2>>>0],0),b=i()[h+32>>>2>>>0],x=_.getTimezoneOffset(),S=new Date(_.getFullYear(),6,1).getTimezoneOffset(),C=new Date(_.getFullYear(),0,1).getTimezoneOffset(),D=Math.min(C,S);return 0>b?i()[h+32>>>2>>>0]=+(S!=C&&D==x):0>>2>>>0]=_.getDay(),b=(or(_.getFullYear())?kw:Sw)[_.getMonth()]+_.getDate()-1|0,i()[h+28>>>2>>>0]=b,i()[h>>>2>>>0]=_.getSeconds(),i()[h+4>>>2>>>0]=_.getMinutes(),i()[h+8>>>2>>>0]=_.getHours(),i()[h+12>>>2>>>0]=_.getDate(),i()[h+16>>>2>>>0]=_.getMonth(),i()[h+20>>>2>>>0]=_.getYear(),h=_.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Ew(h,_,b,x,S,C,D){return w?Me(16,1,h,_,b,x,S,C,D):-52}function Tw(h,_,b,x,S,C){if(w)return Me(17,1,h,_,b,x,S,C)}function BC(h,_,b,x){h>>>=0,_>>>=0,b>>>=0,x>>>=0;var S=new Date().getFullYear(),C=new Date(S,0,1),D=new Date(S,6,1);S=C.getTimezoneOffset();var V=D.getTimezoneOffset(),Q=Math.max(S,V);o()[h>>>2>>>0]=60*Q,i()[_>>>2>>>0]=+(S!=V),C=(h=Z=>Z.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(C),D=h(D),V{zo.length=0;for(var b;b=r()[h++>>>0];){var x=b!=105;_+=(x&=b!=112)&&_%8?4:0,zo.push(b==112?o()[_>>>2>>>0]:b==106?Ee[_>>>3]:b==105?i()[_>>>2>>>0]:u()[_>>>3>>>0]),_+=x?8:4}return zo};function RC(h,_,b){return h>>>=0,_=Cw(_>>>0,b>>>0),_o[h](..._)}function DC(h,_,b){return h>>>=0,_=Cw(_>>>0,b>>>0),_o[h](..._)}var FC=()=>{},NC=()=>Date.now();function LC(h,_){return H(Ge(h>>>0,_>>>0))}var Mw,UC=()=>{throw Fn+=1,"unwind"};function VC(){return 4294901760}Mw=()=>performance.timeOrigin+performance.now();var jC=()=>navigator.hardwareConcurrency;function qC(){return Jt("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function GC(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)-z.buffer.byteLength+65535)/65536;try{z.grow(S),Oe();var C=1;break e}catch{}C=void 0}if(C)return!0}return!1}var ri=()=>(Jt("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Kr={},Aw=h=>{h.forEach(_=>{ri()})};function WC(){var h=Error().stack.toString().split(` `);return h[0]=="Error"&&h.shift(),Aw(h),Kr.Ob=ri(),Kr.ac=h,Kr.Ob}function HC(h,_,b){if(h>>>=0,_>>>=0,Kr.Ob==h)var x=Kr.ac;else(x=Error().stack.toString().split(` `))[0]=="Error"&&x.shift(),Aw(x);for(var S=3;x[S]&&ri()!=h;)++S;for(h=0;h>>2>>>0]=ri();return h}var Oo,Po={},Iw=()=>{if(!Oo){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 Po)Po[h]===void 0?delete _[h]:_[h]=Po[h];var b=[];for(h in _)b.push(`${h}=${_[h]}`);Oo=b}return Oo};function zw(h,_){if(w)return Me(18,1,h,_);h>>>=0,_>>>=0;var b=0;return Iw().forEach((x,S)=>{var C=_+b;for(S=o()[h+4*S>>>2>>>0]=C,C=0;C>>0]=x.charCodeAt(C);n()[S>>>0]=0,b+=x.length+1}),0}function Ow(h,_){if(w)return Me(19,1,h,_);h>>>=0,_>>>=0;var b=Iw();o()[h>>>2>>>0]=b.length;var x=0;return b.forEach(S=>x+=S.length+1),o()[_>>>2>>>0]=x,0}function Pw(h){return w?Me(20,1,h):52}function Bw(h,_,b,x){return w?Me(21,1,h,_,b,x):52}function Rw(h,_,b,x){return w?Me(22,1,h,_,b,x):70}var KC=[null,[],[]];function Dw(h,_,b,x){if(w)return Me(23,1,h,_,b,x);_>>>=0,b>>>=0,x>>>=0;for(var S=0,C=0;C>>2>>>0],V=o()[_+4>>>2>>>0];_+=8;for(var Q=0;Q>>0],le=KC[h];Z===0||Z===10?((h===1?X:H)(Z_(le,0)),le.length=0):le.push(Z)}S+=V}return o()[x>>>2>>>0]=S,0}var Fw=[31,29,31,30,31,30,31,31,30,31,30,31],Nw=[31,28,31,30,31,30,31,31,30,31,30,31],XC=(h,_)=>{n().set(h,_>>>0)};function Lw(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 C(P,_e){return S(P,_e,"0")}function D(P,_e){function Pe(ey){return 0>ey?-1:0Ln-P.getDate())){P.setDate(P.getDate()+_e);break}_e-=Ln-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>=D(_e,P)?0>=D(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:i()[x>>>2>>>0],ec:i()[x+4>>>2>>>0],Gb:i()[x+8>>>2>>>0],Kb:i()[x+12>>>2>>>0],Hb:i()[x+16>>>2>>>0],Cb:i()[x+20>>>2>>>0],ub:i()[x+24>>>2>>>0],Bb:i()[x+28>>>2>>>0],nc:i()[x+32>>>2>>>0],dc:i()[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=>C((P.Cb+1900)/100|0,2),"%d":P=>C(P.Kb,2),"%e":P=>S(P.Kb,2," "),"%g":P=>Q(P).toString().substring(2),"%G":Q,"%H":P=>C(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)?Fw:Nw)[Pe++]);return C(P.Kb+_e,3)},"%m":P=>C(P.Hb+1,2),"%M":P=>C(P.ec,2),"%n":()=>` `,"%p":P=>0<=P.Gb&&12>P.Gb?"AM":"PM","%S":P=>C(P.fc,2),"%t":()=>" ","%u":P=>P.ub||7,"%U":P=>C(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 C(_e,2)},"%w":P=>P.ub,"%W":P=>C(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(xo(P)+1);return tw(P,_e,0,_e.length),_e}(b=b.replace(/\0\0/g,"%")),le.length>_?0:(XC(le,h),le.length-1)}function QC(h,_,b,x){return Lw(h>>>0,_>>>0,b>>>0,x>>>0)}w||function(){for(var h=d.numThreads-1;h--;)K_();Bt.unshift(()=>{at++,function(_){w?_():Promise.all(gn.map(H_)).then(_)}(()=>Dn())})}();for(var Uw=Array(256),si=0;256>si;++si)Uw[si]=String.fromCharCode(si);hw=Uw,_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"}},tn.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>tn.length/2-5-So.length;var YC=[bo,j_,X_,J_,ew,nw,rw,sw,iw,aw,ow,lw,uw,dw,cw,pw,Ew,Tw,zw,Ow,Pw,Bw,Rw,Dw],oe=function(){function h(b,x){return oe=b.exports,oe=function(){var S=oe,C={};for(let[D,V]of Object.entries(S))C[D]=typeof V=="function"?(...Q)=>{ei.push(D);try{return V(...Q)}finally{Ne||(ei.pop(),qt&&yn===1&&ei.length===0&&(yn=0,Fn+=1,Js(Qw),typeof Fibers<"u"&&Fibers.oc()))}}:V;return C}(),oe=function(){var S=oe,C=V=>Q=>V(Q)>>>0,D=V=>()=>V()>>>0;return(S=Object.assign({},S)).Ca=C(S.Ca),S.fb=D(S.fb),S.gb=C(S.gb),S.emscripten_main_runtime_thread_id=D(S.emscripten_main_runtime_thread_id),S.sb=C(S.sb),S.tb=D(S.tb),S}(),q_.push(oe.ib),Fe.unshift(oe.Ba),N=x,Dn(),oe}var _=U_();if(at++,d.instantiateWasm)try{return d.instantiateWasm(_,h)}catch(b){H(`Module.instantiateWasm callback failed with error: ${b}`),p(b)}return go||(go=d.locateFile?D_("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",R):R+"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=go;return L||typeof WebAssembly.instantiateStreaming!="function"||D_(S)||F_(S)||typeof fetch!="function"?L_(S,b,x):fetch(S,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,b).then(x,function(D){return H(`wasm streaming compile failed: ${D}`),H("falling back to ArrayBuffer instantiation"),L_(S,b,x)}))}(_,function(b){h(b.instance,b.module)}).catch(p),{}}(),Vw=h=>(Vw=oe.Ca)(h),jw=()=>(jw=oe.Da)();d._OrtInit=(h,_)=>(d._OrtInit=oe.Ea)(h,_),d._OrtGetLastError=(h,_)=>(d._OrtGetLastError=oe.Fa)(h,_),d._OrtCreateSessionOptions=(h,_,b,x,S,C,D,V,Q,Z)=>(d._OrtCreateSessionOptions=oe.Ga)(h,_,b,x,S,C,D,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,C)=>(d._OrtCreateTensor=oe.Ra)(h,_,b,x,S,C),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,C,D,V)=>(d._OrtRun=oe.bb)(h,_,b,x,S,C,D,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 ii,lr=()=>(lr=oe.fb)(),ai=d._malloc=h=>(ai=d._malloc=oe.gb)(h),Gt=d._free=h=>(Gt=d._free=oe.hb)(h),Bo=(h,_,b,x,S,C)=>(Bo=oe.kb)(h,_,b,x,S,C),qw=()=>(qw=oe.lb)(),Gw=(h,_,b,x,S)=>(Gw=oe.mb)(h,_,b,x,S),Ro=h=>(Ro=oe.nb)(h),oi=h=>(oi=oe.ob)(h),Ww=()=>(Ww=oe.pb)(),Hw=(h,_)=>(Hw=oe.qb)(h,_),li=h=>(li=oe.rb)(h),Do=h=>(Do=oe.sb)(h),Fo=()=>(Fo=oe.tb)(),Kw=d.dynCall_ii=(h,_)=>(Kw=d.dynCall_ii=oe.vb)(h,_),Xw=h=>(Xw=oe.wb)(h),Qw=()=>(Qw=oe.xb)(),Yw=h=>(Yw=oe.yb)(h),Zw=()=>(Zw=oe.zb)();function Jw(){0Fo(),d.stackRestore=h=>li(h),d.stackAlloc=h=>Do(h),d.UTF8ToString=Ge,d.stringToUTF8=ar,d.lengthBytesUTF8=xo,Rt=function h(){ii||Jw(),ii||(Rt=h)},Jw(),f}),_l=Ei,((t=globalThis.self)==null?void 0:t.name)==="em-pthread"&&Ei()}),jn,wl,yl,bl,Ti,vl,xl,$l,is=W(()=>{var t,e;xi(),jn=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),wl=typeof location>"u"?void 0:location.origin,yl=(n,r)=>{try{let s=r??jn;return(s?new URL(n,s):new URL(n)).origin===wl}catch{return!1}},bl=async n=>{let r=await(await fetch(n,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},Ti=(Wy(),rs(fl)).default,vl=async()=>{if(!jn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(yl(jn))return[void 0,Ti()];let n=await bl(jn);return[n,Ti(n)]},xl=(Hy(),rs(gl)).default,$l=async(n,r,s)=>[void 0,xl]}),Ci,as,fr,Mi,kl,Sl,Ai,je,qn=W(()=>{is(),as=!1,fr=!1,Mi=!1,kl=()=>{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}},Sl=()=>{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}},Ai=async t=>{if(as)return Promise.resolve();if(fr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Mi)throw new Error("previous call to 'initializeWebAssembly()' failed.");fr=!0;let e=t.initTimeout,n=t.numThreads;if(!Sl())throw new Error("WebAssembly SIMD is not supported in the current environment.");let r=kl();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,a=typeof s=="string"?s:void 0,i=s==null?void 0:s.mjs,o=(i==null?void 0:i.href)??i,l=s==null?void 0:s.wasm,u=(l==null?void 0:l.href)??l,c=t.wasmBinary,[p,d]=await $l(o,a,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||a)&&(v.locateFile=(y,$)=>u??(a??$)+y),d(v).then(y=>{fr=!1,as=!0,Ci=y,g(),p&&URL.revokeObjectURL(p)},y=>{fr=!1,Mi=!0,w(y)})})),await Promise.race(m),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},je=()=>{if(as&&Ci)return Ci;throw new Error("WebAssembly is not initialized yet.")}}),Ke,os,Ae,Ii=W(()=>{qn(),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,a])=>{let i=e?e+s:s;if(typeof a=="object")os(a,i+".",n,r);else if(typeof a=="string"||typeof a=="number")r(i,a.toString());else if(typeof a=="boolean")r(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},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],a=e.HEAPU32[r/4+1],i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${s}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(n)}}}),El,Ky=W(()=>{qn(),Ii(),El=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 a=0;return(t==null?void 0:t.tag)!==void 0&&(a=Ke(t.tag,r)),n=e._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),n===0&&Ae("Can't create run options."),(t==null?void 0:t.extra)!==void 0&&os(t.extra,"",new WeakSet,(i,o)=>{let l=Ke(i,r),u=Ke(o,r);e._OrtAddRunConfigEntry(n,l,u)!==0&&Ae(`Can't set a run config entry: ${i} - ${o}.`)}),[n,r]}catch(a){throw n!==0&&e._OrtReleaseRunOptions(n),r.forEach(i=>e._free(i)),a}}}),Tl,Cl,Ml,Al,Il,Xy=W(()=>{qn(),Ii(),Tl=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},Cl=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},Ml=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(t.enableMemPattern=!1)},Al=(t,e,n)=>{for(let r of e){let s=typeof r=="string"?r:r.name;switch(s){case"webnn":if(s="WEBNN",typeof r!="string"){let i=r==null?void 0:r.deviceType;if(i){let o=Ke("deviceType",n),l=Ke(i,n);je()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ae(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(s="JS",typeof r!="string"){let i=r;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let o=Ke("preferredLayout",n),l=Ke(i.preferredLayout,n);je()._OrtAddSessionConfigEntry(t,o,l)!==0&&Ae(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Ke(s,n);je()._OrtAppendExecutionProvider(t,a)!==0&&Ae(`Can't append execution provider: ${s}.`)}},Il=t=>{let e=je(),n=0,r=[],s=t||{};Ml(s);try{let a=Tl(s.graphOptimizationLevel??"all"),i=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(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,o,l,u,c),n===0&&Ae("Can't create session options."),s.executionProviders&&Al(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(a){throw n!==0&&e._OrtReleaseSessionOptions(n),r.forEach(i=>e._free(i)),a}}}),zi,$n,ls,Oi,us,Pi,Bi,ue=W(()=>{zi=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,a)=>s*a,1);return n>0?Math.ceil(r*n):void 0},Oi=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}`)}},Pi=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Bi=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}`)}}}),Ri,zl=W(()=>{xi(),Ri=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(),a;try{a=new ArrayBuffer(r)}catch(o){if(o instanceof RangeError){let l=Math.ceil(r/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw o}let i=0;for(;;){let{done:o,value:l}=await s.read();if(o)break;let u=l.byteLength;new Uint8Array(a,i,u).set(l),i+=u}return new Uint8Array(a,0,r)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),Ol,Pl,Bl,Rl,Dl,Fl,Be,sn=W(()=>{ue(),Ol=["V","I","W","E","F"],Pl=(t,e)=>{console.log(`[${Ol[t]},${new Date().toISOString()}]${e}`)},Dl=(t,e)=>{Bl=t,Rl=e},Fl=(t,e)=>{let n=us(t),r=us(Bl);n>=r&&Pl(n,typeof e=="function"?e():e)},Be=(...t)=>{Rl&&Fl(...t)}}),Nl,Qy=W(()=>{ue(),Nl=(t,e)=>new(Oi(e))(t)}),Di=W(()=>{}),Fi,ds,cs,Ll,Ul,Ni,Li,Vl,jl,Yy=W(()=>{sn(),Di(),Fi=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,Ll=t=>{for(let e=0;eUl++,Li=async(t,e,n,r)=>{let s=cs(n),a=t.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=t.getCommandEncoder();t.endComputePass(),i.copyBufferToBuffer(e,0,a,0,s),t.flush(),await a.mapAsync(GPUMapMode.READ);let o=a.getMappedRange();if(r){let l=r();return l.set(new Uint8Array(o,0,n)),l}else return new Uint8Array(o.slice(0,n))}finally{a.destroy()}},Vl=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 Fi)ds.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[])}upload(t,e){let n=e.buffer,r=e.byteOffset,s=e.byteLength,a=cs(s),i=this.storageCache.get(t);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${s}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,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,i.gpuData.buffer,0,a),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),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.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=Ni();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=Ll(t),r,s=(e&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(e&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||a){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 i={id:Ni(),type:0,buffer:r};return this.storageCache.set(i.id,{gpuData:i,originalSize:t}),Be("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${i.id}`),i}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 Li(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=Fi.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))}},jl=(...t)=>new Vl(...t)}),ql,xe,De=W(()=>{ql=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}},xe=t=>new ql(t)}),Gl,Gn,F,ps,Wl,Ui,Vi,pe=W(()=>{Gl=class{static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}},Gn=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 a=Math.max(t.length,e.length),i=new Array(a);if(n){if(r<2||s<2)return;let o=Gl.calcMatMulShape([t[r-2],t[r-1]],[e[s-2],e[s-1]]);if(o===void 0)return;[i[a-2],i[a-1]]=o}for(let o=n?3:1;o<=a;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)i[a-o]=Math.max(l,u);else{if(c>1)return;i[a-o]=0}}return i}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}},F=class ui{static size(e){return ui.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,n=4){let r=e.length;if(r===0)return[];let s=new Array(r),a=r-1;for(;a>=0;){if(e[a]%n===0){s[a]=e[a]/n;break}if(n%e[a]!==0)throw new Error("cannot convert shape");s[a]=1,n/=e[a],a--}for(a--;a>=0;a--)s[a]=e[a];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 ui.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 ui.getSizeFromDimensionRange(e,0,n)}static getSizeFromDimensionRange(e,n,r){let s=1;for(let a=n;a=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,a)=>s+n[a]+n[a+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,a,i){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]||i[o+r.length]>=r[o])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,n,r,s,a,i,o){if(o){if(a.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(),Wn=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:F.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})`,Hn=(t,e,n)=>t==="f32"?n:e===1?`f32(${n})`:`vec${e}(${n})`,an=(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 a=typeof n=="number",i=a?n:n.length,o=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`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=a?"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,i<2?O:`o2i_${t}(${O})`),E=[];if(i>=2)for(let O=i-1;O>=0;O--)E.push(`${re(v,O,i)} * (indices[${O}])`);let T=i<2?"":` fn i2o_${t}(indices: ${d.indices}) -> u32 { return ${E.join("+")}; }`,M=O=>(m.indicesToOffset=!0,i<2?O:`i2o_${t}(${O})`),R=(...O)=>i===0?"0u":`${d.indices}(${O.map(f).join(",")})`,L=(O,q)=>i<2?`${O}`:`${re(O,q,i)}`,G=(O,q,ae)=>i<2?`${O}=${ae};`:`${re(O,q,i)}=${ae};`,K={},X=(O,q)=>{m.broadcastedIndicesToOffset=!0;let ae=`${q.name}broadcastedIndicesTo${t}Offset`;if(ae in K)return`${ae}(${O})`;let ge=[];for(let ve=i-1;ve>=0;ve--){let Ee=q.indicesGet("outputIndices",ve+q.rank-i);ge.push(`${L(v,ve)} * (${Ee} % ${L(w,ve)})`)}return K[ae]=`fn ${ae}(outputIndices: ${q.type.indices}) -> u32 { return ${ge.length>0?ge.join("+"):"0u"}; }`,`${ae}(${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`)})(),ee=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=i<2?"":` fn get_${t}ByIndices(indices: ${d.indices}) -> ${c} { return ${ee(`i2o_${t}(indices)`)}; }`,z=i<2?"":(()=>{let O=o.map(ae=>`d${ae}: u32`).join(", "),q=o.map(ae=>`d${ae}`).join(", ");return` fn get_${t}(${O}) -> ${c} { return get_${t}ByIndices(${R(q)}); }`})(),N=(...O)=>{if(O.length!==i)throw new Error(`indices length must be ${i}`);let q=O.map(f).join(",");return i===0?ee("0u"):i===1?ee(q[0]):(m.get=!0,m.getByIndices=!0,m.indicesToOffset=!0,`get_${t}(${q})`)},B=O=>i<2?ee(O):(m.getByIndices=!0,m.indicesToOffset=!0,`get_${t}ByIndices(${O})`),Y=i<2?"":` fn set_${t}ByIndices(indices: ${d.indices}, value: ${c}) { ${H(`i2o_${t}(indices)`,"value")} }`,te=i<2?"":(()=>{let O=o.map(ae=>`d${ae}: u32`).join(", "),q=o.map(ae=>`d${ae}`).join(", ");return` fn set_${t}(${O}, value: ${c}) { set_${t}ByIndices(${R(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(ae=>O.push(ae)),q=!0),m.set&&(O.push(te),q=!0),m.setByIndices&&(O.push(Y),q=!0),m.get&&(O.push(z),q=!0),m.getByIndices&&(O.push(ne),q=!0),!a&&q&&O.unshift(`const ${w} = ${d.indices}(${n.join(",")});`,`const ${v} = ${d.indices}(${F.computeStrides(n).join(",")});`),O.join(` `)},type:d,offsetToIndices:k,indicesToOffset:M,broadcastedIndicesToOffset:X,indices:R,indicesGet:L,indicesSet:G,set:(...O)=>{if(O.length!==i+1)throw new Error(`indices length must be ${i}`);let q=O[i];if(typeof q!="string")throw new Error("value must be string");let ae=O.slice(0,i).map(f).join(",");return i===0?H("0u",q):i===1?H(ae[0],q):(m.set=!0,m.setByIndices=!0,m.indicesToOffset=!0,`set_${t}(${ae}, ${q})`)},setByOffset:H,setByIndices:(O,q)=>i<2?H(O,q):(m.setByIndices=!0,m.indicesToOffset=!0,`set_${t}ByIndices(${O}, ${q});`),get:N,getByOffset:ee,getByIndices:B,usage:r,name:t,strides:v,shape:w,rank:i}},U=(t,e,n,r=1)=>fs(t,e,n,"input",r),ie=(t,e,n,r=1)=>fs(t,e,n,"output",r),ji=(t,e,n,r=1)=>fs(t,e,n,"internal",r),Hl=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=Wn){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,a=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`,i=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(${a}) { ${i} `}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])}},Kl=(t,e)=>new Hl(t,e),mr=(t,e)=>{let n=t.length,r=[];for(let s=0;s1&&i===1&&r.unshift(a)}return r}}),Xl,qi,Ql,Yl,Dt,Zl,Jl,Kn=W(()=>{ue(),pe(),De(),he(),Xl=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},qi=(t,e)=>e&&e.length!==t?[...new Array(t).keys()].reverse():e,Ql=(t,e)=>F.sortBasedOnPerm(t,qi(t.length,e)),Yl=(t,e,n,r)=>{let s=[];s.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} { var a: ${n.type.indices};`);for(let a=0;a{let n=t.dataType,r=t.dims.length,s=qi(r,e),a=Ql(t.dims,s),i=ie("output",n,a.length),o=U("a",n,r),l;if(s.length===2&&s[0]===1&&s[1]===0){let u=i.type.value,c=[16,16,1];l=p=>` ${p.registerUniform("output_size","u32").declareVariables(o,i)} 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) { ${i.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} } }`}else l=u=>` ${u.registerUniform("output_size","u32").declareVariables(o,i)} ${Yl(s,r,o,i)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${i.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${i.setByOffset("global_idx",o.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:["rank"]},getRunData:()=>{let u=F.size(a);return{outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},...se(t.dims,a)]}},getShaderSource:l}},Zl=(t,e)=>{Xl(t.inputs),t.compute(Dt(t.inputs[0],e.perm))},Jl=t=>xe({perm:t.perm})}),eu,tu,nu,ru,su,iu,au,ou,lu,uu,Ct,du,cu,pu,hu,fu,mu,gu,_u,wu,yu,Zy=W(()=>{ue(),pe(),he(),Wi(),Kn(),eu={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"},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",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},nu={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},ru={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},su=(t,e)=>{let n=[];for(let r=e-t;r{let n=[],r=t.length;for(let a=0;at[a]);return[n,s]},au=(t,e)=>{let n=t.length+e.length,r=[],s=0;for(let a=0;a{for(let n=0;n{let n=[];if(!ou(t,e)){for(let r=0;rn.push(r))}return n},uu=(t,e,n,r,s,a,i)=>{let o=n[0].dims,l=F.size(a),u=F.size(i),c=U("_A",n[0].dataType,o),p=ie("output",s,a),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(${nu[r]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${d}) { let candidate = f32(${c.getByOffset("offset + k")}); bestValue = ${eu[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 = ${tu[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}(${ru[r]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},Ct=(t,e,n,r)=>{let s=t.inputs.length===1?n:Gi(t.inputs,n),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=t.inputs[0].dims.map((f,m)=>m));let i=F.normalizeAxes(a,t.inputs[0].dims.length),o=i,l=t.inputs[0],u=lu(o,t.inputs[0].dims.length);u.length>0&&(l=t.compute(Dt(t.inputs[0],u),{inputs:[0],outputs:[-1]})[0],o=su(o.length,l.dims.length));let[c,p]=iu(l.dims,o),d=c;s.keepDims&&(d=au(c,i)),t.compute(uu(e,{hint:s.cacheKey,inputDependencies:["type"]},[l],r,t.inputs[0].dataType,d,p),{inputs:[l]})},du=(t,e)=>{Ct(t,"ReduceMeanShared",e,"mean")},cu=(t,e)=>{Ct(t,"ReduceL1Shared",e,"l1")},pu=(t,e)=>{Ct(t,"ReduceL2Shared",e,"l2")},hu=(t,e)=>{Ct(t,"ReduceLogSumExpShared",e,"logSumExp")},fu=(t,e)=>{Ct(t,"ReduceMaxShared",e,"max")},mu=(t,e)=>{Ct(t,"ReduceMinShared",e,"min")},gu=(t,e)=>{Ct(t,"ReduceProdShared",e,"prod")},_u=(t,e)=>{Ct(t,"ReduceSumShared",e,"sum")},wu=(t,e)=>{Ct(t,"ReduceSumSquareShared",e,"sumSquare")},yu=(t,e)=>{Ct(t,"ReduceLogSumShared",e,"logSum")}}),Mt,bu,ms,Gi,At,vu,xu,$u,ku,Su,Eu,Tu,Cu,Mu,Au,It,Iu,zu,Ou,Pu,Bu,Ru,Du,Fu,Nu,Lu,Wi=W(()=>{ue(),pe(),De(),he(),Zy(),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.")},bu=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],ms=(t,e,n,r,s,a,i=!1,o=!1)=>{let l=[],u=n[0].dims,c=u.length,p=F.normalizeAxes(s,c),d=!o&&p.length===0;u.forEach((g,w)=>{d||p.indexOf(w)>=0?i&&l.push(1):l.push(g)});let f=l.length,m=F.size(l);return{name:t,shaderCache:e,getShaderSource:g=>{let w=[],v=U("_A",n[0].dataType,c),y=ie("output",a,f),$=r(v,y,p),k=$[2];for(let E=0,T=0;E=0?(i&&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:a}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...se(u,l)]})}},Gi=(t,e)=>{let n=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(r=>n.push(Number(r))),xe({axes:n,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},At=(t,e,n,r)=>{let s=t.inputs,a=s.length===1?n:Gi(s,n);t.compute(ms(e,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?bu:r,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},vu=(t,e)=>{Mt(t.inputs),At(t,"ReduceLogSum",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},xu=(t,e)=>{Mt(t.inputs),At(t,"ReduceL1",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},$u=(t,e)=>{Mt(t.inputs),At(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);"])},ku=(t,e)=>{Mt(t.inputs),At(t,"ReduceLogSumExp",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Su=(t,e)=>{Mt(t.inputs),At(t,"ReduceMax",e,(n,r,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(n.indicesSet("input_indices",i,0));return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Eu=(t,e)=>{Mt(t.inputs),At(t,"ReduceMean",e,(n,r,s)=>{let a=1;for(let i=0;i=0||s.length===0)&&(a*=t.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${r.type.value}(sum / ${a});`]})},Tu=(t,e)=>{Mt(t.inputs),At(t,"ReduceMin",e,(n,r,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Cu=(t,e)=>{Mt(t.inputs),At(t,"ReduceProd",e,(n,r)=>[`var value = ${r.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Mu=(t,e)=>{Mt(t.inputs),At(t,"ReduceSum",e,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Au=(t,e)=>{Mt(t.inputs),At(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;`,""])},It=(t,e,n)=>{if(e.length===0)return n;let r=1,s=1;for(let a=0;a1024},Iu=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Eu(t,e):du(t,e)},zu=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?xu(t,e):cu(t,e)},Ou=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?$u(t,e):pu(t,e)},Pu=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?ku(t,e):hu(t,e)},Bu=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Su(t,e):fu(t,e)},Ru=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Tu(t,e):mu(t,e)},Du=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Cu(t,e):gu(t,e)},Fu=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Mu(t,e):_u(t,e)},Nu=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Au(t,e):wu(t,e)},Lu=(t,e)=>{It(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?vu(t,e):yu(t,e)}}),Hi,Uu,Vu,Ki,Jy=W(()=>{ue(),De(),Wi(),Hi=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.")},Uu=(t,e)=>{Hi(t.inputs);let n=(r,s,a)=>{let i=[];for(let o=0;o=0||a.length===0)&&i.push(`input_indices[${o}] = 0;`);return[`${i.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]})},Vu=(t,e)=>{Hi(t.inputs);let n=(r,s,a)=>{let i=[];for(let o=0;o=0||a.length===0)&&i.push(`input_indices[${o}] = 0;`);return[`${i.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]})},Ki=t=>xe(t)}),ju,qu,Gu,Wu,gr,Hu,Ku,Xi=W(()=>{ue(),pe(),Di(),he(),ju=(t,e)=>{let n=t[0],r=t[1],s=t[2],a=t[3],i=t[4],o=t[5];if(i&&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(i){if(d!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==e.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==d/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(g=i.dims[3])}let w=m+g,v=-1,y=0;if(a)throw new Error("Mask not supported");if(i)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}},qu=(t,e,n)=>{let r=Ue(n),s=64,a=n/r;a{let f=ie("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})}},Gu=(t,e,n,r,s,a,i,o)=>{let l=o+a.kvSequenceLength,u=[a.batchSize,a.numHeads,a.sequenceLength,l],c=a.kvNumHeads===void 0&&t>1&&r,p=c?[a.batchSize,a.numHeads,l,a.headSize]:void 0,d=i.scale===0?1/Math.sqrt(a.headSize):i.scale,f=Ue(a.headSize),m=a.headSize/f,g=12,w={x:Math.ceil(l/g),y:Math.ceil(a.sequenceLength/g),z:a.batchSize*a.numHeads},v=[{type:12,data:a.sequenceLength},{type:12,data:m},{type:12,data:l},{type:12,data:a.numHeads},{type:1,data:d},{type:12,data:o},{type:12,data:a.kvSequenceLength}],y=c&&r&&F.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 M=U("q",e.dataType,e.dims,f),R=U("key",n.dataType,n.dims,f),L=[M,R];if(y){let ee=U("past_key",r.dataType,r.dims,f);L.push(ee)}s&&L.push(U("attention_bias",s.dataType,s.dims));let G=ie("output",e.dataType,u),K=[G];c&&K.push(ie("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<${M.type.storage}, ${g*g}>; var tileK: array<${M.type.storage}, ${g*g}>; ${T.registerUniforms(H).declareVariables(...L,...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}},Wu=(t,e,n,r,s,a)=>{let i=a+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,i,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:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:l},{type:12,data:a},{type:12,data:s.kvSequenceLength}],g=u&&r&&F.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=U("probs",e.dataType,e.dims),E=U("v",n.dataType,n.dims),T=[k,E];g&&T.push(U("past_value",r.dataType,r.dims));let M=[ie("output",e.dataType,p)];u&&M.push(ie("present_value",e.dataType,c));let R=[{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(R).declareVariables(...T,...M)} ${$.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,a,i,o,l,u,c)=>{let p=Math.min(t.outputCount,1+(i?1:0)+(o?1:0)),d=u.kvNumHeads!==void 0||p>1?u.pastSequenceLength:0,f=d+u.kvSequenceLength,m=l&&F.size(l.dims)>0?l:void 0,g=[e,n];u.kvNumHeads===void 0&&p>1&&i&&F.size(i.dims)>0&&g.push(i),m&&g.push(m);let w=t.compute(Gu(p,e,n,i,m,u,c,d),{inputs:g,outputs:u.kvNumHeads===void 0&&p>1?[-1,1]:[-1]})[0];t.compute(qu(w,u.batchSize*u.numHeads*u.sequenceLength,f),{inputs:[w],outputs:[]});let v=[w,r];u.kvNumHeads===void 0&&p>1&&o&&F.size(o.dims)>0&&v.push(o),t.compute(Wu(p,w,r,o,u,d),{inputs:v,outputs:u.kvNumHeads===void 0&&p>1?[0,2]:[0]})},Hu=(t,e)=>{let n=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],r=e.sequenceLength,s=e.inputHiddenSize,a=e.headSize,i=12,o={x:Math.ceil(e.headSize/i),y:Math.ceil(e.sequenceLength/i),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:a},{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=ie("output_q",l[0].dataType,n),f=ie("output_k",l[0].dataType,n),m=ie("output_v",l[0].dataType,n),g=U("input",l[0].dataType,l[0].dims),w=U("weight",l[1].dataType,l[1].dims),v=U("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 = ${i}u; var tileInput: array<${y}, ${i*i}>; var tileWeightQ: array<${y}, ${i*i}>; var tileWeightK: array<${y}, ${i*i}>; var tileWeightV: array<${y}, ${i*i}>; ${p.registerUniforms($).declareVariables(g,w,v,d,f,m)} ${p.mainStart([i,i,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]})},Ku=(t,e)=>{let n=ju(t.inputs,e),[r,s,a]=Hu(t,n);return gr(t,r,s,a,t.inputs[4],void 0,void 0,void 0,t.inputs[5],n,e)}}),Xu,Qu,Yu,Zu,e0=W(()=>{Tt(),ue(),pe(),De(),he(),Xu=(t,e)=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(r,s,a)=>{let i=s.length;if(i!==r.length)throw new Error(`${a}: num dimensions != ${i}`);s.forEach((o,l)=>{if(o!==r[l])throw new Error(`${a}: 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")},Qu=(t,e)=>{let{epsilon:n,spatial:r,format:s}=e,a=t[0].dims,i=r?Ue(a[a.length-1]):1,o=s==="NHWC"&&a.length>1?i:1,l=F.size(a)/i,u=r,c=u?a.length:a,p=U("x",t[0].dataType,t[0].dims,i),d=U("scale",t[1].dataType,t[1].dims,o),f=U("bias",t[2].dataType,t[2].dims,o),m=U("inputMean",t[3].dataType,t[3].dims,o),g=U("inputVar",t[4].dataType,t[4].dims,o),w=ie("y",t[0].dataType,c,i),v=()=>{let $="";if(r)$=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"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[${a.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 * ${i}`)}; ${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}_${i}`,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(a)]:[{type:12,data:l}]})}},Yu=t=>xe(t),Zu=(t,e)=>{let{inputs:n,outputCount:r}=t,s=Yu({...e,outputCount:r});if(Te.webgpu.validateInputContent&&Xu(n,s),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(Qu(n,s))}}),Ju,ed,td,t0=W(()=>{pe(),he(),Ju=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")},ed=t=>{let e=t[0].dims,n=t[0].dims[2],r=F.size(e)/4,s=t[0].dataType,a=U("input",s,e,4),i=U("bias",s,[n],4),o=U("residual",s,e,4),l=ie("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(a,i,o,l)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(r)} let value = ${a.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} }`}},td=t=>{Ju(t.inputs),t.compute(ed(t.inputs))}}),nd,ye,rd,sd,id,ad,od,ld,ud,dd,cd,pd,hd,fd,md,gd,_r,_d,gs,wd,yd,bd,vd,xd,$d,kd,Sd,Ed,Td,Cd,Md,Ad,Id,zd,Od,Qi,Pd,Yi,Zi,Bd,Rd,Dd,Fd,Nd,Ld,Ji=W(()=>{ue(),pe(),De(),he(),nd=(t,e,n,r,s,a)=>{let i=Math.ceil(e/4),o="";typeof s=="string"?o=`${s}(a)`:o=s("a");let l=U("inputData",n,[i],4),u=ie("outputData",r,[i],4);return` ${t.registerUniform("vec_size","u32").declareVariables(l,u)} ${a??""} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${l.getByOffset("global_idx")}; ${u.setByOffset("global_idx",o)} }`},ye=(t,e,n,r,s,a=t.dataType)=>({name:e,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:i=>nd(i,F.size(t.dims),t.dataType,a,n,r),getRunData:i=>({outputs:[{dims:t.dims,dataType:a}],dispatchGroup:{x:Math.ceil(F.size(i[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(F.size(t.dims)/4)}]})}),rd=t=>{t.compute(ye(t.inputs[0],"Abs","abs"))},sd=t=>{t.compute(ye(t.inputs[0],"Acos","acos"))},id=t=>{t.compute(ye(t.inputs[0],"Acosh","acosh"))},ad=t=>{t.compute(ye(t.inputs[0],"Asin","asin"))},od=t=>{t.compute(ye(t.inputs[0],"Asinh","asinh"))},ld=t=>{t.compute(ye(t.inputs[0],"Atan","atan"))},ud=t=>{t.compute(ye(t.inputs[0],"Atanh","atanh"))},dd=t=>xe(t),cd=(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))},pd=t=>{let e=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:Ui,n=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:Vi;return xe({min:e,max:n})},hd=(t,e)=>{let n=t.inputs.length===1?e:pd(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]})},fd=t=>{t.compute(ye(t.inputs[0],"Ceil","ceil"))},md=t=>{t.compute(ye(t.inputs[0],"Cos","cos"))},gd=t=>{t.compute(ye(t.inputs[0],"Cosh","cosh"))},_r=t=>xe(t),_d=(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)); }`,wd=t=>{let e=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"Erf",n=>`erf_vf32(${n})`,gs(e)))},yd=t=>{t.compute(ye(t.inputs[0],"Exp","exp"))},bd=t=>{t.compute(ye(t.inputs[0],"Floor","floor"))},vd=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)))},xd=(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))},$d=t=>{t.compute(ye(t.inputs[0],"Not",e=>`!${e}`))},kd=t=>{t.compute(ye(t.inputs[0],"Neg",e=>`-${e}`))},Sd=t=>{t.compute(ye(t.inputs[0],"Reciprocal",e=>`1.0/${e}`))},Ed=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))`))},Td=t=>{t.compute(ye(t.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},Cd=t=>xe(t),Md=(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))},Ad=t=>{t.compute(ye(t.inputs[0],"Sin","sin"))},Id=t=>{t.compute(ye(t.inputs[0],"Sinh","sinh"))},zd=t=>{t.compute(ye(t.inputs[0],"Sqrt","sqrt"))},Od=t=>{t.compute(ye(t.inputs[0],"Tan","tan"))},Qi=t=>`sign(${t}) * (1 - exp(-2 * abs(${t}))) / (1 + exp(-2 * abs(${t})))`,Pd=t=>{t.compute(ye(t.inputs[0],"Tanh",Qi))},Yi=(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 ${Qi("v")}; } `,Zi=t=>`(fast_gelu_a + fast_gelu_a * tanh_v(${t} * (fast_gelu_c * ${t} * ${t} + fast_gelu_b))) * ${t}`,Bd=t=>{let e=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"FastGelu",Zi,Yi(e),void 0,t.inputs[0].dataType))},Rd=(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"))},Fd=(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; } `,Nd=t=>`quick_gelu_impl(${t})`,Ld=(t,e)=>{let n=Ze(t.inputs[0].dataType);t.compute(ye(t.inputs[0],"QuickGelu",Nd,Fd(n,e.alpha),e.cacheKey,t.inputs[0].dataType))}}),Ud,Vd,jd,n0=W(()=>{pe(),he(),Ji(),Ud=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")},Vd=t=>{let e=t[0].dims.slice();e[2]=e[2]/2;let n=U("input",t[0].dataType,t[0].dims,4),r=U("bias",t[0].dataType,[t[0].dims[2]],4),s=ie("output",t[0].dataType,e,4),a=F.size(e)/4,i=Le(t[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:o=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${t[0].dims[2]/4/2}u; ${o.declareVariables(n,r,s)} ${gs(i)} ${o.mainStart()} ${o.guardAgainstOutOfBoundsWorkgroupSizes(a)} 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")} }`}},jd=t=>{Ud(t.inputs),t.compute(Vd(t.inputs))}}),qd,Gd,zt,Wd,Hd,Kd,Xd,Qd,Yd,Zd,Jd,ec,tc,r0=W(()=>{ue(),pe(),he(),qd=(t,e,n,r,s,a,i,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=ie("outputData",c,r.length,4),g=U("aData",l,e.length,4),w=U("bData",u,n.length,4),v;if(s)if(a){let y=F.size(e)===1,$=F.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(i||k?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||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(!a)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}]`,M=`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,M)}); `};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} }`},Gd=(t,e,n,r,s,a,i=n.dataType)=>{let o=!F.areEqual(n.dims,r.dims),l=n.dims,u=F.size(n.dims),c=!1,p=!1,d=[o];if(o){let f=Gn.calcShape(n.dims,r.dims,!1);if(!f)throw new Error("Can't perform binary op on the given tensors");l=f,u=F.size(l);let m=F.size(n.dims)===1,g=F.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=>qd(f,n.dims,r.dims,l,c,o,p,s,n.dataType,r.dataType,i,a),getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(F.size(l)/4)},...se(n.dims,r.dims,l)]})}},zt=(t,e,n,r,s,a)=>{t.compute(Gd(e,s??"",t.inputs[0],t.inputs[1],n,r,a))},Wd=t=>{zt(t,"Add",(e,n)=>`${e}+${n}`)},Hd=t=>{zt(t,"Div",(e,n)=>`${e}/${n}`)},Kd=t=>{zt(t,"Equal",{scalar:(e,n)=>`u32(${e}==${n})`,vector:(e,n)=>`vec4(${e}==${n})`},void 0,void 0,9)},Xd=t=>{zt(t,"Mul",(e,n)=>`${e}*${n}`)},Qd=t=>{let e=U("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;zt(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)); } `)},Yd=t=>{zt(t,"Sub",(e,n)=>`${e}-${n}`)},Zd=t=>{zt(t,"Greater",{scalar:(e,n)=>`u32(${e}>${n})`,vector:(e,n)=>`vec4(${e}>${n})`},void 0,void 0,9)},Jd=t=>{zt(t,"Less",{scalar:(e,n)=>`u32(${e}<${n})`,vector:(e,n)=>`vec4(${e}<${n})`},void 0,void 0,9)},ec=t=>{zt(t,"GreaterOrEqual",{scalar:(e,n)=>`u32(${e}>=${n})`,vector:(e,n)=>`vec4(${e}>=${n})`},void 0,void 0,9)},tc=t=>{zt(t,"LessOrEqual",{scalar:(e,n)=>`u32(${e}<=${n})`,vector:(e,n)=>`vec4(${e}<=${n})`},void 0,void 0,9)}}),nc,rc,sc,ic,ac,oc,s0=W(()=>{ue(),pe(),De(),he(),nc=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");let n=0,r=t[n],s=r.dataType,a=r.dims.length;t.forEach((i,o)=>{if(o!==n){if(i.dataType!==s)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==e&&l!==r.dims[u])throw new Error("non concat dimensions must match")})}})},rc=(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; }`,sc=(t,e)=>{let n=t.length,r=[];for(let s=0;s{let s=F.size(n),a=new Array(t.length),i=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]; } ${sc(i,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}},ac=(t,e)=>{let n=t.inputs,r=n[0].dims,s=F.normalizeAxis(e.axis,r.length);nc(n,s);let a=r.slice();a[s]=n.reduce((o,l)=>o+(l.dims.length>s?l.dims[s]:0),0);let i=n.filter(o=>F.size(o.dims)>0);t.compute(ic(i,s,a,n[0].dataType),{inputs:i})},oc=t=>xe({axis:t.axis})}),on,ln,un,ea,dn=W(()=>{ue(),pe(),on=(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}`)}},ln=(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})},un=(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"})},ea=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)||[Ui,Vi];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,ta,_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.`)}},ta=t=>` ${t?"value = value + getBiasByOutputCoords(coords);":""} `}),na,lc=W(()=>{na=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)); } `}),uc,dc,ws,ra,cc,ys,pc,sa,bs=W(()=>{ue(),pe(),he(),dn(),_s(),uc=(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":""}); `,dc=(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,a=32,i=!1,o=32)=>{let l=e[1]*t[1],u=e[0]*t[0],c=s?l:a,p=s?a:l,d=c/e[0],f=a/e[1];if(!((s&&d===4&&t[1]===4||!s&&(d===3||d===4))&&c%e[0]===0&&a%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 ${a} 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]}>, ${a}>; const rowPerThread = ${t[1]}; const colPerThread = ${t[0]}; const innerElementSize = ${d}; const tileInner = ${a}; @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 = ${i?"0":"i32(globalId.z)"}; ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${l}; let num_tiles = ${i?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`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; ${uc(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];"} ${dc(s,d)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},ra=(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":""}); `,cc=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ys=(t,e,n="f32",r,s=!1,a=32,i=!1,o=32,l=!1)=>{let u=t[1]*e[1],c=t[0]*e[0],p=s?u:a,d=s?a:u;if(!(d%e[1]===0&&p%e[0]===0&&a%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 ${a} must be divisible by workgroupSize[1]${e[1]}`);let f=d/e[1],m=p/e[0],g=a/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]}) { ${ra(s,r)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; 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; ${ra(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) { ${cc(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, ${a}>; const rowPerThread = ${t[1]}; const colPerThread = ${t[0]}; const tileInner = ${a}; @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 = ${i?"0":"i32(globalId.z)"}; ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${i?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${o}`:"0"}; var acc : array, rowPerThread>; ${w} } `},pc=(t,e,n,r,s,a=!1)=>{let[i,o,l]=s,[u,c,p,d]=r,f=mr(i,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 + ${a?"bias[colIn]":`${Je(t,g)}(bias[row])`};`:""} ${n} ${d.setByIndices("vec3(coords)","value")} } } `},sa=(t,e,n,r,s=!1,a)=>{let i=t[0].dims,o=t[1].dims,l=i.slice(0,-2),u=o.slice(0,-2),c=r?r.slice(0,-2):n.slice(0,-2),p=F.size(c),d=i[i.length-2],f=i[i.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/$],M=T.length,R=[p,d,m/$],L=[{type:6,data:d},{type:6,data:m},{type:6,data:f}];ln(e,L),L.push(...se(c,k,T));let G=["rank","rank"],K=t.length>2;K&&(L.push(...se(t[2].dims)),G.push("rank")),L.push(...se(R));let X=H=>{let ee=c.length,ne=ji("batchDims",t[0].dataType,ee,1),z=Le(t[0].dataType),N=U("a",t[0].dataType,E,$),B=U("b",t[1].dataType,M,$),Y=ie("result",t[0].dataType,R.length,$),te=[N,B];if(K){let ve=s?$:1;te.push(U("bias",t[2].dataType,t[2].dims.length,ve))}let O=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];un(e,O);let q=Le(Y.type.tensor),ae=on(e,Y.type.value,q),ge=pc($,K,ae,[ne,N,B,Y],[l,u,c],s);return` ${H.registerUniforms(O).registerInternalVariables(ne).declareVariables(...te,Y)} ${ge} ${g?ws(w,v,z,ne):ys(w,v,z,ne)} `};return{name:"MatMul",shaderCache:{hint:`${w};${e.activation};${g};${s}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:t[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:L}),getShaderSource:X}}}),hc,fc,i0=W(()=>{ue(),sn(),he(),dn(),_s(),lc(),bs(),hc=(t,e,n,r,s=!1,a,i=4,o=4,l=4,u="f32")=>{let c=L=>{switch(L){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 ${L} is not supported.`)}},p=L=>{switch(L){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${L} is not supported.`)}},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(i,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(i)} } return resData;`,$=t?e&&r?` let col = colIn * ${i}; ${y}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${y} } return ${Je(i,u)}(0.0);`:r&&n?` let col = colIn * ${i}; ${y}`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${y} } return ${Je(i,u)}(0.0);`,k=`${p(o)}`,E=Je(l,u),T=Je(t?i:o,u),M=Je(t?o:i,u),R=on(a,E,u);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${T} { ${t?$:k} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${M} { ${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} ${ta(s)} ${R} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},fc=(t,e,n,r,s,a,i,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],M=y[0]*$[0],R=Math.max(y[0]*E,y[1]),L=r%T===0,G=s%M===0,K=a%R===0,X=g?[E,4,4]:[1,1,1],H=[{type:6,data:r},{type:6,data:s},{type:6,data:a},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];ln(e,H),H.push(...se(t[0].dims,t[1].dims));let ee=["rank","rank"];i&&(H.push(...se(t[2].dims)),ee.push("rank")),H.push(...se(n));let ne=z=>{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}];un(e,N);let B=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=U("x",t[0].dataType,t[0].dims.length,E===3?1:E),q=U("w",t[1].dataType,t[1].dims.length,B),ae=[O,q],ge=ie("result",t[0].dataType,n.length,B);if(i){let ve=U("bias",t[2].dataType,t[2].dims.length,B);ae.push(ve),te+=` fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${Y}>`:Y} { return bias[coords.${u?"w":"y"}${g?"/ 4":""}]; }`}return` ${na("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 }; ${z.registerUniforms(N).declareVariables(...ae,ge)} ${te} ${hc(u,L,G,K,i,e,X[0],X[1],X[2],Y)} ${g?ws($,y,Y,void 0,!u,R):ys($,y,Y,void 0,!u,R,!1,void 0,o)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${E};${g};${L};${G};${K};${T};${M};${R}`,inputDependencies:ee},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}}}),mc,ia,wr,gc,aa,_c,wc,yc,a0=W(()=>{ue(),sn(),pe(),he(),dn(),_s(),mc=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),gc=(t,e,n,r=1)=>{let s=wr(e,r);return Math.floor((t[0]*(n-1)-n+s)/2)},aa=(t,e,n,r,s)=>{s==null&&(s=gc(t,e[0],r[0]));let a=[0,0,0,n];for(let i=0;i<3;i++)t[i]+2*s>=e[i]&&(a[i]=Math.trunc((t[i]-e[i]+2*s)/r[i]+1));return a},_c=(t,e,n,r,s,a,i,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=aa([e,n,r,1],[o,l,u],1,[s,a,i],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=aa([e,n,r,1],[o,l,u],1,[s,a,i],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/a),f=Math.ceil(r/i);let m=(p-1)*s+o-e,g=(d-1)*a+l-n,w=(f-1)*i+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}},wc=(t,e,n,r,s,a=!1,i="channelsLast")=>{let o,l,u,c,p;if(i==="channelsLast")[o,l,u,c,p]=t;else if(i==="channelsFirst")[o,p,l,u,c]=t;else throw new Error(`Unknown dataFormat ${i}`);let[d,,f,m,g]=e,[w,v,y]=ia(n),[$,k,E]=ia(r),T=wr(f,$),M=wr(m,k),R=wr(g,E),{padInfo:L,outDepth:G,outHeight:K,outWidth:X}=_c(s,l,u,c,w,v,y,T,M,R),H=a?d*p:d,ee=[0,0,0,0,0];return i==="channelsFirst"?ee=[o,H,G,K,X]:i==="channelsLast"&&(ee=[o,G,K,X,H]),{batchSize:o,dataFormat:i,inDepth:l,inHeight:u,inWidth:c,inChannels:p,outDepth:G,outHeight:K,outWidth:X,outChannels:H,padInfo:L,strideDepth:w,strideHeight:v,strideWidth:y,filterDepth:f,filterHeight:m,filterWidth:g,effectiveFilterDepth:T,effectiveFilterHeight:M,effectiveFilterWidth:R,dilationDepth:$,dilationHeight:k,dilationWidth:E,inShape:t,outShape:ee,filterShape:e}},yc=(t,e,n,r,s,a)=>{let i=a==="channelsLast";i?t[0].dims[3]:t[0].dims[1];let o=[64,1,1],l={x:n.map((w,v)=>v)},u=[Math.ceil(mc(l.x.map(w=>n[w]))/o[0]),1,1];Be("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let c=1,p=F.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}];ln(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}];un(e,v);let y=1,$=Le(t[0].dataType),k=U("x",t[0].dataType,t[0].dims.length,c),E=U("W",t[1].dataType,t[1].dims.length,y),T=[k,E],M=ie("result",t[0].dataType,n.length,y),R="";if(m){let K=U("bias",t[2].dataType,t[2].dims.length,y);T.push(K),R+=` fn getBiasByOutputCoords(coords : array) -> ${$} { return bias[${i?re("coords",4,5):re("coords",1,5)}]; }`}let L=Je(c,$),G=on(e,L,$);return` ${R} 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,M)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${M.offsetToIndices("global_idx")}; let batch = ${re("coords",0,k.rank)}; let d2 = ${i?re("coords",k.rank-1,k.rank):re("coords",1,k.rank)}; let xFRCCorner = vec3(${i?re("coords",1,k.rank):re("coords",2,k.rank)}, ${i?re("coords",2,k.rank):re("coords",3,k.rank)}, ${i?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 = ${i?re("uniforms.x_shape",1,k.rank):re("uniforms.x_shape",2,k.rank)}; let xShapeZ = ${i?re("uniforms.x_shape",2,k.rank):re("uniforms.x_shape",3,k.rank)}; let xShapeW = ${i?re("uniforms.x_shape",3,k.rank):re("uniforms.x_shape",4,k.rank)}; let xShapeU = ${i?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) { ${i?`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) { ${i?`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) { ${i?`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) { ${i?`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};${i};${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}}}),bc,vc,o0=W(()=>{ue(),pe(),he(),Cc(),dn(),bc=(t,e,n)=>{let r=t.length>2,s=r?"value += b[output_channel];":"",a=t[0].dims,i=t[1].dims,o=i[0]/e.group,l=e.format==="NHWC",u=vs(a,i,e.dilations,e.pads,e.strides,l),c=F.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}];ln(e,p),p.push(...se(a,i));let d=["rank","rank"];r&&(p.push(...se(t[2].dims)),d.push("rank")),p.push(...se(u));let f=m=>{let g=ie("output",t[0].dataType,u.length),w=Le(g.type.tensor),v=on(e,g.type.value,w),y=U("x",t[0].dataType,a.length),$=U("w",t[1].dataType,i.length),k=[y,$];r&&k.push(U("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 un(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}},vc=(t,e,n,r)=>{let s=t.length>2,a=Ue(n[3]),i=Ue(n[2]),o=F.size(n)/a/i,l=[t[0].dims[0],t[0].dims[1],t[0].dims[2],t[0].dims[3]/a],u=[t[1].dims[0],t[1].dims[1],t[1].dims[2],t[1].dims[3]/a],c=[n[0],n[1],n[2],n[3]/a],p=[{type:12,data:o},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];ln(e,p),p.push(...se(l,u,c));let d=(i-1)*e.strides[1]+u[1],f=m=>{let g=ie("output",t[0].dataType,c.length,a),w=Le(g.type.tensor),v=on(e,g.type.value,w),y=U("x",t[0].dataType,l.length,a),$=U("w",t[1].dataType,u.length,a),k=[y,$];s&&k.push(U("b",t[2].dataType,t[2].dims,a));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 un(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] / ${i}u; let col = (index1 % width1) * ${i}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${y.type.value}, ${d}>; var values: array<${g.type.value}, ${i}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${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 < ${i}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${i}u; i++) { var value = values[i]; ${E} ${v} ${g.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${a};${i};${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}}}),oa,xc,$c,kc=W(()=>{ue(),pe(),bs(),he(),dn(),oa=(t,e,n,r,s=!1,a)=>{let i=t[0].dims,o=t[1].dims,l=i[i.length-2],u=o[o.length-1],c=i[i.length-1],p=Ue(u),d=Ue(c),f=Ue(l),m=F.size(n)/p/f,g=t.length>2,w=r?r.slice(0,-2):n.slice(0,-2),v=[F.size(w),l,u],y=[{type:12,data:m},{type:12,data:l},{type:12,data:u},{type:12,data:c}];ln(e,y),y.push(...se(w,i,o)),g&&y.push(...se(t[2].dims)),y.push(...se(v));let $=k=>{let E=ji("batch_dims",t[0].dataType,w.length),T=U("a",t[0].dataType,i.length,d),M=U("b",t[1].dataType,o.length,p),R=ie("output",t[0].dataType,v.length,p),L=Le(R.type.tensor),G=on(e,R.type.value,L),K=[T,M],X="";if(g){let te=s?p:1;K.push(U("bias",t[2].dataType,t[2].dims.length,te)),X=`${s?`value += bias[col / ${te}];`:`value += ${R.type.value}(bias[row + i]);`}`}let H=i.slice(0,-2),ee=o.slice(0,-2),ne=mr(H,w),z=mr(ee,w),N=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];un(e,N);let B=(te,O)=>{let q=te.rank,ae=te.name;if(q===2)return`var ${ae}_indices = ${te.type.indices}(0u, 0u);`;let ge=E.rank,ve=`var ${ae}_indices: ${te.type.indices};`;for(let Ee=q-2-1,ut=ge-1;Ee>=0;Ee--,ut--)ve+=` ${ae}_indices[${Ee}] = ${ge>1?`batch_indices[${ut}]`:"batch_indices"};`;return O.forEach(Ee=>{ve+=` ${ae}_indices[${Ee}] = 0;`}),ve+=`${ae}_indices[${q-2}] = 0u; ${ae}_indices[${q-1}] = 0u;`,ve},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 = ${R.type.indices}(batch, row + i, col); let offset = ${R.indicesToOffset("cur_indices")}; ${R.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:a?a(n):n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$}},xc=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.")},$c=t=>{xc(t.inputs);let e=Gn.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(oa(t.inputs,{activation:""},e)):t.compute(sa(t.inputs,{activation:""},e))}}),vs,xs,Sc,$s,la,ua,Ec,Tc,da,Cc=W(()=>{pe(),i0(),a0(),bs(),o0(),dn(),kc(),Kn(),vs=(t,e,n,r,s,a)=>{let i=t[0],o=t.slice(a?1:2,a?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,i),p.splice(a?3:1,0,u),p},xs=[2,3,1,0],Sc=(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 a=2;a{let e=ea(t),n=t.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],s=t.dilations,a=t.group,i=t.kernel_shape,o=t.pads,l=t.strides,u=t.w_is_const();return{autoPad:r,format:n,dilations:s,group:a,kernelShape:i,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${t.format};${e.activation};`}},ua=(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),M=t.kernelCustomData.wT??t.compute(Dt(e[1],xs),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=M);let R=[e[0],M];e.length===3&&R.push(e[2]),t.compute(vc(R,n,T,r),{inputs:R})}else t.compute(bc(e,n,r));return}let a=e.length===3,i=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===i&&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],M,R,L,G=[];if(s){let H=t.kernelCustomData.wT??t.compute(Dt(e[1],xs),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=H),g){let ee=i*o*l;M=e[0].reshape([1,T,ee]),R=H.reshape([1,ee,m]),L=[1,T,m]}else M=e[0].reshape([T,i*o,l]),R=H.reshape([1,l,m]),L=[T,d*f,m];G.push(M),G.push(R)}else M=e[0].reshape([T,l,i*o]),R=e[1].reshape([1,m,l]),L=[T,m,d*f],G.push(R),G.push(M);a&&G.push(e[2]);let K=L[2],X=G[0].dims[G[0].dims.length-1];K<8&&X<8?t.compute(oa(G,n,p,L,s,r),{inputs:G}):t.compute(sa(G,n,p,L,s,r),{inputs:G});return}let w=!0,v=t.kernelCustomData.wT??t.compute(Dt(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];a&&y.push(e[2]);let $=s?d*f:m,k=s?m:d*f,E=u*c*l;t.compute(fc(y,n,p,$,k,E,a,w,r),{inputs:y})},Ec=(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]],a=[1].concat(e.strides),i=[1].concat(e.dilations),o=[1].concat(e.kernelShape),l=$s({...e,pads:s,strides:a,dilations:i,kernelShape:o},r);ua(t,r,l,u=>n?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},Tc=(t,e,n)=>{let r=n.format==="NHWC"?"channelsLast":"channelsFirst",s=$s(n,e),a=n.autoPad==="NOTSET"?n.pads:n.autoPad,i=wc(e[0].dims,e[1].dims,n.strides,n.dilations,a,!1,r);t.compute(yc(e,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],r))},da=(t,e)=>{if(Sc(t.inputs,e),t.inputs[0].dims.length===3)Ec(t,e);else if(t.inputs[0].dims.length===5)Tc(t,t.inputs,e);else{let n=$s(e,t.inputs);ua(t,t.inputs,n)}}}),Mc,Ac,l0=W(()=>{ue(),sn(),he(),dn(),_s(),lc(),bs(),Mc=(t,e=!1,n,r,s=4)=>{let a=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.`)}},i=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; ${i} 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); ${a(s)} } return ${r}(0.0); `,g=on(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} ${ta(e)} ${g} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; } }`},Ac=(t,e,n,r,s,a,i,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,M=[e.kernelShape[l?1:2],e.kernelShape[l?2:3]],R=[M[0]+(e.dilations[0]<=1?0:(M[0]-1)*(e.dilations[0]-1)),M[1]+(e.dilations[1]<=1?0:(M[1]-1)*(e.dilations[1]-1))],L=[R[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),R[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],G=[{type:6,data:r},{type:6,data:s},{type:6,data:a},{type:6,data:e.strides},{type:6,data:e.dilations},{type:6,data:M},{type:6,data:L}];ln(e,G),G.push(...se(t[0].dims,t[1].dims));let K=["rank","rank"];i&&(G.push(...se(t[2].dims)),K.push("rank")),G.push(...se(n));let X=H=>{let ee=U("x",t[0].dataType,t[0].dims.length,T),ne=U("w",t[1].dataType,t[1].dims.length,1),z=ie("result",t[0].dataType,n.length,T),N=[ee,ne],B="";if(i){let O=U("bias",t[2].dataType,t[2].dims.length,T);N.push(O),B+=` 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:M.length},{name:"pads",type:"i32",length:L.length}];un(e,Y);let te=Le(t[0].dataType,1);if(te!=="f16"&&te!=="f32")throw new Error(`elemType ${te} is not supported.`);return` ${na("uniforms.result_strides")} ${H.registerUniforms(Y).declareVariables(...N,z)}; ${B} ${Mc(l,i,e,ee.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}}}),Ic,ca,u0=W(()=>{ue(),sn(),pe(),he(),Ic=(t,e,n,r,s,a=!1,i,o,l=!1)=>{let u=l?1:2,c=l?2:3,p=l?3:1,d=a?2:1,f=` fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { result[flatIndex] = ${a?`vec4<${i}>`:i}(value); }`;r&&(f+=` fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { return bias[coords.${l?"w":"y"}${a?"/ 4":""}]; }`);let m=a?4:1,g=U("W",e[1].dataType,e[1].dims.length,m),w=U("Dy",e[0].dataType,e[0].dims.length,m),v=[w,g];r&&v.push(U("bias",e[2].dataType,[n[p]].length,m));let y=ie("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<${i}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${i}(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 = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(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 >= ${i}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${i}(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<${i}>(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<${i}>(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<${i}>(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<${i}>(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<${i}>(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 = ${i}(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 = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${i}(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 = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${i}(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]":`${i}(0.0)`}; ${y.setByOffset("global_idx","value")}; `;return` ${t.registerUniforms(o).declareVariables(...v,y)} ${f} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${a?$:k}}`},ca=(t,e,n)=>{let r=t.length>2,s=e.outputShape,a=F.size(s),i=[Math.ceil(a/64),1,1];Be("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);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:a},{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=i[1]===1&&i[2]===1,E=T=>{let M=[{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"}],R=Le(t[0].dataType);return`${Ic(T,t,s,r,k,m,R,M,o)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:n?n(s):s,dataType:t[0].dataType}],programUniforms:$}),getShaderSource:E}}}),zc,Oc,Pc,pa,Bc,Rc,Dc,Fc,Nc,Lc,d0=W(()=>{l0(),u0(),dn(),Kn(),zc=(t,e,n,r,s,a)=>(t-1)*e+n+(r-1)*s+1-a,Oc=(t,e,n,r,s)=>{let a=Math.floor(t/2);e==="SAME_UPPER"?(n[r]=a,n[s]=t-a):e==="SAME_LOWER"&&(n[r]=t-a,n[s]=a)},Pc=(t,e,n,r,s,a,i,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)}Pc(o,n,l,t.autoPad,t.group,s,u,r,i,a);let c=Object.assign({},t);return Object.assign(c,{kernelShape:n,pads:s,outputPadding:i,outputShape:a,dilations:l,strides:u}),c},Bc=t=>{let e=ea(t),n=t.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof t.autoPad>"u"?0:t.autoPad],s=t.dilations,a=t.group,i=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:a,kernelShape:i,outputPadding:c,outputShape:p,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${t.format};${e.activation};`}},Rc=(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 a=t[0].dims.length-2;if(e.dilations.reduce((i,o)=>i+o,0)>0&&e.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(e.strides.reduce((i,o)=>i+o,0)>0&&e.strides.length!==a)throw new Error(`strides should be ${a}D`);if(e.pads.reduce((i,o)=>i+o,0)>0&&e.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(e.outputPadding.length!==a&&e.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(e.kernelShape.reduce((i,o)=>i+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],Fc=(t,e,n)=>{let r=pa(n,e),s=n.format==="NHWC",a=r.outputShape,i=a[s?3:1],o=e[0].dims[s?3:1];if(r.group!==1||i===1&&o===1){t.compute(ca(e,r));return}let l=a[s?1:2],u=a[s?2:3],c=e[1].dims[2],p=e[1].dims[3],d=s?l*u:i,f=s?i:l*u,m=c*p*o,g=!0,w=t.kernelCustomData.wT??t.compute(Dt(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(Ac(v,r,a,d,f,m,y,g),{inputs:v})},Nc=(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 a=e.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=e.strides;(i.length===0||i[0]===0)&&(i=[1]);let o=e.pads;o.length===0&&(o=[0,0]),o=[0,o[0],0,o[1]],i=[1].concat(i),a=[1].concat(a),s=[1].concat(s);let l=pa({...e,pads:o,strides:i,dilations:a,kernelShape:s},r);t.compute(ca(r,l,u=>n?[u[0],u[2],u[3]]:[u[0],u[1],u[3]]))},Lc=(t,e)=>{Rc(t.inputs,e),t.inputs[0].dims.length===3?Nc(t,e):Fc(t,t.inputs,e)}}),Uc,Vc,jc,c0=W(()=>{ue(),pe(),De(),he(),Uc=(t,e,n,r)=>{let s=F.size(e),a=e.length,i=U("input",t,a),o=ie("output",t,a),l=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),u=F.normalizeAxis(l,a),c=p=>{let d=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=re("uniforms.input_shape","uniforms.axis",a),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(i,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++) { ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${i.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}},Vc=(t,e)=>{let n=t.inputs[0].dims,r=t.inputs[0].dataType,s=t.inputs[1];t.compute(Uc(r,n,s,e),{inputs:[0]})},jc=t=>{let e=t.exclusive===1,n=t.reverse===1;return xe({exclusive:e,reverse:n})}}),qc,Gc,Wc,Hc,Kc,p0=W(()=>{ue(),pe(),De(),he(),qc=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.")},Gc=(t,e,n,r)=>{let s=[];s.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} { var a: ${n.type.indices};`);for(let a=0;a{let n,r,s,a,i,o,l=e.format==="NHWC",u=e.blocksize,c=e.mode==="DCR";l?([n,r,s,a]=t.dims,i=c?[n,r,s,u,u,a/u**2]:[n,r,s,a/u**2,u,u],o=c?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,r,s,a]=[t.dims[0],t.dims[2],t.dims[3],t.dims[1]],i=c?[n,u,u,a/u**2,r,s]:[n,a/u**2,u,u,r,s],o=c?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let p=t.reshape(i),d=p.dims.length,f=t.dataType,m=U("a",f,d),g=ie("output",f,d),w=v=>` ${v.registerUniform("output_size","u32").declareVariables(m,g)} ${Gc(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,a/u**2]:[n,a/u**2,r*u,s*u],$=F.size(y),k=p.dims,E=F.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}},Hc=(t,e)=>{qc(t.inputs),t.compute(Wc(t.inputs[0],e))},Kc=t=>xe({blocksize:t.blocksize,mode:t.mode,format:t.format})}),ks,yr,ha,Xc,Qc,Yc,Zc,fa,Jc,ep,tp,h0=W(()=>{ue(),pe(),De(),he(),ks="[a-zA-Z]|\\.\\.\\.",yr="("+ks+")+",ha="^"+yr+"$",Xc="("+yr+",)*"+yr,Qc="^"+Xc+"$",Yc=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)}},Zc=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(Qc)))throw new Error("Invalid LHS term");if(n.split(",").forEach((a,i)=>{let o=t[i].dims.slice();if(!a.match(RegExp(ha)))throw new Error("Invalid LHS term");let l=this.processTerm(a,!0,o,i);this.lhs.push(l)}),r==="")r+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!r.match(RegExp(yr)))throw new Error("Invalid RHS");(s=r.match(RegExp(ks,"g")))==null||s.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(t,e,n){let r=this.symbolToInfo.get(t);if(r!==void 0){if(r.dimValue!==e&&r.count!==1)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:e,inputIndices:[n]};this.symbolToInfo.set(t,r)}processTerm(t,e,n,r=-1){let s=n.length,a=!1,i=[],o=0;if(!t.match(RegExp(ha))&&!e&&t!=="")throw new Error("Invalid LHS term");let l=t.match(RegExp(ks,"g")),u=new Yc(r);return l==null||l.forEach((c,p)=>{if(c==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let d=s-l.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(i=n.slice(o,o+d),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(e)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;ft+"_max",Jc=(t,e,n,r)=>{let s=t.map(u=>u.length).map((u,c)=>U(`input${c}`,e,u)),a=F.size(r),i=ie("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 M=(T=n.rhs.symbolToIndices.get(E))==null?void 0:T[0];M!==void 0&&n.lhs.forEach((R,L)=>{if(k.inputIndices.includes(L)){let G=R.symbolToIndices.get(E);if(G===void 0)throw new Error("Invalid symbol error");G.forEach(K=>{c.push(`${s[L].indicesSet(`input${L}Indices`,K,i.indicesGet("outputIndices",M))}`)})}})}else n.lhs.forEach((M,R)=>{if(k.inputIndices.includes(R)){let L=M.symbolToIndices.get(E);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(G=>{m.push(`${s[R].indicesSet(`input${R}Indices`,G,`${E}`)}`)}),v.push(`prod *= ${s[R].getByIndices(`input${R}Indices`)};`)}}),g.push(`for(var ${E}: u32 = 0; ${E} < uniforms.${fa(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:`${fa(k)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${s.map((k,E)=>`var input${E}Indices: ${s[E].type.indices};`).join(` `)} ${$.join(` `)}; ${i.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:a});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(a/64)},programUniforms:c}},getShaderSource:l}},ep=(t,e)=>{let n=new Zc(t.inputs,e.equation),r=n.outputDims,s=t.inputs.map((a,i)=>a.dims);t.compute(Jc(s,t.inputs[0].dataType,n,r))},tp=t=>{let e=t.equation.replace(/\s+/g,"");return xe({equation:e})}}),np,ma,rp,sp,ip,f0=W(()=>{ue(),pe(),he(),np=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?ma(t,e):ma(e,t),sp=t=>{let e=t[0].dims,n=Array.from(t[1].getBigInt64Array(),Number),r=rp(e,n),s=t[0].dataType,a=s===9?4:1,i=Math.ceil(F.size(r)/a),o=u=>{let c=U("input",s,e.length,a),p=ie("output",s,r.length,a),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 * ${a}; 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:i},...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(i/64)},programUniforms:l})}},ip=t=>{np(t.inputs),t.compute(sp(t.inputs),{inputs:[0]})}}),ap,op,m0=W(()=>{ue(),pe(),he(),Ji(),ap=t=>{let e=t[0].dataType,n=F.size(t[0].dims),r=F.size(t[1].dims),s=r%4===0,a=i=>{let o=U("x",e,[1],4),l=U("bias",e,[1],4),u=ie("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`${i.registerUniforms(c).declareVariables(o,l,u)} ${Yi(Ze(e))} ${i.mainStart(Wn)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${o.getByOffset("global_idx")}; ${d} let x_in = x + bias; ${u.setByOffset("global_idx",Zi("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/Wn/4)}})}},op=t=>{t.inputs.length<2||F.size(t.inputs[1].dims)===0?Bd(t):t.compute(ap(t.inputs))}}),lp,up,dp,cp,g0=W(()=>{ue(),pe(),De(),he(),lp=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},up=(t,e)=>{let n=t[0].dims,r=t[1].dims,s=n.length,a=F.normalizeAxis(e.axis,s),i=n.slice(0);i.splice(a,1,...r);let o=n[a],l=t[0].dataType===9?4:1,u=Math.ceil(F.size(i)/l),c=[{type:12,data:u},{type:6,data:o},{type:12,data:a},...se(t[0].dims,t[1].dims,i)],p=d=>{let f=U("data",t[0].dataType,t[0].dims.length,l),m=U("inputIndices",t[1].dataType,t[1].dims.length),g=ie("output",t[0].dataType,i.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}`} = ${i.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}`} = ${i.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:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}),getShaderSource:p}},dp=t=>xe({axis:t.axis}),cp=(t,e)=>{let n=t.inputs;lp(n),t.compute(up(t.inputs,e))}}),pp,hp,fp,mp,_0=W(()=>{ue(),pe(),De(),he(),pp=(t,e)=>{if(t.length<3||t.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=F.normalizeAxis(e.quantizeAxis,t[0].dims.length),r=e.blockSize,s=t[0],a=t[2],i=t.length===4?t[3]:void 0;if(a.dims.length!==s.dims.length||!s.dims.map((o,l)=>l===n?Math.ceil(o/r)===a.dims[l]:o===a.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(i){if(i.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((o,l)=>o===a.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.")}},hp=(t,e)=>{let n=t[0].dims,r=t[1].dims,s=n.length,a=F.normalizeAxis(e.gatherAxis,s),i=F.normalizeAxis(e.quantizeAxis,s),o=n.slice(0);o.splice(a,1,...r);let l=F.size(o),u=t[2].dataType,c=t[0].dataType===22,p=[{type:12,data:l},{type:12,data:i},{type:12,data:a},{type:12,data:e.blockSize},...se(...t.map((f,m)=>f.dims),o)],d=f=>{let m=U("data",t[0].dataType,t[0].dims.length),g=U("inputIndices",t[1].dataType,t[1].dims.length),w=U("scales",t[2].dataType,t[2].dims.length),v=t.length>3?U("zeroPoint",t[3].dataType,t[3].dims.length):void 0,y=ie("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[a]}; } ${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}},fp=(t,e)=>{let n=t.inputs;pp(n,e),t.compute(hp(t.inputs,e))},mp=t=>xe({blockSize:t.blockSize,gatherAxis:t.gatherAxis,quantizeAxis:t.quantizeAxis})}),gp,_p,wp,yp,w0=W(()=>{ue(),pe(),De(),he(),gp=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.`)},_p=(t,e)=>{let n=t[0].dims,r=t[0].dataType,s=n.length,a=t[1].dims,i=t[1].dataType,o=F.normalizeAxis(e.axis,s),l=n[o],u=a.slice(0),c=F.size(u),p=U("input",r,s),d=U("indicesInput",i,a.length),f=ie("output",r,u.length),m=[{type:12,data:c},{type:6,data:l},{type:12,data:o}];return m.push(...se(n,a,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")}; }`}},wp=t=>xe({axis:t.axis}),yp=(t,e)=>{let n=t.inputs;gp(n),t.compute(_p(t.inputs,e))}}),bp,vp,xp,$p,y0=W(()=>{ue(),pe(),he(),bp=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")},vp=(t,e)=>{let n=t[0].dims.slice(),r=t[1].dims.slice(),[s,a,i]=Wl.getShapeOfGemmResult(n,e.transA,r,e.transB,t.length===3?t[2].dims:void 0),o=[s,a];if(!o)throw new Error("Can't use gemm on the given tensors");let l=F.size(o),u=[{type:12,data:l},{type:12,data:s},{type:12,data:a},{type:12,data:i},{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=U("a",t[0].dataType,t[0].dims),w=U("b",t[1].dataType,t[1].dims),v=g.type.value,y=null,$=[g,w];t.length===3&&(y=U("c",t[2].dataType,t[2].dims.length),$.push(y));let k=ie("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}},xp=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}`}},$p=(t,e)=>{bp(t.inputs),t.compute(vp(t.inputs,e))}}),rt,kp,Sp,ga,Ep,br,Tp,Cp=W(()=>{ue(),pe(),De(),Di(),Xi(),he(),Kn(),rt=(t,e)=>t.length>e&&t[e].dims.length>0?t[e]:void 0,kp=(t,e)=>{let n=t[0],r=rt(t,1),s=rt(t,2),a=rt(t,3),i=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&&F.size(l.dims)&&F.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&&F.size(l.dims)||u&&F.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v;if(r&&F.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(a&&F.size(a.dims)>0){if(a.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(i&&F.size(i.dims)>0){$=8;let M=i.dims;throw M.length===1?M[0]===c?$=1:M[0]===3*c+2&&($=3):M.length===2&&M[0]===c&&M[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&&F.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(i&&F.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(o&&F.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}},Sp=t=>xe({...t}),ga=xe({perm:[0,2,1,3]}),Ep=(t,e,n,r,s,a,i)=>{let o=[r,s,a],l=F.size(o),u=[{type:12,data:l},{type:12,data:i},{type:12,data:a}],c=p=>{let d=ie("qkv_with_bias",e.dataType,o),f=U("qkv",e.dataType,o),m=U("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,a,i,o)=>{let l=a;if(i&&F.size(i.dims)>0){if(r===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Ep(t,a,i,e,r,n*s,o),l=l.reshape([e,r,n,s]),t.compute(Dt(l,ga.perm),{inputs:[l],outputs:[-1]})[0]}else return a.dims.length===3&&(l=a.reshape([e,r,n,s])),t.compute(Dt(l,ga.perm),{inputs:[l],outputs:[-1]})[0]},Tp=(t,e)=>{let n=kp(t.inputs,e),r=t.inputs[0],s=rt(t.inputs,1),a=rt(t.inputs,2),i=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&&a&&s.dims.length===4&&a.dims.length===4,d=br(t,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,i,0);if(p)return gr(t,d,s,a,o,void 0,u,c,l,n,e);if(!s||!a)throw new Error("key and value must be provided");let f=br(t,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,s,i,n.hiddenSize),m=br(t,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,a,i,2*n.hiddenSize);gr(t,d,f,m,o,void 0,u,c,l,n,e)}}),_a,Mp,Ap,wa,Ip,zp=W(()=>{ue(),pe(),he(),_a=t=>Array.from(t.getBigInt64Array(),Number),Mp=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(_a(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")},Ap=(t,e)=>{let n=[];for(let r=0;r{let n=t[0].dims,r=e??_a(t[1]),s=Ap(n,r),a=F.size(s),i=t[0].dataType,o=U("input",i,n.length),l=ie("output",i,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(a/64)},programUniforms:[{type:12,data:a},...se(t[0].dims,s)]}),getShaderSource:u}},Ip=t=>{Mp(t.inputs),t.compute(wa(t.inputs),{inputs:[0]})}}),Op,ya,Pp,Bp,ba,Rp,b0=W(()=>{ue(),pe(),De(),Xi(),he(),Cp(),zp(),Kn(),Op=(t,e)=>{let n=t[0],r=t[1],s=t[2],a=t[3],i=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=a&&a.dims.length!==0,w=i&&i.dims.length!==0,v=!0;if(g&&w){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=a.dims[1],f=a.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}},ya=(t,e,n,r)=>{let s=[r.batchSize,r.totalSequenceLength,r.kvNumHeads,r.headSize],a=4,i=F.size(s)/a,o=r.totalSequenceLength,l=ie("present_kv",n,s.length,a),u=U("new_kv",t.dataType,t.dims.length,a),c=e?U("past_kv",e.dataType,e.dims.length,a):void 0,p=Math.ceil(r.headSize/a),d={x:o,y:t.dims[0],z:1},f=e?["rank","rank"]:["rank"],m=[{type:12,data:i},{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}},Pp=t=>xe({...t}),Bp=xe({perm:[0,2,1,3]}),ba=(t,e,n,r,s)=>{let a=e,i=r.kvNumHeads,o=r.nReps;return e.dims.length===3&&r.kvSequenceLength!==0&&(a=e.reshape([r.batchSize,r.kvSequenceLength,i,r.headSize])),n?a=t.compute(ya(a,n,a.dataType,r),{inputs:[a,n],outputs:[r.isPastkvBSNH?s:-1]})[0]:a=t.compute(ya(a,void 0,a.dataType,r),{inputs:[a],outputs:[r.isPastkvBSNH?s:-1]})[0],o!==1&&(a=t.compute(wa([a],[1,1,1,o]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([r.batchSize,r.totalSequenceLength,i*o,r.headSize])),t.compute(Dt(a,Bp.perm),{inputs:[a],outputs:[-1]})[0]},Rp=(t,e)=>{var l;let n=Op(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,a=t.inputs[4]&&t.inputs[4].dims.length!==0?t.inputs[4]:void 0,i=ba(t,t.inputs[1],s,n,1),o=ba(t,t.inputs[2],a,n,2);gr(t,r,i,o,void 0,void 0,void 0,void 0,void 0,n,e)}}),Dp,Fp,Np,Lp,v0=W(()=>{ue(),pe(),he(),Dp=(t,e)=>{let n=t[0].dims,r=n,s=2,a=F.sizeToDimension(n,s),i=F.sizeFromDimension(n,s),o=Ue(i),l=i/o,u=[n[0],n[1],l],c=["rank","type","type"],p=[{type:12,data:i},{type:12,data:l}];p.push(...se(u,u));let d=f=>{let m=U("x",t[0].dataType,u.length,o),g=U("scale",t[1].dataType,t[1].dims),w=U("bias",t[2].dataType,t[2].dims),v=ie("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 = ${an("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 = ${an("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:a},programUniforms:p}),getShaderSource:d}},Fp=(t,e,n,r,s,a,i,o)=>{let l=Ue(i),u=64,c=l===1?"vec2f":`mat2x${l}f`,p=l===1?"f32":`vec${l}f`,d=(T,M)=>`${c}(${T}, ${M})`,f=s*i/l,m=Math.ceil(a/u),g=["type"],w=[{type:12,data:m},{type:12,data:a},{type:12,data:Math.floor(i/l)},{type:12,data:Math.floor(a*i/l)}],v=T=>{let M=U("input",e.dataType,e.dims,l);return` ${T.declareVariables(M)} @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,i,u,2],dataType:1}],dispatchGroup:{x:s*i/l},programUniforms:w}),getShaderSource:v},{inputs:[e],outputs:[-1]})[0],$=[{type:12,data:f},{type:12,data:a},{type:12,data:Math.floor(i/l)},{type:12,data:Math.floor(u*i/l)}],k=["type","type","type"],E=T=>{let M=U("scale",n.dataType,n.dims,l),R=U("bias",r.dataType,r.dims,l);return` @group(0) @binding(0) var input : array<${c}>; @group(0) @binding(1) var scale : array<${M.type.storage}>; @group(0) @binding(2) var bias : array<${R.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,i,2],dataType:1}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:$}),getShaderSource:E},{inputs:[y,n,r],outputs:[-1]})[0]},Np=(t,e,n)=>{let r=e[0].dims,s=r,a=r[0],i=r[r.length-1],o=F.sizeFromDimension(r,1)/i,l=Ue(i),u=F.size(s)/l,c=[{type:12,data:o},{type:12,data:Math.floor(i/l)}],p=["type","type"],d=Fp(t,e[0],e[1],e[2],a,o,i,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=U("input",e[0].dataType,e[0].dims,l),$=ie("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]})},Lp=(t,e)=>{e.format==="NHWC"?Np(t,t.inputs,e):t.compute(Dp(t.inputs,e))}}),Up,Vp,jp,x0=W(()=>{ue(),pe(),he(),Up=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Vp=(t,e,n)=>{let r=e.simplified,s=t[0].dims,a=t[1],i=!r&&t[2],o=s,l=F.normalizeAxis(e.axis,s.length),u=F.sizeToDimension(s,l),c=F.sizeFromDimension(s,l),p=F.size(a.dims),d=i?F.size(i.dims):0;if(p!==c||i&&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),M=[U("x",t[0].dataType,t[0].dims,m),U("scale",a.dataType,a.dims,m)];i&&M.push(U("bias",i.dataType,i.dims,m)),M.push(ie("output",t[0].dataType,o,m)),v&&M.push(ie("mean_data_output",1,f)),y&&M.push(ie("inv_std_output",1,f));let R=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${E.registerUniforms(R).declareVariables(...M)} ${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 = ${Hn(T,m,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${an("mean_vector",m)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${an("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 = ${Hn(T,m,"x[j + offset]")}; let f32scale = ${Hn(T,m,"scale[j]")}; output[j + offset] = ${M[0].type.value}((f32input ${r?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${Hn(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:$}},jp=(t,e)=>{Up(t.inputs),t.compute(Vp(t.inputs,e,t.outputCount))}}),qp,Gp,Wp,Hp,$0=W(()=>{ue(),pe(),De(),he(),qp=(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),a=e.blockSize/8*e.bits,i=t[1];if(!F.areEqual(i.dims,[e.n,s,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=t[2].dims;if(F.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(F.size(l)!==u)throw new Error("zeroPoints input size error.")}},Gp=(t,e)=>{let n=t[0].dims,r=n.length,s=n[r-2],a=e.k,i=e.n,o=n.slice(0,r-2),l=F.size(o),u=t[1].dims[2]/4,c=t[0].dataType,p=Ue(e.k),d=Ue(u),f=Ue(i),m=o.concat([s,i]),g=s>1&&i/f%2===0?2:1,w=F.size(m)/f/g,v=64,y=[],$=[l,s,a/p],k=F.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(F.convertShape(t[3].dims)));let E=[l,s,i/f];y.push(...se(E));let T=M=>{let R=$.length,L=U("a",t[0].dataType,R,p),G=U("b",12,k.length,d),K=U("scales",t[2].dataType,t[2].dims.length),X=[L,G,K],H=t.length===4?U("zero_points",12,t[3].dims.length):void 0;H&&X.push(H);let ee=E.length,ne=ie("output",t[0].dataType,ee,f),z=Le(t[0].dataType),N=(()=>{switch(p){case 1:return`array<${z}, 8>`;case 2:return`mat4x2<${z}>`;case 4:return`mat2x4<${z}>`;default:throw new Error(`${p}-component is not supported.`)}})(),B=()=>{let O=` // reuse a data var input_offset = ${L.indicesToOffset(`${L.type.indices}(batch, row, word_offset)`)}; var a_data: ${N}; for (var j: u32 = 0; j < ${8/p}; j++) { a_data[j] = ${L.getByOffset("input_offset")}; input_offset++; } `;for(let q=0;q> 4) & b_mask); b_quantized_values = ${N}(${Array.from({length:4},(ae,ge)=>`${z}(b_value_lower[${ge}]), ${z}(b_value_upper[${ge}])`).join(", ")}); b_dequantized_values = ${p===1?`${N}(${Array.from({length:8},(ae,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},(ae,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 = ${z}(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} = ${z}((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}>; ${M.declareVariables(...X,ne)} ${M.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++) { ${B()} 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}},Wp=(t,e)=>{qp(t.inputs,e),t.compute(Gp(t.inputs,e))},Hp=t=>xe(t)}),Kp,Xp,Qp,Yp,Zp,Jp,eh,th,nh,k0=W(()=>{ue(),pe(),he(),Kp=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].")}},Xp=(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]; } `},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) { 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]; `},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 = 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]; `},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 += 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]; `},Jp=(t,e,n)=>{switch(n.mode){case 0:return Xp(t,e,n.pads.length);case 1:return Qp(t,e,n.pads.length);case 2:return Yp(t,e,n.pads.length);case 3:return Zp(t,e,n.pads.length);default:throw new Error("Invalid mode")}},eh=(t,e)=>{let n=F.padShape(t[0].dims.slice(),e.pads),r=t[0].dims,s=F.size(n),a=[{type:12,data:s},{type:6,data:e.pads}],i=t.length>=3&&t[2].data;e.mode===0&&a.push({type:i?t[2].dataType:1,data:e.value}),a.push(...se(t[0].dims,n));let o=["rank"],l=u=>{let c=ie("output",t[0].dataType,n.length),p=U("x",t[0].dataType,r.length),d=p.type.value,f=Jp(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:i?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}${i}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(F.size(n)/64)},programUniforms:a}),getShaderSource:l}},th=(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,a=new Int32Array(2*s).fill(0);if(t.length>=4){let o=t[3].getBigInt64Array();for(let l=0;la[Number(l)]=Number(o));let i=[];return a.forEach(o=>i.push(o)),{mode:e.mode,value:r,pads:i}}else return e},nh=(t,e)=>{Kp(t.inputs);let n=th(t.inputs,e);t.compute(eh(t.inputs,n),{inputs:[0]})}}),vr,va,xa,$a,ka,rh,sh,Sa,Ea,ih,ah,Ta,oh,lh,Ca,uh,dh,ch,ph,S0=W(()=>{Tt(),ue(),pe(),he(),vr=t=>{if(Te.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},va=(t,e,n)=>{let r=e.format==="NHWC",s=t.dims.slice();r&&s.splice(1,0,s.pop());let a=Object.hasOwnProperty.call(e,"dilations"),i=e.kernelShape.slice(),o=e.strides.slice(),l=a?e.dilations.slice():[],u=e.pads.slice();ps.adjustPoolAttributes(n,s,i,o,l,u);let c=ps.computePoolOutputShape(n,s,o,l,i,u,e.autoPad),p=Object.assign({},e);a?Object.assign(p,{kernelShape:i,strides:o,pads:u,dilations:l,cacheKey:e.cacheKey}):Object.assign(p,{kernelShape:i,strides:o,pads:u,cacheKey:e.cacheKey});let d=c.slice();return d.push(d.splice(1,1)[0]),[p,r?d:c]},xa=(t,e)=>{let n=e.format==="NHWC",r=F.size(t),s=F.size(e.kernelShape),a=[{type:12,data:r},{type:12,data:s}],i=[{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);a.push({type:12,data:o},{type:12,data:l},{type:12,data:u},{type:12,data:c}),i.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),a.push({type:12,data:f},{type:12,data:m},{type:12,data:g},{type:12,data:w}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,p,d]}else{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let o=F.computeStrides(e.kernelShape);a.push({type:12,data:o},{type:12,data:e.pads},{type:12,data:e.strides}),i.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[a,i,!!l,!1,!1]}},$a=(t,e,n,r,s,a,i,o,l,u,c,p)=>{let d=s.format==="NHWC",f=e.type.value,m=ie("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")}]; ${a} }`: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")}]; ${a} }`,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} ${i} 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")}]; ${a} }`:v=` } let x_val = x[${e.indicesToOffset("xIndices")}]; ${a} `,` ${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} } ${i} output[global_idx] = value; }`}},ka=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,rh=t=>`${ka(t)};${t.countIncludePad}`,sh=t=>`${ka(t)};${t.storageOrder};${t.dilations}`,Sa=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}),Ea=(t,e,n,r)=>{let[s,a]=va(e,r,n),i=U("x",e.dataType,e.dims.length),o=i.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]=xa(a,s);c.push(...se(e.dims,a));let g=["rank"];return{name:t,shaderCache:{hint:`${r.cacheKey};${d};${f};${m}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(F.size(a)/64)},programUniforms:c}),getShaderSource:w=>$a(w,i,e.dims.length,a.length,s,l,u,0,p,d,f,m)}},ih=t=>{let e=t.count_include_pad!==0,n=Sa(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:rh(r)}},ah=(t,e)=>{vr(t.inputs),t.compute(Ea("AveragePool",t.inputs[0],!1,e))},Ta={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},oh=t=>{let e=t.format;return{format:e,...Ta,cacheKey:e}},lh=(t,e)=>{vr(t.inputs),t.compute(Ea("GlobalAveragePool",t.inputs[0],!0,e))},Ca=(t,e,n,r)=>{let[s,a]=va(e,r,n),i=` value = max(x_val, value); `,o="",l=U("x",e.dataType,e.dims.length),u=["rank"],[c,p,d,f,m]=xa(a,s);return c.push(...se(e.dims,a)),{name:t,shaderCache:{hint:`${r.cacheKey};${d};${f};${m}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(F.size(a)/64)},programUniforms:c}),getShaderSource:g=>$a(g,l,e.dims.length,a.length,s,i,o,e.dataType===10?-65504:-1e5,p,d,f,m)}},uh=(t,e)=>{vr(t.inputs),t.compute(Ca("MaxPool",t.inputs[0],!1,e))},dh=t=>{let e=t.storage_order,n=t.dilations,r=Sa(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:sh(s)}},ch=t=>{let e=t.format;return{format:e,...Ta,cacheKey:e}},ph=(t,e)=>{vr(t.inputs),t.compute(Ca("GlobalMaxPool",t.inputs[0],!0,e))}}),hh,fh,mh,gh,E0=W(()=>{ue(),pe(),De(),he(),hh=(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,a)=>a===e.axis||s===t[0].dims[a]).reduce((s,a)=>s&&a,!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)].")}},fh=(t,e)=>{let n=F.normalizeAxis(e.axis,t[0].dims.length),r=t[0].dataType,s=r===3,a=t[0].dims,i=t[1].dataType,o=F.size(a),l=r===3||r===2,u=l?[Math.ceil(F.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(F.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,$=U("input",l?12:r,u.length,y),k=U("scale",i,c.length),E=p?U("zero_point",l?12:r,d.length):void 0,T=ie("output",i,a.length,v),M=[$,k];E&&M.push(E);let R=[u,c];p&&R.push(d);let L=[{type:12,data:o/v},{type:12,data:n},{type:12,data:e.blockSize},...se(...R,a)],G=K=>{let X=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${K.registerUniforms(X).declareVariables(...M,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:a,dataType:i}],dispatchGroup:{x:Math.ceil(o/v/64),y:1,z:1},programUniforms:L})}},mh=(t,e)=>{hh(t.inputs,e),t.compute(fh(t.inputs,e))},gh=t=>xe({axis:t.axis,blockSize:t.blockSize})}),_h,wh,yh,T0=W(()=>{Tt(),ue(),he(),_h=(t,e,n)=>{let r=t===e,s=te&&n>0;if(r||s||a)throw new Error("Range these inputs' contents are invalid.")},wh=(t,e,n,r)=>{let s=Math.abs(Math.ceil((e-t)/n)),a=[s],i=s,o=[{type:12,data:i},{type:r,data:t},{type:r,data:n},...se(a)],l=u=>{let c=ie("output",r,a.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:a,dataType:r}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:o})}},yh=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&&_h(e,n,r),t.compute(wh(e,n,r,t.inputs[0].dataType),{inputs:[]})}}),bh,vh,xh,$h,kh,Sh,Eh,Th,Ch,Mh,Ah,Ma,Ih,zh,Oh,Ph,Bh,Rh,Dh,C0=W(()=>{ue(),pe(),De(),he(),bh=(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")}},vh=(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,a)=>r[s]=t[a]),r},xh=(t,e,n,r,s,a)=>{let[i,o,l]=n>10?[1,2,3]:[-1,t.length>1?1:-1,-1],u=t[0].dims.length;if(i>0&&t.length>i&&t[i].dims.length>0)t[i].getFloat32Array().forEach(c=>a.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");bh(r,e),e.axes.length>0&&vh(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")},$h=(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`)}})()+"}",kh=(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`)}})()+"}",Sh=(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((a,i)=>{r[a]=s[i],r[i+n]=s[e.length+i]}),r):s},Eh=(t,e,n,r)=>{let s=[];if(n.length>0)if(r.length>0){if(t.forEach(a=>s.push(a)),Math.max(...r)>t.length)throw new Error("axes is out of bound");r.forEach((a,i)=>s[a]=n[i])}else n.forEach(a=>s.push(a));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");s=t.map((a,i)=>Math.round(a*e[i]))}return s},Th=(t,e,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map(a=>e[a]),Number.MAX_VALUE):Math.min(...e,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map(a=>e[a]),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(a=>e[a]=r),n.axes.forEach(a=>s[a]=Math.round(t[a]*e[a]))):(e.fill(r,0,e.length),s.forEach((a,i)=>s[i]=Math.round(a*e[i]))),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; }`,Mh=(t,e,n,r,s,a,i)=>` 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",a)}; var roi_hi = ${re("uniforms.roi",`i + ${n.length}`,a)}; 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 (!${i} || (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; }`,Ah=(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; }`,Ma=(t,e,n,r)=>t.rank>r?` ${t.indicesSet("input_indices",e,"channel")}; ${t.indicesSet("input_indices",n,"batch")}; `:"",Ih=(t,e,n,r,s)=>{let[a,i,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",i,`max(0, min(row, ${n[i]} - 1))`)}; ${t.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)}; ${Ma(t,l,a,2)} return ${t.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${e.type.indices}) -> ${u} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${u} = originalIndices[${i}]; var col:${u} = originalIndices[${o}]; ${r?`if (row < 0 || row > (${n[i]} - 1) || col < 0 || col > (${n[o]} - 1)) { return ${s}; }`:""}; row = max(0, min(row, ${n[i]} - 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[${a}])`:"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); }`},zh=(t,e,n,r,s,a,i,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]}, ${a[g]}, ${a[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] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; 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); } `},Oh=(t,e,n,r,s)=>{let[a,i,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",i,`max(0, min(depth, ${n[i]} - 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))`)}; ${Ma(t,u,a,3)} return ${t.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${c} = originalIndices[${i}]; var height:${c} = originalIndices[${o}]; var width:${c} = originalIndices[${l}]; ${r?`if (depth < 0 || depth > (${n[i]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[l]} - 1)) { return ${s}; }`:""}; depth = max(0, min(depth, ${n[i]} - 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[${a}])`:"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); }`},Ph=(t,e,n,r,s,a)=>{let i=t.dims,o=Sh(a,e.axes,i.length),l=Eh(i,r,s,e.axes),u=r.slice();r.length===0&&(u=i.map((y,$)=>y===0?1:l[$]/y),e.keepAspectRatioPolicy!=="stretch"&&(l=Th(i,u,e)));let c=ie("output",t.dataType,l.length),p=U("input",t.dataType,i.length),d=F.size(l),f=i.length===l.length&&i.every((y,$)=>y===l[$]),m=e.coordinateTransformMode==="tf_crop_and_resize",g=e.extrapolationValue,w=p.type.value,v=y=>` ${f?"":` ${$h(e.coordinateTransformMode,w)}; ${(()=>{switch(e.mode){case"nearest":return` ${Ah(p,i)}; ${kh(e.nearestMode,n,w)}; ${Mh(p,c,i,l,u.length,o.length,m)}; `;case"linear":return` ${Ch(c,i,l,u.length,o.length)}; ${(()=>{if(i.length===2||i.length===4)return`${Ih(p,c,i,m,g)}`;if(i.length===3||i.length===5)return`${Oh(p,c,i,m,g)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(i.length===2||i.length===4)return`${zh(p,c,i,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] = ${i.length===2||i.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}|${i}`,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(i,l)]})}},Bh=t=>{let e=t.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},Rh=(t,e)=>{let n=[],r=[],s=[],a=Bh(t);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");xh(t.inputs,e,a,n,r,s),t.compute(Ph(t.inputs[0],e,a,n,r,s),{inputs:[0]})},Dh=t=>{let e=t.antialias,n=t.axes,r=t.coordinateTransformMode,s=t.cubicCoeffA,a=t.excludeOutside!==0,i=t.extrapolationValue,o=t.keepAspectRatioPolicy,l=t.mode,u=t.nearestMode===""?"simple":t.nearestMode;return xe({antialias:e,axes:n,coordinateTransformMode:r,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:o,mode:l,nearestMode:u})}}),Fh,Nh,Lh,M0=W(()=>{ue(),pe(),De(),he(),Fh=(t,e)=>{let[n,r,s,a]=t,{numHeads:i,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(!F.areEqual(r.dims,[])&&!F.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(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!F.areEqual(s.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(o>0&&i===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=F.sizeFromDimension(n.dims,1)/u,d=o===0?s.dims[1]*2:p/i;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")},Nh=(t,e)=>{let{interleaved:n,numHeads:r,rotaryEmbeddingDim:s,scale:a}=e,i=t[0].dims[0],o=F.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(i,l,u/p,p-c),f=F.computeStrides(d),m=[{type:1,data:a},{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=U("input",t[0].dataType,t[0].dims.length),y=U("position_ids",t[1].dataType,t[1].dims.length),$=U("cos_cache",t[2].dataType,t[2].dims.length),k=U("sin_cache",t[3].dataType,t[3].dims.length),E=ie("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(Wn)} 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",ie("",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:xe({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(F.size(d)/Wn)},programUniforms:m})}},Lh=(t,e)=>{Fh(t.inputs,e),t.compute(Nh(t.inputs,e))}}),Uh,Vh,jh,A0=W(()=>{ue(),pe(),he(),Uh=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],a=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]!==a)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 i=t[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(t.length>4){let i=t[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},Vh=(t,e,n,r)=>{let s=e.simplified,a=t[0].dims,i=F.size(a),o=a,l=i,u=a.slice(-1)[0],c=r?a.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"}],M=[U("x",t[0].dataType,t[0].dims,v),U("skip",t[1].dataType,t[1].dims,v),U("gamma",t[2].dataType,t[2].dims,v)];p&&M.push(U("beta",t[3].dataType,t[3].dims,v)),d&&M.push(U("bias",t[4].dataType,t[4].dims,v)),M.push(ie("output",t[0].dataType,o,v)),f&&M.push(ie("mean_output",1,c)),m&&M.push(ie("inv_std_output",1,c)),g&&M.push(ie("input_skip_bias_sum",t[0].dataType,o,v));let R=Le(t[0].dataType),L=Le(1,v);return` ${E.registerUniforms(T).declareVariables(...M)} var sum_shared : array<${L}, ${w}>; var sum_squared_shared : array<${L}, ${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]":R+"(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 = ${Hn(R,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 = ${an("sum",v)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${an("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?"":`- ${R}(mean)`}) * ${R}(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:a,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})}},jh=(t,e)=>{Uh(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(Vh(t.inputs,e,t.outputCount,!1),{outputs:n})}}),qh,xr,Gh,Aa,Wh,Hh,Kh,Xh,I0=W(()=>{ue(),pe(),De(),he(),qh=(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},Gh=(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()]),xe({starts:n,ends:r,axes:s})}else return e},Aa=(t,e,n,r,s)=>{let a=t;return t<0&&(a+=n[r[e]]),s[e]<0?Math.max(0,Math.min(a,n[r[e]]-1)):Math.max(0,Math.min(a,n[r[e]]))},Wh=(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; }`,Hh=(t,e)=>{let n=t[0].dims,r=F.size(n),s=e.axes.length>0?F.normalizeAxes(e.axes,n.length):[...Array(n.length).keys()],a=xr(t,4);a.forEach(v=>v!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(s.length).fill(1));let i=e.starts.map((v,y)=>Aa(v,y,n,s,a)),o=e.ends.map((v,y)=>Aa(v,y,n,s,a));if(s.length!==i.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));a.forEach((v,y,$)=>{if(v<0){let k=(o[y]-i[y])/v,E=i[y],T=E+k*a[y];i[y]=T,o[y]=E,$[y]=-v}});let u=n.slice(0);s.forEach((v,y)=>{u[v]=Math.ceil((o[v]-i[v])/a[v])});let c={dims:u,dataType:t[0].dataType},p=ie("output",t[0].dataType,u.length),d=U("input",t[0].dataType,t[0].dims.length),f=F.size(u),m=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:a.length}],g=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:a},...se(t[0].dims,u)],w=v=>` ${v.registerUniforms(m).declareVariables(d,p)} ${Wh(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}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[c],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:g})}},Kh=(t,e)=>{qh(t.inputs,e);let n=Gh(t.inputs,e);t.compute(Hh(t.inputs,n),{inputs:[0]})},Xh=t=>{let e=t.starts,n=t.ends,r=t.axes;return xe({starts:e,ends:n,axes:r})}}),Qh,Yh,Zh,Jh,z0=W(()=>{ue(),pe(),De(),he(),Qh=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},Yh=(t,e)=>{let n=t.dims,r=F.size(n),s=64,a=e.axis;if(a<0&&(a=n.length+a),av===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=U("x",t.dataType,t.dims,l),d=ie("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}(${an("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}},Zh=(t,e)=>{Qh(t.inputs),t.compute(Yh(t.inputs[0],e))},Jh=t=>xe({axis:t.axis})}),ef,tf,nf,rf,sf,af,of,O0=W(()=>{ue(),pe(),De(),he(),ef=t=>{if(!t||t.length<1)throw new Error("too few inputs")},tf=(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),xe({numOutputs:r,axis:e.axis,splitSizes:n})},nf=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; }`,rf=t=>{let e=t.length,n=[];for(let r=0;r{let n=t[0].dims,r=F.size(n),s=t[0].dataType,a=F.normalizeAxis(e.axis,n.length),i=new Array(e.numOutputs),o=U("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,...i)} ${nf(l.length)} ${rf(i)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${o.offsetToIndices("global_idx")}; var index = ${o.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${re("uniforms.size_in_split_axis","output_number - 1u",l.length)}; ${o.indicesSet("indices",a,"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})}},af=(t,e)=>{ef(t.inputs);let n=t.inputs.length===1?e:tf(t.inputs,e);t.compute(sf(t.inputs,n),{inputs:[0]})},of=t=>{let e=t.axis,n=t.splitSizes,r=t.numOutputs<0?n.length:t.numOutputs;if(r!==n.length)throw new Error("numOutputs and splitSizes lengh must be equal");return xe({axis:e,numOutputs:r,splitSizes:n})}}),lf,uf,df,P0=W(()=>{ue(),pe(),he(),lf=(t,e,n,r,s)=>{let a=ie("output_data",s,n.length,4),i=U("a_data",e[1].dataType,e[1].dims.length,4),o=U("b_data",e[2].dataType,e[2].dims.length,4),l=U("c_data",e[0].dataType,e[0].dims.length,4),u,c=(p,d,f)=>`select(${d}, ${p}, ${f})`;if(!r)u=a.setByOffset("global_idx",c(i.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} = ${a.offsetToIndices(`global_idx * 4u + ${f}u`)}; let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,a)}; let offset_b${f} = ${o.broadcastedIndicesToOffset(`output_indices${f}`,a)}; let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,a)}; 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,i,o,a)} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${u} }`},uf=t=>{let e=t[1].dims,n=t[2].dims,r=t[0].dims,s=t[1].dataType,a=!(F.areEqual(e,n)&&F.areEqual(n,r)),i=e,o=F.size(e);if(a){let u=Gn.calcShape(Gn.calcShape(e,n,!1),r,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,o=F.size(i)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>lf(u,t,i,a,s),getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...se(r,e,n,i)]})}},df=t=>{t.compute(uf(t.inputs))}}),cf,B0=W(()=>{Jy(),Xi(),e0(),t0(),n0(),r0(),s0(),Cc(),d0(),c0(),p0(),h0(),f0(),m0(),g0(),_0(),w0(),y0(),b0(),v0(),x0(),kc(),$0(),Cp(),k0(),S0(),E0(),T0(),Wi(),C0(),M0(),A0(),I0(),z0(),O0(),zp(),Kn(),Ji(),P0(),cf=new Map([["Abs",[rd]],["Acos",[sd]],["Acosh",[id]],["Add",[Wd]],["ArgMax",[Vu,Ki]],["ArgMin",[Uu,Ki]],["Asin",[ad]],["Asinh",[od]],["Atan",[ld]],["Atanh",[ud]],["Attention",[Ku]],["AveragePool",[ah,ih]],["BatchNormalization",[Zu]],["BiasAdd",[td]],["BiasSplitGelu",[jd]],["Cast",[cd,dd]],["Ceil",[fd]],["Clip",[hd]],["Concat",[ac,oc]],["Conv",[da,la]],["ConvTranspose",[Lc,Bc]],["Cos",[md]],["Cosh",[gd]],["CumSum",[Vc,jc]],["DepthToSpace",[Hc,Kc]],["DequantizeLinear",[mh,gh]],["Div",[Hd]],["Einsum",[ep,tp]],["Elu",[_d,_r]],["Equal",[Kd]],["Erf",[wd]],["Exp",[yd]],["Expand",[ip]],["FastGelu",[op]],["Floor",[bd]],["FusedConv",[da,la]],["Gather",[cp,dp]],["GatherElements",[yp,wp]],["GatherBlockQuantized",[fp,mp]],["Gelu",[vd]],["Gemm",[$p,xp]],["GlobalAveragePool",[lh,oh]],["GlobalMaxPool",[ph,ch]],["Greater",[Zd]],["GreaterOrEqual",[ec]],["GroupQueryAttention",[Rp,Pp]],["HardSigmoid",[Md,Cd]],["InstanceNormalization",[Lp]],["LayerNormalization",[jp]],["LeakyRelu",[xd,_r]],["Less",[Jd]],["LessOrEqual",[tc]],["Log",[Dd]],["MatMul",[$c]],["MatMulNBits",[Wp,Hp]],["MaxPool",[uh,dh]],["Mul",[Xd]],["MultiHeadAttention",[Tp,Sp]],["Neg",[kd]],["Not",[$d]],["Pad",[nh]],["Pow",[Qd]],["QuickGelu",[Ld,_r]],["Range",[yh]],["Reciprocal",[Sd]],["ReduceMin",[Ru]],["ReduceMean",[Iu]],["ReduceMax",[Bu]],["ReduceSum",[Fu]],["ReduceProd",[Du]],["ReduceL1",[zu]],["ReduceL2",[Ou]],["ReduceLogSum",[Lu]],["ReduceLogSumExp",[Pu]],["ReduceSumSquare",[Nu]],["Relu",[Ed]],["Resize",[Rh,Dh]],["RotaryEmbedding",[Lh]],["Sigmoid",[Td]],["Sin",[Ad]],["Sinh",[Id]],["Slice",[Kh,Xh]],["SkipLayerNormalization",[jh]],["Split",[af,of]],["Sqrt",[zd]],["Softmax",[Zh,Jh]],["Sub",[Yd]],["Tan",[Od]],["Tanh",[Pd]],["ThresholdedRelu",[Rd,_r]],["Tile",[Ip]],["Transpose",[Zl,Jl]],["Where",[df]]])}),pf,R0=W(()=>{Tt(),sn(),he(),pf=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){Et(t.programInfo.name);let a=this.backend.device,i=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=a.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)}i.setPipeline(t.computePipeline),i.setBindGroup(0,l),i.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){Et(t.name);let n=this.backend.device,r=[];n.features.has("shader-f16")&&r.push("enable f16;");let s=Kl(e,this.backend.device.limits),a=t.getShaderSource(s),i=`${r.join(` `)} ${s.additionalImplementations} ${a}`,o=n.createShaderModule({code:i,label:t.name});Be("verbose",()=>`[WebGPU] ${t.name} shader code: ${i}`);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 a=e*n*r,i=Math.ceil(Math.sqrt(a));if(i>s){if(i=Math.ceil(Math.cbrt(a)),i>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),hf,ff,mf,gf,D0=W(()=>{Tt(),ue(),sn(),Qy(),Yy(),B0(),R0(),hf=(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,a;let r=t.name;return(s=t.shaderCache)!=null&&s.hint&&(r+="["+t.shaderCache.hint+"]"),r+=":"+n+`:${hf(e,((a=t.shaderCache)==null?void 0:a.inputDependencies)??new Array(e.length).fill("dims"))}`,r},mf=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},gf=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 mf(e.info||await e.requestAdapterInfo()),this.gpuDataManager=jl(this),this.programManager=new pf(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;Et(),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:i,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 "${i}|${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,a){Et(t.name);let i=[];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=a)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 M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(T)}d.push(T)}if(i.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(M=>{let R=typeof M.data=="number"?[M.data]:M.data;if(R.length===0)return;let L=M.type===10?2:4,G,K;M.type===10?(K=R.length>4?16:R.length>2?8:R.length*L,G=R.length>4?16:L*R.length):(K=R.length<=2?R.length*L:16,G=16),y=Math.ceil(y/K)*K,$.push(y);let X=M.type===10?8:4;y+=R.length>4?Math.ceil(R.length/X)*G:R.length*L});let k=16;y=Math.ceil(y/k)*k;let E=new ArrayBuffer(y);u.forEach((M,R)=>{let L=$[R],G=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(E,L,G.length).set(G);else if(M.type===12)new Uint32Array(E,L,G.length).set(G);else if(M.type===10)new Uint16Array(E,L,G.length).set(G);else if(M.type===1)new Float32Array(E,L,G.length).set(G);else throw new Error(`Unsupported uniform type: ${$n(M.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=ff(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,i,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=cf.get(t);if(!s)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:r,kernelEntry:s[0],attributes:[s[1],n]};this.kernels.set(e,a)}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,a=r.kernelName,i=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${a}" 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}] ${a}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(e,o[1]),0}catch(u){return n.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${u}`)),1}finally{l&&n.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${s}] ${a}": ${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 a=s.get(e),i=this.gpuDataManager.registerExternalBuffer(n,r,a==null?void 0:a[1]);return s.set(e,[i,n]),i}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 Li(this,t,e);return Nl(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()}}}),_f={};dr(_f,{init:()=>yf});var Ss,wf,yf,F0=W(()=>{ue(),D0(),sn(),pe(),Ss=class ry{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=F.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=F.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=F.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=F.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(F.size(e)!==F.size(this.dims))throw new Error("Invalid new shape");return new ry(this.module,this.dataType,this.data,e)}},wf=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 a=r[s++];this.outputCount=r[s++],this.customDataOffset=r[s++],this.customDataSize=r[s++];let i=[];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),a=(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,a,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 a=0;a{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 a=new gf;await a.initialize(n,r),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,o,l,u=!1)=>{if(u)Be("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${o}, size=${l}`),a.memcpy(i,o);else{Be("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${o}, size=${l}`);let c=e.HEAPU8.subarray(i>>>0,(i>>>0)+l);a.upload(o,c)}},async(i,o,l)=>{Be("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${o}, size=${l}`),await a.download(i,()=>e.HEAPU8.subarray(o>>>0,(o>>>0)+l))},(i,o,l)=>a.createKernel(i,o,l,e.UTF8ToString(e._JsepGetNodeName(o))),i=>a.releaseKernel(i),(i,o,l,u)=>{Be("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${i}, contextDataOffset=${o}`);let c=new wf(e,a,o);return a.computeKernel(i,c,u)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else s("webnn")}}),bf,Ia,za,cn,vf,Es,Oa,Pa,Ba,Ra,Da,Fa,xf=W(()=>{Ky(),Xy(),ue(),qn(),Ii(),zl(),bf=(t,e)=>{je()._OrtInit(t,e)!==0&&Ae("Can't initialize onnxruntime.")},Ia=async t=>{bf(t.wasm.numThreads,us(t.logLevel))},za=async(t,e)=>{{let n=(F0(),rs(_f)).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 a=t.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:a}),!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)}}},cn=new Map,vf=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]},Oa=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 a=0,i=0,o=0,l=[],u=[],c=[];try{if([i,l]=Il(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(Ri(typeof E=="string"?E:E.data).then(M=>{s.mountExternalData(T,M)}))}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,M=E==null?void 0:E.gpuDevice,R=E==null?void 0:E.deviceType,L=E==null?void 0:E.numThreads,G=E==null?void 0:E.powerPreference;T?s.currentContext=T:M?s.currentContext=await navigator.ml.createContext(M):s.currentContext=await navigator.ml.createContext({deviceType:R,numThreads:L,powerPreference:G})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(n,r,i),a===0&&Ae("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[f,m]=vf(a),g=!!(e!=null&&e.enableGraphCapture),w=[],v=[],y=[];for(let k=0;kk==="gpu-buffer")&&(o=s._OrtCreateBinding(a),o===0&&Ae("Can't create IO binding."),$={handle:o,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(k=>Bi(k))}),cn.set(a,[a,u,c,$,g,!1]),[a,w,v]}catch(f){throw u.forEach(m=>s._OrtFree(m)),c.forEach(m=>s._OrtFree(m)),o!==0&&s._OrtReleaseBinding(o),a!==0&&s._OrtReleaseSession(a),f}finally{s._free(n),i!==0&&s._OrtReleaseSessionOptions(i),l.forEach(f=>s._free(f)),(d=s.unmountExternalData)==null||d.call(s)}},Pa=t=>{var l;let e=je(),n=cn.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[r,s,a,i,o]=n;i&&(o&&e._OrtClearBoundOutputs(i.handle),e._OrtReleaseBinding(i.handle)),(l=e.jsepOnReleaseSession)==null||l.call(e,t),s.forEach(u=>e._OrtFree(u)),a.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(r),cn.delete(t)},Ba=(t,e,n,r,s,a=!1)=>{if(!t){e.push(0);return}let i=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(a&&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(zi(o),l);let g=i.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=i._malloc(p),n.push(c);let g=c/4;for(let w=0;wi.HEAP32[m++]=w);let g=i._OrtCreateTensor(zi(o),c,p,f,l.length,Bi(u));g===0&&Ae(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{i.stackRestore(d)}},Ra=async(t,e,n,r,s,a)=>{var G,K;let i=je(),o=cn.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=i.stackSave(),T=i.stackAlloc(m*4),M=i.stackAlloc(m*4),R=i.stackAlloc(g*4),L=i.stackAlloc(g*4);try{[w,v]=El(a);for(let B=0;BFe*Ve,1);ae=$n(Ee);let Bt=p==null?void 0:p.outputPreferredLocations[r[B]];if(ae==="string"){if(Bt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Fe=[],Ve=ge/4;for(let at=0;at0){let Fe=i.jsepGetBuffer;if(!Fe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ve=Fe(ge),at=ls(Ee,Oe);if(at===void 0||!Pi(ae))throw new Error(`Unsupported data type: ${ae}`);q=!0,N.push([ae,Ne,{gpuBuffer:Ve,download:i.jsepCreateDownloader(Ve,at,ae),dispose:()=>{i._OrtReleaseTensor(Y)}},"gpu-buffer"])}else{let Fe=Oi(ae),Ve=new Fe(Oe);new Uint8Array(Ve.buffer,Ve.byteOffset,Ve.byteLength).set(i.HEAPU8.subarray(ge,ge+Ve.byteLength)),N.push([ae,Ne,Ve,"cpu"])}}finally{i.stackRestore(te),ae==="string"&&ge&&i._free(ge),q||i._OrtReleaseTensor(Y)}}return p&&!d&&(i._OrtClearBoundOutputs(p.handle),cn.set(t,[l,u,c,p,d,!1])),N}finally{i.stackRestore(E),y.forEach(X=>i._OrtReleaseTensor(X)),$.forEach(X=>i._OrtReleaseTensor(X)),k.forEach(X=>i._free(X)),w!==0&&i._OrtReleaseRunOptions(w),v.forEach(X=>i._free(X))}},Da=t=>{let e=je(),n=cn.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)},Fa=t=>{let e=[];for(let n of t){let r=n[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),pn,ot,Xn,$r,kr,Ts,Na,Cs,Sn,En,$f,kf,Sf,Ef,Tf,Cf,Mf,Af,If=W(()=>{Tt(),xf(),qn(),is(),pn=()=>!!Te.wasm.proxy&&typeof document<"u",Xn=!1,$r=!1,kr=!1,Cs=new Map,Sn=(t,e)=>{let n=Cs.get(t);n?n.push(e):Cs.set(t,[e])},En=()=>{if(Xn||!$r||kr||!ot)throw new Error("worker not ready")},$f=t=>{switch(t.data.type){case"init-wasm":Xn=!1,t.data.err?(kr=!0,Na[1](t.data.err)):($r=!0,Na[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=Cs.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},kf=async()=>{if(!$r){if(Xn)throw new Error("multiple calls to 'initWasm()' detected.");if(kr)throw new Error("previous call to 'initWasm()' failed.");if(Xn=!0,pn())return new Promise((t,e)=>{ot==null||ot.terminate(),vl().then(([n,r])=>{try{ot=r,ot.onerror=a=>e(a),ot.onmessage=$f,Na=[t,e];let s={type:"init-wasm",in:Te};ot.postMessage(s),Ts=n}catch(s){e(s)}},e)});try{await Ai(Te.wasm),await Ia(Te),$r=!0}catch(t){throw kr=!0,t}finally{Xn=!1}}},Sf=async t=>{if(pn())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 za(Te,t)},Ef=async t=>pn()?(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),Tf=async(t,e)=>{if(pn()){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}}},a=[];t instanceof Uint8Array&&a.push(t.buffer),ot.postMessage(s,a)})}else return Oa(t,e)},Cf=async t=>{if(pn())return En(),new Promise((e,n)=>{Sn("release",[e,n]);let r={type:"release",in:t};ot.postMessage(r)});Pa(t)},Mf=async(t,e,n,r,s,a)=>{if(pn()){if(n.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return En(),new Promise((i,o)=>{Sn("run",[i,o]);let l=n,u={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:r,options:a}};ot.postMessage(u,Fa(l))})}else return Ra(t,e,n,r,s,a)},Af=async t=>{if(pn())return En(),new Promise((e,n)=>{Sn("end-profiling",[e,n]);let r={type:"end-profiling",in:t};ot.postMessage(r)});Da(t)}}),La,zf,Of,N0=W(()=>{Tt(),If(),ue(),xi(),zl(),La=(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()}`)}},zf=t=>{switch(t[3]){case"cpu":return new nt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Pi(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]}`)}},Of=class{async fetchModelAndCopyToWasmMemory(t){return Ef(await Ri(t))}async loadModel(t,e){Et();let n;typeof t=="string"?n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await Tf(n,e),_t()}async dispose(){return Cf(this.sessionId)}async run(t,e,n){Et();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 a=[],i=[];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}'`);a.push(f),i.push(m)});let o=r.map((p,d)=>La(p,()=>`input "${this.inputNames[s[d]]}"`)),l=a.map((p,d)=>p?La(p,()=>`output "${this.outputNames[i[d]]}"`):null),u=await Mf(this.sessionId,s,o,i,l,n),c={};for(let p=0;p{Tt(),If(),N0(),is(),Pf=()=>{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"?My("node:os").cpus().length:navigator.hardwareConcurrency;Te.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Bf=class{async init(t){Pf(),await kf(),await Sf(t)}async createInferenceSessionHandler(t,e){let n=new Of;return await n.loadModel(t,e),Promise.resolve(n)}}}),Rf={};dr(Rf,{wasmBackend:()=>Df});var Df,U0=W(()=>{L0(),Df=new Bf});Tt(),Tt(),Tt();var V0="1.20.0-dev.20240827-1d059b8702",j0=hl;{let t=(U0(),rs(Rf)).wasmBackend;vn("webgpu",t,5),vn("webnn",t,5),vn("cpu",t,10),vn("wasm",t,10)}Object.defineProperty(Te.versions,"web",{value:V0,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 q0=Object.freeze({__proto__:null,get InferenceSession(){return bi},get TRACE(){return hr},get TRACE_FUNC_BEGIN(){return Et},get TRACE_FUNC_END(){return _t},get Tensor(){return nt},get TrainingSession(){return vi},default:j0,get env(){return Te},get registerBackend(){return vn}});const G0=(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,a;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],a=t.dims[3]):(s=t.dims[3],a=t.dims[2]);const i=(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=a*s;let p=0,d=c,f=c*2,m=-1;i==="RGBA"?(p=0,d=c,f=c*2,m=c*3):i==="RGB"?(p=0,d=c,f=c*2):i==="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,a,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],a=t.dims[1],i=t.dims[3]):(s=t.dims[3],a=t.dims[2],i=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=a*s;if(e!==void 0&&(e.format!==void 0&&i===4&&e.format!=="RGBA"||i===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,a);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 a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[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,a=typeof t=="string";let i,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),i=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),i=f.getImageData(0,0,p,c).data;else throw new Error("Can not access image data")}else i=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),i=p.getImageData(0,0,f,d).data,o.height=d,o.width=f,Ua(i,o)}else throw new Error("Can not access image data")}else{if(a)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(Ua(g.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ua(i,o);throw new Error("Input data provided is not supported - aborted tensor creation")},K0=(t,e)=>{const{width:n,height:r,download:s,dispose:a}=e,i=[1,r,n,4];return new Ft({location:"texture",type:"float32",texture:t,dims:i,download:s,dispose:a})},X0=(t,e)=>{const{dataType:n,dims:r,download:s,dispose:a}=e;return new Ft({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:s,dispose:a})},Q0=(t,e,n)=>new Ft({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]}),Qn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Ms=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Ff=!1;const Y0=()=>{if(!Ff){Ff=!0;const t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,n=typeof Float16Array<"u"&&Float16Array.from;t&&(Qn.set("int64",BigInt64Array),Ms.set(BigInt64Array,"int64")),e&&(Qn.set("uint64",BigUint64Array),Ms.set(BigUint64Array,"uint64")),n?(Qn.set("float16",Float16Array),Ms.set(Float16Array,"float16")):Qn.set("float16",Uint16Array)}},Z0=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){Y0();let s,a;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,a=e.dims,e.location){case"cpu-pinned":{const o=Qn.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=Qn.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=Ms.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");a=l,this.cpuData=o,this.dataLocation="cpu"}const i=Z0(a);if(this.cpuData&&i!==this.cpuData.length)throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=a,this.size=i}static async fromImage(e,n){return H0(e,n)}static fromTexture(e,n){return K0(e,n)}static fromGpuBuffer(e,n){return X0(e,n)}static fromPinnedBuffer(e,n,r){return Q0(e,n,r)}toDataURL(e){return G0(this,e)}toImageData(e){return W0(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 J0(this,e)}};const eb=Ft,tb=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"}}),Nt=[];let Va,Tn;if(bn.IS_NODE_ENV){switch(Tn=ke??Wt,process.platform){case"win32":Nt.push("dml");break;case"linux":process.arch==="x64"&&Nt.push("cuda");break}Nt.push("cpu"),Va=["cpu"]}else Tn=q0,bn.IS_WEBNN_AVAILABLE&&Nt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),bn.IS_WEBGPU_AVAILABLE&&Nt.push("webgpu"),Nt.push("wasm"),Va=["wasm"];const nb=Tn.InferenceSession;function rb(t=null){if(!t)return Va;switch(t){case"auto":return Nt;case"gpu":return Nt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Nt.includes(t))return[tb[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Nt.join(", ")}.`)}let ja=null;async function Nf(t,e){ja&&await ja;const n=nb.create(t,e);return ja??(ja=n),await n}function Lf(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 Uf(){var t;return(t=lt==null?void 0:lt.wasm)==null?void 0:t.proxy}tt.backends.onnx=lt;const Yn=async(t,e,n)=>{const r=await Nf(new Uint8Array(t),e);return async s=>{const a=Object.fromEntries(Object.entries(s).map(([o,l])=>[o,l.ort_tensor])),i=await r.run(a);return Array.isArray(n)?n.map(o=>new J(i[o])):new J(i[n])}};class Sr{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Yn([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=Yn([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=Yn([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=Yn([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=Yn([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=Yn([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 Vf=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 J{constructor(...e){A(this,"ort_tensor");return Lf(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new eb(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,a)=>s*a);for(let s=0;s0){const s=r.reduce((a,i)=>a*i);return this._subarray(e,s,r)}else return new J(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),a=s.reduce((u,c)=>u*c),i=this.data,o=new i.constructor(a),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]=i[c]}return new J(this.type,o,n)}permute(...e){return ib(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 J(this.type,[o],[])}n=Lt(n,this.dims.length);const a=this.dims.slice();a[n]=1;const i=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*=a[u]}c=Math.floor(c/d)}i[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[i]/=a[o]}return this}normalize(e=2,n=1){return this.clone().normalize_(e,n)}stride(){return ub(this.dims)}squeeze(e=null){return new J(this.type,this.data,qf(this.dims,e))}squeeze_(e=null){return this.dims=qf(this.dims,e),this}unsqueeze(e=null){return new J(this.type,this.data,Gf(this.dims,e))}unsqueeze_(e=null){return this.dims=Gf(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),a=this.dims.slice(n+1);return this.dims=[...r,s.reduce((i,o)=>i*o,1),...a],this}flatten(e=0,n=-1){return this.clone().flatten_(e,n)}view(...e){let n=-1;for(let s=0;so!==n?a*i:a,1);e[n]=r.length/s}return new J(this.type,r,e)}neg_(){const e=this.data;for(let n=0;na*i);if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${e})`);let s=t;for(let a=e.length-1;a>=0;a--)s=s.reduce((i,o)=>{let l=i[i.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 Gf(t,e){return e=Lt(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function Lt(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=Lt(e,t[0].dims.length);const n=t[0].dims.slice();n[e]=t.reduce((i,o)=>i+o.dims[e],0);const r=n.reduce((i,o)=>i*o,1),s=new t[0].data.constructor(r),a=t[0].type;if(e===0){let i=0;for(const o of t){const l=o.data;s.set(l,i),i+=l.length}}else{let i=0;for(let o=0;o=0;--d){const g=u[d];let w=f%g;d===e&&(w+=i),p+=w*m,m*=n[d],f=Math.floor(f/g)}s[p]=l[c]}i+=u[e]}}return new J(a,s,n)}function Er(t,e=0){return ct(t.map(n=>n.unsqueeze(e)),e)}function lb(t,e=null,n=1,r=!1){const s=t.data,a=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 J(t.type,[d],[]);return[new J(t.type,[f],[]),m]}e=Lt(e,a.length);const i=Ga(t,e,r),o=i.data,l=a.slice();l[e]=1;const u=new s.constructor(s.length/a[e]);for(let p=0;p=0;--f){const w=a[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 J(t.type,[o/r.length],[])}const s=t.dims;e=Lt(e,s.length);const a=s.slice();a[e]=1;const i=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*=a[u]}c=Math.floor(c/d)}i[l]+=r[o]}if(s[e]!==1)for(let o=0;o=0;--n)e[n]=r,r*=t[n];return e}function Wa(t,e,n,r){const s=t.reduce((a,i)=>a*i,1);return new J(n,new r(s).fill(e),t)}function db(t,e){let n,r;return n="float32",r=Float32Array,Wa(t,e,n,r)}function cb(t,e){return db(t.dims,e)}function Jn(t){return Wa(t,1n,"int64",BigInt64Array)}function pb(t){return Jn(t.dims)}function hb(t){return Wa(t,0n,"int64",BigInt64Array)}function fb(t){return hb(t.dims)}function mb(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,a=t.data,i=new s(a.length/8);for(let o=0;o0?1:0,u=Math.floor(o/8),c=o%8;i[u]|=l<<7-c,n&&c===0&&(i[u]-=128)}return new J(r,i,[t.dims[0],t.dims[1]/8])}class gb{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),a=new Tr(this.eosTokenId,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(a.clone()),this.beginNodes[this.len].push(a),this.endNodes[0].push(s)}insert(e,n,r,s){const a=this.nodes.length,i=new Tr(s,a,e,n,r);this.beginNodes[e].push(i),this.endNodes[e+n].push(i),this.nodes.push(i)}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=[],a=this.beginNodes[e][0].prev;if(a===null)return[];let i=a.clone();for(;i.prev!==null;)r.push(i.clone()),i=i.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,a){this.tokenId=e,this.nodeId=n,this.pos=r,this.length=s,this.score=a,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 I=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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"}),Wf=Object.freeze({set:I.Set,for:I.For,in:I.In,is:I.Is,if:I.If,else:I.Else,endif:I.EndIf,elif:I.ElseIf,endfor:I.EndFor,and:I.And,or:I.Or,not:I.Not,"not in":I.NotIn,macro:I.Macro,endmacro:I.EndMacro,true:I.BooleanLiteral,false:I.BooleanLiteral,none:I.NullLiteral,True:I.BooleanLiteral,False:I.BooleanLiteral,None:I.NullLiteral}),Cn=class{constructor(t,e){this.value=t,this.type=e}};function Hf(t){return/\w/.test(t)}function Ha(t){return/[0-9]/.test(t)}var yb=[["{%",I.OpenStatement],["%}",I.CloseStatement],["{{",I.OpenExpression],["}}",I.CloseExpression],["(",I.OpenParen],[")",I.CloseParen],["{",I.OpenCurlyBracket],["}",I.CloseCurlyBracket],["[",I.OpenSquareBracket],["]",I.CloseSquareBracket],[",",I.Comma],[".",I.Dot],[":",I.Colon],["|",I.Pipe],["<=",I.ComparisonBinaryOperator],[">=",I.ComparisonBinaryOperator],["==",I.ComparisonBinaryOperator],["!=",I.ComparisonBinaryOperator],["<",I.ComparisonBinaryOperator],[">",I.ComparisonBinaryOperator],["+",I.AdditiveBinaryOperator],["-",I.AdditiveBinaryOperator],["*",I.MultiplicativeBinaryOperator],["/",I.MultiplicativeBinaryOperator],["%",I.MultiplicativeBinaryOperator],["=",I.Equals]],bb=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function vb(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 xb(t,e={}){var i,o,l;const n=[],r=vb(t,e);let s=0;const a=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=bb.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 Cn(p,I.Text));continue}}a(p=>/\s/.test(p));const c=r[s];if(c==="-"||c==="+"){const p=(o=n.at(-1))==null?void 0:o.type;if(p===I.Text||p===void 0)throw new SyntaxError(`Unexpected character: ${c}`);switch(p){case I.Identifier:case I.NumericLiteral:case I.BooleanLiteral:case I.NullLiteral:case I.StringLiteral:case I.CloseParen:case I.CloseSquareBracket:break;default:{++s;const d=a(Ha);n.push(new Cn(`${c}${d}`,d.length>0?I.NumericLiteral:I.UnaryOperator));continue}}}for(const[p,d]of yb)if(r.slice(s,s+p.length)===p){n.push(new Cn(p,d)),s+=p.length;continue e}if(c==="'"||c==='"'){++s;const p=a(d=>d!==c);n.push(new Cn(p,I.StringLiteral)),++s;continue}if(Ha(c)){const p=a(Ha);n.push(new Cn(p,I.NumericLiteral));continue}if(Hf(c)){const p=a(Hf),d=Object.hasOwn(Wf,p)?Wf[p]:I.Identifier;d===I.In&&((l=n.at(-1))==null?void 0:l.type)===I.Not?(n.pop(),n.push(new Cn("not in",I.NotIn))):n.push(new Cn(p,d));continue}throw new SyntaxError(`Unexpected character: ${c}`)}return n}var er=class{constructor(){A(this,"type","Statement")}},$b=class extends er{constructor(e){super();A(this,"type","Program");this.body=e}},Kf=class extends er{constructor(e,n,r){super();A(this,"type","If");this.test=e,this.body=n,this.alternate=r}},kb=class extends er{constructor(e,n,r,s){super();A(this,"type","For");this.loopvar=e,this.iterable=n,this.body=r,this.defaultBlock=s}},Sb=class extends er{constructor(e,n){super();A(this,"type","Set");this.assignee=e,this.value=n}},Eb=class extends er{constructor(e,n,r){super();A(this,"type","Macro");this.name=e,this.args=n,this.body=r}},Ot=class extends er{constructor(){super(...arguments);A(this,"type","Expression")}},Tb=class extends Ot{constructor(e,n,r){super();A(this,"type","MemberExpression");this.object=e,this.property=n,this.computed=r}},Cb=class extends Ot{constructor(e,n){super();A(this,"type","CallExpression");this.callee=e,this.args=n}},Mn=class extends Ot{constructor(e){super();A(this,"type","Identifier");this.value=e}},An=class extends Ot{constructor(e){super();A(this,"type","Literal");this.value=e}},Mb=class extends An{constructor(){super(...arguments);A(this,"type","NumericLiteral")}},Xf=class extends An{constructor(){super(...arguments);A(this,"type","StringLiteral")}},Qf=class extends An{constructor(){super(...arguments);A(this,"type","BooleanLiteral")}},Yf=class extends An{constructor(){super(...arguments);A(this,"type","NullLiteral")}},Ab=class extends An{constructor(){super(...arguments);A(this,"type","ArrayLiteral")}},Zf=class extends An{constructor(){super(...arguments);A(this,"type","TupleLiteral")}},Ib=class extends An{constructor(){super(...arguments);A(this,"type","ObjectLiteral")}},Cr=class extends Ot{constructor(e,n,r){super();A(this,"type","BinaryExpression");this.operator=e,this.left=n,this.right=r}},zb=class extends Ot{constructor(e,n){super();A(this,"type","FilterExpression");this.operand=e,this.filter=n}},Ob=class extends Ot{constructor(e,n){super();A(this,"type","SelectExpression");this.iterable=e,this.test=n}},Pb=class extends Ot{constructor(e,n,r){super();A(this,"type","TestExpression");this.operand=e,this.negate=n,this.test=r}},Bb=class extends Ot{constructor(e,n){super();A(this,"type","UnaryExpression");this.operator=e,this.argument=n}},Rb=class extends Ot{constructor(e=void 0,n=void 0,r=void 0){super();A(this,"type","SliceExpression");this.start=e,this.stop=n,this.step=r}},Db=class extends Ot{constructor(e,n){super();A(this,"type","KeywordArgumentExpression");this.key=e,this.value=n}};function Fb(t){const e=new $b([]);let n=0;function r(z,N){const B=t[n++];if(!B||B.type!==z)throw new Error(`Parser Error: ${N}. ${B.type} !== ${z}.`);return B}function s(){switch(t[n].type){case I.Text:return o();case I.OpenStatement:return l();case I.OpenExpression:return u();default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}}function a(...z){return n+z.length<=t.length&&z.some((N,B)=>N!==t[n+B].type)}function i(...z){return n+z.length<=t.length&&z.every((N,B)=>N===t[n+B].type)}function o(){return new Xf(r(I.Text,"Expected text token").value)}function l(){r(I.OpenStatement,"Expected opening statement token");let z;switch(t[n].type){case I.Set:++n,z=c(),r(I.CloseStatement,"Expected closing statement token");break;case I.If:++n,z=p(),r(I.OpenStatement,"Expected {% token"),r(I.EndIf,"Expected endif token"),r(I.CloseStatement,"Expected %} token");break;case I.Macro:++n,z=d(),r(I.OpenStatement,"Expected {% token"),r(I.EndMacro,"Expected endmacro token"),r(I.CloseStatement,"Expected %} token");break;case I.For:++n,z=m(),r(I.OpenStatement,"Expected {% token"),r(I.EndFor,"Expected endfor token"),r(I.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type}`)}return z}function u(){r(I.OpenExpression,"Expected opening expression token");const z=g();return r(I.CloseExpression,"Expected closing expression token"),z}function c(){const z=g();if(i(I.Equals)){++n;const N=c();return new Sb(z,N)}return z}function p(){var Y,te,O,q,ae,ge,ve,Ee;const z=g();r(I.CloseStatement,"Expected closing statement token");const N=[],B=[];for(;!(((Y=t[n])==null?void 0:Y.type)===I.OpenStatement&&(((te=t[n+1])==null?void 0:te.type)===I.ElseIf||((O=t[n+1])==null?void 0:O.type)===I.Else||((q=t[n+1])==null?void 0:q.type)===I.EndIf));)N.push(s());if(((ae=t[n])==null?void 0:ae.type)===I.OpenStatement&&((ge=t[n+1])==null?void 0:ge.type)!==I.EndIf)if(++n,i(I.ElseIf))r(I.ElseIf,"Expected elseif token"),B.push(p());else for(r(I.Else,"Expected else token"),r(I.CloseStatement,"Expected closing statement token");!(((ve=t[n])==null?void 0:ve.type)===I.OpenStatement&&((Ee=t[n+1])==null?void 0:Ee.type)===I.EndIf);)B.push(s());return new Kf(z,N,B)}function d(){const z=ne();if(z.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const N=R();r(I.CloseStatement,"Expected closing statement token");const B=[];for(;a(I.OpenStatement,I.EndMacro);)B.push(s());return new Eb(z,N,B)}function f(z=!1){const N=z?ne:g,B=[N()],Y=i(I.Comma);for(;Y&&(++n,B.push(N()),!!i(I.Comma)););return Y?new Zf(B):B[0]}function m(){const z=f(!0);if(!(z instanceof Mn||z instanceof Zf))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${z.type} instead`);r(I.In,"Expected `in` keyword following loop variable");const N=g();r(I.CloseStatement,"Expected closing statement token");const B=[];for(;a(I.OpenStatement,I.EndFor)&&a(I.OpenStatement,I.Else);)B.push(s());const Y=[];if(i(I.OpenStatement,I.Else))for(++n,++n,r(I.CloseStatement,"Expected closing statement token");a(I.OpenStatement,I.EndFor);)Y.push(s());return new kb(z,N,B,Y)}function g(){return w()}function w(){const z=v();if(i(I.If)){++n;const N=v();if(i(I.Else)){++n;const B=v();return new Kf(N,[z],[B])}else return new Ob(z,N)}return z}function v(){let z=y();for(;i(I.Or);){const N=t[n];++n;const B=y();z=new Cr(N,z,B)}return z}function y(){let z=$();for(;i(I.And);){const N=t[n];++n;const B=$();z=new Cr(N,z,B)}return z}function $(){let z;for(;i(I.Not);){const N=t[n];++n;const B=$();z=new Bb(N,B)}return z??k()}function k(){let z=E();for(;i(I.ComparisonBinaryOperator)||i(I.In)||i(I.NotIn);){const N=t[n];++n;const B=E();z=new Cr(N,z,B)}return z}function E(){let z=X();for(;i(I.AdditiveBinaryOperator);){const N=t[n];++n;const B=X();z=new Cr(N,z,B)}return z}function T(){const z=K();return i(I.OpenParen)?M(z):z}function M(z){let N=new Cb(z,R());return i(I.OpenParen)&&(N=M(N)),N}function R(){r(I.OpenParen,"Expected opening parenthesis for arguments list");const z=L();return r(I.CloseParen,"Expected closing parenthesis for arguments list"),z}function L(){const z=[];for(;!i(I.CloseParen);){let N=g();if(i(I.Equals)){if(++n,!(N instanceof Mn))throw new SyntaxError("Expected identifier for keyword argument");const B=g();N=new Db(N,B)}z.push(N),i(I.Comma)&&++n}return z}function G(){const z=[];let N=!1;for(;!i(I.CloseSquareBracket);)i(I.Colon)?(z.push(void 0),++n,N=!0):(z.push(g()),i(I.Colon)&&(++n,N=!0));if(z.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(z.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Rb(...z)}return z[0]}function K(){let z=ne();for(;i(I.Dot)||i(I.OpenSquareBracket);){const N=t[n];++n;let B;const Y=N.type!==I.Dot;if(Y)B=G(),r(I.CloseSquareBracket,"Expected closing square bracket");else if(B=ne(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");z=new Tb(z,B,Y)}return z}function X(){let z=H();for(;i(I.MultiplicativeBinaryOperator);){const N=t[n];++n;const B=H();z=new Cr(N,z,B)}return z}function H(){let z=ee();for(;i(I.Is);){++n;const N=i(I.Not);N&&++n;let B=ne();if(B instanceof Qf?B=new Mn(B.value.toString()):B instanceof Yf&&(B=new Mn("none")),!(B instanceof Mn))throw new SyntaxError("Expected identifier for the test");z=new Pb(z,N,B)}return z}function ee(){let z=T();for(;i(I.Pipe);){++n;let N=ne();if(!(N instanceof Mn))throw new SyntaxError("Expected identifier for the filter");i(I.OpenParen)&&(N=M(N)),z=new zb(z,N)}return z}function ne(){const z=t[n];switch(z.type){case I.NumericLiteral:return++n,new Mb(Number(z.value));case I.StringLiteral:return++n,new Xf(z.value);case I.BooleanLiteral:return++n,new Qf(z.value.toLowerCase()==="true");case I.NullLiteral:return++n,new Yf(null);case I.Identifier:return++n,new Mn(z.value);case I.OpenParen:{++n;const N=f();if(t[n].type!==I.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,N}case I.OpenSquareBracket:{++n;const N=[];for(;!i(I.CloseSquareBracket);)N.push(g()),i(I.Comma)&&++n;return++n,new Ab(N)}case I.OpenCurlyBracket:{++n;const N=new Map;for(;!i(I.CloseCurlyBracket);){const B=g();r(I.Colon,"Expected colon between key and value in object literal");const Y=g();N.set(B,Y),i(I.Comma)&&++n}return++n,new Ib(N)}default:throw new SyntaxError(`Unexpected token: ${z.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 a=[];for(let i=e;s*ie.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")}},fe=class extends Xt{constructor(){super(...arguments);A(this,"type","StringValue");A(this,"builtins",new Map([["upper",new yt(()=>new fe(this.value.toUpperCase()))],["lower",new yt(()=>new fe(this.value.toLowerCase()))],["strip",new yt(()=>new fe(this.value.trim()))],["title",new yt(()=>new fe(em(this.value)))],["length",new Se(this.value.length)],["rstrip",new yt(()=>new fe(this.value.trimEnd()))],["lstrip",new yt(()=>new fe(this.value.trimStart()))]]))}},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 yt(([e,n])=>{if(!(e instanceof fe))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??n??new Qt})],["items",new yt(()=>new ze(Array.from(this.value.entries()).map(([e,n])=>new ze([new fe(e),n]))))]]))}__bool__(){return new Ie(this.value.size>0)}},Lb=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)}},Ub=class extends ze{constructor(){super(...arguments);A(this,"type","TupleValue")}},yt=class extends Xt{constructor(){super(...arguments);A(this,"type","FunctionValue")}},Qt=class extends Xt{constructor(){super(...arguments);A(this,"type","NullValue")}},pt=class extends Xt{constructor(){super(...arguments);A(this,"type","UndefinedValue")}},Mr=class{constructor(t){A(this,"variables",new Map([["namespace",new yt(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 yt],["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],["none",t=>t.type==="NullValue"],["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 fe],["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}}},Vb=class{constructor(t){A(this,"global");this.global=t??new Mr}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 Qt||r instanceof Qt)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(a=>a.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 fe||r instanceof fe)switch(t.operator.value){case"+":return new fe(n.value.toString()+r.value.toString())}if(n instanceof fe&&r instanceof fe)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 fe&&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 a=s;r.set(a.key.value,this.evaluate(a.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 fe(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,a)=>{if(s.type!==a.type)throw new Error(`Cannot compare different types: ${s.type} and ${a.type}`);switch(s.type){case"NumericValue":return s.value-a.value;case"StringValue":return s.value.localeCompare(a.value);default:throw new Error(`Cannot compare type: ${s.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof fe)switch(r.value){case"length":return new Se(n.value.length);case"upper":return new fe(n.value.toUpperCase());case"lower":return new fe(n.value.toLowerCase());case"title":return new fe(em(n.value));case"capitalize":return new fe(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new fe(n.value.trim());case"indent":return new fe(n.value.split(` `).map((s,a)=>a===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,a])=>new ze([new fe(s),a])));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[,a]=this.evaluateArguments(r.args,e),i=a.get("indent")??new Qt;if(!(i instanceof Se||i instanceof Qt))throw new Error("If set, indent must be a number");return new fe(zs(n,i.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[a,i,o]=r.args.map(c=>this.evaluate(c,e));let l;if(i){const c=e.tests.get(i.value);if(!c)throw new Error(`Unknown test: ${i.value}`);l=c}else l=(...c)=>c[0].__bool__().value;const u=n.value.filter(c=>{const p=c.value.get(a.value);return p?l(p,o):!1});return new ze(u)}case"map":{const[,a]=this.evaluateArguments(r.args,e);if(a.has("attribute")){const i=a.get("attribute");if(!(i instanceof fe))throw new Error("attribute must be a string");const o=a.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(i.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 fe){switch(s){case"indent":{const[a,i]=this.evaluateArguments(r.args,e),o=a.at(0)??i.get("width")??new Se(4);if(!(o instanceof Se))throw new Error("width must be a number");const l=a.at(1)??i.get("first")??new Ie(!1),u=a.at(2)??i.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 fe(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 fe(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 Lb(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 fe))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),a=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(!(a instanceof Se||a instanceof pt))throw new Error("Slice step must be numeric or undefined");return t instanceof ze?new ze(Jf(t.value,r.value,s.value,a.value)):new fe(Jf(Array.from(t.value),r.value,s.value,a.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 fe(t.property.value);let s;if(n instanceof wt){if(!(r instanceof fe))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 fe)if(r instanceof Se)s=n.value.at(r.value),n instanceof fe&&(s=new fe(n.value.at(r.value)));else if(r instanceof fe)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 fe))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 Qt}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 Mr(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 a=[],i=[];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?a[u-1]:new pt],["nextitem",u{var i;const s=new Mr(r);n=n.slice();let a;((i=n.at(-1))==null?void 0:i.type)==="KeywordArgumentsValue"&&(a=n.pop());for(let o=0;othis.evaluate(n,e)));case"TupleLiteral":return new Ub(t.value.map(n=>this.evaluate(n,e)));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const a=this.evaluate(r,e);if(!(a instanceof fe))throw new Error(`Object keys must be strings: got ${a.type}`);n.set(a.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 fe(t);case"boolean":return new Ie(t);case"undefined":return new pt;case"object":return t===null?new Qt: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 yt((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):"",a=` `+s.repeat(r),i=a+s;if(t.type==="ArrayValue"){const o=t.value.map(l=>zs(l,e,r+1));return e?`[${i}${o.join(`,${i}`)}${a}]`:`[${o.join(", ")}]`}else{const o=Array.from(t.value.entries()).map(([l,u])=>{const c=`"${l}": ${zs(u,e,r+1)}`;return e?`${i}${c}`:c});return e?`{${o.join(",")}${a}}`:`{${o.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var jb=class{constructor(t){A(this,"parsed");const e=xb(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Fb(e)}render(t){const e=new Mr;e.set("false",!1),e.set("true",!0),e.set("raise_exception",s=>{throw new Error(s)}),e.set("range",Nb);for(const[s,a]of Object.entries(t))e.set(s,a);return new Vb(e).run(this.parsed).value}};const tm=[["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(tm),qb=new Map([...tm.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 nm(t){t=t.toLowerCase();let e=qb.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 Ka="https://github.com/xenova/transformers.js/issues/new/choose";async function rm(t,e){const n=await Promise.all([nn(t,"tokenizer.json",!0,e),nn(t,"tokenizer_config.json",!0,e)]);return e.legacy!==null&&(n[1].legacy=e.legacy),n}function Gb(t,e){const n=[];let r=0;for(const s of t.matchAll(e)){const a=s[0];r0&&n.push(a),r=s.index+a.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 Kb(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 Jb extends Ar{constructor(e){super(e),this.tokens_to_ids=Xa(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 a=!1,i=0;const o=[];for(;i0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){u=c;break}--l}if(u===null){a=!0;break}o.push(u),i=l}a?n.push(this.unk_token):n.push(...o)}return n}}class e1 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,a])),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=Ko(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new _b,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,a)=>a+33),...Array.from({length:12},(s,a)=>a+161),...Array.from({length:82},(s,a)=>a+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,a)=>[s,r[a]]))})(),t1=dy(am);class n1 extends Ar{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=Xa(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 a=new gb((l,u)=>l.score`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`)):n.push(this.unk_token)}return n}}class r1 extends Ar{constructor(e,n){super(e),this.tokens_to_ids=Xa(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 h1(e);case"Precompiled":return new z1(e);case"Sequence":return new p1(e);case"Replace":return new s1(e);case"NFC":return new i1(e);case"NFKC":return new a1(e);case"NFKD":return new o1(e);case"Strip":return new l1(e);case"StripAccents":return new u1(e);case"Lowercase":return new d1(e);case"Prepend":return new c1(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 s1 extends ht{normalize(e){const n=Ps(this.config.pattern);return n===null?e:e.replaceAll(n,this.config.content)}}class i1 extends ht{normalize(e){return e=e.normalize("NFC"),e}}class a1 extends ht{normalize(e){return e=e.normalize("NFKC"),e}}class o1 extends ht{normalize(e){return e=e.normalize("NFKD"),e}}class l1 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 u1 extends ht{normalize(e){return e=im(e),e}}class d1 extends ht{normalize(e){return e=e.toLowerCase(),e}}class c1 extends ht{normalize(e){return e=this.config.prepend+e,e}}class p1 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 h1 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 f1 extends bt{constructor(e){super(),this.pattern=new RegExp(`[^\\s${tr}]+|[${tr}]`,"gu")}pre_tokenize_text(e,n){return e.trim().match(this.pattern)||[]}}class m1 extends bt{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=am,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),a=>this.byte_encoder[a]).join(""))}}class g1 extends bt{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)||[]:Gb(e,this.pattern)}}class _1 extends bt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${tr}]+|[${tr}]+`,"gu")}pre_tokenize_text(e,n){return e.match(this.pattern)||[]}}class w1 extends bt{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 y1(e);case"ByteLevel":return new um(e);case"RobertaProcessing":return new lm(e);case"BertProcessing":return new om(e);case"Sequence":return new b1(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 om 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 a=r&&this instanceof lm?[this.sep]:[],i=r?[this.sep]:[];e=We(e,a,n,i),s=We(s,new Array(n.length+a.length+i.length).fill(1))}return{tokens:e,token_type_ids:s}}}class lm extends om{}class y1 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 a=[],i=[];for(const o of s)"SpecialToken"in o?r&&(a.push(o.SpecialToken.id),i.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(a=We(a,e),i=We(i,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(a=We(a,n),i=We(i,new Array(n.length).fill(o.Sequence.type_id))));return{tokens:a,token_type_ids:i}}}class um extends nr{post_process(e,n=null){return n&&(e=We(e,n)),{tokens:e}}}class b1 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 a of this.processors)if(a instanceof um)e=a.post_process(e).tokens,n&&(n=a.post_process(n).tokens);else{const i=a.post_process(e,n,r);e=i.tokens,s=i.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 S1(e);case"Metaspace":return new I1(e);case"ByteLevel":return new E1(e);case"Replace":return new v1(e);case"ByteFallback":return new x1(e);case"Fuse":return new $1(e);case"Strip":return new k1(e);case"Sequence":return new C1(e);case"CTC":return new T1(e);case"BPEDecoder":return new M1(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 v1 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 x1 extends ft{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const n=[];let r=[];for(const s of e){let a=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){const i=parseInt(s.slice(3,5),16);isNaN(i)||(a=i)}if(a!==null)r.push(a);else{if(r.length>0){const i=this.text_decoder.decode(Uint8Array.from(r));n.push(i),r=[]}n.push(s)}}if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));n.push(s),r=[]}return n}}class $1 extends ft{decode_chain(e){return[e.join("")]}}class k1 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 a=0;a(r!==0&&(n.startsWith(this.config.prefix)?n=n.replace(this.config.prefix,""):n=" "+n),this.cleanup&&(n=Qa(n)),n))}}class E1 extends ft{constructor(e){super(e),this.byte_decoder=t1,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(a=>this.byte_decoder[a]));return this.text_decoder.decode(r)}decode_chain(e){const n=[];let r=[];for(const s of e)this.added_tokens.find(a=>a.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 T1 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 a=1;aa!==this.pad_token).join("");return this.cleanup&&(s=Qa(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class C1 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 M1 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 A1 extends ft{decode_chain(e){let n="";for(let r=1;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}}class O1 extends bt{constructor(e){super(),this.tokenizers=e.pretokenizers.map(n=>bt.fromConfig(n))}pre_tokenize_text(e,n){return this.tokenizers.reduce((r,s)=>s.pre_tokenize(r,n),[e])}}class P1 extends bt{constructor(e){super()}pre_tokenize_text(e,n){return e.match(/\w+|[^\w\s]+/g)||[]}}class B1 extends bt{constructor(e){super()}pre_tokenize_text(e,n){return Xb(e)}}class R1 extends bt{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 D1=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function F1(t,e,n,r){for(const s of Object.keys(t)){const a=e-t[s].length,i=n(s),o=new Array(a).fill(i);t[s]=r==="right"?We(t[s],o):We(o,t[s])}}function N1(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=bt.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 a=new Zb(s);this.added_tokens.push(a),this.model.tokens_to_ids.set(a.content,a.id),this.model.vocab[a.id]=a.content,a.special&&(this.special_tokens.push(a.content),this.all_special_ids.push(a.id))}if(this.additional_special_tokens=r.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.toSorted((s,a)=>a.content.length-s.content.length).map(s=>`${s.lstrip?"\\s*":""}(${Go(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:a,template:i}of this.chat_template){if(typeof a!="string"||typeof i!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');s[a]=i}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:a=null,local_files_only:i=!1,revision:o="main",legacy:l=null}={}){const u=await rm(n,{progress_callback:r,config:s,cache_dir:a,local_files_only:i,revision:o,legacy:l});return new this(...u)}_call(n,{text_pair:r=null,add_special_tokens:s=!0,padding:a=!1,truncation:i=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?a==="max_length"?o=this.model_max_length:o=dt(p.map(f=>f.input_ids.length))[0]:i||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),o=Math.min(o,this.model_max_length??1/0),a||i)for(let f=0;fo?i&&N1(p[f],o):a&&F1(p[f],o,m=>m==="input_ids"?this.pad_token_id:0,this.padding_side));const d={};if(l){if(!(a&&i)&&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 J("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(a=>a):[n]).map((a,i)=>{if(this.added_tokens.find(l=>l.content===a)!==void 0)return a;{if(this.remove_space===!0&&(a=a.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(a=Wb(a)),this.normalizer!==null&&(a=this.normalizer(a)),a.length===0)return[];const l=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:i}):[a];return this.model(l)}}).flat()}_encode_plus(n,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:a=null}={}){const{tokens:i,token_type_ids:o}=this._tokenize_helper(n,{pair:r,add_special_tokens:s}),l=this.model.convert_tokens_to_ids(i),u={input_ids:l,attention_mask:new Array(l.length).fill(1)};return(a??this.return_token_type_ids)&&o&&(u.token_type_ids=o),u}_tokenize_helper(n,{pair:r=null,add_special_tokens:s=!1}={}){const a=this._encode_text(n),i=this._encode_text(r);return this.post_processor?this.post_processor(a,i,{add_special_tokens:s}):{tokens:We(a??[],i??[])}}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:a=null}={}){return this._encode_plus(n,{text_pair:r,add_special_tokens:s,return_token_type_ids:a}).input_ids}batch_decode(n,r={}){return n instanceof J&&(n=n.tolist()),n.map(s=>this.decode(s,r))}decode(n,r={}){if(n instanceof J&&(n=sm(n)),!Array.isArray(n)||n.length===0||!cy(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 a=this.model.convert_ids_to_tokens(n);r&&(a=a.filter(o=>!this.special_tokens.includes(o)));let i=this.decoder?this.decoder(a):a.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(i=i.replaceAll(this.decoder.end_of_word_suffix," "),r&&(i=i.trim())),(s??this.clean_up_tokenization_spaces)&&(i=Qa(i)),i}apply_chat_template(n,{tools:r=null,documents:s=null,chat_template:a=null,add_generation_prompt:i=!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"||this.chat_template===null){const y=this.chat_template;if(a!==null&&Object.hasOwn(y,a))a=y[a];else if(a===null&&"default"in y)a=y.default;else if(a===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(y).sort()}.`)}else if(this.chat_template)a=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 a!="string")throw Error(`chat_template must be a string, but got ${typeof a}`);let g=this._compiled_template_cache.get(a);g===void 0&&(g=new jb(a),this._compiled_template_cache.set(a,g));const w=Object.create(null);for(const y of D1){const $=this.getToken(y);$&&(w[y]=$)}const v=g.render({messages:n,add_generation_prompt:i,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 L1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class U1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class V1 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 q1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class G1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class W1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class H1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class K1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class X1 extends ce{}class Q1 extends ce{}class Y1 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 Z1 extends ce{constructor(){super(...arguments);A(this,"return_token_type_ids",!0)}}class J1 extends ce{}class ev extends ce{}class tv extends ce{}class cm 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 Ya(this,e,n,r)}}class nv extends cm{}class rv extends ce{}class sv extends ce{constructor(e,n){var a,i;const r=".,!?…。,、।۔،",s=(i=(a=e.pre_tokenizer)==null?void 0:a.pretokenizers[0])==null?void 0:i.pattern;s&&s.Regex===` ?[^(\\s|[${r}])]+`&&(s.Regex=` ?[^\\s${r}]+`),super(e,n)}}const Bs="▁";class iv 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 dm({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 av extends ce{}class ov extends ce{}class lv extends ce{}class uv extends ce{}class dv extends ce{}class cv extends ce{}class pv extends ce{}class hv extends ce{}class fv extends ce{}function Ya(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,a=r.tgt_lang;if(!t.language_codes.includes(a))throw new Error(`Target language code "${a}" 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 i of t.post_processor.config.single)if("SpecialToken"in i&&t.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=t.lang_to_token(s);break}}return r.forced_bos_token_id=t.model.convert_tokens_to_ids([t.lang_to_token(a)])[0],t._call(e,n)}class mv 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 Ya(this,e,n,r)}}class gv 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 Ya(this,e,n,r)}}class _v 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:a=!0}={}){if(s===null)throw Error("Must specify time_precision");let i=null;const o=n==="word";function l(){return{language:i,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 M=null,R=d;if("stride"in k){const[K,X,H]=k.stride;if(p-=X,w=K-H,X&&(R=X/s+d),H)for(let ee=E.length-1;ee>=0;--ee){const ne=Number(E[ee]);if(ne>=d){if(M!==null&&(ne-d)*s=d){const H=(X-d)*s+p,ee=ur(H,2);if(M!==null&&X>=M)g=!0;else if(g||f.length>0&&X0?(f.push(L),o&&m.push(G)):f.every(K=>K.length===0)&&(c=l(),f=[],L=[],m=[],G=[])}if(f.length>0){if(a&&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,i)),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=i?[]:null,l=i?n[0]:null;for(let u=1;uee===G[ne]&&l[E+ne]<=n[u][R+ne]).length:K=M.filter((ee,ne)=>ee===G[ne]).length;const X=k/1e4,H=K/k+X;K>1&&H>p&&(p=H,d=[E,T,R,L])}const[m,g,w,v]=d,y=Math.floor((g+m)/2),$=Math.floor((v+w)/2);a.push(...r.slice(0,y)),r=c.slice($),s=r.length,i&&(o.push(...l.slice(0,y)),l=n[u].slice($))}return a.push(...r),i?(o.push(...l),[a,o]):[a,[]]}collateWordTimestamps(e,n,r){const[s,a,i]=this.combineTokensIntoWords(e,r),o=[];for(let l=0;l=s){const o=((i-s)*r).toFixed(2);a.push(`<|${o}|>`),a.push([])}else a[a.length-1].push(i);return a=a.map(i=>typeof i=="string"?i:super.decode(i,n)),a.join("")}splitTokensOnUnicode(e){const n=this.decode(e,{decode_with_timestamps:!0}),r="�",s=[],a=[],i=[];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||a.length===0)a.push(c),i.push(p),o.push(d);else{const v=a.length-1;a[v]+=c,i[v].push(...p),o[v].push(...d)}}return[a,i,o]}mergePunctuations(e,n,r,s,a){const i=structuredClone(e),o=structuredClone(n),l=structuredClone(r);let u=i.length-2,c=i.length-1;for(;u>=0;)i[u].startsWith(" ")&&s.includes(i[u].trim())?(i[c]=i[u]+i[c],o[c]=We(o[u],o[c]),l[c]=We(l[u],l[c]),i[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 a=nm(e),i=this.model.tokens_to_ids.get(`<|${a}|>`);if(i===void 0)throw new Error(`Unable to find language "${a}" in model vocabulary. Please report this issue at ${Ka}.`);s.push(i)}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 a=this.model.tokens_to_ids.get(`<|${n}|>`);if(a===void 0)throw new Error(`Unable to find task "${n}" in model vocabulary. Please report this issue at ${Ka}.`);s.push(a)}else s.push(null);if(r){const a=this.model.tokens_to_ids.get("<|notimestamps|>");if(a===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${Ka}.`);s.push(a)}return s.map((a,i)=>[i+1,a]).filter(a=>a[1]!==null)}}class wv extends ce{}class yv extends ce{}class bv extends ce{}class vv 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,a]=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(a))}}}class xv extends ce{}class $v extends ce{}class kv extends ce{}class Sv extends ce{}class Ev extends ce{}class Tv extends ce{constructor(e,n){super(e,n),this.decoder=new A1({})}}class Cv extends ce{}class qe{static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:a=!1,revision:i="main",legacy:o=null}={}){var d;const[l,u]=await rm(e,{progress_callback:n,config:r,cache_dir:s,local_files_only:a,revision:i,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:J1,DistilBertTokenizer:X1,CamembertTokenizer:Q1,DebertaTokenizer:q1,DebertaV2Tokenizer:G1,BertTokenizer:L1,HerbertTokenizer:W1,ConvBertTokenizer:H1,RoFormerTokenizer:K1,XLMTokenizer:Y1,ElectraTokenizer:Z1,MobileBertTokenizer:V1,SqueezeBertTokenizer:j1,AlbertTokenizer:U1,GPT2Tokenizer:ev,BartTokenizer:tv,MBartTokenizer:cm,MBart50Tokenizer:nv,RobertaTokenizer:rv,WhisperTokenizer:_v,CodeGenTokenizer:wv,CLIPTokenizer:yv,SiglipTokenizer:bv,MarianTokenizer:vv,BloomTokenizer:sv,NllbTokenizer:mv,M2M100Tokenizer:gv,LlamaTokenizer:iv,CodeLlamaTokenizer:av,XLMRobertaTokenizer:ov,MPNetTokenizer:lv,FalconTokenizer:uv,GPTNeoXTokenizer:dv,EsmTokenizer:cv,Wav2Vec2CTCTokenizer:xv,BlenderbotTokenizer:$v,BlenderbotSmallTokenizer:kv,SpeechT5Tokenizer:Sv,NougatTokenizer:Ev,VitsTokenizer:Tv,Qwen2Tokenizer:pv,GemmaTokenizer:hv,Grok1Tokenizer:fv,CohereTokenizer:Cv,PreTrainedTokenizer:ce});async function Mv(t,e){return await nn(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"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),a="num_decoder_layers"in s,i=Ht(t,["model_type","is_encoder_decoder"]);return a?(i.num_decoder_layers=s.num_decoder_layers,i.num_decoder_heads=s.num_decoder_heads,i.decoder_hidden_size=s.decoder_hidden_size,i.num_encoder_layers=s.num_encoder_layers,i.num_encoder_heads=s.num_encoder_heads,i.encoder_hidden_size=s.encoder_hidden_size):(i.num_layers=s.num_layers,i.num_heads=s.num_heads,i.hidden_size=s.hidden_size),i}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 pm(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 a=r.encoder_dim_kv??r.encoder_hidden_size/r.num_encoder_heads,i=r.decoder_dim_kv??r.decoder_hidden_size/r.num_decoder_heads,o=[s,r.num_encoder_heads,0,a],l=[s,r.num_decoder_heads,0,i];for(let u=0;u=1&&a[a.length-1]>=this.timestamp_begin,o=a.length<2||a[a.length-2]>=this.timestamp_begin;if(i&&(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=by(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 Rv extends Ut{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const n=e.length,r=[];for(let a=0;a1 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),a=n.slice([r,n.dims[0]],null);for(let i=0;i1)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 qv extends Za{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 gm{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 Ja 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 Ja&&(e=[e]),this.criteria.push(...e)}_call(e,n){const r=new Array(e.length).fill(!1);for(const s of this.criteria){const a=s(e,n);for(let i=0;in.length>=this.max_length)}}class Wv extends Ja{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(a=>s==a)})}}class Fs 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 a=n*r;s=s.slice(a,a+r)}return s}randomSelect(e){let n=0;for(let s=0;s1)return new Xv(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 Hv(e)}}class Hv extends Fs{async sample(e){const n=dt(e.data)[1];return[[BigInt(n),0]]}}class Kv extends Fs{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 Zn(e,n),a=He(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const i=this.randomSelect(a);return[s.data[i],Math.log(a[i])]})}}class Xv extends Fs{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 Zn(e,n),a=He(r.data);return Array.from({length:this.generation_config.num_beams},(i,o)=>[s.data[o],Math.log(a[o])])}}class Qv extends gm{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,_m=new Map,zr=new Map;async function Yv(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"),a=rb(s);let i=n.dtype;typeof i!="string"&&(i&&i.hasOwnProperty(e)?i=i[e]:(i=zv[s]??vt.fp32,console.warn(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${s}).`)));const o=i;if(fm.hasOwnProperty(o)){if(o===vt.fp16&&s==="webgpu"&&!await Iv())throw new Error(`The device (${s}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${o}. Should be one of: ${Object.keys(vt).join(", ")}`);const l=fm[o],u=`${n.subfolder??""}/${e}${l}.onnx`,c={...n.session_options};c.executionProviders??(c.executionProviders=a);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=pm(n.config,{prefix:"present"});if(Object.keys(m).length>0&&!Uf()){const g={};for(const w in m)g[w]="gpu-buffer";c.preferredOutputLocation=g}}return{buffer:await p,session_options:c}}async function In(t,e,n){return Object.fromEntries(await Promise.all(Object.keys(e).map(async r=>{const{buffer:s,session_options:a}=await Yv(t,e[r],n),i=await Nf(s,a);return[r,i]})))}function Zv(t,e){const n=Object.create(null),r=[];for(const i of t.inputNames){const o=e[i];if(!(o instanceof J)){r.push(i);continue}n[i]=Uf()?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,a=t.inputNames.length;if(s>a){let i=Object.keys(e).filter(o=>!t.inputNames.includes(o));console.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${i.join(", ")}".`)}return n}async function hn(t,e){const n=Zv(t,e);try{const r=Object.fromEntries(Object.entries(n).map(([a,i])=>[a,i.ort_tensor]));let s=await t.run(r);return s=wm(s),s}catch(r){throw console.error(`An error occurred during model execution: "${r}".`),console.error("Inputs given to model:",n),r}}function wm(t){for(let e in t)Lf(t[e])?t[e]=new J(t[e]):typeof t[e]=="object"&&wm(t[e]);return t}function to(t){if(t instanceof J)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 J("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new J("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function ym(t){return new J("bool",[t],[1])}async function bm(t,e){let{encoder_outputs:n,input_ids:r,decoder_input_ids:s,...a}=e;if(!n){const o=Ht(e,t.sessions.model.inputNames);n=(await rr(t,o)).last_hidden_state}return a.input_ids=s,a.encoder_hidden_states=n,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=e.attention_mask),await Ls(t,a,!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 J("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,...a}=e;r.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=ym(!!s)),r.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids&&(a.position_ids=ex(a,s)),t.addPastKeyValues(a,s);const i=Ht(a,r.inputNames);return await hn(r,i)}async function Jv(t,{input_ids:e=null,attention_mask:n=null,pixel_values:r=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:o=null,logits_processor:l=null,...u}){if(!a){if(a=await t.encode_text({input_ids:e}),r&&e.dims[1]!==1){const p=await t.encode_image({pixel_values:r});({inputs_embeds:a,attention_mask:n}=t._merge_input_ids_with_image_features({image_features:p,inputs_embeds:a,input_ids:e,attention_mask:n}))}else if(i&&r&&e.dims[1]===1){const p=e.dims[1],d=Object.values(i)[0].dims.at(-2);n=ct([Jn([e.dims[0],d]),n.slice(null,[n.dims[1]-p,n.dims[1]])],1)}}return await Ls(t,{inputs_embeds:a,past_key_values:i,attention_mask:n,position_ids:s,generation_config:o,logits_processor:l},!0)}function ex(t,e=null){const{input_ids:n,inputs_embeds:r,attention_mask:s}=t,[a,i]=s.dims,o=new BigInt64Array(s.data.length);for(let u=0;ua.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=a.dims[1]-(s-o);n.input_ids=a.slice(null,[-l,null]),n.attention_mask=Jn([1,s+l])}}}return n}function xm(t,e,n,r){return n.past_key_values&&(e=e.map(s=>[s.at(-1)])),{...n,decoder_input_ids:to(e)}}function tx(t,...e){return t.config.is_encoder_decoder?xm(t,...e):vm(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),a=Ns.get(s);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,a){case de.DecoderOnly:this.can_generate=!0,this._forward=Ls,this._prepare_inputs_for_generation=vm;break;case de.Seq2Seq:case de.Vision2Seq:case de.Musicgen:this.can_generate=!0,this._forward=bm,this._prepare_inputs_for_generation=xm;break;case de.EncoderDecoder:this._forward=bm;break;case de.ImageTextToText:this.can_generate=!0,this._forward=Jv,this._prepare_inputs_for_generation=tx;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:a=null,local_files_only:i=!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:a,local_files_only:i,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 hm.from_pretrained(n,m);let v;if(w===de.DecoderOnly)v=await Promise.all([In(n,{model:m.model_file_name??"model"},m),nn(n,"generation_config.json",!1,m)]);else if(w===de.Seq2Seq||w===de.Vision2Seq)v=await Promise.all([In(n,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m),nn(n,"generation_config.json",!1,m)]);else if(w===de.MaskGeneration)v=await Promise.all([In(n,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},m)]);else if(w===de.EncoderDecoder)v=await Promise.all([In(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([In(n,y,m),nn(n,"generation_config.json",!1,m)])}else w===de.Musicgen?v=await Promise.all([In(n,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},m),nn(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([In(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 Ds;return n.temperature!==null&&n.temperature!==1&&r.push(new Vv(n.temperature)),n.top_k!==null&&n.top_k!==0&&r.push(new qv(n.top_k)),n.top_p!==null&&n.top_p<1&&r.push(new jv(n.top_p)),r}_get_logits_processor(n,r,s=null){const a=new Ds;if(n.repetition_penalty!==null&&n.repetition_penalty!==1&&a.push(new Dv(n.repetition_penalty)),n.no_repeat_ngram_size!==null&&n.no_repeat_ngram_size>0&&a.push(new Rv(n.no_repeat_ngram_size)),n.bad_words_ids!==null&&a.push(new Lv(n.bad_words_ids,n.eos_token_id)),n.min_length!==null&&n.eos_token_id!==null&&n.min_length>0&&a.push(new Fv(n.min_length,n.eos_token_id)),n.min_new_tokens!==null&&n.eos_token_id!==null&&n.min_new_tokens>0&&a.push(new Nv(r,n.min_new_tokens,n.eos_token_id)),n.forced_bos_token_id!==null&&a.push(new Ov(n.forced_bos_token_id)),n.forced_eos_token_id!==null&&a.push(new Pv(n.max_length,n.forced_eos_token_id)),n.begin_suppress_tokens!==null){const i=r>1||n.forced_bos_token_id===null?r:r+1;a.push(new mm(n.begin_suppress_tokens,i))}return n.guidance_scale!==null&&n.guidance_scale>1&&a.push(new Uv(n.guidance_scale)),s!==null&&a.extend(s),a}_prepare_generation_config(n,r,s=gm){const a={...this.config};for(const o of["decoder","generator","text_config"])o in a&&Object.assign(a,a[o]);const i=new s(a);return"generation_config"in this&&Object.assign(i,this.generation_config),n&&Object.assign(i,n),r&&Object.assign(i,Ht(r,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(n,r=null){const s=new eo;return n.max_length!==null&&s.push(new Gv(n.max_length,this.config.max_position_embeddings??null)),n.eos_token_id!==null&&s.push(new Wv(n.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){const n=[uo,co,lo,oo],r=zr.get(this.constructor),s=new Set,a=this.config.model_type;for(const o of n){const l=o.get(a);l&&s.add(l[0])}let i=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(i+=` Please use the following class instead: ${[...s].join(", ")}`),Error(i)}}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:a}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new J("int64",n.flat(),[n.length,1]),a||(s.attention_mask=ct([s.attention_mask,Jn([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 a=Ht(s,this.forward_params),i=this.main_input_name;if(i in a){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 a[i]=n;return{inputs_tensor:a[i],model_inputs:a,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:n,model_inputs:r,model_input_name:s,generation_config:a}){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:i}=await rr(this,r);if(a.guidance_scale!==null&&a.guidance_scale>1)i=ct([i,cb(i,0)],0),"attention_mask"in r&&(r.attention_mask=ct([r.attention_mask,fb(r.attention_mask)],0));else if(r.decoder_input_ids){const o=to(r.decoder_input_ids).dims[0];if(o!==i.dims[0]){if(i.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${o}).`);i=ct(Array.from({length:o},()=>i),0)}}return r.encoder_outputs=i,r}_prepare_decoder_input_ids_for_generation({batch_size:n,model_input_name:r,model_kwargs:s,decoder_start_token_id:a,bos_token_id:i,generation_config:o}){let{decoder_input_ids:l,...u}=s;if(l)Array.isArray(l[0])||(l=Array.from({length:n},()=>l));else if(a??(a=i),this.config.model_type==="musicgen")l=Array.from({length:n*this.config.decoder.num_codebooks},()=>[a]);else if(Array.isArray(a)){if(a.length!==n)throw new Error(`\`decoder_start_token_id\` expcted to have length ${n} but got ${a.length}`);l=a}else l=Array.from({length:n},()=>[a]);return l=to(l),s.decoder_attention_mask=pb(l),{input_ids:l,model_inputs:u}}async generate({inputs:n=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:a=null,streamer:i=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,a),w=u[c].dims.at(0),v=Fs.getSampler(r),y=new Array(w).fill(0),$=d.tolist();i&&i.put($);let k=null,E={};for(;;){u=this.prepare_inputs_for_generation($,u,r);const M=await this.forward(u);if(r.output_attentions&&r.return_dict_in_generate){const X=this.getAttentions(M);for(const H in X)H in E||(E[H]=[]),E[H].push(X[H])}const R=M.logits.slice(null,-1,null),L=m($,R),G=[];for(let X=0;XX)){r.return_dict_in_generate&&(k=this.getPastKeyValues(M,u.past_key_values,!1));break}u=this._update_model_kwargs_for_generation({generated_input_ids:G,outputs:M,model_inputs:u,is_encoder_decoder:p})}i&&i.end();const T=new J("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 a=Object.create(null);for(const i in n)if(i.startsWith("present")){const o=i.replace("present","past_key_values");if(r&&i.includes("encoder"))a[o]=r[o];else{if(s&&r){const l=r[o];l.location==="gpu-buffer"&&l.dispose()}a[o]=n[i]}}return a}getAttentions(n){const r={};for(const s of["cross_attentions","encoder_attentions","decoder_attentions"])for(const a in n)a.startsWith(s)&&(s in r||(r[s]=[]),r[s].push(n[a]));return r}addPastKeyValues(n,r){if(r)Object.assign(n,r);else{const s=this.custom_config.kv_cache_dtype??"float32",a=s==="float16"?new Uint16Array:[],i=pm(this.config);for(const o in i)n[o]=new J(s,a,i[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 nx extends Or{}class rx extends Or{async _call(e){return new et(await super._call(e))}}class sx extends Or{async _call(e){return new me(await super._call(e))}}class ix extends Or{async _call(e){return new Xe(await super._call(e))}}class ax extends Or{async _call(e){return new st(await super._call(e))}}class ox extends j{}class lx extends ox{}class Pr extends j{}class ux extends Pr{}class dx extends Pr{async _call(e){return new et(await super._call(e))}}class cx extends Pr{async _call(e){return new me(await super._call(e))}}class px extends Pr{async _call(e){return new Xe(await super._call(e))}}class hx extends Pr{async _call(e){return new st(await super._call(e))}}class Br extends j{}class fx extends Br{}class mx extends Br{async _call(e){return new et(await super._call(e))}}class gx extends Br{async _call(e){return new me(await super._call(e))}}class _x extends Br{async _call(e){return new Xe(await super._call(e))}}class wx extends Br{async _call(e){return new st(await super._call(e))}}class Rr extends j{}class yx extends Rr{}class bx extends Rr{async _call(e){return new et(await super._call(e))}}class vx extends Rr{async _call(e){return new me(await super._call(e))}}class xx extends Rr{async _call(e){return new Xe(await super._call(e))}}class $x extends Rr{async _call(e){return new st(await super._call(e))}}class Dr extends j{}class kx extends Dr{}class Sx extends Dr{async _call(e){return new et(await super._call(e))}}class Ex extends Dr{async _call(e){return new me(await super._call(e))}}class Tx extends Dr{async _call(e){return new Xe(await super._call(e))}}class Cx extends Dr{async _call(e){return new st(await super._call(e))}}class Fr extends j{}class Mx extends Fr{}class Ax extends Fr{async _call(e){return new et(await super._call(e))}}class Ix extends Fr{async _call(e){return new me(await super._call(e))}}class zx extends Fr{async _call(e){return new Xe(await super._call(e))}}class Ox extends Fr{async _call(e){return new st(await super._call(e))}}class Nr extends j{}class Px extends Nr{}class Bx extends Nr{async _call(e){return new et(await super._call(e))}}class Rx extends Nr{async _call(e){return new me(await super._call(e))}}class Dx extends Nr{async _call(e){return new Xe(await super._call(e))}}class Fx extends Nr{async _call(e){return new st(await super._call(e))}}class Lr extends j{}class Nx extends Lr{}class Lx extends Lr{async _call(e){return new me(await super._call(e))}}class Ux extends Lr{async _call(e){return new Xe(await super._call(e))}}class Vx extends Lr{async _call(e){return new st(await super._call(e))}}class jx extends Lr{async _call(e){return new et(await super._call(e))}}class Us extends j{}class qx extends Us{}class Gx extends Us{async _call(e){return new et(await super._call(e))}}class Wx extends Us{async _call(e){return new me(await super._call(e))}}class Hx extends Us{async _call(e){return new Xe(await super._call(e))}}class Vs extends j{}class Kx extends Vs{}class Xx extends Vs{async _call(e){return new et(await super._call(e))}}class Qx extends Vs{async _call(e){return new me(await super._call(e))}}class Yx extends Vs{async _call(e){return new st(await super._call(e))}}class Ur extends j{}class Zx extends Ur{}class Jx extends Ur{async _call(e){return new et(await super._call(e))}}class e2 extends Ur{async _call(e){return new me(await super._call(e))}}class t2 extends Ur{async _call(e){return new Xe(await super._call(e))}}class n2 extends Ur{async _call(e){return new st(await super._call(e))}}class js extends j{}class r2 extends js{}class s2 extends js{async _call(e){return new et(await super._call(e))}}class i2 extends js{async _call(e){return new me(await super._call(e))}}class a2 extends js{async _call(e){return new st(await super._call(e))}}class qs extends j{}class o2 extends qs{}class l2 extends qs{async _call(e){return new me(await super._call(e))}}class u2 extends qs{async _call(e){return new st(await super._call(e))}}class d2 extends qs{async _call(e){return new et(await super._call(e))}}class $m 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 c2 extends $m{}class p2 extends $m{}class km extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class h2 extends km{}class f2 extends km{}class Sm extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class m2 extends Sm{}class g2 extends Sm{}class no extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class _2 extends no{}class w2 extends no{}class y2 extends no{async _call(e){return new me(await super._call(e))}}class Gs extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class b2 extends Gs{}class v2 extends Gs{}class x2 extends Gs{async _call(e){return new me(await super._call(e))}}class $2 extends Gs{}class Em extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class k2 extends Em{}class S2 extends Em{}class Tm extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class E2 extends Tm{}class T2 extends Tm{}class Vr extends j{}class C2 extends Vr{}class M2 extends Vr{async _call(e){return new et(await super._call(e))}}class A2 extends Vr{async _call(e){return new me(await super._call(e))}}class I2 extends Vr{async _call(e){return new Xe(await super._call(e))}}class z2 extends Vr{async _call(e){return new st(await super._call(e))}}class jr extends j{}class O2 extends jr{}class P2 extends jr{async _call(e){return new et(await super._call(e))}}class B2 extends jr{async _call(e){return new me(await super._call(e))}}class R2 extends jr{async _call(e){return new Xe(await super._call(e))}}class D2 extends jr{async _call(e){return new st(await super._call(e))}}class qr extends j{}class F2 extends qr{}class N2 extends qr{async _call(e){return new et(await super._call(e))}}class L2 extends qr{async _call(e){return new me(await super._call(e))}}class U2 extends qr{async _call(e){return new Xe(await super._call(e))}}class V2 extends qr{async _call(e){return new st(await super._call(e))}}class Cm extends j{}class j2 extends Cm{}class q2 extends Cm{}class Mm 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 G2 extends Mm{}class W2 extends Mm{_prepare_generation_config(e,n){return super._prepare_generation_config(e,n,Qv)}_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 i=`<|${nm(r)}|>`;n.push(e.lang_to_id[i]),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(a=>a!=null)}async generate({inputs:e=null,generation_config:n=null,logits_processor:r=null,stopping_criteria:s=null,...a}){n=this._prepare_generation_config(n,a);const i=a.decoder_input_ids??this._retrieve_init_tokens(n);if(n.return_timestamps&&(r??(r=new Ds),r.push(new Bv(n,i))),n.begin_suppress_tokens&&(r??(r=new Ds),r.push(new mm(n.begin_suppress_tokens,i.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:i,...a});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 a=this.config.median_filter_width;a===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const i=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(g,w)=>ct(i.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]=lb(l,-2,0,!0),p=l.clone();for(let g=0;gv[M+1]-v[M]),k=We([1],$).map(T=>!!T),E=[];for(let T=0;Td.findIndex(f=>f==a)),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;da*i,1);e.input_labels=new J("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 Vk(await super._call(e))}}class Vk extends mt{constructor({iou_scores:e,pred_masks:n}){super(),this.iou_scores=e,this.pred_masks=n}}class wg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class jk extends wg{}class qk extends wg{}class yg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class Gk extends yg{}class Wk extends yg{}class zn extends j{}class Hk extends zn{}class Kk extends zn{async _call(e){return new sr(await super._call(e))}}class Xk extends zn{async _call(e){return new me(await super._call(e))}}class Qk extends zn{async _call(e){return new Xe(await super._call(e))}}class bg extends j{}class Yk extends bg{}class Zk extends bg{async _call(e){return new Xe(await super._call(e))}}class Jk extends j{}class eS extends Jk{}class so extends j{}class tS extends so{}class nS extends so{async _call(e){return new sr(await super._call(e))}}class rS extends so{async _call(e){return new me(await super._call(e))}}class Hs extends j{}class sS extends Hs{}class iS extends Hs{async _call(e){return new sr(await super._call(e))}}class aS extends Hs{async _call(e){return new me(await super._call(e))}}class oS extends Hs{async _call(e){return new Xe(await super._call(e))}}class io extends j{}class lS extends io{}class uS extends io{async _call(e){return new sr(await super._call(e))}}class dS extends io{async _call(e){return new me(await super._call(e))}}class cS extends zn{}class pS extends zn{async _call(e){return new sr(await super._call(e))}}class hS extends zn{async _call(e){return new me(await super._call(e))}}class Gr extends j{}class fS extends Gr{}class mS extends Gr{async _call(e){return new sr(await super._call(e))}}class gS extends Gr{async _call(e){return new me(await super._call(e))}}class _S extends Gr{async _call(e){return new rE(await super._call(e))}}class wS extends Gr{async _call(e){return new Xe(await super._call(e))}}class vg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class yS extends vg{}class bS extends vg{async generate_speech(e,n,{threshold:r=.5,minlenratio:s=0,maxlenratio:a=20,vocoder:i=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*a),d=Math.floor(c*s),f=this.config.num_mel_bins;let m=[],g=null,w=null,v=0;for(;;){++v;const k=ym(!!w);let E;w?E=w.output_sequence_out:E=new J("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:M,spectrum:R}=w;if(m.push(R),v>=d&&(Array.from(M.data).filter(L=>L>=r).length>0||v>=p))break}const y=ct(m),{waveform:$}=await hn(i.sessions.model,{spectrogram:y});return{spectrogram:y,waveform:$}}}class vS extends j{constructor(){super(...arguments);A(this,"main_input_name","spectrogram")}}class xS extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class $S extends xS{}class xg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class kS extends xg{}class SS extends xg{}class $g extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class ES extends $g{}class TS extends $g{}class kg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class CS extends kg{}class MS extends kg{}class ao extends j{}class AS extends ao{}class IS extends ao{static async from_pretrained(e,n={}){return n.model_file_name??(n.model_file_name="text_model"),super.from_pretrained(e,n)}}class zS extends ao{static async from_pretrained(e,n={}){return n.model_file_name??(n.model_file_name="audio_model"),super.from_pretrained(e,n)}}class OS extends j{}class Sg extends OS{async _call(e){return new iE(await super._call(e))}}class Eg extends j{}class PS extends Eg{}class BS extends Eg{}class Tg extends j{constructor(e,n,r){super(e,n),this.generation_config=r}}class RS extends Tg{}class DS extends Tg{}class Cg extends j{}class FS extends Cg{}class NS extends Cg{async _call(e){return new me(await super._call(e))}}class Mg 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,a=this.config.decoder.num_codebooks,i=s-a;let o=0;for(let c=0;c0&&f<=i&&(n.data[o++]=n.data[c])}const l=Math.floor(r/a),u=o/(l*a);return new J(n.type,n.data.slice(0,o),[l,a,u])}prepare_inputs_for_generation(n,r,s){let a=structuredClone(n);for(let o=0;o=l&&(a[o][l]=BigInt(this.config.decoder.pad_token_id));return s.guidance_scale!==null&&s.guidance_scale>1&&(a=a.concat(a)),super.prepare_inputs_for_generation(a,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:a}=await hn(this.sessions.encodec_decode,{audio_codes:s});return a}}class Ag extends j{}class LS extends Ag{}class US extends Ag{async _call(e){return new me(await super._call(e))}}class Ig extends j{}class VS extends Ig{}class jS extends Ig{async _call(e){return new me(await super._call(e))}}class zg extends j{}class qS extends zg{}class GS extends zg{async _call(e){return new me(await super._call(e))}}class Og extends j{}class WS extends Og{}class HS extends Og{async _call(e){return new me(await super._call(e))}}class Ce{static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:a=!1,revision:i="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:c=null,use_external_data_format:p=null,session_options:d={}}={}){let f={progress_callback:n,config:r,cache_dir:s,local_files_only:a,revision:i,model_file_name:o,subfolder:l,device:u,dtype:c,use_external_data_format:p,session_options:d};if(f.config=await hm.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let m of this.MODEL_CLASS_MAPPINGS){const g=m.get(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(Ce,"MODEL_CLASS_MAPPINGS",null),A(Ce,"BASE_IF_FAIL",!1);const KS=new Map([["bert",["BertModel",nx]],["nomic_bert",["NomicBertModel",lx]],["roformer",["RoFormerModel",ux]],["electra",["ElectraModel",yx]],["esm",["EsmModel",qx]],["convbert",["ConvBertModel",fx]],["camembert",["CamembertModel",kx]],["deberta",["DebertaModel",Mx]],["deberta-v2",["DebertaV2Model",Px]],["mpnet",["MPNetModel",Zx]],["albert",["AlbertModel",o2]],["distilbert",["DistilBertModel",Nx]],["roberta",["RobertaModel",C2]],["xlm",["XLMModel",O2]],["xlm-roberta",["XLMRobertaModel",F2]],["clap",["ClapModel",AS]],["clip",["CLIPModel",Y2]],["clipseg",["CLIPSegModel",i$]],["chinese_clip",["ChineseCLIPModel",s$]],["siglip",["SiglipModel",e$]],["mobilebert",["MobileBertModel",Kx]],["squeezebert",["SqueezeBertModel",r2]],["wav2vec2",["Wav2Vec2Model",Hk]],["wav2vec2-bert",["Wav2Vec2BertModel",lS]],["unispeech",["UniSpeechModel",tS]],["unispeech-sat",["UniSpeechSatModel",sS]],["hubert",["HubertModel",cS]],["wavlm",["WavLMModel",fS]],["audio-spectrogram-transformer",["ASTModel",j2]],["vits",["VitsModel",Sg]],["pyannote",["PyAnnoteModel",Yk]],["wespeaker-resnet",["WeSpeakerResNetModel",eS]],["detr",["DetrModel",rk]],["rt_detr",["RTDetrModel",ok]],["table-transformer",["TableTransformerModel",dk]],["vit",["ViTModel",U$]],["fastvit",["FastViTModel",j$]],["mobilevit",["MobileViTModel",H$]],["mobilevitv2",["MobileViTV2Model",X$]],["owlvit",["OwlViTModel",Y$]],["owlv2",["Owlv2Model",J$]],["beit",["BeitModel",tk]],["deit",["DeiTModel",hk]],["convnext",["ConvNextModel",Ik]],["convnextv2",["ConvNextV2Model",Ok]],["dinov2",["Dinov2Model",Bk]],["resnet",["ResNetModel",mk]],["swin",["SwinModel",_k]],["swin2sr",["Swin2SRModel",yk]],["donut-swin",["DonutSwinModel",Ak]],["yolos",["YolosModel",Dk]],["dpt",["DPTModel",vk]],["glpn",["GLPNModel",Tk]],["hifigan",["SpeechT5HifiGan",vS]],["efficientnet",["EfficientNetModel",FS]],["mobilenet_v1",["MobileNetV1Model",LS]],["mobilenet_v2",["MobileNetV2Model",VS]],["mobilenet_v3",["MobileNetV3Model",qS]],["mobilenet_v4",["MobileNetV4Model",WS]]]),XS=new Map([["t5",["T5Model",c2]],["longt5",["LongT5Model",h2]],["mt5",["MT5Model",m2]],["bart",["BartModel",_2]],["mbart",["MBartModel",b2]],["marian",["MarianModel",jk]],["whisper",["WhisperModel",G2]],["m2m_100",["M2M100Model",Gk]],["blenderbot",["BlenderbotModel",k2]],["blenderbot-small",["BlenderbotSmallModel",E2]]]),QS=new Map([["bloom",["BloomModel",B$]],["gpt2",["GPT2Model",o$]],["gptj",["GPTJModel",h$]],["gpt_bigcode",["GPTBigCodeModel",m$]],["gpt_neo",["GPTNeoModel",u$]],["gpt_neox",["GPTNeoXModel",c$]],["codegen",["CodeGenModel",_$]],["llama",["LlamaModel",y$]],["cohere",["CohereModel",v$]],["gemma",["GemmaModel",$$]],["gemma2",["Gemma2Model",S$]],["openelm",["OpenELMModel",T$]],["qwen2",["Qwen2Model",M$]],["phi",["PhiModel",I$]],["phi3",["Phi3Model",O$]],["mpt",["MptModel",D$]],["opt",["OPTModel",N$]],["mistral",["MistralModel",kS]],["starcoder2",["Starcoder2Model",ES]],["falcon",["FalconModel",CS]],["stablelm",["StableLmModel",RS]]]),oo=new Map([["speecht5",["SpeechT5ForSpeechToText",yS]],["whisper",["WhisperForConditionalGeneration",W2]]]),Pg=new Map([["speecht5",["SpeechT5ForTextToSpeech",bS]]]),Bg=new Map([["vits",["VitsModel",Sg]],["musicgen",["MusicgenForConditionalGeneration",Mg]]]),Rg=new Map([["bert",["BertForSequenceClassification",sx]],["roformer",["RoFormerForSequenceClassification",cx]],["electra",["ElectraForSequenceClassification",vx]],["esm",["EsmForSequenceClassification",Wx]],["convbert",["ConvBertForSequenceClassification",gx]],["camembert",["CamembertForSequenceClassification",Ex]],["deberta",["DebertaForSequenceClassification",Ix]],["deberta-v2",["DebertaV2ForSequenceClassification",Rx]],["mpnet",["MPNetForSequenceClassification",e2]],["albert",["AlbertForSequenceClassification",l2]],["distilbert",["DistilBertForSequenceClassification",Lx]],["roberta",["RobertaForSequenceClassification",A2]],["xlm",["XLMForSequenceClassification",B2]],["xlm-roberta",["XLMRobertaForSequenceClassification",L2]],["bart",["BartForSequenceClassification",y2]],["mbart",["MBartForSequenceClassification",x2]],["mobilebert",["MobileBertForSequenceClassification",Qx]],["squeezebert",["SqueezeBertForSequenceClassification",i2]]]),Dg=new Map([["bert",["BertForTokenClassification",ix]],["roformer",["RoFormerForTokenClassification",px]],["electra",["ElectraForTokenClassification",xx]],["esm",["EsmForTokenClassification",Hx]],["convbert",["ConvBertForTokenClassification",_x]],["camembert",["CamembertForTokenClassification",Tx]],["deberta",["DebertaForTokenClassification",zx]],["deberta-v2",["DebertaV2ForTokenClassification",Dx]],["mpnet",["MPNetForTokenClassification",t2]],["distilbert",["DistilBertForTokenClassification",Ux]],["roberta",["RobertaForTokenClassification",I2]],["xlm",["XLMForTokenClassification",R2]],["xlm-roberta",["XLMRobertaForTokenClassification",U2]]]),lo=new Map([["t5",["T5ForConditionalGeneration",p2]],["longt5",["LongT5ForConditionalGeneration",f2]],["mt5",["MT5ForConditionalGeneration",g2]],["bart",["BartForConditionalGeneration",w2]],["mbart",["MBartForConditionalGeneration",v2]],["marian",["MarianMTModel",qk]],["m2m_100",["M2M100ForConditionalGeneration",Wk]],["blenderbot",["BlenderbotForConditionalGeneration",S2]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",T2]]]),uo=new Map([["bloom",["BloomForCausalLM",R$]],["gpt2",["GPT2LMHeadModel",l$]],["gptj",["GPTJForCausalLM",f$]],["gpt_bigcode",["GPTBigCodeForCausalLM",g$]],["gpt_neo",["GPTNeoForCausalLM",d$]],["gpt_neox",["GPTNeoXForCausalLM",p$]],["codegen",["CodeGenForCausalLM",w$]],["llama",["LlamaForCausalLM",b$]],["cohere",["CohereForCausalLM",x$]],["gemma",["GemmaForCausalLM",k$]],["gemma2",["Gemma2ForCausalLM",E$]],["openelm",["OpenELMForCausalLM",C$]],["qwen2",["Qwen2ForCausalLM",A$]],["phi",["PhiForCausalLM",z$]],["phi3",["Phi3ForCausalLM",P$]],["mpt",["MptForCausalLM",F$]],["opt",["OPTForCausalLM",L$]],["mbart",["MBartForCausalLM",$2]],["mistral",["MistralForCausalLM",SS]],["starcoder2",["Starcoder2ForCausalLM",TS]],["falcon",["FalconForCausalLM",MS]],["trocr",["TrOCRForCausalLM",$S]],["stablelm",["StableLmForCausalLM",DS]]]),Fg=new Map([["bert",["BertForMaskedLM",rx]],["roformer",["RoFormerForMaskedLM",dx]],["electra",["ElectraForMaskedLM",bx]],["esm",["EsmForMaskedLM",Gx]],["convbert",["ConvBertForMaskedLM",mx]],["camembert",["CamembertForMaskedLM",Sx]],["deberta",["DebertaForMaskedLM",Ax]],["deberta-v2",["DebertaV2ForMaskedLM",Bx]],["mpnet",["MPNetForMaskedLM",Jx]],["albert",["AlbertForMaskedLM",d2]],["distilbert",["DistilBertForMaskedLM",jx]],["roberta",["RobertaForMaskedLM",M2]],["xlm",["XLMWithLMHeadModel",P2]],["xlm-roberta",["XLMRobertaForMaskedLM",N2]],["mobilebert",["MobileBertForMaskedLM",Xx]],["squeezebert",["SqueezeBertForMaskedLM",s2]]]),Ng=new Map([["bert",["BertForQuestionAnswering",ax]],["roformer",["RoFormerForQuestionAnswering",hx]],["electra",["ElectraForQuestionAnswering",$x]],["convbert",["ConvBertForQuestionAnswering",wx]],["camembert",["CamembertForQuestionAnswering",Cx]],["deberta",["DebertaForQuestionAnswering",Ox]],["deberta-v2",["DebertaV2ForQuestionAnswering",Fx]],["mpnet",["MPNetForQuestionAnswering",n2]],["albert",["AlbertForQuestionAnswering",u2]],["distilbert",["DistilBertForQuestionAnswering",Vx]],["roberta",["RobertaForQuestionAnswering",z2]],["xlm",["XLMForQuestionAnswering",D2]],["xlm-roberta",["XLMRobertaForQuestionAnswering",V2]],["mobilebert",["MobileBertForQuestionAnswering",Yx]],["squeezebert",["SqueezeBertForQuestionAnswering",a2]]]),co=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Am]]]),YS=new Map([["llava",["LlavaForConditionalGeneration",Im]],["moondream1",["Moondream1ForConditionalGeneration",K2]],["florence2",["Florence2ForConditionalGeneration",Q2]]]),ZS=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Am]]]),Lg=new Map([["vit",["ViTForImageClassification",V$]],["fastvit",["FastViTForImageClassification",q$]],["mobilevit",["MobileViTForImageClassification",K$]],["mobilevitv2",["MobileViTV2ForImageClassification",Q$]],["beit",["BeitForImageClassification",nk]],["deit",["DeiTForImageClassification",fk]],["convnext",["ConvNextForImageClassification",zk]],["convnextv2",["ConvNextV2ForImageClassification",Pk]],["dinov2",["Dinov2ForImageClassification",Rk]],["resnet",["ResNetForImageClassification",gk]],["swin",["SwinForImageClassification",wk]],["segformer",["SegformerForImageClassification",PS]],["efficientnet",["EfficientNetForImageClassification",NS]],["mobilenet_v1",["MobileNetV1ForImageClassification",US]],["mobilenet_v2",["MobileNetV2ForImageClassification",jS]],["mobilenet_v3",["MobileNetV3ForImageClassification",GS]],["mobilenet_v4",["MobileNetV4ForImageClassification",HS]]]),Ug=new Map([["detr",["DetrForObjectDetection",sk]],["rt_detr",["RTDetrForObjectDetection",lk]],["table-transformer",["TableTransformerForObjectDetection",ck]],["yolos",["YolosForObjectDetection",Fk]]]),Vg=new Map([["owlvit",["OwlViTForObjectDetection",Z$]],["owlv2",["Owlv2ForObjectDetection",ek]]]),jg=new Map([["detr",["DetrForSegmentation",ik]],["clipseg",["CLIPSegForImageSegmentation",a$]]]),qg=new Map([["segformer",["SegformerForSemanticSegmentation",BS]],["sapiens",["SapiensForSemanticSegmentation",Sk]]]),JS=new Map([["sam",["SamModel",Uk]]]),Gg=new Map([["wav2vec2",["Wav2Vec2ForCTC",Kk]],["wav2vec2-bert",["Wav2Vec2BertForCTC",uS]],["unispeech",["UniSpeechForCTC",nS]],["unispeech-sat",["UniSpeechSatForCTC",iS]],["wavlm",["WavLMForCTC",mS]],["hubert",["HubertForCTC",pS]]]),Wg=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Xk]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",dS]],["unispeech",["UniSpeechForSequenceClassification",rS]],["unispeech-sat",["UniSpeechSatForSequenceClassification",aS]],["wavlm",["WavLMForSequenceClassification",gS]],["hubert",["HubertForSequenceClassification",hS]],["audio-spectrogram-transformer",["ASTForAudioClassification",q2]]]),eE=new Map([["wavlm",["WavLMForXVector",_S]]]),Hg=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",oS]],["wavlm",["WavLMForAudioFrameClassification",wS]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Qk]],["pyannote",["PyAnnoteForAudioFrameClassification",Zk]]]),tE=new Map([["vitmatte",["VitMatteForImageMatting",W$]]]),Kg=new Map([["swin2sr",["Swin2SRForImageSuperResolution",bk]]]),Xg=new Map([["dpt",["DPTForDepthEstimation",xk]],["depth_anything",["DepthAnythingForDepthEstimation",kk]],["glpn",["GLPNForDepthEstimation",Ck]],["sapiens",["SapiensForDepthEstimation",Ek]]]),Qg=new Map([["clip",["CLIPVisionModelWithProjection",J2]],["siglip",["SiglipVisionModel",n$]]]),Yg=[[KS,de.EncoderOnly],[XS,de.EncoderDecoder],[QS,de.DecoderOnly],[Rg,de.EncoderOnly],[Dg,de.EncoderOnly],[lo,de.Seq2Seq],[oo,de.Seq2Seq],[uo,de.DecoderOnly],[Fg,de.EncoderOnly],[Ng,de.EncoderOnly],[co,de.Vision2Seq],[YS,de.ImageTextToText],[Lg,de.EncoderOnly],[jg,de.EncoderOnly],[qg,de.EncoderOnly],[tE,de.EncoderOnly],[Kg,de.EncoderOnly],[Xg,de.EncoderOnly],[Ug,de.EncoderOnly],[Vg,de.EncoderOnly],[JS,de.MaskGeneration],[Gg,de.EncoderOnly],[Wg,de.EncoderOnly],[Pg,de.Seq2Seq],[Bg,de.EncoderOnly],[eE,de.EncoderOnly],[Hg,de.EncoderOnly],[Qg,de.EncoderOnly]];for(const[t,e]of Yg)for(const[n,r]of t.values())Ns.set(n,e),zr.set(r,n),_m.set(n,r);const nE=[["MusicgenForConditionalGeneration",Mg,de.Musicgen],["CLIPTextModelWithProjection",Z2,de.EncoderOnly],["SiglipTextModel",t$,de.EncoderOnly],["ClapTextModelWithProjection",IS,de.EncoderOnly],["ClapAudioModelWithProjection",zS,de.EncoderOnly]];for(const[t,e,n]of nE)Ns.set(t,n),zr.set(e,t),_m.set(t,e);class On extends Ce{}A(On,"MODEL_CLASS_MAPPINGS",Yg.map(e=>e[0])),A(On,"BASE_IF_FAIL",!0);class po extends Ce{}A(po,"MODEL_CLASS_MAPPINGS",[Rg]);class Zg extends Ce{}A(Zg,"MODEL_CLASS_MAPPINGS",[Dg]);class Ks extends Ce{}A(Ks,"MODEL_CLASS_MAPPINGS",[lo]);class Jg extends Ce{}A(Jg,"MODEL_CLASS_MAPPINGS",[oo]);class e_ extends Ce{}A(e_,"MODEL_CLASS_MAPPINGS",[Pg]);class t_ extends Ce{}A(t_,"MODEL_CLASS_MAPPINGS",[Bg]);class n_ extends Ce{}A(n_,"MODEL_CLASS_MAPPINGS",[uo]);class r_ extends Ce{}A(r_,"MODEL_CLASS_MAPPINGS",[Fg]);class s_ extends Ce{}A(s_,"MODEL_CLASS_MAPPINGS",[Ng]);class i_ extends Ce{}A(i_,"MODEL_CLASS_MAPPINGS",[co]);class a_ extends Ce{}A(a_,"MODEL_CLASS_MAPPINGS",[Lg]);class o_ extends Ce{}A(o_,"MODEL_CLASS_MAPPINGS",[jg]);class l_ extends Ce{}A(l_,"MODEL_CLASS_MAPPINGS",[qg]);class u_ extends Ce{}A(u_,"MODEL_CLASS_MAPPINGS",[Ug]);class d_ extends Ce{}A(d_,"MODEL_CLASS_MAPPINGS",[Vg]);class c_ extends Ce{}A(c_,"MODEL_CLASS_MAPPINGS",[Gg]);class p_ extends Ce{}A(p_,"MODEL_CLASS_MAPPINGS",[Wg]);class h_ extends Ce{}A(h_,"MODEL_CLASS_MAPPINGS",[Hg]);class f_ extends Ce{}A(f_,"MODEL_CLASS_MAPPINGS",[ZS]);class m_ extends Ce{}A(m_,"MODEL_CLASS_MAPPINGS",[Kg]);class g_ extends Ce{}A(g_,"MODEL_CLASS_MAPPINGS",[Xg]);class __ extends Ce{}A(__,"MODEL_CLASS_MAPPINGS",[Qg]);class me extends mt{constructor({logits:e}){super(),this.logits=e}}class rE 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 sE extends mt{constructor({alphas:e}){super(),this.alphas=e}}class iE extends mt{constructor({waveform:e,spectrogram:n}){super(),this.waveform=e,this.spectrogram=n}}const xt=typeof self<"u",aE=xt&&self.constructor.name==="DedicatedWorkerGlobalScope";let Pn,w_,fn;if(xt)Pn=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},fn=self.createImageBitmap,w_=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}),a=new it(new Uint8ClampedArray(r),s.width,s.height,s.channels);return n!==void 0&&n!==s.channels&&a.convert(n),a};else throw new Error("Unable to load image processing library.");const oE={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},lE=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class it{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 it)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(!xt)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 it(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(xt){const n=await fn(e),r=Pn(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 it(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(i,l,u,e,n,c,p,e,n),new it(o.getImageData(0,0,e,n).data,e,n,4).convert(a)}else{let a=this.toSharp();if(r>=0&&s>=0)a=a.extract({left:Math.floor(r),top:Math.floor(s),width:e,height:n});else if(r<=0&&s<=0){const i=Math.floor(-s),o=Math.floor(-r);a=a.extend({top:i,left:o,right:e-this.width-o,bottom:n-this.height-i})}else{let i=[0,0],o=0;s<0?(i[0]=Math.floor(-s),i[1]=n-this.height-i[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),a=a.extend({top:i[0],bottom:i[1],left:l[0],right:l[1]}).extract({left:u,top:o,width:e,height:n})}return await fn(a)}}async toBlob(e="image/png",n=1){if(!xt)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 J("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(!xt)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),n=Pn(e.width,e.height),r=new w_(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 it(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(xt){if(aE)throw new Error("Unable to save an image from a Web Worker.");const n=e.split(".").pop().toLowerCase(),r=lE.get(n)??"image/png",s=await this.toBlob(r),a=URL.createObjectURL(s),i=document.createElement("a");i.href=a,i.download=e,i.click(),i.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(xt)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 uE(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 a;if(s.numberOfChannels===2){const i=Math.sqrt(2),o=s.getChannelData(0),l=s.getChannelData(1);a=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 ho(t,e="htk"){const n=cE[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 pE={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 hE(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))}function fE(t,e){const n=Float64Array.from({length:e.length-1},(i,o)=>e[o+1]-e[o]),r=Array.from({length:t.length},()=>new Array(e.length));for(let i=0;inew Array(t.length));for(let i=0;it+r*a)}function ir(t,e,n,r,s,a=null,i="htk",o=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');const l=ho(n,i),u=ho(r,i),c=v_(l,u,e+2);let p=hE(c,i),d;if(o){const m=s/(t*2);d=ho(Float64Array.from({length:t},(g,w)=>w*m),i),p=c}else d=v_(0,Math.floor(s/2),t);const f=fE(d,p);if(a!==null&&a==="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(a===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(i){if(o!=="reflect")throw new Error(`pad_mode="${o}" not implemented yet.`);const N=Math.floor((s-1)/2)+1;t=mE(t,N,N)}let T=Math.floor(1+Math.floor((t.length-n)/r));v!==null&&TT?$&&(L=y):L=R=y);const G=new xy(s),K=new Float64Array(s),X=new Float64Array(G.outputBufferSize),H=new Float32Array(M*L);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&&(i=i.subarray(0,t)),r===null)return i;if(t>r)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${r})`);return i}function wE([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,a=t.pred_boxes,[i,o,l]=s.dims;if(n!==null&&n.length!==i)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 $_(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 a=0;ap[y]&&(p[y]=v[y],d[y]=w)}const f=new Array(o.dims[0]),m=c.data;for(let w=0;ww!==void 0);s.push({segmentation:c,labels:g})}return s}function Bn(t,e){var n;if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${((n=t==null?void 0:t.constructor)==null?void 0:n.name)??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function k_(t,e,n=0,r=null){const s=t/e;let a=ky(s)*e;return r!==null&&a>r&&(a=Math.floor(s)*e),aa?u=Math.floor(a*l/s):a>s&&(l=Math.floor(s*u/a)),await e.resize(u,l,{resample:r}))}async crop_margin(e,n=200){const r=e.clone().grayscale(),s=Ko(r.data)[0],i=dt(r.data)[0]-s;if(i===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(a)));return{pixel_values:Er(r.map(a=>a.pixel_values),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}}class yE extends $e{post_process_semantic_segmentation(...e){return $_(...e)}}class bE extends $e{post_process_semantic_segmentation(...e){return $_(...e)}}class S_ extends $e{}class vE extends S_{}class xE extends $e{}class $E extends $e{}class E_ extends $e{}class kE extends E_{}class SE extends $e{}class EE extends $e{}class T_ extends $e{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),[a,i]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(a,i,{resample:this.resample}),e=await e.center_crop(n,n)}else e=await e.resize(n,n,{resample:this.resample});return e}}class TE extends T_{}class CE extends $e{}class ME extends $e{}class AE extends $e{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 IE extends $e{}class zE extends $e{}class OE extends $e{}class PE extends $e{}class C_ extends $e{}class BE extends C_{}class M_ extends $e{post_process_object_detection(...e){return Xs(...e)}}class RE extends M_{}class DE extends $e{post_process_object_detection(...e){return Xs(...e)}}class FE extends $e{}class NE extends $e{}class A_ extends $e{pad_image(e,n,r,s={}){const[a,i,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 LE extends A_{}class UE extends $e{async _call(e){const n=await super._call(e),r=[n.pixel_values.dims[0],64,64],s=new J("int64",new BigInt64Array(r.reduce((a,i)=>a*i)).fill(1n),r);return{...n,pixel_mask:s}}post_process_object_detection(...e){return Xs(...e)}remove_low_and_no_objects(e,n,r,s){let a=[],i=[],o=[];for(let l=0;lr&&(a.push(c),i.push(f),o.push(p))}return[a,i,o]}check_segment_validity(e,n,r,s=.5,a=.8){let i=[],o=0,l=0;const u=n[r].data;for(let p=0;p=s&&++l;let c=o>0&&l>0;return c&&(c=o/l>a),[c,i]}compute_segments(e,n,r,s,a,i=null,o=null){let[l,u]=o??e[0].dims,c=new J("int32",new Int32Array(l*u),[l,u]),p=[];if(o!==null)for(let w=0;wf[$]&&(d[$]=w,f[$]=y[$])}let m=0;const g=c.data;for(let w=0;ws!==n.dims[a]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new J("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:n=null,input_labels:r=null,input_boxes:s=null}={}){const a=await super._call(e);if(n&&(a.input_points=this.reshape_input_points(n,a.original_sizes,a.reshaped_input_sizes)),r){if(!a.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");a.input_labels=this.add_input_labels(r,a.input_points)}return s&&(a.input_boxes=this.reshape_input_points(s,a.original_sizes,a.reshaped_input_sizes,!0)),a}async post_process_masks(e,n,r,{mask_threshold:s=0,binarize:a=!0,pad_size:i=null}={}){const o=[];i=i??this.pad_size;const l=[i.height,i.width];for(let u=0;us&&(m[g]=1);d=new J("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:a=32,crop_n_points_downscale_factor:i=1}={}){}}class qE extends $e{pad_image(e,n,r,s={}){const[a,i,o]=n;return super.pad_image(e,n,{width:i+(r-i%r)%r,height:a+(r-a%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...s})}}class GE extends $e{async _call(e,n){Array.isArray(e)||(e=[e]),Array.isArray(n)||(n=[n]);const r=await Promise.all(e.map(i=>this.preprocess(i))),s=await Promise.all(n.map(i=>this.preprocess(i,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Er(r.map((i,o)=>ct([i.pixel_values,s[o].pixel_values],0)),0),original_sizes:r.map(i=>i.original_size),reshaped_input_sizes:r.map(i=>i.reshaped_input_size)}}}class WE extends Yt{constructor(e){var n;super(e),(n=this.config).mel_filters??(n.mel_filters=ir(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 a=0;athis.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 HE extends Yt{_zero_mean_unit_var_norm(e){const r=e.reduce((a,i)=>a+i,0)/e.length,s=e.reduce((a,i)=>a+(i-r)**2,0)/e.length;return e.map(a=>(a-r)/Math.sqrt(s+1e-7))}async _call(e){Bn(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 J("float32",n,r),attention_mask:new J("int64",new BigInt64Array(n.length).fill(1n),r)}}}class KE extends Yt{constructor(e){super(e);const n=this.config.sampling_rate,r=ir(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:a=!0}={}){Bn(e,"SeamlessM4TFeatureExtractor");let i=await this._extract_fbank_features(e,this.config.max_length);if(s){const[m,g]=i.dims,w=i.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;i=new J(i.type,y,[$,g]),a&&(o=new J("int64",new BigInt64Array($),[1,$]),o.data.fill(1n,0,m))}}const[l,u]=i.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=i.view(1,Math.floor(l/c),u*c),f={input_features:d};if(a){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()*(i+1));e=e.subarray(o,o+n),a=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(i<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 ZE extends Yt{constructor(e){super(e);const n=this.config.sampling_rate,r=ir(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){Bn(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,[a,i,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,a]of this.task_prompts_with_input)if(r.includes(s)){n.push(a.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 a;switch(s){case"pure_text":a=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const i=s==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[i]),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]));a={labels:l,[i]:u};break;default:throw new Error(`Task "${n}" (of type "${s}") not yet implemented.`)}return{[n]:a}}}class Qe{static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:a=!1,revision:i="main"}={}){let o=r??await nn(e,"preprocessor_config.json",!0,{progress_callback:n,config:r,cache_dir:s,local_files_only:a,revision:i}),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=$e;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:$e,WhisperFeatureExtractor:WE,ViTFeatureExtractor:CE,MobileViTFeatureExtractor:C_,MobileViTImageProcessor:BE,MobileNetV1FeatureExtractor:IE,MobileNetV2FeatureExtractor:zE,MobileNetV3FeatureExtractor:OE,MobileNetV4FeatureExtractor:PE,OwlViTFeatureExtractor:M_,Owlv2ImageProcessor:RE,CLIPFeatureExtractor:E_,CLIPImageProcessor:kE,Florence2Processor:I_,ChineseCLIPFeatureExtractor:SE,SiglipImageProcessor:EE,ConvNextFeatureExtractor:T_,ConvNextImageProcessor:TE,SegformerFeatureExtractor:bE,SapiensFeatureExtractor:yE,BitImageProcessor:xE,DPTImageProcessor:vE,DPTFeatureExtractor:S_,GLPNFeatureExtractor:$E,BeitFeatureExtractor:NE,DeiTFeatureExtractor:FE,DetrFeatureExtractor:UE,RTDetrImageProcessor:DE,YolosFeatureExtractor:VE,DonutFeatureExtractor:A_,NougatImageProcessor:LE,EfficientNetImageProcessor:AE,ViTImageProcessor:ME,VitMatteImageProcessor:GE,SamImageProcessor:jE,Swin2SRImageProcessor:qE,Wav2Vec2FeatureExtractor:HE,SeamlessM4TFeatureExtractor:KE,SpeechT5FeatureExtractor:JE,ASTFeatureExtractor:XE,ClapFeatureExtractor:QE,PyAnnoteFeatureExtractor:YE,WeSpeakerFeatureExtractor:ZE}),A(Qe,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:tT,Wav2Vec2ProcessorWithLM:nT,PyAnnoteProcessor:rT,SamProcessor:eT,SpeechT5Processor:sT,OwlViTProcessor:iT,Florence2Processor:I_});async function Zt(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>it.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?uE(n,e):n instanceof Float64Array?new Float32Array(n):n))}function z_(t,e){e&&(t=t.map(i=>i|0));const[n,r,s,a]=t;return{xmin:n,ymin:r,xmax:s,ymax:a}}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 aT 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),a=this.model.config.problem_type==="multi_label_classification"?l=>l.sigmoid():l=>new J("float32",He(l.data),l.dims),i=this.model.config.id2label,o=[];for(const l of s.logits){const u=a(l),c=await Zn(u,n),p=c[0].tolist(),f=c[1].tolist().map((m,g)=>({label:i?i[m]:`LABEL_${m}`,score:p[g]}));n===1?o.push(...f):o.push(f)}return Array.isArray(e)||n===1?o:o[0]}}class oT 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}),i=(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=a[p].tolist(),g=i[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=py(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 Zn(new J("float32",He(c.data),c.dims),n),d=p[0].tolist(),f=p[1].tolist();a.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)?a:a[0]}}class mo 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 a=this.tokenizer,i={padding:!0,truncation:!0};let o;this instanceof O_&&"_build_translation_inputs"in a?o=a._build_translation_inputs(n,i,r):o=a(n,i);const l=await this.model.generate({...o,...r});return a.batch_decode(l,{skip_special_tokens:!0}).map(u=>({[this._key]:u}))}}class dT extends mo{constructor(n){super(n);A(this,"_key","summary_text")}}class O_ extends mo{constructor(n){super(n);A(this,"_key","translation_text")}}function P_(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}class cT extends Re{constructor(e){super(e)}async _call(e,n={}){let r=!1,s=!1,a;if(typeof e=="string")a=e=[e];else if(Array.isArray(e)&&e.every(f=>typeof f=="string"))r=!0,a=e;else{if(P_(e))e=[e];else if(Array.isArray(e)&&e.every(P_))r=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");s=!0,a=e.map(f=>this.tokenizer.apply_chat_template(f,{tokenize:!1,add_generation_prompt:!0}))}const i=n.add_special_tokens??!1,o=s?!1:n.return_full_text??!0;this.tokenizer.padding_side="left";const l=this.tokenizer(a,{add_special_tokens:i,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 a=Array.isArray(e);a||(e=[e]),Array.isArray(n)||(n=[n]);const i=n.map(u=>r.replace("{}",u)),o=s||n.length===1,l=[];for(const u of e){const c=[];for(const f of i){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 a?l:l[0]}}class hT extends Re{constructor(e){super(e)}async _call(e,{pooling:n="none",normalize:r=!1,quantize:s=!1,precision:a="binary"}={}){const i=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(i);let l=o.last_hidden_state??o.logits??o.token_embeddings;if(n!=="none")if(n==="mean")l=ob(l,i.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=mb(l,a)),l}}class fT extends Re{constructor(e){super(e)}async _call(e,{pool:n=null}={}){const r=await Zt(e),{pixel_values:s}=await this.processor(r),a=await this.model({pixel_values:s});let i;if(n){if(!("pooler_output"in a))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");i=a.pooler_output}else i=a.last_hidden_state??a.logits??a.image_embeds;return i}}class mT 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),a=this.model.config.id2label,i=[];for(const o of s){const l=await this.processor(o),c=(await this.model(l)).logits[0],p=await Zn(new J("float32",He(c.data),c.dims),n),d=p[0].tolist(),m=p[1].tolist().map((g,w)=>({label:a?a[g]:`LABEL_${g}`,score:d[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}}class gT 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 a=n.map(c=>r.replace("{}",c)),i=this.tokenizer(a,{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({...i,...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 _T 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,a=await Qs(e,s),i=[];for(const o of a){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);i.push({text:d})}return r?i[0]:i}async _call_whisper(e,n){const r=n.return_timestamps??!1,s=n.chunk_length_s??0,a=n.force_full_sequences??!1;let i=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(i===null)i=s/6;else if(s<=i)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const y=p*s,$=p*i,k=y-2*$;let E=0;for(;;){const T=E+y,M=m.subarray(E,T),R=await this.processor(M),L=E===0,G=T>=m.length;if(g.push({stride:[M.length,L?0:$,G?0:$],input_features:R.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:a});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 Zt(e),{pixel_values:a}=await this.processor(s),i=[];for(const o of a){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()}));i.push(u)}return r?i:i[0]}}class yT extends Re{constructor(e){super(e)}async _call(e,{top_k:n=5}={}){const r=await Zt(e),{pixel_values:s}=await this.processor(r),a=await this.model({pixel_values:s}),i=this.model.config.id2label,o=[];for(const l of a.logits){const u=await Zn(new J("float32",He(l.data),l.dims),n),c=u[0].tolist(),d=u[1].tolist().map((f,m)=>({label:i?i[f]:`LABEL_${f}`,score:c[m]}));o.push(d)}return Array.isArray(e)?o:o[0]}}class bT 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:a=null,target_sizes:i=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 Zt(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,a,i??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(i,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(a),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 xT 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 a=await Zt(e),i=r?null:a.map(f=>[f.height,f.width]),{pixel_values:o,pixel_mask:l}=await this.processor(a),u=await this.model({pixel_values:o,pixel_mask:l}),c=this.processor.feature_extractor.post_process_object_detection(u,n,i),p=this.model.config.id2label,d=c.map(f=>f.boxes.map((m,g)=>({score:f.scores[g],label:p[f.classes[g]],box:z_(m,!r)})));return s?d:d[0]}}class $T extends Re{constructor(e){super(e)}async _call(e,n,{threshold:r=.1,top_k:s=null,percentage:a=!1}={}){const i=Array.isArray(e),o=await Zt(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:z_(y,!a)})).sort((y,$)=>$.score-y.score);s!==null&&(v=v.slice(0,s)),c.push(v)}return i?c:c[0]}}class kT 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 ST 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),a=this.model.config.sampling_rate;return{audio:s.data,sampling_rate:a}}async _call_text_to_spectrogram(n,{speaker_embeddings:r}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await On.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 J("float32",r,[1,r.length]);else if(!(r instanceof J))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:a}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),i=this.processor.feature_extractor.config.sampling_rate;return{audio:a.data,sampling_rate:i}}}class ET extends Re{constructor(e){super(e)}async _call(e){const n=await Zt(e),r=await this.processor(n),s=await this.model(r),a=[];for(const i of s.reconstruction){const o=i.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");a.push(it.fromTensor(o))}return a.length>1?a:a[0]}}class TT extends Re{constructor(e){super(e)}async _call(e){const n=await Zt(e),r=await this.processor(n),{predicted_depth:s}=await this.model(r),a=[];for(let i=0;i1?a:a[0]}}const B_=Object.freeze({"text-classification":{tokenizer:qe,pipeline:aT,model:po,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:qe,pipeline:oT,model:Zg,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:qe,pipeline:lT,model:s_,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:qe,pipeline:uT,model:r_,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:O_,model:Ks,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:qe,pipeline:mo,model:Ks,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:qe,pipeline:cT,model:n_,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:qe,pipeline:pT,model:po,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:mT,model:p_,processor:Qe,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:qe,pipeline:gT,model:On,processor:Qe,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:qe,pipeline:_T,model:[Jg,c_],processor:Qe,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:qe,pipeline:ST,model:[t_,e_],processor:[Qe,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:qe,pipeline:wT,model:i_,processor:Qe,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:yT,model:a_,processor:Qe,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:bT,model:[o_,l_],processor:Qe,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:qe,pipeline:vT,model:On,processor:Qe,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:xT,model:u_,processor:Qe,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:qe,pipeline:$T,model:d_,processor:Qe,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:qe,pipeline:kT,model:f_,processor:Qe,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ET,model:m_,processor:Qe,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:TT,model:g_,processor:Qe,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:qe,pipeline:hT,model:On,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:Qe,pipeline:fT,model:[__,On],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),CT=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function MT(t,e=null,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:a=!1,revision:i="main",device:o=null,dtype:l=null,model_file_name:u=null,session_options:c={}}={}){t=CT[t]??t;const p=B_[t.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(B_)}]`);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:a,revision:i,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 AT(f,e,d);m.task=t,Vn(n,{status:"ready",task:t,model:e});const g=p.pipeline;return new g(m)}async function AT(t,e,n){const r=Object.create(null),s=[];for(let[a,i]of t.entries()){if(!i)continue;let o;Array.isArray(i)?o=new Promise(async(l,u)=>{var p,d;let c;for(let f of i){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=i.from_pretrained(e,n),r[a]=o,s.push(o)}await Promise.all(s);for(let[a,i]of Object.entries(r))r[a]=await i;return r}bn.IS_PROCESS_AVAILABLE;const IT={webgpu:{dtype:{encoder_model:"fp32",decoder_model_merged:"q4"},device:"webgpu"},wasm:{dtype:"q8",device:"wasm"}};class Rn{static async getInstance(e=null,n="webgpu"){return this.asr_instance??(this.asr_instance=MT("automatic-speech-recognition",this.asr_model_id,{...IT[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=h_.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(Rn,"asr_model_id","onnx-community/whisper-tiny_timestamped"),A(Rn,"asr_instance",null),A(Rn,"segmentation_model_id","onnx-community/pyannote-segmentation-3.0"),A(Rn,"segmentation_instance",null),A(Rn,"segmentation_processor",null);async function zT({device:t}){self.postMessage({status:"loading",data:`Loading models (${t})...`});const[e,n,r]=await Rn.getInstance(s=>{self.postMessage(s)},t);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 OT(t,e,n){const r=await t(n),{logits:s}=await e(r),a=t.post_process_speaker_diarization(s,n.length)[0];for(const i of a)i.label=e.config.id2label[i.id];return a}async function PT({audio:t,language:e}){const[n,r,s]=await Rn.getInstance(),a=performance.now(),[i,o]=await Promise.all([n(t,{language:e,return_timestamps:"word",chunk_length_s:30}),OT(r,s,t)]);console.table(o,["start","end","id","label","confidence"]);const l=performance.now();self.postMessage({status:"complete",result:{transcript:i,segments:o},time:l-a})}self.addEventListener("message",async t=>{const{type:e,data:n}=t.data;switch(e){case"load":zT(n);break;case"run":PT(n);break}})})();