var eE=Object.defineProperty;var tE=(Ve,vr,wn)=>vr in Ve?eE(Ve,vr,{enumerable:!0,configurable:!0,writable:!0,value:wn}):Ve[vr]=wn;var B=(Ve,vr,wn)=>tE(Ve,typeof vr!="symbol"?vr+"":vr,wn);(function(){"use strict";var s0;var Ve={},vr=Object.freeze({__proto__:null,default:Ve});const wn="3.0.0-alpha.0",Ja=typeof self<"u",N0=Ja&&self.constructor.name==="DedicatedWorkerGlobalScope",Cl=Ja&&"caches"in self,F0=typeof navigator<"u"&&"gpu"in navigator,Tl=typeof process<"u",L0=Tl&&((s0=process==null?void 0:process.release)==null?void 0:s0.name)==="node",ei=!Ol(Ve),Al=!Ol(Ve),Hr=Object.freeze({IS_BROWSER_ENV:Ja,IS_WEBWORKER_ENV:N0,IS_WEB_CACHE_AVAILABLE:Cl,IS_WEBGPU_AVAILABLE:F0,IS_PROCESS_AVAILABLE:Tl,IS_NODE_ENV:L0,IS_FS_AVAILABLE:ei,IS_PATH_AVAILABLE:Al}),Ss=ei&&Al,Il=Ss?Ve.dirname(Ve.dirname(Ve.fileURLToPath(self.location.href))):"./",U0=Ss?Ve.join(Il,"/.cache/"):null,Ml="/models/",W0=Ss?Ve.join(Il,Ml):Ml,Mt={version:wn,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ja,localModelPath:W0,useFS:ei,useBrowserCache:Cl,useFSCache:ei,cacheDir:U0,useCustomCache:!1,customCache:null};function Ol(t){return Object.keys(t).length===0}const wt=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 bn(t,e){t&&t(e)}function V0(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e]))}function zl(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G0(t){return Number.isInteger(t)||typeof t=="bigint"}function Pl(t){const e=[];let r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function gt(...t){return Array.prototype.concat.apply([],t)}function H0(...t){return t.reduce((e,r)=>e.flatMap(n=>r.map(a=>[n,a])))}function ti(t,e){return Math.abs((t+e)%(2*e)-e)}function $r(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}var xr={};class ri{constructor(e){B(this,"_CONTENT_TYPE_MAP",{txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});if(this.filePath=e,this.headers=new Headers,this.exists=Ve.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Ve.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let n=this;this.body=new ReadableStream({start(a){n.arrayBuffer().then(s=>{a.enqueue(new Uint8Array(s)),a.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new ri(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 Ve.promises.readFile(this.filePath)).buffer}async blob(){const e=await Ve.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Ve.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function ks(t,e=null,r=null){let n;try{n=new URL(t)}catch{return!1}return!(e&&!e.includes(n.protocol)||r&&!r.includes(n.hostname))}async function ni(t){var e;if(Mt.useFS&&!ks(t,["http:","https:","blob:"]))return new ri(t);if(typeof process<"u"&&((e=process==null?void 0:process.release)==null?void 0:e.name)==="node"){const r=!!(xr!=null&&xr.TESTING_REMOTELY),n=Mt.version,a=new Headers;if(a.set("User-Agent",`transformers.js/${n}; is_ci/${r};`),ks(t,["http:","https:"],["huggingface.co","hf.co"])){const i=(xr==null?void 0:xr.HF_TOKEN)??(xr==null?void 0:xr.HF_ACCESS_TOKEN);i&&a.set("Authorization",`Bearer ${i}`)}return fetch(t,{headers:a})}else return fetch(t)}const j0={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 q0(t,e,r){if(!r)return null;const n=j0[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${n}: "${e}".`)}class Rl{constructor(e){this.path=e}async match(e){let r=Ve.join(this.path,e),n=new ri(r);if(n.exists)return n}async put(e,r){const n=Buffer.from(await r.arrayBuffer());let a=Ve.join(this.path,e);try{await Ve.promises.mkdir(Ve.dirname(a),{recursive:!0}),await Ve.promises.writeFile(a,n)}catch(s){console.warn("An error occurred while writing the file to cache:",s)}}}async function K0(t,...e){for(let r of e)try{let n=await t.match(r);if(n)return n}catch{continue}}async function ai(t,e,r=!0,n={}){if(!Mt.allowLocalModels&&n.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");bn(n.progress_callback,{status:"initiate",name:t,file:e});let a;if(!a&&Mt.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{a=await caches.open("transformers-cache")}catch(S){console.warn("An error occurred while opening the browser cache:",S)}}if(!a&&Mt.useFSCache&&(a=new Rl(n.cache_dir??Mt.cacheDir)),!a&&Mt.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const s=n.revision??"main";let i=ii(t,e),o=ii(Mt.localModelPath,i),l=ii(Mt.remoteHost,Mt.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(s)),e),u=s==="main"?i:ii(t,s,e),d,h=a instanceof Rl?u:l,m=!1,g;a&&(g=await K0(a,o,h));const p=g!==void 0;if(g===void 0){if(Mt.allowLocalModels)if(ks(i,["http:","https:"])){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`)}else try{g=await ni(o),d=o}catch($){console.warn(`Unable to load from local path "${o}": "${$}"`)}if(g===void 0||g.status===404){if(n.local_files_only||!Mt.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${o}".`);return null}if(g=await ni(l),g.status!==200)return q0(g.status,l,r);d=h}m=a&&typeof Response<"u"&&g instanceof Response&&g.status===200}bn(n.progress_callback,{status:"download",name:t,file:e});const w={status:"progress",name:t,file:e};let v;return n.progress_callback?p&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(v=new Uint8Array(await g.arrayBuffer()),bn(n.progress_callback,{...w,progress:100,loaded:v.length,total:v.length})):v=await Y0(g,S=>{bn(n.progress_callback,{...w,...S})}):v=new Uint8Array(await g.arrayBuffer()),m&&d&&await a.match(d)===void 0&&await a.put(d,new Response(v,{headers:g.headers})).catch(S=>{console.warn(`Unable to add response to browser cache: ${S}.`)}),bn(n.progress_callback,{status:"done",name:t,file:e}),v}async function Rr(t,e,r=!0,n={}){let a=await ai(t,e,r,n);if(a===null)return{};let i=new TextDecoder("utf-8").decode(a);return JSON.parse(i)}async function Y0(t,e){const r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let n=parseInt(r??"0"),a=new Uint8Array(n),s=0;const i=t.body.getReader();async function o(){const{done:l,value:u}=await i.read();if(l)return;let d=s+u.length;if(d>n){n=d;let m=new Uint8Array(n);m.set(a),a=m}a.set(u,s),s=d;const h=s/n*100;return e({progress:h,loaded:s,total:n}),o()}return await o(),a}function ii(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function X0(t,[e,r,n],[a,s],i="bilinear",o=!1){const l=s/n,u=a/r,d=new t.constructor(a*s*e),h=r*n,m=a*s;for(let g=0;g=0;--o)a[o]=l,n[o]=e[r[o]],l*=n[o];const s=r.map((o,l)=>a[r.indexOf(l)]),i=new t.constructor(t.length);for(let o=0;o=0;--u)l+=d%e[u]*s[u],d=Math.floor(d/e[u]);i[l]=t[o]}return[i,n]}function bt(t){const e=qt(t)[0],r=t.map(s=>Math.exp(s-e)),n=r.reduce((s,i)=>s+i,0);return r.map(s=>s/n)}function Z0(t){return bt(t).map(n=>Math.log(n))}function Bl(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let n=1;ne&&(e=t[n],r=n);return[Number(e),r]}function Dl(t){return t>0&&(t&t-1)===0}class Nl{constructor(e){if(this.size=e|0,this.size<=1||!Dl(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let n=0;nn;n<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>a&3)<>>1);for(let a=0;a>>1]=e[a];return n}toComplexArray(e,r){const n=r||this.createComplexArray();for(let a=0;a>>1],n[a+1]=0;return n}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let n=0;n>=2;i>=2;i>>=2){o=a/i<<1;const m=o>>>2;for(l=0;l>>1,i>>>1)}else for(l=0,u=0;l>>1,i>>>1,n)}const h=this.table;for(i>>=2;i>=2;i>>=2){o=a/i<<1;const g=o>>>1,p=g>>>1,w=p>>>1;for(l=0;l>>1;for(let g=2;g>1;++d){const h=(d+1-e)**2/2,m=Math.sqrt(l**2+u**2)**h,g=h*Math.atan2(u,l),p=2*d;s[p]=m*Math.cos(g),s[p+1]=m*Math.sin(g),i[p]=s[p],i[p+1]=-s[p+1]}this._slicedChirpBuffer=s.subarray(r,n),this._f=new Nl(a>>1),this._f.transform(this._chirpBuffer,i)}_transform(e,r,n){const a=this._buffer1,s=this._buffer2,i=this._outBuffer1,o=this._outBuffer2,l=this._chirpBuffer,u=this._slicedChirpBuffer,d=this._a;if(n)for(let h=0;h>1,p=r[g];a[h]=p*u[h],a[m]=p*u[m]}else for(let h=0;h=t.length&&(l=2*(t.length-1)-l),n[i++]=t[l]}n.sort(),r[s]=n[a]}return r}function Xn(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}function ry(t){const e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function ny(t){const e=t.length,r=t[0].length,n=[e+1,r+1],a=Array.from({length:n[0]},()=>Array(n[1]).fill(1/0));a[0][0]=0;const s=Array.from({length:n[0]},()=>Array(n[1]).fill(-1));for(let d=1;d0||o>0;)switch(l.push(i-1),u.push(o-1),s[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.18.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var Es=Object.defineProperty,ay=Object.getOwnPropertyDescriptor,iy=Object.getOwnPropertyNames,sy=Object.prototype.hasOwnProperty,te=(t,e)=>()=>(t&&(e=t(t=0)),e),vn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$n=(t,e)=>{for(var r in e)Es(t,r,{get:e[r],enumerable:!0})},oy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of iy(e))!sy.call(t,a)&&a!==r&&Es(t,a,{get:()=>e[a],enumerable:!(n=ay(e,a))||n.enumerable});return t},jr=t=>oy(Es({},"__esModule",{value:!0}),t),Qn,Br,qr,Fl,Cs,Ts=te(()=>{Qn=new Map,Br=[],qr=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let n=Qn.get(t);if(n===void 0)Qn.set(t,{backend:e,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let a=Br.indexOf(t);a!==-1&&Br.splice(a,1);for(let s=0;s{let e=Qn.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(n){return r||(e.error=`${n}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Cs=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),n=r.length===0?Br:r,a,s=[],i=new Set;for(let l of n){let u=await Fl(l);typeof u=="string"?s.push({name:l,err:u}):(a||(a=u),a===u&&i.add(l))}if(!a)throw new Error(`no available backend found. ERR: ${s.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of s)r.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[a,new Proxy(t,{get:(l,u)=>u==="executionProviders"?o:Reflect.get(l,u)})]}}),ly=te(()=>{Ts()}),Ll,uy=te(()=>{Ll="1.18.0"}),As,Kt,Ul=te(()=>{uy(),As="warning",Kt={wasm:{},webgl:{},webgpu:{},versions:{common:Ll},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}`);As=t}},get logLevel(){return As}},Object.defineProperty(Kt,"logLevel",{enumerable:!0})}),Ue,dy=te(()=>{Ul(),Ue=Kt}),Wl,Vl,cy=te(()=>{Wl=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let n=r.getContext("2d");if(n!=null){let a,s;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],s=t.dims[3]):(a=t.dims[3],s=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 d=s*a,h=0,m=d,g=d*2,p=-1;i==="RGBA"?(h=0,m=d,g=d*2,p=d*3):i==="RGB"?(h=0,m=d,g=d*2):i==="RBG"&&(h=0,g=d,m=d*2);for(let w=0;w{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let a,s,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],s=t.dims[1],i=t.dims[3]):(a=t.dims[3],s=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,d;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?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=s*a;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 m=4,g=0,p=1,w=2,v=3,S=0,$=h,E=h*2,T=-1;o==="RGBA"?(S=0,$=h,E=h*2,T=h*3):o==="RGB"?(S=0,$=h,E=h*2):o==="RBG"&&(S=0,E=h,$=h*2),n=r.createImageData(a,s);for(let A=0;A{Ms(),si=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=e,a=e.norm??{mean:255,bias:0},s,i;typeof a.mean=="number"?s=[a.mean,a.mean,a.mean,a.mean]:s=[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],typeof a.bias=="number"?i=[a.bias,a.bias,a.bias,a.bias]:i=[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];let o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=r*n,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),h=4,m=0,g=1,p=2,w=3,v=0,S=u,$=u*2,E=-1;o==="RGB"&&(h=3,m=0,g=1,p=2,w=-1),l==="RGBA"?E=u*3:l==="RBG"?(v=0,$=u,S=u*2):l==="BGR"&&($=0,S=u,v=u*2);for(let T=0;T{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,n=typeof ImageData<"u"&&t instanceof ImageData,a=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,s=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=d=>d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=t.width,d.height=t.height;let h=u(d);if(h!=null){let m=t.height,g=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,g=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=m,o.width=g}else o.tensorFormat="RGBA",o.height=m,o.width=g;h.drawImage(t,0,0),i=h.getImageData(0,0,g,m).data}else throw new Error("Can not access image data")}else if(n){let d,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,h=e.resizedWidth):(d=t.height,h=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=d,o.width=h,e!==void 0){let m=l();m.width=h,m.height=d;let g=u(m);if(g!=null)g.putImageData(t,0,0),i=g.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else i=t.data}else if(a){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=t.width,d.height=t.height;let h=u(d);if(h!=null){let m=t.height,g=t.width;return h.drawImage(t,0,0,g,m),i=h.getImageData(0,0,g,m).data,o.height=m,o.width=g,si(i,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((d,h)=>{let m=l(),g=u(m);if(!t||!g)return h();let p=new Image;p.crossOrigin="Anonymous",p.src=t,p.onload=()=>{m.width=p.width,m.height=p.height,g.drawImage(p,0,0,m.width,m.height);let w=g.getImageData(0,0,m.width,m.height);o.height=m.height,o.width=m.width,d(si(w.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return si(i,o);throw new Error("Input data provided is not supported - aborted tensor creation")},Hl=(t,e)=>{let{width:r,height:n,download:a,dispose:s}=e,i=[1,n,r,4];return new er({location:"texture",type:"float32",texture:t,dims:i,download:a,dispose:s})},jl=(t,e)=>{let{dataType:r,dims:n,download:a,dispose:s}=e;return new er({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:s})},ql=(t,e,r)=>new er({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Kr,Zn,Is,Kl,hy=te(()=>{Kr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Zn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Is=!1,Kl=()=>{if(!Is){Is=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;t&&(Kr.set("int64",BigInt64Array),Zn.set(BigInt64Array,"int64")),e&&(Kr.set("uint64",BigUint64Array),Zn.set(BigUint64Array,"uint64")),r?(Kr.set("float16",Float16Array),Zn.set(Float16Array,"float16")):Kr.set("float16",Uint16Array)}}}),Yl,Xl,fy=te(()=>{Ms(),Yl=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new er(t.type,t.data,e);case"cpu-pinned":return new er({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new er({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new er({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),er,Ms=te(()=>{cy(),py(),hy(),fy(),er=class{constructor(t,e,r){Kl();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case"cpu-pinned":{let i=Kr.get(n);if(!i)throw new TypeError(`unsupported type "${n}" 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(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,o;if(typeof t=="string")if(n=t,o=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");i=e}else{let l=Kr.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");t==="uint64"||t==="int64"?i=l.from(e,BigInt):i=l.from(e)}else if(e instanceof l)i=e;else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(o=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")n="string",i=t;else if(l==="boolean")n="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else{let l=Zn.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=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");a=o,this.cpuData=i,this.dataLocation="cpu"}let s=Yl(a);if(this.cpuData&&s!==this.cpuData.length)throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=s}static async fromImage(t,e){return Gl(t,e)}static fromTexture(t,e){return Hl(t,e)}static fromGpuBuffer(t,e){return jl(t,e)}static fromPinnedBuffer(t,e,r){return ql(t,e,r)}toDataURL(t){return Wl(this,t)}toImageData(t){return Vl(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 Xl(this,t)}}}),kt,Os=te(()=>{Ms(),kt=er}),Jn,zs,tr,Yt,Ql=te(()=>{Ul(),Jn=(t,e)=>{(typeof Kt.trace>"u"?!Kt.wasm.trace:!Kt.trace)||console.timeStamp(`${t}::ORT::${e}`)},zs=(t,e)=>{var a;let r=((a=new Error().stack)==null?void 0:a.split(/\r\n|\r|\n/g))||[],n=!1;for(let s=0;s{(typeof Kt.trace>"u"?!Kt.wasm.trace:!Kt.trace)||zs("BEGIN",t)},Yt=t=>{(typeof Kt.trace>"u"?!Kt.wasm.trace:!Kt.trace)||zs("END",t)}}),Zl,my=te(()=>{Ts(),Os(),Ql(),Zl=class R0{constructor(e){this.handler=e}async run(e,r,n){tr();let a={},s={};if(typeof e!="object"||e===null||e instanceof kt||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 r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof kt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let u of r){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}.`);a[u]=null}if(typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,d=Object.getOwnPropertyNames(r);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let m=r[h];(m===null||m instanceof kt)&&(u=!0,i=!1,a[h]=m)}if(u){if(typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"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)a[u]=null;let o=await this.handler.run(e,a,s),l={};for(let u in o)if(Object.hasOwnProperty.call(o,u)){let d=o[u];d instanceof kt?l[u]=d:l[u]=new kt(d.type,d.data,d.dims)}return Yt(),l}async release(){return this.handler.dispose()}static async create(e,r,n,a){tr();let s,i={};if(typeof e=="string"){if(s=e,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let d=e,h=0,m=e.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(h=r,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(m=e.byteLength-h,typeof n=="number"){if(m=n,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||h+m>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);if(typeof a=="object"&&a!==null)i=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(d,h,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await Cs(i),u=await o.createInferenceSessionHandler(s,l);return Yt(),new R0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Ps,gy=te(()=>{my(),Ps=Zl}),_y=te(()=>{}),yy=te(()=>{}),wy=te(()=>{}),by=te(()=>{}),Jl,eu,vy=te(()=>{Ts(),Os(),Jl="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",eu=class B0{constructor(e,r,n){this.handler=e,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,r){let n=e.evalModel||"",a=e.optimizerModel||"",s=r||{},[i,o]=await Cs(s);if(i.createTrainingSessionHandler){let l=await i.createTrainingSessionHandler(e.checkpointState,e.trainModel,n,a,o);return new B0(l,!!e.optimizerModel,!!e.evalModel)}else throw new Error(Jl)}typeNarrowingForRunStep(e,r,n,a,s){let i={},o={};if(typeof n!="object"||n===null||n instanceof kt||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof a=="object"){if(a===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(a instanceof kt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(a)){if(a.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(let u of a){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);i[u]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,d=Object.getOwnPropertyNames(a);for(let h of r)if(d.indexOf(h)!==-1){let m=a[h];(m===null||m instanceof kt)&&(u=!0,l=!1,i[h]=m)}if(u){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=a}}else if(typeof a<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of e)if(typeof n[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(l)for(let u of r)i[u]=null;return[i,o]}convertHandlerReturnTypeToMapOfTensors(e){let r={};for(let n in e)if(Object.hasOwnProperty.call(e,n)){let a=e[n];a instanceof kt?r[n]=a:r[n]=new kt(a.type,a.data,a.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,r,n){let[a,s]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,r,n),i=await this.handler.runTrainStep(e,a,s);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,r,n){if(this.hasEvalModel){let[a,s]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,r,n),i=await this.handler.runEvalStep(e,a,s);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,r=!0){let n=await this.getParametersSize(r);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,r)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}}),Rs,$y=te(()=>{vy(),Rs=eu}),tu={};$n(tu,{InferenceSession:()=>Ps,TRACE:()=>Jn,TRACE_FUNC_BEGIN:()=>tr,TRACE_FUNC_END:()=>Yt,Tensor:()=>kt,TrainingSession:()=>Rs,env:()=>Ue,registerBackend:()=>qr});var rr=te(()=>{ly(),dy(),gy(),Os(),_y(),yy(),Ql(),wy(),by(),$y()}),Bs={};$n(Bs,{createReadStream:()=>au,readFile:()=>ru,readFileSync:()=>nu});var ru,nu,au,iu=te(()=>{ru=void 0,nu=void 0,au=void 0}),Ds={};$n(Ds,{join:()=>su});var su,ou=te(()=>{su=void 0}),xy=vn((t,e)=>{var r=(()=>{var a;var n=typeof document<"u"?(a=document.currentScript)==null?void 0:a.src:void 0;return typeof __filename<"u"&&(n||(n=__filename)),function(s={}){var i=s,o,l,u=new Promise((f,y)=>{o=f,l=y});i.mountExternalData=(f,y)=>{(i.eb||(i.eb=new Map)).set(f,y)},i.unmountExternalData=()=>{delete i.eb};let d=()=>{let f=(x,C,O)=>(...F)=>{let Y=Nt,re=C==null?void 0:C();F=x(...F);let ue=C==null?void 0:C();return re!==ue&&(x=ue,O(re),C=O=null),Nt!=Y?us():F},y=x=>async(...C)=>{var O;try{if(i.cb)throw Error("Session already started");let F=i.cb={xb:C[0],errors:[]},Y=await x(...C);if(i.cb!==F)throw Error("Session mismatch");(O=i.kb)==null||O.flush();let re=F.errors;if(0ie),0i._OrtCreateSession,x=>i._OrtCreateSession=x),i._OrtRun=y(f(i._OrtRun,()=>i._OrtRun,x=>i._OrtRun=x)),i._OrtRunWithBinding=y(f(i._OrtRunWithBinding,()=>i._OrtRunWithBinding,x=>i._OrtRunWithBinding=x)),i._OrtBindInput=f(i._OrtBindInput,()=>i._OrtBindInput,x=>i._OrtBindInput=x),d=void 0};i.jsepInit=(f,y)=>{if(d==null||d(),f==="webgpu"){[i.kb,i.pb,i.tb,i.lb,i.sb,i.Ra,i.ub,i.wb,i.qb,i.rb,i.vb]=y;let x=i.kb;i.jsepRegisterBuffer=(C,O,F,Y)=>x.registerBuffer(C,O,F,Y),i.jsepGetBuffer=C=>x.getBuffer(C),i.jsepCreateDownloader=(C,O,F)=>x.createDownloader(C,O,F),i.jsepOnReleaseSession=C=>{x.onReleaseSession(C)},i.jsepOnRunStart=C=>x.onRunStart(C)}};var h=Object.assign({},i),m="./this.program",g=(f,y)=>{throw y},p=typeof window=="object",w=typeof importScripts=="function",v=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",S="",$,E,T;if(v){var A=(iu(),jr(Bs)),z=(ou(),jr(Ds));S=w?z.dirname(S)+"/":__dirname+"/",$=(f,y)=>(f=ut(f)?new URL(f):z.normalize(f),A.readFileSync(f,y?void 0:"utf8")),T=f=>(f=$(f,!0),f.buffer||(f=new Uint8Array(f)),f),E=(f,y,x,C=!0)=>{f=ut(f)?new URL(f):z.normalize(f),A.readFile(f,C?void 0:"utf8",(O,F)=>{O?x(O):y(C?F.buffer:F)})},!i.thisProgram&&1{throw process.exitCode=f,y}}else(p||w)&&(w?S=self.location.href:typeof document<"u"&&document.currentScript&&(S=document.currentScript.src),n&&(S=n),S.startsWith("blob:")?S="":S=S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1),$=f=>{var y=new XMLHttpRequest;return y.open("GET",f,!1),y.send(null),y.responseText},w&&(T=f=>{var y=new XMLHttpRequest;return y.open("GET",f,!1),y.responseType="arraybuffer",y.send(null),new Uint8Array(y.response)}),E=(f,y,x)=>{var C=new XMLHttpRequest;C.open("GET",f,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?y(C.response):x()},C.onerror=x,C.send(null)});var R=console.log.bind(console),V=console.error.bind(console);Object.assign(i,h),h=null;var j,q=!1,fe,ee,ne,se,D,M,G,K,pe,le,N;function ae(){var f=j.buffer;i.HEAP8=ee=new Int8Array(f),i.HEAP16=se=new Int16Array(f),i.HEAPU8=ne=new Uint8Array(f),i.HEAPU16=D=new Uint16Array(f),i.HEAP32=M=new Int32Array(f),i.HEAPU32=G=new Uint32Array(f),i.HEAPF32=K=new Float32Array(f),i.HEAPF64=N=new Float64Array(f),i.HEAP64=pe=new BigInt64Array(f),i.HEAPU64=le=new BigUint64Array(f)}var de=[],Se=[],Te=[],Xe=0,ot=null;function je(f){throw f="Aborted("+f+")",V(f),q=!0,fe=1,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),l(f),f}var ht=f=>f.startsWith("data:application/octet-stream;base64,"),ut=f=>f.startsWith("file://"),yt;if(yt="ort-wasm-simd.wasm",!ht(yt)){var We=yt;yt=i.locateFile?i.locateFile(We,S):S+We}function Ze(f){if(T)return T(f);throw"both async and sync fetching of the wasm failed"}function Rt(f){if(p||w){if(typeof fetch=="function"&&!ut(f))return fetch(f,{credentials:"same-origin"}).then(y=>{if(!y.ok)throw`failed to load wasm binary file at '${f}'`;return y.arrayBuffer()}).catch(()=>Ze(f));if(E)return new Promise((y,x)=>{E(f,C=>y(new Uint8Array(C)),x)})}return Promise.resolve().then(()=>Ze(f))}function dt(f,y,x){return Rt(f).then(C=>WebAssembly.instantiate(C,y)).then(x,C=>{V(`failed to asynchronously prepare wasm: ${C}`),je(C)})}function Ar(f,y){var x=yt;return typeof WebAssembly.instantiateStreaming!="function"||ht(x)||ut(x)||v||typeof fetch!="function"?dt(x,f,y):fetch(x,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,f).then(y,function(O){return V(`wasm streaming compile failed: ${O}`),V("falling back to ArrayBuffer instantiation"),dt(x,f,y)}))}var Ir={824920:(f,y,x,C)=>{if(typeof i>"u"||!i.eb)return 1;if(f=Je(f>>>0),f.startsWith("./")&&(f=f.substring(2)),f=i.eb.get(f),!f)return 2;if(y>>>=0,x>>>=0,y+x>f.byteLength)return 3;try{return ne.set(f.subarray(y,y+x),C>>>0>>>0),0}catch{return 4}},825421:()=>{i.qb()},825452:()=>{i.rb()},825481:()=>{i.vb()},825506:f=>i.pb(f),825539:f=>i.tb(f),825571:(f,y,x)=>{i.lb(f,y,x,!0)},825610:(f,y,x)=>{i.lb(f,y,x)},825643:f=>{i.Ra("Abs",f,void 0)},825694:f=>{i.Ra("Neg",f,void 0)},825745:f=>{i.Ra("Floor",f,void 0)},825798:f=>{i.Ra("Ceil",f,void 0)},825850:f=>{i.Ra("Reciprocal",f,void 0)},825908:f=>{i.Ra("Sqrt",f,void 0)},825960:f=>{i.Ra("Exp",f,void 0)},826011:f=>{i.Ra("Erf",f,void 0)},826062:f=>{i.Ra("Sigmoid",f,void 0)},826117:(f,y,x)=>{i.Ra("HardSigmoid",f,{alpha:y,beta:x})},826196:f=>{i.Ra("Log",f,void 0)},826247:f=>{i.Ra("Sin",f,void 0)},826298:f=>{i.Ra("Cos",f,void 0)},826349:f=>{i.Ra("Tan",f,void 0)},826400:f=>{i.Ra("Asin",f,void 0)},826452:f=>{i.Ra("Acos",f,void 0)},826504:f=>{i.Ra("Atan",f,void 0)},826556:f=>{i.Ra("Sinh",f,void 0)},826608:f=>{i.Ra("Cosh",f,void 0)},826660:f=>{i.Ra("Asinh",f,void 0)},826713:f=>{i.Ra("Acosh",f,void 0)},826766:f=>{i.Ra("Atanh",f,void 0)},826819:f=>{i.Ra("Tanh",f,void 0)},826871:f=>{i.Ra("Not",f,void 0)},826922:(f,y,x)=>{i.Ra("Clip",f,{min:y,max:x})},826991:f=>{i.Ra("Clip",f,void 0)},827043:(f,y)=>{i.Ra("Elu",f,{alpha:y})},827101:f=>{i.Ra("Relu",f,void 0)},827153:(f,y)=>{i.Ra("LeakyRelu",f,{alpha:y})},827217:(f,y)=>{i.Ra("ThresholdedRelu",f,{alpha:y})},827287:(f,y)=>{i.Ra("Cast",f,{to:y})},827345:f=>{i.Ra("Add",f,void 0)},827396:f=>{i.Ra("Sub",f,void 0)},827447:f=>{i.Ra("Mul",f,void 0)},827498:f=>{i.Ra("Div",f,void 0)},827549:f=>{i.Ra("Pow",f,void 0)},827600:f=>{i.Ra("Equal",f,void 0)},827653:f=>{i.Ra("Greater",f,void 0)},827708:f=>{i.Ra("GreaterOrEqual",f,void 0)},827770:f=>{i.Ra("Less",f,void 0)},827822:f=>{i.Ra("LessOrEqual",f,void 0)},827881:(f,y,x,C,O)=>{i.Ra("ReduceMean",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},828040:(f,y,x,C,O)=>{i.Ra("ReduceMax",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},828198:(f,y,x,C,O)=>{i.Ra("ReduceMin",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},828356:(f,y,x,C,O)=>{i.Ra("ReduceProd",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},828515:(f,y,x,C,O)=>{i.Ra("ReduceSum",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},828673:(f,y,x,C,O)=>{i.Ra("ReduceL1",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},828830:(f,y,x,C,O)=>{i.Ra("ReduceL2",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},828987:(f,y,x,C,O)=>{i.Ra("ReduceLogSum",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},829148:(f,y,x,C,O)=>{i.Ra("ReduceSumSquare",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},829312:(f,y,x,C,O)=>{i.Ra("ReduceLogSumExp",f,{keepDims:!!y,noopWithEmptyAxes:!!x,axes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},829476:f=>{i.Ra("Where",f,void 0)},829529:(f,y,x)=>{i.Ra("Transpose",f,{perm:y?Array.from(M.subarray(y>>>0,x>>>0)):[]})},829637:(f,y,x,C)=>{i.Ra("DepthToSpace",f,{blocksize:y,mode:Je(x),format:C?"NHWC":"NCHW"})},829770:(f,y,x,C)=>{i.Ra("DepthToSpace",f,{blocksize:y,mode:Je(x),format:C?"NHWC":"NCHW"})},829903:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L,Ee)=>{i.Ra("ConvTranspose",f,{format:ue?"NHWC":"NCHW",autoPad:y,dilations:[x],group:C,kernelShape:[O],pads:[F,Y],strides:[re],wIsConst:()=>!!ee[ie>>>0],outputPadding:ge?Array.from(M.subarray(ge>>>0,Be>>>0)):[],outputShape:Fe?Array.from(M.subarray(Fe>>>0,L>>>0)):[],activation:Je(Ee)})},830304:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L)=>{i.Ra("ConvTranspose",f,{format:re?"NHWC":"NCHW",autoPad:y,dilations:Array.from(M.subarray(x>>>0,(x>>>0)+2>>>0)),group:C,kernelShape:Array.from(M.subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(M.subarray(F>>>0,(F>>>0)+4>>>0)),strides:Array.from(M.subarray(Y>>>0,(Y>>>0)+2>>>0)),wIsConst:()=>!!ee[ue>>>0],outputPadding:ie?Array.from(M.subarray(ie>>>0,ge>>>0)):[],outputShape:Be?Array.from(M.subarray(Be>>>0,Fe>>>0)):[],activation:Je(L)})},830869:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L,Ee)=>{i.Ra("ConvTranspose",f,{format:ue?"NHWC":"NCHW",autoPad:y,dilations:[x],group:C,kernelShape:[O],pads:[F,Y],strides:[re],wIsConst:()=>!!ee[ie>>>0],outputPadding:ge?Array.from(M.subarray(ge>>>0,Be>>>0)):[],outputShape:Fe?Array.from(M.subarray(Fe>>>0,L>>>0)):[],activation:Je(Ee)})},831270:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L)=>{i.Ra("ConvTranspose",f,{format:re?"NHWC":"NCHW",autoPad:y,dilations:Array.from(M.subarray(x>>>0,(x>>>0)+2>>>0)),group:C,kernelShape:Array.from(M.subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(M.subarray(F>>>0,(F>>>0)+4>>>0)),strides:Array.from(M.subarray(Y>>>0,(Y>>>0)+2>>>0)),wIsConst:()=>!!ee[ue>>>0],outputPadding:ie?Array.from(M.subarray(ie>>>0,ge>>>0)):[],outputShape:Be?Array.from(M.subarray(Be>>>0,Fe>>>0)):[],activation:Je(L)})},831835:(f,y)=>{i.Ra("GlobalAveragePool",f,{format:y?"NHWC":"NCHW"})},831926:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L,Ee,Pe)=>{i.Ra("AveragePool",f,{format:Pe?"NHWC":"NCHW",auto_pad:y,ceil_mode:x,count_include_pad:C,storage_order:O,dilations:[F,Y],kernel_shape:[re,ue],pads:[ie,ge,Be,Fe],strides:[L,Ee]})},832210:(f,y)=>{i.Ra("GlobalAveragePool",f,{format:y?"NHWC":"NCHW"})},832301:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L,Ee,Pe)=>{i.Ra("AveragePool",f,{format:Pe?"NHWC":"NCHW",auto_pad:y,ceil_mode:x,count_include_pad:C,storage_order:O,dilations:[F,Y],kernel_shape:[re,ue],pads:[ie,ge,Be,Fe],strides:[L,Ee]})},832585:(f,y)=>{i.Ra("GlobalMaxPool",f,{format:y?"NHWC":"NCHW"})},832672:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L,Ee,Pe)=>{i.Ra("MaxPool",f,{format:Pe?"NHWC":"NCHW",auto_pad:y,ceil_mode:x,count_include_pad:C,storage_order:O,dilations:[F,Y],kernel_shape:[re,ue],pads:[ie,ge,Be,Fe],strides:[L,Ee]})},832952:(f,y)=>{i.Ra("GlobalMaxPool",f,{format:y?"NHWC":"NCHW"})},833039:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L,Ee,Pe)=>{i.Ra("MaxPool",f,{format:Pe?"NHWC":"NCHW",auto_pad:y,ceil_mode:x,count_include_pad:C,storage_order:O,dilations:[F,Y],kernel_shape:[re,ue],pads:[ie,ge,Be,Fe],strides:[L,Ee]})},833319:(f,y,x,C,O)=>{i.Ra("Gemm",f,{alpha:y,beta:x,transA:C,transB:O})},833423:f=>{i.Ra("MatMul",f,void 0)},833477:(f,y,x,C)=>{i.Ra("ArgMax",f,{keepDims:!!y,selectLastIndex:!!x,axis:C})},833585:(f,y,x,C)=>{i.Ra("ArgMin",f,{keepDims:!!y,selectLastIndex:!!x,axis:C})},833693:(f,y)=>{i.Ra("Softmax",f,{axis:y})},833756:(f,y)=>{i.Ra("Concat",f,{axis:y})},833816:(f,y,x,C,O)=>{i.Ra("Split",f,{axis:y,numOutputs:x,splitSizes:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},833956:f=>{i.Ra("Expand",f,void 0)},834010:(f,y)=>{i.Ra("Gather",f,{axis:Number(y)})},834081:(f,y)=>{i.Ra("GatherElements",f,{axis:Number(y)})},834160:(f,y,x,C,O,F,Y,re,ue,ie,ge)=>{i.Ra("Resize",f,{antialias:y,axes:x?Array.from(M.subarray(x>>>0,C>>>0)):[],coordinateTransformMode:Je(O),cubicCoeffA:F,excludeOutside:Y,extrapolationValue:re,keepAspectRatioPolicy:Je(ue),mode:Je(ie),nearestMode:Je(ge)})},834506:(f,y,x,C,O,F,Y)=>{i.Ra("Slice",f,{starts:y?Array.from(M.subarray(y>>>0,x>>>0)):[],ends:C?Array.from(M.subarray(C>>>0,O>>>0)):[],axes:F?Array.from(M.subarray(F>>>0,Y>>>0)):[]})},834722:f=>{i.Ra("Tile",f,void 0)},834774:(f,y,x,C)=>{i.Ra("LayerNormalization",f,{axis:y,epsilon:x,simplified:!!C})},834885:(f,y,x)=>{i.Ra("InstanceNormalization",f,{epsilon:y,format:x?"NHWC":"NCHW"})},834999:(f,y,x)=>{i.Ra("InstanceNormalization",f,{epsilon:y,format:x?"NHWC":"NCHW"})},835113:f=>{i.Ra("Range",f,void 0)},835166:(f,y)=>{i.Ra("Einsum",f,{equation:Je(y)})},835247:(f,y,x,C,O)=>{i.Ra("Pad",f,{mode:y,value:x,pads:C?Array.from(M.subarray(C>>>0,O>>>0)):[]})},835374:(f,y,x,C,O,F)=>{i.Ra("BatchNormalization",f,{epsilon:y,momentum:x,spatial:!!O,trainingMode:!!C,format:F?"NHWC":"NCHW"})},835543:(f,y,x,C,O,F)=>{i.Ra("BatchNormalization",f,{epsilon:y,momentum:x,spatial:!!O,trainingMode:!!C,format:F?"NHWC":"NCHW"})},835712:(f,y,x)=>{i.Ra("CumSum",f,{exclusive:Number(y),reverse:Number(x)})},835809:(f,y,x,C,O,F,Y,re,ue)=>{i.Ra("Attention",f,{numHeads:y,isUnidirectional:x,maskFilterValue:C,scale:O,doRotary:F,qkvHiddenSizes:Y?Array.from(M.subarray(Number(re)>>>0,Number(re)+Y>>>0)):[],pastPresentShareBuffer:!!ue})},836081:f=>{i.Ra("BiasAdd",f,void 0)},836136:f=>{i.Ra("BiasSplitGelu",f,void 0)},836197:f=>{i.Ra("FastGelu",f,void 0)},836253:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe)=>{i.Ra("Conv",f,{format:ue?"NHWC":"NCHW",auto_pad:y,dilations:[x],group:C,kernel_shape:[O],pads:F?Array.from(M.subarray(F>>>0,Y>>>0)):[],strides:[re],w_is_const:()=>!!ee[ie>>>0],activation:Je(ge),activation_params:Be?Array.from(K.subarray(Be>>>0,Fe>>>0)):[]})},836623:(f,y,x,C,O,F,Y,re,ue,ie,ge,Be,Fe,L,Ee,Pe)=>{i.Ra("Conv",f,{format:Be?"NHWC":"NCHW",auto_pad:y,dilations:[x,C],group:O,kernel_shape:[F,Y],pads:re?Array.from(M.subarray(re>>>0,ue>>>0)):[],strides:[ie,ge],w_is_const:()=>!!ee[Fe>>>0],activation:Je(L),activation_params:Ee?Array.from(K.subarray(Ee>>>0,Pe>>>0)):[]})},837014:f=>{i.Ra("Gelu",f,void 0)},837066:(f,y,x,C,O,F)=>{i.Ra("MatMulNBits",f,{k:y,n:x,accuracyLevel:C,bits:O,blockSize:F})},837193:(f,y,x,C,O,F)=>{i.Ra("MultiHeadAttention",f,{numHeads:y,isUnidirectional:x,maskFilterValue:C,scale:O,doRotary:F})},837352:(f,y,x,C,O)=>{i.Ra("RotaryEmbedding",f,{interleaved:!!y,numHeads:x,rotaryEmbeddingDim:C,scale:O})},837491:(f,y,x)=>{i.Ra("SkipLayerNormalization",f,{epsilon:y,simplified:!!x})},837593:(f,y,x)=>{i.Ra("SkipLayerNormalization",f,{epsilon:y,simplified:!!x})},837695:(f,y,x,C)=>{i.Ra("LayerNormalization",f,{axis:y,epsilon:x,simplified:!!C})},837806:f=>{i.ub(f)},837840:(f,y)=>i.wb(f,y,i.cb.xb,i.cb.errors)};function pn(f){this.name="ExitStatus",this.message=`Program terminated with exit(${f})`,this.status=f}class hl{constructor(y){this.hb=y-24}}var Mr=0,Wr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ba=(f,y,x)=>{y>>>=0;var C=y+x;for(x=y;f[x]&&!(x>=C);)++x;if(16O?C+=String.fromCharCode(O):(O-=65536,C+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else C+=String.fromCharCode(O)}return C},Je=(f,y)=>(f>>>=0)?Ba(ne,f,y):"",Dn=f=>{for(var y=0,x=0;x=C?y++:2047>=C?y+=2:55296<=C&&57343>=C?(y+=4,++x):y+=3}return y},Jt=(f,y,x,C)=>{if(x>>>=0,!(0=Y){var re=f.charCodeAt(++F);Y=65536+((Y&1023)<<10)|re&1023}if(127>=Y){if(x>=C)break;y[x++>>>0]=Y}else{if(2047>=Y){if(x+1>=C)break;y[x++>>>0]=192|Y>>6}else{if(65535>=Y){if(x+2>=C)break;y[x++>>>0]=224|Y>>12}else{if(x+3>=C)break;y[x++>>>0]=240|Y>>18,y[x++>>>0]=128|Y>>12&63}y[x++>>>0]=128|Y>>6&63}y[x++>>>0]=128|Y&63}}return y[x>>>0]=0,x-O},Vr,Vt=f=>{for(var y="";ne[f>>>0];)y+=Vr[ne[f++>>>0]];return y},Da={},Nn={},wr;function Na(f,y,x={}){var C=y.name;if(!f)throw new wr(`type "${C}" must have a positive integer typeid pointer`);if(Nn.hasOwnProperty(f)){if(x.nb)return;throw new wr(`Cannot register type '${C}' twice`)}Nn[f]=y,Da.hasOwnProperty(f)&&(y=Da[f],delete Da[f],y.forEach(O=>O()))}function Bt(f,y,x={}){if(!("argPackAdvance"in y))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Na(f,y,x)}var Fn=(f,y,x)=>{switch(y){case 1:return x?C=>ee[C>>>0]:C=>ne[C>>>0];case 2:return x?C=>se[C>>>1>>>0]:C=>D[C>>>1>>>0];case 4:return x?C=>M[C>>>2>>>0]:C=>G[C>>>2>>>0];case 8:return x?C=>pe[C>>>3]:C=>le[C>>>3];default:throw new TypeError(`invalid integer width (${y}): ${f}`)}},Ln=[],ft=[];function Fa(f){f>>>=0,9{if(!f)throw new wr("Cannot use deleted val. handle = "+f);return ft[f]},Dt=f=>{switch(f){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let y=Ln.pop()||ft.length;return ft[y]=f,ft[y+1]=1,y}};function hn(f){return this.fromWireType(G[f>>>2>>>0])}var fl={name:"emscripten::val",fromWireType:f=>{var y=ze(f);return Fa(f),y},toWireType:(f,y)=>Dt(y),argPackAdvance:8,readValueFromPointer:hn,bb:null},ts=(f,y)=>{switch(y){case 4:return function(x){return this.fromWireType(K[x>>>2>>>0])};case 8:return function(x){return this.fromWireType(N[x>>>3>>>0])};default:throw new TypeError(`invalid float width (${y}): ${f}`)}},rs=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ve=(f,y)=>{for(var x=f>>1,C=x+y/2;!(x>=C)&&D[x>>>0];)++x;if(x<<=1,32>>0,x>>>0));for(x="",C=0;!(C>=y/2);++C){var O=se[f+2*C>>>1>>>0];if(O==0)break;x+=String.fromCharCode(O)}return x},Un=(f,y,x)=>{if(x??(x=2147483647),2>x)return 0;x-=2;var C=y;x=x<2*f.length?x/2:f.length;for(var O=0;O>>1>>>0]=f.charCodeAt(O),y+=2;return se[y>>>1>>>0]=0,y-C},ns=f=>2*f.length,ml=(f,y)=>{for(var x=0,C="";!(x>=y/4);){var O=M[f+4*x>>>2>>>0];if(O==0)break;++x,65536<=O?(O-=65536,C+=String.fromCharCode(55296|O>>10,56320|O&1023)):C+=String.fromCharCode(O)}return C},as=(f,y,x)=>{if(y>>>=0,x??(x=2147483647),4>x)return 0;var C=y;x=C+x-4;for(var O=0;O=F){var Y=f.charCodeAt(++O);F=65536+((F&1023)<<10)|Y&1023}if(M[y>>>2>>>0]=F,y+=4,y+4>x)break}return M[y>>>2>>>0]=0,y-C},is=f=>{for(var y=0,x=0;x=C&&++x,y+=4}return y},Wn=(f,y)=>{var x=Nn[f];if(x===void 0)throw f=Ya(f),x=Vt(f),It(f),new wr(`${y} has unknown type ${x}`);return x},La=(f,y,x)=>{var C=[];return f=f.toWireType(C,x),C.length&&(G[y>>>2>>>0]=Dt(C)),f},fn=f=>{try{f()}catch(y){je(y)}},lt=f=>{var y;if(!q)try{f();try{fe=fe=f=fe,(y=i.onExit)==null||y.call(i,f),q=!0,g(f,new pn(f))}catch(x){x instanceof pn||x=="unwind"||g(1,x)}}catch(x){x instanceof pn||x=="unwind"||g(1,x)}};function ss(){var f=be,y={};for(let[x,C]of Object.entries(f))y[x]=typeof C=="function"?(...O)=>{pr.push(x);try{return C(...O)}finally{q||(pr.pop(),Nt&&cr===1&&pr.length===0&&(cr=0,fn(gs),typeof Fibers<"u"&&Fibers.Db()))}}:C;return y}var cr=0,Nt=null,Ua=0,pr=[],Wa={},Va={},os=0,Vn=null,ls=[];function us(){return new Promise((f,y)=>{Vn={resolve:f,reject:y}})}function ds(){var f=Gr(65548),y=f+12;G[f>>>2>>>0]=y,G[f+4>>>2>>>0]=y+65536,y=pr[0];var x=Wa[y];return x===void 0&&(x=os++,Wa[y]=x,Va[x]=y),M[f+8>>>2>>>0]=x,f}function cs(f){if(!q){if(cr===0){var y=!1,x=!1;f((C=0)=>{if(!q&&(Ua=C,y=!0,x)){cr=2,fn(()=>fr(Nt)),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.resume(),C=!1;try{var O=(0,be[Va[M[Nt+8>>>2>>>0]]])()}catch(re){O=re,C=!0}var F=!1;if(!Nt){var Y=Vn;Y&&(Vn=null,(C?Y.reject:Y.resolve)(O),F=!0)}if(C&&!F)throw O}}),x=!0,y||(cr=1,Nt=ds(),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.pause(),fn(()=>_n(Nt)))}else cr===2?(cr=0,fn(jt),It(Nt),Nt=null,ls.forEach(lt)):je(`invalid state: ${cr}`);return Ua}}function Ga(f){return cs(y=>{f().then(y)})}var mn=[],ps={},Gn=f=>{var y=ps[f];return y===void 0?Vt(f):y},Gt=()=>typeof globalThis=="object"?globalThis:Function("return this")(),Ha=f=>{var y=mn.length;return mn.push(f),y},ja=(f,y)=>{for(var x=Array(f),C=0;C>>2>>>0],"parameter "+C);return x},hr=(f,y)=>Object.defineProperty(y,"name",{value:f});function gl(f){var y=Function;if(!(y instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof y} which is not a function`);var x=hr(y.name||"unknownFunctionName",function(){});return x.prototype=y.prototype,x=new x,f=y.apply(x,f),f instanceof Object?f:x}var St=f=>f%4===0&&(f%100!==0||f%400===0),qa=[0,31,60,91,121,152,182,213,244,274,305,335],Hn=[0,31,59,90,120,151,181,212,243,273,304,334],Ht=[],jn=(f,y)=>{Ht.length=0;for(var x;x=ne[f++>>>0];){var C=x!=105;C&=x!=112,y+=C&&y%8?4:0,Ht.push(x==112?G[y>>>2>>>0]:x==106?pe[y>>>3]:x==105?M[y>>>2>>>0]:N[y>>>3>>>0]),y+=C?8:4}return Ht},mt={},Ft=()=>{if(!gn){var f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"},y;for(y in mt)mt[y]===void 0?delete f[y]:f[y]=mt[y];var x=[];for(y in f)x.push(`${y}=${f[y]}`);gn=x}return gn},gn,_l=[null,[],[]],hs=[31,29,31,30,31,30,31,31,30,31,30,31],Ka=[31,28,31,30,31,30,31,31,30,31,30,31];function yl(f){var y=Array(Dn(f)+1);return Jt(f,y,0,y.length),y}function fs(f,y,x,C){function O(L,Ee,Pe){for(L=typeof L=="number"?L.toString():L||"";L.lengthPr?-1:0zr-L.getDate())Ee-=zr-L.getDate()+1,L.setDate(1),11>Pe?L.setMonth(Pe+1):(L.setMonth(0),L.setFullYear(L.getFullYear()+1));else{L.setDate(L.getDate()+Ee);break}}return Pe=new Date(L.getFullYear()+1,0,4),Ee=re(new Date(L.getFullYear(),0,4)),Pe=re(Pe),0>=Y(Ee,L)?0>=Y(Pe,L)?L.getFullYear()+1:L.getFullYear():L.getFullYear()-1}f>>>=0,y>>>=0,x>>>=0,C>>>=0;var ie=G[C+40>>>2>>>0];C={Ab:M[C>>>2>>>0],zb:M[C+4>>>2>>>0],fb:M[C+8>>>2>>>0],jb:M[C+12>>>2>>>0],gb:M[C+16>>>2>>>0],ab:M[C+20>>>2>>>0],Va:M[C+24>>>2>>>0],$a:M[C+28>>>2>>>0],Cb:M[C+32>>>2>>>0],yb:M[C+36>>>2>>>0],Bb:ie?Je(ie):""},x=Je(x),ie={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var ge in ie)x=x.replace(new RegExp(ge,"g"),ie[ge]);var Be="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Fe="January February March April May June July August September October November December".split(" ");ie={"%a":L=>Be[L.Va].substring(0,3),"%A":L=>Be[L.Va],"%b":L=>Fe[L.gb].substring(0,3),"%B":L=>Fe[L.gb],"%C":L=>F((L.ab+1900)/100|0,2),"%d":L=>F(L.jb,2),"%e":L=>O(L.jb,2," "),"%g":L=>ue(L).toString().substring(2),"%G":ue,"%H":L=>F(L.fb,2),"%I":L=>(L=L.fb,L==0?L=12:12{for(var Ee=0,Pe=0;Pe<=L.gb-1;Ee+=(St(L.ab+1900)?hs:Ka)[Pe++]);return F(L.jb+Ee,3)},"%m":L=>F(L.gb+1,2),"%M":L=>F(L.zb,2),"%n":()=>` `,"%p":L=>0<=L.fb&&12>L.fb?"AM":"PM","%S":L=>F(L.Ab,2),"%t":()=>" ","%u":L=>L.Va||7,"%U":L=>F(Math.floor((L.$a+7-L.Va)/7),2),"%V":L=>{var Ee=Math.floor((L.$a+7-(L.Va+6)%7)/7);if(2>=(L.Va+371-L.$a-2)%7&&Ee++,Ee)Ee==53&&(Pe=(L.Va+371-L.$a)%7,Pe==4||Pe==3&&St(L.ab)||(Ee=1));else{Ee=52;var Pe=(L.Va+7-L.$a-1)%7;(Pe==4||Pe==5&&St(L.ab%400-1))&&Ee++}return F(Ee,2)},"%w":L=>L.Va,"%W":L=>F(Math.floor((L.$a+7-(L.Va+6)%7)/7),2),"%y":L=>(L.ab+1900).toString().substring(2),"%Y":L=>L.ab+1900,"%z":L=>{L=L.yb;var Ee=0<=L;return L=Math.abs(L)/60,(Ee?"+":"-")+("0000"+(L/60*100+L%60)).slice(-4)},"%Z":L=>L.Bb,"%%":()=>"%"},x=x.replace(/%%/g,"\0\0");for(ge in ie)x.includes(ge)&&(x=x.replace(new RegExp(ge,"g"),ie[ge](C)));return x=x.replace(/\0\0/g,"%"),ge=yl(x),ge.length>y?0:(ee.set(ge,f>>>0),ge.length-1)}for(var ms=Array(256),qn=0;256>qn;++qn)ms[qn]=String.fromCharCode(qn);Vr=ms,wr=i.BindingError=class extends Error{constructor(f){super(f),this.name="BindingError"}},i.InternalError=class extends Error{constructor(f){super(f),this.name="InternalError"}},ft.push(0,1,void 0,1,null,1,!0,1,!1,1),i.count_emval_handles=()=>ft.length/2-5-Ln.length;var wl={ia:function(f,y,x){return Ga(async()=>{await i.sb(f,y,x)})},a:function(f,y,x){f>>>=0;var C=new hl(f);throw G[C.hb+16>>>2>>>0]=0,G[C.hb+4>>>2>>>0]=y>>>0,G[C.hb+8>>>2>>>0]=x>>>0,Mr=f,Mr},y:function(){return 0},ea:function(){},R:function(){},T:function(){},ga:function(){return 0},ca:function(){},Z:function(){},ba:function(){},G:function(){},S:function(){},P:function(){},da:function(){},Q:function(){},C:function(f,y,x){y=Vt(y>>>0),Bt(f>>>0,{name:y,fromWireType:C=>C,toWireType:function(C,O){if(typeof O!="bigint"&&typeof O!="number")throw O===null?O="null":(C=typeof O,O=C==="object"||C==="array"||C==="function"?O.toString():""+O),new TypeError(`Cannot convert "${O}" to ${this.name}`);return typeof O=="number"&&(O=BigInt(O)),O},argPackAdvance:8,readValueFromPointer:Fn(y,x>>>0,y.indexOf("u")==-1),bb:null})},K:function(f,y,x,C){y=Vt(y>>>0),Bt(f>>>0,{name:y,fromWireType:function(O){return!!O},toWireType:function(O,F){return F?x:C},argPackAdvance:8,readValueFromPointer:function(O){return this.fromWireType(ne[O>>>0])},bb:null})},J:function(f){return Bt(f>>>0,fl)},B:function(f,y,x){y=Vt(y>>>0),Bt(f>>>0,{name:y,fromWireType:C=>C,toWireType:(C,O)=>O,argPackAdvance:8,readValueFromPointer:ts(y,x>>>0),bb:null})},s:function(f,y,x,C,O){if(f>>>=0,x>>>=0,y=Vt(y>>>0),O===-1&&(O=4294967295),O=re=>re,C===0){var F=32-8*x;O=re=>re<>>F}var Y=y.includes("unsigned")?function(re,ue){return ue>>>0}:function(re,ue){return ue};Bt(f,{name:y,fromWireType:O,toWireType:Y,argPackAdvance:8,readValueFromPointer:Fn(y,x,C!==0),bb:null})},o:function(f,y,x){function C(F){return new O(ee.buffer,G[F+4>>>2>>>0],G[F>>>2>>>0])}var O=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][y];x=Vt(x>>>0),Bt(f>>>0,{name:x,fromWireType:C,argPackAdvance:8,readValueFromPointer:C},{nb:!0})},D:function(f,y){y=Vt(y>>>0);var x=y==="std::string";Bt(f>>>0,{name:y,fromWireType:function(C){var O=G[C>>>2>>>0],F=C+4;if(x)for(var Y=F,re=0;re<=O;++re){var ue=F+re;if(re==O||ne[ue>>>0]==0){if(Y=Je(Y,ue-Y),ie===void 0)var ie=Y;else ie+="\0",ie+=Y;Y=ue+1}}else{for(ie=Array(O),re=0;re>>0]);ie=ie.join("")}return It(C),ie},toWireType:function(C,O){O instanceof ArrayBuffer&&(O=new Uint8Array(O));var F=typeof O=="string";if(!(F||O instanceof Uint8Array||O instanceof Uint8ClampedArray||O instanceof Int8Array))throw new wr("Cannot pass non-string to std::string");var Y=x&&F?Dn(O):O.length,re=Gr(4+Y+1),ue=re+4;if(G[re>>>2>>>0]=Y,x&&F)Jt(O,ne,ue,Y+1);else if(F)for(F=0;F>>0]=ie}else for(F=0;F>>0]=O[F];return C!==null&&C.push(It,re),re},argPackAdvance:8,readValueFromPointer:hn,bb(C){It(C)}})},x:function(f,y,x){if(y>>>=0,x>>>=0,x=Vt(x),y===2)var C=ve,O=Un,F=ns,Y=re=>D[re>>>1>>>0];else y===4&&(C=ml,O=as,F=is,Y=re=>G[re>>>2>>>0]);Bt(f>>>0,{name:x,fromWireType:re=>{for(var ue=G[re>>>2>>>0],ie,ge=re+4,Be=0;Be<=ue;++Be){var Fe=re+4+Be*y;(Be==ue||Y(Fe)==0)&&(ge=C(ge,Fe-ge),ie===void 0?ie=ge:(ie+="\0",ie+=ge),ge=Fe+y)}return It(re),ie},toWireType:(re,ue)=>{if(typeof ue!="string")throw new wr(`Cannot pass non-string to C++ string type ${x}`);var ie=F(ue),ge=Gr(4+ie+y);return G[ge>>>2>>>0]=ie/y,O(ue,ge+4,ie+y),re!==null&&re.push(It,ge),ge},argPackAdvance:8,readValueFromPointer:hn,bb(re){It(re)}})},L:function(f,y){y=Vt(y>>>0),Bt(f>>>0,{ob:!0,name:y,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ha:()=>1,u:function(f,y,x){return y>>>=0,x>>>=0,f=ze(f>>>0),y=Wn(y,"emval::as"),La(y,x,f)},w:function(f){return f>>>=0,Ga(()=>(f=ze(f),f.then(Dt)))},n:function(f,y,x,C){return x>>>=0,C>>>=0,f=mn[f>>>0],y=ze(y>>>0),f(null,y,x,C)},j:function(f,y,x,C,O){return x>>>=0,C>>>=0,O>>>=0,f=mn[f>>>0],y=ze(y>>>0),x=Gn(x),f(y,y[x],C,O)},b:Fa,A:function(f,y){return y>>>=0,f=ze(f>>>0),y=ze(y),f==y},m:function(f){return f>>>=0,f===0?Dt(Gt()):(f=Gn(f),Dt(Gt()[f]))},i:function(f,y,x){y=ja(f,y>>>0);var C=y.shift();f--;var O=`return function (obj, func, destructorsRef, args) { `,F=0,Y=[];x===0&&Y.push("obj");for(var re=["retType"],ue=[C],ie=0;iege.name).join(", ")}) => ${C.name}>`,Ha(hr(x,f))},r:function(f,y){return y>>>=0,f=ze(f>>>0),y=ze(y),Dt(f[y])},e:function(f){f>>>=0,9>>0);for(var y=Array(f.length),x=0;x>>0))},k:function(){return Dt({})},h:function(f){f>>>=0;for(var y=ze(f);y.length;){var x=y.pop();y.pop()(x)}Fa(f)},g:function(f,y,x){y>>>=0,x>>>=0,f=ze(f>>>0),y=ze(y),x=ze(x),f[y]=x},c:function(f,y){return y>>>=0,f=Wn(f>>>0,"_emval_take_value"),f=f.readValueFromPointer(y),Dt(f)},W:function(f,y){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),M[y>>>2>>>0]=f.getUTCSeconds(),M[y+4>>>2>>>0]=f.getUTCMinutes(),M[y+8>>>2>>>0]=f.getUTCHours(),M[y+12>>>2>>>0]=f.getUTCDate(),M[y+16>>>2>>>0]=f.getUTCMonth(),M[y+20>>>2>>>0]=f.getUTCFullYear()-1900,M[y+24>>>2>>>0]=f.getUTCDay(),M[y+28>>>2>>>0]=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},X:function(f,y){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),M[y>>>2>>>0]=f.getSeconds(),M[y+4>>>2>>>0]=f.getMinutes(),M[y+8>>>2>>>0]=f.getHours(),M[y+12>>>2>>>0]=f.getDate(),M[y+16>>>2>>>0]=f.getMonth(),M[y+20>>>2>>>0]=f.getFullYear()-1900,M[y+24>>>2>>>0]=f.getDay(),M[y+28>>>2>>>0]=(St(f.getFullYear())?qa:Hn)[f.getMonth()]+f.getDate()-1|0,M[y+36>>>2>>>0]=-(60*f.getTimezoneOffset());var x=new Date(f.getFullYear(),6,1).getTimezoneOffset(),C=new Date(f.getFullYear(),0,1).getTimezoneOffset();M[y+32>>>2>>>0]=(x!=C&&f.getTimezoneOffset()==Math.min(C,x))|0},Y:function(f){f>>>=0;var y=new Date(M[f+20>>>2>>>0]+1900,M[f+16>>>2>>>0],M[f+12>>>2>>>0],M[f+8>>>2>>>0],M[f+4>>>2>>>0],M[f>>>2>>>0],0),x=M[f+32>>>2>>>0],C=y.getTimezoneOffset(),O=new Date(y.getFullYear(),6,1).getTimezoneOffset(),F=new Date(y.getFullYear(),0,1).getTimezoneOffset(),Y=Math.min(F,O);return 0>x?M[f+32>>>2>>>0]=+(O!=F&&Y==C):0>>2>>>0]=y.getDay(),M[f+28>>>2>>>0]=(St(y.getFullYear())?qa:Hn)[y.getMonth()]+y.getDate()-1|0,M[f>>>2>>>0]=y.getSeconds(),M[f+4>>>2>>>0]=y.getMinutes(),M[f+8>>>2>>>0]=y.getHours(),M[f+12>>>2>>>0]=y.getDate(),M[f+16>>>2>>>0]=y.getMonth(),M[f+20>>>2>>>0]=y.getYear(),f=y.getTime(),BigInt(isNaN(f)?-1:f/1e3)},U:function(){return-52},V:function(){},N:function(f,y,x,C){x>>>=0,C>>>=0;var O=new Date().getFullYear(),F=new Date(O,0,1),Y=new Date(O,6,1);O=F.getTimezoneOffset();var re=Y.getTimezoneOffset();G[f>>>0>>>2>>>0]=60*Math.max(O,re),M[y>>>0>>>2>>>0]=+(O!=re),f=ue=>ue.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],F=f(F),Y=f(Y),re{je("")},d:function(f,y,x){return f>>>=0,y=jn(y>>>0,x>>>0),Ir[f](...y)},I:function(f,y,x){return f>>>=0,y=jn(y>>>0,x>>>0),Ir[f](...y)},H:()=>Date.now(),O:function(){return 4294901760},q:()=>performance.now(),M:function(f){f>>>=0;var y=ne.length;if(4294901760=x;x*=2){var C=y*(1+.2/x);C=Math.min(C,f+100663296);var O=Math;C=Math.max(f,C);e:{O=(O.min.call(O,4294901760,C+(65536-C%65536)%65536)-j.buffer.byteLength+65535)/65536;try{j.grow(O),ae();var F=1;break e}catch{}F=void 0}if(F)return!0}return!1},$:function(f,y){f>>>=0,y>>>=0;var x=0;return Ft().forEach((C,O)=>{var F=y+x;for(O=G[f+4*O>>>2>>>0]=F,F=0;F>>0]=C.charCodeAt(F);ee[O>>>0]=0,x+=C.length+1}),0},aa:function(f,y){f>>>=0,y>>>=0;var x=Ft();G[f>>>2>>>0]=x.length;var C=0;return x.forEach(O=>C+=O.length+1),G[y>>>2>>>0]=C,0},z:()=>52,F:function(){return 52},_:function(){return 70},E:function(f,y,x,C){y>>>=0,x>>>=0,C>>>=0;for(var O=0,F=0;F>>2>>>0],re=G[y+4>>>2>>>0];y+=8;for(var ue=0;ue>>0],ge=_l[f];ie===0||ie===10?((f===1?R:V)(Ba(ge,0)),ge.length=0):ge.push(ie)}O+=re}return G[C>>>2>>>0]=O,0},fa:fs,p:function(f,y,x,C){return fs(f>>>0,y>>>0,x>>>0,C>>>0)}},be=function(){function f(x){return be=x.exports,be=ss(),be=_s(),j=be.ja,ae(),Se.unshift(be.ka),Xe--,Xe==0&&ot&&(x=ot,ot=null,x()),be}var y={a:wl};if(Xe++,i.instantiateWasm)try{return i.instantiateWasm(y,f)}catch(x){V(`Module.instantiateWasm callback failed with error: ${x}`),l(x)}return Ar(y,function(x){f(x.instance)}).catch(l),{}}(),Ya=f=>(Ya=be.la)(f);i._OrtInit=(f,y)=>(i._OrtInit=be.ma)(f,y),i._OrtGetLastError=(f,y)=>(i._OrtGetLastError=be.na)(f,y),i._OrtCreateSessionOptions=(f,y,x,C,O,F,Y,re,ue,ie)=>(i._OrtCreateSessionOptions=be.oa)(f,y,x,C,O,F,Y,re,ue,ie),i._OrtAppendExecutionProvider=(f,y)=>(i._OrtAppendExecutionProvider=be.pa)(f,y),i._OrtAddFreeDimensionOverride=(f,y,x)=>(i._OrtAddFreeDimensionOverride=be.qa)(f,y,x),i._OrtAddSessionConfigEntry=(f,y,x)=>(i._OrtAddSessionConfigEntry=be.ra)(f,y,x),i._OrtReleaseSessionOptions=f=>(i._OrtReleaseSessionOptions=be.sa)(f),i._OrtCreateSession=(f,y,x)=>(i._OrtCreateSession=be.ta)(f,y,x),i._OrtReleaseSession=f=>(i._OrtReleaseSession=be.ua)(f),i._OrtGetInputOutputCount=(f,y,x)=>(i._OrtGetInputOutputCount=be.va)(f,y,x),i._OrtGetInputName=(f,y)=>(i._OrtGetInputName=be.wa)(f,y),i._OrtGetOutputName=(f,y)=>(i._OrtGetOutputName=be.xa)(f,y),i._OrtFree=f=>(i._OrtFree=be.ya)(f),i._OrtCreateTensor=(f,y,x,C,O,F)=>(i._OrtCreateTensor=be.za)(f,y,x,C,O,F),i._OrtGetTensorData=(f,y,x,C,O)=>(i._OrtGetTensorData=be.Aa)(f,y,x,C,O),i._OrtReleaseTensor=f=>(i._OrtReleaseTensor=be.Ba)(f),i._OrtCreateRunOptions=(f,y,x,C)=>(i._OrtCreateRunOptions=be.Ca)(f,y,x,C),i._OrtAddRunConfigEntry=(f,y,x)=>(i._OrtAddRunConfigEntry=be.Da)(f,y,x),i._OrtReleaseRunOptions=f=>(i._OrtReleaseRunOptions=be.Ea)(f),i._OrtCreateBinding=f=>(i._OrtCreateBinding=be.Fa)(f),i._OrtBindInput=(f,y,x)=>(i._OrtBindInput=be.Ga)(f,y,x),i._OrtBindOutput=(f,y,x,C)=>(i._OrtBindOutput=be.Ha)(f,y,x,C),i._OrtClearBoundOutputs=f=>(i._OrtClearBoundOutputs=be.Ia)(f),i._OrtReleaseBinding=f=>(i._OrtReleaseBinding=be.Ja)(f),i._OrtRunWithBinding=(f,y,x,C,O)=>(i._OrtRunWithBinding=be.Ka)(f,y,x,C,O),i._OrtRun=(f,y,x,C,O,F,Y,re)=>(i._OrtRun=be.La)(f,y,x,C,O,F,Y,re),i._OrtEndProfiling=f=>(i._OrtEndProfiling=be.Ma)(f),i._JsepOutput=(f,y,x)=>(i._JsepOutput=be.Na)(f,y,x),i._JsepGetNodeName=f=>(i._JsepGetNodeName=be.Oa)(f);var Gr=i._malloc=f=>(Gr=i._malloc=be.Pa)(f),It=i._free=f=>(It=i._free=be.Qa)(f),Kn=f=>(Kn=be.Sa)(f),Yn=f=>(Yn=be.Ta)(f),Xa=()=>(Xa=be.Ua)(),_n=f=>(_n=be.Wa)(f),gs=()=>(gs=be.Xa)(),fr=f=>(fr=be.Ya)(f),jt=()=>(jt=be.Za)();i.___start_em_js=837952,i.___stop_em_js=838113;function _s(){var f=be;f=Object.assign({},f);var y=x=>C=>x(C)>>>0;return f.la=y(f.la),f.Pa=y(f.Pa),f.Ta=y(f.Ta),f.Ua=(x=>()=>x()>>>0)(f.Ua),f}i.stackSave=()=>Xa(),i.stackRestore=f=>Kn(f),i.stackAlloc=f=>Yn(f),i.UTF8ToString=Je,i.stringToUTF8=(f,y,x)=>Jt(f,ne,y,x),i.lengthBytesUTF8=Dn;var Or;ot=function f(){Or||Qa(),Or||(ot=f)};function Qa(){if(!(0r)}),Sy=vn(()=>{}),ky=vn(()=>{}),lu={};$n(lu,{cpus:()=>uu});var uu,Ey=te(()=>{uu=void 0}),Cy=vn((t,e)=>{var r=(()=>{var a;var n=typeof document<"u"?(a=document.currentScript)==null?void 0:a.src:void 0;return typeof __filename<"u"&&(n||(n=__filename)),function(s={}){function i(){return N.buffer!=Te.buffer&&dt(),Te}function o(){return N.buffer!=Te.buffer&&dt(),Xe}function l(){return N.buffer!=Te.buffer&&dt(),ot}function u(){return N.buffer!=Te.buffer&&dt(),je}function d(){return N.buffer!=Te.buffer&&dt(),ht}function h(){return N.buffer!=Te.buffer&&dt(),ut}function m(){return N.buffer!=Te.buffer&&dt(),yt}function g(){return N.buffer!=Te.buffer&&dt(),Rt}var p=s,w,v,S=new Promise((c,_)=>{w=c,v=_});p.mountExternalData=(c,_)=>{(p.Db||(p.Db=new Map)).set(c,_)},p.unmountExternalData=()=>{delete p.Db};let $=()=>{let c=(b,k,I)=>(...P)=>{let H=jt,J=k==null?void 0:k();P=b(...P);let he=k==null?void 0:k();return J!==he&&(b=he,I(J),k=I=null),jt!=H?O():P},_=b=>async(...k)=>{var I;try{if(p.Cb)throw Error("Session already started");let P=p.Cb={ec:k[0],errors:[]},H=await b(...k);if(p.Cb!==P)throw Error("Session mismatch");(I=p.Kb)==null||I.flush();let J=P.errors;if(0oe),0p._OrtCreateSession,b=>p._OrtCreateSession=b),p._OrtRun=_(c(p._OrtRun,()=>p._OrtRun,b=>p._OrtRun=b)),p._OrtRunWithBinding=_(c(p._OrtRunWithBinding,()=>p._OrtRunWithBinding,b=>p._OrtRunWithBinding=b)),p._OrtBindInput=c(p._OrtBindInput,()=>p._OrtBindInput,b=>p._OrtBindInput=b),$=void 0};p.jsepInit=(c,_)=>{if($==null||$(),c==="webgpu"){[p.Kb,p.Wb,p.$b,p.Lb,p.Zb,p.ob,p.ac,p.cc,p.Xb,p.Yb,p.bc]=_;let b=p.Kb;p.jsepRegisterBuffer=(k,I,P,H)=>b.registerBuffer(k,I,P,H),p.jsepGetBuffer=k=>b.getBuffer(k),p.jsepCreateDownloader=(k,I,P)=>b.createDownloader(k,I,P),p.jsepOnReleaseSession=k=>{b.onReleaseSession(k)},p.jsepOnRunStart=k=>b.onRunStart(k)}};var E=Object.assign({},p),T="./this.program",A=(c,_)=>{throw _},z=typeof window=="object",R=typeof importScripts=="function",V=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",j=p.ENVIRONMENT_IS_PTHREAD||!1,q="";function fe(c){return p.locateFile?p.locateFile(c,q):q+c}var ee,ne,se;if(V){var D=(iu(),jr(Bs)),M=(ou(),jr(Ds));q=R?M.dirname(q)+"/":__dirname+"/",ee=(c,_)=>(c=Jt(c)?new URL(c):M.normalize(c),D.readFileSync(c,_?void 0:"utf8")),se=c=>(c=ee(c,!0),c.buffer||(c=new Uint8Array(c)),c),ne=(c,_,b,k=!0)=>{c=Jt(c)?new URL(c):M.normalize(c),D.readFile(c,k?void 0:"utf8",(I,P)=>{I?b(I):_(k?P.buffer:P)})},!p.thisProgram&&1{throw process.exitCode=c,_},global.Worker=Sy().Worker}else(z||R)&&(R?q=self.location.href:typeof document<"u"&&document.currentScript&&(q=document.currentScript.src),typeof n<"u"&&n&&(q=n),q.startsWith("blob:")?q="":q=q.substr(0,q.replace(/[?#].*/,"").lastIndexOf("/")+1),V||(ee=c=>{var _=new XMLHttpRequest;return _.open("GET",c,!1),_.send(null),_.responseText},R&&(se=c=>{var _=new XMLHttpRequest;return _.open("GET",c,!1),_.responseType="arraybuffer",_.send(null),new Uint8Array(_.response)}),ne=(c,_,b)=>{var k=new XMLHttpRequest;k.open("GET",c,!0),k.responseType="arraybuffer",k.onload=()=>{k.status==200||k.status==0&&k.response?_(k.response):b()},k.onerror=b,k.send(null)}));V&&typeof performance>"u"&&(global.performance=ky().performance);var G=console.log.bind(console),K=console.error.bind(console);V&&(G=(...c)=>D.writeSync(1,c.join(" ")+` `),K=(...c)=>D.writeSync(2,c.join(" ")+` `));var pe=G,le=K;Object.assign(p,E),E=null;var N,ae,de=!1,Se,Te,Xe,ot,je,ht,ut,yt,We,Ze,Rt;function dt(){var c=N.buffer;p.HEAP8=Te=new Int8Array(c),p.HEAP16=ot=new Int16Array(c),p.HEAPU8=Xe=new Uint8Array(c),p.HEAPU16=je=new Uint16Array(c),p.HEAP32=ht=new Int32Array(c),p.HEAPU32=ut=new Uint32Array(c),p.HEAPF32=yt=new Float32Array(c),p.HEAPF64=Rt=new Float64Array(c),p.HEAP64=We=new BigInt64Array(c),p.HEAPU64=Ze=new BigUint64Array(c)}var Ar=16777216;if(j)N=p.wasmMemory;else if(p.wasmMemory)N=p.wasmMemory;else if(N=new WebAssembly.Memory({initial:Ar/65536,maximum:65536,shared:!0}),!(N.buffer instanceof SharedArrayBuffer))throw le("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"),V&&le("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");dt(),Ar=N.buffer.byteLength;var Ir=[],pn=[],hl=[],Mr=0,Wr=null;function Ba(){if(Mr--,Mr==0&&Wr){var c=Wr;Wr=null,c()}}function Je(c){throw c="Aborted("+c+")",le(c),de=!0,Se=1,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),v(c),c}var Dn=c=>c.startsWith("data:application/octet-stream;base64,"),Jt=c=>c.startsWith("file://"),Vr;Vr="ort-wasm-simd-threaded.wasm",Dn(Vr)||(Vr=fe(Vr));function Vt(c){if(se)return se(c);throw"both async and sync fetching of the wasm failed"}function Da(c){if(z||R){if(typeof fetch=="function"&&!Jt(c))return fetch(c,{credentials:"same-origin"}).then(_=>{if(!_.ok)throw`failed to load wasm binary file at '${c}'`;return _.arrayBuffer()}).catch(()=>Vt(c));if(ne)return new Promise((_,b)=>{ne(c,k=>_(new Uint8Array(k)),b)})}return Promise.resolve().then(()=>Vt(c))}function Nn(c,_,b){return Da(c).then(k=>WebAssembly.instantiate(k,_)).then(b,k=>{le(`failed to asynchronously prepare wasm: ${k}`),Je(k)})}function wr(c,_){var b=Vr;return typeof WebAssembly.instantiateStreaming!="function"||Dn(b)||Jt(b)||V||typeof fetch!="function"?Nn(b,c,_):fetch(b,{credentials:"same-origin"}).then(k=>WebAssembly.instantiateStreaming(k,c).then(_,function(I){return le(`wasm streaming compile failed: ${I}`),le("falling back to ArrayBuffer instantiation"),Nn(b,c,_)}))}var Na={826468:(c,_,b,k)=>{if(typeof p>"u"||!p.Db)return 1;if(c=lt(c>>>0),c.startsWith("./")&&(c=c.substring(2)),c=p.Db.get(c),!c)return 2;if(_>>>=0,b>>>=0,k>>>=0,_+b>c.byteLength)return 3;try{return o().set(c.subarray(_,_+b),k>>>0),0}catch{return 4}},826969:()=>{p.Xb()},827e3:()=>{p.Yb()},827029:()=>{p.bc()},827054:c=>p.Wb(c),827087:c=>p.$b(c),827119:(c,_,b)=>{p.Lb(c,_,b,!0)},827158:(c,_,b)=>{p.Lb(c,_,b)},827191:c=>{p.ob("Abs",c,void 0)},827242:c=>{p.ob("Neg",c,void 0)},827293:c=>{p.ob("Floor",c,void 0)},827346:c=>{p.ob("Ceil",c,void 0)},827398:c=>{p.ob("Reciprocal",c,void 0)},827456:c=>{p.ob("Sqrt",c,void 0)},827508:c=>{p.ob("Exp",c,void 0)},827559:c=>{p.ob("Erf",c,void 0)},827610:c=>{p.ob("Sigmoid",c,void 0)},827665:(c,_,b)=>{p.ob("HardSigmoid",c,{alpha:_,beta:b})},827744:c=>{p.ob("Log",c,void 0)},827795:c=>{p.ob("Sin",c,void 0)},827846:c=>{p.ob("Cos",c,void 0)},827897:c=>{p.ob("Tan",c,void 0)},827948:c=>{p.ob("Asin",c,void 0)},828e3:c=>{p.ob("Acos",c,void 0)},828052:c=>{p.ob("Atan",c,void 0)},828104:c=>{p.ob("Sinh",c,void 0)},828156:c=>{p.ob("Cosh",c,void 0)},828208:c=>{p.ob("Asinh",c,void 0)},828261:c=>{p.ob("Acosh",c,void 0)},828314:c=>{p.ob("Atanh",c,void 0)},828367:c=>{p.ob("Tanh",c,void 0)},828419:c=>{p.ob("Not",c,void 0)},828470:(c,_,b)=>{p.ob("Clip",c,{min:_,max:b})},828539:c=>{p.ob("Clip",c,void 0)},828591:(c,_)=>{p.ob("Elu",c,{alpha:_})},828649:c=>{p.ob("Relu",c,void 0)},828701:(c,_)=>{p.ob("LeakyRelu",c,{alpha:_})},828765:(c,_)=>{p.ob("ThresholdedRelu",c,{alpha:_})},828835:(c,_)=>{p.ob("Cast",c,{to:_})},828893:c=>{p.ob("Add",c,void 0)},828944:c=>{p.ob("Sub",c,void 0)},828995:c=>{p.ob("Mul",c,void 0)},829046:c=>{p.ob("Div",c,void 0)},829097:c=>{p.ob("Pow",c,void 0)},829148:c=>{p.ob("Equal",c,void 0)},829201:c=>{p.ob("Greater",c,void 0)},829256:c=>{p.ob("GreaterOrEqual",c,void 0)},829318:c=>{p.ob("Less",c,void 0)},829370:c=>{p.ob("LessOrEqual",c,void 0)},829429:(c,_,b,k,I)=>{p.ob("ReduceMean",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},829588:(c,_,b,k,I)=>{p.ob("ReduceMax",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},829746:(c,_,b,k,I)=>{p.ob("ReduceMin",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},829904:(c,_,b,k,I)=>{p.ob("ReduceProd",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},830063:(c,_,b,k,I)=>{p.ob("ReduceSum",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},830221:(c,_,b,k,I)=>{p.ob("ReduceL1",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},830378:(c,_,b,k,I)=>{p.ob("ReduceL2",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},830535:(c,_,b,k,I)=>{p.ob("ReduceLogSum",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},830696:(c,_,b,k,I)=>{p.ob("ReduceSumSquare",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},830860:(c,_,b,k,I)=>{p.ob("ReduceLogSumExp",c,{keepDims:!!_,noopWithEmptyAxes:!!b,axes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},831024:c=>{p.ob("Where",c,void 0)},831077:(c,_,b)=>{p.ob("Transpose",c,{perm:_?Array.from(d().subarray(_>>>0,b>>>0)):[]})},831185:(c,_,b,k)=>{p.ob("DepthToSpace",c,{blocksize:_,mode:lt(b),format:k?"NHWC":"NCHW"})},831318:(c,_,b,k)=>{p.ob("DepthToSpace",c,{blocksize:_,mode:lt(b),format:k?"NHWC":"NCHW"})},831451:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W,Ae)=>{p.ob("ConvTranspose",c,{format:he?"NHWC":"NCHW",autoPad:_,dilations:[b],group:k,kernelShape:[I],pads:[P,H],strides:[J],wIsConst:()=>!!i()[oe>>>0],outputPadding:ye?Array.from(d().subarray(ye>>>0,Le>>>0)):[],outputShape:He?Array.from(d().subarray(He>>>0,W>>>0)):[],activation:lt(Ae)})},831852:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W)=>{p.ob("ConvTranspose",c,{format:J?"NHWC":"NCHW",autoPad:_,dilations:Array.from(d().subarray(b>>>0,(b>>>0)+2>>>0)),group:k,kernelShape:Array.from(d().subarray(I>>>0,(I>>>0)+2>>>0)),pads:Array.from(d().subarray(P>>>0,(P>>>0)+4>>>0)),strides:Array.from(d().subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!i()[he>>>0],outputPadding:oe?Array.from(d().subarray(oe>>>0,ye>>>0)):[],outputShape:Le?Array.from(d().subarray(Le>>>0,He>>>0)):[],activation:lt(W)})},832417:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W,Ae)=>{p.ob("ConvTranspose",c,{format:he?"NHWC":"NCHW",autoPad:_,dilations:[b],group:k,kernelShape:[I],pads:[P,H],strides:[J],wIsConst:()=>!!i()[oe>>>0],outputPadding:ye?Array.from(d().subarray(ye>>>0,Le>>>0)):[],outputShape:He?Array.from(d().subarray(He>>>0,W>>>0)):[],activation:lt(Ae)})},832818:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W)=>{p.ob("ConvTranspose",c,{format:J?"NHWC":"NCHW",autoPad:_,dilations:Array.from(d().subarray(b>>>0,(b>>>0)+2>>>0)),group:k,kernelShape:Array.from(d().subarray(I>>>0,(I>>>0)+2>>>0)),pads:Array.from(d().subarray(P>>>0,(P>>>0)+4>>>0)),strides:Array.from(d().subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!i()[he>>>0],outputPadding:oe?Array.from(d().subarray(oe>>>0,ye>>>0)):[],outputShape:Le?Array.from(d().subarray(Le>>>0,He>>>0)):[],activation:lt(W)})},833383:(c,_)=>{p.ob("GlobalAveragePool",c,{format:_?"NHWC":"NCHW"})},833474:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W,Ae,Ne)=>{p.ob("AveragePool",c,{format:Ne?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:k,storage_order:I,dilations:[P,H],kernel_shape:[J,he],pads:[oe,ye,Le,He],strides:[W,Ae]})},833758:(c,_)=>{p.ob("GlobalAveragePool",c,{format:_?"NHWC":"NCHW"})},833849:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W,Ae,Ne)=>{p.ob("AveragePool",c,{format:Ne?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:k,storage_order:I,dilations:[P,H],kernel_shape:[J,he],pads:[oe,ye,Le,He],strides:[W,Ae]})},834133:(c,_)=>{p.ob("GlobalMaxPool",c,{format:_?"NHWC":"NCHW"})},834220:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W,Ae,Ne)=>{p.ob("MaxPool",c,{format:Ne?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:k,storage_order:I,dilations:[P,H],kernel_shape:[J,he],pads:[oe,ye,Le,He],strides:[W,Ae]})},834500:(c,_)=>{p.ob("GlobalMaxPool",c,{format:_?"NHWC":"NCHW"})},834587:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W,Ae,Ne)=>{p.ob("MaxPool",c,{format:Ne?"NHWC":"NCHW",auto_pad:_,ceil_mode:b,count_include_pad:k,storage_order:I,dilations:[P,H],kernel_shape:[J,he],pads:[oe,ye,Le,He],strides:[W,Ae]})},834867:(c,_,b,k,I)=>{p.ob("Gemm",c,{alpha:_,beta:b,transA:k,transB:I})},834971:c=>{p.ob("MatMul",c,void 0)},835025:(c,_,b,k)=>{p.ob("ArgMax",c,{keepDims:!!_,selectLastIndex:!!b,axis:k})},835133:(c,_,b,k)=>{p.ob("ArgMin",c,{keepDims:!!_,selectLastIndex:!!b,axis:k})},835241:(c,_)=>{p.ob("Softmax",c,{axis:_})},835304:(c,_)=>{p.ob("Concat",c,{axis:_})},835364:(c,_,b,k,I)=>{p.ob("Split",c,{axis:_,numOutputs:b,splitSizes:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},835504:c=>{p.ob("Expand",c,void 0)},835558:(c,_)=>{p.ob("Gather",c,{axis:Number(_)})},835629:(c,_)=>{p.ob("GatherElements",c,{axis:Number(_)})},835708:(c,_,b,k,I,P,H,J,he,oe,ye)=>{p.ob("Resize",c,{antialias:_,axes:b?Array.from(d().subarray(b>>>0,k>>>0)):[],coordinateTransformMode:lt(I),cubicCoeffA:P,excludeOutside:H,extrapolationValue:J,keepAspectRatioPolicy:lt(he),mode:lt(oe),nearestMode:lt(ye)})},836054:(c,_,b,k,I,P,H)=>{p.ob("Slice",c,{starts:_?Array.from(d().subarray(_>>>0,b>>>0)):[],ends:k?Array.from(d().subarray(k>>>0,I>>>0)):[],axes:P?Array.from(d().subarray(P>>>0,H>>>0)):[]})},836270:c=>{p.ob("Tile",c,void 0)},836322:(c,_,b,k)=>{p.ob("LayerNormalization",c,{axis:_,epsilon:b,simplified:!!k})},836433:(c,_,b)=>{p.ob("InstanceNormalization",c,{epsilon:_,format:b?"NHWC":"NCHW"})},836547:(c,_,b)=>{p.ob("InstanceNormalization",c,{epsilon:_,format:b?"NHWC":"NCHW"})},836661:c=>{p.ob("Range",c,void 0)},836714:(c,_)=>{p.ob("Einsum",c,{equation:lt(_)})},836795:(c,_,b,k,I)=>{p.ob("Pad",c,{mode:_,value:b,pads:k?Array.from(d().subarray(k>>>0,I>>>0)):[]})},836922:(c,_,b,k,I,P)=>{p.ob("BatchNormalization",c,{epsilon:_,momentum:b,spatial:!!I,trainingMode:!!k,format:P?"NHWC":"NCHW"})},837091:(c,_,b,k,I,P)=>{p.ob("BatchNormalization",c,{epsilon:_,momentum:b,spatial:!!I,trainingMode:!!k,format:P?"NHWC":"NCHW"})},837260:(c,_,b)=>{p.ob("CumSum",c,{exclusive:Number(_),reverse:Number(b)})},837357:(c,_,b,k,I,P,H,J,he)=>{p.ob("Attention",c,{numHeads:_,isUnidirectional:b,maskFilterValue:k,scale:I,doRotary:P,qkvHiddenSizes:H?Array.from(d().subarray(Number(J)>>>0,Number(J)+H>>>0)):[],pastPresentShareBuffer:!!he})},837629:c=>{p.ob("BiasAdd",c,void 0)},837684:c=>{p.ob("BiasSplitGelu",c,void 0)},837745:c=>{p.ob("FastGelu",c,void 0)},837801:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He)=>{p.ob("Conv",c,{format:he?"NHWC":"NCHW",auto_pad:_,dilations:[b],group:k,kernel_shape:[I],pads:P?Array.from(d().subarray(P>>>0,H>>>0)):[],strides:[J],w_is_const:()=>!!i()[oe>>>0],activation:lt(ye),activation_params:Le?Array.from(m().subarray(Le>>>0,He>>>0)):[]})},838171:(c,_,b,k,I,P,H,J,he,oe,ye,Le,He,W,Ae,Ne)=>{p.ob("Conv",c,{format:Le?"NHWC":"NCHW",auto_pad:_,dilations:[b,k],group:I,kernel_shape:[P,H],pads:J?Array.from(d().subarray(J>>>0,he>>>0)):[],strides:[oe,ye],w_is_const:()=>!!i()[He>>>0],activation:lt(W),activation_params:Ae?Array.from(m().subarray(Ae>>>0,Ne>>>0)):[]})},838562:c=>{p.ob("Gelu",c,void 0)},838614:(c,_,b,k,I,P)=>{p.ob("MatMulNBits",c,{k:_,n:b,accuracyLevel:k,bits:I,blockSize:P})},838741:(c,_,b,k,I,P)=>{p.ob("MultiHeadAttention",c,{numHeads:_,isUnidirectional:b,maskFilterValue:k,scale:I,doRotary:P})},838900:(c,_,b,k,I)=>{p.ob("RotaryEmbedding",c,{interleaved:!!_,numHeads:b,rotaryEmbeddingDim:k,scale:I})},839039:(c,_,b)=>{p.ob("SkipLayerNormalization",c,{epsilon:_,simplified:!!b})},839141:(c,_,b)=>{p.ob("SkipLayerNormalization",c,{epsilon:_,simplified:!!b})},839243:(c,_,b,k)=>{p.ob("LayerNormalization",c,{axis:_,epsilon:b,simplified:!!k})},839354:c=>{p.ac(c)},839388:(c,_)=>p.cc(c,_,p.Cb.ec,p.Cb.errors)};function Bt(c){this.name="ExitStatus",this.message=`Program terminated with exit(${c})`,this.status=c}var Fn=c=>{c.terminate(),c.onmessage=()=>{}},Ln=c=>{ve.xb.length==0&&(ts(),ve.Mb(ve.xb[0]));var _=ve.xb.pop();if(!_)return 6;ve.yb.push(_),ve.ub[c.wb]=_,_.wb=c.wb;var b={cmd:"run",start_routine:c.fc,arg:c.Rb,pthread_ptr:c.wb};return V&&_.unref(),_.postMessage(b,c.mc),0},ft=0,Fa=c=>{var _=El();return c=c(),vs(_),c},ze=(c,_,...b)=>Fa(()=>{for(var k=2*b.length,I=kl(8*k),P=I>>>3,H=0;H>>0]=J)}return k0(c,0,k,I,_)});function Dt(c){var _;if(j)return ze(0,1,c);Se=c,0{if(Se=c,j)throw ns(c),"unwind";Dt(c)};function fl(){for(var c=p.numThreads;c--;)ts();Ir.unshift(()=>{Mr++,rs(()=>Ba())})}function ts(){var c=fe("ort-wasm-simd-threaded.worker.js");c=new Worker(c),ve.xb.push(c)}function rs(c){j?c():Promise.all(ve.xb.map(ve.Mb)).then(c)}var ve={xb:[],yb:[],Qb:[],ub:{},Gb(){j?(ve.receiveObjectTransfer=ve.dc,ve.threadInitTLS=ve.Pb,ve.setExitStatus=ve.Ob):fl()},Ob:c=>Se=c,pc:["$terminateWorker"],hc:()=>{for(var c of ve.yb)Fn(c);for(c of ve.xb)Fn(c);ve.xb=[],ve.yb=[],ve.ub=[]},Nb:c=>{var _=c.wb;delete ve.ub[_],ve.xb.push(c),ve.yb.splice(ve.yb.indexOf(c),1),c.wb=0,xl(_)},dc(){},Pb(){ve.Qb.forEach(c=>c())},Mb:c=>new Promise(_=>{c.onmessage=P=>{P=P.data;var H=P.cmd;if(P.targetThread&&P.targetThread!=ws()){var J=ve.ub[P.targetThread];J?J.postMessage(P,P.transferList):le(`Internal error! Worker sent a message "${H}" to target pthread ${P.targetThread}, but that thread no longer exists!`)}else H==="checkMailbox"?It():H==="spawnThread"?Ln(P):H==="cleanupThread"?ve.Nb(ve.ub[P.thread]):H==="killThread"?(P=P.thread,H=ve.ub[P],delete ve.ub[P],Fn(H),xl(P),ve.yb.splice(ve.yb.indexOf(H),1),H.wb=0):H==="cancelThread"?ve.ub[P.thread].postMessage({cmd:"cancel"}):H==="loaded"?(c.loaded=!0,V&&!c.wb&&c.unref(),_(c)):H==="alert"?alert(`Thread ${P.threadId}: ${P.text}`):P.target==="setimmediate"?c.postMessage(P):H==="callHandler"?p[P.handler](...P.args):H&&le(`worker sent an unknown command ${H}`)},c.onerror=P=>{throw le(`worker sent an error! ${P.filename}:${P.lineno}: ${P.message}`),P},V&&(c.on("message",P=>c.onmessage({data:P})),c.on("error",P=>c.onerror(P)));var b=[],k=["onExit"],I;for(I of k)p.hasOwnProperty(I)&&b.push(I);c.postMessage({cmd:"load",handlers:b,urlOrBlob:p.mainScriptUrlOrBlob||n,wasmMemory:N,wasmModule:ae})})};p.PThread=ve;var Un=c=>{for(;0{var c=ws(),_=h()[c+52>>>2>>>0];c=h()[c+56>>>2>>>0],C0(_,_-c),vs(_)};function ns(c){if(j)return ze(1,0,c);hn(c)}p.invokeEntryPoint=(c,_)=>{ft=0,c=T0(c,_),0>>2>>>0]=0,h()[this.Ib+4>>>2>>>0]=_,h()[this.Ib+8>>>2>>>0]=b}}var as=0;function is(c,_,b,k){return j?ze(2,1,c,_,b,k):Wn(c,_,b,k)}function Wn(c,_,b,k){if(c>>>=0,_>>>=0,b>>>=0,k>>>=0,typeof SharedArrayBuffer>"u")return le("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var I=[];return j&&I.length===0?is(c,_,b,k):(c={fc:b,wb:c,Rb:k,mc:I},j?(c.oc="spawnThread",postMessage(c,I),0):Ln(c))}var La=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,fn=(c,_,b)=>{_>>>=0;var k=_+b;for(b=_;c[b]&&!(b>=k);)++b;if(16I?k+=String.fromCharCode(I):(I-=65536,k+=String.fromCharCode(55296|I>>10,56320|I&1023))}}else k+=String.fromCharCode(I)}return k},lt=(c,_)=>(c>>>=0)?fn(o(),c,_):"";function ss(c,_,b){return j?ze(3,1,c,_,b):0}function cr(c,_){if(j)return ze(4,1,c,_)}var Nt=c=>{for(var _=0,b=0;b=k?_++:2047>=k?_+=2:55296<=k&&57343>=k?(_+=4,++b):_+=3}return _},Ua=(c,_,b,k)=>{if(b>>>=0,!(0=H){var J=c.charCodeAt(++P);H=65536+((H&1023)<<10)|J&1023}if(127>=H){if(b>=k)break;_[b++>>>0]=H}else{if(2047>=H){if(b+1>=k)break;_[b++>>>0]=192|H>>6}else{if(65535>=H){if(b+2>=k)break;_[b++>>>0]=224|H>>12}else{if(b+3>=k)break;_[b++>>>0]=240|H>>18,_[b++>>>0]=128|H>>12&63}_[b++>>>0]=128|H>>6&63}_[b++>>>0]=128|H&63}}return _[b>>>0]=0,b-I},pr=(c,_,b)=>Ua(c,o(),_,b);function Wa(c,_){if(j)return ze(5,1,c,_)}function Va(c,_,b){if(j)return ze(6,1,c,_,b)}function os(c,_,b){return j?ze(7,1,c,_,b):0}function Vn(c,_){if(j)return ze(8,1,c,_)}function ls(c,_,b){if(j)return ze(9,1,c,_,b)}function us(c,_,b,k){if(j)return ze(10,1,c,_,b,k)}function ds(c,_,b,k){if(j)return ze(11,1,c,_,b,k)}function cs(c,_,b,k){if(j)return ze(12,1,c,_,b,k)}function Ga(c){if(j)return ze(13,1,c)}function mn(c,_){if(j)return ze(14,1,c,_)}function ps(c,_,b){if(j)return ze(15,1,c,_,b)}var Gn,Gt=c=>{for(var _="";o()[c>>>0];)_+=Gn[o()[c++>>>0]];return _},Ha={},ja={},hr;function gl(c,_,b={}){var k=_.name;if(!c)throw new hr(`type "${k}" must have a positive integer typeid pointer`);if(ja.hasOwnProperty(c)){if(b.Ub)return;throw new hr(`Cannot register type '${k}' twice`)}ja[c]=_,Ha.hasOwnProperty(c)&&(_=Ha[c],delete Ha[c],_.forEach(I=>I()))}function St(c,_,b={}){if(!("argPackAdvance"in _))throw new TypeError("registerType registeredInstance requires argPackAdvance");return gl(c,_,b)}var qa=(c,_,b)=>{switch(_){case 1:return b?k=>i()[k>>>0]:k=>o()[k>>>0];case 2:return b?k=>l()[k>>>1>>>0]:k=>u()[k>>>1>>>0];case 4:return b?k=>d()[k>>>2>>>0]:k=>h()[k>>>2>>>0];case 8:return b?k=>We[k>>>3]:k=>Ze[k>>>3];default:throw new TypeError(`invalid integer width (${_}): ${c}`)}},Hn=[],Ht=[];function jn(c){c>>>=0,9{if(!c)throw new hr("Cannot use deleted val. handle = "+c);return Ht[c]},Ft=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let _=Hn.pop()||Ht.length;return Ht[_]=c,Ht[_+1]=1,_}};function gn(c){return this.fromWireType(h()[c>>>2>>>0])}var _l={name:"emscripten::val",fromWireType:c=>{var _=mt(c);return jn(c),_},toWireType:(c,_)=>Ft(_),argPackAdvance:8,readValueFromPointer:gn,Bb:null},hs=(c,_)=>{switch(_){case 4:return function(b){return this.fromWireType(m()[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(g()[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${_}): ${c}`)}},Ka=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,yl=(c,_)=>{for(var b=c>>1,k=b+_/2;!(b>=k)&&u()[b>>>0];)++b;if(b<<=1,32=_/2);++k){var I=l()[c+2*k>>>1>>>0];if(I==0)break;b+=String.fromCharCode(I)}return b},fs=(c,_,b)=>{if(b??(b=2147483647),2>b)return 0;b-=2;var k=_;b=b<2*c.length?b/2:c.length;for(var I=0;I>>1>>>0]=P,_+=2}return l()[_>>>1>>>0]=0,_-k},ms=c=>2*c.length,qn=(c,_)=>{for(var b=0,k="";!(b>=_/4);){var I=d()[c+4*b>>>2>>>0];if(I==0)break;++b,65536<=I?(I-=65536,k+=String.fromCharCode(55296|I>>10,56320|I&1023)):k+=String.fromCharCode(I)}return k},wl=(c,_,b)=>{if(_>>>=0,b??(b=2147483647),4>b)return 0;var k=_;b=k+b-4;for(var I=0;I=P){var H=c.charCodeAt(++I);P=65536+((P&1023)<<10)|H&1023}if(d()[_>>>2>>>0]=P,_+=4,_+4>b)break}return d()[_>>>2>>>0]=0,_-k},be=c=>{for(var _=0,b=0;b=k&&++b,_+=4}return _},Ya=c=>{if(!de)try{if(c(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(d(),c>>>2,c).value.then(It),c+=128,Atomics.store(d(),c>>>2,1))}p.__emscripten_thread_mailbox_await=Gr;var It=()=>{var c=ws();c&&(Gr(c),Ya(E0))};p.checkMailbox=It;var Kn=[],Yn=(c,_)=>{var b=ja[c];if(b===void 0)throw c=x0(c),b=Gt(c),br(c),new hr(`${_} has unknown type ${b}`);return b},Xa=(c,_,b)=>{var k=[];return c=c.toWireType(k,b),k.length&&(h()[_>>>2>>>0]=Ft(k)),c},_n=c=>{try{c()}catch(_){Je(_)}};function gs(){var c=me,_={};for(let[b,k]of Object.entries(c))_[b]=typeof k=="function"?(...I)=>{Or.push(b);try{return k(...I)}finally{de||(Or.pop(),jt&&fr===1&&Or.length===0&&(fr=0,ft+=1,_n(I0),typeof Fibers<"u"&&Fibers.rc()))}}:k;return _}var fr=0,jt=null,_s=0,Or=[],Qa={},f={},y=0,x=null,C=[];function O(){return new Promise((c,_)=>{x={resolve:c,reject:_}})}function F(){var c=bs(65548),_=c+12;h()[c>>>2>>>0]=_,h()[c+4>>>2>>>0]=_+65536,_=Or[0];var b=Qa[_];return b===void 0&&(b=y++,Qa[_]=b,f[b]=_),_=b,d()[c+8>>>2>>>0]=_,c}function Y(){var c=d()[jt+8>>>2>>>0];return c=me[f[c]],--ft,c()}function re(c){if(!de){if(fr===0){var _=!1,b=!1;c((k=0)=>{if(!de&&(_s=k,_=!0,b)){fr=2,_n(()=>M0(jt)),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.resume(),k=!1;try{var I=Y()}catch(J){I=J,k=!0}var P=!1;if(!jt){var H=x;H&&(x=null,(k?H.reject:H.resolve)(I),P=!0)}if(k&&!P)throw I}}),b=!0,_||(fr=1,jt=F(),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.pause(),_n(()=>A0(jt)))}else fr===2?(fr=0,_n(O0),br(jt),jt=null,C.forEach(Ya)):Je(`invalid state: ${fr}`);return _s}}function ue(c){return re(_=>{c().then(_)})}var ie=[],ge={},Be=c=>{var _=ge[c];return _===void 0?Gt(c):_},Fe=()=>typeof globalThis=="object"?globalThis:Function("return this")(),L=c=>{var _=ie.length;return ie.push(c),_},Ee=(c,_)=>{for(var b=Array(c),k=0;k>>2>>>0],"parameter "+k);return b},Pe=(c,_)=>Object.defineProperty(_,"name",{value:c});function zr(c){var _=Function;if(!(_ instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof _} which is not a function`);var b=Pe(_.name||"unknownFunctionName",function(){});return b.prototype=_.prototype,b=new b,c=_.apply(b,c),c instanceof Object?c:b}var Pr=c=>c%4===0&&(c%100!==0||c%400===0),o0=[0,31,60,91,121,152,182,213,244,274,305,335],l0=[0,31,59,90,120,151,181,212,243,273,304,334];function u0(c,_,b,k,I,P,H){return j?ze(16,1,c,_,b,k,I,P,H):-52}function d0(c,_,b,k,I,P){if(j)return ze(17,1,c,_,b,k,I,P)}var bl=[],c0=(c,_)=>{bl.length=0;for(var b;b=o()[c++>>>0];){var k=b!=105;k&=b!=112,_+=k&&_%8?4:0,bl.push(b==112?h()[_>>>2>>>0]:b==106?We[_>>>3]:b==105?d()[_>>>2>>>0]:g()[_>>>3>>>0]),_+=k?8:4}return bl},vl={},p0=()=>{if(!$l){var c={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:T||"./this.program"},_;for(_ in vl)vl[_]===void 0?delete c[_]:c[_]=vl[_];var b=[];for(_ in c)b.push(`${_}=${c[_]}`);$l=b}return $l},$l;function h0(c,_){if(j)return ze(18,1,c,_);c>>>=0,_>>>=0;var b=0;return p0().forEach((k,I)=>{var P=_+b;for(I=h()[c+4*I>>>2>>>0]=P,P=0;P>>0]=k.charCodeAt(P);i()[I>>>0]=0,b+=k.length+1}),0}function f0(c,_){if(j)return ze(19,1,c,_);c>>>=0,_>>>=0;var b=p0();h()[c>>>2>>>0]=b.length;var k=0;return b.forEach(I=>k+=I.length+1),h()[_>>>2>>>0]=k,0}function m0(c){return j?ze(20,1,c):52}function g0(c,_,b,k){return j?ze(21,1,c,_,b,k):52}function _0(c,_,b,k){return j?ze(22,1,c,_,b,k):70}var K3=[null,[],[]];function y0(c,_,b,k){if(j)return ze(23,1,c,_,b,k);_>>>=0,b>>>=0,k>>>=0;for(var I=0,P=0;P>>2>>>0],J=h()[_+4>>>2>>>0];_+=8;for(var he=0;he>>0],ye=K3[c];oe===0||oe===10?((c===1?pe:le)(fn(ye,0)),ye.length=0):ye.push(oe)}I+=J}return h()[k>>>2>>>0]=I,0}var w0=[31,29,31,30,31,30,31,31,30,31,30,31],b0=[31,28,31,30,31,30,31,31,30,31,30,31];function Y3(c){var _=Array(Nt(c)+1);return Ua(c,_,0,_.length),_}var X3=(c,_)=>{i().set(c,_>>>0)};function v0(c,_,b,k){function I(W,Ae,Ne){for(W=typeof W=="number"?W.toString():W||"";W.lengthP0?-1:0yn-W.getDate())Ae-=yn-W.getDate()+1,W.setDate(1),11>Ne?W.setMonth(Ne+1):(W.setMonth(0),W.setFullYear(W.getFullYear()+1));else{W.setDate(W.getDate()+Ae);break}}return Ne=new Date(W.getFullYear()+1,0,4),Ae=J(new Date(W.getFullYear(),0,4)),Ne=J(Ne),0>=H(Ae,W)?0>=H(Ne,W)?W.getFullYear()+1:W.getFullYear():W.getFullYear()-1}c>>>=0,_>>>=0,b>>>=0,k>>>=0;var oe=h()[k+40>>>2>>>0];k={kc:d()[k>>>2>>>0],jc:d()[k+4>>>2>>>0],Eb:d()[k+8>>>2>>>0],Jb:d()[k+12>>>2>>>0],Fb:d()[k+16>>>2>>>0],Ab:d()[k+20>>>2>>>0],vb:d()[k+24>>>2>>>0],zb:d()[k+28>>>2>>>0],qc:d()[k+32>>>2>>>0],ic:d()[k+36>>>2>>>0],lc:oe?lt(oe):""},b=lt(b),oe={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var ye in oe)b=b.replace(new RegExp(ye,"g"),oe[ye]);var Le="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),He="January February March April May June July August September October November December".split(" ");oe={"%a":W=>Le[W.vb].substring(0,3),"%A":W=>Le[W.vb],"%b":W=>He[W.Fb].substring(0,3),"%B":W=>He[W.Fb],"%C":W=>P((W.Ab+1900)/100|0,2),"%d":W=>P(W.Jb,2),"%e":W=>I(W.Jb,2," "),"%g":W=>he(W).toString().substring(2),"%G":he,"%H":W=>P(W.Eb,2),"%I":W=>(W=W.Eb,W==0?W=12:12{for(var Ae=0,Ne=0;Ne<=W.Fb-1;Ae+=(Pr(W.Ab+1900)?w0:b0)[Ne++]);return P(W.Jb+Ae,3)},"%m":W=>P(W.Fb+1,2),"%M":W=>P(W.jc,2),"%n":()=>` `,"%p":W=>0<=W.Eb&&12>W.Eb?"AM":"PM","%S":W=>P(W.kc,2),"%t":()=>" ","%u":W=>W.vb||7,"%U":W=>P(Math.floor((W.zb+7-W.vb)/7),2),"%V":W=>{var Ae=Math.floor((W.zb+7-(W.vb+6)%7)/7);if(2>=(W.vb+371-W.zb-2)%7&&Ae++,Ae)Ae==53&&(Ne=(W.vb+371-W.zb)%7,Ne==4||Ne==3&&Pr(W.Ab)||(Ae=1));else{Ae=52;var Ne=(W.vb+7-W.zb-1)%7;(Ne==4||Ne==5&&Pr(W.Ab%400-1))&&Ae++}return P(Ae,2)},"%w":W=>W.vb,"%W":W=>P(Math.floor((W.zb+7-(W.vb+6)%7)/7),2),"%y":W=>(W.Ab+1900).toString().substring(2),"%Y":W=>W.Ab+1900,"%z":W=>{W=W.ic;var Ae=0<=W;return W=Math.abs(W)/60,(Ae?"+":"-")+("0000"+(W/60*100+W%60)).slice(-4)},"%Z":W=>W.lc,"%%":()=>"%"},b=b.replace(/%%/g,"\0\0");for(ye in oe)b.includes(ye)&&(b=b.replace(new RegExp(ye,"g"),oe[ye](k)));return b=b.replace(/\0\0/g,"%"),ye=Y3(b),ye.length>_?0:(X3(ye,c),ye.length-1)}ve.Gb();for(var $0=Array(256),ys=0;256>ys;++ys)$0[ys]=String.fromCharCode(ys);Gn=$0,hr=p.BindingError=class extends Error{constructor(c){super(c),this.name="BindingError"}},p.InternalError=class extends Error{constructor(c){super(c),this.name="InternalError"}},Ht.push(0,1,void 0,1,null,1,!0,1,!1,1),p.count_emval_handles=()=>Ht.length/2-5-Hn.length;var Q3=[Dt,ns,is,ss,cr,Wa,Va,os,Vn,ls,us,ds,cs,Ga,mn,ps,u0,d0,h0,f0,m0,g0,_0,y0],Z3={ua:function(c,_,b){return ue(async()=>{await p.Zb(c,_,b)})},b:function(c,_,b){throw c>>>=0,new ml(c).Gb(_>>>0,b>>>0),as=c,as},ia:function(c){S0(c>>>0,!R,1,!z,131072,!1),ve.Pb()},G:function(c){c>>>=0,j?postMessage({cmd:"cleanupThread",thread:c}):ve.Nb(ve.ub[c])},_:Wn,A:ss,pa:cr,W:Wa,Y:Va,qa:os,na:Vn,fa:ls,ma:us,K:ds,X:cs,U:Ga,oa:mn,V:ps,E:function(c,_,b){c>>>=0,b>>>=0,_=Gt(_>>>0),St(c,{name:_,fromWireType:k=>k,toWireType:function(k,I){if(typeof I!="bigint"&&typeof I!="number")throw I===null?I="null":(k=typeof I,I=k==="object"||k==="array"||k==="function"?I.toString():""+I),new TypeError(`Cannot convert "${I}" to ${this.name}`);return typeof I=="number"&&(I=BigInt(I)),I},argPackAdvance:8,readValueFromPointer:qa(_,b,_.indexOf("u")==-1),Bb:null})},O:function(c,_,b,k){c>>>=0,_=Gt(_>>>0),St(c,{name:_,fromWireType:function(I){return!!I},toWireType:function(I,P){return P?b:k},argPackAdvance:8,readValueFromPointer:function(I){return this.fromWireType(o()[I>>>0])},Bb:null})},N:function(c){return St(c>>>0,_l)},D:function(c,_,b){c>>>=0,b>>>=0,_=Gt(_>>>0),St(c,{name:_,fromWireType:k=>k,toWireType:(k,I)=>I,argPackAdvance:8,readValueFromPointer:hs(_,b),Bb:null})},t:function(c,_,b,k,I){if(c>>>=0,b>>>=0,_=Gt(_>>>0),I===-1&&(I=4294967295),I=J=>J,k===0){var P=32-8*b;I=J=>J<

>>P}var H=_.includes("unsigned")?function(J,he){return he>>>0}:function(J,he){return he};St(c,{name:_,fromWireType:I,toWireType:H,argPackAdvance:8,readValueFromPointer:qa(_,b,k!==0),Bb:null})},p:function(c,_,b){function k(P){var H=h()[P>>>2>>>0];return P=h()[P+4>>>2>>>0],new I(i().buffer,P,H)}c>>>=0;var I=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][_];b=Gt(b>>>0),St(c,{name:b,fromWireType:k,argPackAdvance:8,readValueFromPointer:k},{Ub:!0})},F:function(c,_){c>>>=0,_=Gt(_>>>0);var b=_==="std::string";St(c,{name:_,fromWireType:function(k){var I=h()[k>>>2>>>0],P=k+4;if(b)for(var H=P,J=0;J<=I;++J){var he=P+J;if(J==I||o()[he>>>0]==0){if(H=lt(H,he-H),oe===void 0)var oe=H;else oe+="\0",oe+=H;H=he+1}}else{for(oe=Array(I),J=0;J>>0]);oe=oe.join("")}return br(k),oe},toWireType:function(k,I){I instanceof ArrayBuffer&&(I=new Uint8Array(I));var P=typeof I=="string";if(!(P||I instanceof Uint8Array||I instanceof Uint8ClampedArray||I instanceof Int8Array))throw new hr("Cannot pass non-string to std::string");var H=b&&P?Nt(I):I.length,J=bs(4+H+1),he=J+4;if(h()[J>>>2>>>0]=H,b&&P)pr(I,he,H+1);else if(P)for(P=0;P>>0]=oe}else for(P=0;P>>0]=I[P];return k!==null&&k.push(br,J),J},argPackAdvance:8,readValueFromPointer:gn,Bb(k){br(k)}})},z:function(c,_,b){if(c>>>=0,_>>>=0,b>>>=0,b=Gt(b),_===2)var k=yl,I=fs,P=ms,H=J=>u()[J>>>1>>>0];else _===4&&(k=qn,I=wl,P=be,H=J=>h()[J>>>2>>>0]);St(c,{name:b,fromWireType:J=>{for(var he=h()[J>>>2>>>0],oe,ye=J+4,Le=0;Le<=he;++Le){var He=J+4+Le*_;(Le==he||H(He)==0)&&(ye=k(ye,He-ye),oe===void 0?oe=ye:(oe+="\0",oe+=ye),ye=He+_)}return br(J),oe},toWireType:(J,he)=>{if(typeof he!="string")throw new hr(`Cannot pass non-string to C++ string type ${b}`);var oe=P(he),ye=bs(4+oe+_);return h()[ye>>>2>>>0]=oe/_,I(he,ye+4,oe+_),J!==null&&J.push(br,ye),ye},argPackAdvance:8,readValueFromPointer:gn,Bb(J){br(J)}})},P:function(c,_){c>>>=0,_=Gt(_>>>0),St(c,{Vb:!0,name:_,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ta:()=>1,S:function(c,_){c>>>=0,c==_>>>0?setTimeout(It):j?postMessage({targetThread:c,cmd:"checkMailbox"}):(c=ve.ub[c])&&c.postMessage({cmd:"checkMailbox"})},$:function(c,_,b,k,I){_>>>=0,b>>>=0,k/=2,Kn.length=k,I=I>>>0>>>3;for(var P=0;P>>0];return c=_?Na[_]:Q3[c],ve.Sb=b,b=c(...Kn),ve.Sb=0,b},ha:Gr,sa:function(c){V&&ve.ub[c>>>0].ref()},w:function(c,_,b){return _>>>=0,b>>>=0,c=mt(c>>>0),_=Yn(_,"emval::as"),Xa(_,b,c)},y:function(c){return c>>>=0,ue(()=>(c=mt(c),c.then(Ft)))},o:function(c,_,b,k){return b>>>=0,k>>>=0,c=ie[c>>>0],_=mt(_>>>0),c(null,_,b,k)},k:function(c,_,b,k,I){return b>>>=0,k>>>=0,I>>>=0,c=ie[c>>>0],_=mt(_>>>0),b=Be(b),c(_,_[b],k,I)},c:jn,C:function(c,_){return _>>>=0,c=mt(c>>>0),_=mt(_),c==_},n:function(c){return c>>>=0,c===0?Ft(Fe()):(c=Be(c),Ft(Fe()[c]))},j:function(c,_,b){_=Ee(c,_>>>0);var k=_.shift();c--;var I=`return function (obj, func, destructorsRef, args) { `,P=0,H=[];b===0&&H.push("obj");for(var J=["retType"],he=[k],oe=0;oeye.name).join(", ")}) => ${k.name}>`,L(Pe(b,c))},s:function(c,_){return _>>>=0,c=mt(c>>>0),_=mt(_),Ft(c[_])},d:function(c){c>>>=0,9>>0);for(var _=Array(c.length),b=0;b>>0))},l:function(){return Ft({})},i:function(c){c>>>=0;for(var _=mt(c);_.length;){var b=_.pop();_.pop()(b)}jn(c)},h:function(c,_,b){_>>>=0,b>>>=0,c=mt(c>>>0),_=mt(_),b=mt(b),c[_]=b},e:function(c,_){return _>>>=0,c=Yn(c>>>0,"_emval_take_value"),c=c.readValueFromPointer(_),Ft(c)},ca:function(c,_){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),d()[_>>>2>>>0]=c.getUTCSeconds(),d()[_+4>>>2>>>0]=c.getUTCMinutes(),d()[_+8>>>2>>>0]=c.getUTCHours(),d()[_+12>>>2>>>0]=c.getUTCDate(),d()[_+16>>>2>>>0]=c.getUTCMonth(),d()[_+20>>>2>>>0]=c.getUTCFullYear()-1900,d()[_+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,d()[_+28>>>2>>>0]=c},da:function(c,_){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),d()[_>>>2>>>0]=c.getSeconds(),d()[_+4>>>2>>>0]=c.getMinutes(),d()[_+8>>>2>>>0]=c.getHours(),d()[_+12>>>2>>>0]=c.getDate(),d()[_+16>>>2>>>0]=c.getMonth(),d()[_+20>>>2>>>0]=c.getFullYear()-1900,d()[_+24>>>2>>>0]=c.getDay();var b=(Pr(c.getFullYear())?o0:l0)[c.getMonth()]+c.getDate()-1|0;d()[_+28>>>2>>>0]=b,d()[_+36>>>2>>>0]=-(60*c.getTimezoneOffset()),b=new Date(c.getFullYear(),6,1).getTimezoneOffset();var k=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=(b!=k&&c.getTimezoneOffset()==Math.min(k,b))|0,d()[_+32>>>2>>>0]=c},ea:function(c){c>>>=0;var _=new Date(d()[c+20>>>2>>>0]+1900,d()[c+16>>>2>>>0],d()[c+12>>>2>>>0],d()[c+8>>>2>>>0],d()[c+4>>>2>>>0],d()[c>>>2>>>0],0),b=d()[c+32>>>2>>>0],k=_.getTimezoneOffset(),I=new Date(_.getFullYear(),6,1).getTimezoneOffset(),P=new Date(_.getFullYear(),0,1).getTimezoneOffset(),H=Math.min(P,I);return 0>b?d()[c+32>>>2>>>0]=+(I!=P&&H==k):0>>2>>>0]=_.getDay(),b=(Pr(_.getFullYear())?o0:l0)[_.getMonth()]+_.getDate()-1|0,d()[c+28>>>2>>>0]=b,d()[c>>>2>>>0]=_.getSeconds(),d()[c+4>>>2>>>0]=_.getMinutes(),d()[c+8>>>2>>>0]=_.getHours(),d()[c+12>>>2>>>0]=_.getDate(),d()[c+16>>>2>>>0]=_.getMonth(),d()[c+20>>>2>>>0]=_.getYear(),c=_.getTime(),BigInt(isNaN(c)?-1:c/1e3)},aa:u0,ba:d0,R:function(c,_,b,k){c>>>=0,_>>>=0,b>>>=0,k>>>=0;var I=new Date().getFullYear(),P=new Date(I,0,1),H=new Date(I,6,1);I=P.getTimezoneOffset();var J=H.getTimezoneOffset(),he=Math.max(I,J);h()[c>>>2>>>0]=60*he,d()[_>>>2>>>0]=+(I!=J),c=oe=>oe.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],P=c(P),H=c(H),J{Je("")},f:function(c,_,b){return c>>>=0,_=c0(_>>>0,b>>>0),Na[c](..._)},M:function(c,_,b){return c>>>=0,_=c0(_>>>0,b>>>0),Na[c](..._)},H:()=>{},L:()=>Date.now(),ra:()=>{throw ft+=1,"unwind"},T:function(){return 4294901760},u:()=>performance.timeOrigin+performance.now(),x:()=>V?(Ey(),jr(lu)).cpus().length:navigator.hardwareConcurrency,Q:function(c){c>>>=0;var _=o().length;if(c<=_||4294901760=b;b*=2){var k=_*(1+.2/b);k=Math.min(k,c+100663296);var I=Math;k=Math.max(c,k);e:{I=(I.min.call(I,4294901760,k+(65536-k%65536)%65536)-N.buffer.byteLength+65535)/65536;try{N.grow(I),dt();var P=1;break e}catch{}P=void 0}if(P)return!0}return!1},ja:h0,la:f0,Z:hn,B:m0,J:g0,ga:_0,I:y0,a:N||p.wasmMemory,ka:v0,r:function(c,_,b,k){return v0(c>>>0,_>>>0,b>>>0,k>>>0)}},me=function(){function c(b,k){return me=b.exports,me=gs(),me=J3(),ve.Qb.push(me.cb),pn.unshift(me.va),ae=k,Ba(),me}var _={a:Z3};if(Mr++,p.instantiateWasm)try{return p.instantiateWasm(_,c)}catch(b){le(`Module.instantiateWasm callback failed with error: ${b}`),v(b)}return wr(_,function(b){c(b.instance,b.module)}).catch(v),{}}(),x0=c=>(x0=me.wa)(c);p.__embind_initialize_bindings=()=>(p.__embind_initialize_bindings=me.xa)(),p._OrtInit=(c,_)=>(p._OrtInit=me.ya)(c,_),p._OrtGetLastError=(c,_)=>(p._OrtGetLastError=me.za)(c,_),p._OrtCreateSessionOptions=(c,_,b,k,I,P,H,J,he,oe)=>(p._OrtCreateSessionOptions=me.Aa)(c,_,b,k,I,P,H,J,he,oe),p._OrtAppendExecutionProvider=(c,_)=>(p._OrtAppendExecutionProvider=me.Ba)(c,_),p._OrtAddFreeDimensionOverride=(c,_,b)=>(p._OrtAddFreeDimensionOverride=me.Ca)(c,_,b),p._OrtAddSessionConfigEntry=(c,_,b)=>(p._OrtAddSessionConfigEntry=me.Da)(c,_,b),p._OrtReleaseSessionOptions=c=>(p._OrtReleaseSessionOptions=me.Ea)(c),p._OrtCreateSession=(c,_,b)=>(p._OrtCreateSession=me.Fa)(c,_,b),p._OrtReleaseSession=c=>(p._OrtReleaseSession=me.Ga)(c),p._OrtGetInputOutputCount=(c,_,b)=>(p._OrtGetInputOutputCount=me.Ha)(c,_,b),p._OrtGetInputName=(c,_)=>(p._OrtGetInputName=me.Ia)(c,_),p._OrtGetOutputName=(c,_)=>(p._OrtGetOutputName=me.Ja)(c,_),p._OrtFree=c=>(p._OrtFree=me.Ka)(c),p._OrtCreateTensor=(c,_,b,k,I,P)=>(p._OrtCreateTensor=me.La)(c,_,b,k,I,P),p._OrtGetTensorData=(c,_,b,k,I)=>(p._OrtGetTensorData=me.Ma)(c,_,b,k,I),p._OrtReleaseTensor=c=>(p._OrtReleaseTensor=me.Na)(c),p._OrtCreateRunOptions=(c,_,b,k)=>(p._OrtCreateRunOptions=me.Oa)(c,_,b,k),p._OrtAddRunConfigEntry=(c,_,b)=>(p._OrtAddRunConfigEntry=me.Pa)(c,_,b),p._OrtReleaseRunOptions=c=>(p._OrtReleaseRunOptions=me.Qa)(c),p._OrtCreateBinding=c=>(p._OrtCreateBinding=me.Ra)(c),p._OrtBindInput=(c,_,b)=>(p._OrtBindInput=me.Sa)(c,_,b),p._OrtBindOutput=(c,_,b,k)=>(p._OrtBindOutput=me.Ta)(c,_,b,k),p._OrtClearBoundOutputs=c=>(p._OrtClearBoundOutputs=me.Ua)(c),p._OrtReleaseBinding=c=>(p._OrtReleaseBinding=me.Va)(c),p._OrtRunWithBinding=(c,_,b,k,I)=>(p._OrtRunWithBinding=me.Wa)(c,_,b,k,I),p._OrtRun=(c,_,b,k,I,P,H,J)=>(p._OrtRun=me.Xa)(c,_,b,k,I,P,H,J),p._OrtEndProfiling=c=>(p._OrtEndProfiling=me.Ya)(c),p._JsepOutput=(c,_,b)=>(p._JsepOutput=me.Za)(c,_,b),p._JsepGetNodeName=c=>(p._JsepGetNodeName=me._a)(c);var ws=p._pthread_self=()=>(ws=p._pthread_self=me.$a)(),bs=p._malloc=c=>(bs=p._malloc=me.ab)(c),br=p._free=c=>(br=p._free=me.bb)(c);p.__emscripten_tls_init=()=>(p.__emscripten_tls_init=me.cb)();var S0=p.__emscripten_thread_init=(c,_,b,k,I,P)=>(S0=p.__emscripten_thread_init=me.eb)(c,_,b,k,I,P);p.__emscripten_thread_crashed=()=>(p.__emscripten_thread_crashed=me.fb)();var k0=(c,_,b,k,I)=>(k0=me.gb)(c,_,b,k,I),xl=c=>(xl=me.hb)(c),Sl=p.__emscripten_thread_exit=c=>(Sl=p.__emscripten_thread_exit=me.ib)(c),E0=()=>(E0=me.jb)(),C0=(c,_)=>(C0=me.kb)(c,_),vs=c=>(vs=me.lb)(c),kl=c=>(kl=me.mb)(c),El=()=>(El=me.nb)(),T0=p.dynCall_ii=(c,_)=>(T0=p.dynCall_ii=me.pb)(c,_),A0=c=>(A0=me.qb)(c),I0=()=>(I0=me.rb)(),M0=c=>(M0=me.sb)(c),O0=()=>(O0=me.tb)();p.___start_em_js=839500,p.___stop_em_js=839661;function J3(){var c=me;c=Object.assign({},c);var _=k=>I=>k(I)>>>0,b=k=>()=>k()>>>0;return c.wa=_(c.wa),c.$a=b(c.$a),c.ab=_(c.ab),c.emscripten_main_runtime_thread_id=b(c.emscripten_main_runtime_thread_id),c.mb=_(c.mb),c.nb=b(c.nb),c}p.wasmMemory=N,p.stackSave=()=>El(),p.stackRestore=c=>vs(c),p.stackAlloc=c=>kl(c),p.keepRuntimeAlive=()=>0r)}),Ty=vn((t,e)=>{e.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(...e){var a=e.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,a+`\n`);return}console.error(a)}function threadAlert(...e){var a=e.join(" ");postMessage({cmd:"alert",text:a,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,a)=>{var r=Module.wasmModule;Module.wasmModule=null;var t=new WebAssembly.Instance(r,e);return a(t)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let r=[];self.onmessage=t=>r.push(t),self.startWorker=t=>{Module=t,postMessage({cmd:"loaded"});for(let s of r)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const t of e.data.handlers)Module[t]=(...s)=>{postMessage({cmd:"callHandler",handler:t,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var a=URL.createObjectURL(e.data.urlOrBlob);importScripts(a),URL.revokeObjectURL(a)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(r){if(r!="unwind")throw r}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(r){throw Module.__emscripten_thread_crashed?.(),r}}self.onmessage=handleMessage;\n'}),du,cu,Ns,oi,ea,Fs,pu,hu,fu,mu,it,ta=te(()=>{du=xy(),cu=Cy(),oi=!1,ea=!1,Fs=!1,pu=t=>{if(t===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+t+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},hu=()=>{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}},fu=(t,e)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",mu=async t=>{if(oi)return Promise.resolve();if(ea)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Fs)throw new Error("previous call to 'initializeWebAssembly()' failed.");ea=!0;let e=t.initTimeout,r=t.numThreads,n=t.simd,a=pu(r),s=n&&hu(),i=t.wasmPaths,o=typeof i=="string"?i:void 0,l=fu(s,a),u=typeof i=="object"?i[l]:void 0,d=!1,h=[];if(e>0&&h.push(new Promise(m=>{setTimeout(()=>{d=!0,m()},e)})),h.push(new Promise((m,g)=>{let p=a?cu:du,w={locateFile:(v,S)=>{if(a&&v.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Ty()],{type:"text/javascript"}));if(v.endsWith(".wasm")){if(u)return u;let $=o??S;return l==="ort-wasm-simd.wasm"?$+"ort-wasm-simd.jsep.wasm":l==="ort-wasm-simd-threaded.wasm"?$+"ort-wasm-simd-threaded.jsep.wasm":$+l}return S+v}};if(a)if(w.numThreads=r,typeof Blob>"u")w.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let v=`var ortWasmThreaded=${p.toString()};`;w.mainScriptUrlOrBlob=new Blob([v],{type:"text/javascript"})}p(w).then(v=>{ea=!1,oi=!0,Ns=v,m()},v=>{ea=!1,Fs=!0,g(v)})})),await Promise.race(h),d)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},it=()=>{if(oi&&Ns)return Ns;throw new Error("WebAssembly is not initialized yet.")}}),rt,li,qe,Ls=te(()=>{ta(),rt=(t,e)=>{let r=it(),n=r.lengthBytesUTF8(t)+1,a=r._malloc(n);return r.stringToUTF8(t,a,n),e.push(a),a},li=(t,e,r,n)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([a,s])=>{let i=e?e+a:a;if(typeof s=="object")li(s,i+".",r,n);else if(typeof s=="string"||typeof s=="number")n(i,s.toString());else if(typeof s=="boolean")n(i,s?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof s}`)})},qe=t=>{let e=it(),r=e.stackSave();try{let n=e.stackAlloc(8);e._OrtGetLastError(n,n+4);let a=e.HEAP32[n/4],s=e.HEAPU32[n/4+1],i=s?e.UTF8ToString(s):"";throw new Error(`${t} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),gu,Ay=te(()=>{ta(),Ls(),gu=t=>{let e=it(),r=0,n=[],a=t||{};try{if((t==null?void 0:t.logSeverityLevel)===void 0)a.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if((t==null?void 0:t.logVerbosityLevel)===void 0)a.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);(t==null?void 0:t.terminate)===void 0&&(a.terminate=!1);let s=0;return(t==null?void 0:t.tag)!==void 0&&(s=rt(t.tag,n)),r=e._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,s),r===0&&qe("Can't create run options."),(t==null?void 0:t.extra)!==void 0&&li(t.extra,"",new WeakSet,(i,o)=>{let l=rt(i,n),u=rt(o,n);e._OrtAddRunConfigEntry(r,l,u)!==0&&qe(`Can't set a run config entry: ${i} - ${o}.`)}),[r,n]}catch(s){throw r!==0&&e._OrtReleaseRunOptions(r),n.forEach(i=>e._free(i)),s}}}),_u,yu,wu,bu,vu,Iy=te(()=>{ta(),Ls(),_u=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}`)}},yu=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},wu=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},bu=(t,e,r)=>{for(let n of e){let a=typeof n=="string"?n:n.name;switch(a){case"webnn":if(a="WEBNN",typeof n!="string"){let i=n;if(i!=null&&i.deviceType){let o=rt("deviceType",r),l=rt(i.deviceType,r);it()._OrtAddSessionConfigEntry(t,o,l)!==0&&qe(`Can't set a session config entry: 'deviceType' - ${i.deviceType}.`)}if(i!=null&&i.numThreads){let o=i.numThreads;(typeof o!="number"||!Number.isInteger(o)||o<0)&&(o=0);let l=rt("numThreads",r),u=rt(o.toString(),r);it()._OrtAddSessionConfigEntry(t,l,u)!==0&&qe(`Can't set a session config entry: 'numThreads' - ${i.numThreads}.`)}if(i!=null&&i.powerPreference){let o=rt("powerPreference",r),l=rt(i.powerPreference,r);it()._OrtAddSessionConfigEntry(t,o,l)!==0&&qe(`Can't set a session config entry: 'powerPreference' - ${i.powerPreference}.`)}}break;case"webgpu":if(a="JS",typeof n!="string"){let i=n;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=rt("preferredLayout",r),l=rt(i.preferredLayout,r);it()._OrtAddSessionConfigEntry(t,o,l)!==0&&qe(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let s=rt(a,r);it()._OrtAppendExecutionProvider(t,s)!==0&&qe(`Can't append execution provider: ${a}.`)}},vu=t=>{let e=it(),r=0,n=[],a=t||{};wu(a);try{let s=_u(a.graphOptimizationLevel??"all"),i=yu(a.executionMode??"sequential"),o=typeof a.logId=="string"?rt(a.logId,n):0,l=a.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=a.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let d=typeof a.optimizedModelFilePath=="string"?rt(a.optimizedModelFilePath,n):0;if(r=e._OrtCreateSessionOptions(s,!!a.enableCpuMemArena,!!a.enableMemPattern,i,!!a.enableProfiling,0,o,l,u,d),r===0&&qe("Can't create session options."),a.executionProviders&&bu(r,a.executionProviders,n),a.enableGraphCapture!==void 0){if(typeof a.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${a.enableGraphCapture}`);let h=rt("enableGraphCapture",n),m=rt(a.enableGraphCapture.toString(),n);e._OrtAddSessionConfigEntry(r,h,m)!==0&&qe(`Can't set a session config entry: 'enableGraphCapture' - ${a.enableGraphCapture}.`)}if(a.freeDimensionOverrides)for(let[h,m]of Object.entries(a.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let g=rt(h,n);e._OrtAddFreeDimensionOverride(r,g,m)!==0&&qe(`Can't set a free dimension override: ${h} - ${m}.`)}return a.extra!==void 0&&li(a.extra,"",new WeakSet,(h,m)=>{let g=rt(h,n),p=rt(m,n);e._OrtAddSessionConfigEntry(r,g,p)!==0&&qe(`Can't set a session config entry: ${h} - ${m}.`)}),[r,n]}catch(s){throw r!==0&&e._OrtReleaseSessionOptions(r),n.forEach(i=>e._free(i)),s}}}),Us,Yr,ra,Ws,ui,Vs,Gs,xe=te(()=>{Us=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},Yr=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},ra=t=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][t],Ws=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}`)}},ui=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}`)}},Vs=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool",Gs=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}`)}}}),di,$u=te(()=>{di=async t=>{if(typeof t=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(t),n=[];for await(let a of r)n.push(a);return new Uint8Array(Buffer.concat(n))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let a=e.body.getReader(),s;try{s=new ArrayBuffer(n)}catch(o){if(o instanceof RangeError){let l=Math.ceil(n/65536);s=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw o}let i=0;for(;;){let{done:o,value:l}=await a.read();if(o)break;let u=l.byteLength;new Uint8Array(s,i,u).set(l),i+=u}return new Uint8Array(s,0,n)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),xu,Su,ku,Eu,Cu,Tu,nt,Xr=te(()=>{xe(),xu=["V","I","W","E","F"],Su=(t,e)=>{console.log(`[${xu[t]},${new Date().toISOString()}]${e}`)},Cu=(t,e)=>{ku=t,Eu=e},Tu=(t,e)=>{let r=ui(t),n=ui(ku);r>=n&&Su(r,typeof e=="function"?e():e)},nt=(...t)=>{Eu&&Tu(...t)}}),Au,My=te(()=>{xe(),Au=(t,e)=>new(Ws(e))(t)}),Hs=te(()=>{}),js,ci,pi,Iu,Mu,qs,Ks,Ou,zu,Oy=te(()=>{Xr(),Hs(),js=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]]),ci=[],pi=t=>Math.ceil(t/16)*16,Iu=t=>{for(let e=0;eMu++,Ks=async(t,e,r,n)=>{let a=pi(r),s=t.device.createBuffer({size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=t.getCommandEncoder();t.endComputePass(),i.copyBufferToBuffer(e,0,s,0,a),t.flush(),await s.mapAsync(GPUMapMode.READ);let o=s.getMappedRange();if(n){let l=n();return l.set(new Uint8Array(o,0,r)),l}else return new Uint8Array(o.slice(0,r))}finally{s.destroy()}},Ou=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 js)ci.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[])}upload(t,e){let r=e.buffer,n=e.byteOffset,a=e.byteLength,s=pi(a),i=this.storageCache.get(t);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==a)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${a}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:s,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=o.getMappedRange();new Uint8Array(l).set(new Uint8Array(r,n,a)),o.unmap();let u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o,0,i.gpuData.buffer,0,s),nt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(o)}memcpy(t,e){let r=this.storageCache.get(t);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(e);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let a=pi(r.originalSize),s=this.backend.getCommandEncoder();this.backend.endComputePass(),s.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,a)}registerExternalBuffer(t,e,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(t===r)return nt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`);this.externalBuffers.delete(r)}else n=qs();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:e}),this.externalBuffers.set(t,n),nt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${n}, registered.`),n}unregisterExternalBuffer(t){let e=this.externalBuffers.get(t);e!==void 0&&(this.storageCache.delete(e),this.externalBuffers.delete(t),nt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(t,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Iu(t),n,a=(e&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,s=(e&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(a||s){let o=(a?this.freeBuffers:this.freeUniformBuffers).get(r);o?o.length>0?n=o.pop():n=this.backend.device.createBuffer({size:r,usage:e}):n=this.backend.device.createBuffer({size:r,usage:e})}else n=this.backend.device.createBuffer({size:r,usage:e});let i={id:qs(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:t}),nt("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 nt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${e.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(e.gpuData.buffer),e.originalSize}async download(t,e){let r=this.storageCache.get(t);if(!r)throw new Error("data does not exist");await Ks(this.backend,r.gpuData.buffer,r.originalSize,e)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let e=js.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(t.size)||[];e===void 0||r.length>=e?t.destroy():r.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(t.size)||[];e===void 0||r.length>=e?t.destroy():r.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(r=>{r.destroy()}),this.capturedPendingBuffers.delete(t))}},zu=(...t)=>new Ou(...t)}),Pu,Ke,ct=te(()=>{Pu=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}},Ke=t=>new Pu(t)}),Ru,xn,X,hi,Bu,Ys,Xs,Oe=te(()=>{Ru=class{static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}},xn=class{static calcShape(t,e,r=!1){let n=t.length,a=e.length;if(n===0)return e;if(a===0)return t;let s=Math.max(t.length,e.length),i=new Array(s);if(r){if(n<2||a<2)return;let o=Ru.calcMatMulShape([t[n-2],t[n-1]],[e[a-2],e[a-1]]);if(o===void 0)return;[i[s-2],i[s-1]]=o}for(let o=r?3:1;o<=s;o++){let l=n-o<0?1:t[n-o],u=a-o<0?1:e[a-o];if(l!==u&&l>1&&u>1)return;let d=Math.max(l,u);if(l&&u)i[s-o]=Math.max(l,u);else{if(d>1)return;i[s-o]=0}}return i}static isValidBroadcast(t,e){let r=t.length,n=e.length;if(r>n)return!1;for(let a=1;a<=r;a++)if(t[r-a]!==1&&t[r-a]!==e[n-a])return!1;return!0}},X=class xs{static size(e){return xs.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,r=4){let n=e.length;if(n===0)return[];let a=new Array(n),s=n-1;for(;s>=0;){if(e[s]%r===0){a[s]=e[s]/r;break}if(r%e[s]!==0)throw new Error("cannot convert shape");a[s]=1,r/=e[s],s--}for(s--;s>=0;s--)a[s]=e[s];return a}static sizeFromDimension(e,r){if(r<0||r>e.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return xs.getSizeFromDimensionRange(e,r,e.length)}static sizeToDimension(e,r){if(r<0||r>e.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${e.length} dimensions.`);return xs.getSizeFromDimensionRange(e,0,r)}static getSizeFromDimensionRange(e,r,n){let a=1;for(let s=r;s=0;--a)n[a]=n[a+1]*e[a+1];return n}static normalizeAxis(e,r){if(e<-r&&e>=r)throw new Error("unsupported axis for this operation.");return e<0?e+r:e}static normalizeAxes(e,r){return e.map(n=>this.normalizeAxis(n,r??e.length))}static sortBasedOnPerm(e,r){return r?r.map(n=>e[n]):e.slice().reverse()}static padShape(e,r){let n=e.length;return e.map((a,s)=>a+r[s]+r[s+n])}static areEqual(e,r){return e.length!==r.length?!1:e.every((n,a)=>n===r[a])}},hi=class Za{static adjustPoolAttributes(e,r,n,a,s,i){if(!e&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let o=0;o=n.length?n.push(r[o+2]):n[o]=r[o+2];for(let o=0;o=n[o]||i[o+n.length]>=n[o])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,r,n,a,s,i,o){if(o){if(s.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(a.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{xe(),Oe(),Sn=64,fi=(t,e)=>{if(e===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(t){case 10:return e>1?`vec${e}`:"f16";case 1:return e>1?`vec${e}`:"f32";case 6:return e>1?`vec${e}`:"i32";case 12:return e>1?`vec${e}`:"u32";case 7:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(e!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${t}`)}},_t=(t,e=1)=>{let r=fi(t,e);return typeof r=="string"?r:r[0]},Ot=(t,e=1)=>{let r=fi(t,e);return typeof r=="string"?r:r[1]},we=(...t)=>{let e=[];return t.forEach(r=>{r.length!==0&&e.push({type:12,data:r},{type:12,data:X.computeStrides(r)})}),e},st=t=>t%4===0?4:t%2===0?2:1,Sr=(t="f32",e,r="0")=>!e||e===1?`${t}(${r})`:`vec${e}<${t}>(${r})`,kn=(t,e,r)=>t==="f32"?r:e===1?`f32(${r})`:`vec${e}(${r})`,Dr=(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,ke=(t,e,r,n)=>t.startsWith("uniforms.")&&r>4?typeof e=="string"?n==="f16"?`${t}[(${e}) / 8][(${e}) % 8 / 4][(${e}) % 8 % 4]`:`${t}[(${e}) / 4][(${e}) % 4]`:n==="f16"?`${t}[${Math.floor(e/8)}][${Math.floor(e%8/4)}][${e%8%4}]`:`${t}[${Math.floor(e/4)}][${e%4}]`:r>1?`${t}[${e}]`:t,mi=(t,e,r,n,a)=>{let s=typeof r=="number",i=s?r:r.length,o=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,u=fi(e,a),d=typeof u=="string"?u:u[1],h=typeof u=="string"?u:u[0],m={indices:l,value:d,storage:h,tensor:e},g=N=>typeof N=="string"?N:`${N}u`,p={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},w=s?"uniforms.":"",v=`${w}${t}_shape`,S=`${w}${t}_strides`,$="";for(let N=0;N ${m.indices} { var indices: ${m.indices}; var current = offset; ${$} return indices; }`,T=N=>(p.offsetToIndices=!0,i<2?N:`o2i_${t}(${N})`),A=[];if(i>=2)for(let N=i-1;N>=0;N--)A.push(`${ke(S,N,i)} * (indices[${N}])`);let z=i<2?"":` fn i2o_${t}(indices: ${m.indices}) -> u32 { return ${A.join("+")}; }`,R=N=>(p.indicesToOffset=!0,i<2?N:`i2o_${t}(${N})`),V=(...N)=>i===0?"0u":`${m.indices}(${N.map(g).join(",")})`,j=(N,ae)=>i<2?`${N}`:`${ke(N,ae,i)}`,q=(N,ae,de)=>i<2?`${N}=${de};`:`${ke(N,ae,i)}=${de};`,fe={},ee=(N,ae)=>{p.broadcastedIndicesToOffset=!0;let de=`${ae.name}broadcastedIndicesTo${t}Offset`;if(de in fe)return`${de}(${N})`;let Se=[];for(let Te=i-1;Te>=0;Te--){let Xe=ae.indicesGet("outputIndices",Te+ae.rank-i);Se.push(`${j(S,Te)} * (${Xe} % ${j(v,Te)})`)}return fe[de]=`fn ${de}(outputIndices: ${ae.type.indices}) -> u32 { return ${Se.length>0?Se.join("+"):"0u"}; }`,`${de}(${N})`},ne=(N,ae)=>(()=>{if(m.storage===m.value)return`${t}[${N}]=${ae};`;if(m.storage==="vec2"&&m.value==="i32")return`${t}[${N}]=vec2(u32(${ae}), select(0u, 0xFFFFFFFFu, ${ae} < 0));`;if(m.storage==="vec2"&&m.value==="u32")return`${t}[${N}]=vec2(u32(${ae}), 0u);`;if(m.storage==="u32"&&m.value==="vec4")return`${t}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ae}));`;throw new Error(`not supported combination of storage type ${m.storage} and value type ${m.value} yet`)})(),se=N=>(()=>{if(m.storage===m.value)return`${t}[${N}]`;if(m.storage==="vec2"&&m.value==="i32")return`i32(${t}[${N}].x)`;if(m.storage==="vec2"&&m.value==="u32")return`u32(${t}[${N}].x)`;if(m.storage==="u32"&&m.value==="vec4")return`vec4(bool(${t}[${N}] & 0xFFu), bool(${t}[${N}] & 0xFF00u), bool(${t}[${N}] & 0xFF0000u), bool(${t}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${m.storage} and value type ${m.value} yet`)})(),D=i<2?"":` fn get_${t}ByIndices(indices: ${m.indices}) -> ${d} { return ${se(`i2o_${t}(indices)`)}; }`,M=i<2?"":(()=>{let N=o.map(de=>`d${de}: u32`).join(", "),ae=o.map(de=>`d${de}`).join(", ");return` fn get_${t}(${N}) -> ${d} { return get_${t}ByIndices(${V(ae)}); }`})(),G=(...N)=>{if(N.length!==i)throw new Error(`indices length must be ${i}`);let ae=N.map(g).join(",");return i===0?se("0u"):i===1?se(ae[0]):(p.get=!0,p.getByIndices=!0,p.indicesToOffset=!0,`get_${t}(${ae})`)},K=N=>i<2?se(N):(p.getByIndices=!0,p.indicesToOffset=!0,`get_${t}ByIndices(${N})`),pe=i<2?"":` fn set_${t}ByIndices(indices: ${m.indices}, value: ${d}) { ${ne(`i2o_${t}(indices)`,"value")} }`,le=i<2?"":(()=>{let N=o.map(de=>`d${de}: u32`).join(", "),ae=o.map(de=>`d${de}`).join(", ");return` fn set_${t}(${N}, value: ${d}) { set_${t}ByIndices(${V(ae)}, value); }`})();return{impl:()=>{let N=[],ae=!1;return p.offsetToIndices&&(N.push(E),ae=!0),p.indicesToOffset&&(N.push(z),ae=!0),p.broadcastedIndicesToOffset&&(Object.values(fe).forEach(de=>N.push(de)),ae=!0),p.set&&(N.push(le),ae=!0),p.setByIndices&&(N.push(pe),ae=!0),p.get&&(N.push(M),ae=!0),p.getByIndices&&(N.push(D),ae=!0),!s&&ae&&N.unshift(`const ${v} = ${m.indices}(${r.join(",")});`,`const ${S} = ${m.indices}(${X.computeStrides(r).join(",")});`),N.join(` `)},type:m,offsetToIndices:T,indicesToOffset:R,broadcastedIndicesToOffset:ee,indices:V,indicesGet:j,indicesSet:q,set:(...N)=>{if(N.length!==i+1)throw new Error(`indices length must be ${i}`);let ae=N[i];if(typeof ae!="string")throw new Error("value must be string");let de=N.slice(0,i).map(g).join(",");return i===0?ne("0u",ae):i===1?ne(de[0],ae):(p.set=!0,p.setByIndices=!0,p.indicesToOffset=!0,`set_${t}(${de}, ${ae})`)},setByOffset:ne,setByIndices:(N,ae)=>i<2?ne(N,ae):(p.setByIndices=!0,p.indicesToOffset=!0,`set_${t}ByIndices(${N}, ${ae});`),get:G,getByOffset:se,getByIndices:K,usage:n,name:t,strides:S,shape:v,rank:i}},Q=(t,e,r,n=1)=>mi(t,e,r,"input",n),_e=(t,e,r,n=1)=>mi(t,e,r,"output",n),Qs=(t,e,r,n=1)=>mi(t,e,r,"internal",n),Du=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=Sn){let e=typeof t=="number"?t:t[0],r=typeof t=="number"?1:t[1],n=typeof t=="number"?1:t[2];if(e>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${e}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(e*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${e}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let a=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,s=a?`@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=a?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${e*r*n}u + local_idx;`;return`@compute @workgroup_size(${e}, ${r}, ${n}) fn main(${s}) { ${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 r=t.usage==="input"?"read":"read_write",n=t.type.storage;return`@group(0) @binding(${e}) var ${t.name}: array<${n}>;`}declareVariables(...t){return t.map(e=>this.declareVariable(e,this.variableIndex++)).join(` `)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(e=>this.registerInternalVariable(e)),this}registerUniform(t,e,r=1){return this.uniforms.push({name:t,type:e,length:r}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:e,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?t.push(`@align(16) ${e}:array, ${Math.ceil(n/8)}>`):t.push(`${e}:array, ${Math.ceil(n/4)}>`);else{let a=n==null||n===1?r:`vec${n}<${r}>`;t.push(`${e}:${a}`)}return` struct Uniforms { ${t.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(` `)+this.internalVariables.map(t=>t.impl()).join(` `)}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])}},Nu=(t,e)=>new Du(t,e),na=(t,e)=>{let r=t.length,n=[];for(let a=0;a1&&i===1&&n.unshift(s)}return n}}),Fu,Zs,Lu,Uu,kr,Wu,Vu,aa=te(()=>{xe(),Oe(),ct(),Ie(),Fu=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},Zs=(t,e)=>e&&e.length!==t?[...new Array(t).keys()].reverse():e,Lu=(t,e)=>X.sortBasedOnPerm(t,Zs(t.length,e)),Uu=(t,e,r,n)=>{let a=[];a.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let s=0;s{let r=t.dataType,n=t.dims.length,a=Zs(n,e),s=Lu(t.dims,a),i=_e("output",r,s.length),o=Q("a",r,n),l=u=>` ${u.registerUniform("output_size","u32").declareVariables(o,i)} ${Uu(a,n,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:u=>{let d=X.size(s);return{outputs:[{dims:s,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},...we(u[0].dims,s)]}},getShaderSource:l}},Wu=(t,e)=>{Fu(t.inputs),t.compute(kr(t.inputs[0],e.perm))},Vu=t=>Ke({perm:t.perm})}),Gu,Hu,ju,qu,Ku,Yu,Xu,Qu,Zu,Ju,nr,ed,td,rd,nd,ad,id,sd,od,ld,ud,zy=te(()=>{xe(),Oe(),Ie(),eo(),aa(),Gu={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"},Hu={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"},ju={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},qu={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ku=(t,e)=>{let r=[];for(let n=e-t;n{let r=[],n=t.length;for(let s=0;st[s]);return[r,a]},Xu=(t,e)=>{let r=t.length+e.length,n=[],a=0;for(let s=0;s{for(let r=0;r{let r=[];if(!Qu(t,e)){for(let n=0;nr.push(n))}return r},Ju=(t,e,r,n,a,s,i)=>{let o=r[0].dims,l=X.size(s),u=X.size(i),d=Q("_A",r[0].dataType,o),h=_e("output",a,s),m=32,g=` var aBestValues : array; `;return{name:t,shaderCache:e,getShaderSource:p=>` ${p.registerUniform("reduceSize","u32").declareVariables(d,h)} ${g} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${p.mainStart(m)} let outputIndex = global_idx / ${m}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${ju[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${m}) { let candidate = f32(${d.getByOffset("offset + k")}); bestValue = ${Gu[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${m}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 = ${Hu[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${h.setByOffset("outputIndex",`${n==="mean"?`${h.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${h.type.storage}(${qu[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},nr=(t,e,r,n)=>{let a=t.inputs.length===1?r:Js(t.inputs,r),s=a.axes;s.length===0&&!a.noopWithEmptyAxes&&(s=t.inputs[0].dims.map((g,p)=>p));let i=X.normalizeAxes(s,t.inputs[0].dims.length),o=i,l=t.inputs[0],u=Zu(o,t.inputs[0].dims.length);u.length>0&&(l=t.compute(kr(t.inputs[0],u),{inputs:[0],outputs:[-1]})[0],o=Ku(o.length,l.dims.length));let[d,h]=Yu(l.dims,o),m=d;a.keepDims&&(m=Xu(d,i)),t.compute(Ju(e,{hint:a.cacheKey,inputDependencies:["type"]},[l],n,t.inputs[0].dataType,m,h),{inputs:[l]})},ed=(t,e)=>{nr(t,"ReduceMeanShared",e,"mean")},td=(t,e)=>{nr(t,"ReduceL1Shared",e,"l1")},rd=(t,e)=>{nr(t,"ReduceL2Shared",e,"l2")},nd=(t,e)=>{nr(t,"ReduceLogSumExpShared",e,"logSumExp")},ad=(t,e)=>{nr(t,"ReduceMaxShared",e,"max")},id=(t,e)=>{nr(t,"ReduceMinShared",e,"min")},sd=(t,e)=>{nr(t,"ReduceProdShared",e,"prod")},od=(t,e)=>{nr(t,"ReduceSumShared",e,"sum")},ld=(t,e)=>{nr(t,"ReduceSumSquareShared",e,"sumSquare")},ud=(t,e)=>{nr(t,"ReduceLogSumShared",e,"logSum")}}),ar,dd,gi,Js,ir,cd,pd,hd,fd,md,gd,_d,yd,wd,bd,sr,vd,$d,xd,Sd,kd,Ed,Cd,Td,Ad,Id,eo=te(()=>{xe(),Oe(),ct(),Ie(),zy(),ar=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.")},dd=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],gi=(t,e,r,n,a,s,i=!1,o=!1)=>{let l=[],u=r[0].dims,d=u.length,h=X.normalizeAxes(a,d),m=!o&&h.length===0;u.forEach((w,v)=>{m||h.indexOf(v)>=0?i&&l.push(1):l.push(w)});let g=l.length,p=X.size(l);return{name:t,shaderCache:e,getShaderSource:w=>{let v=[],S=Q("_A",r[0].dataType,d),$=_e("output",s,g),E=n(S,$,h),T=E[2];for(let A=0,z=0;A=0?(i&&z++,T=`for(var j${A}: u32 = 0; j${A} < ${u[A]}; j${A}++) { ${E[2].includes("last_index")?`let last_index = j${A};`:""} ${S.indicesSet("input_indices",A,`j${A}`)} ${T} }`):(v.push(`${S.indicesSet("input_indices",A,$.indicesGet("output_indices",z))};`),z++);return` ${w.registerUniform("output_size","u32").declareVariables(S,$)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${S.type.indices}; let output_indices = ${$.offsetToIndices("global_idx")}; ${v.join(` `)} ${E[0]} // init ops for reduce max/min ${E[1]} ${T} ${E[3]} ${E.length===4?$.setByOffset("global_idx","value"):E.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...we(u,l)]})}},Js=(t,e)=>{let r=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(n=>r.push(Number(n))),Ke({axes:r,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},ir=(t,e,r,n)=>{let a=t.inputs,s=a.length===1?r:Js(a,r);t.compute(gi(e,{hint:s.cacheKey,inputDependencies:["rank"]},[a[0]],s.noopWithEmptyAxes&&s.axes.length===0?dd:n,s.axes,a[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},cd=(t,e)=>{ar(t.inputs),ir(t,"ReduceLogSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},pd=(t,e)=>{ar(t.inputs),ir(t,"ReduceL1",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},hd=(t,e)=>{ar(t.inputs),ir(t,"ReduceL2",e,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},fd=(t,e)=>{ar(t.inputs),ir(t,"ReduceLogSumExp",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},md=(t,e)=>{ar(t.inputs),ir(t,"ReduceMax",e,(r,n,a)=>{let s=[];for(let i=0;i=0||a.length===0)&&s.push(r.indicesSet("input_indices",i,0));return[`${s.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},gd=(t,e)=>{ar(t.inputs),ir(t,"ReduceMean",e,(r,n,a)=>{let s=1;for(let i=0;i=0||a.length===0)&&(s*=t.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${s});`]})},_d=(t,e)=>{ar(t.inputs),ir(t,"ReduceMin",e,(r,n,a)=>{let s=[];for(let i=0;i=0||a.length===0)&&s.push(`input_indices[${i}] = 0;`);return[`${s.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},yd=(t,e)=>{ar(t.inputs),ir(t,"ReduceProd",e,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},wd=(t,e)=>{ar(t.inputs),ir(t,"ReduceSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},bd=(t,e)=>{ar(t.inputs),ir(t,"ReduceSumSquare",e,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},sr=(t,e,r)=>{if(e.length===0)return r;let n=1,a=1;for(let s=0;s1024},vd=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?gd(t,e):ed(t,e)},$d=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?pd(t,e):td(t,e)},xd=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?hd(t,e):rd(t,e)},Sd=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?fd(t,e):nd(t,e)},kd=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?md(t,e):ad(t,e)},Ed=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?_d(t,e):id(t,e)},Cd=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?yd(t,e):sd(t,e)},Td=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?wd(t,e):od(t,e)},Ad=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?bd(t,e):ld(t,e)},Id=(t,e)=>{sr(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?cd(t,e):ud(t,e)}}),to,Md,Od,ro,Py=te(()=>{xe(),ct(),eo(),to=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.")},Md=(t,e)=>{to(t.inputs);let r=(n,a,s)=>{let i=[];for(let o=0;o=0||s.length===0)&&i.push(`input_indices[${o}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${e.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",a.setByOffset("global_idx","best_index")]};t.compute(gi("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},Od=(t,e)=>{to(t.inputs);let r=(n,a,s)=>{let i=[];for(let o=0;o=0||s.length===0)&&i.push(`input_indices[${o}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${e.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",a.setByOffset("global_idx","best_index")]};t.compute(gi("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},ro=t=>Ke(t)}),zd,Pd,Rd,_i,Bd,Dd,Nd=te(()=>{xe(),Oe(),ct(),Ie(),zd=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");let r=0,n=t[r],a=n.dataType,s=n.dims.length;t.forEach((i,o)=>{if(o!==r){if(i.dataType!==a)throw new Error("input tensors should be one type");if(i.dims.length!==s)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==e&&l!==n.dims[u])throw new Error("non concat dimensions must match")})}})},Pd=(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; }`,Rd=(t,e)=>{let r=t.length,n=[];for(let a=0;a{let a=X.size(r),s=new Array(t.length),i=new Array(t.length),o=0,l=[],u=[],d=[{type:12,data:a}];for(let w=0;w`uniforms.sizeInConcatAxis${w}`).join(","),p=w=>` ${(()=>{w.registerUniform("outputSize","u32");for(let v=0;v(${g}); ${m} -= sizeInConcatAxis[inputIndex - 1u]; } ${Rd(i,h)} }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:p}},Bd=(t,e)=>{let r=t.inputs,n=r[0].dims,a=X.normalizeAxis(e.axis,n.length);zd(r,a);let s=n.slice();s[a]=r.reduce((o,l)=>o+(l.dims.length>a?l.dims[a]:0),0);let i=r.filter(o=>X.size(o.dims)>0);t.compute(_i(i,a,s,r[0].dataType),{inputs:i})},Dd=t=>Ke({axis:t.axis})}),Fd,Ld,Ud,Wd,yi,Vd,Gd,Hd=te(()=>{xe(),Hs(),Ie(),Nd(),Fd=(t,e)=>{let r=t[0],n=t[1],a=t[2],s=t[3],i=t[4],o=t[5];if(i&&o)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=r.dims[0],u=r.dims[1],d=r.dims[2];if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(a.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let h=a.dims[0]/3,m=h,g=m;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let E of e.qkvHiddenSizes)if(E%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");h=e.qkvHiddenSizes[0],m=e.qkvHiddenSizes[1],g=e.qkvHiddenSizes[2]}let p=u;if(h!==m)throw new Error("qkv_hidden_sizes first element should be same as the second");if(a.dims[0]!==h+m+g)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let w=0;if(i){if(m!==g)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]!==m/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(w=i.dims[3])}let v=p+w,S=-1,$=0;if(s)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");return{batchSize:l,sequenceLength:u,pastSequenceLength:w,kvSequenceLength:p,totalSequenceLength:v,maxSequenceLength:S,inputHiddenSize:d,hiddenSize:h,vHiddenSize:g,headSize:Math.floor(h/e.numHeads),vHeadSize:Math.floor(g/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:$,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ld=(t,e,r,n)=>{let a=st(n),s=64,i=n/a;i{let g=_e("x",e.dataType,e.dims,a),p=[{name:"d_inv",type:Ot(e.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${m.registerUniforms(p).declareVariables(g)} ${m.mainStart([s,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = workgroup_id.x * uniforms.d_comp + local_offset; var thread_max_vector = ${d}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${d}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(a){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: ${a}`)}})()}; 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 = ${d}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${d}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(a){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: ${a}`)}})()}; 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] = ${g.type.value}(uniforms.d_inv); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${d}(x[offset + i]); x[offset + i] = ${g.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${u};${a}`},getShaderSource:h,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:l})}},Ud=(t,e,r,n,a,s,i)=>{let o=i+a.kvSequenceLength,l=[a.batchSize,a.numHeads,a.sequenceLength,o],u=s.scale===0?1/Math.sqrt(a.headSize):s.scale,d=st(a.headSize),h=a.headSize/d,m=12,g={x:Math.ceil(o/m),y:Math.ceil(a.sequenceLength/m),z:a.batchSize*a.numHeads},p=[{type:12,data:a.sequenceLength},{type:12,data:h},{type:12,data:o},{type:12,data:a.numHeads},{type:1,data:u}],w=n?["type","type","type"]:["type","type"],v=S=>{let $=Q("q",e.dataType,e.dims,d),E=Q("key",r.dataType,r.dims,d),T=[$,E];n&&T.push(Q("relative_position_bias",n.dataType,n.dims));let A=_e("output",e.dataType,l),z=Ot(1,d),R=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return` const TILE_SIZE = ${m}u; var tileQ: array<${$.type.storage}, ${m*m}>; var tileK: array<${$.type.storage}, ${m*m}>; ${S.registerUniforms(R).declareVariables(...T,A)} ${S.mainStart([m,m,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; let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K; var value = ${z}(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) { tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x]; } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${z}(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(d){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: ${d}`)}})()}; output[outputIdx] = ${A.type.value} (sum * uniforms.alpha) + ${n?"relative_position_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${d}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:l,dataType:e.dataType,gpuDataType:0}],dispatchGroup:g,programUniforms:p}),getShaderSource:v}},Wd=(t,e,r,n,a)=>{let s=a+n.kvSequenceLength,i=[n.batchSize,n.sequenceLength,n.vHiddenSize],o=12,l={x:Math.ceil(n.vHeadSize/o),y:Math.ceil(n.sequenceLength/o),z:n.batchSize*n.numHeads},u=[{type:12,data:n.sequenceLength},{type:12,data:s},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:u}),getShaderSource:d=>{let h=Q("probs",e.dataType,e.dims),m=Q("v",r.dataType,r.dims),g=_e("output",e.dataType,i),p=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return` const TILE_SIZE = ${o}u; var tileQ: array<${h.type.value}, ${o*o}>; var tileK: array<${h.type.value}, ${o*o}>; ${d.registerUniforms(p).declareVariables(h,m,g)} ${d.mainStart([o,o,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; let offsetB = headIdx * (uniforms.N * uniforms.K) + n; var value = ${h.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N]; } workgroupBarrier(); for (var k: u32 = 0u; k < 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; } }`}}},yi=(t,e,r,n,a,s,i,o,l,u,d)=>{let h=t.outputCount>1,m=t.outputCount>2,g=h&&m?u.pastSequenceLength:0,p=g+u.kvSequenceLength,w=[u.batchSize,u.numHeads,p,u.headSize],v=i?[i,r]:[r],S=h?t.compute(_i(v,2,w,r.dataType),{inputs:v,outputs:[1]})[0]:r,$=[u.batchSize,u.numHeads,p,u.headSize],E=o?[o,n]:[n],T=m?t.compute(_i(E,2,$,n.dataType),{inputs:E,outputs:[2]})[0]:n,A=[e,S];l&&A.push(l);let z=t.compute(Ud(t,e,S,l,u,d,g),{inputs:A,outputs:[-1]})[0];t.compute(Ld(t,z,u.batchSize*u.numHeads*u.sequenceLength,p),{inputs:[z],outputs:[]});let R=[z,T];t.compute(Wd(t,z,T,u,g),{inputs:R,outputs:[0]})},Vd=(t,e)=>{let r=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],n=e.sequenceLength,a=e.inputHiddenSize,s=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:n},{type:12,data:a},{type:12,data:s},{type:12,data:e.numHeads},{type:12,data:e.headSize},{type:12,data:e.hiddenSize},{type:12,data:e.hiddenSize+e.hiddenSize+e.vHiddenSize}],d=h=>{let m=_e("output_q",l[0].dataType,r),g=_e("output_k",l[0].dataType,r),p=_e("output_v",l[0].dataType,r),w=Q("input",l[0].dataType,l[0].dims),v=Q("weight",l[1].dataType,l[1].dims),S=Q("bias",l[2].dataType,l[2].dims),$=w.type.storage,E=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${i}u; var tileInput: array<${$}, ${i*i}>; var tileWeightQ: array<${$}, ${i*i}>; var tileWeightK: array<${$}, ${i*i}>; var tileWeightV: array<${$}, ${i*i}>; ${h.registerUniforms(E).declareVariables(w,v,S,m,g,p)} ${h.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 = ${$}(0); var valueK = ${$}(0); var valueV = ${$}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:u}),getShaderSource:d},{inputs:l,outputs:[-1,-1,-1]})},Gd=(t,e)=>{let r=Fd(t.inputs,e),[n,a,s]=Vd(t,r);return yi(t,n,a,s,t.inputs[4],void 0,void 0,void 0,t.inputs[5],r,e)}}),jd,qd,Kd,Yd,Ry=te(()=>{rr(),xe(),Oe(),ct(),Ie(),jd=(t,e)=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,a,s)=>{let i=a.length;if(i!==n.length)throw new Error(`${s}: num dimensions != ${i}`);a.forEach((o,l)=>{if(o!==n[l])throw new Error(`${s}: dim[${l}] do not match`)})};if(t[0].dims.length>1){let n=e.format==="NHWC"?e.spatial?t[0].dims.slice(-1):t[0].dims.slice(-1).concat(t[0].dims.slice(1,t[0].dims.length-1)):t[0].dims.slice(1,e.spatial?2:void 0);r(t[1].dims,n,"Invalid input scale"),r(t[2].dims,n,"Invalid input B"),r(t[3].dims,n,"Invalid input mean"),r(t[4].dims,n,"Invalid input var")}else r(t[1].dims,[1],"Invalid input scale"),r(t[2].dims,[1],"Invalid input B"),r(t[3].dims,[1],"Invalid input mean"),r(t[4].dims,[1],"Invalid input var")},qd=(t,e)=>{let{epsilon:r,spatial:n,format:a}=e,s=t[0].dims,i=n?st(s[s.length-1]):1,o=a==="NHWC"&&s.length>1?i:1,l=X.size(s)/i,u=n,d=u?s.length:s,h=Q("x",t[0].dataType,t[0].dims,i),m=Q("scale",t[1].dataType,t[1].dims,o),g=Q("bias",t[2].dataType,t[2].dims,o),p=Q("inputMean",t[3].dataType,t[3].dims,o),w=Q("inputVar",t[4].dataType,t[4].dims,o),v=_e("y",t[0].dataType,d,i),S=()=>{let E="";if(n)E=`let cOffset = ${s.length===1?"0u":a==="NHWC"?`outputIndices[${s.length-1}] / ${i}`:"outputIndices[1]"};`;else if(a==="NCHW")E=` ${v.indicesSet("outputIndices","0","0")} let cOffset = ${v.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${m.type.indices}(0); cIndices[0] = outputIndices[${s.length-1}];`;for(let T=1;T` const epsilon = ${r}; ${E.registerUniform("outputSize","u32").declareVariables(h,m,g,p,w,v)} ${E.mainStart()} ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${v.offsetToIndices(`global_idx * ${i}`)}; ${S()} let scale = ${m.getByOffset("cOffset")}; let bias = ${g.getByOffset("cOffset")}; let inputMean = ${p.getByOffset("cOffset")}; let inputVar = ${w.getByOffset("cOffset")}; let x = ${h.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${v.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${e.epsilon}_${e.format}_${n}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:$,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...we(s)]:[{type:12,data:l}]})}},Kd=t=>Ke(t),Yd=(t,e)=>{let{inputs:r,outputCount:n}=t,a=Kd({...e,outputCount:n});if(Ue.webgpu.validateInputContent&&jd(r,a),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(qd(r,a))}}),Xd,Qd,Zd,By=te(()=>{Oe(),Ie(),Xd=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")},Qd=t=>{let e=t[0].dims,r=t[0].dims[2],n=X.size(e)/4,a=t[0].dataType,s=Q("input",a,e,4),i=Q("bias",a,[r],4),o=Q("residual",a,e,4),l=_e("output",a,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:u=>` const channels = ${r}u / 4; ${u.declareVariables(s,i,o,l)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${s.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} }`}},Zd=t=>{Xd(t.inputs),t.compute(Qd(t.inputs))}}),Jd,De,ec,tc,rc,nc,ac,ic,sc,oc,lc,uc,dc,cc,pc,hc,wi,fc,bi,mc,gc,_c,yc,wc,bc,vc,$c,xc,Sc,kc,Ec,Cc,Tc,Ac,Ic,no,Mc,ao,io,Oc,zc,Pc,so=te(()=>{xe(),Oe(),ct(),Ie(),Jd=(t,e,r,n,a,s)=>{let i=Math.ceil(e/4),o="";typeof a=="string"?o=`${a}(a)`:o=a("a");let l=Q("inputData",r,[i],4),u=_e("outputData",n,[i],4);return` ${t.registerUniform("vec_size","u32").declareVariables(l,u)} ${s??""} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${l.getByOffset("global_idx")}; ${u.setByOffset("global_idx",o)} }`},De=(t,e,r,n,a,s=t.dataType)=>({name:e,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:i=>Jd(i,X.size(t.dims),t.dataType,s,r,n),getRunData:i=>({outputs:[{dims:t.dims,dataType:s}],dispatchGroup:{x:Math.ceil(X.size(i[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(X.size(t.dims)/4)}]})}),ec=t=>{t.compute(De(t.inputs[0],"Abs","abs"))},tc=t=>{t.compute(De(t.inputs[0],"Acos","acos"))},rc=t=>{t.compute(De(t.inputs[0],"Acosh","acosh"))},nc=t=>{t.compute(De(t.inputs[0],"Asin","asin"))},ac=t=>{t.compute(De(t.inputs[0],"Asinh","asinh"))},ic=t=>{t.compute(De(t.inputs[0],"Atan","atan"))},sc=t=>{t.compute(De(t.inputs[0],"Atanh","atanh"))},oc=t=>Ke(t),lc=(t,e)=>{let r;switch(e.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${e.to}`)}t.compute(De(t.inputs[0],"Cast",r,void 0,e.cacheKey,e.to))},uc=t=>{let e=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:Ys,r=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:Xs;return Ke({min:e,max:r})},dc=(t,e)=>{let r=t.inputs.length===1?e:uc(t.inputs),n=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"Clip",a=>`clamp(${a}, clip_min_, clip_max_)`,` const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); `,r.cacheKey),{inputs:[0]})},cc=t=>{t.compute(De(t.inputs[0],"Ceil","ceil"))},pc=t=>{t.compute(De(t.inputs[0],"Cos","cos"))},hc=t=>{t.compute(De(t.inputs[0],"Cosh","cosh"))},wi=t=>Ke(t),fc=(t,e)=>{let r=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${r}(${e.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,e.cacheKey))},bi=(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)); }`,mc=t=>{let e=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"Erf",r=>`erf_vf32(${r})`,bi(e)))},gc=t=>{t.compute(De(t.inputs[0],"Exp","exp"))},_c=t=>{t.compute(De(t.inputs[0],"Floor","floor"))},yc=t=>{let e=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,bi(e)))},wc=(t,e)=>{let r=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${e.alpha});`,e.cacheKey))},bc=t=>{t.compute(De(t.inputs[0],"Not",e=>`!${e}`))},vc=t=>{t.compute(De(t.inputs[0],"Neg",e=>`-${e}`))},$c=t=>{t.compute(De(t.inputs[0],"Reciprocal",e=>`1.0/${e}`))},xc=t=>{let e=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"Relu",r=>`select(vec4<${e}>(0.0), ${r}, ${r} > vec4<${e}>(0.0))`))},Sc=t=>{t.compute(De(t.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},kc=t=>Ke(t),Ec=(t,e)=>{let r=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${e.alpha} * ${n} + vec4<${r}>(${e.beta})))`,void 0,e.cacheKey))},Cc=t=>{t.compute(De(t.inputs[0],"Sin","sin"))},Tc=t=>{t.compute(De(t.inputs[0],"Sinh","sinh"))},Ac=t=>{t.compute(De(t.inputs[0],"Sqrt","sqrt"))},Ic=t=>{t.compute(De(t.inputs[0],"Tan","tan"))},no=t=>`sign(${t}) * (1 - exp(-2 * abs(${t}))) / (1 + exp(-2 * abs(${t})))`,Mc=t=>{t.compute(De(t.inputs[0],"Tanh",no))},ao=(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 ${no("v")}; } `,io=t=>`(fast_gelu_a + fast_gelu_a * tanh_v(${t} * (fast_gelu_c * ${t} * ${t} + fast_gelu_b))) * ${t}`,Oc=t=>{let e=Ot(t.inputs[0].dataType);t.compute(De(t.inputs[0],"FastGelu",io,ao(e),void 0,t.inputs[0].dataType))},zc=(t,e)=>{let r=Ot(t.inputs[0].dataType);return t.compute(De(t.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${e.alpha});`,e.cacheKey)),0},Pc=t=>{t.compute(De(t.inputs[0],"Log","log"))}}),Rc,Bc,Dc,Dy=te(()=>{Oe(),Ie(),so(),Rc=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")},Bc=t=>{let e=t[0].dims.slice();e[2]=e[2]/2;let r=Q("input",t[0].dataType,t[0].dims,4),n=Q("bias",t[0].dataType,[t[0].dims[2]],4),a=_e("output",t[0].dataType,e,4),s=X.size(e)/4,i=_t(t[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:o=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${t[0].dims[2]/4/2}u; ${o.declareVariables(r,n,a)} ${bi(i)} ${o.mainStart()} ${o.guardAgainstOutOfBoundsWorkgroupSizes(s)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${a.setByOffset("global_idx","valueLeft * geluRight")} }`}},Dc=t=>{Rc(t.inputs),t.compute(Bc(t.inputs))}}),Nc,Fc,or,Lc,Uc,Wc,Vc,Gc,Hc,jc,qc,Kc,Yc,Ny=te(()=>{xe(),Oe(),Ie(),Nc=(t,e,r,n,a,s,i,o,l,u,d,h)=>{let m,g;typeof o=="string"?m=g=($,E)=>`${o}((${$}),(${E}))`:typeof o=="function"?m=g=o:(m=o.scalar,g=o.vector);let p=_e("outputData",d,n.length,4),w=Q("aData",l,e.length,4),v=Q("bData",u,r.length,4),S;if(a)if(s){let $=X.size(e)===1,E=X.size(r)===1,T=e.length>0&&e[e.length-1]%4===0,A=r.length>0&&r[r.length-1]%4===0;$||E?S=p.setByOffset("global_idx",g($?`${w.type.value}(${w.getByOffset("0")}.x)`:w.getByOffset("global_idx"),E?`${v.type.value}(${v.getByOffset("0")}.x)`:v.getByOffset("global_idx"))):S=` let outputIndices = ${p.offsetToIndices("global_idx * 4u")}; let offsetA = ${w.broadcastedIndicesToOffset("outputIndices",p)}; let offsetB = ${v.broadcastedIndicesToOffset("outputIndices",p)}; ${p.setByOffset("global_idx",g(i||T?w.getByOffset("offsetA / 4u"):`${w.type.value}(${w.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||A?v.getByOffset("offsetB / 4u"):`${v.type.value}(${v.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else S=p.setByOffset("global_idx",g(w.getByOffset("global_idx"),v.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let $=(E,T,A="")=>{let z=`aData[indexA${T}][componentA${T}]`,R=`bData[indexB${T}][componentB${T}]`;return` let outputIndices${T} = ${p.offsetToIndices(`global_idx * 4u + ${T}u`)}; let offsetA${T} = ${w.broadcastedIndicesToOffset(`outputIndices${T}`,p)}; let offsetB${T} = ${v.broadcastedIndicesToOffset(`outputIndices${T}`,p)}; let indexA${T} = offsetA${T} / 4u; let indexB${T} = offsetB${T} / 4u; let componentA${T} = offsetA${T} % 4u; let componentB${T} = offsetB${T} % 4u; ${E}[${T}] = ${A}(${m(z,R)}); `};d===9?S=` var data = vec4(0); ${$("data",0,"u32")} ${$("data",1,"u32")} ${$("data",2,"u32")} ${$("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:S=` ${$("outputData[global_idx]",0)} ${$("outputData[global_idx]",1)} ${$("outputData[global_idx]",2)} ${$("outputData[global_idx]",3)} `}return` ${t.registerUniform("vec_size","u32").declareVariables(w,v,p)} ${h??""} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${S} }`},Fc=(t,e,r,n,a,s,i=r.dataType)=>{let o=!X.areEqual(r.dims,n.dims),l=r.dims,u=X.size(r.dims),d=!1,h=!1,m=[o];if(o){let g=xn.calcShape(r.dims,n.dims,!1);if(!g)throw new Error("Can't perform binary op on the given tensors");l=g,u=X.size(l);let p=X.size(r.dims)===1,w=X.size(n.dims)===1,v=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,S=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;m.push(p),m.push(w),m.push(v),m.push(S);let $=1;for(let E=1;Eg.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:g=>Nc(g,r.dims,n.dims,l,d,o,h,a,r.dataType,n.dataType,i,s),getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(X.size(l)/4)},...we(r.dims,n.dims,l)]})}},or=(t,e,r,n,a,s)=>{t.compute(Fc(e,a??"",t.inputs[0],t.inputs[1],r,n,s))},Lc=t=>{or(t,"Add",(e,r)=>`${e}+${r}`)},Uc=t=>{or(t,"Div",(e,r)=>`${e}/${r}`)},Wc=t=>{or(t,"Equal",{scalar:(e,r)=>`u32(${e}==${r})`,vector:(e,r)=>`vec4(${e}==${r})`},void 0,void 0,9)},Vc=t=>{or(t,"Mul",(e,r)=>`${e}*${r}`)},Gc=t=>{let e=Q("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;or(t,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` fn pow_custom(a : ${e}, b : ${e}) -> ${e} { if (b == ${e}(0.0)) { return ${e}(1.0); } else if (a < ${e}(0.0) && f32(b) != floor(f32(b))) { return ${e}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${e}(1.0), round(f32(abs(b) % ${e}(2.0))) != 1.0) * ${e}(${e==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${e}>, b : vec4<${e}>) -> vec4<${e}> { // TODO: implement vectorized pow return vec4<${e}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},Hc=t=>{or(t,"Sub",(e,r)=>`${e}-${r}`)},jc=t=>{or(t,"Greater",{scalar:(e,r)=>`u32(${e}>${r})`,vector:(e,r)=>`vec4(${e}>${r})`},void 0,void 0,9)},qc=t=>{or(t,"Less",{scalar:(e,r)=>`u32(${e}<${r})`,vector:(e,r)=>`vec4(${e}<${r})`},void 0,void 0,9)},Kc=t=>{or(t,"GreaterOrEqual",{scalar:(e,r)=>`u32(${e}>=${r})`,vector:(e,r)=>`vec4(${e}>=${r})`},void 0,void 0,9)},Yc=t=>{or(t,"LessOrEqual",{scalar:(e,r)=>`u32(${e}<=${r})`,vector:(e,r)=>`vec4(${e}<=${r})`},void 0,void 0,9)}}),Qr,Zr,Jr,oo,en=te(()=>{xe(),Oe(),Qr=(t,e,r="f32")=>{switch(t.activation){case"Relu":return`value = max(value, ${e}(0.0));`;case"Sigmoid":return`value = (${e}(1.0) / (${e}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${e}(${r}(uniforms.clip_min)), ${e}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${e}(0.0), min(${e}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${e}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${t.activation}`)}},Zr=(t,e)=>{t.activation==="Clip"?e.push({type:1,data:t.clipMax},{type:1,data:t.clipMin}):t.activation==="HardSigmoid"?e.push({type:1,data:t.alpha},{type:1,data:t.beta}):t.activation==="LeakyRelu"&&e.push({type:1,data:t.alpha})},Jr=(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"})},oo=t=>{let e=(t==null?void 0:t.activation)||"";if(e==="HardSigmoid"){let[r,n]=(t==null?void 0:t.activation_params)||[.2,.5];return{activation:e,alpha:r,beta:n}}else if(e==="Clip"){let[r,n]=(t==null?void 0:t.activation_params)||[Ys,Xs];return{activation:e,clipMax:n,clipMin:r}}else if(e==="LeakyRelu"){let[r]=(t==null?void 0:t.activation_params)||[.01];return{activation:e,alpha:r}}return{activation:e}}}),Et,lo,uo=te(()=>{Et=(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.`)}},lo=t=>` ${t?"value = value + getBiasByOutputCoords(coords);":""} `}),co,Xc=te(()=>{co=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)); } `}),Qc,Zc,vi,po,Jc,$i,ep,ho,xi=te(()=>{xe(),Oe(),Ie(),en(),uo(),Qc=(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":""}); `,Zc=(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];"} }`,vi=(t,e,r="f32",n,a=!1,s=32,i=!1,o=32)=>{let l=e[1]*t[1],u=e[0]*t[0],d=a?l:s,h=a?s:l,m=d/e[0],g=s/e[1];if(!((a&&m===4&&t[1]===4||!a&&(m===3||m===4))&&d%e[0]===0&&s%e[1]===0&&t[0]===4))throw new Error(`If transposeA ${a} is true, innerElementSize ${m} and workPerThread[1] ${t[1]} must be 4. Otherwise, innerElementSize ${m} must be 3 or 4. tileAWidth ${d} must be divisible by workgroupSize[0]${e[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${t[0]} must be 4.`);return` var mm_Asub: array, ${d/m}>, ${h}>; var mm_Bsub: array, ${u/t[0]}>, ${s}>; const rowPerThread = ${t[1]}; const colPerThread = ${t[0]}; const innerElementSize = ${m}; const tileInner = ${s}; @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)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${l}; let num_tiles = ${i?`${Math.ceil(o/s)}`:"(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 * ${g}; 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; ${Qc(a,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${g}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${m===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Zc(a,m)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},po=(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":""}); `,Jc=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",$i=(t,e,r="f32",n,a=!1,s=32,i=!1,o=32,l=!1)=>{let u=t[1]*e[1],d=t[0]*e[0],h=a?u:s,m=a?s:u;if(!(m%e[1]===0&&h%e[0]===0&&s%e[1]===0))throw new Error(`tileAHight ${m} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${h} must be divisible by workgroupSize[0]${e[0]}, tileInner ${s} must be divisible by workgroupSize[1]${e[1]}`);let g=m/e[1],p=h/e[0],w=s/e[1],v=l?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${u}; let globalColStart = i32(workgroupId.x) * ${d}; // 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 < ${m}; inputRow = inputRow + ${e[1]}) { for (var inputCol = localCol; inputCol < ${h}; inputCol = inputCol + ${e[0]}) { ${po(a,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${e[1]}) { for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${e[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${a?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${e[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${e[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${u}; let tileRowA = i32(localId.y) * ${g}; let tileColA = i32(localId.x) * ${p}; let tileRowB = i32(localId.y) * ${w}; // 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 < ${g}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${p}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${po(a,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Jc(a)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${m}>; var mm_Bsub : array, ${s}>; const rowPerThread = ${t[1]}; const colPerThread = ${t[0]}; const tileInner = ${s}; @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)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${i?`${Math.ceil(o/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${o}`:"0"}; var acc : array, rowPerThread>; // Without this initialization strange values show up in acc. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = 0.0; } } ${v} } `},ep=(t,e,r,n,a,s=!1)=>{let[i,o,l]=a,[u,d,h,m]=n,g=na(i,l),p=na(o,l),w=_t(n[0].type.tensor),v=()=>{let $=d.rank,E=u.rank,T=`var aIndices: ${d.type.indices};`;for(let A=$-2-1,z=E-1;A>=0;A--,z--)T+=` aIndices[${A}] = ${E>1?`batchIndices[${z}]`:"batchIndices"};`;return g.forEach(A=>{T+=` aIndices[${A}] = 0;`}),T+=` aIndices[${$-2}] = u32(row); aIndices[${$-1}] = u32(colIn);`,T},S=()=>{let $=h.rank,E=u.rank,T=`var bIndices: ${h.type.indices};`;for(let A=$-2-1,z=E-1;A>=0;A--,z--)T+=` bIndices[${A}] = ${E>1?`batchIndices[${z}]`:"batchIndices"};`;return p.forEach(A=>{T+=` bIndices[${A}] = 0;`}),T+=` bIndices[${$-2}] = u32(row); bIndices[${$-1}] = u32(colIn);`,T};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${Et(t,w)} { var value = ${Et(t,w)}(0.0); let col = colIn * ${t}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${v()} value = ${d.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${u.type.indices}) -> ${Et(t,w)} { var value = ${Et(t,w)}(0.0); let col = colIn * ${t}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${S()} value = ${h.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Et(t,w)}) { 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 + ${s?"bias[colIn]":`${Et(t,w)}(bias[row])`};`:""} ${r} ${m.setByIndices("vec3(coords)","value")} } } `},ho=(t,e,r,n,a=!1)=>{let s=t[0].dims,i=t[1].dims,o=s.slice(0,-2),l=i.slice(0,-2),u=n?n.slice(0,-2):r.slice(0,-2),d=X.size(u),h=s[s.length-2],m=s[s.length-1],g=i[i.length-1],p=m%4===0&&g%4===0,w=h<=8?[4,1,1]:[4,4,1],v=[8,8,1],S=[Math.ceil(g/v[0]/w[0]),Math.ceil(h/v[1]/w[1]),Math.ceil(d/v[2]/w[2])],$=p?4:1,E=[...o,h,m/$],T=E.length,A=[...l,m,g/$],z=A.length,R=[d,h,g/$],V=[{type:6,data:h},{type:6,data:g},{type:6,data:m}];Zr(e,V),V.push(...we(u,E,A));let j=["rank","rank"],q=t.length>2;q&&(V.push(...we(t[2].dims)),j.push("rank")),V.push(...we(R));let fe=ee=>{let ne=u.length,se=Qs("batchDims",t[0].dataType,ne,1),D=_t(t[0].dataType),M=Q("a",t[0].dataType,T,$),G=Q("b",t[1].dataType,z,$),K=_e("result",t[0].dataType,R.length,$),pe=[M,G];if(q){let Se=a?$:1;pe.push(Q("bias",t[2].dataType,t[2].dims.length,Se))}let le=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Jr(e,le);let N=_t(K.type.tensor),ae=Qr(e,K.type.value,N),de=ep($,q,ae,[se,M,G,K],[o,l,u],a);return` ${ee.registerUniforms(le).registerInternalVariables(se).declareVariables(...pe,K)} ${de} ${p?vi(w,v,D,se):$i(w,v,D,se)} `};return{name:"MatMul",shaderCache:{hint:`${w};${e.activation};${p};${a}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:V}),getShaderSource:fe}}}),tp,rp,Fy=te(()=>{xe(),Xr(),Ie(),en(),uo(),Xc(),xi(),tp=(t,e,r,n,a=!1,s,i=4,o=4,l=4,u="f32")=>{let d=j=>{switch(j){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 ${j} is not supported.`)}},h=j=>{switch(j){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${j} is not supported.`)}},m=t?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,g=t?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,p=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",w=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",v=t?"row":"col",S=t?"col":"row",$=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${v} / outWidth; let outCol = ${v} % outWidth; let WRow = ${S} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${S} / 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 = ${S} % inChannels; var resData = ${Et(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 < ${p} && xCol >= 0 && xCol < ${w}) { ${m} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${d(i)} } return resData;`,E=t?e&&n?` let col = colIn * ${i}; ${$}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${$} } return ${Et(i,u)}(0.0);`:n&&r?` let col = colIn * ${i}; ${$}`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${$} } return ${Et(i,u)}(0.0);`,T=`${h(o)}`,A=Et(l,u),z=Et(t?i:o,u),R=Et(t?o:i,u),V=Qr(s,A,u);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${z} { ${t?E:T} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${R} { ${t?T:E} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${A}) { 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])"}; ${g} ${lo(a)} ${V} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},rp=(t,e,r,n,a,s,i,o)=>{let l=e.format==="NHWC",u=l?t[0].dims[3]:t[0].dims[1],d=r[0],h=l?r[2]:r[3],m=l?r[1]:r[2],g=l?r[3]:r[1],p=l&&(u%4===0||u%3===0)&&g%4===0,w=l?g:h*m,v=l?h*m:g,S=[8,8,1],$=n<=8?[4,1,1]:[4,4,1],E=[Math.ceil(w/S[0]/$[0]),Math.ceil(v/S[1]/$[1]),Math.ceil(d/S[2]/$[2])];nt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let T=p?l&&u%4!==0?3:4:1,A=S[1]*$[1],z=S[0]*$[0],R=Math.max(S[0]*T,S[1]),V=n%A===0,j=a%z===0,q=s%R===0,fe=p?[T,4,4]:[1,1,1],ee=[{type:6,data:n},{type:6,data:a},{type:6,data:s},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];Zr(e,ee),ee.push(...we(t[0].dims,t[1].dims));let ne=["rank","rank"];i&&(ee.push(...we(t[2].dims)),ne.push("rank")),ee.push(...we(r));let se=D=>{let M=[{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}];Jr(e,M);let G=p?4:1,K=_t(t[0].dataType),pe=` fn setOutputAtIndex(flatIndex : i32, value : ${p?`vec4<${K}>`:K}) { result[flatIndex] = ${p?`vec4<${K}>`:K}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${p?`vec4<${K}>`:K}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${p?"/ 4":""}, value); }`,le=Q("x",t[0].dataType,t[0].dims.length,T===3?1:T),N=Q("w",t[1].dataType,t[1].dims.length,G),ae=[le,N],de=_e("result",t[0].dataType,r.length,G);if(i){let Se=Q("bias",t[2].dataType,t[2].dims.length,G);ae.push(Se),pe+=` fn getBiasByOutputCoords(coords : vec4) -> ${p?`vec4<${K}>`:K} { return bias[coords.${l?"w":"y"}${p?"/ 4":""}]; }`}return` ${co("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 }; ${D.registerUniforms(M).declareVariables(...ae,de)} ${pe} ${tp(l,V,j,q,i,e,fe[0],fe[1],fe[2],K)} ${p?vi($,S,K,void 0,!l,R):$i($,S,K,void 0,!l,R,!1,void 0,o)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${T};${p};${V};${j};${q};${A};${z};${R}`,inputDependencies:ne},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:ee}),getShaderSource:se}}}),fo,np,Ly=te(()=>{xe(),Oe(),Ie(),dp(),en(),fo=(t,e,r)=>{let n=t.length>2,a=n?"value += b[output_channel];":"",s=t[0].dims,i=t[1].dims,o=i[0]/e.group,l=e.format==="NHWC",u=Si(s,i,e.dilations,e.pads,e.strides,l),d=X.size(u),h=[{type:12,data:d},{type:12,data:e.dilations},{type:12,data:[e.strides[0],e.strides[1]]},{type:12,data:[e.pads[0],e.pads[1]]},{type:12,data:o}];Zr(e,h),h.push(...we(s,i));let m=["rank","rank"];n&&(h.push(...we(t[2].dims)),m.push("rank")),h.push(...we(u));let g=p=>{let w=_e("output",t[0].dataType,u.length),v=_t(w.type.tensor),S=Qr(e,w.type.value,v),$=Q("x",t[0].dataType,s.length),E=Q("w",t[1].dataType,i.length),T=[$,E];n&&T.push(Q("b",t[2].dataType,t[2].dims.length));let A=[{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 Jr(e,A),` ${p.registerUniforms(A).declareVariables(...T,w)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${w.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: ${w.type.value} = ${w.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?$.get("batch","xHeight","xWidth","input_channel"):$.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${E.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${a} ${S} ${w.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:e.cacheKey,inputDependencies:m},getRunData:()=>({outputs:[{dims:r?r(u):u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:g}},np=(t,e,r)=>{let n=t.length>2,a=st(r[3]),s=st(r[2]),i=X.size(r)/a/s,o=[t[0].dims[0],t[0].dims[1],t[0].dims[2],t[0].dims[3]/a],l=[t[1].dims[0],t[1].dims[1],t[1].dims[2],t[1].dims[3]/a],u=[r[0],r[1],r[2],r[3]/a],d=[{type:12,data:i},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];Zr(e,d),d.push(...we(o,l,u));let h=(s-1)*e.strides[1]+l[1],m=g=>{let p=_e("output",t[0].dataType,u.length,a),w=_t(p.type.tensor),v=Qr(e,p.type.value,w),S=Q("x",t[0].dataType,o.length,a),$=Q("w",t[1].dataType,l.length,a),E=[S,$];n&&E.push(Q("b",t[2].dataType,t[2].dims,a));let T=n?"value += b[output_channel];":"",A=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Jr(e,A),` ${g.registerUniforms(A).declareVariables(...E,p)} ${g.mainStart()} ${g.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] / ${s}u; let col = (index1 % width1) * ${s}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<${S.type.value}, ${h}>; var values: array<${p.type.value}, ${s}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${l[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${h}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${S.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${S.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) { let w_val = ${$.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${s}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${s}u; i++) { var value = values[i]; ${T} ${v} ${p.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${a};${s};${h};${l[0]};${l[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d}),getShaderSource:m}}}),mo,ap,ip,sp=te(()=>{xe(),Oe(),xi(),Ie(),en(),mo=(t,e,r,n,a=!1)=>{let s=t[0].dims,i=t[1].dims,o=s[s.length-2],l=i[i.length-1],u=s[s.length-1],d=st(l),h=st(u),m=st(o),g=X.size(r)/d/m,p=t.length>2,w=n?n.slice(0,-2):r.slice(0,-2),v=[X.size(w),o,l],S=[{type:12,data:g},{type:12,data:o},{type:12,data:l},{type:12,data:u}];Zr(e,S),S.push(...we(w,s,i)),p&&S.push(...we(t[2].dims)),S.push(...we(v));let $=E=>{let T=Qs("batch_dims",t[0].dataType,w.length),A=Q("a",t[0].dataType,s.length,h),z=Q("b",t[1].dataType,i.length,d),R=_e("output",t[0].dataType,v.length,d),V=_t(R.type.tensor),j=Qr(e,R.type.value,V),q=[A,z],fe="";if(p){let pe=a?d:1;q.push(Q("bias",t[2].dataType,t[2].dims.length,pe)),fe=`${a?`value += bias[col / ${pe}];`:`value += ${R.type.value}(bias[row + i]);`}`}let ee=s.slice(0,-2),ne=i.slice(0,-2),se=na(ee,w),D=na(ne,w),M=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Jr(e,M);let G=(pe,le)=>{let N=pe.rank,ae=pe.name;if(N===2)return`var ${ae}_indices = ${pe.type.indices}(0u, 0u);`;let de=T.rank,Se=`var ${ae}_indices: ${pe.type.indices};`;for(let Te=N-2-1,Xe=de-1;Te>=0;Te--,Xe--)Se+=` ${ae}_indices[${Te}] = ${de>1?`batch_indices[${Xe}]`:"batch_indices"};`;return le.forEach(Te=>{Se+=` ${ae}_indices[${Te}] = 0;`}),Se+=`${ae}_indices[${N-2}] = 0u; ${ae}_indices[${N-1}] = 0u;`,Se},K=()=>{let pe=`var a_data: ${A.type.value};`;for(let le=0;le; for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) { ${K()} } for (var i = 0u; i < ${m}u; i++) { var value = values[i]; ${fe} ${j} let cur_indices = ${R.type.indices}(batch, row + i, col); let offset = ${R.indicesToOffset("cur_indices")}; ${R.setByOffset(`offset / ${d}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${d};${h};${m};${a}`,inputDependencies:p?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:S}),getShaderSource:$}},ap=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.")},ip=t=>{ap(t.inputs);let e=xn.calcShape(t.inputs[0].dims,t.inputs[1].dims,!0);if(!e)throw new Error("Can't use matmul on the given tensors");let r=e[e.length-1],n=t.inputs[0].dims[t.inputs[0].dims.length-1];r<8&&n<8?t.compute(mo(t.inputs,{activation:""},e)):t.compute(ho(t.inputs,{activation:""},e))}}),Si,ki,op,go,_o,lp,up,yo,dp=te(()=>{Oe(),Fy(),xi(),Ly(),en(),sp(),aa(),Si=(t,e,r,n,a,s)=>{let i=t[0],o=t.slice(s?1:2,s?3:4),l=o.length,u=e[0],d=e.slice(2).map((m,g)=>m+(m-1)*(r[g]-1)),h=o.map((m,g)=>m+n[g]+n[g+l]).map((m,g)=>Math.floor((m-d[g]+a[g])/a[g]));return h.splice(0,0,i),h.splice(s?3:1,0,u),h},ki=[2,3,1,0],op=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4&&t[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let r=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],n=t[1].dims[1]*e.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(t.length===3&&(t[2].dims.length!==1||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");let a=t[0].dims.length-2;if(e.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(e.strides.length!==a)throw new Error(`strides should be ${a}D`);if(e.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape")},go=(t,e)=>{let r=t.kernelShape.slice();for(let s=2;s{let e=oo(t),r=t.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],a=t.dilations,s=t.group,i=t.kernel_shape,o=t.pads,l=t.strides,u=t.w_is_const();return{autoPad:n,format:r,dilations:a,group:s,kernelShape:i,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${t.format};${e.activation};`}},lp=(t,e,r)=>{let n=go(r,e),a=r.format==="NHWC";if(r.group!==1){if(!t.adapterInfo.isArchitecture("ampere")&&a&&e[1].dims[0]===r.group&&e[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let z=Si(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),R=t.kernelCustomData.wT??t.compute(kr(e[1],ki),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=R);let V=[e[0],R];e.length===3&&V.push(e[2]),t.compute(np(V,n,z),{inputs:V})}else t.compute(fo(e,n));return}let s=e.length===3,i=e[0].dims[a?1:2],o=e[0].dims[a?2:3],l=e[0].dims[a?3:1],u=e[1].dims[2],d=e[1].dims[3],h=Si(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),m=h[a?1:2],g=h[a?2:3],p=h[a?3:1],w=a&&u===i&&d===o&&r.pads[0]===0&&r.pads[1]===0;if(w||u===1&&d===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let z=h[0],R,V,j,q=[];if(a){let ne=t.kernelCustomData.wT??t.compute(kr(e[1],ki),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=ne),w){let se=i*o*l;R=e[0].reshape([1,z,se]),V=ne.reshape([1,se,p]),j=[1,z,p]}else R=e[0].reshape([z,i*o,l]),V=ne.reshape([1,l,p]),j=[z,m*g,p];q.push(R),q.push(V)}else R=e[0].reshape([z,l,i*o]),V=e[1].reshape([1,p,l]),j=[z,p,m*g],q.push(V),q.push(R);s&&q.push(e[2]);let fe=j[2],ee=q[0].dims[q[0].dims.length-1];fe<8&&ee<8?t.compute(mo(q,n,h,j,a),{inputs:q}):t.compute(ho(q,n,h,j,a),{inputs:q});return}let v=!0,S=t.kernelCustomData.wT??t.compute(kr(e[1],ki),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=S);let $=[e[0],S];s&&$.push(e[2]);let E=a?m*g:p,T=a?p:m*g,A=u*d*l;t.compute(rp($,n,h,E,T,A,s,v),{inputs:$})},up=(t,e)=>{let r=e.format==="NHWC",n=[t.inputs[0].reshape(r?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];t.inputs.length===3&&n.push(t.inputs[2]);let a=[0,e.pads[0],0,e.pads[1]],s=[1].concat(e.strides),i=[1].concat(e.dilations),o=[1].concat(e.kernelShape),l=go({...e,pads:a,strides:s,dilations:i,kernelShape:o},n);t.compute(fo(n,l,u=>r?[u[0],u[2],u[3]]:[]))},yo=(t,e)=>{op(t.inputs,e),t.inputs[0].dims.length===3?up(t,e):lp(t,t.inputs,e)}}),cp,pp,Uy=te(()=>{xe(),Xr(),Ie(),en(),uo(),Xc(),xi(),cp=(t,e=!1,r,n,a=4)=>{let s=v=>{switch(v){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${n}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${v} is not supported.`)}},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])",d=t?"row":"col",h=t?"col":"row",m=` 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 = ${d} / outWidth; let outCol = ${d} % outWidth; let WRow = ${h} / (uniforms.filter_dims[1] * inChannels); let WCol = ${h} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${l}) || fract(xR) > 0.0) { return ${n}(0.0); } if (xC < 0.0 || xC >= f32(${u}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${h} % inChannels; ${i} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${a}];`,g=t?` let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${m} } return ${n}(0.0);`:` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${m} } return ${n}(0.0);`,p=` let col = colIn * ${a}; let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${t?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${s(a)} } return ${n}(0.0); `,w=Qr(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${t?g:p} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${t?p:g} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${o} ${lo(e)} ${w} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${a}] = value; } }`},pp=(t,e,r,n,a,s,i,o)=>{let l=e.format==="NHWC",u=l?t[0].dims[3]:t[0].dims[1],d=r[0],h=l?r[2]:r[3],m=l?r[1]:r[2],g=l?r[3]:r[1],p=l&&u%4===0&&u%3&&g%4===0,w=l?g:h*m,v=l?h*m:g,S=[8,8,1],$=n<=8?[4,1,1]:[4,4,1],E=[Math.ceil(w/S[0]/$[0]),Math.ceil(v/S[1]/$[1]),Math.ceil(d/S[2]/$[2])];nt("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let T=p?4:1,A=Math.max(S[0]*T,S[1]),z=p?4:1,R=[e.kernelShape[l?1:2],e.kernelShape[l?2:3]],V=[R[0]+(e.dilations[0]<=1?0:(R[0]-1)*(e.dilations[0]-1)),R[1]+(e.dilations[1]<=1?0:(R[1]-1)*(e.dilations[1]-1))],j=[V[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),V[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],q=[{type:6,data:n},{type:6,data:a},{type:6,data:s},{type:6,data:e.strides},{type:6,data:e.dilations},{type:6,data:R},{type:6,data:j}];Zr(e,q),q.push(...we(t[0].dims,t[1].dims));let fe=["rank","rank"];i&&(q.push(...we(t[2].dims)),fe.push("rank")),q.push(...we(r));let ee=ne=>{let se=Q("x",t[0].dataType,t[0].dims.length,z),D=Q("w",t[1].dataType,t[1].dims.length,1),M=_e("result",t[0].dataType,r.length,z),G=[se,D],K="";if(i){let N=Q("bias",t[2].dataType,t[2].dims.length,z);G.push(N),K+=` fn getBiasByOutputCoords(coords : vec4) -> ${N.type.value} { return bias[coords.${l?"w":"y"}${p?"/ 4":""}]; }`}let pe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:R.length},{name:"pads",type:"i32",length:j.length}];Jr(e,pe);let le=_t(t[0].dataType,1);if(le!=="f16"&&le!=="f32")throw new Error(`elemType ${le} is not supported.`);return` ${co("uniforms.result_strides")} ${ne.registerUniforms(pe).declareVariables(...G,M)}; ${K} ${cp(l,i,e,se.type.value,T)} ${p?vi($,S,le,void 0,!l,A):$i($,S,le,void 0,!l,A,!1,void 0,o)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${e.cacheKey};${$};${S};${p}`,inputDependencies:fe},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:q}),getShaderSource:ee}}}),hp,wo,Wy=te(()=>{xe(),Xr(),Oe(),Ie(),hp=(t,e,r,n,a,s=!1,i,o,l=!1)=>{let u=l?1:2,d=l?2:3,h=l?3:1,m=s?2:1,g=` fn setOutputAtIndex(flatIndex : u32, value : ${s?`vec4<${i}>`:i}) { result[flatIndex] = ${s?`vec4<${i}>`:i}(value); }`;n&&(g+=` fn getBiasByOutputCoords(coords : vec4) -> ${s?`vec4<${i}>`:i} { return bias[coords.${l?"w":"y"}${s?"/ 4":""}]; }`);let p=s?4:1,w=Q("W",e[1].dataType,e[1].dims.length,p),v=Q("Dy",e[0].dataType,e[0].dims.length,p),S=[v,w];n&&S.push(Q("bias",e[2].dataType,[r[h]].length,p));let $=_e("result",e[0].dataType,r.length,p),E=`{ let batch: u32 = ${a?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${a?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${a?"global_id.y":"workgroup_id.y"} * ${m}; let d1: u32 = ${a?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${m}>; for (var i = 0; i < ${m}; 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 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${v.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 = ${v.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[${h}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${v.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 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${w.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${v.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 < ${m}; i = i + 1) { let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; ${$.set("batch","r","c + i","d1","value")}; } }`,T=` let outputIndices = ${$.offsetToIndices("global_idx")}; let batch = ${$.indicesGet("outputIndices",0)}; let d1 = ${$.indicesGet("outputIndices",h)}; let r = ${$.indicesGet("outputIndices",u)}; let c = ${$.indicesGet("outputIndices",d)}; 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[${d}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${l?v.get("batch","idyR","idyC","inputChannel"):v.get("batch","inputChannel","idyR","idyC")}; let wValue = ${w.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; ${$.setByOffset("global_idx","value")}; `;return` ${t.registerUniforms(o).declareVariables(...S,$)} ${g} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${s?E:T}}`},wo=(t,e,r)=>{let n=t.length>2,a=e.outputShape,s=X.size(a),i=[Math.ceil(s/64),1,1];nt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let o=e.format==="NHWC",l=["rank","rank"],u=[e.strides[0],e.strides[1]],d=[e.kernelShape[o?1:2],e.kernelShape[o?2:3]],h=[e.dilations[0],e.dilations[1]],m=[d[0]+(e.dilations[0]<=1?0:(e.kernelShape[o?1:2]-1)*(e.dilations[0]-1)),d[1]+(e.dilations[1]<=1?0:(e.kernelShape[o?2:3]-1)*(e.dilations[1]-1))],g=[m[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),m[1]-1-Math.floor(e.pads[1]+e.pads[3])/2],p=!1,w=e.group,v=t[1].dims,S=v[0]/w,$=v[1],E=[{type:12,data:s},{type:12,data:u},{type:12,data:d},{type:12,data:h},{type:12,data:m},{type:6,data:g},{type:12,data:S},{type:12,data:$},...we(t[0].dims,t[1].dims)];n&&(E.push(...we(t[2].dims)),l.push("rank")),E.push(...we(a));let T=i[1]===1&&i[2]===1,A=z=>{let R=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:u.length},{name:"filter_dims",type:"u32",length:d.length},{name:"dilations",type:"u32",length:d.length},{name:"effective_filter_dims",type:"u32",length:m.length},{name:"pads",type:"i32",length:g.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],V=_t(t[0].dataType);return`${hp(z,t,a,n,T,p,V,R,o)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(a):a,dataType:t[0].dataType}],programUniforms:E}),getShaderSource:A}}}),fp,mp,gp,bo,_p,yp,wp,bp,vp,$p,Vy=te(()=>{Uy(),Wy(),en(),aa(),fp=(t,e,r,n,a,s)=>(t-1)*e+r+(n-1)*a+1-s,mp=(t,e,r,n,a)=>{let s=Math.floor(t/2);e==="SAME_UPPER"?(r[n]=s,r[a]=t-s):e==="SAME_LOWER"&&(r[n]=t-s,r[a]=s)},gp=(t,e,r,n,a,s,i,o,l,u)=>{let d=t.length-2,h=u.length===0;if(l.length===0)for(let p=0;p{let r=t.kernelShape.slice();if(t.kernelShape.length===0||t.kernelShape.reduce((h,m)=>h*m,1)===0){r.length=0;for(let h=2;hh+m,0)===0){let h=e[0].dims.length-2;l=new Array(h).fill(1)}let u=t.strides.slice();if(u.reduce((h,m)=>h+m,0)===0){let h=e[0].dims.length-2;u=new Array(h).fill(1)}gp(o,r,l,t.autoPad,t.group,a,u,n,i,s);let d=Object.assign({},t);return Object.assign(d,{kernelShape:r,pads:a,outputPadding:i,outputShape:s,dilations:l,strides:u}),d},_p=t=>{let e=oo(t),r=t.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof t.autoPad>"u"?0:t.autoPad],a=t.dilations,s=t.group,i=t.kernelShape,o=t.pads,l=t.strides,u=t.wIsConst(),d=t.outputPadding,h=t.outputShape;return{autoPad:n,format:r,dilations:a,group:s,kernelShape:i,outputPadding:d,outputShape:h,pads:o,strides:l,wIsConst:u,...e,cacheKey:`${t.format};${e.activation};`}},yp=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4&&t[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let r=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],n=t[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let a=t[1].dims[1]*e.group;if(t.length===3&&(t[2].dims.length!==1||t[2].dims[0]!==a))throw new Error("invalid bias");let s=t[0].dims.length-2;if(e.dilations.reduce((i,o)=>i+o,0)>0&&e.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(e.strides.reduce((i,o)=>i+o,0)>0&&e.strides.length!==s)throw new Error(`strides should be ${s}D`);if(e.pads.reduce((i,o)=>i+o,0)>0&&e.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(e.outputPadding.length!==s&&e.outputPadding.length!==0)throw new Error(`output_padding should be ${s}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")},wp=[2,3,1,0],bp=(t,e,r)=>{let n=bo(r,e),a=r.format==="NHWC",s=n.outputShape,i=s[a?3:1],o=e[0].dims[a?3:1];if(n.group!==1||i===1&&o===1){t.compute(wo(e,n));return}let l=s[a?1:2],u=s[a?2:3],d=e[1].dims[2],h=e[1].dims[3],m=a?l*u:i,g=a?i:l*u,p=d*h*o,w=!0,v=t.kernelCustomData.wT??t.compute(kr(e[1],wp),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=v);let S=[e[0],v],$=e.length===3;$&&(!a&&e[2].dims.length===1?S.push(e[2].reshape([e[2].dims[0],1,1])):S.push(e[2])),t.compute(pp(S,n,s,m,g,p,$,w),{inputs:S})},vp=(t,e)=>{let r=e.format==="NHWC",n=[t.inputs[0].reshape(r?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];t.inputs.length===3&&n.push(t.inputs[2]);let a=e.kernelShape;(a.length===0||a[0]===0)&&(a=[t.inputs[1].dims[2]]);let s=e.dilations;(s.length===0||s[0]===0)&&(s=[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),s=[1].concat(s),a=[1].concat(a);let l=bo({...e,pads:o,strides:i,dilations:s,kernelShape:a},n);t.compute(wo(n,l,u=>r?[u[0],u[2],u[3]]:[u[0],u[1],u[3]]))},$p=(t,e)=>{yp(t.inputs,e),t.inputs[0].dims.length===3?vp(t,e):bp(t,t.inputs,e)}}),xp,Sp,kp,Gy=te(()=>{xe(),Oe(),ct(),Ie(),xp=(t,e,r,n)=>{let a=X.size(e),s=e.length,i=Q("input",t,s),o=_e("output",t,s),l=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),u=X.normalizeAxis(l,s),d=h=>{let m=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,g=ke("uniforms.input_shape","uniforms.axis",s),p=n.reverse?m+(n.exclusive?" + 1":""):"0",w=n.reverse?g:m+(n.exclusive?"":" + 1");return` ${h.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,o)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${o.offsetToIndices("global_idx")}; var sum = ${o.type.value}(0); let first : i32 = ${p}; let last : i32 = ${w}; 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:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:e,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},{type:12,data:u},...we(e,e)]}),getShaderSource:d}},Sp=(t,e)=>{let r=t.inputs[0].dims,n=t.inputs[0].dataType,a=t.inputs[1];t.compute(xp(n,r,a,e),{inputs:[0]})},kp=t=>{let e=t.exclusive===1,r=t.reverse===1;return Ke({exclusive:e,reverse:r})}}),Ep,Cp,Tp,Ap,Ip,Hy=te(()=>{xe(),Oe(),ct(),Ie(),Ep=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.")},Cp=(t,e,r,n)=>{let a=[];a.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let s=0;s{let r,n,a,s,i,o,l=e.format==="NHWC",u=e.blocksize,d=e.mode==="DCR";l?([r,n,a,s]=t.dims,i=d?[r,n,a,u,u,s/u**2]:[r,n,a,s/u**2,u,u],o=d?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,a,s]=[t.dims[0],t.dims[2],t.dims[3],t.dims[1]],i=d?[r,u,u,s/u**2,n,a]:[r,s/u**2,u,u,n,a],o=d?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let h=t.reshape(i),m=h.dims.length,g=t.dataType,p=Q("a",g,m),w=_e("output",g,m),v=S=>` ${S.registerUniform("output_size","u32").declareVariables(p,w)} ${Cp(o,m,p,w)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${w.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${w.setByOffset("global_idx",p.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${t.dims};${e.blocksize};${e.mode}`,inputDependencies:["rank"]},getRunData:S=>{let $=l?[r,n*u,a*u,s/u**2]:[r,s/u**2,n*u,a*u],E=X.size($),T=h.dims,A=X.sortBasedOnPerm(T,o);return{outputs:[{dims:$,dataType:S[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:[{type:12,data:E},...we(T,A)]}},getShaderSource:v}},Ap=(t,e)=>{Ep(t.inputs),t.compute(Tp(t.inputs[0],e))},Ip=t=>Ke({blocksize:t.blocksize,mode:t.mode,format:t.format})}),Ei,ia,vo,Mp,Op,zp,Pp,$o,Rp,Bp,Dp,jy=te(()=>{xe(),Oe(),ct(),Ie(),Ei="[a-zA-Z]|\\.\\.\\.",ia="("+Ei+")+",vo="^"+ia+"$",Mp="("+ia+",)*"+ia,Op="^"+Mp+"$",zp=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,e){let r=this.symbolToIndices.get(t);r===void 0?r=[e]:r.push(e),this.symbolToIndices.set(t,r)}},Pp=class{constructor(t,e){var a;this.equation=e,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=e.includes("->")?e.split("->",2):[e,""];if(!r.match(RegExp(Op)))throw new Error("Invalid LHS term");if(r.split(",").forEach((s,i)=>{let o=t[i].dims.slice();if(!s.match(RegExp(vo)))throw new Error("Invalid LHS term");let l=this.processTerm(s,!0,o,i);this.lhs.push(l)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([s,i])=>i.count===1||s==="...").map(([s])=>s).join("");else if(!n.match(RegExp(ia)))throw new Error("Invalid RHS");(a=n.match(RegExp(Ei,"g")))==null||a.forEach(s=>{if(s==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(s);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(t,e,r){let n=this.symbolToInfo.get(t);if(n!==void 0){if(n.dimValue!==e&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:e,inputIndices:[r]};this.symbolToInfo.set(t,n)}processTerm(t,e,r,n=-1){let a=r.length,s=!1,i=[],o=0;if(!t.match(RegExp(vo))&&!e&&t!=="")throw new Error("Invalid LHS term");let l=t.match(RegExp(Ei,"g")),u=new zp(n);return l==null||l.forEach((d,h)=>{if(d==="..."){if(s)throw new Error("Only one ellipsis is allowed per input term");s=!0;let m=a-l.length+1;if(m<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(o,o+m),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 g=0;gt+"_max",Rp=(t,e,r,n)=>{let a=t.map(u=>u.length).map((u,d)=>Q(`input${d}`,e,u)),s=X.size(n),i=_e("output",e,n.length),o=[...r.symbolToInfo.keys()].filter(u=>!r.rhs.symbolToIndices.has(u)),l=u=>{let d=[],h="var prod = 1.0;",m="var sum = 0.0;",g="sum += prod;",p=[],w=[],v=[],S=[],$=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((T,A)=>{var z;if(r.rhs.symbolToIndices.has(A)){let R=(z=r.rhs.symbolToIndices.get(A))==null?void 0:z[0];R!==void 0&&r.lhs.forEach((V,j)=>{if(T.inputIndices.includes(j)){let q=V.symbolToIndices.get(A);if(q===void 0)throw new Error("Invalid symbol error");q.forEach(fe=>{d.push(`${a[j].indicesSet(`input${j}Indices`,fe,i.indicesGet("outputIndices",R))}`)})}})}else r.lhs.forEach((R,V)=>{if(T.inputIndices.includes(V)){let j=R.symbolToIndices.get(A);if(j===void 0)throw new Error("Invalid symbol error");j.forEach(q=>{p.push(`${a[V].indicesSet(`input${V}Indices`,q,`${A}`)}`)}),S.push(`prod *= ${a[V].getByIndices(`input${V}Indices`)};`)}}),w.push(`for(var ${A}: u32 = 0; ${A} < uniforms.${$o(A)}; ${A}++) {`),v.push("}")});let E=$?[...d,`let sum = ${a.map((T,A)=>T.getByIndices(`input${A}Indices`)).join(" * ")};`]:[...d,m,...w,...p,h,...S,g,...v];return` ${u.registerUniforms(o.map(T=>({name:`${$o(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...a,i)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${a.map((T,A)=>`var input${A}Indices: ${a[A].type.indices};`).join(` `)} ${E.join(` `)}; ${i.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:t.map(()=>"rank")},getRunData:()=>{let u=o.filter(h=>r.symbolToInfo.has(h)).map(h=>{var m;return{type:12,data:((m=r.symbolToInfo.get(h))==null?void 0:m.dimValue)||0}});u.push({type:12,data:s});let d=t.map((h,m)=>[...we(h)]).reduce((h,m)=>h.concat(m),u);return d.push(...we(n)),{outputs:[{dims:n,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d}},getShaderSource:l}},Bp=(t,e)=>{let r=new Pp(t.inputs,e.equation),n=r.outputDims,a=t.inputs.map((s,i)=>s.dims);t.compute(Rp(a,t.inputs[0].dataType,r,n))},Dp=t=>{let e=t.equation.replace(/\s+/g,"");return Ke({equation:e})}}),Np,xo,Fp,Lp,Up,qy=te(()=>{xe(),Oe(),Ie(),Np=t=>{if(!t||t.length!==2)throw new Error("Expand requires 2 input.");let e=t[0].dims,r=Array.from(t[1].getBigInt64Array(),Number),n=r.length{let r=t.length-e.length,n=[];for(let a=0;at.length>e.length?xo(t,e):xo(e,t),Lp=t=>{let e=t[0].dims,r=Array.from(t[1].getBigInt64Array(),Number),n=Fp(e,r),a=t[0].dataType,s=a===9?4:1,i=Math.ceil(X.size(n)/s),o=u=>{let d=Q("input",a,e.length,s),h=_e("output",a,n.length,s),m;if(a===9){let g=(p,w,v="")=>` let outputIndices${w} = ${h.offsetToIndices(`outputOffset + ${w}u`)}; let offset${w} = ${d.broadcastedIndicesToOffset(`outputIndices${w}`,h)}; let index${w} = offset${w} / 4u; let component${w} = offset${w} % 4u; ${p}[${w}] = ${v}(${d.getByOffset(`index${w}`)}[component${w}]); `;m=` let outputOffset = global_idx * ${s}; var data = vec4(0); ${g("data",0,"u32")} ${g("data",1,"u32")} ${g("data",2,"u32")} ${g("data",3,"u32")} ${h.setByOffset("global_idx","data")} }`}else m=` let outputIndices = ${h.offsetToIndices("global_idx")}; let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",h)}; ${h.setByOffset("global_idx",d.getByOffset("inputOffset"))} }`;return` ${u.registerUniform("vec_size","u32").declareVariables(d,h)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${m}`},l=[{type:12,data:i},...we(e,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:o,getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:l})}},Up=t=>{Np(t.inputs),t.compute(Lp(t.inputs),{inputs:[0]})}}),Wp,Vp,Ky=te(()=>{xe(),Oe(),Ie(),so(),Wp=t=>{let e=t[0].dataType,r=X.size(t[0].dims),n=X.size(t[1].dims),a=n%4===0,s=i=>{let o=Q("x",e,[1],4),l=Q("bias",e,[1],4),u=_e("y",e,[1],4),d=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],h=g=>` let bias${g}_offset: u32 = (global_idx * 4 + ${g}) % uniforms.bias_size; let bias${g} = ${l.getByOffset(`bias${g}_offset / 4`)}[bias${g}_offset % 4];`,m=a?` let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${h(0)}${h(1)}${h(2)}${h(3)} let bias = ${o.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(d).declareVariables(o,l,u)} ${ao(Ot(e))} ${i.mainStart(Sn)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${o.getByOffset("global_idx")}; ${m} let x_in = x + bias; ${u.setByOffset("global_idx",io("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${a}`,inputDependencies:["type","type"]},getShaderSource:s,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Sn/4)}})}},Vp=t=>{t.inputs.length<2||X.size(t.inputs[1].dims)===0?Oc(t):t.compute(Wp(t.inputs))}}),Gp,Hp,jp,qp,Yy=te(()=>{xe(),Oe(),ct(),Ie(),Gp=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},Hp=(t,e)=>{let r=t[0].dims,n=t[1].dims,a=r.length,s=X.normalizeAxis(e.axis,a),i=r.slice(0);i.splice(s,1,...n);let o=r[s],l=t[0].dataType===9?4:1,u=Math.ceil(X.size(i)/l),d=[{type:12,data:u},{type:6,data:o},{type:12,data:s},...we(t[0].dims,t[1].dims,i)],h=m=>{let g=Q("data",t[0].dataType,t[0].dims.length,l),p=Q("inputIndices",t[1].dataType,t[1].dims.length),w=_e("output",t[0].dataType,i.length,l),v=$=>{let E=n.length,T=`var indicesIndices${$} = ${p.type.indices}(0);`;for(let A=0;A1?`indicesIndices${$}[${A}]`:`indicesIndices${$}`} = ${i.length>1?`outputIndices${$}[uniforms.axis + ${A}]`:`outputIndices${$}`};`;T+=` var idx${$} = ${p.getByIndices(`indicesIndices${$}`)}; if (idx${$} < 0) { idx${$} = idx${$} + uniforms.axisDimLimit; } var dataIndices${$} : ${g.type.indices}; `;for(let A=0,z=0;A1?`dataIndices${$}[${A}]`:`dataIndices${$}`} = u32(idx${$});`,z+=E):(T+=`${a>1?`dataIndices${$}[${A}]`:`dataIndices${$}`} = ${i.length>1?`outputIndices${$}[${z}]`:`outputIndices${$}`};`,z++);return T},S;if(t[0].dataType===9){let $=(E,T,A="")=>` let outputIndices${T} = ${w.offsetToIndices(`outputOffset + ${T}u`)}; ${v(T)}; let offset${T} = ${g.indicesToOffset(`dataIndices${T}`)}; let index${T} = offset${T} / 4u; let component${T} = offset${T} % 4u; ${E}[${T}] = ${A}(${g.getByOffset(`index${T}`)}[component${T}]); `;S=` let outputOffset = global_idx * ${l}; var value = vec4(0); ${$("value",0,"u32")} ${$("value",1,"u32")} ${$("value",2,"u32")} ${$("value",3,"u32")} ${w.setByOffset("global_idx","value")} `}else S=` let outputIndices = ${w.offsetToIndices("global_idx")}; ${v("")}; let value = ${g.getByIndices("dataIndices")}; ${w.setByOffset("global_idx","value")}; `;return` ${m.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,p,w)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${S} }`};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:d}),getShaderSource:h}},jp=t=>Ke({axis:t.axis}),qp=(t,e)=>{let r=t.inputs;Gp(r),t.compute(Hp(t.inputs,e))}}),Kp,Yp,Xp,Qp,Xy=te(()=>{xe(),Oe(),ct(),Ie(),Kp=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.`)},Yp=(t,e)=>{let r=t[0].dims,n=t[0].dataType,a=r.length,s=t[1].dims,i=t[1].dataType,o=X.normalizeAxis(e.axis,a),l=r[o],u=s.slice(0),d=X.size(u),h=Q("input",n,a),m=Q("indicesInput",i,s.length),g=_e("output",n,u.length),p=[{type:12,data:d},{type:6,data:l},{type:12,data:o}];return p.push(...we(r,s,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:w=>` ${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(h,m,g)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${g.offsetToIndices("global_idx")}; var idx = ${m.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${h.type.indices}(outputIndices); ${h.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${h.getByIndices("inputIndices")}; ${g.setByOffset("global_idx","value")}; }`}},Xp=t=>Ke({axis:t.axis}),Qp=(t,e)=>{let r=t.inputs;Kp(r),t.compute(Yp(t.inputs,e))}}),Zp,Jp,eh,th,Qy=te(()=>{xe(),Oe(),Ie(),Zp=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")},Jp=(t,e)=>{let r=t[0].dims.slice(),n=t[1].dims.slice(),[a,s,i]=Bu.getShapeOfGemmResult(r,e.transA,n,e.transB,t.length===3?t[2].dims:void 0),o=[a,s];if(!o)throw new Error("Can't use gemm on the given tensors");let l=X.size(o),u=[{type:12,data:l},{type:12,data:a},{type:12,data:s},{type:12,data:i},{type:1,data:e.alpha},{type:1,data:e.beta}],d=["type","type"];t.length===3&&(u.push(...we(t[2].dims)),d.push("rank")),u.push(...we(o));let h=m=>{let g="";e.transA&&e.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":e.transA&&!e.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!e.transA&&e.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!e.transA&&!e.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let p=e.alpha===1?"":"value *= uniforms.alpha;",w=Q("a",t[0].dataType,t[0].dims),v=Q("b",t[1].dataType,t[1].dims),S=w.type.value,$=null,E=[w,v];t.length===3&&($=Q("c",t[2].dataType,t[2].dims.length),E.push($));let T=_e("output",t[0].dataType,o.length);E.push(T);let A=[{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` ${m.registerUniforms(A).declareVariables(...E)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${S}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${g} } ${p} ${$!=null?`let cOffset = ${$.broadcastedIndicesToOffset("vec2(m, n)",T)}; value += ${S}(uniforms.beta) * ${$.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:h}},eh=t=>{let e=t.transA,r=t.transB,n=t.alpha,a=t.beta;return{transA:e,transB:r,alpha:n,beta:a,cacheKey:`${t.transA};${t.transB};${t.alpha===1}`}},th=(t,e)=>{Zp(t.inputs),t.compute(Jp(t.inputs,e))}}),rh,nh,ah,ih,Zy=te(()=>{xe(),Oe(),Ie(),rh=(t,e)=>{let r=t[0].dims,n=r,a=2,s=X.sizeToDimension(r,a),i=X.sizeFromDimension(r,a),o=st(i),l=i/o,u=[r[0],r[1],l],d=["rank","type","type"],h=[{type:12,data:i},{type:12,data:l}];h.push(...we(u,u));let m=g=>{let p=Q("x",t[0].dataType,u.length,o),w=Q("scale",t[1].dataType,t[1].dims),v=Q("bias",t[2].dataType,t[2].dims),S=_e("output",t[0].dataType,u.length,o),$=[p,w,v,S],E=p.type.value,T=o===1?"f32":`vec${o}`,A=64,z=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${T}, ${A}>; const workgroupSize = ${A}u; ${g.registerUniforms(z).declareVariables(...$)} ${g.mainStart(A)} 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 = ${T}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${T}(${p.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 = ${Dr("workgroupShared[0]",o)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${T}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${T}(${p.get("batch","channel","h")}) - ${T}(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 = ${Dr("workgroupShared[0]",o)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); let channelScale = invStdDev * f32(${w.getByOffset("channel")}); let channelShift = f32(${v.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${p.get("batch","channel","h")} * ${E}(${T}(channelScale)) + ${E}(${T}(channelShift)); ${S.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${e.epsilon};${o}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:s},programUniforms:h}),getShaderSource:m}},nh=(t,e,r,n,a,s,i,o)=>{let l=st(i),u=64,d=l===1?"vec2f":`mat2x${l}f`,h=l===1?"f32":`vec${l}f`,m=(z,R)=>`${d}(${z}, ${R})`,g=a*i/l,p=Math.ceil(s/u),w=["type"],v=[{type:12,data:p},{type:12,data:s},{type:12,data:Math.floor(i/l)},{type:12,data:Math.floor(s*i/l)}],S=z=>{let R=Q("input",e.dataType,e.dims,l);return` ${z.declareVariables(R)} @group(0) @binding(1) var output : array<${d}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${z.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 = ${Sr("f32",l)}; var squaredSum = ${Sr("f32",l)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${h}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${m("sum","squaredSum")}; }`},$=t.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:[a,i,u,2],dataType:1}],dispatchGroup:{x:a*i/l},programUniforms:v}),getShaderSource:S},{inputs:[e],outputs:[-1]})[0],E=[{type:12,data:g},{type:12,data:s},{type:12,data:Math.floor(i/l)},{type:12,data:Math.floor(u*i/l)}],T=["type","type","type"],A=z=>{let R=Q("scale",r.dataType,r.dims,l),V=Q("bias",n.dataType,n.dims,l);return` @group(0) @binding(0) var input : array<${d}>; @group(0) @binding(1) var scale : array<${R.type.storage}>; @group(0) @binding(2) var bias : array<${V.type.storage}>; @group(0) @binding(3) var output : array<${d}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${z.mainStart()} ${z.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 = ${Sr("f32",l)}; var squaredSum = ${Sr("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 * ${h}(scale[currentChannelNumber]); let channelShift = ${h}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${m("channelScale","channelShift")}; }`};return t.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:[a,i,2],dataType:1}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:E}),getShaderSource:A},{inputs:[$,r,n],outputs:[-1]})[0]},ah=(t,e,r)=>{let n=e[0].dims,a=n,s=n[0],i=n[n.length-1],o=X.sizeFromDimension(n,1)/i,l=st(i),u=X.size(a)/l,d=[{type:12,data:o},{type:12,data:Math.floor(i/l)}],h=["type","type"],m=nh(t,e[0],e[1],e[2],s,o,i,r.epsilon),g=p=>{let w=_t(e[0].dataType),v=l===1?"vec2f":`mat2x${l}f`,S=l===1?w:`vec${l}<${w}>`,$=Q("input",e[0].dataType,e[0].dims,l),E=_e("output",e[0].dataType,a,l);return` @group(0) @binding(0) var input : array<${$.type.storage}>; @group(0) @binding(1) var scaleInput : array<${v}>; @group(0) @binding(2) var output : array<${E.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${p.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], ${S}(scale[0]), ${S}(scale[1])); }`};t.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:g},{inputs:[e[0],m]})},ih=(t,e)=>{e.format==="NHWC"?ah(t,t.inputs,e):t.compute(rh(t.inputs,e))}}),sh,oh,lh,Jy=te(()=>{xe(),Oe(),Ie(),sh=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},oh=(t,e,r)=>{let n=e.simplified,a=t[0].dims,s=t[1],i=!n&&t[2],o=a,l=X.normalizeAxis(e.axis,a.length),u=X.sizeToDimension(a,l),d=X.sizeFromDimension(a,l),h=X.size(s.dims),m=i?X.size(i.dims):0;if(h!==d||i&&m!==d)throw new Error(`Size of X.shape()[axis:] == ${d}. Size of scale and bias (if provided) must match this. Got scale size of ${h} and bias size of ${m}`);let g=[];for(let A=0;A1,$=r>2,E=A=>{let z=_t(t[0].dataType),R=[Q("x",t[0].dataType,t[0].dims,p),Q("scale",s.dataType,s.dims,p)];i&&R.push(Q("bias",i.dataType,i.dims,p)),R.push(_e("output",t[0].dataType,o,p)),S&&R.push(_e("mean_data_output",1,g)),$&&R.push(_e("inv_std_output",1,g));let V=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${A.registerUniforms(V).declareVariables(...R)} ${A.mainStart()} ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Sr("f32",p)}; var mean_square_vector = ${Sr("f32",p)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${kn(z,p,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Dr("mean_vector",p)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Dr("mean_square_vector",p)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${kn(z,p,"x[j + offset]")}; let f32scale = ${kn(z,p,"scale[j]")}; output[j + offset] = ${R[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${kn(z,p,"bias[j]")}`:""} ); } ${S?"mean_data_output[global_idx] = mean":""}; ${$?"inv_std_output[global_idx] = inv_std_dev":""}; }`},T=[{dims:o,dataType:t[0].dataType}];return S&&T.push({dims:g,dataType:1}),$&&T.push({dims:g,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${p};${r};${n}`,inputDependencies:w},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:v}),getShaderSource:E}},lh=(t,e)=>{sh(t.inputs),t.compute(oh(t.inputs,e,t.outputCount))}}),uh,dh,ch,ph,ew=te(()=>{xe(),Oe(),ct(),Ie(),uh=(t,e)=>{if(t.length<3||t.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=t[0],n=r.dims.length;if(r.dims[n-1]!==e.k)throw new Error("The last dim of input shape does not match the k value");let a=Math.floor((e.k+e.blockSize-1)/e.blockSize),s=e.blockSize/8*e.bits,i=t[1];if(!X.areEqual(i.dims,[e.n,a,s]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=t[2].dims;if(X.size(o)!==e.n*a)throw new Error("scales input size error.");if(t.length===4){let l=t[3].dims,u=e.bits>4?e.n*a:e.n*Math.floor((a+1)/2);if(X.size(l)!==u)throw new Error("zeroPoints input size error.")}},dh=(t,e,r,n)=>{let a=t[0].dims,s=a.length,i=Math.floor((e.k+e.blockSize-1)/e.blockSize),o=a[s-2],l=e.k,u=e.n,d=a.slice(0,s-2),h=X.size(d),m=e.blockSize/8*e.bits/4,g=t[0].dataType,p=st(o),w=st(e.k),v=st(m),S=ra(g),$=o*i*S,E=Math.floor(n/$),T=i<=r[0]&&E>0,A=!T||E>=4?st(u):E>=2&&st(u)>=2?2:1,z=d.concat([o,u]),R=X.size(z)/A/p,V=T?[]:[{type:12,data:R},{type:12,data:e.blockSize}],j=[h,o,l/w],q=X.convertShape(t[1].dims).slice();q.splice(-1,1,m/v),V.push(...we(j)),V.push(...we(q)),V.push(...we(t[2].dims)),t.length===4&&V.push(...we(X.convertShape(t[3].dims)));let fe=[h,o,u/A];V.push(...we(fe));let ee=ne=>{let se=j.length,D=Q("a",t[0].dataType,se,w),M=Q("b",12,q.length,v),G=Q("scales",t[2].dataType,t[2].dims.length),K=[D,M,G],pe=t.length===4?Q("zero_points",12,t[3].dims.length):void 0;pe&&K.push(pe);let le=fe.length,N=_e("output",t[0].dataType,le,A),ae=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],de=_t(t[0].dataType),Se=(()=>{switch(w){case 1:return`array<${de}, 8>`;case 2:return`mat4x2<${de}>`;case 4:return`mat2x4<${de}>`;default:throw new Error(`${w}-component is not supported.`)}})(),Te=` for (var word: u32 = 0; word < ${m}; word += ${v}) { ${M.indicesSet("b_indices","2","word")}; let b_data = ${M.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${v}; i++) { let b_value: u32 = ${v===1?"b_data":"b_data[word + i]"}; let b_mask: u32 = 0x0F0F0F0Fu; let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); let b_quantized_values = ${Se}(${Array.from({length:4},(ot,je)=>`${de}(b_value_lower[${je}]), ${de}(b_value_upper[${je}])`).join(", ")}); let b_dequantized_values = ${w===1?`${Se}(${Array.from({length:8},(ot,je)=>`(b_quantized_values[${je}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${Se}(${Array(8).fill("zero_point").join(",")})) * scale;`}; // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 for (var m: u32 = 0; m < ${T?o:p}u; m++) { ${D.indicesSet("a_indices",se-2,T?"m":`row * ${p} + m`)}; ${D.indicesSet("a_indices",se-1,"word_offset")}; var input_offset = ${D.indicesToOffset("a_indices")}; var a_data: ${Se}; for (var j: u32 = 0; j < ${8/w}; j++) { a_data[j] = ${D.getByOffset("input_offset")}; input_offset++; } ${T?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${A>1?"[c]":""} += ${Array.from({length:8/w},(ot,je)=>`${w===1?`a_data[${je}] * b_dequantized_values[${je}]`:`dot(a_data[${je}], b_dequantized_values[${je}])`}`).join(" + ")}; } word_offset += ${8/w}; } }`,Xe=pe?` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${pe.getByOffset("zero_point_index")}; }`:"";return T?` var workgroup_shared: array<${N.type.value}, ${o*i}>; ${ne.declareVariables(...K,N)} ${ne.mainStart([i,1,1])} var a_indices: ${D.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${D.indicesSet("a_indices","0","batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${A}; c++) { let col_times_components_plus_c = col * ${A} + c; ${pe?` var zero_point_bytes_per_col: u32 = (${i} + 1) / 2; var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; var zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); var zero_point_word: u32 = ${pe.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} var b_indices: ${M.type.indices}; ${M.indicesSet("b_indices","0","col_times_components_plus_c")}; // The scale and zero points are computed per block. var scales_index = col_times_components_plus_c * ${i} + block; let scale = ${G.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${de}(${pe?"(zero_point_word) & 0xFu":8}); ${M.indicesSet("b_indices","1","block")}; var word_offset: u32 = block * ${e.blockSize/w}; var workgroup_shared_offset: u32 = block * ${o}; ${Te} } workgroupBarrier(); if (local_id.x == 0u) { var output_indices: ${N.type.indices}; ${N.indicesSet("output_indices","0","batch")}; ${N.indicesSet("output_indices",le-1,"col")}; ${N.indicesSet("output_indices",le-2,"0")}; var output_offset = ${N.indicesToOffset("output_indices")}; for (var m: u32 = 0u; m < ${o}u; m++) { var output_value: ${N.type.value} = ${N.type.value}(0); var workgroup_shared_offset: u32 = m; for (var b: u32 = 0u; b < ${i}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${o}; } ${N.setByOffset("output_offset","output_value")}; output_offset += ${u/A}; } } }`:` ${ne.registerUniforms(ae).declareVariables(...K,N)} ${ne.mainStart()} ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${N.type.value}, ${p}>; var output_indices = ${N.offsetToIndices("global_idx")}; var col = ${N.indicesGet("output_indices",le-1)}; var row = ${N.indicesGet("output_indices",le-2)}; var a_indices: ${D.type.indices} = output_indices; // Two zero points are packed into one byte because uniforms.bits <= 4. // zero_point_offset is either 0 or 4. It is bit offset within one byte. // TODO support zero_point_offset for bits > 4 ${pe?` var zero_point_abs_offset = col * ${A} * ((${i} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${pe.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} var scale_index = col * ${i*A}; var b_indices: ${M.type.indices}; for (var c: u32 = 0; c < ${A}; c++) { ${M.indicesSet("b_indices","0",`col * ${A} + c`)}; var block_offset: u32 = 0; for (var block: u32 = 0; block < ${i}; block++) { // The scale and zero points are computed per block. let scale = ${G.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${de}(${pe?"extractBits(zero_point_word, zero_point_offset, 4)":8}); ${M.indicesSet("b_indices","1","block")}; var word_offset: u32 = block_offset; ${Te} scale_index++; ${Xe} block_offset += uniforms.block_size / ${w}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${pe?`if (zero_point_offset % 8 > 0) { ${Xe} }`:""} } for (var k: u32 = 0u; k < ${p}u; k++) { ${N.indicesSet("output_indices",le-2,`${p} * row + k`)}; ${N.setByIndices("output_indices","output_values[k]")} } }`};return{name:T?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${e.cacheKey};${o};${g};${t.length}`,inputDependencies:Array(t.length).fill("rank")},getRunData:()=>({outputs:[{dims:z,dataType:g}],name:T?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:T?{x:1,y:Math.ceil(u/A),z:h}:{x:Math.ceil(R/64)},programUniforms:V}),getShaderSource:ee}},ch=(t,e)=>{uh(t.inputs,e);let r=t.getMaxComputeWorkgroupSizes(),n=t.getMaxComputeWorkgroupStoragesize();t.compute(dh(t.inputs,e,r,n))},ph=t=>Ke(t)}),Ct,hh,fh,So,mh,Ci,gh,tw=te(()=>{xe(),Oe(),ct(),Hs(),Hd(),Ie(),aa(),Ct=(t,e)=>t.length>e&&t[e].dims.length>0&&X.size(t[e].dims)>0?t[e]:void 0,hh=(t,e)=>{let r=t[0],n=Ct(t,1),a=Ct(t,2),s=Ct(t,3),i=Ct(t,4),o=Ct(t,5),l=Ct(t,6),u=Ct(t,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,h=r.dims[0],m=r.dims[1],g=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:e.numHeads*r.dims[4],p=m,w=0,v=0,S=Math.floor(g/e.numHeads);if(l&&u){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==h||l.dims[1]!==e.numHeads||l.dims[3]!==S)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==h||u.dims[1]!==e.numHeads||u.dims[3]!==S)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');w=l.dims[2],v=l.dims[2]}else if(l||u)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let $;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');$=2,p=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==e.numHeads||n.dims[3]!==2||n.dims[4]!==S)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');$=5,p=n.dims[1]}else{if(n.dims[1]!==e.numHeads||n.dims[3]!==S)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,p=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==e.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(s){if(s.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(a&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let E=0;if(i){E=8;let V=i.dims;throw V.length===1?V[0]===h?E=1:V[0]===3*h+2&&(E=3):V.length===2&&V[0]===h&&V[1]===p&&(E=5),E===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let T=!1,A=g;if(a){if(a.dims.length!==3&&a.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(a.dims.length===3){if(p!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');A=a.dims[2]}else{if(p!==a.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');A=a.dims[1]*a.dims[3],T=!0}}let z=w+p,R=!1;if(i)throw new Error("Key padding mask is not supported");if(o){if(o.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(o.dims[0]!==h&&o.dims[0]!==1||o.dims[1]!==e.numHeads||o.dims[2]!==m||o.dims[3]!==z)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:h,sequenceLength:m,pastSequenceLength:w,kvSequenceLength:p,totalSequenceLength:z,maxSequenceLength:v,inputHiddenSize:0,hiddenSize:g,vHiddenSize:A,headSize:S,vHeadSize:Math.floor(A/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:E,scale:e.scale,broadcastResPosBias:R,passPastInKv:T,qkvFormat:$}},fh=t=>Ke({...t}),So=Ke({perm:[0,2,1,3]}),mh=(t,e,r,n,a,s,i)=>{let o=[n,a,s],l=X.size(o),u=[{type:12,data:l},{type:12,data:i},{type:12,data:s}],d=h=>{let m=_e("qkv_with_bias",e.dataType,o),g=Q("qkv",e.dataType,o),p=Q("bias",r.dataType,o),w=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${h.registerUniforms(w).declareVariables(g,p,m)} ${h.mainStart()} ${h.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:d},{inputs:[e,r],outputs:[-1]})[0]},Ci=(t,e,r,n,a,s,i,o)=>{let l=s;if(i){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=mh(t,s,i,e,n,r*a,o),l=l.reshape([e,n,r,a]),t.compute(kr(l,So.perm),{inputs:[l],outputs:[-1]})[0]}else return s.dims.length===3&&(l=s.reshape([e,n,r,a])),t.compute(kr(l,So.perm),{inputs:[l],outputs:[-1]})[0]},gh=(t,e)=>{let r=hh(t.inputs,e),n=t.inputs[0],a=Ct(t.inputs,1),s=Ct(t.inputs,2),i=Ct(t.inputs,3),o=Ct(t.inputs,4),l=Ct(t.inputs,5),u=Ct(t.inputs,6),d=Ct(t.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((a==null?void 0:a.dims.length)===5)throw new Error("Packed KV is not implemented");let h=a&&s&&a.dims.length===4&&s.dims.length===4,m=Ci(t,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(h)return yi(t,m,a,s,o,void 0,u,d,l,r,e);if(!a||!s)throw new Error("key and value must be provided");let g=Ci(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,a,i,r.hiddenSize),p=Ci(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,s,i,2*r.hiddenSize);yi(t,m,g,p,o,void 0,u,d,l,r,e)}}),_h,yh,wh,bh,vh,$h,xh,Sh,kh,rw=te(()=>{xe(),Oe(),Ie(),_h=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].")}},yh=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ke("uniforms.pads",a,r)}; if (k < 0) { break; } if (k >= i32(${ke("uniforms.x_shape",a,e)})) { break; } offset += k * i32(${ke("uniforms.x_strides",a,e)}); `;return` value = ${t.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},wh=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ke("uniforms.pads",a,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${ke("uniforms.x_shape",a,e)}) - 1); k = k % _2n_1; if(k >= i32(${ke("uniforms.x_shape",a,e)})) { k = _2n_1 - k; } } offset += k * i32(${ke("uniforms.x_strides",a,e)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},bh=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ke("uniforms.pads",a,r)}; if (k < 0) { k = 0; } if (k >= i32(${ke("uniforms.x_shape",a,e)})) { k = i32(${ke("uniforms.x_shape",a,e)}) - 1; } offset += k * i32(${ke("uniforms.x_strides",a,e)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},vh=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ke("uniforms.pads",a,r)}; if (k < 0) { k += i32(${ke("uniforms.x_shape",a,e)}]); } if (k >= i32(${ke("uniforms.x_shape",a,e)})) { k -= i32(${ke("uniforms.x_shape",a,e)}); } offset += k * i32(${ke("uniforms.x_strides",a,e)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},$h=(t,e,r)=>{switch(r.mode){case 0:return yh(t,e,r.pads.length);case 1:return wh(t,e,r.pads.length);case 2:return bh(t,e,r.pads.length);case 3:return vh(t,e,r.pads.length);default:throw new Error("Invalid mode")}},xh=(t,e)=>{let r=X.padShape(t[0].dims.slice(),e.pads),n=t[0].dims,a=X.size(r),s=[{type:12,data:a},{type:6,data:e.pads}];e.mode===0&&s.push({type:t[0].dataType,data:e.value}),s.push(...we(t[0].dims,r));let i=["rank"],o=l=>{let u=_e("output",t[0].dataType,r.length),d=Q("x",t[0].dataType,n.length),h=d.type.value,m=$h(u,n.length,e),g=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&g.push({name:"constant_value",type:h}),` ${l.registerUniforms(g).declareVariables(d,u)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${u.offsetToIndices("global_idx")}; var value = ${h}(0); ${m} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${e.mode}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(X.size(r)/64)},programUniforms:s}),getShaderSource:o}},Sh=(t,e)=>{if(t.length>1){let r=t[1].getBigInt64Array(),n=t.length>=3&&t[2].data?t[2].getFloat32Array()[0]:0,a=t[0].dims.length,s=new Int32Array(2*a).fill(0);if(t.length>=4){let o=t[3].getBigInt64Array();for(let l=0;ls[Number(l)]=Number(o));let i=[];return s.forEach(o=>i.push(o)),{mode:e.mode,value:n,pads:i}}else return e},kh=(t,e)=>{_h(t.inputs);let r=Sh(t.inputs,e);t.compute(xh(t.inputs,r),{inputs:[0]})}}),sa,ko,Eo,Co,To,Eh,Ch,Ao,Io,Th,Ah,Mo,Ih,Mh,Oo,Oh,zh,Ph,Rh,nw=te(()=>{rr(),xe(),Oe(),Ie(),sa=t=>{if(Ue.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},ko=(t,e,r)=>{let n=e.format==="NHWC",a=t.dims.slice();n&&a.splice(1,0,a.pop());let s=Object.hasOwnProperty.call(e,"dilations"),i=e.kernelShape.slice(),o=e.strides.slice(),l=s?e.dilations.slice():[],u=e.pads.slice();hi.adjustPoolAttributes(r,a,i,o,l,u);let d=hi.computePoolOutputShape(r,a,o,l,i,u,e.autoPad),h=Object.assign({},e);s?Object.assign(h,{kernelShape:i,strides:o,pads:u,dilations:l,cacheKey:e.cacheKey}):Object.assign(h,{kernelShape:i,strides:o,pads:u,cacheKey:e.cacheKey});let m=d.slice();return m.push(m.splice(1,1)[0]),[h,n?m:d]},Eo=(t,e)=>{let r=e.format==="NHWC",n=X.size(t),a=X.size(e.kernelShape),s=[{type:12,data:n},{type:12,data:a}],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],d=e.pads[e.pads.length-1],h=!!(u+d);s.push({type:12,data:o},{type:12,data:l},{type:12,data:u},{type:12,data:d}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let m=!1;if(e.kernelShape.length===2){let g=e.kernelShape[e.kernelShape.length-2],p=e.strides[e.strides.length-2],w=e.pads[e.pads.length/2-2],v=e.pads[e.pads.length-2];m=!!(w+v),s.push({type:12,data:g},{type:12,data:p},{type:12,data:w},{type:12,data:v}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[s,i,!0,h,m]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let o=X.computeStrides(e.kernelShape);s.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,d)=>u+d);return[s,i,!!l,!1,!1]}},Co=(t,e,r,n,a,s,i,o,l,u,d,h)=>{let m=a.format==="NHWC",g=e.type.value,p=_e("output",e.type.tensor,n);if(a.kernelShape.length<=2){let w="",v="",S="",$=r-(m?2:1);if(d?w=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${$}] < 0 || xIndices[${$}] >= uniforms.x_shape[${$}]) { pad++; continue; } let x_val = x[${e.indicesToOffset("xIndices")}]; ${s} }`:w=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${$}] = indices[${$}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${e.indicesToOffset("xIndices")}]; ${s} }`,a.kernelShape.length===2){let E=r-(m?3:2);h?v=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${E}] = indices[${E}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${E}] < 0 || xIndices[${E}] >= uniforms.x_shape[${E}]) { pad += i32(uniforms.kw); continue; } `:v=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${E}] = indices[${E}] * uniforms.sh - uniforms.phStart + j; `,S=` } `}return` ${t.registerUniforms(l).declareVariables(e,p)} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${p.offsetToIndices("global_idx")}; var xIndices = ${p.offsetToIndices("global_idx")}; var value = ${g}(${o}); var pad = 0; ${v} ${w} ${S} ${i} output[global_idx] = value; }`}else{if(m)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let w=a.kernelShape.length,v=a.pads.length,S="";return u?S=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${e.indicesToOffset("xIndices")}]; ${s} }`:S=` } let x_val = x[${e.indicesToOffset("xIndices")}]; ${s} `,` ${t.registerUniforms(l).declareVariables(e,p)} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${p.offsetToIndices("global_idx")}; var xIndices = ${p.offsetToIndices("global_idx")}; var offsets: array; var value = ${g}(${o}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${w-1}u; j++) { offsets[j] = offset / ${ke("uniforms.kernelStrides","j",w)}; offset -= offsets[j] * ${ke("uniforms.kernelStrides","j",w)}; } offsets[${w-1}] = offset; isPad = false; for (var j = ${r-w}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${ke("uniforms.strides",`j - ${r-w}u`,w)} + offsets[j - ${r-w}u] - ${ke("uniforms.pads","j - 2u",v)}; ${S} } ${i} output[global_idx] = value; }`}},To=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,Eh=t=>`${To(t)};${t.countIncludePad}`,Ch=t=>`${To(t)};${t.storageOrder};${t.dilations}`,Ao=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}),Io=(t,e,r,n)=>{let[a,s]=ko(e,n,r),i=Q("x",e.dataType,e.dims.length),o=i.type.value,l="value += x_val;",u="";a.countIncludePad?u+=`value /= ${o}(uniforms.kernelSize);`:u+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[d,h,m,g,p]=Eo(s,a);d.push(...we(e.dims,s));let w=["rank"];return{name:t,shaderCache:{hint:`${n.cacheKey};${m};${g};${p}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:s,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(X.size(s)/64)},programUniforms:d}),getShaderSource:v=>Co(v,i,e.dims.length,s.length,a,l,u,0,h,m,g,p)}},Th=t=>{let e=t.count_include_pad!==0,r=Ao(t);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:e,...r,cacheKey:""};return{...n,cacheKey:Eh(n)}},Ah=(t,e)=>{sa(t.inputs),t.compute(Io("AveragePool",t.inputs[0],!1,e))},Mo={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Ih=t=>{let e=t.format;return{format:e,...Mo,cacheKey:e}},Mh=(t,e)=>{sa(t.inputs),t.compute(Io("GlobalAveragePool",t.inputs[0],!0,e))},Oo=(t,e,r,n)=>{let[a,s]=ko(e,n,r),i=` value = max(x_val, value); `,o="",l=Q("x",e.dataType,e.dims.length),u=["rank"],[d,h,m,g,p]=Eo(s,a);return d.push(...we(e.dims,s)),{name:t,shaderCache:{hint:`${n.cacheKey};${m};${g};${p}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:s,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(X.size(s)/64)},programUniforms:d}),getShaderSource:w=>Co(w,l,e.dims.length,s.length,a,i,o,e.dataType===10?-65504:-1e5,h,m,g,p)}},Oh=(t,e)=>{sa(t.inputs),t.compute(Oo("MaxPool",t.inputs[0],!1,e))},zh=t=>{let e=t.storage_order,r=t.dilations,n=Ao(t);if(e!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let a={storageOrder:e,dilations:r,...n,cacheKey:""};return{...a,cacheKey:Ch(a)}},Ph=t=>{let e=t.format;return{format:e,...Mo,cacheKey:e}},Rh=(t,e)=>{sa(t.inputs),t.compute(Oo("GlobalMaxPool",t.inputs[0],!0,e))}}),Bh,Dh,Nh,aw=te(()=>{rr(),xe(),Ie(),Bh=(t,e,r)=>{let n=t===e,a=te&&r>0;if(n||a||s)throw new Error("Range these inputs' contents are invalid.")},Dh=(t,e,r,n)=>{let a=Math.abs(Math.ceil((e-t)/r)),s=[a],i=a,o=[{type:12,data:i},{type:n,data:t},{type:n,data:r},...we(s)],l=u=>{let d=_e("output",n,s.length),h=d.type.value,m=[{name:"outputSize",type:"u32"},{name:"start",type:h},{name:"delta",type:h}];return` ${u.registerUniforms(m).declareVariables(d)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${h}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:o})}},Nh=t=>{let e=0,r=0,n=0;t.inputs[0].dataType===6?(e=t.inputs[0].getInt32Array()[0],r=t.inputs[1].getInt32Array()[0],n=t.inputs[2].getInt32Array()[0]):t.inputs[0].dataType===1&&(e=t.inputs[0].getFloat32Array()[0],r=t.inputs[1].getFloat32Array()[0],n=t.inputs[2].getFloat32Array()[0]),Ue.webgpu.validateInputContent&&Bh(e,r,n),t.compute(Dh(e,r,n,t.inputs[0].dataType),{inputs:[]})}}),Fh,Lh,Uh,Wh,Vh,Gh,Hh,jh,qh,Kh,Yh,zo,Xh,Qh,Zh,Jh,ef,tf,rf,iw=te(()=>{xe(),Oe(),ct(),Ie(),Fh=(t,e)=>{if(t.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),t.length>0){if(e.mode==="linear"){if(!(t.length===2||t.length===3||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1||t.length===5&&t[0]===1&&t[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(e.mode==="cubic"&&!(t.length===2||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Lh=(t,e,r)=>{e.every(a=>a>=0&&a{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return e.forEach((a,s)=>n[a]=t[s]),n},Uh=(t,e,r,n,a,s)=>{let[i,o,l]=r>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(d=>s.push(d));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(d=>n.push(d)),n.length!==0&&n.length!==u&&r>=18&&n.length!==e.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Fh(n,e),e.axes.length>0&&Lh(n,e.axes,u).forEach((d,h)=>n[h]=d)}if(l>0&&t.length>l&&(t[l].getBigInt64Array().forEach(d=>a.push(Number(d))),a.length!==u||r>=18&&a.length===e.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(e.axes.length>0){if(n.length!==e.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(a.length!==e.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof a<"u"&&n.length>0&&a.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},Wh=(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`)}})()+"}",Vh=(t,e,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(t){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(e<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${t} is not supported`)}})()+"}",Gh=(t,e,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),a=t.length===0?n:t.slice();return e.length>0?(e.forEach((s,i)=>{n[s]=a[i],n[i+r]=a[e.length+i]}),n):a},Hh=(t,e,r,n)=>{let a=[];if(r.length>0)if(n.length>0){if(t.forEach(s=>a.push(s)),Math.max(...n)>t.length)throw new Error("axes is out of bound");n.forEach((s,i)=>a[s]=r[i])}else r.forEach(s=>a.push(s));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");a=t.map((s,i)=>Math.round(s*e[i]))}return a},jh=(t,e,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(s=>e[s]),Number.MAX_VALUE):Math.min(...e,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(s=>e[s]),Number.MIN_VALUE):Math.max(...e,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();e.fill(1,0,e.length);let a=t.slice();return r.axes.length>0?(r.axes.forEach(s=>e[s]=n),r.axes.forEach(s=>a[s]=Math.round(t[s]*e[s]))):(e.fill(n,0,e.length),a.forEach((s,i)=>a[i]=Math.round(s*e[i]))),a},qh=(t,e,r,n,a)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> array<${t.type.value}, ${r.length}> { var original_indices: array<${t.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var scale = ${ke("uniforms.scales","i",n)}; var roi_low = ${ke("uniforms.roi","i",a)}; var roi_hi = ${ke("uniforms.roi",`i + ${e.length}`,a)}; if (scale == 1.0) { original_indices[i] = ${t.type.value}(output_index); } else { var input_shape_i = ${ke("uniforms.input_shape","i",e.length)}; var output_shape_i = ${ke("uniforms.output_shape","i",r.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,Kh=(t,e,r,n,a,s,i)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> ${t.type.indices} { var input_indices: ${t.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${ke("uniforms.scales","i",a)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${ke("uniforms.roi","i",s)}; var roi_hi = ${ke("uniforms.roi",`i + ${r.length}`,s)}; var input_shape_i = ${ke("uniforms.input_shape","i",r.length)}; var output_shape_i = ${ke("uniforms.output_shape","i",n.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; }`,Yh=(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 >= ${ke("uniforms.input_shape","i",e.length)}) { return false; } } return true; }`,zo=(t,e,r,n)=>t.rank>n?` ${t.indicesSet("input_indices",e,"channel")}; ${t.indicesSet("input_indices",r,"batch")}; `:"",Xh=(t,e,r,n,a)=>{let[s,i,o,l]=r.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, ${r[i]} - 1))`)}; ${t.indicesSet("input_indices",o,`max(0, min(col, ${r[o]} - 1))`)}; ${zo(t,l,s,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}]; ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[o]} - 1)) { return ${a}; }`:""}; row = max(0, min(row, ${r[i]} - 1)); col = max(0, min(col, ${r[o]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${r.length>2?`u32(originalIndices[${l}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${s}])`:"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); }`},Qh=(t,e,r,n,a,s,i,o,l,u)=>{let d=r.length===2,[h,m]=d?[0,1]:[2,3],g=t.type.value,p=w=>{let v=w===h?"row":"col";return` fn ${v}CubicInterpolation(input_indices: ${t.type.indices}, output_indices: ${e.type.indices}) -> ${g} { var output_index = ${e.indicesGet("output_indices",w)}; var originalIdx: ${g} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[w]}, ${n[w]}, ${r[w]}, ${s[w]}, ${s[w]} + ${r.length}); var fractOriginalIdx: ${g} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${o} && (originalIdx < 0 || originalIdx > (${r[w]} - 1))) { return ${l}; } var data: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${v}: ${g} = originalIdx + ${g}(i); if (${v} < 0 || ${v} >= ${r[w]}) { ${u?`coefs[i + 1] = 0.0; continue;`:o?`return ${l};`:`${v} = max(0, min(${v}, ${r[w]} - 1));`}; } var input_indices_copy: ${t.type.indices} = input_indices; ${t.indicesSet("input_indices_copy",w,`u32(${v})`)}; data[i + 1] = ${w===h?t.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${p(h)}; ${p(m)}; fn getCubicInterpolationCoefs(s: ${g}) -> array<${g}, 4> { var absS = abs(s); var coeffs: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${g} = 1.0 - absS; var twoMinusAbsS: ${g} = 2.0 - absS; var onePlusAbsS: ${g} = 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<${g}, 4>, coefs: array<${g}, 4>) -> ${g} { var coefsSum: ${g} = 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}) -> ${g} { var input_indices: ${t.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Zh=(t,e,r,n,a)=>{let[s,i,o,l,u]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],d=t.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${d} { var input_indices: ${t.type.indices}; ${t.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; ${t.indicesSet("input_indices",o,`max(0, min(height, ${r[o]} - 1))`)}; ${t.indicesSet("input_indices",l,`max(0, min(width, ${r[l]} - 1))`)}; ${zo(t,u,s,3)} return ${t.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${d} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${d} = originalIndices[${i}]; var height:${d} = originalIndices[${o}]; var width:${d} = originalIndices[${l}]; ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[o]} - 1) || width < 0 || (width > ${r[l]} - 1)) { return ${a}; }`:""}; depth = max(0, min(depth, ${r[i]} - 1)); height = max(0, min(height, ${r[o]} - 1)); width = max(0, min(width, ${r[l]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${r.length>3?`u32(originalIndices[${u}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${s}])`:"0"}; var x111: ${d} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${d} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${d} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${d} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${d} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${d} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${d} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${d} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${d} = abs(depth - ${d}(depth1)); var dx2: ${d} = abs(${d}(depth2) - depth); var dy1: ${d} = abs(height - ${d}(height1)); var dy2: ${d} = abs(${d}(height2) - height); var dz1: ${d} = abs(width - ${d}(width1)); var dz2: ${d} = abs(${d}(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); }`},Jh=(t,e,r,n,a,s)=>{let i=t.dims,o=Gh(s,e.axes,i.length),l=Hh(i,n,a,e.axes),u=n.slice();n.length===0&&(u=i.map(($,E)=>$===0?1:l[E]/$),e.keepAspectRatioPolicy!=="stretch"&&(l=jh(i,u,e)));let d=_e("output",t.dataType,l.length),h=Q("input",t.dataType,i.length),m=X.size(l),g=i.length===l.length&&i.every(($,E)=>$===l[E]),p=e.coordinateTransformMode==="tf_crop_and_resize",w=e.extrapolationValue,v=h.type.value,S=$=>` ${g?"":` ${Wh(e.coordinateTransformMode,v)}; ${(()=>{switch(e.mode){case"nearest":return` ${Yh(h,i)}; ${Vh(e.nearestMode,r,v)}; ${Kh(h,d,i,l,u.length,o.length,p)}; `;case"linear":return` ${qh(d,i,l,u.length,o.length)}; ${(()=>{if(i.length===2||i.length===4)return`${Xh(h,d,i,p,w)}`;if(i.length===3||i.length===5)return`${Zh(h,d,i,p,w)}`;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`${Qh(h,d,i,l,u,o,e.cubicCoeffA,p,e.extrapolationValue,e.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${$.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",o.length).declareVariables(h,d)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${g?"output[global_idx] = input[global_idx];":` let output_indices = ${d.offsetToIndices("global_idx")}; var input_indices: ${h.type.indices}; ${(()=>{switch(e.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${h.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}|${r}|${u.length>0?u:""}|${a.length>0?a:""}|${o.length>0?o:""}|${g}|${i}`,inputDependencies:["rank"]},getShaderSource:S,getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},{type:1,data:u},{type:1,data:o},...we(i,l)]})}},ef=t=>{let e=t.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},tf=(t,e)=>{let r=[],n=[],a=[],s=ef(t);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Uh(t.inputs,e,s,r,n,a),t.compute(Jh(t.inputs[0],e,s,r,n,a),{inputs:[0]})},rf=t=>{let e=t.antialias,r=t.axes,n=t.coordinateTransformMode,a=t.cubicCoeffA,s=t.excludeOutside!==0,i=t.extrapolationValue,o=t.keepAspectRatioPolicy,l=t.mode,u=t.nearestMode===""?"simple":t.nearestMode;return Ke({antialias:e,axes:r,coordinateTransformMode:n,cubicCoeffA:a,excludeOutside:s,extrapolationValue:i,keepAspectRatioPolicy:o,mode:l,nearestMode:u})}}),nf,af,sf,sw=te(()=>{xe(),Oe(),ct(),Ie(),nf=(t,e)=>{let[r,n,a,s]=t,{numHeads:i,rotaryEmbeddingDim:o}=e;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!X.areEqual(n.dims,[])&&!X.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(s.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(!X.areEqual(a.dims,s.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=r.dims[0],u=r.dims[r.dims.length-2],d=a.dims[0],h=X.sizeFromDimension(r.dims,1)/u,m=o===0?a.dims[1]*2:h/i;if(o>m)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(l!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(u!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(m/2!==a.dims[1]&&o/2!==a.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${a.dims[1]}`);if(u>d)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},af=(t,e)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:a,scale:s}=e,i=t[0].dims[0],o=X.sizeFromDimension(t[0].dims,1),l=t[0].dims[t[0].dims.length-2],u=o/l,d=t[2].dims[1],h=a===0?d*2:u/n,m=new Array(i,l,u/h,h-d),g=X.computeStrides(m),p=[{type:1,data:s},{type:12,data:m},{type:12,data:g},...t[0].dims.length===3?new Array({type:12,data:[o,u,h,1]}):[],...t[0].dims.length===4?new Array({type:12,data:[o,h,l*h,1]}):[],...we(t[0].dims,t[1].dims,t[2].dims,t[3].dims,t[0].dims)],w=v=>{let S=Q("input",t[0].dataType,t[0].dims.length),$=Q("position_ids",t[1].dataType,t[1].dims.length),E=Q("cos_cache",t[2].dataType,t[2].dims.length),T=Q("sin_cache",t[3].dataType,t[3].dims.length),A=_e("output",t[0].dataType,t[0].dims.length);return v.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:m.length},{name:"global_strides",type:"u32",length:g.length},{name:"input_output_strides",type:"u32",length:g.length}]),` ${v.declareVariables(S,$,E,T,A)} ${v.mainStart(Sn)} let half_rotary_emb_dim = uniforms.${E.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${v.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${$.broadcastedIndicesToOffset("bsnh.xy",_e("",$.type.tensor,2))}; let position_id = u32(${$.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${S.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} - ${S.getByOffset("j")} * ${T.get("position_id","bsnh[3]")}; ${A.setByOffset("i","re")} let im = ${S.getByOffset("i")} * ${T.get("position_id","bsnh[3]")} + ${S.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; ${A.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${A.setByOffset("k",S.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:Ke({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(X.size(m)/Sn)},programUniforms:p})}},sf=(t,e)=>{nf(t.inputs,e),t.compute(af(t.inputs,e))}}),of,lf,uf,ow=te(()=>{xe(),Oe(),Ie(),of=t=>{if(!t||t.length<3)throw new Error("layerNorm requires at least 3 inputs.");let e=t[0],r=t[1],n=t[2];if(e.dataType!==r.dataType||e.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(e.dims.length!==3&&e.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let a=e.dims[e.dims.length-1],s=e.dims[e.dims.length-2];if(r.dims[r.dims.length-1]!==a)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==s)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==a)throw new Error("Gamma must have the same hidden size as input");if(t.length>3){let i=t[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==a)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]!==a)throw new Error("Bias must have the same hidden size as input")}},lf=(t,e,r,n)=>{let a=e.simplified,s=t[0].dims,i=X.size(s),o=s,l=i,u=s.slice(-1)[0],d=n?s.slice(0,-1).concat(1):[],h=!a&&t.length>3,m=t.length>4,g=n&&r>1,p=n&&r>2,w=r>3,v=st(u),S=[{type:12,data:l},{type:12,data:v},{type:12,data:u},{type:1,data:e.epsilon}],$=T=>{let A=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],z=[Q("x",t[0].dataType,t[0].dims,v),Q("skip",t[1].dataType,t[1].dims,v),Q("gamma",t[2].dataType,t[2].dims,v)];h&&z.push(Q("beta",t[3].dataType,t[3].dims,v)),m&&z.push(Q("bias",t[4].dataType,t[4].dims,v)),z.push(_e("output",t[0].dataType,o,v)),g&&z.push(_e("mean_output",1,d)),p&&z.push(_e("inv_std_output",1,d)),w&&z.push(_e("input_skip_bias_sum",t[0].dataType,o,v));let R=_t(t[0].dataType);return` ${T.registerUniforms(A).declareVariables(...z)} ${T.mainStart()} ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")} let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; let offset = global_idx * hidden_size_vectorized; var sum = ${Sr("f32",v)}; var squareSum = ${Sr("f32",v)}; for (var i: u32 = 0; i < hidden_size_vectorized; i++) { let skip_value = skip[offset + i]; let bias_value = ${m?"bias[i]":R+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${w?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${kn(R,v,"value")}; sum += f32_value; squareSum += f32_value * f32_value; } let mean = ${Dr("sum",v)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Dr("squareSum",v)} / f32(uniforms.hidden_size) ${a?"":"- mean * mean"} + uniforms.epsilon); ${g?"mean_output[global_idx] = mean;":""} ${p?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < hidden_size_vectorized; i++) { output[offset + i] = (output[offset + i] ${a?"":`- ${R}(mean)`}) * ${R}(inv_std_dev) * gamma[i] ${h?"+ beta[i]":""}; } }`},E=[{dims:o,dataType:t[0].dataType}];return r>1&&E.push({dims:d,dataType:1}),r>2&&E.push({dims:d,dataType:1}),r>3&&E.push({dims:s,dataType:t[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${v};${g};${p};${w}`,inputDependencies:t.map((T,A)=>"type")},getShaderSource:$,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u/64)},programUniforms:S})}},uf=(t,e)=>{of(t.inputs);let r=[0];t.outputCount>1&&r.push(-3),t.outputCount>2&&r.push(-3),t.outputCount>3&&r.push(3),t.compute(lf(t.inputs,e,t.outputCount,!1),{outputs:r})}}),df,oa,cf,Po,pf,hf,ff,mf,lw=te(()=>{xe(),Oe(),ct(),Ie(),df=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");if(e.axes.length!==0){if(e.axes.length!==e.starts.length||e.axes.length!==e.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(e.starts.length!==e.ends.length)throw new Error("starts and ends must have the same length");t.slice(1).forEach((r,n)=>{if(t[n+1].dataType!==6&&t[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},oa=(t,e)=>{let r=[];if(t.length>e)if(t[e].dataType===7)t[e].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(t[e].dataType===6)t[e].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${e} must be an array of int32 or int64`);return r},cf=(t,e)=>{if(t.length>1){let r=oa(t,1),n=oa(t,2),a=oa(t,3);return a.length===0&&(a=[...Array(t[0].dims.length).keys()]),Ke({starts:r,ends:n,axes:a})}else return e},Po=(t,e,r,n,a)=>{let s=t;return t<0&&(s+=r[n[e]]),a[e]<0?Math.max(0,Math.min(s,r[n[e]]-1)):Math.max(0,Math.min(s,r[n[e]]))},pf=(t,e,r)=>`fn calculateInputIndices(output_indices: ${e.type.indices}) -> ${t.type.indices} { var input_indices: ${t.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${ke("uniforms.input_shape","i",r.length)}; let steps_i = ${ke("uniforms.steps","i",r.length)}; let signs_i = ${ke("uniforms.signs","i",r.length)}; let starts_i = ${ke("uniforms.starts","i",r.length)}; var output_index = ${e.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${t.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,hf=(t,e)=>{let r=t[0].dims,n=X.size(r),a=e.axes.length>0?X.normalizeAxes(e.axes,r.length):[...Array(r.length).keys()],s=oa(t,4);s.forEach(S=>S!==0||(()=>{throw new Error("step cannot be 0")})),s.length===0&&(s=Array(a.length).fill(1));let i=e.starts.map((S,$)=>Po(S,$,r,a,s)),o=e.ends.map((S,$)=>Po(S,$,r,a,s));if(a.length!==i.length||a.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(a.length!==r.length)for(let S=0;SMath.sign(S));s.forEach((S,$,E)=>{if(S<0){let T=(o[$]-i[$])/S,A=i[$],z=A+T*s[$];i[$]=z,o[$]=A,E[$]=-S}});let u=r.slice(0);a.forEach((S,$)=>{u[S]=Math.ceil((o[S]-i[S])/s[S])});let d={dims:u,dataType:t[0].dataType},h=_e("output",t[0].dataType,u.length),m=Q("input",t[0].dataType,t[0].dims.length),g=X.size(u),p=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:s.length}],w=[{type:12,data:g},{type:12,data:i},{type:6,data:l},{type:12,data:s},...we(t[0].dims,u)],v=S=>` ${S.registerUniforms(p).declareVariables(m,h)} ${pf(m,h,r)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${h.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${h.setByOffset("global_idx",m.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${s.length}`,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:w})}},ff=(t,e)=>{df(t.inputs,e);let r=cf(t.inputs,e);t.compute(hf(t.inputs,r),{inputs:[0]})},mf=t=>{let e=t.starts,r=t.ends,n=t.axes;return Ke({starts:e,ends:r,axes:n})}}),gf,_f,yf,wf,uw=te(()=>{xe(),Oe(),ct(),Ie(),gf=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},_f=(t,e)=>{let r=t.dims,n=X.size(r),a=64,s=e.axis;if(s<0&&(s=r.length+s),sS===4?`max(max(${v}.x, ${v}.y), max(${v}.z, ${v}.w))`:S===2?`max(${v}.x, ${v}.y)`:S===3?`max(max(${v}.x, ${v}.y), ${v}.z)`:v,h=Q("x",t.dataType,t.dims,l),m=_e("result",t.dataType,t.dims,l),g=h.type.value,p=_t(t.dataType)==="f32"?`var threadMax = ${g}(-3.402823e+38f);`:`var threadMax = ${g}(-65504.0h);`,w=v=>` var rowMaxShared : ${g}; var rowSumShared : ${g}; var threadShared : array<${g}, ${a}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${g} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${g}) { let index = row * row_stride + col; result[index] = value; } ${v.registerUniform("packedCols","i32").declareVariables(h,m)} ${v.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${a}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${p} 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 = ${g}(${d("threadShared[0]",l)}); } workgroupBarrier(); // find the rows sum var threadSum = ${g}(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 = ${g}(${Dr("threadShared[0]",l)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`;return{name:"Softmax",shaderCache:{hint:`${l}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:t.dataType}],dispatchGroup:{x:o},programUniforms:[{type:6,data:u}]}),getShaderSource:w}},yf=(t,e)=>{gf(t.inputs),t.compute(_f(t.inputs[0],e))},wf=t=>Ke({axis:t.axis})}),bf,vf,$f,xf,Sf,kf,Ef,dw=te(()=>{xe(),Oe(),ct(),Ie(),bf=t=>{if(!t||t.length<1)throw new Error("too few inputs")},vf=(t,e)=>{let r=[],n=e.numOutputs;return t[1].dims[0]>0&&(t[1].getBigInt64Array().forEach(a=>r.push(Number(a))),n=r.length),Ke({numOutputs:n,axis:e.axis,splitSizes:r})},$f=t=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${t}u; i += 1u ) { if (index < ${ke("uniforms.size_in_split_axis","i",t)}) { return i; } } return ${t}u; }`,xf=t=>{let e=t.length,r=[];for(let n=0;n{let r=t[0].dims,n=X.size(r),a=t[0].dataType,s=X.normalizeAxis(e.axis,r.length),i=new Array(e.numOutputs),o=Q("input",a,r.length),l=new Array(e.numOutputs),u=[],d=[],h=0,m=[{type:12,data:n}];for(let p=0;p` ${p.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...i)} ${$f(l.length)} ${xf(i)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${o.offsetToIndices("global_idx")}; var index = ${o.indicesGet("indices",s)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${ke("uniforms.size_in_split_axis","output_number - 1u",l.length)}; ${o.indicesSet("indices",s,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:e.cacheKey,inputDependencies:["rank"]},getShaderSource:g,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:m})}},kf=(t,e)=>{bf(t.inputs);let r=t.inputs.length===1?e:vf(t.inputs,e);t.compute(Sf(t.inputs,r),{inputs:[0]})},Ef=t=>{let e=t.axis,r=t.splitSizes,n=t.numOutputs<0?r.length:t.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Ke({axis:e,numOutputs:n,splitSizes:r})}}),Ro,Cf,Tf,Af,If,cw=te(()=>{xe(),Oe(),Ie(),Ro=t=>Array.from(t.getBigInt64Array(),Number),Cf=t=>{if(!t||t.length!==2)throw new Error("Tile requires 2 inputs.");if(t[0].dataType!==1&&t[0].dataType!==6&&t[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(t[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(t[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ro(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")},Tf=(t,e)=>{let r=[];for(let n=0;n{let e=t[0].dims,r=Ro(t[1]),n=Tf(e,r),a=X.size(n),s=t[0].dataType,i=Q("input",s,e.length),o=_e("output",s,n.length),l=u=>` const inputShape = ${i.indices(...e)}; ${u.registerUniform("output_size","u32").declareVariables(i,o)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${o.offsetToIndices("global_idx")}; var input_indices: ${i.type.indices}; for (var i = 0; i < ${e.length}; i++) { let input_dim_i = ${i.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${o.indicesGet("output_indices","i")} % input_dim_i; ${i.indicesSet("input_indices","i","input_dim_value")} } ${o.setByOffset("global_idx",i.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...we(t[0].dims,n)]}),getShaderSource:l}},If=t=>{Cf(t.inputs),t.compute(Af(t.inputs),{inputs:[0]})}}),Mf,Of,zf,pw=te(()=>{xe(),Oe(),Ie(),Mf=(t,e,r,n,a)=>{let s=_e("output_data",a,r.length,4),i=Q("a_data",e[1].dataType,e[1].dims.length,4),o=Q("b_data",e[2].dataType,e[2].dims.length,4),l=Q("c_data",e[0].dataType,e[0].dims.length,4),u,d=(h,m,g)=>`select(${m}, ${h}, ${g})`;if(!n)u=s.setByOffset("global_idx",d(i.getByOffset("global_idx"),o.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let h=(m,g,p="")=>{let w=`a_data[index_a${g}][component_a${g}]`,v=`b_data[index_b${g}][component_b${g}]`,S=`bool(c_data[index_c${g}] & (0xffu << (component_c${g} * 8)))`;return` let output_indices${g} = ${s.offsetToIndices(`global_idx * 4u + ${g}u`)}; let offset_a${g} = ${i.broadcastedIndicesToOffset(`output_indices${g}`,s)}; let offset_b${g} = ${o.broadcastedIndicesToOffset(`output_indices${g}`,s)}; let offset_c${g} = ${l.broadcastedIndicesToOffset(`output_indices${g}`,s)}; let index_a${g} = offset_a${g} / 4u; let index_b${g} = offset_b${g} / 4u; let index_c${g} = offset_c${g} / 4u; let component_a${g} = offset_a${g} % 4u; let component_b${g} = offset_b${g} % 4u; let component_c${g} = offset_c${g} % 4u; ${m}[${g}] = ${p}(${d(w,v,S)}); `};a===9?u=` var data = vec4(0); ${h("data",0,"u32")} ${h("data",1,"u32")} ${h("data",2,"u32")} ${h("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` ${h("output_data[global_idx]",0)} ${h("output_data[global_idx]",1)} ${h("output_data[global_idx]",2)} ${h("output_data[global_idx]",3)} `}return` ${t.registerUniform("vec_size","u32").declareVariables(l,i,o,s)} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${u} }`},Of=t=>{let e=t[1].dims,r=t[2].dims,n=t[0].dims,a=t[1].dataType,s=!(X.areEqual(e,r)&&X.areEqual(r,n)),i=e,o=X.size(e);if(s){let u=xn.calcShape(xn.calcShape(e,r,!1),n,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,o=X.size(i)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>Mf(u,t,i,s,a),getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...we(n,e,r,i)]})}},zf=t=>{t.compute(Of(t.inputs))}}),Pf,hw=te(()=>{Py(),Hd(),Ry(),By(),Dy(),Ny(),Nd(),dp(),Vy(),Gy(),Hy(),jy(),qy(),Ky(),Yy(),Xy(),Qy(),Zy(),Jy(),sp(),ew(),tw(),rw(),nw(),aw(),eo(),iw(),sw(),ow(),lw(),uw(),dw(),cw(),aa(),so(),pw(),Pf=new Map([["Abs",[ec]],["Acos",[tc]],["Acosh",[rc]],["Add",[Lc]],["ArgMax",[Od,ro]],["ArgMin",[Md,ro]],["Asin",[nc]],["Asinh",[ac]],["Atan",[ic]],["Atanh",[sc]],["Attention",[Gd]],["AveragePool",[Ah,Th]],["BatchNormalization",[Yd]],["BiasAdd",[Zd]],["BiasSplitGelu",[Dc]],["Cast",[lc,oc]],["Ceil",[cc]],["Clip",[dc]],["Concat",[Bd,Dd]],["Conv",[yo,_o]],["ConvTranspose",[$p,_p]],["Cos",[pc]],["Cosh",[hc]],["CumSum",[Sp,kp]],["DepthToSpace",[Ap,Ip]],["Div",[Uc]],["Einsum",[Bp,Dp]],["Elu",[fc,wi]],["Equal",[Wc]],["Erf",[mc]],["Exp",[gc]],["Expand",[Up]],["FastGelu",[Vp]],["Floor",[_c]],["FusedConv",[yo,_o]],["Gather",[qp,jp]],["GatherElements",[Qp,Xp]],["Gelu",[yc]],["Gemm",[th,eh]],["GlobalAveragePool",[Mh,Ih]],["GlobalMaxPool",[Rh,Ph]],["Greater",[jc]],["GreaterOrEqual",[Kc]],["HardSigmoid",[Ec,kc]],["InstanceNormalization",[ih]],["LayerNormalization",[lh]],["LeakyRelu",[wc,wi]],["Less",[qc]],["LessOrEqual",[Yc]],["Log",[Pc]],["MatMul",[ip]],["MatMulNBits",[ch,ph]],["MaxPool",[Oh,zh]],["Mul",[Vc]],["MultiHeadAttention",[gh,fh]],["Neg",[vc]],["Not",[bc]],["Pad",[kh]],["Pow",[Gc]],["Range",[Nh]],["Reciprocal",[$c]],["ReduceMin",[Ed]],["ReduceMean",[vd]],["ReduceMax",[kd]],["ReduceSum",[Td]],["ReduceProd",[Cd]],["ReduceL1",[$d]],["ReduceL2",[xd]],["ReduceLogSum",[Id]],["ReduceLogSumExp",[Sd]],["ReduceSumSquare",[Ad]],["Relu",[xc]],["Resize",[tf,rf]],["RotaryEmbedding",[sf]],["Sigmoid",[Sc]],["Sin",[Cc]],["Sinh",[Tc]],["Slice",[ff,mf]],["SkipLayerNormalization",[uf]],["Split",[kf,Ef]],["Sqrt",[Ac]],["Softmax",[yf,wf]],["Sub",[Hc]],["Tan",[Ic]],["Tanh",[Mc]],["ThresholdedRelu",[zc,wi]],["Tile",[If]],["Transpose",[Wu,Vu]],["Where",[zf]]])}),Rf,fw=te(()=>{rr(),Xr(),Ie(),Rf=class{constructor(t){this.backend=t,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,r,n,a){tr(t.programInfo.name);let s=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 r)o.push({binding:o.length,resource:{buffer:u.buffer}});a&&o.push({binding:o.length,resource:a});let l=s.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:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}i.setPipeline(t.computePipeline),i.setBindGroup(0,l),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Yt(t.programInfo.name)}dispose(){}build(t,e){tr(t.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let a=Nu(e,this.backend.device.limits),s=t.getShaderSource(a),i=`${n.join(` `)} ${a.additionalImplementations} ${s}`,o=r.createShaderModule({code:i,label:t.name});nt("verbose",()=>`[WebGPU] ${t.name} shader code: ${i}`);let l=r.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:t.name});return Yt(t.name),{programInfo:t,computePipeline:l,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let e=typeof t=="number"?t:t.x,r=typeof t=="number"?1:t.y||1,n=typeof t=="number"?1:t.z||1,a=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=a&&r<=a&&n<=a)return[e,r,n];let s=e*r*n,i=Math.ceil(Math.sqrt(s));if(i>a){if(i=Math.ceil(Math.cbrt(s)),i>a)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),Bf,Df,Nf,Ff,mw=te(()=>{rr(),xe(),Xr(),My(),Oy(),hw(),fw(),Bf=(t,e)=>{if(e.length!==t.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${t.length}.`);let r=[];for(let n=0;n{var a,s;let n=t.name;return(a=t.shaderCache)!=null&&a.hint&&(n+="["+t.shaderCache.hint+"]"),n+=":"+r+`:${Bf(e,((s=t.shaderCache)==null?void 0:s.inputDependencies)??new Array(e.length).fill("dims"))}`,n},Nf=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Ff=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,e){this.env=t;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};e.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):e.features.has("timestamp-query")&&r.push("timestamp-query"),e.features.has("shader-f16")&&r.push("shader-f16"),this.device=await e.requestDevice(n),this.adapterInfo=new Nf(await e.requestAdapterInfo()),this.gpuDataManager=zu(this),this.programManager=new Rf(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Cu(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;tr(),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 n;let e=new BigUint64Array(t.getMappedRange()),r=this.pendingQueries.get(t);for(let a=0;a"u"&&(this.queryTimeBase=g);let w=Number(g-this.queryTimeBase),v=Number(p-this.queryTimeBase);if(!Number.isSafeInteger(w)||!Number.isSafeInteger(v))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:h.map(S=>({dims:S.dims,dataType:Yr(S.dataType)})),outputsMetadata:m.map(S=>({dims:S.dims,dataType:Yr(S.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:d,startTime:w,endTime:v});else{let S="";h.forEach((E,T)=>{S+=`input[${T}]: [${E.dims}] | ${Yr(E.dataType)}, `});let $="";m.forEach((E,T)=>{$+=`output[${T}]: [${E.dims}] | ${Yr(E.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${d}" ${S}${$}execution time: ${v-w} ns`)}Jn("GPU",`${d}::${g}::${p}`)}t.unmap(),this.pendingQueries.delete(t)}),Yt()}run(t,e,r,n,a,s){tr(t.name);let i=[];for(let $=0;$E):r;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],m=[];for(let $=0;$=s)throw new Error(`Invalid output index: ${d[$]}`);if(d[$]===-3)continue;let E=d[$]===-1,T=d[$]===-2,A=E||T?a(o[$].dataType,o[$].dims):n(d[$],o[$].dataType,o[$].dims);if(h.push(A),A.data===0)continue;let z=this.gpuDataManager.get(A.data);if(!z)throw new Error(`no GPU data for output: ${A.data}`);if(E&&this.temporaryData.push(z),T){let R=this.kernelPersistentData.get(this.currentKernelId);R||(R=[],this.kernelPersistentData.set(this.currentKernelId,R)),R.push(z)}m.push(z)}if(i.length!==e.length||m.length!==h.length){if(m.length===0)return Yt(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let g;if(u){let $=0,E=[];u.forEach(R=>{let V=typeof R.data=="number"?[R.data]:R.data;if(V.length===0)return;let j=R.type===10?2:4,q,fe;R.type===10?(fe=V.length>4?16:V.length>2?8:V.length*j,q=V.length>4?16:j*V.length):(fe=V.length<=2?V.length*j:16,q=16),$=Math.ceil($/fe)*fe,E.push($);let ee=R.type===10?8:4;$+=V.length>4?Math.ceil(V.length/ee)*q:V.length*j});let T=16;$=Math.ceil($/T)*T;let A=new ArrayBuffer($);u.forEach((R,V)=>{let j=E[V],q=typeof R.data=="number"?[R.data]:R.data;if(R.type===6)new Int32Array(A,j,q.length).set(q);else if(R.type===12)new Uint32Array(A,j,q.length).set(q);else if(R.type===10)new Uint16Array(A,j,q.length).set(q);else if(R.type===1)new Float32Array(A,j,q.length).set(q);else throw new Error(`Unsupported uniform type: ${Yr(R.type)}`)});let z=this.gpuDataManager.create($,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(z.buffer,0,A,0,$),this.gpuDataManager.release(z.id),g={offset:0,size:$,buffer:z.buffer}}let p=this.programManager.normalizeDispatchGroupSize(l),w=p[1]===1&&p[2]===1,v=Df(t,e,w),S=this.programManager.getArtifact(v);if(S||(S=this.programManager.build(t,p),this.programManager.setArtifact(v,S),nt("info",()=>`[artifact] key: ${v}, programName: ${t.name}`)),u&&S.uniformVariablesInfo){if(u.length!==S.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${S.uniformVariablesInfo.length}, got ${u.length} in program "${S.programInfo.name}".`);for(let $=0;$`[ProgramManager] run "${t.name}" (key=${v}) with ${p[0]}x${p[1]}x${p[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let $={kernelId:this.currentKernelId,programName:S.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push($),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push($)}return this.programManager.run(S,i,m,p,g),Yt(t.name),h}upload(t,e){this.gpuDataManager.upload(t,e)}memcpy(t,e){this.gpuDataManager.memcpy(t,e)}async download(t,e){await this.gpuDataManager.download(t,e)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,e,r,n){let a=Pf.get(t);if(!a)throw new Error(`kernel not implemented: ${t}`);let s={kernelType:t,kernelName:n,kernelEntry:a[0],attributes:[a[1],r]};this.kernels.set(e,s)}releaseKernel(t){let e=this.kernelPersistentData.get(t);if(e){for(let r of e)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,e,r){let n=this.kernels.get(t);if(!n)throw new Error(`kernel not created: ${t}`);let a=n.kernelType,s=n.kernelName,i=n.kernelEntry,o=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${a}] ${s}" is not allowed to be called recursively`);this.currentKernelId=t,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),nt("info",()=>`[WebGPU] Start to run kernel "[${a}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(e,o[1]),0}catch(u){return r.push(Promise.resolve(`[WebGPU] Kernel "[${a}] ${s}" failed. ${u}`)),1}finally{l&&r.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${a}] ${s}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,e,r,n){let a=this.sessionExternalDataMapping.get(t);a||(a=new Map,this.sessionExternalDataMapping.set(t,a));let s=a.get(e),i=this.gpuDataManager.registerExternalBuffer(r,n,s==null?void 0:s[1]);return a.set(e,[i,r]),i}unregisterBuffers(t){let e=this.sessionExternalDataMapping.get(t);e&&(e.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let e=this.gpuDataManager.get(t);if(!e)throw new Error(`no GPU data for buffer: ${t}`);return e.buffer}createDownloader(t,e,r){return async()=>{let n=await Ks(this,t,e);return Au(n.buffer,r)}}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(){nt("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(){nt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){nt("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),r=t.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}}),Lf={};$n(Lf,{init:()=>Wf});var Ti,Uf,Wf,gw=te(()=>{xe(),mw(),Xr(),Oe(),Ti=class D0{constructor(e,r,n,a){this.module=e,this.dataType=r,this.data=n,this.dims=a}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=X.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=X.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=X.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(X.size(e)!==X.size(this.dims))throw new Error("Invalid new shape");return new D0(this.module,this.dataType,this.data,e)}},Uf=class{constructor(t,e,r){this.module=t,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let n=t.HEAPU32,a=r>>>2;this.opKernelContext=n[a++];let s=n[a++];this.outputCount=n[a++],this.customDataOffset=n[a++],this.customDataSize=n[a++];let i=[];for(let o=0;otypeof o=="number"?this.inputs[o]:o))??this.inputs,n=(e==null?void 0:e.outputs)??[],a=(o,l,u)=>new Ti(this.module,l,this.output(o,u),u),s=(o,l)=>{let u=ra(o);if(!u)throw new Error(`Unsupported data type: ${o}`);let d=u*X.size(l),h=d>0?this.backend.gpuDataManager.create(d).id:0;return new Ti(this.module,o,h,l)};return this.backend.run(t,r,n,a,s,this.outputCount)}output(t,e){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+e.length)*4),a=n>>2;this.module.HEAPU32[a++]=e.length;for(let s=0;s{let a=e.jsepInit;if(!a)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(t==="webgpu"){let s=new Ff;await s.initialize(r,n),a("webgpu",[s,i=>s.alloc(i),i=>s.free(i),(i,o,l,u=!1)=>{if(u)nt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${o}, size=${l}`),s.memcpy(i,o);else{nt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${o}, size=${l}`);let d=e.HEAPU8.subarray(i>>>0,(i>>>0)+l);s.upload(o,d)}},async(i,o,l)=>{nt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${o}, size=${l}`),await s.download(i,()=>e.HEAPU8.subarray(o>>>0,(o>>>0)+l))},(i,o,l)=>s.createKernel(i,o,l,e.UTF8ToString(e._JsepGetNodeName(o))),i=>s.releaseKernel(i),(i,o,l,u)=>{nt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${i}, contextDataOffset=${o}`);let d=new Uf(e,s,o);return s.computeKernel(i,d,u)},()=>s.captureBegin(),()=>s.captureEnd(),()=>s.replay()])}else a("webnn")}}),Vf,Gf,Hf,Nr,jf,Bo,qf,Kf,Do,Yf,Xf,Qf,_w=te(()=>{Ay(),Iy(),xe(),ta(),Ls(),$u(),Vf=(t,e)=>{it()._OrtInit(t,e)!==0&&qe("Can't initialize onnxruntime.")},Gf=async t=>{Vf(t.wasm.numThreads,ui(t.logLevel))},Hf=async(t,e)=>{{let r=(gw(),jr(Lf)).init;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=t.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let a=t.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let s=t.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:a,forceFallbackAdapter:s}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}if(!t.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",it(),t,n)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",it(),t)}}},Nr=new Map,jf=t=>{let e=it(),r=e.stackSave();try{let n=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,n,n+4)!==0&&qe("Can't get session input/output count."),[e.HEAP32[n/4],e.HEAP32[n/4+1]]}finally{e.stackRestore(r)}},Bo=t=>{let e=it(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},qf=async(t,e)=>{var h,m;let r,n,a=it();Array.isArray(t)?[r,n]=t:t.buffer===a.HEAPU8.buffer?[r,n]=[t.byteOffset,t.byteLength]:[r,n]=Bo(t);let s=0,i=0,o=0,l=[],u=[],d=[];try{if([i,l]=vu(e),(e==null?void 0:e.externalData)&&a.mountExternalData){let T=[];for(let A of e.externalData){let z=typeof A=="string"?A:A.path;T.push(di(typeof A=="string"?A:A.data).then(R=>{a.mountExternalData(z,R)}))}await Promise.all(T)}s=await a._OrtCreateSession(r,n,i),s===0&&qe("Can't create a session.");let[g,p]=jf(s),w=!!(e!=null&&e.enableGraphCapture),v=[],S=[],$=[];for(let T=0;TT==="gpu-buffer")&&(o=a._OrtCreateBinding(s),o===0&&qe("Can't create IO binding."),E={handle:o,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(T=>Gs(T))}),Nr.set(s,[s,u,d,E,w,!1]),[s,v,S]}catch(g){throw u.forEach(p=>a._OrtFree(p)),d.forEach(p=>a._OrtFree(p)),o!==0&&a._OrtReleaseBinding(o),s!==0&&a._OrtReleaseSession(s),g}finally{a._free(r),i!==0&&a._OrtReleaseSessionOptions(i),l.forEach(g=>a._free(g)),(m=a.unmountExternalData)==null||m.call(a)}},Kf=t=>{var l;let e=it(),r=Nr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[n,a,s,i,o]=r;i&&(o&&e._OrtClearBoundOutputs(i.handle),e._OrtReleaseBinding(i.handle)),(l=e.jsepOnReleaseSession)==null||l.call(e,t),a.forEach(u=>e._OrtFree(u)),s.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(n),Nr.delete(t)},Do=(t,e,r,n,a,s=!1)=>{if(!t){e.push(0);return}let i=it(),o=t[0],l=t[1],u=t[3],d,h;if(o==="string"&&u==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(s&&u!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(u==="gpu-buffer"){let p=t[2].gpuBuffer,w=ra(Us(o));h=l.reduce((S,$)=>S*$,1)*w;let v=i.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');d=v(n,a,p,h)}else{let p=t[2];if(Array.isArray(p)){h=4*p.length,d=i._malloc(h),r.push(d);let w=d/4;for(let v=0;vi.HEAP32[p++]=v);let w=i._OrtCreateTensor(Us(o),d,h,g,l.length,Gs(u));w===0&&qe(`Can't create tensor for input/output. session=${n}, index=${a}.`),e.push(w)}finally{i.stackRestore(m)}},Yf=async(t,e,r,n,a,s)=>{var q,fe;let i=it(),o=Nr.get(t);if(!o)throw new Error(`cannot run inference. invalid session id: ${t}`);let l=o[0],u=o[1],d=o[2],h=o[3],m=o[4],g=o[5],p=e.length,w=n.length,v=0,S=[],$=[],E=[],T=[],A=i.stackSave(),z=i.stackAlloc(p*4),R=i.stackAlloc(p*4),V=i.stackAlloc(w*4),j=i.stackAlloc(w*4);try{[v,S]=gu(s);for(let K=0;KWe*Ze,1);de=Yr(Xe);let yt=h==null?void 0:h.outputPreferredLocations[n[K]];if(de==="string"){if(yt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let We=[],Ze=Se/4;for(let Rt=0;Rt0){let We=i.jsepGetBuffer;if(!We)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ze=We(Se),Rt=ra(Xe);if(Rt===void 0||!Vs(de))throw new Error(`Unsupported data type: ${de}`);ae=!0,G.push([de,ht,{gpuBuffer:Ze,download:i.jsepCreateDownloader(Ze,ut*Rt,de),dispose:()=>{i._OrtReleaseTensor(pe)}},"gpu-buffer"])}else{let We=Ws(de),Ze=new We(ut);new Uint8Array(Ze.buffer,Ze.byteOffset,Ze.byteLength).set(i.HEAPU8.subarray(Se,Se+Ze.byteLength)),G.push([de,ht,Ze,"cpu"])}}finally{i.stackRestore(le),de==="string"&&Se&&i._free(Se),ae||i._OrtReleaseTensor(pe)}}return h&&!m&&(i._OrtClearBoundOutputs(h.handle),Nr.set(t,[l,u,d,h,m,!1])),G}finally{i.stackRestore(A),$.forEach(ee=>i._OrtReleaseTensor(ee)),E.forEach(ee=>i._OrtReleaseTensor(ee)),T.forEach(ee=>i._free(ee)),v!==0&&i._OrtReleaseRunOptions(v),S.forEach(ee=>i._free(ee))}},Xf=t=>{let e=it(),r=Nr.get(t);if(!r)throw new Error("invalid session id");let n=r[0],a=e._OrtEndProfiling(n);a===0&&qe("Can't get an profile file name."),e._OrtFree(a)},Qf=t=>{let e=[];for(let r of t){let n=r[2];!Array.isArray(n)&&"buffer"in n&&e.push(n.buffer)}return e}}),yw=vn((t,e)=>{e.exports='/*!\n * ONNX Runtime Web v1.18.0\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var ao=Object.defineProperty;var nl=Object.getOwnPropertyDescriptor;var ol=Object.getOwnPropertyNames;var il=Object.prototype.hasOwnProperty;var Y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gn=(e,t)=>{for(var r in t)ao(e,r,{get:t[r],enumerable:!0})},al=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ol(t))!il.call(e,i)&&i!==r&&ao(e,i,{get:()=>t[i],enumerable:!(o=nl(t,i))||o.enumerable});return e};var wr=e=>al(ao({},"__esModule",{value:!0}),e);var so={};gn(so,{createReadStream:()=>Ai,readFile:()=>sl,readFileSync:()=>ul});var sl,ul,Ai,uo=Y(()=>{sl=void 0,ul=void 0,Ai=void 0});var lo={};gn(lo,{join:()=>dl});var dl,co=Y(()=>{dl=void 0});var Ei=Wr((Ti,po)=>{"use strict";var Ii=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(t={}){var r=t,o,i,u=new Promise((s,m)=>{o=s,i=m});r.mountExternalData=(s,m)=>{(r.eb||(r.eb=new Map)).set(s,m)},r.unmountExternalData=()=>{delete r.eb};let a=()=>{let s=(g,$,T)=>(...B)=>{let H=dt,q=$?.();B=g(...B);let te=$?.();return q!==te&&(g=te,T(q),$=T=null),dt!=H?tn():B},m=g=>async(...$)=>{try{if(r.cb)throw Error("Session already started");let T=r.cb={xb:$[0],errors:[]},B=await g(...$);if(r.cb!==T)throw Error("Session mismatch");r.kb?.flush();let H=T.errors;if(0te),0r._OrtCreateSession,g=>r._OrtCreateSession=g),r._OrtRun=m(s(r._OrtRun,()=>r._OrtRun,g=>r._OrtRun=g)),r._OrtRunWithBinding=m(s(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,g=>r._OrtRunWithBinding=g)),r._OrtBindInput=s(r._OrtBindInput,()=>r._OrtBindInput,g=>r._OrtBindInput=g),a=void 0};r.jsepInit=(s,m)=>{if(a?.(),s==="webgpu"){[r.kb,r.pb,r.tb,r.lb,r.sb,r.Ra,r.ub,r.wb,r.qb,r.rb,r.vb]=m;let g=r.kb;r.jsepRegisterBuffer=($,T,B,H)=>g.registerBuffer($,T,B,H),r.jsepGetBuffer=$=>g.getBuffer($),r.jsepCreateDownloader=($,T,B)=>g.createDownloader($,T,B),r.jsepOnReleaseSession=$=>{g.onReleaseSession($)},r.jsepOnRunStart=$=>g.onRunStart($)}};var c=Object.assign({},r),p="./this.program",h=(s,m)=>{throw m},d=typeof window=="object",y=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_="",v,S,A;if(w){var I=(uo(),wr(so)),x=(co(),wr(lo));_=y?x.dirname(_)+"/":__dirname+"/",v=(s,m)=>(s=Ke(s)?new URL(s):x.normalize(s),I.readFileSync(s,m?void 0:"utf8")),A=s=>(s=v(s,!0),s.buffer||(s=new Uint8Array(s)),s),S=(s,m,g,$=!0)=>{s=Ke(s)?new URL(s):x.normalize(s),I.readFile(s,$?void 0:"utf8",(T,B)=>{T?g(T):m($?B.buffer:B)})},!r.thisProgram&&1{throw process.exitCode=s,m}}else(d||y)&&(y?_=self.location.href:typeof document<"u"&&document.currentScript&&(_=document.currentScript.src),e&&(_=e),_.startsWith("blob:")?_="":_=_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1),v=s=>{var m=new XMLHttpRequest;return m.open("GET",s,!1),m.send(null),m.responseText},y&&(A=s=>{var m=new XMLHttpRequest;return m.open("GET",s,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),S=(s,m,g)=>{var $=new XMLHttpRequest;$.open("GET",s,!0),$.responseType="arraybuffer",$.onload=()=>{$.status==200||$.status==0&&$.response?m($.response):g()},$.onerror=g,$.send(null)});var E=console.log.bind(console),P=console.error.bind(console);Object.assign(r,c),c=null;var O,R=!1,L,N,K,Q,he,W,se,Ce,We,ee,ae;function Ae(){var s=O.buffer;r.HEAP8=N=new Int8Array(s),r.HEAP16=Q=new Int16Array(s),r.HEAPU8=K=new Uint8Array(s),r.HEAPU16=he=new Uint16Array(s),r.HEAP32=W=new Int32Array(s),r.HEAPU32=se=new Uint32Array(s),r.HEAPF32=Ce=new Float32Array(s),r.HEAPF64=ae=new Float64Array(s),r.HEAP64=We=new BigInt64Array(s),r.HEAPU64=ee=new BigUint64Array(s)}var me=[],ie=[],ue=[],le=0,qe=null,G=null;function ne(s){throw s="Aborted("+s+")",P(s),R=!0,L=1,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),i(s),s}var xe=s=>s.startsWith("data:application/octet-stream;base64,"),Ke=s=>s.startsWith("file://"),Be;if(Be="ort-wasm-simd.wasm",!xe(Be)){var Ge=Be;Be=r.locateFile?r.locateFile(Ge,_):_+Ge}function Ut(s){if(A)return A(s);throw"both async and sync fetching of the wasm failed"}function Ne(s){if(d||y){if(typeof fetch=="function"&&!Ke(s))return fetch(s,{credentials:"same-origin"}).then(m=>{if(!m.ok)throw`failed to load wasm binary file at \'${s}\'`;return m.arrayBuffer()}).catch(()=>Ut(s));if(S)return new Promise((m,g)=>{S(s,$=>m(new Uint8Array($)),g)})}return Promise.resolve().then(()=>Ut(s))}function Ye(s,m,g){return Ne(s).then($=>WebAssembly.instantiate($,m)).then(g,$=>{P(`failed to asynchronously prepare wasm: ${$}`),ne($)})}function mt(s,m){var g=Be;return typeof WebAssembly.instantiateStreaming!="function"||xe(g)||Ke(g)||w||typeof fetch!="function"?Ye(g,s,m):fetch(g,{credentials:"same-origin"}).then($=>WebAssembly.instantiateStreaming($,s).then(m,function(T){return P(`wasm streaming compile failed: ${T}`),P("falling back to ArrayBuffer instantiation"),Ye(g,s,m)}))}var Rt={824920:(s,m,g,$)=>{if(typeof r>"u"||!r.eb)return 1;if(s=je(s>>>0),s.startsWith("./")&&(s=s.substring(2)),s=r.eb.get(s),!s)return 2;if(m>>>=0,g>>>=0,m+g>s.byteLength)return 3;try{return K.set(s.subarray(m,m+g),$>>>0>>>0),0}catch{return 4}},825421:()=>{r.qb()},825452:()=>{r.rb()},825481:()=>{r.vb()},825506:s=>r.pb(s),825539:s=>r.tb(s),825571:(s,m,g)=>{r.lb(s,m,g,!0)},825610:(s,m,g)=>{r.lb(s,m,g)},825643:s=>{r.Ra("Abs",s,void 0)},825694:s=>{r.Ra("Neg",s,void 0)},825745:s=>{r.Ra("Floor",s,void 0)},825798:s=>{r.Ra("Ceil",s,void 0)},825850:s=>{r.Ra("Reciprocal",s,void 0)},825908:s=>{r.Ra("Sqrt",s,void 0)},825960:s=>{r.Ra("Exp",s,void 0)},826011:s=>{r.Ra("Erf",s,void 0)},826062:s=>{r.Ra("Sigmoid",s,void 0)},826117:(s,m,g)=>{r.Ra("HardSigmoid",s,{alpha:m,beta:g})},826196:s=>{r.Ra("Log",s,void 0)},826247:s=>{r.Ra("Sin",s,void 0)},826298:s=>{r.Ra("Cos",s,void 0)},826349:s=>{r.Ra("Tan",s,void 0)},826400:s=>{r.Ra("Asin",s,void 0)},826452:s=>{r.Ra("Acos",s,void 0)},826504:s=>{r.Ra("Atan",s,void 0)},826556:s=>{r.Ra("Sinh",s,void 0)},826608:s=>{r.Ra("Cosh",s,void 0)},826660:s=>{r.Ra("Asinh",s,void 0)},826713:s=>{r.Ra("Acosh",s,void 0)},826766:s=>{r.Ra("Atanh",s,void 0)},826819:s=>{r.Ra("Tanh",s,void 0)},826871:s=>{r.Ra("Not",s,void 0)},826922:(s,m,g)=>{r.Ra("Clip",s,{min:m,max:g})},826991:s=>{r.Ra("Clip",s,void 0)},827043:(s,m)=>{r.Ra("Elu",s,{alpha:m})},827101:s=>{r.Ra("Relu",s,void 0)},827153:(s,m)=>{r.Ra("LeakyRelu",s,{alpha:m})},827217:(s,m)=>{r.Ra("ThresholdedRelu",s,{alpha:m})},827287:(s,m)=>{r.Ra("Cast",s,{to:m})},827345:s=>{r.Ra("Add",s,void 0)},827396:s=>{r.Ra("Sub",s,void 0)},827447:s=>{r.Ra("Mul",s,void 0)},827498:s=>{r.Ra("Div",s,void 0)},827549:s=>{r.Ra("Pow",s,void 0)},827600:s=>{r.Ra("Equal",s,void 0)},827653:s=>{r.Ra("Greater",s,void 0)},827708:s=>{r.Ra("GreaterOrEqual",s,void 0)},827770:s=>{r.Ra("Less",s,void 0)},827822:s=>{r.Ra("LessOrEqual",s,void 0)},827881:(s,m,g,$,T)=>{r.Ra("ReduceMean",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828040:(s,m,g,$,T)=>{r.Ra("ReduceMax",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828198:(s,m,g,$,T)=>{r.Ra("ReduceMin",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828356:(s,m,g,$,T)=>{r.Ra("ReduceProd",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828515:(s,m,g,$,T)=>{r.Ra("ReduceSum",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828673:(s,m,g,$,T)=>{r.Ra("ReduceL1",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828830:(s,m,g,$,T)=>{r.Ra("ReduceL2",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828987:(s,m,g,$,T)=>{r.Ra("ReduceLogSum",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829148:(s,m,g,$,T)=>{r.Ra("ReduceSumSquare",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829312:(s,m,g,$,T)=>{r.Ra("ReduceLogSumExp",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829476:s=>{r.Ra("Where",s,void 0)},829529:(s,m,g)=>{r.Ra("Transpose",s,{perm:m?Array.from(W.subarray(m>>>0,g>>>0)):[]})},829637:(s,m,g,$)=>{r.Ra("DepthToSpace",s,{blocksize:m,mode:je(g),format:$?"NHWC":"NCHW"})},829770:(s,m,g,$)=>{r.Ra("DepthToSpace",s,{blocksize:m,mode:je(g),format:$?"NHWC":"NCHW"})},829903:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be)=>{r.Ra("ConvTranspose",s,{format:te?"NHWC":"NCHW",autoPad:m,dilations:[g],group:$,kernelShape:[T],pads:[B,H],strides:[q],wIsConst:()=>!!N[X>>>0],outputPadding:de?Array.from(W.subarray(de>>>0,Ee>>>0)):[],outputShape:Oe?Array.from(W.subarray(Oe>>>0,D>>>0)):[],activation:je(be)})},830304:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D)=>{r.Ra("ConvTranspose",s,{format:q?"NHWC":"NCHW",autoPad:m,dilations:Array.from(W.subarray(g>>>0,(g>>>0)+2>>>0)),group:$,kernelShape:Array.from(W.subarray(T>>>0,(T>>>0)+2>>>0)),pads:Array.from(W.subarray(B>>>0,(B>>>0)+4>>>0)),strides:Array.from(W.subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!N[te>>>0],outputPadding:X?Array.from(W.subarray(X>>>0,de>>>0)):[],outputShape:Ee?Array.from(W.subarray(Ee>>>0,Oe>>>0)):[],activation:je(D)})},830869:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be)=>{r.Ra("ConvTranspose",s,{format:te?"NHWC":"NCHW",autoPad:m,dilations:[g],group:$,kernelShape:[T],pads:[B,H],strides:[q],wIsConst:()=>!!N[X>>>0],outputPadding:de?Array.from(W.subarray(de>>>0,Ee>>>0)):[],outputShape:Oe?Array.from(W.subarray(Oe>>>0,D>>>0)):[],activation:je(be)})},831270:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D)=>{r.Ra("ConvTranspose",s,{format:q?"NHWC":"NCHW",autoPad:m,dilations:Array.from(W.subarray(g>>>0,(g>>>0)+2>>>0)),group:$,kernelShape:Array.from(W.subarray(T>>>0,(T>>>0)+2>>>0)),pads:Array.from(W.subarray(B>>>0,(B>>>0)+4>>>0)),strides:Array.from(W.subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!N[te>>>0],outputPadding:X?Array.from(W.subarray(X>>>0,de>>>0)):[],outputShape:Ee?Array.from(W.subarray(Ee>>>0,Oe>>>0)):[],activation:je(D)})},831835:(s,m)=>{r.Ra("GlobalAveragePool",s,{format:m?"NHWC":"NCHW"})},831926:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("AveragePool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832210:(s,m)=>{r.Ra("GlobalAveragePool",s,{format:m?"NHWC":"NCHW"})},832301:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("AveragePool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832585:(s,m)=>{r.Ra("GlobalMaxPool",s,{format:m?"NHWC":"NCHW"})},832672:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("MaxPool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832952:(s,m)=>{r.Ra("GlobalMaxPool",s,{format:m?"NHWC":"NCHW"})},833039:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("MaxPool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},833319:(s,m,g,$,T)=>{r.Ra("Gemm",s,{alpha:m,beta:g,transA:$,transB:T})},833423:s=>{r.Ra("MatMul",s,void 0)},833477:(s,m,g,$)=>{r.Ra("ArgMax",s,{keepDims:!!m,selectLastIndex:!!g,axis:$})},833585:(s,m,g,$)=>{r.Ra("ArgMin",s,{keepDims:!!m,selectLastIndex:!!g,axis:$})},833693:(s,m)=>{r.Ra("Softmax",s,{axis:m})},833756:(s,m)=>{r.Ra("Concat",s,{axis:m})},833816:(s,m,g,$,T)=>{r.Ra("Split",s,{axis:m,numOutputs:g,splitSizes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},833956:s=>{r.Ra("Expand",s,void 0)},834010:(s,m)=>{r.Ra("Gather",s,{axis:Number(m)})},834081:(s,m)=>{r.Ra("GatherElements",s,{axis:Number(m)})},834160:(s,m,g,$,T,B,H,q,te,X,de)=>{r.Ra("Resize",s,{antialias:m,axes:g?Array.from(W.subarray(g>>>0,$>>>0)):[],coordinateTransformMode:je(T),cubicCoeffA:B,excludeOutside:H,extrapolationValue:q,keepAspectRatioPolicy:je(te),mode:je(X),nearestMode:je(de)})},834506:(s,m,g,$,T,B,H)=>{r.Ra("Slice",s,{starts:m?Array.from(W.subarray(m>>>0,g>>>0)):[],ends:$?Array.from(W.subarray($>>>0,T>>>0)):[],axes:B?Array.from(W.subarray(B>>>0,H>>>0)):[]})},834722:s=>{r.Ra("Tile",s,void 0)},834774:(s,m,g,$)=>{r.Ra("LayerNormalization",s,{axis:m,epsilon:g,simplified:!!$})},834885:(s,m,g)=>{r.Ra("InstanceNormalization",s,{epsilon:m,format:g?"NHWC":"NCHW"})},834999:(s,m,g)=>{r.Ra("InstanceNormalization",s,{epsilon:m,format:g?"NHWC":"NCHW"})},835113:s=>{r.Ra("Range",s,void 0)},835166:(s,m)=>{r.Ra("Einsum",s,{equation:je(m)})},835247:(s,m,g,$,T)=>{r.Ra("Pad",s,{mode:m,value:g,pads:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},835374:(s,m,g,$,T,B)=>{r.Ra("BatchNormalization",s,{epsilon:m,momentum:g,spatial:!!T,trainingMode:!!$,format:B?"NHWC":"NCHW"})},835543:(s,m,g,$,T,B)=>{r.Ra("BatchNormalization",s,{epsilon:m,momentum:g,spatial:!!T,trainingMode:!!$,format:B?"NHWC":"NCHW"})},835712:(s,m,g)=>{r.Ra("CumSum",s,{exclusive:Number(m),reverse:Number(g)})},835809:(s,m,g,$,T,B,H,q,te)=>{r.Ra("Attention",s,{numHeads:m,isUnidirectional:g,maskFilterValue:$,scale:T,doRotary:B,qkvHiddenSizes:H?Array.from(W.subarray(Number(q)>>>0,Number(q)+H>>>0)):[],pastPresentShareBuffer:!!te})},836081:s=>{r.Ra("BiasAdd",s,void 0)},836136:s=>{r.Ra("BiasSplitGelu",s,void 0)},836197:s=>{r.Ra("FastGelu",s,void 0)},836253:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe)=>{r.Ra("Conv",s,{format:te?"NHWC":"NCHW",auto_pad:m,dilations:[g],group:$,kernel_shape:[T],pads:B?Array.from(W.subarray(B>>>0,H>>>0)):[],strides:[q],w_is_const:()=>!!N[X>>>0],activation:je(de),activation_params:Ee?Array.from(Ce.subarray(Ee>>>0,Oe>>>0)):[]})},836623:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("Conv",s,{format:Ee?"NHWC":"NCHW",auto_pad:m,dilations:[g,$],group:T,kernel_shape:[B,H],pads:q?Array.from(W.subarray(q>>>0,te>>>0)):[],strides:[X,de],w_is_const:()=>!!N[Oe>>>0],activation:je(D),activation_params:be?Array.from(Ce.subarray(be>>>0,Ie>>>0)):[]})},837014:s=>{r.Ra("Gelu",s,void 0)},837066:(s,m,g,$,T,B)=>{r.Ra("MatMulNBits",s,{k:m,n:g,accuracyLevel:$,bits:T,blockSize:B})},837193:(s,m,g,$,T,B)=>{r.Ra("MultiHeadAttention",s,{numHeads:m,isUnidirectional:g,maskFilterValue:$,scale:T,doRotary:B})},837352:(s,m,g,$,T)=>{r.Ra("RotaryEmbedding",s,{interleaved:!!m,numHeads:g,rotaryEmbeddingDim:$,scale:T})},837491:(s,m,g)=>{r.Ra("SkipLayerNormalization",s,{epsilon:m,simplified:!!g})},837593:(s,m,g)=>{r.Ra("SkipLayerNormalization",s,{epsilon:m,simplified:!!g})},837695:(s,m,g,$)=>{r.Ra("LayerNormalization",s,{axis:m,epsilon:g,simplified:!!$})},837806:s=>{r.ub(s)},837840:(s,m)=>r.wb(s,m,r.cb.xb,r.cb.errors)};function qt(s){this.name="ExitStatus",this.message=`Program terminated with exit(${s})`,this.status=s}class Vt{constructor(m){this.hb=m-24}}var sr=0,jt=0,xr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Kt=(s,m,g)=>{m>>>=0;var $=m+g;for(g=m;s[g]&&!(g>=$);)++g;if(16T?$+=String.fromCharCode(T):(T-=65536,$+=String.fromCharCode(55296|T>>10,56320|T&1023))}}else $+=String.fromCharCode(T)}return $},je=(s,m)=>(s>>>=0)?Kt(K,s,m):"",Wt=s=>{for(var m=0,g=0;g=$?m++:2047>=$?m+=2:55296<=$&&57343>=$?(m+=4,++g):m+=3}return m},at=(s,m,g,$)=>{if(g>>>=0,!(0<$))return 0;var T=g;$=g+$-1;for(var B=0;B=H){var q=s.charCodeAt(++B);H=65536+((H&1023)<<10)|q&1023}if(127>=H){if(g>=$)break;m[g++>>>0]=H}else{if(2047>=H){if(g+1>=$)break;m[g++>>>0]=192|H>>6}else{if(65535>=H){if(g+2>=$)break;m[g++>>>0]=224|H>>12}else{if(g+3>=$)break;m[g++>>>0]=240|H>>18,m[g++>>>0]=128|H>>12&63}m[g++>>>0]=128|H>>6&63}m[g++>>>0]=128|H&63}}return m[g>>>0]=0,g-T},Cr,ft=s=>{for(var m="";K[s>>>0];)m+=Cr[K[s++>>>0]];return m},ur={},Ar={},Ir={},st;function Tr(s,m,g={}){var $=m.name;if(!s)throw new st(`type "${$}" must have a positive integer typeid pointer`);if(Ar.hasOwnProperty(s)){if(g.nb)return;throw new st(`Cannot register type \'${$}\' twice`)}Ar[s]=m,delete Ir[s],ur.hasOwnProperty(s)&&(m=ur[s],delete ur[s],m.forEach(T=>T()))}function ht(s,m,g={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Tr(s,m,g)}var bt=(s,m,g)=>{switch(m){case 1:return g?$=>N[$>>>0]:$=>K[$>>>0];case 2:return g?$=>Q[$>>>1>>>0]:$=>he[$>>>1>>>0];case 4:return g?$=>W[$>>>2>>>0]:$=>se[$>>>2>>>0];case 8:return g?$=>We[$>>>3]:$=>ee[$>>>3];default:throw new TypeError(`invalid integer width (${m}): ${s}`)}},Er=[],Te=[];function dr(s){s>>>=0,9{if(!s)throw new st("Cannot use deleted val. handle = "+s);return Te[s]},ut=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Er.pop()||Te.length;return Te[m]=s,Te[m+1]=1,m}};function lr(s){return this.fromWireType(se[s>>>2>>>0])}var Fn={name:"emscripten::val",fromWireType:s=>{var m=Xe(s);return dr(s),m},toWireType:(s,m)=>ut(m),argPackAdvance:8,readValueFromPointer:lr,bb:null},ge=(s,m)=>{switch(m){case 4:return function(g){return this.fromWireType(Ce[g>>>2>>>0])};case 8:return function(g){return this.fromWireType(ae[g>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${s}`)}},Yt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,jr=(s,m)=>{for(var g=s>>1,$=g+m/2;!(g>=$)&&he[g>>>0];)++g;if(g<<=1,32>>0,g>>>0));for(g="",$=0;!($>=m/2);++$){var T=Q[s+2*$>>>1>>>0];if(T==0)break;g+=String.fromCharCode(T)}return g},qn=(s,m,g)=>{if(g??=2147483647,2>g)return 0;g-=2;var $=m;g=g<2*s.length?g/2:s.length;for(var T=0;T>>1>>>0]=s.charCodeAt(T),m+=2;return Q[m>>>1>>>0]=0,m-$},Kr=s=>2*s.length,jn=(s,m)=>{for(var g=0,$="";!(g>=m/4);){var T=W[s+4*g>>>2>>>0];if(T==0)break;++g,65536<=T?(T-=65536,$+=String.fromCharCode(55296|T>>10,56320|T&1023)):$+=String.fromCharCode(T)}return $},Yr=(s,m,g)=>{if(m>>>=0,g??=2147483647,4>g)return 0;var $=m;g=$+g-4;for(var T=0;T=B){var H=s.charCodeAt(++T);B=65536+((B&1023)<<10)|H&1023}if(W[m>>>2>>>0]=B,m+=4,m+4>g)break}return W[m>>>2>>>0]=0,m-$},Zr=s=>{for(var m=0,g=0;g=$&&++g,m+=4}return m},cr=(s,m)=>{var g=Ar[s];if(g===void 0)throw s=Mr(s),g=ft(s),rt(s),new st(`${m} has unknown type ${g}`);return g},Pr=(s,m,g)=>{var $=[];return s=s.toWireType($,g),$.length&&(se[m>>>2>>>0]=ut($)),s},He=s=>{try{s()}catch(m){ne(m)}},Xr=s=>{if(!R)try{s();try{L=L=s=L,r.onExit?.(s),R=!0,h(s,new qt(s))}catch(m){m instanceof qt||m=="unwind"||h(1,m)}}catch(m){m instanceof qt||m=="unwind"||h(1,m)}};function Qr(){var s=pe,m={};for(let[g,$]of Object.entries(s))m[g]=typeof $=="function"?(...T)=>{Zt.push(g);try{return $(...T)}finally{R||(Zt.pop(),dt&>===1&&Zt.length===0&&(gt=0,He(dn),typeof Fibers<"u"&&Fibers.Db()))}}:$;return m}var gt=0,dt=null,Bt=0,Zt=[],kr={},Or={},Jr=0,pr=null,en=[];function tn(){return new Promise((s,m)=>{pr={resolve:s,reject:m}})}function rn(){var s=Nt(65548),m=s+12;se[s>>>2>>>0]=m,se[s+4>>>2>>>0]=m+65536,m=Zt[0];var g=kr[m];return g===void 0&&(g=Jr++,kr[m]=g,Or[g]=m),W[s+8>>>2>>>0]=g,s}function nn(s){if(!R){if(gt===0){var m=!1,g=!1;s(($=0)=>{if(!R&&(Bt=$,m=!0,g)){gt=2,He(()=>vt(dt)),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.resume(),$=!1;try{var T=(0,pe[Or[W[dt+8>>>2>>>0]]])()}catch(q){T=q,$=!0}var B=!1;if(!dt){var H=pr;H&&(pr=null,($?H.reject:H.resolve)(T),B=!0)}if($&&!B)throw T}}),g=!0,m||(gt=1,dt=rn(),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.pause(),He(()=>Jt(dt)))}else gt===2?(gt=0,He(ct),rt(dt),dt=null,en.forEach(Xr)):ne(`invalid state: ${gt}`);return Bt}}function Rr(s){return nn(m=>{s().then(m)})}var Xt=[],on={},nt=s=>{var m=on[s];return m===void 0?ft(s):m},mr=()=>typeof globalThis=="object"?globalThis:Function("return this")(),Br=s=>{var m=Xt.length;return Xt.push(s),m},Kn=(s,m)=>{for(var g=Array(s),$=0;$>>2>>>0],"parameter "+$);return g},wt=(s,m)=>Object.defineProperty(m,"name",{value:s});function Yn(s){var m=Function;if(!(m instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof m} which is not a function`);var g=wt(m.name||"unknownFunctionName",function(){});return g.prototype=m.prototype,g=new g,s=m.apply(g,s),s instanceof Object?s:g}var Je=s=>s%4===0&&(s%100!==0||s%400===0),Dr=[0,31,60,91,121,152,182,213,244,274,305,335],fr=[0,31,59,90,120,151,181,212,243,273,304,334],lt=[],hr=(s,m)=>{lt.length=0;for(var g;g=K[s++>>>0];){var $=g!=105;$&=g!=112,m+=$&&m%8?4:0,lt.push(g==112?se[m>>>2>>>0]:g==106?We[m>>>3]:g==105?W[m>>>2>>>0]:ae[m>>>3>>>0]),m+=$?8:4}return lt},Qe={},ot=()=>{if(!Qt){var s={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"},m;for(m in Qe)Qe[m]===void 0?delete s[m]:s[m]=Qe[m];var g=[];for(m in s)g.push(`${m}=${s[m]}`);Qt=g}return Qt},Qt,Zn=[null,[],[]],an=[31,29,31,30,31,30,31,31,30,31,30,31],zr=[31,28,31,30,31,30,31,31,30,31,30,31];function Xn(s){var m=Array(Wt(s)+1);return at(s,m,0,m.length),m}function sn(s,m,g,$){function T(D,be,Ie){for(D=typeof D=="number"?D.toString():D||"";D.lengthMt?-1:0zt-D.getDate())be-=zt-D.getDate()+1,D.setDate(1),11>Ie?D.setMonth(Ie+1):(D.setMonth(0),D.setFullYear(D.getFullYear()+1));else{D.setDate(D.getDate()+be);break}}return Ie=new Date(D.getFullYear()+1,0,4),be=q(new Date(D.getFullYear(),0,4)),Ie=q(Ie),0>=H(be,D)?0>=H(Ie,D)?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}s>>>=0,m>>>=0,g>>>=0,$>>>=0;var X=se[$+40>>>2>>>0];$={Ab:W[$>>>2>>>0],zb:W[$+4>>>2>>>0],fb:W[$+8>>>2>>>0],jb:W[$+12>>>2>>>0],gb:W[$+16>>>2>>>0],ab:W[$+20>>>2>>>0],Va:W[$+24>>>2>>>0],$a:W[$+28>>>2>>>0],Cb:W[$+32>>>2>>>0],yb:W[$+36>>>2>>>0],Bb:X?je(X):""},g=je(g),X={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var de in X)g=g.replace(new RegExp(de,"g"),X[de]);var Ee="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Oe="January February March April May June July August September October November December".split(" ");X={"%a":D=>Ee[D.Va].substring(0,3),"%A":D=>Ee[D.Va],"%b":D=>Oe[D.gb].substring(0,3),"%B":D=>Oe[D.gb],"%C":D=>B((D.ab+1900)/100|0,2),"%d":D=>B(D.jb,2),"%e":D=>T(D.jb,2," "),"%g":D=>te(D).toString().substring(2),"%G":te,"%H":D=>B(D.fb,2),"%I":D=>(D=D.fb,D==0?D=12:12{for(var be=0,Ie=0;Ie<=D.gb-1;be+=(Je(D.ab+1900)?an:zr)[Ie++]);return B(D.jb+be,3)},"%m":D=>B(D.gb+1,2),"%M":D=>B(D.zb,2),"%n":()=>`\n`,"%p":D=>0<=D.fb&&12>D.fb?"AM":"PM","%S":D=>B(D.Ab,2),"%t":()=>" ","%u":D=>D.Va||7,"%U":D=>B(Math.floor((D.$a+7-D.Va)/7),2),"%V":D=>{var be=Math.floor((D.$a+7-(D.Va+6)%7)/7);if(2>=(D.Va+371-D.$a-2)%7&&be++,be)be==53&&(Ie=(D.Va+371-D.$a)%7,Ie==4||Ie==3&&Je(D.ab)||(be=1));else{be=52;var Ie=(D.Va+7-D.$a-1)%7;(Ie==4||Ie==5&&Je(D.ab%400-1))&&be++}return B(be,2)},"%w":D=>D.Va,"%W":D=>B(Math.floor((D.$a+7-(D.Va+6)%7)/7),2),"%y":D=>(D.ab+1900).toString().substring(2),"%Y":D=>D.ab+1900,"%z":D=>{D=D.yb;var be=0<=D;return D=Math.abs(D)/60,(be?"+":"-")+("0000"+(D/60*100+D%60)).slice(-4)},"%Z":D=>D.Bb,"%%":()=>"%"},g=g.replace(/%%/g,"\\0\\0");for(de in X)g.includes(de)&&(g=g.replace(new RegExp(de,"g"),X[de]($)));return g=g.replace(/\\0\\0/g,"%"),de=Xn(g),de.length>m?0:(N.set(de,s>>>0),de.length-1)}for(var un=Array(256),gr=0;256>gr;++gr)un[gr]=String.fromCharCode(gr);Cr=un,st=r.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},r.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},Te.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>Te.length/2-5-Er.length;var Qn={ia:function(s,m,g){return Rr(async()=>{await r.sb(s,m,g)})},a:function(s,m,g){s>>>=0;var $=new Vt(s);throw se[$.hb+16>>>2>>>0]=0,se[$.hb+4>>>2>>>0]=m>>>0,se[$.hb+8>>>2>>>0]=g>>>0,sr=s,jt++,sr},y:function(){return 0},ea:function(){},R:function(){},T:function(){},ga:function(){return 0},ca:function(){},Z:function(){},ba:function(){},G:function(){},S:function(){},P:function(){},da:function(){},Q:function(){},C:function(s,m,g){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:$=>$,toWireType:function($,T){if(typeof T!="bigint"&&typeof T!="number")throw T===null?T="null":($=typeof T,T=$==="object"||$==="array"||$==="function"?T.toString():""+T),new TypeError(`Cannot convert "${T}" to ${this.name}`);return typeof T=="number"&&(T=BigInt(T)),T},argPackAdvance:8,readValueFromPointer:bt(m,g>>>0,m.indexOf("u")==-1),bb:null})},K:function(s,m,g,$){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:function(T){return!!T},toWireType:function(T,B){return B?g:$},argPackAdvance:8,readValueFromPointer:function(T){return this.fromWireType(K[T>>>0])},bb:null})},J:function(s){return ht(s>>>0,Fn)},B:function(s,m,g){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:$=>$,toWireType:($,T)=>T,argPackAdvance:8,readValueFromPointer:ge(m,g>>>0),bb:null})},s:function(s,m,g,$,T){if(s>>>=0,g>>>=0,m=ft(m>>>0),T===-1&&(T=4294967295),T=q=>q,$===0){var B=32-8*g;T=q=>q<>>B}var H=m.includes("unsigned")?function(q,te){return te>>>0}:function(q,te){return te};ht(s,{name:m,fromWireType:T,toWireType:H,argPackAdvance:8,readValueFromPointer:bt(m,g,$!==0),bb:null})},o:function(s,m,g){function $(B){return new T(N.buffer,se[B+4>>>2>>>0],se[B>>>2>>>0])}var T=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];g=ft(g>>>0),ht(s>>>0,{name:g,fromWireType:$,argPackAdvance:8,readValueFromPointer:$},{nb:!0})},D:function(s,m){m=ft(m>>>0);var g=m==="std::string";ht(s>>>0,{name:m,fromWireType:function($){var T=se[$>>>2>>>0],B=$+4;if(g)for(var H=B,q=0;q<=T;++q){var te=B+q;if(q==T||K[te>>>0]==0){if(H=je(H,te-H),X===void 0)var X=H;else X+=String.fromCharCode(0),X+=H;H=te+1}}else{for(X=Array(T),q=0;q>>0]);X=X.join("")}return rt($),X},toWireType:function($,T){T instanceof ArrayBuffer&&(T=new Uint8Array(T));var B=typeof T=="string";if(!(B||T instanceof Uint8Array||T instanceof Uint8ClampedArray||T instanceof Int8Array))throw new st("Cannot pass non-string to std::string");var H=g&&B?Wt(T):T.length,q=Nt(4+H+1),te=q+4;if(se[q>>>2>>>0]=H,g&&B)at(T,K,te,H+1);else if(B)for(B=0;B>>0]=X}else for(B=0;B>>0]=T[B];return $!==null&&$.push(rt,q),q},argPackAdvance:8,readValueFromPointer:lr,bb($){rt($)}})},x:function(s,m,g){if(m>>>=0,g>>>=0,g=ft(g),m===2)var $=jr,T=qn,B=Kr,H=q=>he[q>>>1>>>0];else m===4&&($=jn,T=Yr,B=Zr,H=q=>se[q>>>2>>>0]);ht(s>>>0,{name:g,fromWireType:q=>{for(var te=se[q>>>2>>>0],X,de=q+4,Ee=0;Ee<=te;++Ee){var Oe=q+4+Ee*m;(Ee==te||H(Oe)==0)&&(de=$(de,Oe-de),X===void 0?X=de:(X+=String.fromCharCode(0),X+=de),de=Oe+m)}return rt(q),X},toWireType:(q,te)=>{if(typeof te!="string")throw new st(`Cannot pass non-string to C++ string type ${g}`);var X=B(te),de=Nt(4+X+m);return se[de>>>2>>>0]=X/m,T(te,de+4,X+m),q!==null&&q.push(rt,de),de},argPackAdvance:8,readValueFromPointer:lr,bb(q){rt(q)}})},L:function(s,m){m=ft(m>>>0),ht(s>>>0,{ob:!0,name:m,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ha:()=>1,u:function(s,m,g){return m>>>=0,g>>>=0,s=Xe(s>>>0),m=cr(m,"emval::as"),Pr(m,g,s)},w:function(s){return s>>>=0,Rr(()=>(s=Xe(s),s.then(ut)))},n:function(s,m,g,$){return g>>>=0,$>>>=0,s=Xt[s>>>0],m=Xe(m>>>0),s(null,m,g,$)},j:function(s,m,g,$,T){return g>>>=0,$>>>=0,T>>>=0,s=Xt[s>>>0],m=Xe(m>>>0),g=nt(g),s(m,m[g],$,T)},b:dr,A:function(s,m){return m>>>=0,s=Xe(s>>>0),m=Xe(m),s==m},m:function(s){return s>>>=0,s===0?ut(mr()):(s=nt(s),ut(mr()[s]))},i:function(s,m,g){m=Kn(s,m>>>0);var $=m.shift();s--;var T=`return function (obj, func, destructorsRef, args) {\n`,B=0,H=[];g===0&&H.push("obj");for(var q=["retType"],te=[$],X=0;Xde.name).join(", ")}) => ${$.name}>`,Br(wt(g,s))},r:function(s,m){return m>>>=0,s=Xe(s>>>0),m=Xe(m),ut(s[m])},e:function(s){s>>>=0,9>>0);for(var m=Array(s.length),g=0;g>>0))},k:function(){return ut({})},h:function(s){s>>>=0;for(var m=Xe(s);m.length;){var g=m.pop();m.pop()(g)}dr(s)},g:function(s,m,g){m>>>=0,g>>>=0,s=Xe(s>>>0),m=Xe(m),g=Xe(g),s[m]=g},c:function(s,m){return m>>>=0,s=cr(s>>>0,"_emval_take_value"),s=s.readValueFromPointer(m),ut(s)},W:function(s,m){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),W[m>>>2>>>0]=s.getUTCSeconds(),W[m+4>>>2>>>0]=s.getUTCMinutes(),W[m+8>>>2>>>0]=s.getUTCHours(),W[m+12>>>2>>>0]=s.getUTCDate(),W[m+16>>>2>>>0]=s.getUTCMonth(),W[m+20>>>2>>>0]=s.getUTCFullYear()-1900,W[m+24>>>2>>>0]=s.getUTCDay(),W[m+28>>>2>>>0]=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},X:function(s,m){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),W[m>>>2>>>0]=s.getSeconds(),W[m+4>>>2>>>0]=s.getMinutes(),W[m+8>>>2>>>0]=s.getHours(),W[m+12>>>2>>>0]=s.getDate(),W[m+16>>>2>>>0]=s.getMonth(),W[m+20>>>2>>>0]=s.getFullYear()-1900,W[m+24>>>2>>>0]=s.getDay(),W[m+28>>>2>>>0]=(Je(s.getFullYear())?Dr:fr)[s.getMonth()]+s.getDate()-1|0,W[m+36>>>2>>>0]=-(60*s.getTimezoneOffset());var g=new Date(s.getFullYear(),6,1).getTimezoneOffset(),$=new Date(s.getFullYear(),0,1).getTimezoneOffset();W[m+32>>>2>>>0]=(g!=$&&s.getTimezoneOffset()==Math.min($,g))|0},Y:function(s){s>>>=0;var m=new Date(W[s+20>>>2>>>0]+1900,W[s+16>>>2>>>0],W[s+12>>>2>>>0],W[s+8>>>2>>>0],W[s+4>>>2>>>0],W[s>>>2>>>0],0),g=W[s+32>>>2>>>0],$=m.getTimezoneOffset(),T=new Date(m.getFullYear(),6,1).getTimezoneOffset(),B=new Date(m.getFullYear(),0,1).getTimezoneOffset(),H=Math.min(B,T);return 0>g?W[s+32>>>2>>>0]=+(T!=B&&H==$):0>>2>>>0]=m.getDay(),W[s+28>>>2>>>0]=(Je(m.getFullYear())?Dr:fr)[m.getMonth()]+m.getDate()-1|0,W[s>>>2>>>0]=m.getSeconds(),W[s+4>>>2>>>0]=m.getMinutes(),W[s+8>>>2>>>0]=m.getHours(),W[s+12>>>2>>>0]=m.getDate(),W[s+16>>>2>>>0]=m.getMonth(),W[s+20>>>2>>>0]=m.getYear(),s=m.getTime(),BigInt(isNaN(s)?-1:s/1e3)},U:function(){return-52},V:function(){},N:function(s,m,g,$){g>>>=0,$>>>=0;var T=new Date().getFullYear(),B=new Date(T,0,1),H=new Date(T,6,1);T=B.getTimezoneOffset();var q=H.getTimezoneOffset();se[s>>>0>>>2>>>0]=60*Math.max(T,q),W[m>>>0>>>2>>>0]=+(T!=q),s=te=>te.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],B=s(B),H=s(H),q{ne("")},d:function(s,m,g){return s>>>=0,m=hr(m>>>0,g>>>0),Rt[s](...m)},I:function(s,m,g){return s>>>=0,m=hr(m>>>0,g>>>0),Rt[s](...m)},H:()=>Date.now(),O:function(){return 4294901760},q:()=>performance.now(),M:function(s){s>>>=0;var m=K.length;if(4294901760=g;g*=2){var $=m*(1+.2/g);$=Math.min($,s+100663296);var T=Math;$=Math.max(s,$);e:{T=(T.min.call(T,4294901760,$+(65536-$%65536)%65536)-O.buffer.byteLength+65535)/65536;try{O.grow(T),Ae();var B=1;break e}catch{}B=void 0}if(B)return!0}return!1},$:function(s,m){s>>>=0,m>>>=0;var g=0;return ot().forEach(($,T)=>{var B=m+g;for(T=se[s+4*T>>>2>>>0]=B,B=0;B<$.length;++B)N[T++>>>0]=$.charCodeAt(B);N[T>>>0]=0,g+=$.length+1}),0},aa:function(s,m){s>>>=0,m>>>=0;var g=ot();se[s>>>2>>>0]=g.length;var $=0;return g.forEach(T=>$+=T.length+1),se[m>>>2>>>0]=$,0},z:()=>52,F:function(){return 52},_:function(){return 70},E:function(s,m,g,$){m>>>=0,g>>>=0,$>>>=0;for(var T=0,B=0;B>>2>>>0],q=se[m+4>>>2>>>0];m+=8;for(var te=0;te>>0],de=Zn[s];X===0||X===10?((s===1?E:P)(Kt(de,0)),de.length=0):de.push(X)}T+=q}return se[$>>>2>>>0]=T,0},fa:sn,p:function(s,m,g,$){return sn(s>>>0,m>>>0,g>>>0,$>>>0)}},pe=function(){function s(g){return pe=g.exports,pe=Qr(),pe=ln(),O=pe.ja,Ae(),ie.unshift(pe.ka),le--,le==0&&(qe!==null&&(clearInterval(qe),qe=null),G&&(g=G,G=null,g())),pe}var m={a:Qn};if(le++,r.instantiateWasm)try{return r.instantiateWasm(m,s)}catch(g){P(`Module.instantiateWasm callback failed with error: ${g}`),i(g)}return mt(m,function(g){s(g.instance)}).catch(i),{}}(),Mr=s=>(Mr=pe.la)(s);r._OrtInit=(s,m)=>(r._OrtInit=pe.ma)(s,m),r._OrtGetLastError=(s,m)=>(r._OrtGetLastError=pe.na)(s,m),r._OrtCreateSessionOptions=(s,m,g,$,T,B,H,q,te,X)=>(r._OrtCreateSessionOptions=pe.oa)(s,m,g,$,T,B,H,q,te,X),r._OrtAppendExecutionProvider=(s,m)=>(r._OrtAppendExecutionProvider=pe.pa)(s,m),r._OrtAddFreeDimensionOverride=(s,m,g)=>(r._OrtAddFreeDimensionOverride=pe.qa)(s,m,g),r._OrtAddSessionConfigEntry=(s,m,g)=>(r._OrtAddSessionConfigEntry=pe.ra)(s,m,g),r._OrtReleaseSessionOptions=s=>(r._OrtReleaseSessionOptions=pe.sa)(s),r._OrtCreateSession=(s,m,g)=>(r._OrtCreateSession=pe.ta)(s,m,g),r._OrtReleaseSession=s=>(r._OrtReleaseSession=pe.ua)(s),r._OrtGetInputOutputCount=(s,m,g)=>(r._OrtGetInputOutputCount=pe.va)(s,m,g),r._OrtGetInputName=(s,m)=>(r._OrtGetInputName=pe.wa)(s,m),r._OrtGetOutputName=(s,m)=>(r._OrtGetOutputName=pe.xa)(s,m),r._OrtFree=s=>(r._OrtFree=pe.ya)(s),r._OrtCreateTensor=(s,m,g,$,T,B)=>(r._OrtCreateTensor=pe.za)(s,m,g,$,T,B),r._OrtGetTensorData=(s,m,g,$,T)=>(r._OrtGetTensorData=pe.Aa)(s,m,g,$,T),r._OrtReleaseTensor=s=>(r._OrtReleaseTensor=pe.Ba)(s),r._OrtCreateRunOptions=(s,m,g,$)=>(r._OrtCreateRunOptions=pe.Ca)(s,m,g,$),r._OrtAddRunConfigEntry=(s,m,g)=>(r._OrtAddRunConfigEntry=pe.Da)(s,m,g),r._OrtReleaseRunOptions=s=>(r._OrtReleaseRunOptions=pe.Ea)(s),r._OrtCreateBinding=s=>(r._OrtCreateBinding=pe.Fa)(s),r._OrtBindInput=(s,m,g)=>(r._OrtBindInput=pe.Ga)(s,m,g),r._OrtBindOutput=(s,m,g,$)=>(r._OrtBindOutput=pe.Ha)(s,m,g,$),r._OrtClearBoundOutputs=s=>(r._OrtClearBoundOutputs=pe.Ia)(s),r._OrtReleaseBinding=s=>(r._OrtReleaseBinding=pe.Ja)(s),r._OrtRunWithBinding=(s,m,g,$,T)=>(r._OrtRunWithBinding=pe.Ka)(s,m,g,$,T),r._OrtRun=(s,m,g,$,T,B,H,q)=>(r._OrtRun=pe.La)(s,m,g,$,T,B,H,q),r._OrtEndProfiling=s=>(r._OrtEndProfiling=pe.Ma)(s),r._JsepOutput=(s,m,g)=>(r._JsepOutput=pe.Na)(s,m,g),r._JsepGetNodeName=s=>(r._JsepGetNodeName=pe.Oa)(s);var Nt=r._malloc=s=>(Nt=r._malloc=pe.Pa)(s),rt=r._free=s=>(rt=r._free=pe.Qa)(s),yr=s=>(yr=pe.Sa)(s),br=s=>(br=pe.Ta)(s),Ur=()=>(Ur=pe.Ua)(),Jt=s=>(Jt=pe.Wa)(s),dn=()=>(dn=pe.Xa)(),vt=s=>(vt=pe.Ya)(s),ct=()=>(ct=pe.Za)();r.___start_em_js=837952,r.___stop_em_js=838113;function ln(){var s=pe;s=Object.assign({},s);var m=g=>$=>g($)>>>0;return s.la=m(s.la),s.Pa=m(s.Pa),s.Ta=m(s.Ta),s.Ua=(g=>()=>g()>>>0)(s.Ua),s}r.stackSave=()=>Ur(),r.stackRestore=s=>yr(s),r.stackAlloc=s=>br(s),r.UTF8ToString=je,r.stringToUTF8=(s,m,g)=>at(s,K,m,g),r.lengthBytesUTF8=Wt;var Dt;G=function s(){Dt||Vr(),Dt||(G=s)};function Vr(){if(!(0Ii)});var Pi=Wr(()=>{});var ki=Wr(()=>{});var Oi={};gn(Oi,{cpus:()=>ll});var ll,Ri=Y(()=>{ll=void 0});var zi=Wr((Di,mo)=>{"use strict";var Bi=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(t={}){function r(){return ae.buffer!=ue.buffer&&Ne(),ue}function o(){return ae.buffer!=ue.buffer&&Ne(),le}function i(){return ae.buffer!=ue.buffer&&Ne(),qe}function u(){return ae.buffer!=ue.buffer&&Ne(),G}function a(){return ae.buffer!=ue.buffer&&Ne(),ne}function c(){return ae.buffer!=ue.buffer&&Ne(),xe}function p(){return ae.buffer!=ue.buffer&&Ne(),Ke}function h(){return ae.buffer!=ue.buffer&&Ne(),Ut}var d=t,y,w,_=new Promise((n,l)=>{y=n,w=l});d.mountExternalData=(n,l)=>{(d.Db||(d.Db=new Map)).set(n,l)},d.unmountExternalData=()=>{delete d.Db};let v=()=>{let n=(f,b,C)=>(...k)=>{let V=ct,F=b?.();k=f(...k);let re=b?.();return F!==re&&(f=re,C(F),b=C=null),ct!=V?T():k},l=f=>async(...b)=>{try{if(d.Cb)throw Error("Session already started");let C=d.Cb={ec:b[0],errors:[]},k=await f(...b);if(d.Cb!==C)throw Error("Session mismatch");d.Kb?.flush();let V=C.errors;if(0re),0d._OrtCreateSession,f=>d._OrtCreateSession=f),d._OrtRun=l(n(d._OrtRun,()=>d._OrtRun,f=>d._OrtRun=f)),d._OrtRunWithBinding=l(n(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,f=>d._OrtRunWithBinding=f)),d._OrtBindInput=n(d._OrtBindInput,()=>d._OrtBindInput,f=>d._OrtBindInput=f),v=void 0};d.jsepInit=(n,l)=>{if(v?.(),n==="webgpu"){[d.Kb,d.Wb,d.$b,d.Lb,d.Zb,d.ob,d.ac,d.cc,d.Xb,d.Yb,d.bc]=l;let f=d.Kb;d.jsepRegisterBuffer=(b,C,k,V)=>f.registerBuffer(b,C,k,V),d.jsepGetBuffer=b=>f.getBuffer(b),d.jsepCreateDownloader=(b,C,k)=>f.createDownloader(b,C,k),d.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},d.jsepOnRunStart=b=>f.onRunStart(b)}};var S=Object.assign({},d),A="./this.program",I=(n,l)=>{throw l},x=typeof window=="object",E=typeof importScripts=="function",P=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",O=d.ENVIRONMENT_IS_PTHREAD||!1,R="";function L(n){return d.locateFile?d.locateFile(n,R):R+n}var N,K,Q;if(P){var he=(uo(),wr(so)),W=(co(),wr(lo));R=E?W.dirname(R)+"/":__dirname+"/",N=(n,l)=>(n=Wt(n)?new URL(n):W.normalize(n),he.readFileSync(n,l?void 0:"utf8")),Q=n=>(n=N(n,!0),n.buffer||(n=new Uint8Array(n)),n),K=(n,l,f,b=!0)=>{n=Wt(n)?new URL(n):W.normalize(n),he.readFile(n,b?void 0:"utf8",(C,k)=>{C?f(C):l(b?k.buffer:k)})},!d.thisProgram&&1{throw process.exitCode=n,l},global.Worker=Pi().Worker}else(x||E)&&(E?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),typeof e<"u"&&e&&(R=e),R.startsWith("blob:")?R="":R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1),P||(N=n=>{var l=new XMLHttpRequest;return l.open("GET",n,!1),l.send(null),l.responseText},E&&(Q=n=>{var l=new XMLHttpRequest;return l.open("GET",n,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)}),K=(n,l,f)=>{var b=new XMLHttpRequest;b.open("GET",n,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?l(b.response):f()},b.onerror=f,b.send(null)}));P&&typeof performance>"u"&&(global.performance=ki().performance);var se=console.log.bind(console),Ce=console.error.bind(console);P&&(se=(...n)=>he.writeSync(1,n.join(" ")+`\n`),Ce=(...n)=>he.writeSync(2,n.join(" ")+`\n`));var We=se,ee=Ce;Object.assign(d,S),S=null;var ae,Ae,me=!1,ie,ue,le,qe,G,ne,xe,Ke,Be,Ge,Ut;function Ne(){var n=ae.buffer;d.HEAP8=ue=new Int8Array(n),d.HEAP16=qe=new Int16Array(n),d.HEAPU8=le=new Uint8Array(n),d.HEAPU16=G=new Uint16Array(n),d.HEAP32=ne=new Int32Array(n),d.HEAPU32=xe=new Uint32Array(n),d.HEAPF32=Ke=new Float32Array(n),d.HEAPF64=Ut=new Float64Array(n),d.HEAP64=Be=new BigInt64Array(n),d.HEAPU64=Ge=new BigUint64Array(n)}var Ye=16777216;if(O)ae=d.wasmMemory;else if(d.wasmMemory)ae=d.wasmMemory;else if(ae=new WebAssembly.Memory({initial:Ye/65536,maximum:65536,shared:!0}),!(ae.buffer instanceof SharedArrayBuffer))throw ee("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"),P&&ee("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ne(),Ye=ae.buffer.byteLength;var mt=[],Rt=[],qt=[],Vt=0,sr=null,jt=null;function xr(){if(Vt--,Vt==0&&(sr!==null&&(clearInterval(sr),sr=null),jt)){var n=jt;jt=null,n()}}function Kt(n){throw n="Aborted("+n+")",ee(n),me=!0,ie=1,n=new WebAssembly.RuntimeError(n+". Build with -sASSERTIONS for more info."),w(n),n}var je=n=>n.startsWith("data:application/octet-stream;base64,"),Wt=n=>n.startsWith("file://"),at;at="ort-wasm-simd-threaded.wasm",je(at)||(at=L(at));function Cr(n){if(Q)return Q(n);throw"both async and sync fetching of the wasm failed"}function ft(n){if(x||E){if(typeof fetch=="function"&&!Wt(n))return fetch(n,{credentials:"same-origin"}).then(l=>{if(!l.ok)throw`failed to load wasm binary file at \'${n}\'`;return l.arrayBuffer()}).catch(()=>Cr(n));if(K)return new Promise((l,f)=>{K(n,b=>l(new Uint8Array(b)),f)})}return Promise.resolve().then(()=>Cr(n))}function ur(n,l,f){return ft(n).then(b=>WebAssembly.instantiate(b,l)).then(f,b=>{ee(`failed to asynchronously prepare wasm: ${b}`),Kt(b)})}function Ar(n,l){var f=at;return typeof WebAssembly.instantiateStreaming!="function"||je(f)||Wt(f)||P||typeof fetch!="function"?ur(f,n,l):fetch(f,{credentials:"same-origin"}).then(b=>WebAssembly.instantiateStreaming(b,n).then(l,function(C){return ee(`wasm streaming compile failed: ${C}`),ee("falling back to ArrayBuffer instantiation"),ur(f,n,l)}))}var Ir={826468:(n,l,f,b)=>{if(typeof d>"u"||!d.Db)return 1;if(n=He(n>>>0),n.startsWith("./")&&(n=n.substring(2)),n=d.Db.get(n),!n)return 2;if(l>>>=0,f>>>=0,b>>>=0,l+f>n.byteLength)return 3;try{return o().set(n.subarray(l,l+f),b>>>0),0}catch{return 4}},826969:()=>{d.Xb()},827e3:()=>{d.Yb()},827029:()=>{d.bc()},827054:n=>d.Wb(n),827087:n=>d.$b(n),827119:(n,l,f)=>{d.Lb(n,l,f,!0)},827158:(n,l,f)=>{d.Lb(n,l,f)},827191:n=>{d.ob("Abs",n,void 0)},827242:n=>{d.ob("Neg",n,void 0)},827293:n=>{d.ob("Floor",n,void 0)},827346:n=>{d.ob("Ceil",n,void 0)},827398:n=>{d.ob("Reciprocal",n,void 0)},827456:n=>{d.ob("Sqrt",n,void 0)},827508:n=>{d.ob("Exp",n,void 0)},827559:n=>{d.ob("Erf",n,void 0)},827610:n=>{d.ob("Sigmoid",n,void 0)},827665:(n,l,f)=>{d.ob("HardSigmoid",n,{alpha:l,beta:f})},827744:n=>{d.ob("Log",n,void 0)},827795:n=>{d.ob("Sin",n,void 0)},827846:n=>{d.ob("Cos",n,void 0)},827897:n=>{d.ob("Tan",n,void 0)},827948:n=>{d.ob("Asin",n,void 0)},828e3:n=>{d.ob("Acos",n,void 0)},828052:n=>{d.ob("Atan",n,void 0)},828104:n=>{d.ob("Sinh",n,void 0)},828156:n=>{d.ob("Cosh",n,void 0)},828208:n=>{d.ob("Asinh",n,void 0)},828261:n=>{d.ob("Acosh",n,void 0)},828314:n=>{d.ob("Atanh",n,void 0)},828367:n=>{d.ob("Tanh",n,void 0)},828419:n=>{d.ob("Not",n,void 0)},828470:(n,l,f)=>{d.ob("Clip",n,{min:l,max:f})},828539:n=>{d.ob("Clip",n,void 0)},828591:(n,l)=>{d.ob("Elu",n,{alpha:l})},828649:n=>{d.ob("Relu",n,void 0)},828701:(n,l)=>{d.ob("LeakyRelu",n,{alpha:l})},828765:(n,l)=>{d.ob("ThresholdedRelu",n,{alpha:l})},828835:(n,l)=>{d.ob("Cast",n,{to:l})},828893:n=>{d.ob("Add",n,void 0)},828944:n=>{d.ob("Sub",n,void 0)},828995:n=>{d.ob("Mul",n,void 0)},829046:n=>{d.ob("Div",n,void 0)},829097:n=>{d.ob("Pow",n,void 0)},829148:n=>{d.ob("Equal",n,void 0)},829201:n=>{d.ob("Greater",n,void 0)},829256:n=>{d.ob("GreaterOrEqual",n,void 0)},829318:n=>{d.ob("Less",n,void 0)},829370:n=>{d.ob("LessOrEqual",n,void 0)},829429:(n,l,f,b,C)=>{d.ob("ReduceMean",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829588:(n,l,f,b,C)=>{d.ob("ReduceMax",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829746:(n,l,f,b,C)=>{d.ob("ReduceMin",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829904:(n,l,f,b,C)=>{d.ob("ReduceProd",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830063:(n,l,f,b,C)=>{d.ob("ReduceSum",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830221:(n,l,f,b,C)=>{d.ob("ReduceL1",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830378:(n,l,f,b,C)=>{d.ob("ReduceL2",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830535:(n,l,f,b,C)=>{d.ob("ReduceLogSum",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830696:(n,l,f,b,C)=>{d.ob("ReduceSumSquare",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830860:(n,l,f,b,C)=>{d.ob("ReduceLogSumExp",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},831024:n=>{d.ob("Where",n,void 0)},831077:(n,l,f)=>{d.ob("Transpose",n,{perm:l?Array.from(a().subarray(l>>>0,f>>>0)):[]})},831185:(n,l,f,b)=>{d.ob("DepthToSpace",n,{blocksize:l,mode:He(f),format:b?"NHWC":"NCHW"})},831318:(n,l,f,b)=>{d.ob("DepthToSpace",n,{blocksize:l,mode:He(f),format:b?"NHWC":"NCHW"})},831451:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we)=>{d.ob("ConvTranspose",n,{format:re?"NHWC":"NCHW",autoPad:l,dilations:[f],group:b,kernelShape:[C],pads:[k,V],strides:[F],wIsConst:()=>!!r()[J>>>0],outputPadding:ce?Array.from(a().subarray(ce>>>0,Re>>>0)):[],outputShape:ze?Array.from(a().subarray(ze>>>0,z>>>0)):[],activation:He(we)})},831852:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z)=>{d.ob("ConvTranspose",n,{format:F?"NHWC":"NCHW",autoPad:l,dilations:Array.from(a().subarray(f>>>0,(f>>>0)+2>>>0)),group:b,kernelShape:Array.from(a().subarray(C>>>0,(C>>>0)+2>>>0)),pads:Array.from(a().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(a().subarray(V>>>0,(V>>>0)+2>>>0)),wIsConst:()=>!!r()[re>>>0],outputPadding:J?Array.from(a().subarray(J>>>0,ce>>>0)):[],outputShape:Re?Array.from(a().subarray(Re>>>0,ze>>>0)):[],activation:He(z)})},832417:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we)=>{d.ob("ConvTranspose",n,{format:re?"NHWC":"NCHW",autoPad:l,dilations:[f],group:b,kernelShape:[C],pads:[k,V],strides:[F],wIsConst:()=>!!r()[J>>>0],outputPadding:ce?Array.from(a().subarray(ce>>>0,Re>>>0)):[],outputShape:ze?Array.from(a().subarray(ze>>>0,z>>>0)):[],activation:He(we)})},832818:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z)=>{d.ob("ConvTranspose",n,{format:F?"NHWC":"NCHW",autoPad:l,dilations:Array.from(a().subarray(f>>>0,(f>>>0)+2>>>0)),group:b,kernelShape:Array.from(a().subarray(C>>>0,(C>>>0)+2>>>0)),pads:Array.from(a().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(a().subarray(V>>>0,(V>>>0)+2>>>0)),wIsConst:()=>!!r()[re>>>0],outputPadding:J?Array.from(a().subarray(J>>>0,ce>>>0)):[],outputShape:Re?Array.from(a().subarray(Re>>>0,ze>>>0)):[],activation:He(z)})},833383:(n,l)=>{d.ob("GlobalAveragePool",n,{format:l?"NHWC":"NCHW"})},833474:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("AveragePool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},833758:(n,l)=>{d.ob("GlobalAveragePool",n,{format:l?"NHWC":"NCHW"})},833849:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("AveragePool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834133:(n,l)=>{d.ob("GlobalMaxPool",n,{format:l?"NHWC":"NCHW"})},834220:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("MaxPool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834500:(n,l)=>{d.ob("GlobalMaxPool",n,{format:l?"NHWC":"NCHW"})},834587:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("MaxPool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834867:(n,l,f,b,C)=>{d.ob("Gemm",n,{alpha:l,beta:f,transA:b,transB:C})},834971:n=>{d.ob("MatMul",n,void 0)},835025:(n,l,f,b)=>{d.ob("ArgMax",n,{keepDims:!!l,selectLastIndex:!!f,axis:b})},835133:(n,l,f,b)=>{d.ob("ArgMin",n,{keepDims:!!l,selectLastIndex:!!f,axis:b})},835241:(n,l)=>{d.ob("Softmax",n,{axis:l})},835304:(n,l)=>{d.ob("Concat",n,{axis:l})},835364:(n,l,f,b,C)=>{d.ob("Split",n,{axis:l,numOutputs:f,splitSizes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},835504:n=>{d.ob("Expand",n,void 0)},835558:(n,l)=>{d.ob("Gather",n,{axis:Number(l)})},835629:(n,l)=>{d.ob("GatherElements",n,{axis:Number(l)})},835708:(n,l,f,b,C,k,V,F,re,J,ce)=>{d.ob("Resize",n,{antialias:l,axes:f?Array.from(a().subarray(f>>>0,b>>>0)):[],coordinateTransformMode:He(C),cubicCoeffA:k,excludeOutside:V,extrapolationValue:F,keepAspectRatioPolicy:He(re),mode:He(J),nearestMode:He(ce)})},836054:(n,l,f,b,C,k,V)=>{d.ob("Slice",n,{starts:l?Array.from(a().subarray(l>>>0,f>>>0)):[],ends:b?Array.from(a().subarray(b>>>0,C>>>0)):[],axes:k?Array.from(a().subarray(k>>>0,V>>>0)):[]})},836270:n=>{d.ob("Tile",n,void 0)},836322:(n,l,f,b)=>{d.ob("LayerNormalization",n,{axis:l,epsilon:f,simplified:!!b})},836433:(n,l,f)=>{d.ob("InstanceNormalization",n,{epsilon:l,format:f?"NHWC":"NCHW"})},836547:(n,l,f)=>{d.ob("InstanceNormalization",n,{epsilon:l,format:f?"NHWC":"NCHW"})},836661:n=>{d.ob("Range",n,void 0)},836714:(n,l)=>{d.ob("Einsum",n,{equation:He(l)})},836795:(n,l,f,b,C)=>{d.ob("Pad",n,{mode:l,value:f,pads:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},836922:(n,l,f,b,C,k)=>{d.ob("BatchNormalization",n,{epsilon:l,momentum:f,spatial:!!C,trainingMode:!!b,format:k?"NHWC":"NCHW"})},837091:(n,l,f,b,C,k)=>{d.ob("BatchNormalization",n,{epsilon:l,momentum:f,spatial:!!C,trainingMode:!!b,format:k?"NHWC":"NCHW"})},837260:(n,l,f)=>{d.ob("CumSum",n,{exclusive:Number(l),reverse:Number(f)})},837357:(n,l,f,b,C,k,V,F,re)=>{d.ob("Attention",n,{numHeads:l,isUnidirectional:f,maskFilterValue:b,scale:C,doRotary:k,qkvHiddenSizes:V?Array.from(a().subarray(Number(F)>>>0,Number(F)+V>>>0)):[],pastPresentShareBuffer:!!re})},837629:n=>{d.ob("BiasAdd",n,void 0)},837684:n=>{d.ob("BiasSplitGelu",n,void 0)},837745:n=>{d.ob("FastGelu",n,void 0)},837801:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze)=>{d.ob("Conv",n,{format:re?"NHWC":"NCHW",auto_pad:l,dilations:[f],group:b,kernel_shape:[C],pads:k?Array.from(a().subarray(k>>>0,V>>>0)):[],strides:[F],w_is_const:()=>!!r()[J>>>0],activation:He(ce),activation_params:Re?Array.from(p().subarray(Re>>>0,ze>>>0)):[]})},838171:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("Conv",n,{format:Re?"NHWC":"NCHW",auto_pad:l,dilations:[f,b],group:C,kernel_shape:[k,V],pads:F?Array.from(a().subarray(F>>>0,re>>>0)):[],strides:[J,ce],w_is_const:()=>!!r()[ze>>>0],activation:He(z),activation_params:we?Array.from(p().subarray(we>>>0,Pe>>>0)):[]})},838562:n=>{d.ob("Gelu",n,void 0)},838614:(n,l,f,b,C,k)=>{d.ob("MatMulNBits",n,{k:l,n:f,accuracyLevel:b,bits:C,blockSize:k})},838741:(n,l,f,b,C,k)=>{d.ob("MultiHeadAttention",n,{numHeads:l,isUnidirectional:f,maskFilterValue:b,scale:C,doRotary:k})},838900:(n,l,f,b,C)=>{d.ob("RotaryEmbedding",n,{interleaved:!!l,numHeads:f,rotaryEmbeddingDim:b,scale:C})},839039:(n,l,f)=>{d.ob("SkipLayerNormalization",n,{epsilon:l,simplified:!!f})},839141:(n,l,f)=>{d.ob("SkipLayerNormalization",n,{epsilon:l,simplified:!!f})},839243:(n,l,f,b)=>{d.ob("LayerNormalization",n,{axis:l,epsilon:f,simplified:!!b})},839354:n=>{d.ac(n)},839388:(n,l)=>d.cc(n,l,d.Cb.ec,d.Cb.errors)};function st(n){this.name="ExitStatus",this.message=`Program terminated with exit(${n})`,this.status=n}var Tr=n=>{n.terminate(),n.onmessage=()=>{}},ht=n=>{ge.xb.length==0&&(lr(),ge.Mb(ge.xb[0]));var l=ge.xb.pop();if(!l)return 6;ge.yb.push(l),ge.ub[n.wb]=l,l.wb=n.wb;var f={cmd:"run",start_routine:n.fc,arg:n.Rb,pthread_ptr:n.wb};return P&&l.unref(),l.postMessage(f,n.mc),0},bt=0,Er=n=>{var l=io();return n=n(),fn(l),n},Te=(n,l,...f)=>Er(()=>{for(var b=2*f.length,C=oo(8*b),k=C>>>3,V=0;V>>0]=F)}return gi(n,0,b,C,l)});function dr(n){if(O)return Te(0,1,n);ie=n,0{if(ie=n,O)throw jr(n),"unwind";dr(n)};function ut(){for(var n=d.numThreads;n--;)lr();mt.unshift(()=>{Vt++,Fn(()=>xr())})}function lr(){var n=L("ort-wasm-simd-threaded.worker.js");n=new Worker(n),ge.xb.push(n)}function Fn(n){O?n():Promise.all(ge.xb.map(ge.Mb)).then(n)}var ge={xb:[],yb:[],Qb:[],ub:{},Gb(){O?(ge.receiveObjectTransfer=ge.dc,ge.threadInitTLS=ge.Pb,ge.setExitStatus=ge.Ob):ut()},Ob:n=>ie=n,pc:["$terminateWorker"],hc:()=>{for(var n of ge.yb)Tr(n);for(n of ge.xb)Tr(n);ge.xb=[],ge.yb=[],ge.ub=[]},Nb:n=>{var l=n.wb;delete ge.ub[l],ge.xb.push(n),ge.yb.splice(ge.yb.indexOf(n),1),n.wb=0,ro(l)},dc(){},Pb(){ge.Qb.forEach(n=>n())},Mb:n=>new Promise(l=>{n.onmessage=k=>{k=k.data;var V=k.cmd;if(k.targetThread&&k.targetThread!=pn()){var F=ge.ub[k.targetThread];F?F.postMessage(k,k.transferList):ee(`Internal error! Worker sent a message "${V}" to target pthread ${k.targetThread}, but that thread no longer exists!`)}else V==="checkMailbox"?rt():V==="spawnThread"?ht(k):V==="cleanupThread"?ge.Nb(ge.ub[k.thread]):V==="killThread"?(k=k.thread,V=ge.ub[k],delete ge.ub[k],Tr(V),ro(k),ge.yb.splice(ge.yb.indexOf(V),1),V.wb=0):V==="cancelThread"?ge.ub[k.thread].postMessage({cmd:"cancel"}):V==="loaded"?(n.loaded=!0,P&&!n.wb&&n.unref(),l(n)):V==="alert"?alert(`Thread ${k.threadId}: ${k.text}`):k.target==="setimmediate"?n.postMessage(k):V==="callHandler"?d[k.handler](...k.args):V&&ee(`worker sent an unknown command ${V}`)},n.onerror=k=>{throw ee(`worker sent an error! ${k.filename}:${k.lineno}: ${k.message}`),k},P&&(n.on("message",k=>n.onmessage({data:k})),n.on("error",k=>n.onerror(k)));var f=[],b=["onExit"],C;for(C of b)d.hasOwnProperty(C)&&f.push(C);n.postMessage({cmd:"load",handlers:f,urlOrBlob:d.mainScriptUrlOrBlob||e,wasmMemory:ae,wasmModule:Ae})})};d.PThread=ge;var Yt=n=>{for(;0{var n=pn(),l=c()[n+52>>>2>>>0];n=c()[n+56>>>2>>>0],bi(l,l-n),fn(l)};function jr(n){if(O)return Te(1,0,n);Xe(n)}d.invokeEntryPoint=(n,l)=>{bt=0,n=wi(n,l),0>>2>>>0]=0,c()[this.Ib+4>>>2>>>0]=l,c()[this.Ib+8>>>2>>>0]=f}}var Kr=0,jn=0;function Yr(n,l,f,b){return O?Te(2,1,n,l,f,b):Zr(n,l,f,b)}function Zr(n,l,f,b){if(n>>>=0,l>>>=0,f>>>=0,b>>>=0,typeof SharedArrayBuffer>"u")return ee("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var C=[];return O&&C.length===0?Yr(n,l,f,b):(n={fc:f,wb:n,Rb:b,mc:C},O?(n.oc="spawnThread",postMessage(n,C),0):ht(n))}var cr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Pr=(n,l,f)=>{l>>>=0;var b=l+f;for(f=l;n[f]&&!(f>=b);)++f;if(16C?b+=String.fromCharCode(C):(C-=65536,b+=String.fromCharCode(55296|C>>10,56320|C&1023))}}else b+=String.fromCharCode(C)}return b},He=(n,l)=>(n>>>=0)?Pr(o(),n,l):"";function Xr(n,l,f){return O?Te(3,1,n,l,f):0}function Qr(n,l){if(O)return Te(4,1,n,l)}var gt=n=>{for(var l=0,f=0;f=b?l++:2047>=b?l+=2:55296<=b&&57343>=b?(l+=4,++f):l+=3}return l},dt=(n,l,f,b)=>{if(f>>>=0,!(0=V){var F=n.charCodeAt(++k);V=65536+((V&1023)<<10)|F&1023}if(127>=V){if(f>=b)break;l[f++>>>0]=V}else{if(2047>=V){if(f+1>=b)break;l[f++>>>0]=192|V>>6}else{if(65535>=V){if(f+2>=b)break;l[f++>>>0]=224|V>>12}else{if(f+3>=b)break;l[f++>>>0]=240|V>>18,l[f++>>>0]=128|V>>12&63}l[f++>>>0]=128|V>>6&63}l[f++>>>0]=128|V&63}}return l[f>>>0]=0,f-C},Bt=(n,l,f)=>dt(n,o(),l,f);function Zt(n,l){if(O)return Te(5,1,n,l)}function kr(n,l,f){if(O)return Te(6,1,n,l,f)}function Or(n,l,f){return O?Te(7,1,n,l,f):0}function Jr(n,l){if(O)return Te(8,1,n,l)}function pr(n,l,f){if(O)return Te(9,1,n,l,f)}function en(n,l,f,b){if(O)return Te(10,1,n,l,f,b)}function tn(n,l,f,b){if(O)return Te(11,1,n,l,f,b)}function rn(n,l,f,b){if(O)return Te(12,1,n,l,f,b)}function nn(n){if(O)return Te(13,1,n)}function Rr(n,l){if(O)return Te(14,1,n,l)}function Xt(n,l,f){if(O)return Te(15,1,n,l,f)}var on,nt=n=>{for(var l="";o()[n>>>0];)l+=on[o()[n++>>>0]];return l},mr={},Br={},Kn={},wt;function Yn(n,l,f={}){var b=l.name;if(!n)throw new wt(`type "${b}" must have a positive integer typeid pointer`);if(Br.hasOwnProperty(n)){if(f.Ub)return;throw new wt(`Cannot register type \'${b}\' twice`)}Br[n]=l,delete Kn[n],mr.hasOwnProperty(n)&&(l=mr[n],delete mr[n],l.forEach(C=>C()))}function Je(n,l,f={}){if(!("argPackAdvance"in l))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Yn(n,l,f)}var Dr=(n,l,f)=>{switch(l){case 1:return f?b=>r()[b>>>0]:b=>o()[b>>>0];case 2:return f?b=>i()[b>>>1>>>0]:b=>u()[b>>>1>>>0];case 4:return f?b=>a()[b>>>2>>>0]:b=>c()[b>>>2>>>0];case 8:return f?b=>Be[b>>>3]:b=>Ge[b>>>3];default:throw new TypeError(`invalid integer width (${l}): ${n}`)}},fr=[],lt=[];function hr(n){n>>>=0,9{if(!n)throw new wt("Cannot use deleted val. handle = "+n);return lt[n]},ot=n=>{switch(n){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let l=fr.pop()||lt.length;return lt[l]=n,lt[l+1]=1,l}};function Qt(n){return this.fromWireType(c()[n>>>2>>>0])}var Zn={name:"emscripten::val",fromWireType:n=>{var l=Qe(n);return hr(n),l},toWireType:(n,l)=>ot(l),argPackAdvance:8,readValueFromPointer:Qt,Bb:null},an=(n,l)=>{switch(l){case 4:return function(f){return this.fromWireType(p()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(h()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${l}): ${n}`)}},zr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Xn=(n,l)=>{for(var f=n>>1,b=f+l/2;!(f>=b)&&u()[f>>>0];)++f;if(f<<=1,32=l/2);++b){var C=i()[n+2*b>>>1>>>0];if(C==0)break;f+=String.fromCharCode(C)}return f},sn=(n,l,f)=>{if(f??=2147483647,2>f)return 0;f-=2;var b=l;f=f<2*n.length?f/2:n.length;for(var C=0;C>>1>>>0]=k,l+=2}return i()[l>>>1>>>0]=0,l-b},un=n=>2*n.length,gr=(n,l)=>{for(var f=0,b="";!(f>=l/4);){var C=a()[n+4*f>>>2>>>0];if(C==0)break;++f,65536<=C?(C-=65536,b+=String.fromCharCode(55296|C>>10,56320|C&1023)):b+=String.fromCharCode(C)}return b},Qn=(n,l,f)=>{if(l>>>=0,f??=2147483647,4>f)return 0;var b=l;f=b+f-4;for(var C=0;C=k){var V=n.charCodeAt(++C);k=65536+((k&1023)<<10)|V&1023}if(a()[l>>>2>>>0]=k,l+=4,l+4>f)break}return a()[l>>>2>>>0]=0,l-b},pe=n=>{for(var l=0,f=0;f=b&&++f,l+=4}return l},Mr=n=>{if(!me)try{if(n(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(a(),n>>>2,n).value.then(rt),n+=128,Atomics.store(a(),n>>>2,1))}d.__emscripten_thread_mailbox_await=Nt;var rt=()=>{var n=pn();n&&(Nt(n),Mr(yi))};d.checkMailbox=rt;var yr=[],br=(n,l)=>{var f=Br[n];if(f===void 0)throw n=fi(n),f=nt(n),At(n),new wt(`${l} has unknown type ${f}`);return f},Ur=(n,l,f)=>{var b=[];return n=n.toWireType(b,f),b.length&&(c()[l>>>2>>>0]=ot(b)),n},Jt=n=>{try{n()}catch(l){Kt(l)}};function dn(){var n=oe,l={};for(let[f,b]of Object.entries(n))l[f]=typeof b=="function"?(...C)=>{Dt.push(f);try{return b(...C)}finally{me||(Dt.pop(),ct&&vt===1&&Dt.length===0&&(vt=0,bt+=1,Jt($i),typeof Fibers<"u"&&Fibers.rc()))}}:b;return l}var vt=0,ct=null,ln=0,Dt=[],Vr={},s={},m=0,g=null,$=[];function T(){return new Promise((n,l)=>{g={resolve:n,reject:l}})}function B(){var n=mn(65548),l=n+12;c()[n>>>2>>>0]=l,c()[n+4>>>2>>>0]=l+65536,l=Dt[0];var f=Vr[l];return f===void 0&&(f=m++,Vr[l]=f,s[f]=l),l=f,a()[n+8>>>2>>>0]=l,n}function H(){var n=a()[ct+8>>>2>>>0];return n=oe[s[n]],--bt,n()}function q(n){if(!me){if(vt===0){var l=!1,f=!1;n((b=0)=>{if(!me&&(ln=b,l=!0,f)){vt=2,Jt(()=>_i(ct)),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.resume(),b=!1;try{var C=H()}catch(F){C=F,b=!0}var k=!1;if(!ct){var V=g;V&&(g=null,(b?V.reject:V.resolve)(C),k=!0)}if(b&&!k)throw C}}),f=!0,l||(vt=1,ct=B(),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.pause(),Jt(()=>vi(ct)))}else vt===2?(vt=0,Jt(Si),At(ct),ct=null,$.forEach(Mr)):Kt(`invalid state: ${vt}`);return ln}}function te(n){return q(l=>{n().then(l)})}var X=[],de={},Ee=n=>{var l=de[n];return l===void 0?nt(n):l},Oe=()=>typeof globalThis=="object"?globalThis:Function("return this")(),D=n=>{var l=X.length;return X.push(n),l},be=(n,l)=>{for(var f=Array(n),b=0;b>>2>>>0],"parameter "+b);return f},Ie=(n,l)=>Object.defineProperty(l,"name",{value:n});function zt(n){var l=Function;if(!(l instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof l} which is not a function`);var f=Ie(l.name||"unknownFunctionName",function(){});return f.prototype=l.prototype,f=new f,n=l.apply(f,n),n instanceof Object?n:f}var Mt=n=>n%4===0&&(n%100!==0||n%400===0),Qo=[0,31,60,91,121,152,182,213,244,274,305,335],Jo=[0,31,59,90,120,151,181,212,243,273,304,334];function ei(n,l,f,b,C,k,V){return O?Te(16,1,n,l,f,b,C,k,V):-52}function ti(n,l,f,b,C,k){if(O)return Te(17,1,n,l,f,b,C,k)}var Jn=[],ri=(n,l)=>{Jn.length=0;for(var f;f=o()[n++>>>0];){var b=f!=105;b&=f!=112,l+=b&&l%8?4:0,Jn.push(f==112?c()[l>>>2>>>0]:f==106?Be[l>>>3]:f==105?a()[l>>>2>>>0]:h()[l>>>3>>>0]),l+=b?8:4}return Jn},eo={},ni=()=>{if(!to){var n={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",_:A||"./this.program"},l;for(l in eo)eo[l]===void 0?delete n[l]:n[l]=eo[l];var f=[];for(l in n)f.push(`${l}=${n[l]}`);to=f}return to},to;function oi(n,l){if(O)return Te(18,1,n,l);n>>>=0,l>>>=0;var f=0;return ni().forEach((b,C)=>{var k=l+f;for(C=c()[n+4*C>>>2>>>0]=k,k=0;k>>0]=b.charCodeAt(k);r()[C>>>0]=0,f+=b.length+1}),0}function ii(n,l){if(O)return Te(19,1,n,l);n>>>=0,l>>>=0;var f=ni();c()[n>>>2>>>0]=f.length;var b=0;return f.forEach(C=>b+=C.length+1),c()[l>>>2>>>0]=b,0}function ai(n){return O?Te(20,1,n):52}function si(n,l,f,b){return O?Te(21,1,n,l,f,b):52}function ui(n,l,f,b){return O?Te(22,1,n,l,f,b):70}var Xd=[null,[],[]];function di(n,l,f,b){if(O)return Te(23,1,n,l,f,b);l>>>=0,f>>>=0,b>>>=0;for(var C=0,k=0;k>>2>>>0],F=c()[l+4>>>2>>>0];l+=8;for(var re=0;re>>0],ce=Xd[n];J===0||J===10?((n===1?We:ee)(Pr(ce,0)),ce.length=0):ce.push(J)}C+=F}return c()[b>>>2>>>0]=C,0}var li=[31,29,31,30,31,30,31,31,30,31,30,31],ci=[31,28,31,30,31,30,31,31,30,31,30,31];function Qd(n){var l=Array(gt(n)+1);return dt(n,l,0,l.length),l}var Jd=(n,l)=>{r().set(n,l>>>0)};function pi(n,l,f,b){function C(z,we,Pe){for(z=typeof z=="number"?z.toString():z||"";z.lengthCi?-1:0er-z.getDate())we-=er-z.getDate()+1,z.setDate(1),11>Pe?z.setMonth(Pe+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1));else{z.setDate(z.getDate()+we);break}}return Pe=new Date(z.getFullYear()+1,0,4),we=F(new Date(z.getFullYear(),0,4)),Pe=F(Pe),0>=V(we,z)?0>=V(Pe,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}n>>>=0,l>>>=0,f>>>=0,b>>>=0;var J=c()[b+40>>>2>>>0];b={kc:a()[b>>>2>>>0],jc:a()[b+4>>>2>>>0],Eb:a()[b+8>>>2>>>0],Jb:a()[b+12>>>2>>>0],Fb:a()[b+16>>>2>>>0],Ab:a()[b+20>>>2>>>0],vb:a()[b+24>>>2>>>0],zb:a()[b+28>>>2>>>0],qc:a()[b+32>>>2>>>0],ic:a()[b+36>>>2>>>0],lc:J?He(J):""},f=He(f),J={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var ce in J)f=f.replace(new RegExp(ce,"g"),J[ce]);var Re="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ze="January February March April May June July August September October November December".split(" ");J={"%a":z=>Re[z.vb].substring(0,3),"%A":z=>Re[z.vb],"%b":z=>ze[z.Fb].substring(0,3),"%B":z=>ze[z.Fb],"%C":z=>k((z.Ab+1900)/100|0,2),"%d":z=>k(z.Jb,2),"%e":z=>C(z.Jb,2," "),"%g":z=>re(z).toString().substring(2),"%G":re,"%H":z=>k(z.Eb,2),"%I":z=>(z=z.Eb,z==0?z=12:12{for(var we=0,Pe=0;Pe<=z.Fb-1;we+=(Mt(z.Ab+1900)?li:ci)[Pe++]);return k(z.Jb+we,3)},"%m":z=>k(z.Fb+1,2),"%M":z=>k(z.jc,2),"%n":()=>`\n`,"%p":z=>0<=z.Eb&&12>z.Eb?"AM":"PM","%S":z=>k(z.kc,2),"%t":()=>" ","%u":z=>z.vb||7,"%U":z=>k(Math.floor((z.zb+7-z.vb)/7),2),"%V":z=>{var we=Math.floor((z.zb+7-(z.vb+6)%7)/7);if(2>=(z.vb+371-z.zb-2)%7&&we++,we)we==53&&(Pe=(z.vb+371-z.zb)%7,Pe==4||Pe==3&&Mt(z.Ab)||(we=1));else{we=52;var Pe=(z.vb+7-z.zb-1)%7;(Pe==4||Pe==5&&Mt(z.Ab%400-1))&&we++}return k(we,2)},"%w":z=>z.vb,"%W":z=>k(Math.floor((z.zb+7-(z.vb+6)%7)/7),2),"%y":z=>(z.Ab+1900).toString().substring(2),"%Y":z=>z.Ab+1900,"%z":z=>{z=z.ic;var we=0<=z;return z=Math.abs(z)/60,(we?"+":"-")+("0000"+(z/60*100+z%60)).slice(-4)},"%Z":z=>z.lc,"%%":()=>"%"},f=f.replace(/%%/g,"\\0\\0");for(ce in J)f.includes(ce)&&(f=f.replace(new RegExp(ce,"g"),J[ce](b)));return f=f.replace(/\\0\\0/g,"%"),ce=Qd(f),ce.length>l?0:(Jd(ce,n),ce.length-1)}ge.Gb();for(var mi=Array(256),cn=0;256>cn;++cn)mi[cn]=String.fromCharCode(cn);on=mi,wt=d.BindingError=class extends Error{constructor(n){super(n),this.name="BindingError"}},d.InternalError=class extends Error{constructor(n){super(n),this.name="InternalError"}},lt.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>lt.length/2-5-fr.length;var el=[dr,jr,Yr,Xr,Qr,Zt,kr,Or,Jr,pr,en,tn,rn,nn,Rr,Xt,ei,ti,oi,ii,ai,si,ui,di],tl={ua:function(n,l,f){return te(async()=>{await d.Zb(n,l,f)})},b:function(n,l,f){throw n>>>=0,new qn(n).Gb(l>>>0,f>>>0),Kr=n,jn++,Kr},ia:function(n){hi(n>>>0,!E,1,!x,131072,!1),ge.Pb()},G:function(n){n>>>=0,O?postMessage({cmd:"cleanupThread",thread:n}):ge.Nb(ge.ub[n])},_:Zr,A:Xr,pa:Qr,W:Zt,Y:kr,qa:Or,na:Jr,fa:pr,ma:en,K:tn,X:rn,U:nn,oa:Rr,V:Xt,E:function(n,l,f){n>>>=0,f>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:b=>b,toWireType:function(b,C){if(typeof C!="bigint"&&typeof C!="number")throw C===null?C="null":(b=typeof C,C=b==="object"||b==="array"||b==="function"?C.toString():""+C),new TypeError(`Cannot convert "${C}" to ${this.name}`);return typeof C=="number"&&(C=BigInt(C)),C},argPackAdvance:8,readValueFromPointer:Dr(l,f,l.indexOf("u")==-1),Bb:null})},O:function(n,l,f,b){n>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:function(C){return!!C},toWireType:function(C,k){return k?f:b},argPackAdvance:8,readValueFromPointer:function(C){return this.fromWireType(o()[C>>>0])},Bb:null})},N:function(n){return Je(n>>>0,Zn)},D:function(n,l,f){n>>>=0,f>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:b=>b,toWireType:(b,C)=>C,argPackAdvance:8,readValueFromPointer:an(l,f),Bb:null})},t:function(n,l,f,b,C){if(n>>>=0,f>>>=0,l=nt(l>>>0),C===-1&&(C=4294967295),C=F=>F,b===0){var k=32-8*f;C=F=>F<>>k}var V=l.includes("unsigned")?function(F,re){return re>>>0}:function(F,re){return re};Je(n,{name:l,fromWireType:C,toWireType:V,argPackAdvance:8,readValueFromPointer:Dr(l,f,b!==0),Bb:null})},p:function(n,l,f){function b(k){var V=c()[k>>>2>>>0];return k=c()[k+4>>>2>>>0],new C(r().buffer,k,V)}n>>>=0;var C=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][l];f=nt(f>>>0),Je(n,{name:f,fromWireType:b,argPackAdvance:8,readValueFromPointer:b},{Ub:!0})},F:function(n,l){n>>>=0,l=nt(l>>>0);var f=l==="std::string";Je(n,{name:l,fromWireType:function(b){var C=c()[b>>>2>>>0],k=b+4;if(f)for(var V=k,F=0;F<=C;++F){var re=k+F;if(F==C||o()[re>>>0]==0){if(V=He(V,re-V),J===void 0)var J=V;else J+=String.fromCharCode(0),J+=V;V=re+1}}else{for(J=Array(C),F=0;F>>0]);J=J.join("")}return At(b),J},toWireType:function(b,C){C instanceof ArrayBuffer&&(C=new Uint8Array(C));var k=typeof C=="string";if(!(k||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array))throw new wt("Cannot pass non-string to std::string");var V=f&&k?gt(C):C.length,F=mn(4+V+1),re=F+4;if(c()[F>>>2>>>0]=V,f&&k)Bt(C,re,V+1);else if(k)for(k=0;k>>0]=J}else for(k=0;k>>0]=C[k];return b!==null&&b.push(At,F),F},argPackAdvance:8,readValueFromPointer:Qt,Bb(b){At(b)}})},z:function(n,l,f){if(n>>>=0,l>>>=0,f>>>=0,f=nt(f),l===2)var b=Xn,C=sn,k=un,V=F=>u()[F>>>1>>>0];else l===4&&(b=gr,C=Qn,k=pe,V=F=>c()[F>>>2>>>0]);Je(n,{name:f,fromWireType:F=>{for(var re=c()[F>>>2>>>0],J,ce=F+4,Re=0;Re<=re;++Re){var ze=F+4+Re*l;(Re==re||V(ze)==0)&&(ce=b(ce,ze-ce),J===void 0?J=ce:(J+=String.fromCharCode(0),J+=ce),ce=ze+l)}return At(F),J},toWireType:(F,re)=>{if(typeof re!="string")throw new wt(`Cannot pass non-string to C++ string type ${f}`);var J=k(re),ce=mn(4+J+l);return c()[ce>>>2>>>0]=J/l,C(re,ce+4,J+l),F!==null&&F.push(At,ce),ce},argPackAdvance:8,readValueFromPointer:Qt,Bb(F){At(F)}})},P:function(n,l){n>>>=0,l=nt(l>>>0),Je(n,{Vb:!0,name:l,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ta:()=>1,S:function(n,l){n>>>=0,n==l>>>0?setTimeout(rt):O?postMessage({targetThread:n,cmd:"checkMailbox"}):(n=ge.ub[n])&&n.postMessage({cmd:"checkMailbox"})},$:function(n,l,f,b,C){l>>>=0,f>>>=0,b/=2,yr.length=b,C=C>>>0>>>3;for(var k=0;k>>0];return n=l?Ir[l]:el[n],ge.Sb=f,f=n(...yr),ge.Sb=0,f},ha:Nt,sa:function(n){P&&ge.ub[n>>>0].ref()},w:function(n,l,f){return l>>>=0,f>>>=0,n=Qe(n>>>0),l=br(l,"emval::as"),Ur(l,f,n)},y:function(n){return n>>>=0,te(()=>(n=Qe(n),n.then(ot)))},o:function(n,l,f,b){return f>>>=0,b>>>=0,n=X[n>>>0],l=Qe(l>>>0),n(null,l,f,b)},k:function(n,l,f,b,C){return f>>>=0,b>>>=0,C>>>=0,n=X[n>>>0],l=Qe(l>>>0),f=Ee(f),n(l,l[f],b,C)},c:hr,C:function(n,l){return l>>>=0,n=Qe(n>>>0),l=Qe(l),n==l},n:function(n){return n>>>=0,n===0?ot(Oe()):(n=Ee(n),ot(Oe()[n]))},j:function(n,l,f){l=be(n,l>>>0);var b=l.shift();n--;var C=`return function (obj, func, destructorsRef, args) {\n`,k=0,V=[];f===0&&V.push("obj");for(var F=["retType"],re=[b],J=0;Jce.name).join(", ")}) => ${b.name}>`,D(Ie(f,n))},s:function(n,l){return l>>>=0,n=Qe(n>>>0),l=Qe(l),ot(n[l])},d:function(n){n>>>=0,9>>0);for(var l=Array(n.length),f=0;f>>0))},l:function(){return ot({})},i:function(n){n>>>=0;for(var l=Qe(n);l.length;){var f=l.pop();l.pop()(f)}hr(n)},h:function(n,l,f){l>>>=0,f>>>=0,n=Qe(n>>>0),l=Qe(l),f=Qe(f),n[l]=f},e:function(n,l){return l>>>=0,n=br(n>>>0,"_emval_take_value"),n=n.readValueFromPointer(l),ot(n)},ca:function(n,l){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),a()[l>>>2>>>0]=n.getUTCSeconds(),a()[l+4>>>2>>>0]=n.getUTCMinutes(),a()[l+8>>>2>>>0]=n.getUTCHours(),a()[l+12>>>2>>>0]=n.getUTCDate(),a()[l+16>>>2>>>0]=n.getUTCMonth(),a()[l+20>>>2>>>0]=n.getUTCFullYear()-1900,a()[l+24>>>2>>>0]=n.getUTCDay(),n=(n.getTime()-Date.UTC(n.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[l+28>>>2>>>0]=n},da:function(n,l){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),a()[l>>>2>>>0]=n.getSeconds(),a()[l+4>>>2>>>0]=n.getMinutes(),a()[l+8>>>2>>>0]=n.getHours(),a()[l+12>>>2>>>0]=n.getDate(),a()[l+16>>>2>>>0]=n.getMonth(),a()[l+20>>>2>>>0]=n.getFullYear()-1900,a()[l+24>>>2>>>0]=n.getDay();var f=(Mt(n.getFullYear())?Qo:Jo)[n.getMonth()]+n.getDate()-1|0;a()[l+28>>>2>>>0]=f,a()[l+36>>>2>>>0]=-(60*n.getTimezoneOffset()),f=new Date(n.getFullYear(),6,1).getTimezoneOffset();var b=new Date(n.getFullYear(),0,1).getTimezoneOffset();n=(f!=b&&n.getTimezoneOffset()==Math.min(b,f))|0,a()[l+32>>>2>>>0]=n},ea:function(n){n>>>=0;var l=new Date(a()[n+20>>>2>>>0]+1900,a()[n+16>>>2>>>0],a()[n+12>>>2>>>0],a()[n+8>>>2>>>0],a()[n+4>>>2>>>0],a()[n>>>2>>>0],0),f=a()[n+32>>>2>>>0],b=l.getTimezoneOffset(),C=new Date(l.getFullYear(),6,1).getTimezoneOffset(),k=new Date(l.getFullYear(),0,1).getTimezoneOffset(),V=Math.min(k,C);return 0>f?a()[n+32>>>2>>>0]=+(C!=k&&V==b):0>>2>>>0]=l.getDay(),f=(Mt(l.getFullYear())?Qo:Jo)[l.getMonth()]+l.getDate()-1|0,a()[n+28>>>2>>>0]=f,a()[n>>>2>>>0]=l.getSeconds(),a()[n+4>>>2>>>0]=l.getMinutes(),a()[n+8>>>2>>>0]=l.getHours(),a()[n+12>>>2>>>0]=l.getDate(),a()[n+16>>>2>>>0]=l.getMonth(),a()[n+20>>>2>>>0]=l.getYear(),n=l.getTime(),BigInt(isNaN(n)?-1:n/1e3)},aa:ei,ba:ti,R:function(n,l,f,b){n>>>=0,l>>>=0,f>>>=0,b>>>=0;var C=new Date().getFullYear(),k=new Date(C,0,1),V=new Date(C,6,1);C=k.getTimezoneOffset();var F=V.getTimezoneOffset(),re=Math.max(C,F);c()[n>>>2>>>0]=60*re,a()[l>>>2>>>0]=+(C!=F),n=J=>J.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],k=n(k),V=n(V),F{Kt("")},f:function(n,l,f){return n>>>=0,l=ri(l>>>0,f>>>0),Ir[n](...l)},M:function(n,l,f){return n>>>=0,l=ri(l>>>0,f>>>0),Ir[n](...l)},H:()=>{},L:()=>Date.now(),ra:()=>{throw bt+=1,"unwind"},T:function(){return 4294901760},u:()=>performance.timeOrigin+performance.now(),x:()=>P?(Ri(),wr(Oi)).cpus().length:navigator.hardwareConcurrency,Q:function(n){n>>>=0;var l=o().length;if(n<=l||4294901760=f;f*=2){var b=l*(1+.2/f);b=Math.min(b,n+100663296);var C=Math;b=Math.max(n,b);e:{C=(C.min.call(C,4294901760,b+(65536-b%65536)%65536)-ae.buffer.byteLength+65535)/65536;try{ae.grow(C),Ne();var k=1;break e}catch{}k=void 0}if(k)return!0}return!1},ja:oi,la:ii,Z:Xe,B:ai,J:si,ga:ui,I:di,a:ae||d.wasmMemory,ka:pi,r:function(n,l,f,b){return pi(n>>>0,l>>>0,f>>>0,b>>>0)}},oe=function(){function n(f,b){return oe=f.exports,oe=dn(),oe=rl(),ge.Qb.push(oe.cb),Rt.unshift(oe.va),Ae=b,xr(),oe}var l={a:tl};if(Vt++,d.instantiateWasm)try{return d.instantiateWasm(l,n)}catch(f){ee(`Module.instantiateWasm callback failed with error: ${f}`),w(f)}return Ar(l,function(f){n(f.instance,f.module)}).catch(w),{}}(),fi=n=>(fi=oe.wa)(n);d.__embind_initialize_bindings=()=>(d.__embind_initialize_bindings=oe.xa)(),d._OrtInit=(n,l)=>(d._OrtInit=oe.ya)(n,l),d._OrtGetLastError=(n,l)=>(d._OrtGetLastError=oe.za)(n,l),d._OrtCreateSessionOptions=(n,l,f,b,C,k,V,F,re,J)=>(d._OrtCreateSessionOptions=oe.Aa)(n,l,f,b,C,k,V,F,re,J),d._OrtAppendExecutionProvider=(n,l)=>(d._OrtAppendExecutionProvider=oe.Ba)(n,l),d._OrtAddFreeDimensionOverride=(n,l,f)=>(d._OrtAddFreeDimensionOverride=oe.Ca)(n,l,f),d._OrtAddSessionConfigEntry=(n,l,f)=>(d._OrtAddSessionConfigEntry=oe.Da)(n,l,f),d._OrtReleaseSessionOptions=n=>(d._OrtReleaseSessionOptions=oe.Ea)(n),d._OrtCreateSession=(n,l,f)=>(d._OrtCreateSession=oe.Fa)(n,l,f),d._OrtReleaseSession=n=>(d._OrtReleaseSession=oe.Ga)(n),d._OrtGetInputOutputCount=(n,l,f)=>(d._OrtGetInputOutputCount=oe.Ha)(n,l,f),d._OrtGetInputName=(n,l)=>(d._OrtGetInputName=oe.Ia)(n,l),d._OrtGetOutputName=(n,l)=>(d._OrtGetOutputName=oe.Ja)(n,l),d._OrtFree=n=>(d._OrtFree=oe.Ka)(n),d._OrtCreateTensor=(n,l,f,b,C,k)=>(d._OrtCreateTensor=oe.La)(n,l,f,b,C,k),d._OrtGetTensorData=(n,l,f,b,C)=>(d._OrtGetTensorData=oe.Ma)(n,l,f,b,C),d._OrtReleaseTensor=n=>(d._OrtReleaseTensor=oe.Na)(n),d._OrtCreateRunOptions=(n,l,f,b)=>(d._OrtCreateRunOptions=oe.Oa)(n,l,f,b),d._OrtAddRunConfigEntry=(n,l,f)=>(d._OrtAddRunConfigEntry=oe.Pa)(n,l,f),d._OrtReleaseRunOptions=n=>(d._OrtReleaseRunOptions=oe.Qa)(n),d._OrtCreateBinding=n=>(d._OrtCreateBinding=oe.Ra)(n),d._OrtBindInput=(n,l,f)=>(d._OrtBindInput=oe.Sa)(n,l,f),d._OrtBindOutput=(n,l,f,b)=>(d._OrtBindOutput=oe.Ta)(n,l,f,b),d._OrtClearBoundOutputs=n=>(d._OrtClearBoundOutputs=oe.Ua)(n),d._OrtReleaseBinding=n=>(d._OrtReleaseBinding=oe.Va)(n),d._OrtRunWithBinding=(n,l,f,b,C)=>(d._OrtRunWithBinding=oe.Wa)(n,l,f,b,C),d._OrtRun=(n,l,f,b,C,k,V,F)=>(d._OrtRun=oe.Xa)(n,l,f,b,C,k,V,F),d._OrtEndProfiling=n=>(d._OrtEndProfiling=oe.Ya)(n),d._JsepOutput=(n,l,f)=>(d._JsepOutput=oe.Za)(n,l,f),d._JsepGetNodeName=n=>(d._JsepGetNodeName=oe._a)(n);var pn=d._pthread_self=()=>(pn=d._pthread_self=oe.$a)(),mn=d._malloc=n=>(mn=d._malloc=oe.ab)(n),At=d._free=n=>(At=d._free=oe.bb)(n);d.__emscripten_tls_init=()=>(d.__emscripten_tls_init=oe.cb)();var hi=d.__emscripten_thread_init=(n,l,f,b,C,k)=>(hi=d.__emscripten_thread_init=oe.eb)(n,l,f,b,C,k);d.__emscripten_thread_crashed=()=>(d.__emscripten_thread_crashed=oe.fb)();var gi=(n,l,f,b,C)=>(gi=oe.gb)(n,l,f,b,C),ro=n=>(ro=oe.hb)(n),no=d.__emscripten_thread_exit=n=>(no=d.__emscripten_thread_exit=oe.ib)(n),yi=()=>(yi=oe.jb)(),bi=(n,l)=>(bi=oe.kb)(n,l),fn=n=>(fn=oe.lb)(n),oo=n=>(oo=oe.mb)(n),io=()=>(io=oe.nb)(),wi=d.dynCall_ii=(n,l)=>(wi=d.dynCall_ii=oe.pb)(n,l),vi=n=>(vi=oe.qb)(n),$i=()=>($i=oe.rb)(),_i=n=>(_i=oe.sb)(n),Si=()=>(Si=oe.tb)();d.___start_em_js=839500,d.___stop_em_js=839661;function rl(){var n=oe;n=Object.assign({},n);var l=b=>C=>b(C)>>>0,f=b=>()=>b()>>>0;return n.wa=l(n.wa),n.$a=f(n.$a),n.ab=l(n.ab),n.emscripten_main_runtime_thread_id=f(n.emscripten_main_runtime_thread_id),n.mb=l(n.mb),n.nb=f(n.nb),n}d.wasmMemory=ae,d.stackSave=()=>io(),d.stackRestore=n=>fn(n),d.stackAlloc=n=>oo(n),d.keepRuntimeAlive=()=>0Bi)});var Mi=Wr((gm,cl)=>{cl.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(...e){var a=e.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,a+`\\n`);return}console.error(a)}function threadAlert(...e){var a=e.join(" ");postMessage({cmd:"alert",text:a,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,a)=>{var r=Module.wasmModule;Module.wasmModule=null;var t=new WebAssembly.Instance(r,e);return a(t)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let r=[];self.onmessage=t=>r.push(t),self.startWorker=t=>{Module=t,postMessage({cmd:"loaded"});for(let s of r)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const t of e.data.handlers)Module[t]=(...s)=>{postMessage({cmd:"callHandler",handler:t,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var a=URL.createObjectURL(e.data.urlOrBlob);importScripts(a),URL.revokeObjectURL(a)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(r){if(r!="unwind")throw r}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(r){throw Module.__emscripten_thread_crashed?.(),r}}self.onmessage=handleMessage;\\n\'});var go,Gt,tr,bn,Gr,Hi,yo,ye=Y(()=>{"use strict";go=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},Gt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},tr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],bn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Gr=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Hi=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",yo=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}});var wn=Y(()=>{"use strict"});var Fi=Y(()=>{"use strict";wn()});var qi,ji=Y(()=>{"use strict";qi="1.18.0"});var Ki,pt,bo=Y(()=>{"use strict";ji();Ki="warning",pt={wasm:{},webgl:{},webgpu:{},versions:{common:qi},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Ki=e}},get logLevel(){return Ki}};Object.defineProperty(pt,"logLevel",{enumerable:!0})});var vr,Yi=Y(()=>{"use strict";bo();vr=pt});var Zi=Y(()=>{"use strict"});var Xi=Y(()=>{"use strict";vn()});var Ji=Y(()=>{"use strict"});var ea=Y(()=>{"use strict";vn()});var vn=Y(()=>{"use strict";Zi();Xi();Ji();ea()});var $n=Y(()=>{"use strict";vn()});var wo,ta,rr,Ht,vo=Y(()=>{"use strict";bo();wo=(e,t)=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeStamp(`${e}::ORT::${t}`)},ta=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let i=0;i{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||ta("BEGIN",e)},Ht=e=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||ta("END",e)}});var ra=Y(()=>{"use strict";wn();$n();vo()});var na=Y(()=>{"use strict";ra()});var oa=Y(()=>{"use strict"});var ia=Y(()=>{"use strict"});var aa=Y(()=>{"use strict"});var sa=Y(()=>{"use strict"});var ua=Y(()=>{"use strict";wn();$n()});var da=Y(()=>{"use strict";ua()});var $r=Y(()=>{"use strict";Fi();Yi();na();$n();oa();ia();vo();aa();sa();da()});var _l,Sl,la,ca,pa,xl,Ve,Lt=Y(()=>{"use strict";ye();_l=["V","I","W","E","F"],Sl=(e,t)=>{console.log(`[${_l[e]},${new Date().toISOString()}]${t}`)},pa=(e,t)=>{la=e,ca=t},xl=(e,t)=>{let r=Gr(e),o=Gr(la);r>=o&&Sl(r,typeof t=="function"?t():t)},Ve=(...e)=>{ca&&xl(...e)}});var ma,fa=Y(()=>{"use strict";ye();ma=(e,t)=>new(bn(t))(e)});var _n=Y(()=>{"use strict"});var ha,$o,_o,Cl,Al,ga,xo,So,ba,wa=Y(()=>{"use strict";Lt();_n();ha=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]]),$o=[],_o=e=>Math.ceil(e/16)*16,Cl=e=>{for(let t=0;t<$o.length;t++){let r=$o[t];if(e<=r)return r}return Math.ceil(e/16)*16},Al=1,ga=()=>Al++,xo=async(e,t,r,o)=>{let i=_o(r),u=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,u,0,i),e.flush(),await u.mapAsync(GPUMapMode.READ);let c=u.getMappedRange();if(o){let p=o();return p.set(new Uint8Array(c,0,r)),p}else return new Uint8Array(c.slice(0,r))}finally{u.destroy()}},So=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[r]of ha)$o.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[])}upload(t,r){let o=r.buffer,i=r.byteOffset,u=r.byteLength,a=_o(u),c=this.storageCache.get(t);if(!c)throw new Error("gpu data for uploading does not exist");if(c.originalSize!==u)throw new Error(`inconsistent data size. gpu data size=${c.originalSize}, data size=${u}`);let p=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=p.getMappedRange();new Uint8Array(h).set(new Uint8Array(o,i,u)),p.unmap();let d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(p,0,c.gpuData.buffer,0,a),Ve("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(p)}memcpy(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(r);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(o.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=_o(o.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(o.gpuData.buffer,0,i.gpuData.buffer,0,u)}registerExternalBuffer(t,r,o){let i;if(o){if(i=this.externalBuffers.get(o),i===void 0)throw new Error("previous buffer is not registered");if(t===o)return Ve("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`);this.externalBuffers.delete(o)}else i=ga();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,i),Ve("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, registered.`),i}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),Ve("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Cl(t),i,u=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||a){let h=(u?this.freeBuffers:this.freeUniformBuffers).get(o);h?h.length>0?i=h.pop():i=this.backend.device.createBuffer({size:o,usage:r}):i=this.backend.device.createBuffer({size:o,usage:r})}else i=this.backend.device.createBuffer({size:o,usage:r});let c={id:ga(),type:0,buffer:i};return this.storageCache.set(c.id,{gpuData:c,originalSize:t}),Ve("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${c.id}`),c}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=this.storageCache.get(t);if(!r)throw new Error("releasing data does not exist");return Ve("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("data does not exist");await xo(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let r=ha.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let o=this.freeBuffers.get(t.size)||[];r===void 0||o.length>=r?t.destroy():o.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let o=this.freeUniformBuffers.get(t.size)||[];r===void 0||o.length>=r?t.destroy():o.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 r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(o=>{o.destroy()}),this.capturedPendingBuffers.delete(t))}},ba=(...e)=>new So(...e)});var Co,ve,Ze=Y(()=>{"use strict";Co=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}},ve=e=>new Co(e)});var Ao,It,M,nr,Sn,xn,Cn,Se=Y(()=>{"use strict";Ao=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},It=class{static calcShape(t,r,o=!1){let i=t.length,u=r.length;if(i===0)return r;if(u===0)return t;let a=Math.max(t.length,r.length),c=new Array(a);if(o){if(i<2||u<2)return;let p=Ao.calcMatMulShape([t[i-2],t[i-1]],[r[u-2],r[u-1]]);if(p===void 0)return;[c[a-2],c[a-1]]=p}for(let p=o?3:1;p<=a;p++){let h=i-p<0?1:t[i-p],d=u-p<0?1:r[u-p];if(h!==d&&h>1&&d>1)return;let y=Math.max(h,d);if(h&&d)c[a-p]=Math.max(h,d);else{if(y>1)return;c[a-p]=0}}return c}static isValidBroadcast(t,r){let o=t.length,i=r.length;if(o>i)return!1;for(let u=1;u<=o;u++)if(t[o-u]!==1&&t[o-u]!==r[i-u])return!1;return!0}},M=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let o=t.length;if(o===0)return[];let i=new Array(o),u=o-1;for(;u>=0;){if(t[u]%r===0){i[u]=t[u]/r;break}if(r%t[u]!==0)throw new Error("cannot convert shape");i[u]=1,r/=t[u],u--}for(u--;u>=0;u--)i[u]=t[u];return i}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,o){let i=1;for(let u=r;u=0;--i)o[i]=o[i+1]*t[i+1];return o}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(o=>this.normalizeAxis(o,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(o=>t[o]):t.slice().reverse()}static padShape(t,r){let o=t.length;return t.map((i,u)=>i+r[u]+r[u+o])}static areEqual(t,r){return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}},nr=class e{static adjustPoolAttributes(t,r,o,i,u,a){if(!t&&o.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=o.length?o.push(r[c+2]):o[c]=r[c+2];for(let c=0;c=o[c]||a[c+o.length]>=o[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,o,i,u,a,c){if(c){if(u.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{"use strict";ye();Se();or=64,To=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},De=(e,t=1)=>{let r=To(e,t);return typeof r=="string"?r:r[0]},et=(e,t=1)=>{let r=To(e,t);return typeof r=="string"?r:r[1]},Z=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:M.computeStrides(r)})}),t},Me=e=>e%4===0?4:e%2===0?2:1,$t=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,ir=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,_t=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,fe=(e,t,r,o)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?o==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:o==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Eo=(e,t,r,o,i)=>{let u=typeof r=="number",a=u?r:r.length,c=[...new Array(a).keys()],p=a<2?"u32":a<=4?`vec${a}`:`array`,h=To(t,i),d=typeof h=="string"?h:h[1],y=typeof h=="string"?h:h[0],w={indices:p,value:d,storage:y,tensor:t},_=G=>typeof G=="string"?G:`${G}u`,v={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},S=u?"uniforms.":"",A=`${S}${e}_shape`,I=`${S}${e}_strides`,x="";for(let G=0;G ${w.indices} {\n var indices: ${w.indices};\n var current = offset;\n ${x}\n return indices;\n }`,P=G=>(v.offsetToIndices=!0,a<2?G:`o2i_${e}(${G})`),O=[];if(a>=2)for(let G=a-1;G>=0;G--)O.push(`${fe(I,G,a)} * (indices[${G}])`);let R=a<2?"":`\n fn i2o_${e}(indices: ${w.indices}) -> u32 {\n return ${O.join("+")};\n }`,L=G=>(v.indicesToOffset=!0,a<2?G:`i2o_${e}(${G})`),N=(...G)=>a===0?"0u":`${w.indices}(${G.map(_).join(",")})`,K=(G,ne)=>a<2?`${G}`:`${fe(G,ne,a)}`,Q=(G,ne,xe)=>a<2?`${G}=${xe};`:`${fe(G,ne,a)}=${xe};`,he={},W=(G,ne)=>{v.broadcastedIndicesToOffset=!0;let xe=`${ne.name}broadcastedIndicesTo${e}Offset`;if(xe in he)return`${xe}(${G})`;let Ke=[];for(let Be=a-1;Be>=0;Be--){let Ge=ne.indicesGet("outputIndices",Be+ne.rank-a);Ke.push(`${K(I,Be)} * (${Ge} % ${K(A,Be)})`)}return he[xe]=`fn ${xe}(outputIndices: ${ne.type.indices}) -> u32 {\n return ${Ke.length>0?Ke.join("+"):"0u"};\n }`,`${xe}(${G})`},se=(G,ne)=>(()=>{if(w.storage===w.value)return`${e}[${G}]=${ne};`;if(w.storage==="vec2"&&w.value==="i32")return`${e}[${G}]=vec2(u32(${ne}), select(0u, 0xFFFFFFFFu, ${ne} < 0));`;if(w.storage==="vec2"&&w.value==="u32")return`${e}[${G}]=vec2(u32(${ne}), 0u);`;if(w.storage==="u32"&&w.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ne}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),Ce=G=>(()=>{if(w.storage===w.value)return`${e}[${G}]`;if(w.storage==="vec2"&&w.value==="i32")return`i32(${e}[${G}].x)`;if(w.storage==="vec2"&&w.value==="u32")return`u32(${e}[${G}].x)`;if(w.storage==="u32"&&w.value==="vec4")return`vec4(bool(${e}[${G}] & 0xFFu), bool(${e}[${G}] & 0xFF00u), bool(${e}[${G}] & 0xFF0000u), bool(${e}[${G}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),We=a<2?"":`\n fn get_${e}ByIndices(indices: ${w.indices}) -> ${d} {\n return ${Ce(`i2o_${e}(indices)`)};\n }`,ee=a<2?"":(()=>{let G=c.map(xe=>`d${xe}: u32`).join(", "),ne=c.map(xe=>`d${xe}`).join(", ");return`\n fn get_${e}(${G}) -> ${d} {\n return get_${e}ByIndices(${N(ne)});\n }`})(),ae=(...G)=>{if(G.length!==a)throw new Error(`indices length must be ${a}`);let ne=G.map(_).join(",");return a===0?Ce("0u"):a===1?Ce(ne[0]):(v.get=!0,v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}(${ne})`)},Ae=G=>a<2?Ce(G):(v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}ByIndices(${G})`),me=a<2?"":`\n fn set_${e}ByIndices(indices: ${w.indices}, value: ${d}) {\n ${se(`i2o_${e}(indices)`,"value")}\n }`,ie=a<2?"":(()=>{let G=c.map(xe=>`d${xe}: u32`).join(", "),ne=c.map(xe=>`d${xe}`).join(", ");return`\n fn set_${e}(${G}, value: ${d}) {\n set_${e}ByIndices(${N(ne)}, value);\n }`})();return{impl:()=>{let G=[],ne=!1;return v.offsetToIndices&&(G.push(E),ne=!0),v.indicesToOffset&&(G.push(R),ne=!0),v.broadcastedIndicesToOffset&&(Object.values(he).forEach(xe=>G.push(xe)),ne=!0),v.set&&(G.push(ie),ne=!0),v.setByIndices&&(G.push(me),ne=!0),v.get&&(G.push(ee),ne=!0),v.getByIndices&&(G.push(We),ne=!0),!u&&ne&&G.unshift(`const ${A} = ${w.indices}(${r.join(",")});`,`const ${I} = ${w.indices}(${M.computeStrides(r).join(",")});`),G.join(`\n`)},type:w,offsetToIndices:P,indicesToOffset:L,broadcastedIndicesToOffset:W,indices:N,indicesGet:K,indicesSet:Q,set:(...G)=>{if(G.length!==a+1)throw new Error(`indices length must be ${a}`);let ne=G[a];if(typeof ne!="string")throw new Error("value must be string");let xe=G.slice(0,a).map(_).join(",");return a===0?se("0u",ne):a===1?se(xe[0],ne):(v.set=!0,v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}(${xe}, ${ne})`)},setByOffset:se,setByIndices:(G,ne)=>a<2?se(G,ne):(v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${ne});`),get:ae,getByOffset:Ce,getByIndices:Ae,usage:o,name:e,strides:I,shape:A,rank:a}},U=(e,t,r,o=1)=>Eo(e,t,r,"input",o),j=(e,t,r,o=1)=>Eo(e,t,r,"output",o),An=(e,t,r,o=1)=>Eo(e,t,r,"internal",o),Io=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=or){let r=typeof t=="number"?t:t[0],o=typeof t=="number"?1:t[1],i=typeof t=="number"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||o>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${o}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*o*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${o}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let u=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=u?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,c=u?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r*o*i}u + local_idx;`;return`@compute @workgroup_size(${r}, ${o}, ${i})\n fn main(${a}) {\n ${c}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let o=t.usage==="input"?"read":"read_write",i=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${i}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,o=1){return this.uniforms.push({name:t,type:r,length:o}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:o,length:i}of this.uniforms)if(i&&i>4)o==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(i/8)}>`):t.push(`${r}:array, ${Math.ceil(i/4)}>`);else{let u=i==null||i===1?o:`vec${i}<${o}>`;t.push(`${r}:${u}`)}return`\n struct Uniforms { ${t.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},va=(e,t)=>new Io(e,t),_r=(e,t)=>{let r=e.length,o=[];for(let i=0;i1&&a===1&&o.unshift(u)}return o}});var Il,$a,Tl,El,yt,_a,Sa,Sr=Y(()=>{"use strict";ye();Se();Ze();_e();Il=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},$a=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Tl=(e,t)=>M.sortBasedOnPerm(e,$a(e.length,t)),El=(e,t,r,o)=>{let i=[];i.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let u=0;u{let r=e.dataType,o=e.dims.length,i=$a(o,t),u=Tl(e.dims,i),a=j("output",r,u.length),c=U("a",r,o),p=h=>`\n ${h.registerUniform("output_size","u32").declareVariables(c,a)}\n\n ${El(i,o,c,a)}\n\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${a.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${a.setByOffset("global_idx",c.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:h=>{let d=M.size(u);return{outputs:[{dims:u,dataType:h[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},...Z(h[0].dims,u)]}},getShaderSource:p}},_a=(e,t)=>{Il(e.inputs),e.compute(yt(e.inputs[0],t.perm))},Sa=e=>ve({perm:e.perm})});var Pl,kl,Ol,Rl,Bl,Dl,zl,Ml,Ul,Vl,Tt,xa,Ca,Aa,Ia,Ta,Ea,Pa,ka,Oa,Ra,Ba=Y(()=>{"use strict";ye();Se();_e();In();Sr();Pl={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"},kl={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"},Ol={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Rl={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Bl=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let u=0;ue[u]);return[r,i]},zl=(e,t)=>{let r=e.length+t.length,o=[],i=0;for(let u=0;u{for(let r=0;r{let r=[];if(!Ml(e,t)){for(let o=0;or.push(o))}return r},Vl=(e,t,r,o,i,u,a)=>{let c=r[0].dims,p=M.size(u),h=M.size(a),d=U("_A",r[0].dataType,c),y=j("output",i,u),w=32,_=`\n var aBestValues : array;\n `;return{name:e,shaderCache:t,getShaderSource:S=>`\n ${S.registerUniform("reduceSize","u32").declareVariables(d,y)}\n ${_}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${S.mainStart(w)}\n\n let outputIndex = global_idx / ${w};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${Ol[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${w}) {\n let candidate = f32(${d.getByOffset("offset + k")});\n bestValue = ${Pl[o]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${w}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${kl[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${y.setByOffset("outputIndex",`${o==="mean"?`${y.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${y.type.storage}(${Rl[o]})`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:u,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},Tt=(e,t,r,o)=>{let i=e.inputs.length===1?r:Po(e.inputs,r),u=i.axes;u.length===0&&!i.noopWithEmptyAxes&&(u=e.inputs[0].dims.map((_,v)=>v));let a=M.normalizeAxes(u,e.inputs[0].dims.length),c=a,p=e.inputs[0],h=Ul(c,e.inputs[0].dims.length);h.length>0&&(p=e.compute(yt(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],c=Bl(c.length,p.dims.length));let[d,y]=Dl(p.dims,c),w=d;i.keepDims&&(w=zl(d,a)),e.compute(Vl(t,{hint:i.cacheKey,inputDependencies:["type"]},[p],o,e.inputs[0].dataType,w,y),{inputs:[p]})},xa=(e,t)=>{Tt(e,"ReduceMeanShared",t,"mean")},Ca=(e,t)=>{Tt(e,"ReduceL1Shared",t,"l1")},Aa=(e,t)=>{Tt(e,"ReduceL2Shared",t,"l2")},Ia=(e,t)=>{Tt(e,"ReduceLogSumExpShared",t,"logSumExp")},Ta=(e,t)=>{Tt(e,"ReduceMaxShared",t,"max")},Ea=(e,t)=>{Tt(e,"ReduceMinShared",t,"min")},Pa=(e,t)=>{Tt(e,"ReduceProdShared",t,"prod")},ka=(e,t)=>{Tt(e,"ReduceSumShared",t,"sum")},Oa=(e,t)=>{Tt(e,"ReduceSumSquareShared",t,"sumSquare")},Ra=(e,t)=>{Tt(e,"ReduceLogSumShared",t,"logSum")}});var Et,Wl,Tn,Po,Pt,Nl,Gl,Hl,Ll,Fl,ql,jl,Kl,Yl,Zl,kt,Da,za,Ma,Ua,Va,Wa,Na,Ga,Ha,La,In=Y(()=>{"use strict";ye();Se();Ze();_e();Ba();Et=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Wl=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Tn=(e,t,r,o,i,u,a=!1,c=!1)=>{let p=[],h=r[0].dims,d=h.length,y=M.normalizeAxes(i,d),w=!c&&y.length===0;h.forEach((A,I)=>{w||y.indexOf(I)>=0?a&&p.push(1):p.push(A)});let _=p.length,v=M.size(p);return{name:e,shaderCache:t,getShaderSource:A=>{let I=[],x=U("_A",r[0].dataType,d),E=j("output",u,_),P=o(x,E,y),O=P[2];for(let R=0,L=0;R=0?(a&&L++,O=`for(var j${R}: u32 = 0; j${R} < ${h[R]}; j${R}++) {\n ${P[2].includes("last_index")?`let last_index = j${R};`:""}\n ${x.indicesSet("input_indices",R,`j${R}`)}\n ${O}\n }`):(I.push(`${x.indicesSet("input_indices",R,E.indicesGet("output_indices",L))};`),L++);return`\n\n ${A.registerUniform("output_size","u32").declareVariables(x,E)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${x.type.indices};\n let output_indices = ${E.offsetToIndices("global_idx")};\n\n ${I.join(`\n`)}\n ${P[0]} // init ops for reduce max/min\n ${P[1]}\n ${O}\n ${P[3]}\n ${P.length===4?E.setByOffset("global_idx","value"):P.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},...Z(h,p)]})}},Po=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),ve({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Pt=(e,t,r,o)=>{let i=e.inputs,u=i.length===1?r:Po(i,r);e.compute(Tn(t,{hint:u.cacheKey,inputDependencies:["rank"]},[i[0]],u.noopWithEmptyAxes&&u.axes.length===0?Wl:o,u.axes,i[0].dataType,u.keepDims,u.noopWithEmptyAxes),{inputs:[0]})},Nl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceLogSum",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Gl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceL1",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},Hl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceL2",t,(o,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ll=(e,t)=>{Et(e.inputs),Pt(e,"ReduceLogSumExp",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},Fl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMax",t,(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(o.indicesSet("input_indices",c,0));return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = max(value, ${o.getByIndices("input_indices")});`,""]})},ql=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMean",t,(o,i,u)=>{let a=1;for(let c=0;c=0||u.length===0)&&(a*=e.inputs[0].dims[c]);return["var sum = f32(0);","",`sum += f32(${o.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${a});`]})},jl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMin",t,(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = min(value, ${o.getByIndices("input_indices")});`,""]})},Kl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceProd",t,(o,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},Yl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceSum",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},Zl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceSumSquare",t,(o,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += t * t;`,""])},kt=(e,t,r)=>{if(t.length===0)return r;let o=1,i=1;for(let u=0;u1024},Da=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ql(e,t):xa(e,t)},za=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gl(e,t):Ca(e,t)},Ma=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hl(e,t):Aa(e,t)},Ua=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ll(e,t):Ia(e,t)},Va=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fl(e,t):Ta(e,t)},Wa=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jl(e,t):Ea(e,t)},Na=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Kl(e,t):Pa(e,t)},Ga=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yl(e,t):ka(e,t)},Ha=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zl(e,t):Oa(e,t)},La=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Nl(e,t):Ra(e,t)}});var Fa,qa,ja,ko,Ka=Y(()=>{"use strict";ye();Ze();In();Fa=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},qa=(e,t)=>{Fa(e.inputs);let r=(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Tn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ja=(e,t)=>{Fa(e.inputs);let r=(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Tn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ko=e=>ve(e)});var Xl,Ql,Jl,En,Ya,Za,Oo=Y(()=>{"use strict";ye();Se();Ze();_e();Xl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,o=e[r],i=o.dataType,u=o.dims.length;e.forEach((a,c)=>{if(c!==r){if(a.dataType!==i)throw new Error("input tensors should be one type");if(a.dims.length!==u)throw new Error("input tensors should have the same shape");a.dims.forEach((p,h)=>{if(h!==t&&p!==o.dims[h])throw new Error("non concat dimensions must match")})}})},Ql=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,Jl=(e,t)=>{let r=e.length,o=[];for(let i=0;i{let i=M.size(r),u=new Array(e.length),a=new Array(e.length),c=0,p=[],h=[],d=[{type:12,data:i}];for(let S=0;S`uniforms.sizeInConcatAxis${S}`).join(","),v=S=>`\n\n ${(()=>{S.registerUniform("outputSize","u32");for(let A=0;A(${_});\n ${w} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Jl(a,y)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:o}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d}),getShaderSource:v}},Ya=(e,t)=>{let r=e.inputs,o=r[0].dims,i=M.normalizeAxis(t.axis,o.length);Xl(r,i);let u=o.slice();u[i]=r.reduce((c,p)=>c+(p.dims.length>i?p.dims[i]:0),0);let a=r.filter(c=>M.size(c.dims)>0);e.compute(En(a,i,u,r[0].dataType),{inputs:a})},Za=e=>ve({axis:e.axis})});var ec,tc,rc,nc,Pn,oc,Xa,Ro=Y(()=>{"use strict";ye();_n();_e();Oo();ec=(e,t)=>{let r=e[0],o=e[1],i=e[2],u=e[3],a=e[4],c=e[5];if(a&&c)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error(\'Input "input" must have 3 dimensions\');let p=r.dims[0],h=r.dims[1],d=r.dims[2];if(i.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimensions\');if(o.dims.length!==2)throw new Error(\'Input "weights" is expected to have 2 dimensions\');if(o.dims[0]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==o.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let y=i.dims[0]/3,w=y,_=w;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let E of t.qkvHiddenSizes)if(E%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");y=t.qkvHiddenSizes[0],w=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let v=h;if(y!==w)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==y+w+_)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let S=0;if(a){if(w!==_)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(a.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(a.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(a.dims[1]!==p)throw new Error(\'Input "past" second dimension must be batch_size\');if(a.dims[2]!==t.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(a.dims[4]!==w/t.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');t.pastPresentShareBuffer||(S=a.dims[3])}let A=v+S,I=-1,x=0;if(u)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");return{batchSize:p,sequenceLength:h,pastSequenceLength:S,kvSequenceLength:v,totalSequenceLength:A,maxSequenceLength:I,inputHiddenSize:d,hiddenSize:y,vHiddenSize:_,headSize:Math.floor(y/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},tc=(e,t,r,o)=>{let i=Me(o),u=64,a=o/i;a{let _=j("x",t.dataType,t.dims,i),S=[{name:"d_inv",type:et(t.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${w.registerUniforms(S).declareVariables(_)}\n ${w.mainStart([u,1,1])}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = workgroup_id.x * uniforms.d_comp + local_offset;\n\n var thread_max_vector = ${d}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n thread_max_vector = max(${d}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(i){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: ${i}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${u}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${d}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n sum_vector += exp(${d}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(i){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: ${i}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${u}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n x[offset + i] = ${_.type.value}(uniforms.d_inv);\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n var f32input = ${d}(x[offset + i]);\n x[offset + i] = ${_.type.value}(exp(f32input - max_value) / sum);\n }\n }\n }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${h};${i}`},getShaderSource:y,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:p})}},rc=(e,t,r,o,i,u,a)=>{let c=a+i.kvSequenceLength,p=[i.batchSize,i.numHeads,i.sequenceLength,c],h=u.scale===0?1/Math.sqrt(i.headSize):u.scale,d=Me(i.headSize),y=i.headSize/d,w=12,_={x:Math.ceil(c/w),y:Math.ceil(i.sequenceLength/w),z:i.batchSize*i.numHeads},v=[{type:12,data:i.sequenceLength},{type:12,data:y},{type:12,data:c},{type:12,data:i.numHeads},{type:1,data:h}],S=o?["type","type","type"]:["type","type"],A=I=>{let x=U("q",t.dataType,t.dims,d),E=U("key",r.dataType,r.dims,d),P=[x,E];o&&P.push(U("relative_position_bias",o.dataType,o.dims));let O=j("output",t.dataType,p),R=et(1,d),L=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return`\n const TILE_SIZE = ${w}u;\n\n var tileQ: array<${x.type.storage}, ${w*w}>;\n var tileK: array<${x.type.storage}, ${w*w}>;\n ${I.registerUniforms(L).declareVariables(...P,O)}\n ${I.mainStart([w,w,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${R}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${R}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n let headOffset = headIdx * uniforms.M * uniforms.N;\n if (global_id.y < uniforms.M && global_id.x < uniforms.N) {\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(d){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: ${d}`)}})()};\n output[outputIdx] = ${O.type.value} (sum * uniforms.alpha) + ${o?"relative_position_bias[outputIdx]":"0.0"};\n }\n }`};return{name:"AttentionProbs",shaderCache:{hint:`${d}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:p,dataType:t.dataType,gpuDataType:0}],dispatchGroup:_,programUniforms:v}),getShaderSource:A}},nc=(e,t,r,o,i)=>{let u=i+o.kvSequenceLength,a=[o.batchSize,o.sequenceLength,o.vHiddenSize],c=12,p={x:Math.ceil(o.vHeadSize/c),y:Math.ceil(o.sequenceLength/c),z:o.batchSize*o.numHeads},h=[{type:12,data:o.sequenceLength},{type:12,data:u},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType,gpuDataType:0}],dispatchGroup:p,programUniforms:h}),getShaderSource:w=>{let _=U("probs",t.dataType,t.dims),v=U("v",r.dataType,r.dims),S=j("output",t.dataType,a),A=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return`\n const TILE_SIZE = ${c}u;\n var tileQ: array<${_.type.value}, ${c*c}>;\n var tileK: array<${_.type.value}, ${c*c}>;\n ${w.registerUniforms(A).declareVariables(_,v,S)}\n ${w.mainStart([c,c,1])}\n let headIdx = workgroup_id.z;\n let m = global_id.y;\n let n = global_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${_.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads;\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + currentBatchHeadNumber * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`}}},Pn=(e,t,r,o,i,u,a,c,p,h,d)=>{let y=e.outputCount>1,w=e.outputCount>2,_=y&&w?h.pastSequenceLength:0,v=_+h.kvSequenceLength,S=[h.batchSize,h.numHeads,v,h.headSize],A=a?[a,r]:[r],I=y?e.compute(En(A,2,S,r.dataType),{inputs:A,outputs:[1]})[0]:r,x=[h.batchSize,h.numHeads,v,h.headSize],E=c?[c,o]:[o],P=w?e.compute(En(E,2,x,o.dataType),{inputs:E,outputs:[2]})[0]:o,O=[t,I];p&&O.push(p);let R=e.compute(rc(e,t,I,p,h,d,_),{inputs:O,outputs:[-1]})[0];e.compute(tc(e,R,h.batchSize*h.numHeads*h.sequenceLength,v),{inputs:[R],outputs:[]});let L=[R,P];e.compute(nc(e,R,P,h,_),{inputs:L,outputs:[0]})},oc=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],o=t.sequenceLength,i=t.inputHiddenSize,u=t.headSize,a=12,c={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:o},{type:12,data:i},{type:12,data:u},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],d=y=>{let w=j("output_q",p[0].dataType,r),_=j("output_k",p[0].dataType,r),v=j("output_v",p[0].dataType,r),S=U("input",p[0].dataType,p[0].dims),A=U("weight",p[1].dataType,p[1].dims),I=U("bias",p[2].dataType,p[2].dims),x=S.type.storage,E=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`\n const TILE_SIZE = ${a}u;\n var tileInput: array<${x}, ${a*a}>;\n var tileWeightQ: array<${x}, ${a*a}>;\n var tileWeightK: array<${x}, ${a*a}>;\n var tileWeightV: array<${x}, ${a*a}>;\n ${y.registerUniforms(E).declareVariables(S,A,I,w,_,v)}\n ${y.mainStart([a,a,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${x}(0);\n var valueK = ${x}(0);\n var valueV = ${x}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:h}),getShaderSource:d},{inputs:p,outputs:[-1,-1,-1]})},Xa=(e,t)=>{let r=ec(e.inputs,t),[o,i,u]=oc(e,r);return Pn(e,o,i,u,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var ic,ac,sc,Qa,Ja=Y(()=>{"use strict";$r();ye();Se();Ze();_e();ic=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(o,i,u)=>{let a=i.length;if(a!==o.length)throw new Error(`${u}: num dimensions != ${a}`);i.forEach((c,p)=>{if(c!==o[p])throw new Error(`${u}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let o=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,o,"Invalid input scale"),r(e[2].dims,o,"Invalid input B"),r(e[3].dims,o,"Invalid input mean"),r(e[4].dims,o,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},ac=(e,t)=>{let{epsilon:r,spatial:o,format:i}=t,u=e[0].dims,a=o?Me(u[u.length-1]):1,c=i==="NHWC"&&u.length>1?a:1,p=M.size(u)/a,h=o,d=h?u.length:u,y=U("x",e[0].dataType,e[0].dims,a),w=U("scale",e[1].dataType,e[1].dims,c),_=U("bias",e[2].dataType,e[2].dims,c),v=U("inputMean",e[3].dataType,e[3].dims,c),S=U("inputVar",e[4].dataType,e[4].dims,c),A=j("y",e[0].dataType,d,a),I=()=>{let E="";if(o)E=`let cOffset = ${u.length===1?"0u":i==="NHWC"?`outputIndices[${u.length-1}] / ${a}`:"outputIndices[1]"};`;else if(i==="NCHW")E=`\n ${A.indicesSet("outputIndices","0","0")}\n let cOffset = ${A.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${w.type.indices}(0);\n cIndices[0] = outputIndices[${u.length-1}];`;for(let P=1;P`\n const epsilon = ${r};\n ${E.registerUniform("outputSize","u32").declareVariables(y,w,_,v,S,A)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${A.offsetToIndices(`global_idx * ${a}`)};\n ${I()}\n let scale = ${w.getByOffset("cOffset")};\n let bias = ${_.getByOffset("cOffset")};\n let inputMean = ${v.getByOffset("cOffset")};\n let inputVar = ${S.getByOffset("cOffset")};\n let x = ${y.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${A.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${o}_${a}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...Z(u)]:[{type:12,data:p}]})}},sc=e=>ve(e),Qa=(e,t)=>{let{inputs:r,outputCount:o}=e,i=sc({...t,outputCount:o});if(vr.webgpu.validateInputContent&&ic(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ac(r,i))}});var uc,dc,es,ts=Y(()=>{"use strict";Se();_e();uc=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},dc=e=>{let t=e[0].dims,r=e[0].dims[2],o=M.size(t)/4,i=e[0].dataType,u=U("input",i,t,4),a=U("bias",i,[r],4),c=U("residual",i,t,4),p=j("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:d=>`\n const channels = ${r}u / 4;\n ${d.declareVariables(u,a,c,p)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes(o)}\n let value = ${u.getByOffset("global_idx")}\n + ${a.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")};\n ${p.setByOffset("global_idx","value")}\n }`}},es=e=>{uc(e.inputs),e.compute(dc(e.inputs))}});var lc,ke,rs,ns,os,is,as,ss,us,ds,ls,cc,cs,ps,ms,fs,kn,hs,On,gs,ys,bs,ws,vs,$s,_s,Ss,xs,Cs,As,Is,Ts,Es,Ps,ks,Os,Rs,Bo,Do,Bs,Ds,zs,Rn=Y(()=>{"use strict";ye();Se();Ze();_e();lc=(e,t,r,o,i,u)=>{let a=Math.ceil(t/4),c="";typeof i=="string"?c=`${i}(a)`:c=i("a");let p=U("inputData",r,[a],4),h=j("outputData",o,[a],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(p,h)}\n\n ${u??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${p.getByOffset("global_idx")};\n ${h.setByOffset("global_idx",c)}\n }`},ke=(e,t,r,o,i,u=e.dataType)=>({name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:a=>lc(a,M.size(e.dims),e.dataType,u,r,o),getRunData:a=>({outputs:[{dims:e.dims,dataType:u}],dispatchGroup:{x:Math.ceil(M.size(a[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(M.size(e.dims)/4)}]})}),rs=e=>{e.compute(ke(e.inputs[0],"Abs","abs"))},ns=e=>{e.compute(ke(e.inputs[0],"Acos","acos"))},os=e=>{e.compute(ke(e.inputs[0],"Acosh","acosh"))},is=e=>{e.compute(ke(e.inputs[0],"Asin","asin"))},as=e=>{e.compute(ke(e.inputs[0],"Asinh","asinh"))},ss=e=>{e.compute(ke(e.inputs[0],"Atan","atan"))},us=e=>{e.compute(ke(e.inputs[0],"Atanh","atanh"))},ds=e=>ve(e),ls=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute \'to\' from \'Cast\' operator): ${t.to}`)}e.compute(ke(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},cc=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:xn,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:Cn;return ve({min:t,max:r})},cs=(e,t)=>{let r=e.inputs.length===1?t:cc(e.inputs),o=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Clip",i=>`clamp(${i}, clip_min_, clip_max_)`,`\n const clip_min_: vec4<${o}> = vec4(${o}(${r.min}));\n const clip_max_: vec4<${o}> = vec4(${o}(${r.max}));\n`,r.cacheKey),{inputs:[0]})},ps=e=>{e.compute(ke(e.inputs[0],"Ceil","ceil"))},ms=e=>{e.compute(ke(e.inputs[0],"Cos","cos"))},fs=e=>{e.compute(ke(e.inputs[0],"Cosh","cosh"))},kn=e=>ve(e),hs=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Elu",o=>`elu_vf32(${o})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},On=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,gs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,On(t)))},ys=e=>{e.compute(ke(e.inputs[0],"Exp","exp"))},bs=e=>{e.compute(ke(e.inputs[0],"Floor","floor"))},ws=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,On(t)))},vs=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"LeakyRelu",o=>`select(leaky_relu_alpha_ * ${o}, ${o}, ${o} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},$s=e=>{e.compute(ke(e.inputs[0],"Not",t=>`!${t}`))},_s=e=>{e.compute(ke(e.inputs[0],"Neg",t=>`-${t}`))},Ss=e=>{e.compute(ke(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},xs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Cs=e=>{e.compute(ke(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},As=e=>ve(e),Is=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"HardSigmoid",o=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${o} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Ts=e=>{e.compute(ke(e.inputs[0],"Sin","sin"))},Es=e=>{e.compute(ke(e.inputs[0],"Sinh","sinh"))},Ps=e=>{e.compute(ke(e.inputs[0],"Sqrt","sqrt"))},ks=e=>{e.compute(ke(e.inputs[0],"Tan","tan"))},Os=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Rs=e=>{e.compute(ke(e.inputs[0],"Tanh",Os))},Bo=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Os("v")};\n}\n`,Do=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Bs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"FastGelu",Do,Bo(t),void 0,e.inputs[0].dataType))},Ds=(e,t)=>{let r=et(e.inputs[0].dataType);return e.compute(ke(e.inputs[0],"ThresholdedRelu",o=>`select(vec4<${r}>(0.0), ${o}, ${o} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},zs=e=>{e.compute(ke(e.inputs[0],"Log","log"))}});var pc,mc,Us,Vs=Y(()=>{"use strict";Se();_e();Rn();pc=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},mc=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=U("input",e[0].dataType,e[0].dims,4),o=U("bias",e[0].dataType,[e[0].dims[2]],4),i=j("output",e[0].dataType,t,4),u=M.size(t)/4,a=De(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:p=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${p.declareVariables(r,o,i)}\n\n ${On(a)}\n\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes(u)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${i.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},Us=e=>{pc(e.inputs),e.compute(mc(e.inputs))}});var fc,hc,Ot,Ws,Ns,Gs,Hs,Ls,Fs,qs,js,Ks,Ys,Zs=Y(()=>{"use strict";ye();Se();_e();fc=(e,t,r,o,i,u,a,c,p,h,d,y)=>{let w,_;typeof c=="string"?w=_=(x,E)=>`${c}((${x}),(${E}))`:typeof c=="function"?w=_=c:(w=c.scalar,_=c.vector);let v=j("outputData",d,o.length,4),S=U("aData",p,t.length,4),A=U("bData",h,r.length,4),I;if(i)if(u){let x=M.size(t)===1,E=M.size(r)===1,P=t.length>0&&t[t.length-1]%4===0,O=r.length>0&&r[r.length-1]%4===0;x||E?I=v.setByOffset("global_idx",_(x?`${S.type.value}(${S.getByOffset("0")}.x)`:S.getByOffset("global_idx"),E?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):I=`\n let outputIndices = ${v.offsetToIndices("global_idx * 4u")};\n let offsetA = ${S.broadcastedIndicesToOffset("outputIndices",v)};\n let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",v)};\n ${v.setByOffset("global_idx",_(a||P?S.getByOffset("offsetA / 4u"):`${S.type.value}(${S.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||O?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else I=v.setByOffset("global_idx",_(S.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!u)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let x=(E,P,O="")=>{let R=`aData[indexA${P}][componentA${P}]`,L=`bData[indexB${P}][componentB${P}]`;return`\n let outputIndices${P} = ${v.offsetToIndices(`global_idx * 4u + ${P}u`)};\n let offsetA${P} = ${S.broadcastedIndicesToOffset(`outputIndices${P}`,v)};\n let offsetB${P} = ${A.broadcastedIndicesToOffset(`outputIndices${P}`,v)};\n let indexA${P} = offsetA${P} / 4u;\n let indexB${P} = offsetB${P} / 4u;\n let componentA${P} = offsetA${P} % 4u;\n let componentB${P} = offsetB${P} % 4u;\n ${E}[${P}] = ${O}(${w(R,L)});\n `};d===9?I=`\n var data = vec4(0);\n ${x("data",0,"u32")}\n ${x("data",1,"u32")}\n ${x("data",2,"u32")}\n ${x("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:I=`\n ${x("outputData[global_idx]",0)}\n ${x("outputData[global_idx]",1)}\n ${x("outputData[global_idx]",2)}\n ${x("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(S,A,v)}\n\n ${y??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${I}\n }`},hc=(e,t,r,o,i,u,a=r.dataType)=>{let c=!M.areEqual(r.dims,o.dims),p=r.dims,h=M.size(r.dims),d=!1,y=!1,w=[c];if(c){let _=It.calcShape(r.dims,o.dims,!1);if(!_)throw new Error("Can\'t perform binary op on the given tensors");p=_,h=M.size(p);let v=M.size(r.dims)===1,S=M.size(o.dims)===1,A=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,I=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;w.push(v),w.push(S),w.push(A),w.push(I);let x=1;for(let E=1;E_.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:_=>fc(_,r.dims,o.dims,p,d,c,y,i,r.dataType,o.dataType,a,u),getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(M.size(p)/4)},...Z(r.dims,o.dims,p)]})}},Ot=(e,t,r,o,i,u)=>{e.compute(hc(t,i??"",e.inputs[0],e.inputs[1],r,o,u))},Ws=e=>{Ot(e,"Add",(t,r)=>`${t}+${r}`)},Ns=e=>{Ot(e,"Div",(t,r)=>`${t}/${r}`)},Gs=e=>{Ot(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Hs=e=>{Ot(e,"Mul",(t,r)=>`${t}*${r}`)},Ls=e=>{let t=U("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ot(e,"Pow",{scalar:(o,i)=>`pow_custom(${o},${i})`,vector:(o,i)=>`pow_vector_custom(${o},${i})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Fs=e=>{Ot(e,"Sub",(t,r)=>`${t}-${r}`)},qs=e=>{Ot(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},js=e=>{Ot(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Ks=e=>{Ot(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Ys=e=>{Ot(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var St,xt,Ct,Bn,Ft=Y(()=>{"use strict";ye();Se();St=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},xt=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},Ct=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},Bn=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,o]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:o}}else if(t==="Clip"){let[r,o]=e?.activation_params||[xn,Cn];return{activation:t,clipMax:o,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var tt,Dn,zn=Y(()=>{"use strict";tt=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Dn=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var Mn,zo=Y(()=>{"use strict";Mn=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var yc,bc,Hr,Xs,wc,Lr,vc,Un,Fr=Y(()=>{"use strict";ye();Se();_e();Ft();zn();yc=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,bc=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,Hr=(e,t,r="f32",o,i=!1,u=32,a=!1,c=32)=>{let p=t[1]*e[1],h=t[0]*e[0],d=i?p:u,y=i?u:p,w=d/t[0],_=u/t[1];if(!((i&&w===4&&e[1]===4||!i&&(w===3||w===4))&&d%t[0]===0&&u%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${w} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${w} must be 3 or 4.\n tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}. tileInner ${u} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${d/w}>, ${y}>;\nvar mm_Bsub: array, ${h/e[0]}>, ${u}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${w};\nconst tileInner = ${u};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${a?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${p};\n\n let num_tiles = ${a?`${Math.ceil(c/u)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${c}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${_};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${yc(i,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${o?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${w===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${bc(i,w)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Xs=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,wc=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Lr=(e,t,r="f32",o,i=!1,u=32,a=!1,c=32,p=!1)=>{let h=e[1]*t[1],d=e[0]*t[0],y=i?h:u,w=i?u:h;if(!(w%t[1]===0&&y%t[0]===0&&u%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${y} must be divisible by workgroupSize[0]${t[0]}, tileInner ${u} must be divisible by workgroupSize[1]${t[1]}`);let _=w/t[1],v=y/t[0],S=u/t[1],A=p?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${h};\n let globalColStart = i32(workgroupId.x) * ${d};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${w}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${y}; inputCol = inputCol + ${t[0]}) {\n ${Xs(i,o)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${h};\n\nlet tileRowA = i32(localId.y) * ${_};\nlet tileColA = i32(localId.x) * ${v};\nlet tileRowB = i32(localId.y) * ${S};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${v}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Xs(i,o)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${S}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${wc(i)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${w}>;\n var mm_Bsub : array, ${u}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${u};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${a?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${a?`${Math.ceil(c/u)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${c}`:"0"};\n\n var acc : array, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${A}\n }\n`},vc=(e,t,r,o,i,u=!1)=>{let[a,c,p]=i,[h,d,y,w]=o,_=_r(a,p),v=_r(c,p),S=De(o[0].type.tensor),A=()=>{let E=d.rank,P=h.rank,O=`var aIndices: ${d.type.indices};`;for(let R=E-2-1,L=P-1;R>=0;R--,L--)O+=`\naIndices[${R}] = ${P>1?`batchIndices[${L}]`:"batchIndices"};`;return _.forEach(R=>{O+=`\naIndices[${R}] = 0;`}),O+=`\naIndices[${E-2}] = u32(row);\n aIndices[${E-1}] = u32(colIn);`,O},I=()=>{let E=y.rank,P=h.rank,O=`var bIndices: ${y.type.indices};`;for(let R=E-2-1,L=P-1;R>=0;R--,L--)O+=`\nbIndices[${R}] = ${P>1?`batchIndices[${L}]`:"batchIndices"};`;return v.forEach(R=>{O+=`\nbIndices[${R}] = 0;`}),O+=`\nbIndices[${E-2}] = u32(row);\n bIndices[${E-1}] = u32(colIn);`,O};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${tt(e,S)} {\n var value = ${tt(e,S)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n ${A()}\n value = ${d.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${tt(e,S)} {\n var value = ${tt(e,S)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n ${I()}\n value = ${y.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${tt(e,S)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${u?"bias[colIn]":`${tt(e,S)}(bias[row])`};`:""}\n ${r}\n ${w.setByIndices("vec3(coords)","value")}\n }\n }\n `},Un=(e,t,r,o,i=!1)=>{let u=e[0].dims,a=e[1].dims,c=u.slice(0,-2),p=a.slice(0,-2),h=o?o.slice(0,-2):r.slice(0,-2),d=M.size(h),y=u[u.length-2],w=u[u.length-1],_=a[a.length-1],v=w%4===0&&_%4===0,S=y<=8?[4,1,1]:[4,4,1],A=[8,8,1],I=[Math.ceil(_/A[0]/S[0]),Math.ceil(y/A[1]/S[1]),Math.ceil(d/A[2]/S[2])],x=v?4:1,E=[...c,y,w/x],P=E.length,O=[...p,w,_/x],R=O.length,L=[d,y,_/x],N=[{type:6,data:y},{type:6,data:_},{type:6,data:w}];xt(t,N),N.push(...Z(h,E,O));let K=["rank","rank"],Q=e.length>2;Q&&(N.push(...Z(e[2].dims)),K.push("rank")),N.push(...Z(L));let he=W=>{let se=h.length,Ce=An("batchDims",e[0].dataType,se,1),We=De(e[0].dataType),ee=U("a",e[0].dataType,P,x),ae=U("b",e[1].dataType,R,x),Ae=j("result",e[0].dataType,L.length,x),me=[ee,ae];if(Q){let G=i?x:1;me.push(U("bias",e[2].dataType,e[2].dims.length,G))}let ie=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ct(t,ie);let ue=De(Ae.type.tensor),le=St(t,Ae.type.value,ue),qe=vc(x,Q,le,[Ce,ee,ae,Ae],[c,p,h],i);return`\n ${W.registerUniforms(ie).registerInternalVariables(Ce).declareVariables(...me,Ae)}\n ${qe}\n ${v?Hr(S,A,We,Ce):Lr(S,A,We,Ce)}\n `};return{name:"MatMul",shaderCache:{hint:`${S};${t.activation};${v};${i}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:I[0],y:I[1],z:I[2]},programUniforms:N}),getShaderSource:he}}});var $c,Qs,Js=Y(()=>{"use strict";ye();Lt();_e();Ft();zn();zo();Fr();$c=(e,t,r,o,i=!1,u,a=4,c=4,p=4,h="f32")=>{let d=Q=>{switch(Q){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Q} is not supported.`)}},y=Q=>{switch(Q){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 ${Q} is not supported.`)}},w=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,_=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,v=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",S=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",I=e?"col":"row",x=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${A} / outWidth;\n let outCol = ${A} % outWidth;\n\n let WRow = ${I} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${I} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${I} % inChannels;\n var resData = ${tt(a,h)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the \'same\' padding type.\n if (xRow >= 0 && xRow < ${v} && xCol >= 0 && xCol < ${S}) {\n ${w}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${d(a)}\n }\n return resData;`,E=e?t&&o?`\n let col = colIn * ${a};\n ${x}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${x}\n }\n return ${tt(a,h)}(0.0);`:o&&r?`\n let col = colIn * ${a};\n ${x}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${x}\n }\n return ${tt(a,h)}(0.0);`,P=`${y(c)}`,O=tt(p,h),R=e?tt(a,h):tt(c,h),L=e?tt(c,h):tt(a,h),N=St(u,O,h);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${R} {\n ${e?E:P}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${L} {\n ${e?P:E}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${O}) {\n let col = colIn * ${p};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${_}\n ${Dn(i)}\n ${N}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Qs=(e,t,r,o,i,u,a,c)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],d=r[0],y=p?r[2]:r[3],w=p?r[1]:r[2],_=p?r[3]:r[1],v=p&&(h%4===0||h%3===0)&&_%4===0,S=p?_:y*w,A=p?y*w:_,I=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(S/I[0]/x[0]),Math.ceil(A/I[1]/x[1]),Math.ceil(d/I[2]/x[2])];Ve("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let P=v?p&&h%4!==0?3:4:1,O=I[1]*x[1],R=I[0]*x[0],L=Math.max(I[0]*P,I[1]),N=o%O===0,K=i%R===0,Q=u%L===0,he=v?[P,4,4]:[1,1,1],W=[{type:6,data:o},{type:6,data:i},{type:6,data:u},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];xt(t,W),W.push(...Z(e[0].dims,e[1].dims));let se=["rank","rank"];a&&(W.push(...Z(e[2].dims)),se.push("rank")),W.push(...Z(r));let Ce=We=>{let ee=[{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}];Ct(t,ee);let ae=v?4:1,Ae=De(e[0].dataType),me=`\n fn setOutputAtIndex(flatIndex : i32, value : ${v?`vec4<${Ae}>`:Ae}) {\n result[flatIndex] = ${v?`vec4<${Ae}>`:Ae}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${v?`vec4<${Ae}>`:Ae}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${v?"/ 4":""}, value);\n }`,ie=U("x",e[0].dataType,e[0].dims.length,P===3?1:P),ue=U("w",e[1].dataType,e[1].dims.length,ae),le=[ie,ue],qe=j("result",e[0].dataType,r.length,ae);if(a){let G=U("bias",e[2].dataType,e[2].dims.length,ae);le.push(G),me+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${v?`vec4<${Ae}>`:Ae} {\n return bias[coords.${p?"w":"y"}${v?"/ 4":""}];\n }`}return`\n ${Mn("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${We.registerUniforms(ee).declareVariables(...le,qe)}\n ${me}\n ${$c(p,N,K,Q,a,t,he[0],he[1],he[2],Ae)}\n ${v?Hr(x,I,Ae,void 0,!p,L):Lr(x,I,Ae,void 0,!p,L,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${P};${v};${N};${K};${Q};${O};${R};${L}`,inputDependencies:se},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:W}),getShaderSource:Ce}}});var Mo,eu,tu=Y(()=>{"use strict";ye();Se();_e();Uo();Ft();Mo=(e,t,r)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",u=e[0].dims,a=e[1].dims,c=a[0]/t.group,p=t.format==="NHWC",h=Vn(u,a,t.dilations,t.pads,t.strides,p),d=M.size(h),y=[{type:12,data:d},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:c}];xt(t,y),y.push(...Z(u,a));let w=["rank","rank"];o&&(y.push(...Z(e[2].dims)),w.push("rank")),y.push(...Z(h));let _=v=>{let S=j("output",e[0].dataType,h.length),A=De(S.type.tensor),I=St(t,S.type.value,A),x=U("x",e[0].dataType,u.length),E=U("w",e[1].dataType,a.length),P=[x,E];o&&P.push(U("b",e[2].dataType,e[2].dims.length));let O=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Ct(t,O),`\n ${v.registerUniforms(O).declareVariables(...P,S)}\n\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${S.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${p?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel / uniforms.output_channels_per_group;\n\n var value: ${S.type.value} = ${S.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = group_id * uniforms.w_shape[1] + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[${p?1:2}]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[${p?2:3}]) {\n continue;\n }\n\n let xVal = ${p?x.get("batch","xHeight","xWidth","input_channel"):x.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${E.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${i}\n ${I}\n ${S.setByOffset("global_idx","value")}\n }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:w},getRunData:()=>({outputs:[{dims:r?r(h):h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:y}),getShaderSource:_}},eu=(e,t,r)=>{let o=e.length>2,i=Me(r[3]),u=Me(r[2]),a=M.size(r)/i/u,c=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],h=[r[0],r[1],r[2],r[3]/i],d=[{type:12,data:a},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];xt(t,d),d.push(...Z(c,p,h));let y=(u-1)*t.strides[1]+p[1],w=_=>{let v=j("output",e[0].dataType,h.length,i),S=De(v.type.tensor),A=St(t,v.type.value,S),I=U("x",e[0].dataType,c.length,i),x=U("w",e[1].dataType,p.length,i),E=[I,x];o&&E.push(U("b",e[2].dataType,e[2].dims,i));let P=o?"value += b[output_channel];":"",O=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ct(t,O),`\n ${_.registerUniforms(O).declareVariables(...E,v)}\n ${_.mainStart()}\n ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${u}u;\n let col = (index1 % width1) * ${u}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${I.type.value}, ${y}>;\n var values: array<${v.type.value}, ${u}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w\'s height/width.\n for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${y}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${I.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${I.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) {\n let w_val = ${x.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${u}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${u}u; i++) {\n var value = values[i];\n ${P}\n ${A}\n ${v.set("batch","row","col + i","output_channel","value")};\n }\n }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${u};${y};${p[0]};${p[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:w}}});var Vo,_c,ru,Wo=Y(()=>{"use strict";ye();Se();Fr();_e();Ft();Vo=(e,t,r,o,i=!1)=>{let u=e[0].dims,a=e[1].dims,c=u[u.length-2],p=a[a.length-1],h=u[u.length-1],d=Me(p),y=Me(h),w=Me(c),_=M.size(r)/d/w,v=e.length>2,S=o?o.slice(0,-2):r.slice(0,-2),I=[M.size(S),c,p],x=[{type:12,data:_},{type:12,data:c},{type:12,data:p},{type:12,data:h}];xt(t,x),x.push(...Z(S,u,a)),v&&x.push(...Z(e[2].dims)),x.push(...Z(I));let E=P=>{let O=An("batch_dims",e[0].dataType,S.length),R=U("a",e[0].dataType,u.length,y),L=U("b",e[1].dataType,a.length,d),N=j("output",e[0].dataType,I.length,d),K=De(N.type.tensor),Q=St(t,N.type.value,K),he=[R,L],W="";if(v){let ie=i?d:1;he.push(U("bias",e[2].dataType,e[2].dims.length,ie)),W=`${i?`value += bias[col / ${ie}];`:`value += ${N.type.value}(bias[row + i]);`}`}let se=u.slice(0,-2),Ce=a.slice(0,-2),We=_r(se,S),ee=_r(Ce,S),ae=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ct(t,ae);let Ae=(ie,ue)=>{let le=ie.rank,qe=ie.name;if(le===2)return`var ${qe}_indices = ${ie.type.indices}(0u, 0u);`;let G=O.rank,ne=`var ${qe}_indices: ${ie.type.indices};`;for(let xe=le-2-1,Ke=G-1;xe>=0;xe--,Ke--)ne+=`\n${qe}_indices[${xe}] = ${G>1?`batch_indices[${Ke}]`:"batch_indices"};`;return ue.forEach(xe=>{ne+=`\n${qe}_indices[${xe}] = 0;`}),ne+=`${qe}_indices[${le-2}] = 0u;\n ${qe}_indices[${le-1}] = 0u;`,ne},me=()=>{let ie=`var a_data: ${R.type.value};`;for(let ue=0;ue;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) {\n ${me()}\n }\n for (var i = 0u; i < ${w}u; i++) {\n var value = values[i];\n ${W}\n ${Q}\n let cur_indices = ${N.type.indices}(batch, row + i, col);\n let offset = ${N.indicesToOffset("cur_indices")};\n ${N.setByOffset(`offset / ${d}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${d};${y};${w};${i}`,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:x}),getShaderSource:E}},_c=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},ru=e=>{_c(e.inputs);let t=It.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can\'t use matmul on the given tensors");let r=t[t.length-1],o=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&o<8?e.compute(Vo(e.inputs,{activation:""},t)):e.compute(Un(e.inputs,{activation:""},t))}});var Vn,No,Sc,nu,Go,xc,Cc,Ho,Uo=Y(()=>{"use strict";Se();Js();Fr();tu();Ft();Wo();Sr();Vn=(e,t,r,o,i,u)=>{let a=e[0],c=e.slice(u?1:2,u?3:4),p=c.length,h=t[0],y=t.slice(2).map((v,S)=>v+(v-1)*(r[S]-1)),_=c.map((v,S)=>v+o[S]+o[S+p]).map((v,S)=>Math.floor((v-y[S]+i[S])/i[S]));return _.splice(0,0,a),_.splice(u?3:1,0,h),_},No=[2,3,1,0],Sc=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[1]*t.group;if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},nu=(e,t)=>{let r=e.kernelShape.slice();for(let u=2;u{let t=Bn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,u=e.group,a=e.kernel_shape,c=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:o,format:r,dilations:i,group:u,kernelShape:a,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},xc=(e,t,r)=>{let o=nu(r,t),i=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let L=Vn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,i),N=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=N);let K=[t[0],N];t.length===3&&K.push(t[2]),e.compute(eu(K,o,L),{inputs:K})}else e.compute(Mo(t,o));return}let u=t.length===3,a=t[0].dims[i?1:2],c=t[0].dims[i?2:3],p=t[0].dims[i?3:1],h=t[1].dims[2],d=t[1].dims[3],y=Vn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,i),w=y[i?1:2],_=y[i?2:3],v=y[i?3:1],S=i&&h===a&&d===c&&r.pads[0]===0&&r.pads[1]===0;if(S||h===1&&d===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let R=y[0],L,N,K,Q=[];if(i){let se=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=se),S){let Ce=a*c*p;L=t[0].reshape([1,R,Ce]),N=se.reshape([1,Ce,v]),K=[1,R,v]}else L=t[0].reshape([R,a*c,p]),N=se.reshape([1,p,v]),K=[R,w*_,v];Q.push(L),Q.push(N)}else L=t[0].reshape([R,p,a*c]),N=t[1].reshape([1,v,p]),K=[R,v,w*_],Q.push(N),Q.push(L);u&&Q.push(t[2]);let he=K[2],W=Q[0].dims[Q[0].dims.length-1];he<8&&W<8?e.compute(Vo(Q,o,y,K,i),{inputs:Q}):e.compute(Un(Q,o,y,K,i),{inputs:Q});return}let A=!0,I=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let x=[t[0],I];u&&x.push(t[2]);let E=i?w*_:v,P=i?v:w*_,O=h*d*p;e.compute(Qs(x,o,y,E,P,O,u,A),{inputs:x})},Cc=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&o.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],u=[1].concat(t.strides),a=[1].concat(t.dilations),c=[1].concat(t.kernelShape),p=nu({...t,pads:i,strides:u,dilations:a,kernelShape:c},o);e.compute(Mo(o,p,h=>r?[h[0],h[2],h[3]]:[]))},Ho=(e,t)=>{Sc(e.inputs,t),e.inputs[0].dims.length===3?Cc(e,t):xc(e,e.inputs,t)}});var Ac,ou,iu=Y(()=>{"use strict";ye();Lt();_e();Ft();zn();zo();Fr();Ac=(e,t=!1,r,o,i=4)=>{let u=I=>{switch(I){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${o}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${I} is not supported.`)}},a=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,c=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",d=e?"row":"col",y=e?"col":"row",w=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${d} / outWidth;\n let outCol = ${d} % outWidth;\n\n let WRow = ${y} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${y} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${p}) || fract(xR) > 0.0) {\n return ${o}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${h}) || fract(xC) > 0.0) {\n return ${o}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${y} % inChannels;\n ${a}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,_=e?`\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${w}\n }\n return ${o}(0.0);`:`\n let col = colIn * ${i};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${w}\n }\n return ${o}(0.0);`,v=`\n let col = colIn * ${i};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${u(i)}\n }\n return ${o}(0.0);\n `,S=St(r,o);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?_:v}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?v:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${o}) {\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${c}\n ${Dn(t)}\n ${S}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value;\n }\n }`},ou=(e,t,r,o,i,u,a,c)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],d=r[0],y=p?r[2]:r[3],w=p?r[1]:r[2],_=p?r[3]:r[1],v=p&&h%4===0&&h%3&&_%4===0,S=p?_:y*w,A=p?y*w:_,I=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(S/I[0]/x[0]),Math.ceil(A/I[1]/x[1]),Math.ceil(d/I[2]/x[2])];Ve("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let P=v?4:1,O=Math.max(I[0]*P,I[1]),R=v?4:1,L=[t.kernelShape[p?1:2],t.kernelShape[p?2:3]],N=[L[0]+(t.dilations[0]<=1?0:(L[0]-1)*(t.dilations[0]-1)),L[1]+(t.dilations[1]<=1?0:(L[1]-1)*(t.dilations[1]-1))],K=[N[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),N[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Q=[{type:6,data:o},{type:6,data:i},{type:6,data:u},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:L},{type:6,data:K}];xt(t,Q),Q.push(...Z(e[0].dims,e[1].dims));let he=["rank","rank"];a&&(Q.push(...Z(e[2].dims)),he.push("rank")),Q.push(...Z(r));let W=se=>{let Ce=U("x",e[0].dataType,e[0].dims.length,R),We=U("w",e[1].dataType,e[1].dims.length,1),ee=j("result",e[0].dataType,r.length,R),ae=[Ce,We],Ae="";if(a){let ue=U("bias",e[2].dataType,e[2].dims.length,R);ae.push(ue),Ae+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${ue.type.value} {\n return bias[coords.${p?"w":"y"}${v?"/ 4":""}];\n }`}let me=[{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:L.length},{name:"pads",type:"i32",length:K.length}];Ct(t,me);let ie=De(e[0].dataType,1);if(ie!=="f16"&&ie!=="f32")throw new Error(`elemType ${ie} is not supported.`);return`\n ${Mn("uniforms.result_strides")}\n ${se.registerUniforms(me).declareVariables(...ae,ee)};\n ${Ae}\n ${Ac(p,a,t,Ce.type.value,P)}\n ${v?Hr(x,I,ie,void 0,!p,O):Lr(x,I,ie,void 0,!p,O,!1,void 0,c)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${x};${I};${v}`,inputDependencies:he},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:Q}),getShaderSource:W}}});var Ic,Lo,au=Y(()=>{"use strict";ye();Lt();Se();_e();Ic=(e,t,r,o,i,u=!1,a,c,p=!1)=>{let h=p?1:2,d=p?2:3,y=p?3:1,w=u?2:1,_=`\n fn setOutputAtIndex(flatIndex : u32, value : ${u?`vec4<${a}>`:a}) {\n result[flatIndex] = ${u?`vec4<${a}>`:a}(value);\n }`;o&&(_+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${u?`vec4<${a}>`:a} {\n return bias[coords.${p?"w":"y"}${u?"/ 4":""}];\n }`);let v=u?4:1,S=U("W",t[1].dataType,t[1].dims.length,v),A=U("Dy",t[0].dataType,t[0].dims.length,v),I=[A,S];o&&I.push(U("bias",t[2].dataType,[r[y]].length,v));let x=j("result",t[0].dataType,r.length,v),E=`{\n let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${i?"global_id.y":"workgroup_id.y"} * ${w};\n let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${w}>;\n for (var i = 0; i < ${w}; i++) {\n dotProd[i] = vec4<${a}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${A.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${y}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${w}; i = i + 1) {\n let value = dotProd[i] + ${o?"bias[c+i]":`vec4<${a}>(0.0)`};\n ${x.set("batch","r","c + i","d1","value")};\n }\n }`,P=`\n let outputIndices = ${x.offsetToIndices("global_idx")};\n let batch = ${x.indicesGet("outputIndices",0)};\n let d1 = ${x.indicesGet("outputIndices",y)};\n let r = ${x.indicesGet("outputIndices",h)};\n let c = ${x.indicesGet("outputIndices",d)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${a}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${h}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${d}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${p?A.get("batch","idyR","idyC","inputChannel"):A.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${S.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${o?"bias[d1]":`${a}(0.0)`};\n ${x.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(c).declareVariables(...I,x)}\n ${_}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${u?E:P}}`},Lo=(e,t,r)=>{let o=e.length>2,i=t.outputShape,u=M.size(i),a=[Math.ceil(u/64),1,1];Ve("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let c=t.format==="NHWC",p=["rank","rank"],h=[t.strides[0],t.strides[1]],d=[t.kernelShape[c?1:2],t.kernelShape[c?2:3]],y=[t.dilations[0],t.dilations[1]],w=[d[0]+(t.dilations[0]<=1?0:(t.kernelShape[c?1:2]-1)*(t.dilations[0]-1)),d[1]+(t.dilations[1]<=1?0:(t.kernelShape[c?2:3]-1)*(t.dilations[1]-1))],_=[w[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),w[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],v=!1,S=t.group,A=e[1].dims,I=A[0]/S,x=A[1],E=[{type:12,data:u},{type:12,data:h},{type:12,data:d},{type:12,data:y},{type:12,data:w},{type:6,data:_},{type:12,data:I},{type:12,data:x},...Z(e[0].dims,e[1].dims)];o&&(E.push(...Z(e[2].dims)),p.push("rank")),E.push(...Z(i));let P=a[1]===1&&a[2]===1,O=R=>{let L=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:h.length},{name:"filter_dims",type:"u32",length:d.length},{name:"dilations",type:"u32",length:d.length},{name:"effective_filter_dims",type:"u32",length:w.length},{name:"pads",type:"i32",length:_.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],N=De(e[0].dataType);return`${Ic(R,e,i,o,P,v,N,L,c)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:p},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}],programUniforms:E}),getShaderSource:O}}});var Tc,Ec,Pc,su,uu,kc,Oc,Rc,Bc,du,lu=Y(()=>{"use strict";iu();au();Ft();Sr();Tc=(e,t,r,o,i,u)=>(e-1)*t+r+(o-1)*i+1-u,Ec=(e,t,r,o,i)=>{let u=Math.floor(e/2);t==="SAME_UPPER"?(r[o]=u,r[i]=e-u):t==="SAME_LOWER"&&(r[o]=e-u,r[i]=u)},Pc=(e,t,r,o,i,u,a,c,p,h)=>{let d=e.length-2,y=h.length===0;if(p.length===0)for(let v=0;v{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((y,w)=>y*w,1)===0){r.length=0;for(let y=2;yy+w,0)===0){let y=t[0].dims.length-2;p=new Array(y).fill(1)}let h=e.strides.slice();if(h.reduce((y,w)=>y+w,0)===0){let y=t[0].dims.length-2;h=new Array(y).fill(1)}Pc(c,r,p,e.autoPad,e.group,i,h,o,a,u);let d=Object.assign({},e);return Object.assign(d,{kernelShape:r,pads:i,outputPadding:a,outputShape:u,dilations:p,strides:h}),d},uu=e=>{let t=Bn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,u=e.group,a=e.kernelShape,c=e.pads,p=e.strides,h=e.wIsConst(),d=e.outputPadding,y=e.outputShape;return{autoPad:o,format:r,dilations:i,group:u,kernelShape:a,outputPadding:d,outputShape:y,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},kc=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[0];if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let u=e[0].dims.length-2;if(t.dilations.reduce((d,y)=>d+y,0)>0&&t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.reduce((d,y)=>d+y,0)>0&&t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.reduce((d,y)=>d+y,0)>0&&t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.outputPadding.length!==u&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${u}D`);if(t.kernelShape.reduce((d,y)=>d+y,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Oc=[2,3,1,0],Rc=(e,t,r)=>{let o=su(r,t),i=r.format==="NHWC",u=o.outputShape,a=u[i?3:1],c=t[0].dims[i?3:1];if(o.group!==1||a===1&&c===1){e.compute(Lo(t,o));return}let p=u[i?1:2],h=u[i?2:3],d=t[1].dims[2],y=t[1].dims[3],w=i?p*h:a,_=i?a:p*h,v=d*y*c,S=!0,A=e.kernelCustomData.wT??e.compute(yt(t[1],Oc),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=A);let I=[t[0],A],x=t.length===3;x&&(!i&&t[2].dims.length===1?I.push(t[2].reshape([t[2].dims[0],1,1])):I.push(t[2])),e.compute(ou(I,o,u,w,_,v,x,S),{inputs:I})},Bc=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&o.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let u=t.dilations;(u.length===0||u[0]===0)&&(u=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],a=[1].concat(a),u=[1].concat(u),i=[1].concat(i);let p=su({...t,pads:c,strides:a,dilations:u,kernelShape:i},o);e.compute(Lo(o,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]]))},du=(e,t)=>{kc(e.inputs,t),e.inputs[0].dims.length===3?Bc(e,t):Rc(e,e.inputs,t)}});var Dc,cu,pu,mu=Y(()=>{"use strict";ye();Se();Ze();_e();Dc=(e,t,r,o)=>{let i=M.size(t),u=t.length,a=U("input",e,u),c=j("output",e,u),p=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=M.normalizeAxis(p,u),d=y=>{let w=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,_=fe("uniforms.input_shape","uniforms.axis",u),v=o.reverse?w+(o.exclusive?" + 1":""):"0",S=o.reverse?_:w+(o.exclusive?"":" + 1");return`\n ${y.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,c)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${c.offsetToIndices("global_idx")};\n var sum = ${c.type.value}(0);\n let first : i32 = ${v};\n let last : i32 = ${S};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${a.getByIndices("inputIndices")};\n }\n ${c.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:o.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...Z(t,t)]}),getShaderSource:d}},cu=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,i=e.inputs[1];e.compute(Dc(o,r,i,t),{inputs:[0]})},pu=e=>{let t=e.exclusive===1,r=e.reverse===1;return ve({exclusive:t,reverse:r})}});var zc,Mc,Uc,fu,hu,gu=Y(()=>{"use strict";ye();Se();Ze();_e();zc=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Mc=(e,t,r,o)=>{let i=[];i.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let u=0;u{let r,o,i,u,a,c,p=t.format==="NHWC",h=t.blocksize,d=t.mode==="DCR";p?([r,o,i,u]=e.dims,a=d?[r,o,i,h,h,u/h**2]:[r,o,i,u/h**2,h,h],c=d?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,o,i,u]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=d?[r,h,h,u/h**2,o,i]:[r,u/h**2,h,h,o,i],c=d?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let y=e.reshape(a),w=y.dims.length,_=e.dataType,v=U("a",_,w),S=j("output",_,w),A=I=>`\n ${I.registerUniform("output_size","u32").declareVariables(v,S)}\n\n ${Mc(c,w,v,S)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${S.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${S.setByOffset("global_idx",v.getByIndices("aIndices"))}\n }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:I=>{let x=p?[r,o*h,i*h,u/h**2]:[r,u/h**2,o*h,i*h],E=M.size(x),P=y.dims,O=M.sortBasedOnPerm(P,c);return{outputs:[{dims:x,dataType:I[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:[{type:12,data:E},...Z(P,O)]}},getShaderSource:A}},fu=(e,t)=>{zc(e.inputs),e.compute(Uc(e.inputs[0],t))},hu=e=>ve({blocksize:e.blocksize,mode:e.mode,format:e.format})});var Fo,Wn,yu,Vc,Wc,qo,jo,bu,Nc,wu,vu,$u=Y(()=>{"use strict";ye();Se();Ze();_e();Fo="[a-zA-Z]|\\\\.\\\\.\\\\.",Wn="("+Fo+")+",yu="^"+Wn+"$",Vc="("+Wn+",)*"+Wn,Wc="^"+Vc+"$",qo=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let o=this.symbolToIndices.get(t);o===void 0?o=[r]:o.push(r),this.symbolToIndices.set(t,o)}},jo=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[o,i]=r.includes("->")?r.split("->",2):[r,""];if(!o.match(RegExp(Wc)))throw new Error("Invalid LHS term");if(o.split(",").forEach((c,p)=>{let h=t[p].dims.slice();if(!c.match(RegExp(yu)))throw new Error("Invalid LHS term");let d=this.processTerm(c,!0,h,p);this.lhs.push(d)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([c,p])=>p.count===1||c==="...").map(([c])=>c).join("");else if(!i.match(RegExp(Wn)))throw new Error("Invalid RHS");i.match(RegExp(Fo,"g"))?.forEach(c=>{if(c==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let p=this.symbolToInfo.get(c);if(p===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(p.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(t,r,o){let i=this.symbolToInfo.get(t);if(i!==void 0){if(i.dimValue!==r&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(o)}else i={count:1,dimValue:r,inputIndices:[o]};this.symbolToInfo.set(t,i)}processTerm(t,r,o,i=-1){let u=o.length,a=!1,c=[],p=0;if(!t.match(RegExp(yu))&&!r&&t!=="")throw new Error("Invalid LHS term");let h=t.match(RegExp(Fo,"g")),d=new qo(i);return h?.forEach((y,w)=>{if(y==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let _=u-h.length+1;if(_<0)throw new Error("Ellipsis out of bounds");if(c=o.slice(p,p+_),this.hasEllipsis){if(this.ellipsisDims.length!==c.length||this.ellipsisDims.toString()!==c.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=c;else throw new Error("Ellipsis must be specified in the LHS");for(let v=0;ve+"_max",Nc=(e,t,r,o)=>{let u=e.map(d=>d.length).map((d,y)=>U(`input${y}`,t,d)),a=M.size(o),c=j("output",t,o.length),p=[...r.symbolToInfo.keys()].filter(d=>!r.rhs.symbolToIndices.has(d)),h=d=>{let y=[],w="var prod = 1.0;",_="var sum = 0.0;",v="sum += prod;",S=[],A=[],I=[],x=[],E=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((O,R)=>{if(r.rhs.symbolToIndices.has(R)){let L=r.rhs.symbolToIndices.get(R)?.[0];L!==void 0&&r.lhs.forEach((N,K)=>{if(O.inputIndices.includes(K)){let Q=N.symbolToIndices.get(R);if(Q===void 0)throw new Error("Invalid symbol error");Q.forEach(he=>{y.push(`${u[K].indicesSet(`input${K}Indices`,he,c.indicesGet("outputIndices",L))}`)})}})}else r.lhs.forEach((L,N)=>{if(O.inputIndices.includes(N)){let K=L.symbolToIndices.get(R);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(Q=>{S.push(`${u[N].indicesSet(`input${N}Indices`,Q,`${R}`)}`)}),x.push(`prod *= ${u[N].getByIndices(`input${N}Indices`)};`)}}),A.push(`for(var ${R}: u32 = 0; ${R} < uniforms.${bu(R)}; ${R}++) {`),I.push("}")});let P=E?[...y,`let sum = ${u.map((O,R)=>O.getByIndices(`input${R}Indices`)).join(" * ")};`]:[...y,_,...A,...S,w,...x,v,...I];return`\n ${d.registerUniforms(p.map(O=>({name:`${bu(O)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,c)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${c.offsetToIndices("global_idx")};\n ${u.map((O,R)=>`var input${R}Indices: ${u[R].type.indices};`).join(`\n`)}\n ${P.join(`\n`)};\n ${c.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let d=p.filter(w=>r.symbolToInfo.has(w)).map(w=>({type:12,data:r.symbolToInfo.get(w)?.dimValue||0}));d.push({type:12,data:a});let y=e.map((w,_)=>[...Z(w)]).reduce((w,_)=>w.concat(_),d);return y.push(...Z(o)),{outputs:[{dims:o,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:y}},getShaderSource:h}},wu=(e,t)=>{let r=new jo(e.inputs,t.equation),o=r.outputDims,i=e.inputs.map((u,a)=>u.dims);e.compute(Nc(i,e.inputs[0].dataType,r,o))},vu=e=>{let t=e.equation.replace(/\\s+/g,"");return ve({equation:t})}});var Gc,_u,Hc,Lc,Su,xu=Y(()=>{"use strict";ye();Se();_e();Gc=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=r.length{let r=e.length-t.length,o=[];for(let i=0;ie.length>t.length?_u(e,t):_u(t,e),Lc=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=Hc(t,r),i=e[0].dataType,u=i===9?4:1,a=Math.ceil(M.size(o)/u),c=h=>{let d=U("input",i,t.length,u),y=j("output",i,o.length,u),w;if(i===9){let _=(v,S,A="")=>`\n let outputIndices${S} = ${y.offsetToIndices(`outputOffset + ${S}u`)};\n let offset${S} = ${d.broadcastedIndicesToOffset(`outputIndices${S}`,y)};\n let index${S} = offset${S} / 4u;\n let component${S} = offset${S} % 4u;\n ${v}[${S}] = ${A}(${d.getByOffset(`index${S}`)}[component${S}]);\n `;w=`\n let outputOffset = global_idx * ${u};\n var data = vec4(0);\n ${_("data",0,"u32")}\n ${_("data",1,"u32")}\n ${_("data",2,"u32")}\n ${_("data",3,"u32")}\n ${y.setByOffset("global_idx","data")}\n }`}else w=`\n let outputIndices = ${y.offsetToIndices("global_idx")};\n let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",y)};\n ${y.setByOffset("global_idx",d.getByOffset("inputOffset"))}\n }`;return`\n ${h.registerUniform("vec_size","u32").declareVariables(d,y)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${w}`},p=[{type:12,data:a},...Z(t,o)];return{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p})}},Su=e=>{Gc(e.inputs),e.compute(Lc(e.inputs),{inputs:[0]})}});var Fc,Cu,Au=Y(()=>{"use strict";ye();Se();_e();Rn();Fc=e=>{let t=e[0].dataType,r=M.size(e[0].dims),o=M.size(e[1].dims),i=o%4===0,u=a=>{let c=U("x",t,[1],4),p=U("bias",t,[1],4),h=j("y",t,[1],4),d=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],y=_=>`\n let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;\n let bias${_} = ${p.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,w=i?`\n let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${y(0)}${y(1)}${y(2)}${y(3)}\n let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(d).declareVariables(c,p,h)}\n\n ${Bo(et(t))}\n\n ${a.mainStart(or)}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${c.getByOffset("global_idx")};\n ${w}\n let x_in = x + bias;\n ${h.setByOffset("global_idx",Do("x_in"))}\n }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:u,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:o}],dispatchGroup:{x:Math.ceil(r/or/4)}})}},Cu=e=>{e.inputs.length<2||M.size(e.inputs[1].dims)===0?Bs(e):e.compute(Fc(e.inputs))}});var qc,jc,Iu,Tu,Eu=Y(()=>{"use strict";ye();Se();Ze();_e();qc=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},jc=(e,t)=>{let r=e[0].dims,o=e[1].dims,i=r.length,u=M.normalizeAxis(t.axis,i),a=r.slice(0);a.splice(u,1,...o);let c=r[u],p=e[0].dataType===9?4:1,h=Math.ceil(M.size(a)/p),d=[{type:12,data:h},{type:6,data:c},{type:12,data:u},...Z(e[0].dims,e[1].dims,a)],y=w=>{let _=U("data",e[0].dataType,e[0].dims.length,p),v=U("inputIndices",e[1].dataType,e[1].dims.length),S=j("output",e[0].dataType,a.length,p),A=x=>{let E=o.length,P=`var indicesIndices${x} = ${v.type.indices}(0);`;for(let O=0;O1?`indicesIndices${x}[${O}]`:`indicesIndices${x}`} = ${a.length>1?`outputIndices${x}[uniforms.axis + ${O}]`:`outputIndices${x}`};`;P+=`\n var idx${x} = ${v.getByIndices(`indicesIndices${x}`)};\n if (idx${x} < 0) {\n idx${x} = idx${x} + uniforms.axisDimLimit;\n }\n var dataIndices${x} : ${_.type.indices};\n `;for(let O=0,R=0;O1?`dataIndices${x}[${O}]`:`dataIndices${x}`} = u32(idx${x});`,R+=E):(P+=`${i>1?`dataIndices${x}[${O}]`:`dataIndices${x}`} = ${a.length>1?`outputIndices${x}[${R}]`:`outputIndices${x}`};`,R++);return P},I;if(e[0].dataType===9){let x=(E,P,O="")=>`\n let outputIndices${P} = ${S.offsetToIndices(`outputOffset + ${P}u`)};\n ${A(P)};\n let offset${P} = ${_.indicesToOffset(`dataIndices${P}`)};\n let index${P} = offset${P} / 4u;\n let component${P} = offset${P} % 4u;\n ${E}[${P}] = ${O}(${_.getByOffset(`index${P}`)}[component${P}]);\n `;I=`\n let outputOffset = global_idx * ${p};\n var value = vec4(0);\n ${x("value",0,"u32")}\n ${x("value",1,"u32")}\n ${x("value",2,"u32")}\n ${x("value",3,"u32")}\n ${S.setByOffset("global_idx","value")}\n `}else I=`\n let outputIndices = ${S.offsetToIndices("global_idx")};\n ${A("")};\n let value = ${_.getByIndices("dataIndices")};\n ${S.setByOffset("global_idx","value")};\n `;return`\n ${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,v,S)}\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${I}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}),getShaderSource:y}},Iu=e=>ve({axis:e.axis}),Tu=(e,t)=>{let r=e.inputs;qc(r),e.compute(jc(e.inputs,t))}});var Kc,Yc,Pu,ku,Ou=Y(()=>{"use strict";ye();Se();Ze();_e();Kc=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Yc=(e,t)=>{let r=e[0].dims,o=e[0].dataType,i=r.length,u=e[1].dims,a=e[1].dataType,c=M.normalizeAxis(t.axis,i),p=r[c],h=u.slice(0),d=M.size(h),y=U("input",o,i),w=U("indicesInput",a,u.length),_=j("output",o,h.length),v=[{type:12,data:d},{type:6,data:p},{type:12,data:c}];return v.push(...Z(r,u,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:v}),getShaderSource:I=>`\n ${I.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(y,w,_)}\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${_.offsetToIndices("global_idx")};\n\n var idx = ${w.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${y.type.indices}(outputIndices);\n ${y.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${y.getByIndices("inputIndices")};\n\n ${_.setByOffset("global_idx","value")};\n }`}},Pu=e=>ve({axis:e.axis}),ku=(e,t)=>{let r=e.inputs;Kc(r),e.compute(Yc(e.inputs,t))}});var Zc,Xc,Ru,Bu,Du=Y(()=>{"use strict";ye();Se();_e();Zc=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Xc=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[i,u,a]=Sn.getShapeOfGemmResult(r,t.transA,o,t.transB,e.length===3?e[2].dims:void 0),c=[i,u];if(!c)throw new Error("Can\'t use gemm on the given tensors");let p=M.size(c),h=[{type:12,data:p},{type:12,data:i},{type:12,data:u},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],d=["type","type"];e.length===3&&(h.push(...Z(e[2].dims)),d.push("rank")),h.push(...Z(c));let y=w=>{let _="";t.transA&&t.transB?_="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?_="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?_="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(_="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let v=t.alpha===1?"":"value *= uniforms.alpha;",S=U("a",e[0].dataType,e[0].dims),A=U("b",e[1].dataType,e[1].dims),I=S.type.value,x=null,E=[S,A];e.length===3&&(x=U("c",e[2].dataType,e[2].dims.length),E.push(x));let P=j("output",e[0].dataType,c.length);E.push(P);let O=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`\n ${w.registerUniforms(O).declareVariables(...E)}\n\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${I}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${_}\n }\n\n ${v}\n ${(()=>x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",P)}; value += ${I}(uniforms.beta) * ${x.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:y}},Ru=e=>{let t=e.transA,r=e.transB,o=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:o,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Bu=(e,t)=>{Zc(e.inputs),e.compute(Xc(e.inputs,t))}});var Qc,Jc,ep,zu,Mu=Y(()=>{"use strict";ye();Se();_e();Qc=(e,t)=>{let r=e[0].dims,o=r,i=2,u=M.sizeToDimension(r,i),a=M.sizeFromDimension(r,i),c=Me(a),p=a/c,h=[r[0],r[1],p],d=["rank","type","type"],y=[{type:12,data:a},{type:12,data:p}];y.push(...Z(h,h));let w=_=>{let v=U("x",e[0].dataType,h.length,c),S=U("scale",e[1].dataType,e[1].dims),A=U("bias",e[2].dataType,e[2].dims),I=j("output",e[0].dataType,h.length,c),x=[v,S,A,I],E=v.type.value,P=c===1?"f32":`vec${c}`,O=64,R=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${P}, ${O}>;\n const workgroupSize = ${O}u;\n ${_.registerUniforms(R).declareVariables(...x)}\n ${_.mainStart(O)}\n let norm = global_idx / workgroupSize;\n let batch = norm / uniforms.x_shape[1];\n let channel = norm % uniforms.x_shape[1];\n let localIndex = local_id.x;\n\n // initialize workgroup memory\n var initial = ${P}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${P}(${v.get("batch","channel","h")});\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the mean of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n meanShared = ${_t("workgroupShared[0]",c)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${P}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${P}(${v.get("batch","channel","h")}) - ${P}(meanShared);\n initial = initial + deviation * deviation;\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the sum of square of deviation of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n squaredNormShared = ${_t("workgroupShared[0]",c)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${S.getByOffset("channel")});\n let channelShift = f32(${A.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${v.get("batch","channel","h")} * ${E}(${P}(channelScale)) + ${E}(${P}(channelShift));\n ${I.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${c}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:u},programUniforms:y}),getShaderSource:w}},Jc=(e,t,r,o,i,u,a,c)=>{let p=Me(a),h=64,d=p===1?"vec2f":`mat2x${p}f`,y=p===1?"f32":`vec${p}f`,w=(R,L)=>`${d}(${R}, ${L})`,_=i*a/p,v=Math.ceil(u/h),S=["type"],A=[{type:12,data:v},{type:12,data:u},{type:12,data:Math.floor(a/p)},{type:12,data:Math.floor(u*a/p)}],I=R=>{let L=U("input",t.dataType,t.dims,p);return`\n ${R.declareVariables(L)}\n @group(0) @binding(1) var output : array<${d}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${R.mainStart(h)}\n let currentImageNumber = global_idx / ${h} / uniforms.C;\n let currentChannelNumber = (global_idx / ${h}) % uniforms.C;\n let wgOffset = local_id.x * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${$t("f32",p)};\n var squaredSum = ${$t("f32",p)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${y}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${w("sum","squaredSum")};\n }`},x=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:[i,a,h,2],dataType:1}],dispatchGroup:{x:i*a/p},programUniforms:A}),getShaderSource:I},{inputs:[t],outputs:[-1]})[0],E=[{type:12,data:_},{type:12,data:u},{type:12,data:Math.floor(a/p)},{type:12,data:Math.floor(h*a/p)}],P=["type","type","type"],O=R=>{let L=U("scale",r.dataType,r.dims,p),N=U("bias",o.dataType,o.dims,p);return`\n @group(0) @binding(0) var input : array<${d}>;\n @group(0) @binding(1) var scale : array<${L.type.storage}>;\n @group(0) @binding(2) var bias : array<${N.type.storage}>;\n @group(0) @binding(3) var output : array<${d}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${R.mainStart()}\n ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")}\n let currentImageNumber = global_idx / uniforms.C;\n let currentChannelNumber = global_idx % uniforms.C;\n\n let offset = currentImageNumber * uniforms.image_size;\n var sum = ${$t("f32",p)};\n var squaredSum = ${$t("f32",p)};\n for (var i: u32 = 0; i < min(${h}, uniforms.H); i++) {\n let value = input[offset + i + currentChannelNumber * ${h}];\n sum += value[0];\n squaredSum += value[1];\n }\n sum = sum / f32(uniforms.H);\n squaredSum = squaredSum / f32(uniforms.H);\n let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${c}));\n let channelScale = invStdDev * ${y}(scale[currentChannelNumber]);\n let channelShift = ${y}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${w("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${c}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:[i,a,2],dataType:1}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:E}),getShaderSource:O},{inputs:[x,r,o],outputs:[-1]})[0]},ep=(e,t,r)=>{let o=t[0].dims,i=o,u=o[0],a=o[o.length-1],c=M.sizeFromDimension(o,1)/a,p=Me(a),h=M.size(i)/p,d=[{type:12,data:c},{type:12,data:Math.floor(a/p)}],y=["type","type"],w=Jc(e,t[0],t[1],t[2],u,c,a,r.epsilon),_=v=>{let S=De(t[0].dataType),A=p===1?"vec2f":`mat2x${p}f`,I=p===1?S:`vec${p}<${S}>`,x=U("input",t[0].dataType,t[0].dims,p),E=j("output",t[0].dataType,i,p);return`\n @group(0) @binding(0) var input : array<${x.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${A}>;\n @group(0) @binding(2) var output : array<${E.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${v.mainStart()}\n let currentImageNumber = global_idx / (uniforms.C * uniforms.H);\n let currentChannelNumber = global_idx % uniforms.C;\n\n let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber;\n let scale = scaleInput[scaleOffset];\n output[global_idx] = fma(input[global_idx], ${I}(scale[0]), ${I}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}),getShaderSource:_},{inputs:[t[0],w]})},zu=(e,t)=>{t.format==="NHWC"?ep(e,e.inputs,t):e.compute(Qc(e.inputs,t))}});var tp,rp,Uu,Vu=Y(()=>{"use strict";ye();Se();_e();tp=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},rp=(e,t,r)=>{let o=t.simplified,i=e[0].dims,u=e[1],a=!o&&e[2],c=i,p=M.normalizeAxis(t.axis,i.length),h=M.sizeToDimension(i,p),d=M.sizeFromDimension(i,p),y=M.size(u.dims),w=a?M.size(a.dims):0;if(y!==d||a&&w!==d)throw new Error(`Size of X.shape()[axis:] == ${d}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${y} and bias size of ${w}`);let _=[];for(let O=0;O1,x=r>2,E=O=>{let R=De(e[0].dataType),L=[U("x",e[0].dataType,e[0].dims,v),U("scale",u.dataType,u.dims,v)];a&&L.push(U("bias",a.dataType,a.dims,v)),L.push(j("output",e[0].dataType,c,v)),I&&L.push(j("mean_data_output",1,_)),x&&L.push(j("inv_std_output",1,_));let N=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${O.registerUniforms(N).declareVariables(...L)}\n ${O.mainStart()}\n ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${$t("f32",v)};\n var mean_square_vector = ${$t("f32",v)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${ir(R,v,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${_t("mean_vector",v)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${_t("mean_square_vector",v)} / uniforms.norm_size ${o?"":"- mean * mean"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${ir(R,v,"x[j + offset]")};\n let f32scale = ${ir(R,v,"scale[j]")};\n output[j + offset] = ${L[0].type.value}((f32input ${o?"":"- mean"}) * inv_std_dev * f32scale\n ${a?`+ ${ir(R,v,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${x?"inv_std_output[global_idx] = inv_std_dev":""};\n }`},P=[{dims:c,dataType:e[0].dataType}];return I&&P.push({dims:_,dataType:1}),x&&P.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${v};${r};${o}`,inputDependencies:S},getRunData:()=>({outputs:P,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:A}),getShaderSource:E}},Uu=(e,t)=>{tp(e.inputs),e.compute(rp(e.inputs,t,e.outputCount))}});var np,op,Wu,Nu,Gu=Y(()=>{"use strict";ye();Se();Ze();_e();np=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],o=r.dims.length;if(r.dims[o-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),u=t.blockSize/8*t.bits,a=e[1];if(!M.areEqual(a.dims,[t.n,i,u]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let p=e[2].dims;if(M.size(p)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,y=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(M.size(d)!==y)throw new Error("zeroPoints input size error.")}},op=(e,t,r,o)=>{let i=e[0].dims,u=i.length,a=Math.floor((t.k+t.blockSize-1)/t.blockSize),c=i[u-2],p=t.k,h=t.n,d=i.slice(0,u-2),y=M.size(d),_=t.blockSize/8*t.bits/4,v=e[0].dataType,S=Me(c),A=Me(t.k),I=Me(_),x=tr(v),E=c*a*x,P=Math.floor(o/E),O=a<=r[0]&&P>0,R=!O||P>=4?Me(h):P>=2&&Me(h)>=2?2:1,L=d.concat([c,h]),N=M.size(L)/R/S,K=O?[]:[{type:12,data:N},{type:12,data:t.blockSize}],Q=[y,c,p/A],he=M.convertShape(e[1].dims).slice();he.splice(-1,1,_/I),K.push(...Z(Q)),K.push(...Z(he)),K.push(...Z(e[2].dims)),e.length===4&&K.push(...Z(M.convertShape(e[3].dims)));let W=[y,c,h/R];K.push(...Z(W));let se=Ce=>{let We=Q.length,ee=U("a",e[0].dataType,We,A),ae=U("b",12,he.length,I),Ae=U("scales",e[2].dataType,e[2].dims.length),me=[ee,ae,Ae],ie=e.length===4?U("zero_points",12,e[3].dims.length):void 0;ie&&me.push(ie);let ue=W.length,le=j("output",e[0].dataType,ue,R),qe=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],G=De(e[0].dataType),ne=(()=>{switch(A){case 1:return`array<${G}, 8>`;case 2:return`mat4x2<${G}>`;case 4:return`mat2x4<${G}>`;default:throw new Error(`${A}-component is not supported.`)}})(),xe=`\n for (var word: u32 = 0; word < ${_}; word += ${I}) {\n ${ae.indicesSet("b_indices","2","word")};\n let b_data = ${ae.getByIndices("b_indices")};\n for (var i: u32 = 0; i < ${I}; i++) {\n let b_value: u32 = ${I===1?"b_data":"b_data[word + i]"};\n let b_mask: u32 = 0x0F0F0F0Fu;\n let b_value_lower: vec4 = unpack4xU8(b_value & b_mask);\n let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask);\n let b_quantized_values = ${ne}(${Array.from({length:4},(Be,Ge)=>`${G}(b_value_lower[${Ge}]), ${G}(b_value_upper[${Ge}])`).join(", ")});\n let b_dequantized_values = ${(()=>A===1?`${ne}(${Array.from({length:8},(Be,Ge)=>`(b_quantized_values[${Ge}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ne}(${Array(8).fill("zero_point").join(",")})) * scale;`)()};\n // Number of B elements per 32-bit word is 32/bits = 32/4 = 8\n for (var m: u32 = 0; m < ${O?c:S}u; m++) {\n ${ee.indicesSet("a_indices",We-2,O?"m":`row * ${S} + m`)};\n ${ee.indicesSet("a_indices",We-1,"word_offset")};\n var input_offset = ${ee.indicesToOffset("a_indices")};\n var a_data: ${ne};\n for (var j: u32 = 0; j < ${8/A}; j++) {\n a_data[j] = ${ee.getByOffset("input_offset")};\n input_offset++;\n }\n ${O?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${R>1?"[c]":""} += ${Array.from({length:8/A},(Be,Ge)=>`${A===1?`a_data[${Ge}] * b_dequantized_values[${Ge}]`:`dot(a_data[${Ge}], b_dequantized_values[${Ge}])`}`).join(" + ")};\n }\n word_offset += ${8/A};\n }\n }`,Ke=ie?`\n zero_point_offset += 4;\n if (zero_point_offset == 32) {\n zero_point_offset = 0;\n zero_point_index++;\n zero_point_word = ${ie.getByOffset("zero_point_index")};\n }`:"";return O?`\n var workgroup_shared: array<${le.type.value}, ${c*a}>;\n ${Ce.declareVariables(...me,le)}\n ${Ce.mainStart([a,1,1])}\n var a_indices: ${ee.type.indices};\n var block = local_id.x;\n var col = workgroup_id.y;\n var batch = workgroup_id.z;\n ${ee.indicesSet("a_indices","0","batch")};\n // Two zero points are packed into one byte when uniforms.bits is 4.\n for (var c: u32 = 0; c < ${R}; c++) {\n let col_times_components_plus_c = col * ${R} + c;\n ${ie?`\n var zero_point_bytes_per_col: u32 = (${a} + 1) / 2;\n var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u);\n var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u;\n var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u;\n var zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n var zero_point_word: u32 = ${ie.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""}\n var b_indices: ${ae.type.indices};\n ${ae.indicesSet("b_indices","0","col_times_components_plus_c")};\n // The scale and zero points are computed per block.\n var scales_index = col_times_components_plus_c * ${a} + block;\n let scale = ${Ae.getByOffset("scales_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${G}(${ie?"(zero_point_word) & 0xFu":8});\n ${ae.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block * ${t.blockSize/A};\n var workgroup_shared_offset: u32 = block * ${c};\n ${xe}\n }\n workgroupBarrier();\n if (local_id.x == 0u) {\n var output_indices: ${le.type.indices};\n ${le.indicesSet("output_indices","0","batch")};\n ${le.indicesSet("output_indices",ue-1,"col")};\n ${le.indicesSet("output_indices",ue-2,"0")};\n var output_offset = ${le.indicesToOffset("output_indices")};\n for (var m: u32 = 0u; m < ${c}u; m++) {\n var output_value: ${le.type.value} = ${le.type.value}(0);\n var workgroup_shared_offset: u32 = m;\n for (var b: u32 = 0u; b < ${a}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${c};\n }\n ${le.setByOffset("output_offset","output_value")};\n output_offset += ${h/R};\n }\n }\n }`:`\n ${Ce.registerUniforms(qe).declareVariables(...me,le)}\n ${Ce.mainStart()}\n ${Ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var output_values: array<${le.type.value}, ${S}>;\n var output_indices = ${le.offsetToIndices("global_idx")};\n var col = ${le.indicesGet("output_indices",ue-1)};\n var row = ${le.indicesGet("output_indices",ue-2)};\n var a_indices: ${ee.type.indices} = output_indices;\n // Two zero points are packed into one byte because uniforms.bits <= 4.\n // zero_point_offset is either 0 or 4. It is bit offset within one byte.\n // TODO support zero_point_offset for bits > 4\n ${ie?`\n var zero_point_abs_offset = col * ${R} * ((${a} + 1) / 2);\n var zero_point_index: u32 = zero_point_abs_offset / 4;\n var zero_point_word: u32 = ${ie.getByOffset("zero_point_index")};\n var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""}\n var scale_index = col * ${a*R};\n var b_indices: ${ae.type.indices};\n for (var c: u32 = 0; c < ${R}; c++) {\n ${ae.indicesSet("b_indices","0",`col * ${R} + c`)};\n var block_offset: u32 = 0;\n for (var block: u32 = 0; block < ${a}; block++) {\n // The scale and zero points are computed per block.\n let scale = ${Ae.getByOffset("scale_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${G}(${ie?"extractBits(zero_point_word, zero_point_offset, 4)":8});\n ${ae.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block_offset;\n ${xe}\n scale_index++;\n ${Ke}\n block_offset += uniforms.block_size / ${A};\n }\n // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte.\n ${ie?`if (zero_point_offset % 8 > 0) {\n ${Ke}\n }`:""}\n }\n for (var k: u32 = 0u; k < ${S}u; k++) {\n ${le.indicesSet("output_indices",ue-2,`${S} * row + k`)};\n ${le.setByIndices("output_indices","output_values[k]")}\n }\n }`};return{name:O?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${c};${v};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:L,dataType:v}],name:O?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:O?{x:1,y:Math.ceil(h/R),z:y}:{x:Math.ceil(N/64)},programUniforms:K}),getShaderSource:se}},Wu=(e,t)=>{np(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),o=e.getMaxComputeWorkgroupStoragesize();e.compute(op(e.inputs,t,r,o))},Nu=e=>ve(e)});var it,ip,Lu,Hu,ap,Ko,Fu,qu=Y(()=>{"use strict";ye();Se();Ze();_n();Ro();_e();Sr();it=(e,t)=>e.length>t&&e[t].dims.length>0&&M.size(e[t].dims)>0?e[t]:void 0,ip=(e,t)=>{let r=e[0],o=it(e,1),i=it(e,2),u=it(e,3),a=it(e,4),c=it(e,5),p=it(e,6),h=it(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,y=r.dims[0],w=r.dims[1],_=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],v=w,S=0,A=0,I=Math.floor(_/t.numHeads);if(p&&h){if(p.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(p.dims[0]!==y||p.dims[1]!==t.numHeads||p.dims[3]!==I)throw new Error(\'Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(h.dims[0]!==y||h.dims[1]!==t.numHeads||h.dims[3]!==I)throw new Error(\'Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(p.dims[2]!==h.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)\');if(h.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');S=p.dims[2],A=p.dims[2]}else if(p||h)throw new Error(\'Input "past_key" and "past_value" shall be both present or both absent\');let x;if(o){if(r.dims.length!==3)throw new Error(\'Input "query" is expected to have 3 dimensions when key is given\');if(o.dims.length<3||o.dims.length>5)throw new Error(\'Input "key" is expected to have 3, 4, or 5 dimensions\');if(r.dims[0]!==o.dims[0])throw new Error(\'Input "query" and "key" shall have same dim 0 (batch size)\');if(o.dims.length===3){if(o.dims[2]!==r.dims[2])throw new Error(\'Input "query" and "key" shall have same dim 2 (hidden_size)\');x=2,v=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==I)throw new Error(\'Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv\');if(i)throw new Error(\'Expect "value" be none when "key" has packed kv format.\');x=5,v=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==I)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');x=0,v=o.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\'Input "query" is expected to have 3 or 5 dimensions when key is empty\');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error(\'Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv\');x=3}if(u){if(u.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(i&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let E=0;if(a){E=8;let N=a.dims;throw N.length===1?N[0]===y?E=1:N[0]===3*y+2&&(E=3):N.length===2&&N[0]===y&&N[1]===v&&(E=5),E===8?new Error(\'Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)\'):new Error("Mask not supported")}let P=!1,O=_;if(i){if(i.dims.length!==3&&i.dims.length!==4)throw new Error(\'Input "value" is expected to have 3 or 4 dimensions\');if(r.dims[0]!==i.dims[0])throw new Error(\'Input "query" and "value" shall have same dim 0 (batch_size)\');if(i.dims.length===3){if(v!==i.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');O=i.dims[2]}else{if(v!==i.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');O=i.dims[1]*i.dims[3],P=!0}}let R=S+v,L=!1;if(a)throw new Error("Key padding mask is not supported");if(c){if(c.dims.length!==4)throw new Error(\'Input "relative_position_bias" is expected to have 4 dimensions\');if(c.dims[0]!==y&&c.dims[0]!==1||c.dims[1]!==t.numHeads||c.dims[2]!==w||c.dims[3]!==R)throw new Error(\'Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)\')}return{batchSize:y,sequenceLength:w,pastSequenceLength:S,kvSequenceLength:v,totalSequenceLength:R,maxSequenceLength:A,inputHiddenSize:0,hiddenSize:_,vHiddenSize:O,headSize:I,vHeadSize:Math.floor(O/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:E,scale:t.scale,broadcastResPosBias:L,passPastInKv:P,qkvFormat:x}},Lu=e=>ve({...e}),Hu=ve({perm:[0,2,1,3]}),ap=(e,t,r,o,i,u,a)=>{let c=[o,i,u],p=M.size(c),h=[{type:12,data:p},{type:12,data:a},{type:12,data:u}],d=y=>{let w=j("qkv_with_bias",t.dataType,c),_=U("qkv",t.dataType,c),v=U("bias",r.dataType,c),S=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${y.registerUniforms(S).declareVariables(_,v,w)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:d},{inputs:[t,r],outputs:[-1]})[0]},Ko=(e,t,r,o,i,u,a,c)=>{let p=u;if(a){if(o===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=ap(e,u,a,t,o,r*i,c),p=p.reshape([t,o,r,i]),e.compute(yt(p,Hu.perm),{inputs:[p],outputs:[-1]})[0]}else return u.dims.length===3&&(p=u.reshape([t,o,r,i])),e.compute(yt(p,Hu.perm),{inputs:[p],outputs:[-1]})[0]},Fu=(e,t)=>{let r=ip(e.inputs,t),o=e.inputs[0],i=it(e.inputs,1),u=it(e.inputs,2),a=it(e.inputs,3),c=it(e.inputs,4),p=it(e.inputs,5),h=it(e.inputs,6),d=it(e.inputs,7);if(o.dims.length===5)throw new Error("Packed QKV is not implemented");if(i?.dims.length===5)throw new Error("Packed KV is not implemented");let y=i&&u&&i.dims.length===4&&u.dims.length===4,w=Ko(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,o,a,0);if(y)return Pn(e,w,i,u,c,void 0,h,d,p,r,t);if(!i||!u)throw new Error("key and value must be provided");let _=Ko(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,a,r.hiddenSize),v=Ko(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,u,a,2*r.hiddenSize);Pn(e,w,_,v,c,void 0,h,d,p,r,t)}});var sp,up,dp,lp,cp,pp,mp,fp,ju,Ku=Y(()=>{"use strict";ye();Se();_e();sp=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},up=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n break;\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n }\n `},dp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${fe("uniforms.x_shape",i,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},lp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k = i32(${fe("uniforms.x_shape",i,t)}) - 1;\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},cp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k += i32(${fe("uniforms.x_shape",i,t)}]);\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k -= i32(${fe("uniforms.x_shape",i,t)});\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},pp=(e,t,r)=>{switch(r.mode){case 0:return up(e,t,r.pads.length);case 1:return dp(e,t,r.pads.length);case 2:return lp(e,t,r.pads.length);case 3:return cp(e,t,r.pads.length);default:throw new Error("Invalid mode")}},mp=(e,t)=>{let r=M.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,i=M.size(r),u=[{type:12,data:i},{type:6,data:t.pads}];t.mode===0&&u.push({type:e[0].dataType,data:t.value}),u.push(...Z(e[0].dims,r));let a=["rank"],c=p=>{let h=j("output",e[0].dataType,r.length),d=U("x",e[0].dataType,o.length),y=d.type.value,w=pp(h,o.length,t),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&_.push({name:"constant_value",type:y}),`\n ${p.registerUniforms(_).declareVariables(d,h)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${h.offsetToIndices("global_idx")};\n\n var value = ${y}(0);\n ${w}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(M.size(r)/64)},programUniforms:u}),getShaderSource:c}},fp=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),o=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,i=e[0].dims.length,u=new Int32Array(2*i).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let p=0;pu[Number(p)]=Number(c));let a=[];return u.forEach(c=>a.push(c)),{mode:t.mode,value:o,pads:a}}else return t},ju=(e,t)=>{sp(e.inputs);let r=fp(e.inputs,t);e.compute(mp(e.inputs,r),{inputs:[0]})}});var Nn,Yu,Zu,Xu,Qu,hp,gp,Ju,ed,td,rd,nd,od,id,ad,sd,ud,dd,ld,cd=Y(()=>{"use strict";$r();ye();Se();_e();Nn=e=>{if(vr.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Yu=(e,t,r)=>{let o=t.format==="NHWC",i=e.dims.slice();o&&i.splice(1,0,i.pop());let u=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),c=t.strides.slice(),p=u?t.dilations.slice():[],h=t.pads.slice();nr.adjustPoolAttributes(r,i,a,c,p,h);let d=nr.computePoolOutputShape(r,i,c,p,a,h,t.autoPad),y=Object.assign({},t);u?Object.assign(y,{kernelShape:a,strides:c,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(y,{kernelShape:a,strides:c,pads:h,cacheKey:t.cacheKey});let w=d.slice();return w.push(w.splice(1,1)[0]),[y,o?w:d]},Zu=(e,t)=>{let r=t.format==="NHWC",o=M.size(e),i=M.size(t.kernelShape),u=[{type:12,data:o},{type:12,data:i}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],d=t.pads[t.pads.length-1],y=!!(h+d);u.push({type:12,data:c},{type:12,data:p},{type:12,data:h},{type:12,data:d}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let w=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],v=t.strides[t.strides.length-2],S=t.pads[t.pads.length/2-2],A=t.pads[t.pads.length-2];w=!!(S+A),u.push({type:12,data:_},{type:12,data:v},{type:12,data:S},{type:12,data:A}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[u,a,!0,y,w]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=M.computeStrides(t.kernelShape);u.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,d)=>h+d);return[u,a,!!p,!1,!1]}},Xu=(e,t,r,o,i,u,a,c,p,h,d,y)=>{let w=i.format==="NHWC",_=t.type.value,v=j("output",t.type.tensor,o);if(i.kernelShape.length<=2){let S="",A="",I="",x=r-(w?2:1);if(d?S=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${x}] < 0 || xIndices[${x}]\n >= uniforms.x_shape[${x}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n }`:S=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n }`,i.kernelShape.length===2){let P=r-(w?3:2);y?A=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${P}] < 0 || xIndices[${P}] >= uniforms.x_shape[${P}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:A=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;\n `,I=`\n }\n `}return`\n ${e.registerUniforms(p).declareVariables(t,v)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${v.offsetToIndices("global_idx")};\n var xIndices = ${v.offsetToIndices("global_idx")};\n\n var value = ${_}(${c});\n var pad = 0;\n ${A}\n ${S}\n ${I}\n ${a}\n\n output[global_idx] = value;\n }`}else{if(w)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let S=i.kernelShape.length,A=i.pads.length,I="";return h?I=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n }`:I=`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n `,`\n ${e.registerUniforms(p).declareVariables(t,v)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${v.offsetToIndices("global_idx")};\n var xIndices = ${v.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${_}(${c});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${S-1}u; j++) {\n offsets[j] = offset / ${fe("uniforms.kernelStrides","j",S)};\n offset -= offsets[j] * ${fe("uniforms.kernelStrides","j",S)};\n }\n offsets[${S-1}] = offset;\n\n isPad = false;\n for (var j = ${r-S}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${fe("uniforms.strides",`j - ${r-S}u`,S)}\n + offsets[j - ${r-S}u] - ${fe("uniforms.pads","j - 2u",A)};\n ${I}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},Qu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,hp=e=>`${Qu(e)};${e.countIncludePad}`,gp=e=>`${Qu(e)};${e.storageOrder};${e.dilations}`,Ju=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),ed=(e,t,r,o)=>{let[i,u]=Yu(t,o,r),a=U("x",t.dataType,t.dims.length),c=a.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${c}(uniforms.kernelSize);`:h+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[d,y,w,_,v]=Zu(u,i);d.push(...Z(t.dims,u));let S=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${w};${_};${v}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(M.size(u)/64)},programUniforms:d}),getShaderSource:A=>Xu(A,a,t.dims.length,u.length,i,p,h,0,y,w,_,v)}},td=e=>{let t=e.count_include_pad!==0,r=Ju(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let o={countIncludePad:t,...r,cacheKey:""};return{...o,cacheKey:hp(o)}},rd=(e,t)=>{Nn(e.inputs),e.compute(ed("AveragePool",e.inputs[0],!1,t))},nd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},od=e=>{let t=e.format;return{format:t,...nd,cacheKey:t}},id=(e,t)=>{Nn(e.inputs),e.compute(ed("GlobalAveragePool",e.inputs[0],!0,t))},ad=(e,t,r,o)=>{let[i,u]=Yu(t,o,r),a=`\n value = max(x_val, value);\n `,c="",p=U("x",t.dataType,t.dims.length),h=["rank"],[d,y,w,_,v]=Zu(u,i);return d.push(...Z(t.dims,u)),{name:e,shaderCache:{hint:`${o.cacheKey};${w};${_};${v}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(M.size(u)/64)},programUniforms:d}),getShaderSource:S=>Xu(S,p,t.dims.length,u.length,i,a,c,t.dataType===10?-65504:-1e5,y,w,_,v)}},sd=(e,t)=>{Nn(e.inputs),e.compute(ad("MaxPool",e.inputs[0],!1,t))},ud=e=>{let t=e.storage_order,r=e.dilations,o=Ju(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(o.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:r,...o,cacheKey:""};return{...i,cacheKey:gp(i)}},dd=e=>{let t=e.format;return{format:t,...nd,cacheKey:t}},ld=(e,t)=>{Nn(e.inputs),e.compute(ad("GlobalMaxPool",e.inputs[0],!0,t))}});var bp,wp,pd,md=Y(()=>{"use strict";$r();ye();_e();bp=(e,t,r)=>{let o=e===t,i=et&&r>0;if(o||i||u)throw new Error("Range these inputs\' contents are invalid.")},wp=(e,t,r,o)=>{let i=Math.abs(Math.ceil((t-e)/r)),u=[i],a=i,c=[{type:12,data:a},{type:o,data:e},{type:o,data:r},...Z(u)],p=h=>{let d=j("output",o,u.length),y=d.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:y},{name:"delta",type:y}];return`\n ${h.registerUniforms(w).declareVariables(d)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${y}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c})}},pd=e=>{let t=0,r=0,o=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],o=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],o=e.inputs[2].getFloat32Array()[0]),vr.webgpu.validateInputContent&&bp(t,r,o),e.compute(wp(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var vp,$p,_p,Sp,xp,Cp,Ap,Ip,Tp,Ep,Pp,fd,kp,Op,Rp,Bp,Dp,hd,gd,yd=Y(()=>{"use strict";ye();Se();Ze();_e();vp=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},$p=(e,t,r)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let o=new Array(r).fill(1);return t.forEach((i,u)=>o[i]=e[u]),o},_p=(e,t,r,o,i,u)=>{let[a,c,p]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(d=>u.push(d));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length>0){if(e[c].getFloat32Array().forEach(d=>o.push(d)),o.length!==0&&o.length!==h&&r>=18&&o.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");vp(o,t),t.axes.length>0&&$p(o,t.axes,h).forEach((d,y)=>o[y]=d)}if(p>0&&e.length>p&&(e[p].getBigInt64Array().forEach(d=>i.push(Number(d))),i.length!==h||r>=18&&i.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(o.length!==t.axes.length)throw new Error(\'Resize requires "scales" input size to be of axes rank when axes attributes is specified\');if(i.length!==t.axes.length)throw new Error(\'Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified\')}if(typeof o<"u"&&typeof i<"u"&&o.length>0&&i.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Sp=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",xp=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Cp=(e,t,r)=>{let o=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?o:e.slice();return t.length>0?(t.forEach((u,a)=>{o[u]=i[a],o[a+r]=i[t.length+a]}),o):i},Ap=(e,t,r,o)=>{let i=[];if(r.length>0)if(o.length>0){if(e.forEach(u=>i.push(u)),Math.max(...o)>e.length)throw new Error("axes is out of bound");o.forEach((u,a)=>i[u]=r[a])}else r.forEach(u=>i.push(u));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((u,a)=>Math.round(u*t[a]))}return i},Ip=(e,t,r)=>{let o=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(u=>t[u]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(u=>t[u]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return r.axes.length>0?(r.axes.forEach(u=>t[u]=o),r.axes.forEach(u=>i[u]=Math.round(e[u]*t[u]))):(t.fill(o,0,t.length),i.forEach((u,a)=>i[a]=Math.round(u*t[a]))),i},Tp=(e,t,r,o,i)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${fe("uniforms.scales","i",o)};\n var roi_low = ${fe("uniforms.roi","i",i)};\n var roi_hi = ${fe("uniforms.roi",`i + ${t.length}`,i)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${fe("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${fe("uniforms.output_shape","i",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Ep=(e,t,r,o,i,u,a)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${o.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${fe("uniforms.scales","i",i)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${fe("uniforms.roi","i",u)};\n var roi_hi = ${fe("uniforms.roi",`i + ${r.length}`,u)};\n var input_shape_i = ${fe("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${fe("uniforms.output_shape","i",o.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,Pp=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${fe("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,fd=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",kp=(e,t,r,o,i)=>{let[a,c,p,h]=r.length===2?[-1,0,1,-1]:[0,2,3,1],d=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${d} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",c,`max(0, min(row, ${r[c]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(col, ${r[p]} - 1))`)};\n ${fd(e,h,a,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${d} = originalIndices[${c}];\n var col:${d} = originalIndices[${p}];\n ${o?`if (row < 0 || row > (${r[c]} - 1) || col < 0 || col > (${r[p]} - 1)) {\n return ${i};\n }`:""};\n row = max(0, min(row, ${r[c]} - 1));\n col = max(0, min(col, ${r[p]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${h}])`:"0"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"};\n var x11: ${d} = getInputValue(batch, channel, row1, col1);\n var x12: ${d} = getInputValue(batch, channel, row1, col2);\n var x21: ${d} = getInputValue(batch, channel, row2, col1);\n var x22: ${d} = getInputValue(batch, channel, row2, col2);\n var dx1: ${d} = abs(row - ${d}(row1));\n var dx2: ${d} = abs(${d}(row2) - row);\n var dy1: ${d} = abs(col - ${d}(col1));\n var dy2: ${d} = abs(${d}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Op=(e,t,r,o,i,u,a,c,p,h)=>{let d=r.length===2,y=!0,[w,_]=d?[0,1]:y?[2,3]:[1,2],v=e.type.value,S=A=>{let I=A===w?"row":"col";return`\n fn ${I}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${v} {\n var output_index = ${t.indicesGet("output_indices",A)};\n var originalIdx: ${v} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[A]},\n ${o[A]}, ${r[A]}, ${u[A]}, ${u[A]} + ${r.length});\n var fractOriginalIdx: ${v} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${c} && (originalIdx < 0 || originalIdx > (${r[A]} - 1))) {\n return ${p};\n }\n var data: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${I}: ${v} = originalIdx + ${v}(i);\n if (${I} < 0 || ${I} >= ${r[A]}) {\n ${(()=>h?`coefs[i + 1] = 0.0;\n continue;`:c?`return ${p};`:`${I} = max(0, min(${I}, ${r[A]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",A,`u32(${I})`)};\n data[i + 1] = ${A===w?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${S(w)};\n ${S(_)};\n fn getCubicInterpolationCoefs(s: ${v}) -> array<${v}, 4> {\n var absS = abs(s);\n var coeffs: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${v} = 1.0 - absS;\n var twoMinusAbsS: ${v} = 2.0 - absS;\n var onePlusAbsS: ${v} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${v}, 4>, coefs: array<${v}, 4>) -> ${v} {\n var coefsSum: ${v} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${v} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Rp=(e,t,r,o,i)=>{let[a,c,p,h,d]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],y=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${y} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",c,`max(0, min(depth, ${r[c]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(height, ${r[p]} - 1))`)};\n ${e.indicesSet("input_indices",h,`max(0, min(width, ${r[h]} - 1))`)};\n ${fd(e,d,a,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${y} = originalIndices[${c}];\n var height:${y} = originalIndices[${p}];\n var width:${y} = originalIndices[${h}];\n ${o?`if (depth < 0 || depth > (${r[c]} - 1) || height < 0 || height > (${r[p]} - 1) || width < 0 || (width > ${r[h]} - 1)) {\n return ${i};\n }`:""};\n\n depth = max(0, min(depth, ${r[c]} - 1));\n height = max(0, min(height, ${r[p]} - 1));\n width = max(0, min(width, ${r[h]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${d}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"};\n\n var x111: ${y} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${y} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${y} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${y} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${y} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${y} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${y} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${y} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${y} = abs(depth - ${y}(depth1));\n var dx2: ${y} = abs(${y}(depth2) - depth);\n var dy1: ${y} = abs(height - ${y}(height1));\n var dy2: ${y} = abs(${y}(height2) - height);\n var dz1: ${y} = abs(width - ${y}(width1));\n var dz2: ${y} = abs(${y}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Bp=(e,t,r,o,i,u)=>{let a=e.dims,c=Cp(u,t.axes,a.length),p=Ap(a,o,i,t.axes),h=o.slice();o.length===0&&(h=a.map((x,E)=>x===0?1:p[E]/x),t.keepAspectRatioPolicy!=="stretch"&&(p=Ip(a,h,t)));let d=j("output",e.dataType,p.length),y=U("input",e.dataType,a.length),w=M.size(p),_=a.length===p.length&&a.every((x,E)=>x===p[E]),v=t.coordinateTransformMode==="tf_crop_and_resize",S=t.extrapolationValue,A=y.type.value,I=x=>`\n ${_?"":`\n ${Sp(t.coordinateTransformMode,A)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Pp(y,a)};\n ${xp(t.nearestMode,r,A)};\n ${Ep(y,d,a,p,h.length,c.length,v)};\n `;case"linear":return`\n ${Tp(d,a,p,h.length,c.length)};\n ${(()=>{if(a.length===2||a.length===4)return`${kp(y,d,a,v,S)}`;if(a.length===3||a.length===5)return`${Rp(y,d,a,v,S)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(a.length===2||a.length===4)return`${Op(y,d,a,p,h,c,t.cubicCoeffA,v,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${x.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",c.length).declareVariables(y,d)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${_?"output[global_idx] = input[global_idx];":`\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${y.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${y.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${h.length>0?h:""}|${i.length>0?i:""}|${c.length>0?c:""}|${_}|${a}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:h},{type:1,data:c},...Z(a,p)]})}},Dp=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},hd=(e,t)=>{let r=[],o=[],i=[],u=Dp(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");_p(e.inputs,t,u,r,o,i),e.compute(Bp(e.inputs[0],t,u,r,o,i),{inputs:[0]})},gd=e=>{let t=e.antialias,r=e.axes,o=e.coordinateTransformMode,i=e.cubicCoeffA,u=e.excludeOutside!==0,a=e.extrapolationValue,c=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return ve({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:i,excludeOutside:u,extrapolationValue:a,keepAspectRatioPolicy:c,mode:p,nearestMode:h})}});var zp,Mp,bd,wd=Y(()=>{"use strict";ye();Se();Ze();_e();zp=(e,t)=>{let[r,o,i,u]=e,{numHeads:a,rotaryEmbeddingDim:c}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input \'x\' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!M.areEqual(o.dims,[])&&!M.areEqual(o.dims,[1])&&o.dims.length!==2)throw new Error(`Input \'position_ids\' is expected to have 0, 1, or 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input \'cos_cache\' is expected to have 2 dimensions, got ${i.dims.length}`);if(u.dims.length!==2)throw new Error(`Input \'sin_cache\' is expected to have 2 dimensions, got ${u.dims.length}`);if(!M.areEqual(i.dims,u.dims))throw new Error("Inputs \'cos_cache\' and \'sin_cache\' are expected to have the same shape");if(c>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=r.dims[0],h=r.dims[r.dims.length-2],d=i.dims[0],y=M.sizeFromDimension(r.dims,1)/h,w=c===0?i.dims[1]*2:y/a;if(c>w)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(o.dims.length===2){if(p!==o.dims[0])throw new Error(`Input \'position_ids\' dimension 0 should be of size batch_size, got ${o.dims[0]}`);if(h!==o.dims[1])throw new Error(`Input \'position_ids\' dimension 1 should be of size sequence_length, got ${o.dims[1]}`)}if(w/2!==i.dims[1]&&c/2!==i.dims[1])throw new Error(`Input \'cos_cache\' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>d)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Mp=(e,t)=>{let{interleaved:r,numHeads:o,rotaryEmbeddingDim:i,scale:u}=t,a=e[0].dims[0],c=M.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=c/p,d=e[2].dims[1],y=i===0?d*2:h/o,w=new Array(a,p,h/y,y-d),_=M.computeStrides(w),v=[{type:1,data:u},{type:12,data:w},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[c,h,y,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,y,p*y,1]}):[],...Z(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],S=A=>{let I=U("input",e[0].dataType,e[0].dims.length),x=U("position_ids",e[1].dataType,e[1].dims.length),E=U("cos_cache",e[2].dataType,e[2].dims.length),P=U("sin_cache",e[3].dataType,e[3].dims.length),O=j("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),`\n ${A.declareVariables(I,x,E,P,O)}\n\n ${A.mainStart(or)}\n let half_rotary_emb_dim = uniforms.${E.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${x.broadcastedIndicesToOffset("bsnh.xy",j("",x.type.tensor,2))};\n let position_id =\n u32(${x.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});\n let j = i + select(half_rotary_emb_dim, 1, ${r});\n let re = ${I.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} -\n ${I.getByOffset("j")} * ${P.get("position_id","bsnh[3]")};\n ${O.setByOffset("i","re")}\n let im = ${I.getByOffset("i")} * ${P.get("position_id","bsnh[3]")} +\n ${I.getByOffset("j")} * ${E.get("position_id","bsnh[3]")};\n ${O.setByOffset("j","im")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${O.setByOffset("k",I.getByOffset("k"))}\n }\n }`};return{name:"RotaryEmbedding",shaderCache:{hint:ve({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:S,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(M.size(w)/or)},programUniforms:v})}},bd=(e,t)=>{zp(e.inputs,t),e.compute(Mp(e.inputs,t))}});var Up,Vp,vd,$d=Y(()=>{"use strict";ye();Se();_e();Up=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],o=e[2];if(t.dataType!==r.dataType||t.dataType!==o.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],u=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==u)throw new Error("Skip must have the same sequence length as input");if(o.dims.length!==1)throw new Error("Gamma must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Vp=(e,t,r,o)=>{let i=t.simplified,u=e[0].dims,a=M.size(u),c=u,p=a,h=u.slice(-1)[0],d=o?u.slice(0,-1).concat(1):[],y=!i&&e.length>3,w=e.length>4,_=o&&r>1,v=o&&r>2,S=r>3,A=Me(h),I=[{type:12,data:p},{type:12,data:A},{type:12,data:h},{type:1,data:t.epsilon}],x=P=>{let O=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],R=[U("x",e[0].dataType,e[0].dims,A),U("skip",e[1].dataType,e[1].dims,A),U("gamma",e[2].dataType,e[2].dims,A)];y&&R.push(U("beta",e[3].dataType,e[3].dims,A)),w&&R.push(U("bias",e[4].dataType,e[4].dims,A)),R.push(j("output",e[0].dataType,c,A)),_&&R.push(j("mean_output",1,d)),v&&R.push(j("inv_std_output",1,d)),S&&R.push(j("input_skip_bias_sum",e[0].dataType,c,A));let L=De(e[0].dataType);return`\n\n ${P.registerUniforms(O).declareVariables(...R)}\n\n ${P.mainStart()}\n ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")}\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n let offset = global_idx * hidden_size_vectorized;\n var sum = ${$t("f32",A)};\n var squareSum = ${$t("f32",A)};\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${w?"bias[i]":L+"(0.0)"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${S?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${ir(L,A,"value")};\n sum += f32_value;\n squareSum += f32_value * f32_value;\n }\n let mean = ${_t("sum",A)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${_t("squareSum",A)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon);\n ${_?"mean_output[global_idx] = mean;":""}\n ${v?"inv_std_output[global_idx] = inv_std_dev;":""}\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n output[offset + i] = (output[offset + i] ${i?"":`- ${L}(mean)`}) * ${L}(inv_std_dev) * gamma[i] ${y?"+ beta[i]":""};\n }\n }`},E=[{dims:c,dataType:e[0].dataType}];return r>1&&E.push({dims:d,dataType:1}),r>2&&E.push({dims:d,dataType:1}),r>3&&E.push({dims:u,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${A};${_};${v};${S}`,inputDependencies:e.map((P,O)=>"type")},getShaderSource:x,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(p/h/64)},programUniforms:I})}},vd=(e,t)=>{Up(e.inputs);let o=[0];e.outputCount>1&&o.push(-3),e.outputCount>2&&o.push(-3),e.outputCount>3&&o.push(3),e.compute(Vp(e.inputs,t,e.outputCount,!1),{outputs:o})}});var Wp,Gn,Np,_d,Gp,Hp,Sd,xd,Cd=Y(()=>{"use strict";ye();Se();Ze();_e();Wp=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,o)=>{if(e[o+1].dataType!==6&&e[o+1].dataType!==7)throw new Error(`Input ${o} must be an array of int32 or int64`)})},Gn=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(o=>r.push(Number(o)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(o=>r.push(Number(o)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Np=(e,t)=>{if(e.length>1){let r=Gn(e,1),o=Gn(e,2),i=Gn(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),ve({starts:r,ends:o,axes:i})}else return t},_d=(e,t,r,o,i)=>{let u=e;return e<0&&(u+=r[o[t]]),i[t]<0?Math.max(0,Math.min(u,r[o[t]]-1)):Math.max(0,Math.min(u,r[o[t]]))},Gp=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${fe("uniforms.input_shape","i",r.length)};\n let steps_i = ${fe("uniforms.steps","i",r.length)};\n let signs_i = ${fe("uniforms.signs","i",r.length)};\n let starts_i = ${fe("uniforms.starts","i",r.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,Hp=(e,t)=>{let r=e[0].dims,o=M.size(r),i=t.axes.length>0?M.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],u=Gn(e,4);u.forEach(I=>I!==0||(()=>{throw new Error("step cannot be 0")})),u.length===0&&(u=Array(i.length).fill(1));let a=t.starts.map((I,x)=>_d(I,x,r,i,u)),c=t.ends.map((I,x)=>_d(I,x,r,i,u));if(i.length!==a.length||i.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let I=0;IMath.sign(I));u.forEach((I,x,E)=>{if(I<0){let P=(c[x]-a[x])/I,O=a[x],R=O+P*u[x];a[x]=R,c[x]=O,E[x]=-I}});let h=r.slice(0);i.forEach((I,x)=>{h[I]=Math.ceil((c[I]-a[I])/u[I])});let d={dims:h,dataType:e[0].dataType},y=j("output",e[0].dataType,h.length),w=U("input",e[0].dataType,e[0].dims.length),_=M.size(h),v=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:u.length}],S=[{type:12,data:_},{type:12,data:a},{type:6,data:p},{type:12,data:u},...Z(e[0].dims,h)],A=I=>`\n ${I.registerUniforms(v).declareVariables(w,y)}\n ${Gp(w,y,r)}\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${y.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${y.setByOffset("global_idx",w.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${a.length}_${u.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:S})}},Sd=(e,t)=>{Wp(e.inputs,t);let r=Np(e.inputs,t);e.compute(Hp(e.inputs,r),{inputs:[0]})},xd=e=>{let t=e.starts,r=e.ends,o=e.axes;return ve({starts:t,ends:r,axes:o})}});var Lp,Fp,Ad,Id,Td=Y(()=>{"use strict";ye();Se();Ze();_e();Lp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Fp=(e,t)=>{let r=e.dims,o=M.size(r),i=64,u=t.axis;if(u<0&&(u=r.length+u),uI===4?`max(max(${A}.x, ${A}.y), max(${A}.z, ${A}.w))`:I===2?`max(${A}.x, ${A}.y)`:I===3?`max(max(${A}.x, ${A}.y), ${A}.z)`:A,y=U("x",e.dataType,e.dims,p),w=j("result",e.dataType,e.dims,p),_=y.type.value,v=De(e.dataType)==="f32"?`var threadMax = ${_}(-3.402823e+38f);`:`var threadMax = ${_}(-65504.0h);`,S=A=>`\n var rowMaxShared : ${_};\n var rowSumShared : ${_};\n var threadShared : array<${_}, ${i}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${_} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${_}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${A.registerUniform("packedCols","i32").declareVariables(y,w)}\n ${A.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${i};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${v}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${_}(${d("threadShared[0]",p)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${_}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${_}(${_t("threadShared[0]",p)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`;return{name:"Softmax",shaderCache:{hint:`${p}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:h}]}),getShaderSource:S}},Ad=(e,t)=>{Lp(e.inputs),e.compute(Fp(e.inputs[0],t))},Id=e=>ve({axis:e.axis})});var qp,jp,Kp,Yp,Zp,Ed,Pd,kd=Y(()=>{"use strict";ye();Se();Ze();_e();qp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},jp=(e,t)=>{let r=[],o=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),o=r.length),ve({numOutputs:o,axis:t.axis,splitSizes:r})},Kp=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${fe("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Yp=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=M.size(r),i=e[0].dataType,u=M.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),c=U("input",i,r.length),p=new Array(t.numOutputs),h=[],d=[],y=0,w=[{type:12,data:o}];for(let v=0;v`\n ${v.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(c,...a)}\n ${Kp(p.length)}\n ${Yp(a)}\n\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${c.offsetToIndices("global_idx")};\n var index = ${c.indicesGet("indices",u)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${fe("uniforms.size_in_split_axis","output_number - 1u",p.length)};\n ${c.indicesSet("indices",u,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:w})}},Ed=(e,t)=>{qp(e.inputs);let r=e.inputs.length===1?t:jp(e.inputs,t);e.compute(Zp(e.inputs,r),{inputs:[0]})},Pd=e=>{let t=e.axis,r=e.splitSizes,o=e.numOutputs<0?r.length:e.numOutputs;if(o!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ve({axis:t,numOutputs:o,splitSizes:r})}});var Od,Xp,Qp,Jp,Rd,Bd=Y(()=>{"use strict";ye();Se();_e();Od=e=>Array.from(e.getBigInt64Array(),Number),Xp=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Od(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Qp=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=Od(e[1]),o=Qp(t,r),i=M.size(o),u=e[0].dataType,a=U("input",u,t.length),c=j("output",u,o.length),p=h=>`\n const inputShape = ${a.indices(...t)};\n ${h.registerUniform("output_size","u32").declareVariables(a,c)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${c.offsetToIndices("global_idx")};\n var input_indices: ${a.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${c.indicesGet("output_indices","i")} % input_dim_i;\n\n ${a.indicesSet("input_indices","i","input_dim_value")}\n }\n ${c.setByOffset("global_idx",a.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...Z(e[0].dims,o)]}),getShaderSource:p}},Rd=e=>{Xp(e.inputs),e.compute(Jp(e.inputs),{inputs:[0]})}});var em,tm,Dd,zd=Y(()=>{"use strict";ye();Se();_e();em=(e,t,r,o,i)=>{let u=j("output_data",i,r.length,4),a=U("a_data",t[1].dataType,t[1].dims.length,4),c=U("b_data",t[2].dataType,t[2].dims.length,4),p=U("c_data",t[0].dataType,t[0].dims.length,4),h,d=(y,w,_)=>`select(${w}, ${y}, ${_})`;if(!o)h=u.setByOffset("global_idx",d(a.getByOffset("global_idx"),c.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let y=(w,_,v="")=>{let S=`a_data[index_a${_}][component_a${_}]`,A=`b_data[index_b${_}][component_b${_}]`,I=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`\n let output_indices${_} = ${u.offsetToIndices(`global_idx * 4u + ${_}u`)};\n let offset_a${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let offset_b${_} = ${c.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let offset_c${_} = ${p.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let index_a${_} = offset_a${_} / 4u;\n let index_b${_} = offset_b${_} / 4u;\n let index_c${_} = offset_c${_} / 4u;\n let component_a${_} = offset_a${_} % 4u;\n let component_b${_} = offset_b${_} % 4u;\n let component_c${_} = offset_c${_} % 4u;\n ${w}[${_}] = ${v}(${d(S,A,I)});\n `};i===9?h=`\n var data = vec4(0);\n ${y("data",0,"u32")}\n ${y("data",1,"u32")}\n ${y("data",2,"u32")}\n ${y("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=`\n ${y("output_data[global_idx]",0)}\n ${y("output_data[global_idx]",1)}\n ${y("output_data[global_idx]",2)}\n ${y("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(p,a,c,u)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${h}\n }`},tm=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,i=e[1].dataType,u=!(M.areEqual(t,r)&&M.areEqual(r,o)),a=t,c=M.size(t);if(u){let h=It.calcShape(It.calcShape(t,r,!1),o,!1);if(!h)throw new Error("Can\'t perform where op on the given tensors");a=h,c=M.size(a)}let p=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>em(h,e,a,u,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:p},...Z(o,t,r,a)]})}},Dd=e=>{e.compute(tm(e.inputs))}});var Md,Ud=Y(()=>{"use strict";Ka();Ro();Ja();ts();Vs();Zs();Oo();Uo();lu();mu();gu();$u();xu();Au();Eu();Ou();Du();Mu();Vu();Wo();Gu();qu();Ku();cd();md();In();yd();wd();$d();Cd();Td();kd();Bd();Sr();Rn();zd();Md=new Map([["Abs",[rs]],["Acos",[ns]],["Acosh",[os]],["Add",[Ws]],["ArgMax",[ja,ko]],["ArgMin",[qa,ko]],["Asin",[is]],["Asinh",[as]],["Atan",[ss]],["Atanh",[us]],["Attention",[Xa]],["AveragePool",[rd,td]],["BatchNormalization",[Qa]],["BiasAdd",[es]],["BiasSplitGelu",[Us]],["Cast",[ls,ds]],["Ceil",[ps]],["Clip",[cs]],["Concat",[Ya,Za]],["Conv",[Ho,Go]],["ConvTranspose",[du,uu]],["Cos",[ms]],["Cosh",[fs]],["CumSum",[cu,pu]],["DepthToSpace",[fu,hu]],["Div",[Ns]],["Einsum",[wu,vu]],["Elu",[hs,kn]],["Equal",[Gs]],["Erf",[gs]],["Exp",[ys]],["Expand",[Su]],["FastGelu",[Cu]],["Floor",[bs]],["FusedConv",[Ho,Go]],["Gather",[Tu,Iu]],["GatherElements",[ku,Pu]],["Gelu",[ws]],["Gemm",[Bu,Ru]],["GlobalAveragePool",[id,od]],["GlobalMaxPool",[ld,dd]],["Greater",[qs]],["GreaterOrEqual",[Ks]],["HardSigmoid",[Is,As]],["InstanceNormalization",[zu]],["LayerNormalization",[Uu]],["LeakyRelu",[vs,kn]],["Less",[js]],["LessOrEqual",[Ys]],["Log",[zs]],["MatMul",[ru]],["MatMulNBits",[Wu,Nu]],["MaxPool",[sd,ud]],["Mul",[Hs]],["MultiHeadAttention",[Fu,Lu]],["Neg",[_s]],["Not",[$s]],["Pad",[ju]],["Pow",[Ls]],["Range",[pd]],["Reciprocal",[Ss]],["ReduceMin",[Wa]],["ReduceMean",[Da]],["ReduceMax",[Va]],["ReduceSum",[Ga]],["ReduceProd",[Na]],["ReduceL1",[za]],["ReduceL2",[Ma]],["ReduceLogSum",[La]],["ReduceLogSumExp",[Ua]],["ReduceSumSquare",[Ha]],["Relu",[xs]],["Resize",[hd,gd]],["RotaryEmbedding",[bd]],["Sigmoid",[Cs]],["Sin",[Ts]],["Sinh",[Es]],["Slice",[Sd,xd]],["SkipLayerNormalization",[vd]],["Split",[Ed,Pd]],["Sqrt",[Ps]],["Softmax",[Ad,Id]],["Sub",[Fs]],["Tan",[ks]],["Tanh",[Rs]],["ThresholdedRelu",[Ds,kn]],["Tile",[Rd]],["Transpose",[_a,Sa]],["Where",[Dd]]])});var Hn,Vd=Y(()=>{"use strict";$r();Lt();_e();Hn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,o,i,u){rr(t.programInfo.name);let a=this.backend.device,c=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let p=[];for(let d of r)p.push({binding:p.length,resource:{buffer:d.buffer}});for(let d of o)p.push({binding:p.length,resource:{buffer:d.buffer}});u&&p.push({binding:p.length,resource:u});let h=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:p,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:h,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}c.setPipeline(t.computePipeline),c.setBindGroup(0,h),c.dispatchWorkgroups(...i),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(),Ht(t.programInfo.name)}dispose(){}build(t,r){rr(t.name);let o=this.backend.device,i=[];o.features.has("shader-f16")&&i.push("enable f16;");let u=va(r,this.backend.device.limits),a=t.getShaderSource(u),c=`${i.join(`\n`)}\n${u.additionalImplementations}\n${a}`,p=o.createShaderModule({code:c,label:t.name});Ve("verbose",()=>`[WebGPU] ${t.name} shader code: ${c}`);let h=o.createComputePipeline({compute:{module:p,entryPoint:"main"},layout:"auto",label:t.name});return Ht(t.name),{programInfo:t,computePipeline:h,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,o=typeof t=="number"?1:t.y||1,i=typeof t=="number"?1:t.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=u&&o<=u&&i<=u)return[r,o,i];let a=r*o*i,c=Math.ceil(Math.sqrt(a));if(c>u){if(c=Math.ceil(Math.cbrt(a)),c>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[c,c,c]}else return[c,c,1]}}});var rm,nm,Yo,Ln,Wd=Y(()=>{"use strict";$r();ye();Lt();fa();wa();Ud();Vd();rm=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let o=0;o{let o=e.name;return e.shaderCache?.hint&&(o+="["+e.shaderCache.hint+"]"),o+=":"+r+`:${rm(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},Yo=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Ln=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let o=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:o};r.features.has("chromium-experimental-timestamp-query-inside-passes")?o.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&o.push("timestamp-query"),r.features.has("shader-f16")&&o.push("shader-f16"),this.device=await r.requestDevice(i),this.adapterInfo=new Yo(await r.requestAdapterInfo()),this.gpuDataManager=ba(this),this.programManager=new Hn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,pa(t.logLevel,!!t.debug),this.device.onuncapturederror=u=>{u.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${u.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;rr(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),o=this.pendingQueries.get(t);for(let i=0;i"u"&&(this.queryTimeBase=_);let S=Number(_-this.queryTimeBase),A=Number(v-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:y.map(I=>({dims:I.dims,dataType:Gt(I.dataType)})),outputsMetadata:w.map(I=>({dims:I.dims,dataType:Gt(I.dataType)})),kernelId:a,kernelType:p,kernelName:h,programName:d,startTime:S,endTime:A});else{let I="";y.forEach((E,P)=>{I+=`input[${P}]: [${E.dims}] | ${Gt(E.dataType)}, `});let x="";w.forEach((E,P)=>{x+=`output[${P}]: [${E.dims}] | ${Gt(E.dataType)}, `}),console.log(`[profiling] kernel "${a}|${p}|${h}|${d}" ${I}${x}execution time: ${A-S} ns`)}wo("GPU",`${d}::${_}::${v}`)}t.unmap(),this.pendingQueries.delete(t)}),Ht()}run(t,r,o,i,u,a){rr(t.name);let c=[];for(let E=0;EP):o;if(y.length!==p.length)throw new Error(`Output size ${y.length} must be equal to ${p.length}.`);let w=[],_=[];for(let E=0;E=a)throw new Error(`Invalid output index: ${y[E]}`);if(y[E]===-3)continue;let P=y[E]===-1,O=y[E]===-2,R=P||O?u(p[E].dataType,p[E].dims):i(y[E],p[E].dataType,p[E].dims);if(w.push(R),R.data===0)continue;let L=this.gpuDataManager.get(R.data);if(!L)throw new Error(`no GPU data for output: ${R.data}`);if(P&&this.temporaryData.push(L),O){let N=this.kernelPersistentData.get(this.currentKernelId);N||(N=[],this.kernelPersistentData.set(this.currentKernelId,N)),N.push(L)}_.push(L)}if(c.length!==r.length||_.length!==w.length){if(_.length===0)return Ht(t.name),w;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let v;if(d){let E=0,P=[];d.forEach(N=>{let K=typeof N.data=="number"?[N.data]:N.data;if(K.length===0)return;let Q=N.type===10?2:4,he,W;N.type===10?(W=K.length>4?16:K.length>2?8:K.length*Q,he=K.length>4?16:Q*K.length):(W=K.length<=2?K.length*Q:16,he=16),E=Math.ceil(E/W)*W,P.push(E);let se=N.type===10?8:4;E+=K.length>4?Math.ceil(K.length/se)*he:K.length*Q});let O=16;E=Math.ceil(E/O)*O;let R=new ArrayBuffer(E);d.forEach((N,K)=>{let Q=P[K],he=typeof N.data=="number"?[N.data]:N.data;if(N.type===6)new Int32Array(R,Q,he.length).set(he);else if(N.type===12)new Uint32Array(R,Q,he.length).set(he);else if(N.type===10)new Uint16Array(R,Q,he.length).set(he);else if(N.type===1)new Float32Array(R,Q,he.length).set(he);else throw new Error(`Unsupported uniform type: ${Gt(N.type)}`)});let L=this.gpuDataManager.create(E,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(L.buffer,0,R,0,E),this.gpuDataManager.release(L.id),v={offset:0,size:E,buffer:L.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),A=S[1]===1&&S[2]===1,I=nm(t,r,A),x=this.programManager.getArtifact(I);if(x||(x=this.programManager.build(t,S),this.programManager.setArtifact(I,x),Ve("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),d&&x.uniformVariablesInfo){if(d.length!==x.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${x.uniformVariablesInfo.length}, got ${d.length} in program "${x.programInfo.name}".`);for(let E=0;E`[ProgramManager] run "${t.name}" (key=${I}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let E={kernelId:this.currentKernelId,programName:x.programInfo.name,inputTensorViews:r,outputTensorViews:w};this.pendingKernels.push(E),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(E)}return this.programManager.run(x,c,_,S,v),Ht(t.name),w}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,o,i){let u=Md.get(t);if(!u)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:i,kernelEntry:u[0],attributes:[u[1],o]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let o of r)this.gpuDataManager.release(o.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,o){let i=this.kernels.get(t);if(!i)throw new Error(`kernel not created: ${t}`);let u=i.kernelType,a=i.kernelName,c=i.kernelEntry,p=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${a}" is not allowed to be called recursively`);this.currentKernelId=t,p[0]&&(p[1]=p[0](p[1]),p[0]=void 0),Ve("info",()=>`[WebGPU] Start to run kernel "[${u}] ${a}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),c(r,p[1]),0}catch(d){return o.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${a}" failed. ${d}`)),1}finally{h&&o.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${u}] ${a}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,o,i){let u=this.sessionExternalDataMapping.get(t);u||(u=new Map,this.sessionExternalDataMapping.set(t,u));let a=u.get(r),c=this.gpuDataManager.registerExternalBuffer(o,i,a?.[1]);return u.set(r,[c,o]),c}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(o=>this.gpuDataManager.unregisterExternalBuffer(o[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,o){return async()=>{let i=await xo(this,t,r);return ma(i.buffer,o)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Ve("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(){Ve("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ve("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),o=t.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var Nd={};gn(Nd,{init:()=>om});var qr,Zo,om,Gd=Y(()=>{"use strict";ye();Wd();Lt();Se();qr=class e{constructor(t,r,o,i){this.module=t;this.dataType=r;this.data=o;this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=M.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=M.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=M.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(M.size(t)!==M.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Zo=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let i=t.HEAPU32,u=o>>>2;this.opKernelContext=i[u++];let a=i[u++];this.outputCount=i[u++],this.customDataOffset=i[u++],this.customDataSize=i[u++];let c=[];for(let p=0;ptypeof c=="number"?this.inputs[c]:c)??this.inputs,i=r?.outputs??[],u=(c,p,h)=>new qr(this.module,p,this.output(c,h),h),a=(c,p)=>{let h=tr(c);if(!h)throw new Error(`Unsupported data type: ${c}`);let d=h*M.size(p),y=d>0?this.backend.gpuDataManager.create(d).id:0;return new qr(this.module,c,y,p)};return this.backend.run(t,o,i,u,a,this.outputCount)}output(t,r){let o=this.module.stackSave();try{let i=this.module.stackAlloc((1+r.length)*4),u=i>>2;this.module.HEAPU32[u++]=r.length;for(let a=0;a{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let u=new Ln;await u.initialize(r,o),i("webgpu",[u,a=>u.alloc(a),a=>u.free(a),(a,c,p,h=!1)=>{if(h)Ve("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${c}, size=${p}`),u.memcpy(a,c);else{Ve("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${c}, size=${p}`);let d=t.HEAPU8.subarray(a>>>0,(a>>>0)+p);u.upload(c,d)}},async(a,c,p)=>{Ve("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${c}, size=${p}`),await u.download(a,()=>t.HEAPU8.subarray(c>>>0,(c>>>0)+p))},(a,c,p)=>u.createKernel(a,c,p,t.UTF8ToString(t._JsepGetNodeName(c))),a=>u.releaseKernel(a),(a,c,p,h)=>{Ve("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${a}, contextDataOffset=${c}`);let d=new Zo(t,u,c);return u.computeKernel(a,d,h)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else i("webnn")}});var Vi;Vi=Ei();var pl=zi(),fo,ho=!1,yn=!1,Ui=!1,ml=e=>{if(e===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},fl=()=>{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}},hl=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Wi=async e=>{if(ho)return Promise.resolve();if(yn)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Ui)throw new Error("previous call to \'initializeWebAssembly()\' failed.");yn=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,i=ml(r),u=o&&fl(),a=e.wasmPaths,c=typeof a=="string"?a:void 0,p=hl(u,i),h=typeof a=="object"?a[p]:void 0,d=!1,y=[];if(t>0&&y.push(new Promise(w=>{setTimeout(()=>{d=!0,w()},t)})),y.push(new Promise((w,_)=>{let v=i?pl:Vi,S={locateFile:(A,I)=>{if(i&&A.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Mi()],{type:"text/javascript"}));if(A.endsWith(".wasm")){if(h)return h;let x=c??I;return p==="ort-wasm-simd.wasm"?x+"ort-wasm-simd.jsep.wasm":p==="ort-wasm-simd-threaded.wasm"?x+"ort-wasm-simd-threaded.jsep.wasm":x+p}return I+A}};if(i)if(S.numThreads=r,typeof Blob>"u")S.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let A=`var ortWasmThreaded=${v.toString()};`;S.mainScriptUrlOrBlob=new Blob([A],{type:"text/javascript"})}v(S).then(A=>{yn=!1,ho=!0,fo=A,w()},A=>{yn=!1,Ui=!0,_(A)})})),await Promise.race(y),d)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Le=()=>{if(ho&&fo)return fo;throw new Error("WebAssembly is not initialized yet.")};var Fe=(e,t)=>{let r=Le(),o=r.lengthBytesUTF8(e)+1,i=r._malloc(o);return r.stringToUTF8(e,i,o),t.push(i),i},Nr=(e,t,r,o)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([i,u])=>{let a=t?t+i:i;if(typeof u=="object")Nr(u,a+".",r,o);else if(typeof u=="string"||typeof u=="number")o(a,u.toString());else if(typeof u=="boolean")o(a,u?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof u}`)})},Ue=e=>{let t=Le(),r=t.stackSave();try{let o=t.stackAlloc(8);t._OrtGetLastError(o,o+4);let i=t.HEAP32[o/4],u=t.HEAPU32[o/4+1],a=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(r)}};var Ni=e=>{let t=Le(),r=0,o=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let u=0;return e?.tag!==void 0&&(u=Fe(e.tag,o)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,u),r===0&&Ue("Can\'t create run options."),e?.extra!==void 0&&Nr(e.extra,"",new WeakSet,(a,c)=>{let p=Fe(a,o),h=Fe(c,o);t._OrtAddRunConfigEntry(r,p,h)!==0&&Ue(`Can\'t set a run config entry: ${a} - ${c}.`)}),[r,o]}catch(u){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(a=>t._free(a)),u}};var gl=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},yl=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},bl=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},wl=(e,t,r)=>{for(let o of t){let i=typeof o=="string"?o:o.name;switch(i){case"webnn":if(i="WEBNN",typeof o!="string"){let a=o;if(a?.deviceType){let c=Fe("deviceType",r),p=Fe(a.deviceType,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'deviceType\' - ${a.deviceType}.`)}if(a?.numThreads){let c=a.numThreads;(typeof c!="number"||!Number.isInteger(c)||c<0)&&(c=0);let p=Fe("numThreads",r),h=Fe(c.toString(),r);Le()._OrtAddSessionConfigEntry(e,p,h)!==0&&Ue(`Can\'t set a session config entry: \'numThreads\' - ${a.numThreads}.`)}if(a?.powerPreference){let c=Fe("powerPreference",r),p=Fe(a.powerPreference,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'powerPreference\' - ${a.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof o!="string"){let a=o;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${a.preferredLayout}`);let c=Fe("preferredLayout",r),p=Fe(a.preferredLayout,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'preferredLayout\' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let u=Fe(i,r);Le()._OrtAppendExecutionProvider(e,u)!==0&&Ue(`Can\'t append execution provider: ${i}.`)}},Gi=e=>{let t=Le(),r=0,o=[],i=e||{};bl(i);try{let u=gl(i.graphOptimizationLevel??"all"),a=yl(i.executionMode??"sequential"),c=typeof i.logId=="string"?Fe(i.logId,o):0,p=i.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=i.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let d=typeof i.optimizedModelFilePath=="string"?Fe(i.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(u,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,c,p,h,d),r===0&&Ue("Can\'t create session options."),i.executionProviders&&wl(r,i.executionProviders,o),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let y=Fe("enableGraphCapture",o),w=Fe(i.enableGraphCapture.toString(),o);t._OrtAddSessionConfigEntry(r,y,w)!==0&&Ue(`Can\'t set a session config entry: \'enableGraphCapture\' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[y,w]of Object.entries(i.freeDimensionOverrides)){if(typeof y!="string")throw new Error(`free dimension override name must be a string: ${y}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let _=Fe(y,o);t._OrtAddFreeDimensionOverride(r,_,w)!==0&&Ue(`Can\'t set a free dimension override: ${y} - ${w}.`)}return i.extra!==void 0&&Nr(i.extra,"",new WeakSet,(y,w)=>{let _=Fe(y,o),v=Fe(w,o);t._OrtAddSessionConfigEntry(r,_,v)!==0&&Ue(`Can\'t set a session config entry: ${y} - ${w}.`)}),[r,o]}catch(u){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(a=>t._free(a)),u}};ye();var Li=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(e),o=[];for await(let i of r)o.push(i);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),o=r?parseInt(r,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),u;try{u=new ArrayBuffer(o)}catch(c){if(c instanceof RangeError){let p=Math.ceil(o/65536);u=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw c}let a=0;for(;;){let{done:c,value:p}=await i.read();if(c)break;let h=p.byteLength;new Uint8Array(u,a,h).set(p),a+=h}return new Uint8Array(u,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var im=(e,t)=>{Le()._OrtInit(e,t)!==0&&Ue("Can\'t initialize onnxruntime.")},Ld=async e=>{im(e.wasm.numThreads,Gr(e.logLevel))},Fd=async(e,t)=>{{let r=(Gd(),wr(Nd)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let o=e.webgpu.adapter;if(o){if(typeof o.limits!="object"||typeof o.features!="object"||typeof o.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(o=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:u}),!o)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\')}if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",Le(),e,o)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Le(),e)}}},ar=new Map,am=e=>{let t=Le(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&Ue("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},Xo=e=>{let t=Le(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},qd=async(e,t)=>{let r,o,i=Le();Array.isArray(e)?[r,o]=e:e.buffer===i.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=Xo(e);let u=0,a=0,c=0,p=[],h=[],d=[];try{if([a,p]=Gi(t),t?.externalData&&i.mountExternalData){let x=[];for(let E of t.externalData){let P=typeof E=="string"?E:E.path;x.push(Li(typeof E=="string"?E:E.data).then(O=>{i.mountExternalData(P,O)}))}await Promise.all(x)}u=await i._OrtCreateSession(r,o,a),u===0&&Ue("Can\'t create a session.");let[y,w]=am(u),_=!!t?.enableGraphCapture,v=[],S=[],A=[];for(let x=0;xx==="gpu-buffer")&&(c=i._OrtCreateBinding(u),c===0&&Ue("Can\'t create IO binding."),I={handle:c,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(x=>yo(x))}),ar.set(u,[u,h,d,I,_,!1]),[u,v,S]}catch(y){throw h.forEach(w=>i._OrtFree(w)),d.forEach(w=>i._OrtFree(w)),c!==0&&i._OrtReleaseBinding(c),u!==0&&i._OrtReleaseSession(u),y}finally{i._free(r),a!==0&&i._OrtReleaseSessionOptions(a),p.forEach(y=>i._free(y)),i.unmountExternalData?.()}},jd=e=>{let t=Le(),r=ar.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,i,u,a,c]=r;a&&(c&&t._OrtClearBoundOutputs(a.handle),t._OrtReleaseBinding(a.handle)),t.jsepOnReleaseSession?.(e),i.forEach(p=>t._OrtFree(p)),u.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(o),ar.delete(e)},Hd=(e,t,r,o,i,u=!1)=>{if(!e){t.push(0);return}let a=Le(),c=e[0],p=e[1],h=e[3],d,y;if(c==="string"&&h==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(u&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let v=e[2].gpuBuffer,S=tr(go(c));y=p.reduce((I,x)=>I*x,1)*S;let A=a.jsepRegisterBuffer;if(!A)throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');d=A(o,i,v,y)}else{let v=e[2];if(Array.isArray(v)){y=4*v.length,d=a._malloc(y),r.push(d);let S=d/4;for(let A=0;Aa.HEAP32[v++]=A);let S=a._OrtCreateTensor(go(c),d,y,_,p.length,yo(h));S===0&&Ue(`Can\'t create tensor for input/output. session=${o}, index=${i}.`),t.push(S)}finally{a.stackRestore(w)}},Kd=async(e,t,r,o,i,u)=>{let a=Le(),c=ar.get(e);if(!c)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=c[0],h=c[1],d=c[2],y=c[3],w=c[4],_=c[5],v=t.length,S=o.length,A=0,I=[],x=[],E=[],P=[],O=a.stackSave(),R=a.stackAlloc(v*4),L=a.stackAlloc(v*4),N=a.stackAlloc(S*4),K=a.stackAlloc(S*4);try{[A,I]=Ni(u);for(let ee=0;eeNe*Ye,1);ue=Gt(ne);let Ut=y?.outputPreferredLocations[o[ee]];if(ue==="string"){if(Ut==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ne=[],Ye=le/4;for(let mt=0;mt0){let Ne=a.jsepGetBuffer;if(!Ne)throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');let Ye=Ne(le),mt=tr(ne);if(mt===void 0||!Hi(ue))throw new Error(`Unsupported data type: ${ue}`);ie=!0,We.push([ue,Be,{gpuBuffer:Ye,download:a.jsepCreateDownloader(Ye,Ge*mt,ue),dispose:()=>{a._OrtReleaseTensor(ae)}},"gpu-buffer"])}else{let Ne=bn(ue),Ye=new Ne(Ge);new Uint8Array(Ye.buffer,Ye.byteOffset,Ye.byteLength).set(a.HEAPU8.subarray(le,le+Ye.byteLength)),We.push([ue,Be,Ye,"cpu"])}}finally{a.stackRestore(Ae),ue==="string"&&le&&a._free(le),ie||a._OrtReleaseTensor(ae)}}return y&&!w&&(a._OrtClearBoundOutputs(y.handle),ar.set(e,[p,h,d,y,w,!1])),We}finally{a.stackRestore(O),x.forEach(Q=>a._OrtReleaseTensor(Q)),E.forEach(Q=>a._OrtReleaseTensor(Q)),P.forEach(Q=>a._free(Q)),A!==0&&a._OrtReleaseRunOptions(A),I.forEach(Q=>a._free(Q))}},Yd=e=>{let t=Le(),r=ar.get(e);if(!r)throw new Error("invalid session id");let o=r[0],i=t._OrtEndProfiling(o);i===0&&Ue("Can\'t get an profile file name."),t._OrtFree(i)},Zd=e=>{let t=[];for(let r of e){let o=r[2];!Array.isArray(o)&&"buffer"in o&&t.push(o.buffer)}return t};self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Wi(r.wasm).then(()=>{Ld(r).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:i}=r;Fd(i,o).then(()=>{postMessage({type:t})},u=>{postMessage({type:t,err:u})});break}case"copy-from":{let{buffer:o}=r,i=Xo(o);postMessage({type:t,out:i});break}case"create":{let{model:o,options:i}=r;qd(o,i).then(u=>{postMessage({type:t,out:u})},u=>{postMessage({type:t,err:u})});break}case"release":jd(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:i,inputs:u,outputIndices:a,options:c}=r;Kd(o,i,u,a,new Array(a.length).fill(null),c).then(p=>{p.some(h=>h[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:p},Zd([...u,...p]))},p=>{postMessage({type:t,err:p})});break}case"end-profiling":Yd(r),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}};})();\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n'}),Fr,zt,En,la,ua,No,Ai,tn,rn,Zf,da,Jf,em,tm,rm,nm,am,im,sm=te(()=>{var t;rr(),_w(),ta(),Fr=()=>!!Ue.wasm.proxy&&typeof document<"u",En=!1,la=!1,ua=!1,Ai=new Map,tn=(e,r)=>{let n=Ai.get(e);n?n.push(r):Ai.set(e,[r])},rn=()=>{if(En||!la||ua||!zt)throw new Error("worker not ready")},Zf=e=>{switch(e.data.type){case"init-wasm":En=!1,e.data.err?(ua=!0,No[1](e.data.err)):(la=!0,No[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Ai.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},da=typeof document<"u"?(t=document==null?void 0:document.currentScript)==null?void 0:t.src:void 0,Jf=async()=>{if(!la){if(En)throw new Error("multiple calls to 'initWasm()' detected.");if(ua)throw new Error("previous call to 'initWasm()' failed.");if(En=!0,Fr())return Ue.wasm.wasmPaths===void 0&&da&&da.indexOf("blob:")!==0&&(Ue.wasm.wasmPaths=da.substr(0,+da.lastIndexOf("/")+1)),new Promise((e,r)=>{zt==null||zt.terminate();let n=URL.createObjectURL(new Blob([yw()],{type:"text/javascript"}));zt=new Worker(n,{name:"ort-wasm-proxy-worker"}),zt.onerror=s=>r(s),zt.onmessage=Zf,URL.revokeObjectURL(n),No=[e,r];let a={type:"init-wasm",in:Ue};zt.postMessage(a)});try{await mu(Ue.wasm),await Gf(Ue),la=!0}catch(e){throw ua=!0,e}finally{En=!1}}},em=async e=>{if(Fr())return rn(),new Promise((r,n)=>{tn("init-ep",[r,n]);let a={type:"init-ep",in:{epName:e,env:Ue}};zt.postMessage(a)});await Hf(Ue,e)},tm=async e=>Fr()?(rn(),new Promise((r,n)=>{tn("copy-from",[r,n]);let a={type:"copy-from",in:{buffer:e}};zt.postMessage(a,[e.buffer])})):Bo(e),rm=async(e,r)=>{if(Fr()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return rn(),new Promise((n,a)=>{tn("create",[n,a]);let s={type:"create",in:{model:e,options:{...r}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),zt.postMessage(s,i)})}else return qf(e,r)},nm=async e=>{if(Fr())return rn(),new Promise((r,n)=>{tn("release",[r,n]);let a={type:"release",in:e};zt.postMessage(a)});Kf(e)},am=async(e,r,n,a,s,i)=>{if(Fr()){if(n.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return rn(),new Promise((o,l)=>{tn("run",[o,l]);let u=n,d={type:"run",in:{sessionId:e,inputIndices:r,inputs:u,outputIndices:a,options:i}};zt.postMessage(d,Qf(u))})}else return Yf(e,r,n,a,s,i)},im=async e=>{if(Fr())return rn(),new Promise((r,n)=>{tn("end-profiling",[r,n]);let a={type:"end-profiling",in:e};zt.postMessage(a)});Xf(e)}}),Fo,om,lm,ww=te(()=>{rr(),sm(),xe(),$u(),Fo=(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()}`)}},om=t=>{switch(t[3]){case"cpu":return new kt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Vs(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:a}=t[2];return kt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:n,dispose:a})}default:throw new Error(`invalid data location: ${t[3]}`)}},lm=class{async fetchModelAndCopyToWasmMemory(t){return tm(await di(t))}async loadModel(t,e){tr();let r;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?r=await di(t):r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames]=await rm(r,e),Yt()}async dispose(){return nm(this.sessionId)}async run(t,e,r){tr();let n=[],a=[];Object.entries(t).forEach(h=>{let m=h[0],g=h[1],p=this.inputNames.indexOf(m);if(p===-1)throw new Error(`invalid input '${m}'`);n.push(g),a.push(p)});let s=[],i=[];Object.entries(e).forEach(h=>{let m=h[0],g=h[1],p=this.outputNames.indexOf(m);if(p===-1)throw new Error(`invalid output '${m}'`);s.push(g),i.push(p)});let o=n.map((h,m)=>Fo(h,()=>`input "${this.inputNames[a[m]]}"`)),l=s.map((h,m)=>h?Fo(h,()=>`output "${this.outputNames[i[m]]}"`):null),u=await am(this.sessionId,a,o,i,l,r),d={};for(let h=0;h{rr(),sm(),ww(),um=()=>{if((typeof Ue.wasm.initTimeout!="number"||Ue.wasm.initTimeout<0)&&(Ue.wasm.initTimeout=0),typeof Ue.wasm.simd!="boolean"&&(Ue.wasm.simd=!0),typeof Ue.wasm.proxy!="boolean"&&(Ue.wasm.proxy=!1),typeof Ue.wasm.trace!="boolean"&&(Ue.wasm.trace=!1),typeof Ue.wasm.numThreads!="number"||!Number.isInteger(Ue.wasm.numThreads)||Ue.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Ue.wasm.numThreads=1);let t=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Ue.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},dm=class{async init(t){um(),await Jf(),await em(t)}async createInferenceSessionHandler(t,e){let r=new lm;return await r.loadModel(t,e),Promise.resolve(r)}}}),cm={};$n(cm,{wasmBackend:()=>pm});var pm,vw=te(()=>{bw(),pm=new dm});rr(),rr(),rr();var $w="1.18.0",xw=tu;{let t=(vw(),jr(cm)).wasmBackend;qr("webgpu",t,5),qr("webnn",t,5),qr("cpu",t,10),qr("wasm",t,10)}Object.defineProperty(Ue.versions,"web",{value:$w,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 Sw=Object.freeze({__proto__:null,get InferenceSession(){return Ps},get TRACE(){return Jn},get TRACE_FUNC_BEGIN(){return tr},get TRACE_FUNC_END(){return Yt},get Tensor(){return kt},get TrainingSession(){return Rs},default:xw,get env(){return Ue},get registerBackend(){return qr}});const kw=(t,e)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];const n=r.getContext("2d");if(n!=null){let a,s;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],s=t.dims[3]):(a=t.dims[3],s=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 d=s*a;let h=0,m=d,g=d*2,p=-1;i==="RGBA"?(h=0,m=d,g=d*2,p=d*3):i==="RGB"?(h=0,m=d,g=d*2):i==="RBG"&&(h=0,g=d,m=d*2);for(let w=0;w{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(r!=null){let a,s,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],s=t.dims[1],i=t.dims[3]):(a=t.dims[3],s=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,d;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?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));const h=s*a;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 m=4;let g=0,p=1,w=2,v=3,S=0,$=h,E=h*2,T=-1;o==="RGBA"?(S=0,$=h,E=h*2,T=h*3):o==="RGB"?(S=0,$=h,E=h*2):o==="RBG"&&(S=0,E=h,$=h*2),n=r.createImageData(a,s);for(let A=0;A{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:n}=e,a=e.norm??{mean:255,bias:0};let s,i;typeof a.mean=="number"?s=[a.mean,a.mean,a.mean,a.mean]:s=[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],typeof a.bias=="number"?i=[a.bias,a.bias,a.bias,a.bias]:i=[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];const o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=r*n,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let h=4,m=0,g=1,p=2,w=3,v=0,S=u,$=u*2,E=-1;o==="RGB"&&(h=3,m=0,g=1,p=2,w=-1),l==="RGBA"?E=u*3:l==="RBG"?(v=0,$=u,S=u*2):l==="BGR"&&($=0,S=u,v=u*2);for(let A=0;A{const r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,n=typeof ImageData<"u"&&t instanceof ImageData,a=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,s=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=d=>d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){const d=l();d.width=t.width,d.height=t.height;const h=u(d);if(h!=null){let m=t.height,g=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,g=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=m,o.width=g}else o.tensorFormat="RGBA",o.height=m,o.width=g;h.drawImage(t,0,0),i=h.getImageData(0,0,g,m).data}else throw new Error("Can not access image data")}else if(n){let d,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,h=e.resizedWidth):(d=t.height,h=t.width),e!==void 0&&(o=e),o.format="RGBA",o.height=d,o.width=h,e!==void 0){const m=l();m.width=h,m.height=d;const g=u(m);if(g!=null)g.putImageData(t,0,0),i=g.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else i=t.data}else if(a){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");const d=l();d.width=t.width,d.height=t.height;const h=u(d);if(h!=null){const m=t.height,g=t.width;return h.drawImage(t,0,0,g,m),i=h.getImageData(0,0,g,m).data,o.height=m,o.width=g,Lo(i,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((d,h)=>{const m=l(),g=u(m);if(!t||!g)return h();const p=new Image;p.crossOrigin="Anonymous",p.src=t,p.onload=()=>{m.width=p.width,m.height=p.height,g.drawImage(p,0,0,m.width,m.height);const w=g.getImageData(0,0,m.width,m.height);o.height=m.height,o.width=m.width,d(Lo(w.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Lo(i,o);throw new Error("Input data provided is not supported - aborted tensor creation")},Tw=(t,e)=>{const{width:r,height:n,download:a,dispose:s}=e,i=[1,n,r,4];return new mr({location:"texture",type:"float32",texture:t,dims:i,download:a,dispose:s})},Aw=(t,e)=>{const{dataType:r,dims:n,download:a,dispose:s}=e;return new mr({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:s})},Iw=(t,e,r)=>new mr({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]}),Cn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Ii=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let hm=!1;const Mw=()=>{if(!hm){hm=!0;const t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;t&&(Cn.set("int64",BigInt64Array),Ii.set(BigInt64Array,"int64")),e&&(Cn.set("uint64",BigUint64Array),Ii.set(BigUint64Array,"uint64")),r?(Cn.set("float16",Float16Array),Ii.set(Float16Array,"float16")):Cn.set("float16",Uint16Array)}},Ow=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new mr(t.type,t.data,e);case"cpu-pinned":return new mr({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new mr({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new mr({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let mr=class{constructor(e,r,n){Mw();let a,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,a=e.type,s=e.dims,e.location){case"cpu-pinned":{const o=Cn.get(a);if(!o)throw new TypeError(`unsupported type "${a}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(a!=="float32")throw new TypeError(`unsupported type "${a}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(a!=="float32"&&a!=="float16"&&a!=="int32"&&a!=="int64"&&a!=="uint32"&&a!=="uint8"&&a!=="bool")throw new TypeError(`unsupported type "${a}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,l;if(typeof e=="string")if(a=e,l=n,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");o=r}else{const u=Cn.get(e);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){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(r,BigInt):o=u.from(r)}else if(r instanceof u)o=r;else throw new TypeError(`A ${a} tensor's data must be type of ${u}`)}else if(l=r,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")a="string",o=e;else if(u==="boolean")a="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else{const u=Ii.get(e.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);a=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");s=l,this.cpuData=o,this.dataLocation="cpu"}const i=Ow(s);if(this.cpuData&&i!==this.cpuData.length)throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=a,this.dims=s,this.size=i}static async fromImage(e,r){return Cw(e,r)}static fromTexture(e,r){return Tw(e,r)}static fromGpuBuffer(e,r){return Aw(e,r)}static fromPinnedBuffer(e,r,n){return Iw(e,r,n)}toDataURL(e){return kw(this,e)}toImageData(e){return Ew(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return zw(this,e)}};const Pw=mr,ca=[];let Uo,nn;Hr.IS_NODE_ENV?(nn=Ve??vr,ca.push("cpu"),Uo=["cpu"]):(nn=Sw,Hr.IS_WEBGPU_AVAILABLE&&ca.push("webgpu"),ca.push("wasm"),Uo=["wasm"]);const Rw=nn.InferenceSession;function Bw(t){let e=Uo;if(t){if(!ca.includes(t))throw new Error(`Unsupported device: "${t}". Should be one of: ${ca.join(", ")}.`);e=[t]}return e}async function fm(t,e){return await Rw.create(t,e)}function mm(t){return t instanceof nn.Tensor}const lr=nn==null?void 0:nn.env;lr!=null&&lr.wasm&&(lr.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/",lr.wasm.proxy=!Hr.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(lr.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(lr.wasm.simd=!1));function Dw(){var t;return(t=lr==null?void 0:lr.wasm)==null?void 0:t.proxy}Mt.backends.onnx=lr;const Tn=async(t,e,r)=>{const n=await fm(new Uint8Array(t),e);return async a=>{const s=Object.fromEntries(Object.entries(a).map(([o,l])=>[o,l.ort_tensor])),i=await n.run(s);return Array.isArray(r)?r.map(o=>new ce(i[o])):new ce(i[r])}};class pa{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Tn([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=Tn([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=Tn([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=Tn([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=Tn([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=Tn([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}}B(pa,"session_options",{});const gm=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 ce{constructor(...e){B(this,"ort_tensor");return mm(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Pw(e[0],e[1],e[2]),new Proxy(this,{get:(r,n)=>{if(typeof n=="string"){let a=Number(n);if(Number.isInteger(a))return r._getitem(a)}return r[n]},set:(r,n,a)=>r[n]=a})}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,...r]=this.dims;if(r.length>0){const n=r.reduce((a,s)=>a*s);for(let a=0;a0){const a=n.reduce((s,i)=>s*i);return this._subarray(e,a,n)}else return new ce(this.type,[this.data[e]],n)}indexOf(e){const r=this.data;for(let n=0;nm)throw new Error(`Invalid slice: ${d}`);let g=[Math.max(h,0),Math.min(m,this.dims[u])];n.push(g),r.push(g[1]-g[0])}else throw new Error(`Invalid slice: ${d}`)}let a=n.map(([u,d])=>d-u),s=a.reduce((u,d)=>u*d);const i=this.data;let o=new i.constructor(s);const l=this.stride();for(let u=0;u=0;--h){const g=a[h];d+=(m%g+n[h][0])*l[h],m=Math.floor(m/g)}o[u]=i[d]}return new ce(this.type,o,r)}permute(...e){return Fw(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,n=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);const a=this.data;if(r===null){let o=a.reduce((l,u)=>l+u**e,0)**(1/e);return new ce(this.type,[o],[])}r=gr(r,this.dims.length);const s=this.dims.slice();s[r]=1;const i=new a.constructor(a.length/this.dims[r]);for(let o=0;o=0;--u){const m=this.dims[u];if(u!==r){const g=d%m;l+=g*h,h*=s[u]}d=Math.floor(d/m)}i[l]+=a[o]**e}if(e!==1)for(let o=0;o=0;--l){const h=this.dims[l];if(l!==r){const m=u%h;o+=m*d,d*=this.dims[l]}u=Math.floor(u/h)}a[i]/=s[o]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Vw(this.dims)}squeeze(e=null){return new ce(this.type,this.data,ym(this.dims,e))}squeeze_(e=null){return this.dims=ym(this.dims,e),this}unsqueeze(e=null){return new ce(this.type,this.data,wm(this.dims,e))}unsqueeze_(e=null){return this.dims=wm(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),a=this.dims.slice(e,r+1),s=this.dims.slice(r+1);return this.dims=[...n,a.reduce((i,o)=>i*o,1),...s],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let a=0;ao!==r?s*i:s,1);e[r]=n.length/a}return new ce(this.type,n,e)}neg_(){const e=this.data;for(let r=0;rs*i);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let a=t;for(let s=e.length-1;s>=0;s--)a=a.reduce((i,o)=>{let l=i[i.length-1];return l.lengthr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,n)=>r!==1||!e.includes(n))),t}function wm(t,e){return e=gr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function gr(t,e,r=null,n=!0){if(n&&(t<-e||t>=e))throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<0&&(t=(t%e+e)%e),t}function Xt(t,e=0){e=gr(e,t[0].dims.length);const r=t[0].dims.slice();r[e]=t.reduce((i,o)=>i+o.dims[e],0);const n=r.reduce((i,o)=>i*o,1),a=new t[0].data.constructor(n),s=t[0].type;if(e===0){let i=0;for(const o of t){const l=o.data;a.set(l,i),i+=l.length}}else{let i=0;for(let o=0;o=0;--m){const w=u[m];let v=g%w;m===e&&(v+=i),h+=v*p,p*=r[m],g=Math.floor(g/w)}a[h]=l[d]}i+=u[e]}}return new ce(s,a,r)}function ha(t,e=0){return Xt(t.map(r=>r.unsqueeze(e)),e)}function Ww(t,e=null,r=1,n=!1){const a=t.data,s=t.dims;if(e===null){const m=a.reduce((v,S)=>v+S,0)/a.length,g=Math.sqrt(a.reduce((v,S)=>v+(S-m)**2,0)/(a.length-r)),p=new ce(t.type,[m],[]);return[new ce(t.type,[g],[]),p]}e=gr(e,s.length);const i=Vo(t,e,n),o=i.data,l=s.slice();l[e]=1;const u=new a.constructor(a.length/s[e]);for(let h=0;h=0;--g){const v=s[g];if(g!==e){const S=p%v;m+=S*w,w*=l[g]}p=Math.floor(p/v)}u[m]+=(a[h]-o[m])**2}for(let h=0;hl+u,0);return new ce(t.type,[o/n.length],[])}const a=t.dims;e=gr(e,a.length);const s=a.slice();s[e]=1;const i=new n.constructor(n.length/a[e]);for(let o=0;o=0;--u){const m=a[u];if(u!==e){const g=d%m;l+=g*h,h*=s[u]}d=Math.floor(d/m)}i[l]+=n[o]}if(a[e]!==1)for(let o=0;o=0;--r)e[r]=n,n*=t[r];return e}function Go(t,e,r,n){const a=t.reduce((s,i)=>s*i,1);return new ce(r,new n(a).fill(e),t)}function Gw(t,e){let r,n;return r="float32",n=Float32Array,Go(t,e,r,n)}function Hw(t,e){return Gw(t.dims,e)}function In(t){return Go(t,1n,"int64",BigInt64Array)}function jw(t){return In(t.dims)}function qw(t){return Go(t,0n,"int64",BigInt64Array)}function Kw(t){return qw(t.dims)}function Yw(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 r=e==="binary",n=r?"int8":"uint8",a=r?Int8Array:Uint8Array,s=t.data,i=new a(s.length/8);for(let o=0;o0?1:0,u=Math.floor(o/8),d=o%8;i[u]|=l<<7-d,r&&d===0&&(i[u]-=128)}return new ce(n,i,[t.dims[0],t.dims[1]/8])}class Xw{constructor(e=(n,a)=>n>a,r=1/0){this._heap=[],this._comparator=e,this._maxSize=r}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const r of e)if(this.size0&&this._swap(0,r),this._heap.pop(),this._siftDown(),e}replace(e){const r=this.peek();return this._heap[0]=e,this._siftDown(),r}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,r){return this._comparator(this._heap[e],this._heap[r])}_swap(e,r){const n=this._heap[e];this._heap[e]=this._heap[r],this._heap[r]=n}_siftUp(){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 a=new fa(this.bosTokenId,0,0,0,0),s=new fa(this.eosTokenId,1,this.len,0,0);this.nodes.push(a.clone()),this.nodes.push(s.clone()),this.beginNodes[this.len].push(s),this.endNodes[0].push(a)}insert(e,r,n,a){const s=this.nodes.length,i=new fa(a,s,e,r,n);this.beginNodes[e].push(i),this.endNodes[e+r].push(i),this.nodes.push(i)}viterbi(){const e=this.len;let r=0;for(;r<=e;){if(this.beginNodes[r].length==0)return[];for(let o of this.beginNodes[r]){o.prev=null;let l=0,u=null;for(let d of this.endNodes[r]){const h=d.backtraceScore+o.score;(u===null||h>l)&&(u=d.clone(),l=h)}if(u!==null)o.prev=u,o.backtraceScore=l;else return[]}++r}const n=[],s=this.beginNodes[e][0].prev;if(s===null)return[];let i=s.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){return this.viterbi().map(r=>this.piece(r))}tokenIds(){return this.viterbi().map(r=>r.tokenId)}}class fa{constructor(e,r,n,a,s){this.tokenId=e,this.nodeId=r,this.pos=n,this.length=a,this.score=s,this.prev=null,this.backtraceScore=0}clone(){const e=new fa(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}var U=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),bm=Object.freeze({set:U.Set,for:U.For,in:U.In,is:U.Is,if:U.If,else:U.Else,endif:U.EndIf,elif:U.ElseIf,endfor:U.EndFor,and:U.And,or:U.Or,not:U.Not,"not in":U.NotIn,true:U.BooleanLiteral,false:U.BooleanLiteral}),an=class{constructor(t,e){this.value=t,this.type=e}};function vm(t){return/\w/.test(t)}function Ho(t){return/[0-9]/.test(t)}var Jw=[["{%",U.OpenStatement],["%}",U.CloseStatement],["{{",U.OpenExpression],["}}",U.CloseExpression],["(",U.OpenParen],[")",U.CloseParen],["{",U.OpenCurlyBracket],["}",U.CloseCurlyBracket],["[",U.OpenSquareBracket],["]",U.CloseSquareBracket],[",",U.Comma],[".",U.Dot],[":",U.Colon],["|",U.Pipe],["<=",U.ComparisonBinaryOperator],[">=",U.ComparisonBinaryOperator],["==",U.ComparisonBinaryOperator],["!=",U.ComparisonBinaryOperator],["<",U.ComparisonBinaryOperator],[">",U.ComparisonBinaryOperator],["+",U.AdditiveBinaryOperator],["-",U.AdditiveBinaryOperator],["*",U.MultiplicativeBinaryOperator],["/",U.MultiplicativeBinaryOperator],["%",U.MultiplicativeBinaryOperator],["=",U.Equals]],eb=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function tb(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 rb(t,e={}){var i,o,l;const r=[],n=tb(t,e);let a=0;const s=u=>{let d="";for(;u(n[a]);){if(n[a]==="\\"){if(++a,a>=n.length)throw new SyntaxError("Unexpected end of input");const h=n[a++],m=eb.get(h);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${h}`);d+=m;continue}if(d+=n[a++],a>=n.length)throw new SyntaxError("Unexpected end of input")}return d};e:for(;a0){r.push(new an(h,U.Text));continue}}s(h=>/\s/.test(h));const d=n[a];if(d==="-"||d==="+"){const h=(o=r.at(-1))==null?void 0:o.type;if(h===U.Text||h===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(h){case U.Identifier:case U.NumericLiteral:case U.BooleanLiteral:case U.StringLiteral:case U.CloseParen:case U.CloseSquareBracket:break;default:{++a;const m=s(Ho);r.push(new an(`${d}${m}`,m.length>0?U.NumericLiteral:U.UnaryOperator));continue}}}for(const[h,m]of Jw)if(n.slice(a,a+h.length)===h){r.push(new an(h,m)),a+=h.length;continue e}if(d==="'"||d==='"'){++a;const h=s(m=>m!==d);r.push(new an(h,U.StringLiteral)),++a;continue}if(Ho(d)){const h=s(Ho);r.push(new an(h,U.NumericLiteral));continue}if(vm(d)){const h=s(vm),m=Object.hasOwn(bm,h)?bm[h]:U.Identifier;m===U.In&&((l=r.at(-1))==null?void 0:l.type)===U.Not?(r.pop(),r.push(new an("not in",U.NotIn))):r.push(new an(h,m));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var ma=class{constructor(){B(this,"type","Statement")}},nb=class extends ma{constructor(e){super();B(this,"type","Program");this.body=e}},$m=class extends ma{constructor(e,r,n){super();B(this,"type","If");this.test=e,this.body=r,this.alternate=n}},ab=class extends ma{constructor(e,r,n){super();B(this,"type","For");this.loopvar=e,this.iterable=r,this.body=n}},ib=class extends ma{constructor(e,r){super();B(this,"type","Set");this.assignee=e,this.value=r}},_r=class extends ma{constructor(){super(...arguments);B(this,"type","Expression")}},sb=class extends _r{constructor(e,r,n){super();B(this,"type","MemberExpression");this.object=e,this.property=r,this.computed=n}},ob=class extends _r{constructor(e,r){super();B(this,"type","CallExpression");this.callee=e,this.args=r}},Mn=class extends _r{constructor(e){super();B(this,"type","Identifier");this.value=e}},On=class extends _r{constructor(e){super();B(this,"type","Literal");this.value=e}},lb=class extends On{constructor(){super(...arguments);B(this,"type","NumericLiteral")}},xm=class extends On{constructor(){super(...arguments);B(this,"type","StringLiteral")}},Sm=class extends On{constructor(){super(...arguments);B(this,"type","BooleanLiteral")}},ub=class extends On{constructor(){super(...arguments);B(this,"type","ArrayLiteral")}},km=class extends On{constructor(){super(...arguments);B(this,"type","TupleLiteral")}},db=class extends On{constructor(){super(...arguments);B(this,"type","ObjectLiteral")}},ga=class extends _r{constructor(e,r,n){super();B(this,"type","BinaryExpression");this.operator=e,this.left=r,this.right=n}},cb=class extends _r{constructor(e,r){super();B(this,"type","FilterExpression");this.operand=e,this.filter=r}},pb=class extends _r{constructor(e,r,n){super();B(this,"type","TestExpression");this.operand=e,this.negate=r,this.test=n}},hb=class extends _r{constructor(e,r){super();B(this,"type","UnaryExpression");this.operator=e,this.argument=r}},fb=class extends _r{constructor(e=void 0,r=void 0,n=void 0){super();B(this,"type","SliceExpression");this.start=e,this.stop=r,this.step=n}},mb=class extends _r{constructor(e,r){super();B(this,"type","KeywordArgumentExpression");this.key=e,this.value=r}};function gb(t){const e=new nb([]);let r=0;function n(D,M){const G=t[r++];if(!G||G.type!==D)throw new Error(`Parser Error: ${M}. ${G.type} !== ${D}.`);return G}function a(){switch(t[r].type){case U.Text:return o();case U.OpenStatement:return l();case U.OpenExpression:return u();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function s(...D){return r+D.length<=t.length&&D.some((M,G)=>M!==t[r+G].type)}function i(...D){return r+D.length<=t.length&&D.every((M,G)=>M===t[r+G].type)}function o(){return new xm(n(U.Text,"Expected text token").value)}function l(){n(U.OpenStatement,"Expected opening statement token");let D;switch(t[r].type){case U.Set:++r,D=d(),n(U.CloseStatement,"Expected closing statement token");break;case U.If:++r,D=h(),n(U.OpenStatement,"Expected {% token"),n(U.EndIf,"Expected endif token"),n(U.CloseStatement,"Expected %} token");break;case U.For:++r,D=g(),n(U.OpenStatement,"Expected {% token"),n(U.EndFor,"Expected endfor token"),n(U.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type}`)}return D}function u(){n(U.OpenExpression,"Expected opening expression token");const D=p();return n(U.CloseExpression,"Expected closing expression token"),D}function d(){const D=p();if(i(U.Equals)){++r;const M=d();return new ib(D,M)}return D}function h(){var K,pe,le,N,ae,de,Se,Te;const D=p();n(U.CloseStatement,"Expected closing statement token");const M=[],G=[];for(;!(((K=t[r])==null?void 0:K.type)===U.OpenStatement&&(((pe=t[r+1])==null?void 0:pe.type)===U.ElseIf||((le=t[r+1])==null?void 0:le.type)===U.Else||((N=t[r+1])==null?void 0:N.type)===U.EndIf));)M.push(a());if(((ae=t[r])==null?void 0:ae.type)===U.OpenStatement&&((de=t[r+1])==null?void 0:de.type)!==U.EndIf)if(++r,i(U.ElseIf))n(U.ElseIf,"Expected elseif token"),G.push(h());else for(n(U.Else,"Expected else token"),n(U.CloseStatement,"Expected closing statement token");!(((Se=t[r])==null?void 0:Se.type)===U.OpenStatement&&((Te=t[r+1])==null?void 0:Te.type)===U.EndIf);)G.push(a());return new $m(D,M,G)}function m(D=!1){const M=D?se:p,G=[M()],K=i(U.Comma);for(;K&&(++r,G.push(M()),!!i(U.Comma)););return K?new km(G):G[0]}function g(){const D=m(!0);if(!(D instanceof Mn||D instanceof km))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${D.type} instead`);n(U.In,"Expected `in` keyword following loop variable");const M=p();n(U.CloseStatement,"Expected closing statement token");const G=[];for(;s(U.OpenStatement,U.EndFor);)G.push(a());return new ab(D,M,G)}function p(){return w()}function w(){const D=v();if(i(U.If)){++r;const M=v();n(U.Else,"Expected else token");const G=v();return new $m(M,[D],[G])}return D}function v(){let D=S();for(;i(U.Or);){const M=t[r];++r;const G=S();D=new ga(M,D,G)}return D}function S(){let D=$();for(;i(U.And);){const M=t[r];++r;const G=$();D=new ga(M,D,G)}return D}function $(){let D;for(;i(U.Not);){const M=t[r];++r;const G=$();D=new hb(M,G)}return D??E()}function E(){let D=T();for(;i(U.ComparisonBinaryOperator)||i(U.In)||i(U.NotIn);){const M=t[r];++r;const G=T();D=new ga(M,D,G)}return D}function T(){let D=fe();for(;i(U.AdditiveBinaryOperator);){const M=t[r];++r;const G=fe();D=new ga(M,D,G)}return D}function A(){const D=q();return i(U.OpenParen)?z(D):D}function z(D){let M=new ob(D,R());return i(U.OpenParen)&&(M=z(M)),M}function R(){n(U.OpenParen,"Expected opening parenthesis for arguments list");const D=V();return n(U.CloseParen,"Expected closing parenthesis for arguments list"),D}function V(){const D=[];for(;!i(U.CloseParen);){let M=p();if(i(U.Equals)){if(++r,!(M instanceof Mn))throw new SyntaxError("Expected identifier for keyword argument");const G=p();M=new mb(M,G)}D.push(M),i(U.Comma)&&++r}return D}function j(){const D=[];let M=!1;for(;!i(U.CloseSquareBracket);)i(U.Colon)?(D.push(void 0),++r,M=!0):(D.push(p()),i(U.Colon)&&(++r,M=!0));if(D.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(M){if(D.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new fb(...D)}return D[0]}function q(){let D=se();for(;i(U.Dot)||i(U.OpenSquareBracket);){const M=t[r];++r;let G;const K=M.type!==U.Dot;if(K)G=j(),n(U.CloseSquareBracket,"Expected closing square bracket");else if(G=se(),G.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");D=new sb(D,G,K)}return D}function fe(){let D=ee();for(;i(U.MultiplicativeBinaryOperator);){const M=t[r];++r;const G=ee();D=new ga(M,D,G)}return D}function ee(){let D=ne();for(;i(U.Is);){++r;const M=i(U.Not);M&&++r;let G=se();if(G instanceof Sm&&(G=new Mn(G.value.toString())),!(G instanceof Mn))throw new SyntaxError("Expected identifier for the test");D=new pb(D,M,G)}return D}function ne(){let D=A();for(;i(U.Pipe);){++r;let M=se();if(!(M instanceof Mn))throw new SyntaxError("Expected identifier for the filter");i(U.OpenParen)&&(M=z(M)),D=new cb(D,M)}return D}function se(){const D=t[r];switch(D.type){case U.NumericLiteral:return++r,new lb(Number(D.value));case U.StringLiteral:return++r,new xm(D.value);case U.BooleanLiteral:return++r,new Sm(D.value==="true");case U.Identifier:return++r,new Mn(D.value);case U.OpenParen:{++r;const M=m();if(t[r].type!==U.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,M}case U.OpenSquareBracket:{++r;const M=[];for(;!i(U.CloseSquareBracket);)M.push(p()),i(U.Comma)&&++r;return++r,new ub(M)}case U.OpenCurlyBracket:{++r;const M=new Map;for(;!i(U.CloseCurlyBracket);){const G=p();n(U.Colon,"Expected colon between key and value in object literal");const K=p();M.set(G,K),i(U.Comma)&&++r}return++r,new db(M)}default:throw new SyntaxError(`Unexpected token: ${D.type}`)}}for(;r=0?(e=(e??(e=0))<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??(r=t.length))<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??(e=t.length-1))<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??(r=-1))<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const s=[];for(let i=e;a*ie.toUpperCase())}var Er=class{constructor(t=void 0){B(this,"type","RuntimeValue");B(this,"value");B(this,"builtins",new Map);this.value=t}__bool__(){return new at(!!this.value)}},Ye=class extends Er{constructor(){super(...arguments);B(this,"type","NumericValue")}},Re=class extends Er{constructor(){super(...arguments);B(this,"type","StringValue");B(this,"builtins",new Map([["upper",new Cr(()=>new Re(this.value.toUpperCase()))],["lower",new Cr(()=>new Re(this.value.toLowerCase()))],["strip",new Cr(()=>new Re(this.value.trim()))],["title",new Cr(()=>new Re(Cm(this.value)))],["length",new Ye(this.value.length)]]))}},at=class extends Er{constructor(){super(...arguments);B(this,"type","BooleanValue")}},ur=class extends Er{constructor(){super(...arguments);B(this,"type","ObjectValue");B(this,"builtins",new Map([["get",new Cr(([e,r])=>{if(!(e instanceof Re))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??r??new _a})],["items",new Cr(()=>new et(Array.from(this.value.entries()).map(([e,r])=>new et([new Re(e),r]))))]]))}__bool__(){return new at(this.value.size>0)}},et=class extends Er{constructor(){super(...arguments);B(this,"type","ArrayValue");B(this,"builtins",new Map([["length",new Ye(this.value.length)]]))}__bool__(){return new at(this.value.length>0)}},yb=class extends et{constructor(){super(...arguments);B(this,"type","TupleValue")}},Cr=class extends Er{constructor(){super(...arguments);B(this,"type","FunctionValue")}},_a=class extends Er{constructor(){super(...arguments);B(this,"type","NullValue")}},dr=class extends Er{constructor(){super(...arguments);B(this,"type","UndefinedValue")}},jo=class{constructor(t){B(this,"variables",new Map([["namespace",new Cr(t=>{if(t.length===0)return new ur(new Map);if(t.length!==1||!(t[0]instanceof ur))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]));B(this,"tests",new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Cr],["odd",t=>{if(t.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!==0}],["even",t=>{if(t.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["number",t=>t.type==="NumericValue"],["integer",t=>t.type==="NumericValue"&&Number.isInteger(t.value)],["iterable",t=>t instanceof et||t instanceof Re],["lower",t=>{const e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value]]));this.parent=t}set(t,e){return this.declareVariable(t,Oi(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 dr}catch{return new dr}}},wb=class{constructor(t){B(this,"global");this.global=t??new jo}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new at(r.value==n.value);case"!=":return new at(r.value!=n.value)}if(r instanceof dr||n instanceof dr)throw new Error("Cannot perform operation on undefined values");if(r instanceof _a||n instanceof _a)throw new Error("Cannot perform operation on null values");if(r instanceof Ye&&n instanceof Ye)switch(t.operator.value){case"+":return new Ye(r.value+n.value);case"-":return new Ye(r.value-n.value);case"*":return new Ye(r.value*n.value);case"/":return new Ye(r.value/n.value);case"%":return new Ye(r.value%n.value);case"<":return new at(r.value":return new at(r.value>n.value);case">=":return new at(r.value>=n.value);case"<=":return new at(r.value<=n.value)}else if(r instanceof et&&n instanceof et)switch(t.operator.value){case"+":return new et(r.value.concat(n.value))}else if(n instanceof et){const a=n.value.find(s=>s.value===r.value)!==void 0;switch(t.operator.value){case"in":return new at(a);case"not in":return new at(!a)}}if(r instanceof Re||n instanceof Re)switch(t.operator.value){case"+":return new Re(r.value.toString()+n.value.toString())}if(r instanceof Re&&n instanceof Re)switch(t.operator.value){case"in":return new at(n.value.includes(r.value));case"not in":return new at(!n.value.includes(r.value))}if(r instanceof Re&&n instanceof ur)switch(t.operator.value){case"in":return new at(n.value.has(r.value));case"not in":return new at(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if(t.filter.type==="Identifier"){const n=t.filter;if(r instanceof et)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new Ye(r.value.length);case"reverse":return new et(r.value.reverse());case"sort":return new et(r.value.sort((a,s)=>{if(a.type!==s.type)throw new Error(`Cannot compare different types: ${a.type} and ${s.type}`);switch(a.type){case"NumericValue":return a.value-s.value;case"StringValue":return a.value.localeCompare(s.value);default:throw new Error(`Cannot compare type: ${a.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof Re)switch(n.value){case"length":return new Ye(r.value.length);case"upper":return new Re(r.value.toUpperCase());case"lower":return new Re(r.value.toLowerCase());case"title":return new Re(Cm(r.value));case"capitalize":return new Re(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new Re(r.value.trim());default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(r instanceof Ye)switch(n.value){case"abs":return new Ye(Math.abs(r.value));default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(r instanceof ur)switch(n.value){case"items":return new et(Array.from(r.value.entries()).map(([a,s])=>new et([new Re(a),s])));case"length":return new Ye(r.value.size);default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}throw new Error(`Cannot apply filter "${n.value}" to type: ${r.type}`)}else if(t.filter.type==="CallExpression"){const n=t.filter;if(n.callee.type!=="Identifier")throw new Error(`Unknown filter: ${n.callee.type}`);const a=n.callee.value;if(r instanceof et){switch(a){case"selectattr":{if(r.value.some(d=>!(d instanceof ur)))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some(d=>d.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[s,i,o]=n.args.map(d=>this.evaluate(d,e));let l;if(i){const d=e.tests.get(i.value);if(!d)throw new Error(`Unknown test: ${i.value}`);l=d}else l=(...d)=>d[0].__bool__().value;const u=r.value.filter(d=>{const h=d.value.get(s.value);return h?l(h,o):!1});return new et(u)}}throw new Error(`Unknown ArrayValue filter: ${a}`)}else throw new Error(`Cannot apply filter "${a}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const a=n(r);return new at(t.negate?!a:a)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);switch(t.operator.value){case"not":return new at(!r.value);default:throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const a=this.evaluate(n,e);a.type!=="NullValue"&&a.type!=="UndefinedValue"&&(r+=a.value)}return new Re(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const r=[],n=new Map;for(const s of t.args)if(s.type==="KeywordArgumentExpression"){const i=s;n.set(i.key.value,this.evaluate(i.value,e))}else r.push(this.evaluate(s,e));n.size>0&&r.push(new ur(n));const a=this.evaluate(t.callee,e);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);return a.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof et||t instanceof Re))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),a=this.evaluate(e.stop,r),s=this.evaluate(e.step,r);if(!(n instanceof Ye||n instanceof dr))throw new Error("Slice start must be numeric or undefined");if(!(a instanceof Ye||a instanceof dr))throw new Error("Slice stop must be numeric or undefined");if(!(s instanceof Ye||s instanceof dr))throw new Error("Slice step must be numeric or undefined");return t instanceof et?new et(Em(t.value,n.value,a.value,s.value)):new Re(Em(Array.from(t.value),n.value,a.value,s.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new Re(t.property.value);let a;if(r instanceof ur){if(!(n instanceof Re))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof et||r instanceof Re)if(n instanceof Ye)a=r.value.at(n.value),r instanceof Re&&(a=new Re(r.value.at(n.value)));else if(n instanceof Re)a=r.builtins.get(n.value);else throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof Re))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=r.builtins.get(n.value)}return a instanceof Er?a:new dr}evaluateSet(t,e){const r=this.evaluate(t.value,e);if(t.assignee.type==="Identifier"){const n=t.assignee.value;e.setVariable(n,r)}else if(t.assignee.type==="MemberExpression"){const n=t.assignee,a=this.evaluate(n.object,e);if(!(a instanceof ur))throw new Error("Cannot assign to member of non-object");if(n.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");a.value.set(n.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new _a}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new jo(e),n=this.evaluate(t.iterable,r);if(!(n instanceof et))throw new Error(`Expected iterable type in for loop: got ${n.type}`);let a="";for(let s=0;s0?n.value[s-1]:new dr],["nextitem",sd.value.length?"few":"many"} items to unpack`);for(let h=0;hthis.evaluate(r,e)));case"TupleLiteral":return new yb(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{const r=new Map;for(const[n,a]of t.value){const s=this.evaluate(n,e);if(!(s instanceof Re))throw new Error(`Object keys must be strings: got ${s.type}`);r.set(s.value,this.evaluate(a,e))}return new ur(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Oi(t){switch(typeof t){case"number":return new Ye(t);case"string":return new Re(t);case"boolean":return new at(t);case"object":return t===null?new _a:Array.isArray(t)?new et(t.map(Oi)):new ur(new Map(Object.entries(t).map(([e,r])=>[e,Oi(r)])));case"function":return new Cr((e,r)=>{const n=t(...e.map(a=>a.value))??null;return Oi(n)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var bb=class{constructor(t){B(this,"parsed");const e=rb(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=gb(e)}render(t){const e=new jo;e.set("false",!1),e.set("true",!0),e.set("raise_exception",a=>{throw new Error(a)}),e.set("range",_b);for(const[a,s]of Object.entries(t))e.set(a,s);return new wb(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"]],zi=new Map(Tm),vb=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 Am(t){t=t.toLowerCase();let e=vb.get(t);if(e===void 0)if(zi.has(t))e=t;else{const n=t.length===2?zi.keys():zi.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(n)}`)}return e}const qo="https://github.com/xenova/transformers.js/issues/new/choose";async function Im(t,e){const r=await Promise.all([Rr(t,"tokenizer.json",!0,e),Rr(t,"tokenizer_config.json",!0,e)]);return e.legacy!==null&&(r[1].legacy=e.legacy),r}function $b(t,e){const r=[];let n=0;for(const a of t.matchAll(e)){const s=a[0];n0&&r.push(s),n=a.index+s.length}return n=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,r){const n=[];let a=0;for(;athis.tokens_to_ids.get(r)??this.unk_token_id)}convert_ids_to_tokens(e){return e.map(r=>this.vocab[r]??this.unk_token)}}class Ib extends ya{constructor(e){super(e),this.tokens_to_ids=Ko(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r}encode(e){const r=[];for(const n of e){const a=[...n];if(a.length>this.max_input_chars_per_word){r.push(this.unk_token);continue}let s=!1,i=0;const o=[];for(;i0&&(d=this.config.continuing_subword_prefix+d),this.tokens_to_ids.has(d)){u=d;break}--l}if(u===null){s=!0;break}o.push(u),i=l}s?r.push(this.unk_token):r.push(...o)}return r}}class Mb extends ya{constructor(e,r){super(e);const n=e.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let a=0;a[a,s])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=r.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=Bl(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new Qw,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const r=e.sentence,n=r.length;let a=0;for(;a{const t=[...Array.from({length:94},(a,s)=>s+33),...Array.from({length:12},(a,s)=>s+161),...Array.from({length:82},(a,s)=>s+174)],e=t.slice();let r=0;for(let a=0;a<256;++a)t.includes(a)||(t.push(a),e.push(256+r),r+=1);const n=e.map(a=>String.fromCharCode(a));return Object.fromEntries(t.map((a,s)=>[a,n[s]]))})(),Ob=V0(zm);class zb extends ya{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=Ko(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r;this.bpe_ranks=new Map(e.merges.map((r,n)=>[r,n])),this.merges=e.merges.map(r=>r.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(e){if(e.length===0)return[];const r=this.cache.get(e);if(r!==void 0)return r;const n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let a=[];if(n.length>1){const s=new Xw((l,u)=>l.score`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`)):r.push(this.unk_token)}return r}}class Pb extends ya{constructor(e,r){super(e),this.tokens_to_ids=Ko(r.target_lang?e.vocab[r.target_lang]:e.vocab),this.bos_token=r.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=r.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=r.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=r.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[n,a]of this.tokens_to_ids)this.vocab[a]=n}encode(e){return e}}class Lt extends wt{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new Gb(e);case"Precompiled":return new uv(e);case"Sequence":return new Vb(e);case"Replace":return new Rb(e);case"NFC":return new Bb(e);case"NFKC":return new Db(e);case"NFKD":return new Nb(e);case"Strip":return new Fb(e);case"StripAccents":return new Lb(e);case"Lowercase":return new Ub(e);case"Prepend":return new Wb(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 Rb extends Lt{normalize(e){const r=Pi(this.config.pattern);return r===null?e:e.replaceAll(r,this.config.content)}}class Bb extends Lt{normalize(e){return e=e.normalize("NFC"),e}}class Db extends Lt{normalize(e){return e=e.normalize("NFKC"),e}}class Nb extends Lt{normalize(e){return e=e.normalize("NFKD"),e}}class Fb extends Lt{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 Lb extends Lt{normalize(e){return e=Om(e),e}}class Ub extends Lt{normalize(e){return e=e.toLowerCase(),e}}class Wb extends Lt{normalize(e){return e=this.config.prepend+e,e}}class Vb extends Lt{constructor(e){super(e),this.normalizers=e.normalizers.map(r=>Lt.fromConfig(r))}normalize(e){return this.normalizers.reduce((r,n)=>n.normalize(r),e)}}class Gb extends Lt{_tokenize_chinese_chars(e){const r=[];for(let n=0;nthis.pre_tokenize_text(n,r)):this.pre_tokenize_text(e,r)).flat()}_call(e,r){return this.pre_tokenize(e,r)}}class Hb extends Qt{constructor(e){super(),this.pattern=new RegExp(`[^\\s${zn}]+|[${zn}]`,"gu")}pre_tokenize_text(e,r){return e.trim().match(this.pattern)||[]}}class jb extends Qt{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=zm,this.text_encoder=new TextEncoder}pre_tokenize_text(e,r){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(a=>Array.from(this.text_encoder.encode(a),s=>this.byte_encoder[s]).join(""))}}class qb extends Qt{constructor(e){super(),this.config=e,this.pattern=Pi(this.config.pattern,this.config.invert)}pre_tokenize_text(e,r){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:$b(e,this.pattern)}}class Kb extends Qt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${zn}]+|[${zn}]+`,"gu")}pre_tokenize_text(e,r){return e.match(this.pattern)||[]}}class Yb extends Qt{constructor(e){super(),this.config=e;const r=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(r,"gu")}pre_tokenize_text(e,r){return e.match(this.pattern)||[]}}class Pn extends wt{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new Xb(e);case"ByteLevel":return new Bm(e);case"RobertaProcessing":return new Rm(e);case"BertProcessing":return new Pm(e);case"Sequence":return new Qb(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...r){throw Error("post_process should be implemented in subclass.")}_call(e,...r){return this.post_process(e,...r)}}class Pm extends Pn{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,r=null,{add_special_tokens:n=!0}={}){n&&(e=gt([this.cls],e,[this.sep]));let a=new Array(e.length).fill(0);if(r!==null){const s=n&&this instanceof Rm?[this.sep]:[],i=n?[this.sep]:[];e=gt(e,s,r,i),a=gt(a,new Array(r.length+s.length+i.length).fill(1))}return{tokens:e,token_type_ids:a}}}class Rm extends Pm{}class Xb extends Pn{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,r=null,{add_special_tokens:n=!0}={}){const a=r===null?this.single:this.pair;let s=[],i=[];for(const o of a)"SpecialToken"in o?n&&(s.push(o.SpecialToken.id),i.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(s=gt(s,e),i=gt(i,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=gt(s,r),i=gt(i,new Array(r.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:i}}}class Bm extends Pn{post_process(e,r=null){return r&&(e=gt(e,r)),{tokens:e}}}class Qb extends Pn{constructor(e){super(e),this.processors=e.processors.map(r=>Pn.fromConfig(r))}post_process(e,r=null,n={}){let a;for(const s of this.processors)if(s instanceof Bm)e=s.post_process(e).tokens,r&&(r=s.post_process(r).tokens);else{const i=s.post_process(e,r,n);e=i.tokens,a=i.token_type_ids}return{tokens:e,token_type_ids:a}}}class Ut extends wt{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 rv(e);case"Metaspace":return new lv(e);case"ByteLevel":return new nv(e);case"Replace":return new Zb(e);case"ByteFallback":return new Jb(e);case"Fuse":return new ev(e);case"Strip":return new tv(e);case"Sequence":return new iv(e);case"CTC":return new av(e);case"BPEDecoder":return new sv(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 Zb extends Ut{decode_chain(e){const r=Pi(this.config.pattern);return r===null?e:e.map(n=>n.replaceAll(r,this.config.content))}}class Jb extends Ut{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const r=[];let n=[];for(const a of e){let s=null;if(a.length===6&&a.startsWith("<0x")&&a.endsWith(">")){const i=parseInt(a.slice(3,5),16);isNaN(i)||(s=i)}if(s!==null)n.push(s);else{if(n.length>0){const i=this.text_decoder.decode(Uint8Array.from(n));r.push(i),n=[]}r.push(a)}}if(n.length>0){const a=this.text_decoder.decode(Uint8Array.from(n));r.push(a),n=[]}return r}}class ev extends Ut{decode_chain(e){return[e.join("")]}}class tv extends Ut{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map(r=>{let n=0;for(let s=0;s(n!==0&&(r.startsWith(this.config.prefix)?r=r.replace(this.config.prefix,""):r=" "+r),this.cleanup&&(r=Yo(r)),r))}}class nv extends Ut{constructor(e){super(e),this.byte_decoder=Ob,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const r=e.join(""),n=new Uint8Array([...r].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(n)}decode_chain(e){const r=[];let n=[];for(const a of e)this.added_tokens.find(s=>s.content===a)!==void 0?(n.length>0&&(r.push(this.convert_tokens_to_string(n)),n=[]),r.push(a)):n.push(a);return n.length>0&&r.push(this.convert_tokens_to_string(n)),r}}class av extends Ut{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const r=[e[0]];for(let s=1;ss!==this.pad_token).join("");return this.cleanup&&(a=Yo(a).replaceAll(this.word_delimiter_token," ").trim()),a}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class iv extends Ut{constructor(e){super(e),this.decoders=e.decoders.map(r=>Ut.fromConfig(r))}decode_chain(e){return this.decoders.reduce((r,n)=>n.decode_chain(r),e)}}class sv extends Ut{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map((r,n)=>r.replaceAll(this.suffix,n===e.length-1?"":" "))}}class ov extends Ut{decode_chain(e){let r="";for(let n=1;nn.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}}class dv extends Qt{constructor(e){super(),this.tokenizers=e.pretokenizers.map(r=>Qt.fromConfig(r))}pre_tokenize_text(e,r){return this.tokenizers.reduce((n,a)=>a.pre_tokenize(n,r),[e])}}class cv extends Qt{constructor(e){super()}pre_tokenize_text(e,r){return e.match(/\w+|[^\w\s]+/g)||[]}}class pv extends Qt{constructor(e){super()}pre_tokenize_text(e,r){return Eb(e)}}class hv extends Qt{constructor(e){super(),this.config=e,this.pattern=Pi(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,r){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const fv=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function mv(t,e,r,n){for(const a of Object.keys(t)){const s=e-t[a].length,i=r(a),o=new Array(s).fill(i);t[a]=n==="right"?gt(t[a],o):gt(o,t[a])}}function gv(t,e){for(const r of Object.keys(t))t[r].length=e}class Ce extends wt{constructor(r,n){super();B(this,"return_token_type_ids",!1);B(this,"_default_chat_template",`{% for message in messages %}{{'<|im_start|>' + message['role'] + ' ' + message['content'] + '<|im_end|>' + ' '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant ' }}{% endif %}`);B(this,"padding_side","right");this._tokenizer_config=n,this.normalizer=Lt.fromConfig(r.normalizer),this.pre_tokenizer=Qt.fromConfig(r.pre_tokenizer),this.model=ya.fromConfig(r.model,n),this.post_processor=Pn.fromConfig(r.post_processor),this.decoder=Ut.fromConfig(r.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const a of r.added_tokens){const s=new Ab(a);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}if(this.additional_special_tokens=n.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.toSorted((a,s)=>s.content.length-a.content.length).map(a=>`${a.lstrip?"\\s*":""}(${zl(a.content)})${a.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=n.model_max_length,this.remove_space=n.remove_space,this.clean_up_tokenization_spaces=n.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=n.do_lowercase_and_remove_accent??!1,n.padding_side&&(this.padding_side=n.padding_side),this.legacy=!1,this.chat_template=n.chat_template??null,Array.isArray(this.chat_template)){const a=Object.create(null);for(const{name:s,template:i}of this.chat_template){if(typeof s!="string"||typeof i!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');a[s]=i}this.chat_template=a}this._compiled_template_cache=new Map}getToken(...r){for(const n of r){const a=this._tokenizer_config[n];if(a)if(typeof a=="object"){if(a.__type==="AddedToken")return a.content;throw Error(`Unknown token: ${a}`)}else return a}return null}static async from_pretrained(r,{progress_callback:n=null,config:a=null,cache_dir:s=null,local_files_only:i=!1,revision:o="main",legacy:l=null}={}){const u=await Im(r,{progress_callback:n,config:a,cache_dir:s,local_files_only:i,revision:o,legacy:l});return new this(...u)}_call(r,{text_pair:n=null,add_special_tokens:a=!0,padding:s=!1,truncation:i=null,max_length:o=null,return_tensor:l=!0,return_token_type_ids:u=null}={}){const d=Array.isArray(r);let h;if(d){if(r.length===0)throw Error("text array must be non-empty");if(n!==null){if(Array.isArray(n)){if(r.length!==n.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=r.map((g,p)=>this._encode_plus(g,{text_pair:n[p],add_special_tokens:a,return_token_type_ids:u}))}else h=r.map(g=>this._encode_plus(g,{add_special_tokens:a,return_token_type_ids:u}))}else{if(r==null)throw Error("text may not be null or undefined");if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this._encode_plus(r,{text_pair:n,add_special_tokens:a,return_token_type_ids:u})]}if(o===null?s==="max_length"?o=this.model_max_length:o=qt(h.map(g=>g.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),s||i)for(let g=0;go?i&&gv(h[g],o):s&&mv(h[g],o,p=>p==="input_ids"?this.pad_token_id:0,this.padding_side));const m={};if(l){if(!(s&&i)&&h.some(p=>{var w;for(const v of Object.keys(p))if(p[v].length!==((w=h[0][v])==null?void 0:w.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 g=[h.length,h[0].input_ids.length];for(const p of Object.keys(h[0]))m[p]=new ce("int64",BigInt64Array.from(h.flatMap(w=>w[p]).map(BigInt)),g)}else{for(const g of Object.keys(h[0]))m[g]=h.map(p=>p[g]);if(!d)for(const g of Object.keys(m))m[g]=m[g][0]}return m}_encode_text(r){return r===null?null:(this.added_tokens_regex?r.split(this.added_tokens_regex).filter(s=>s):[r]).map((s,i)=>{if(this.added_tokens.find(l=>l.content===s)!==void 0)return s;{if(this.remove_space===!0&&(s=s.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(s=xb(s)),this.normalizer!==null&&(s=this.normalizer(s)),s.length===0)return[];const l=this.pre_tokenizer!==null?this.pre_tokenizer(s,{section_index:i}):[s];return this.model(l)}}).flat()}_encode_plus(r,{text_pair:n=null,add_special_tokens:a=!0,return_token_type_ids:s=null}={}){const{tokens:i,token_type_ids:o}=this._tokenize_helper(r,{pair:n,add_special_tokens:a}),l=this.model.convert_tokens_to_ids(i),u={input_ids:l,attention_mask:new Array(l.length).fill(1)};return(s??this.return_token_type_ids)&&o&&(u.token_type_ids=o),u}_tokenize_helper(r,{pair:n=null,add_special_tokens:a=!1}={}){const s=this._encode_text(r),i=this._encode_text(n);return this.post_processor?this.post_processor(s,i,{add_special_tokens:a}):{tokens:gt(s??[],i??[])}}tokenize(r,{pair:n=null,add_special_tokens:a=!1}={}){return this._tokenize_helper(r,{pair:n,add_special_tokens:a}).tokens}encode(r,{text_pair:n=null,add_special_tokens:a=!0,return_token_type_ids:s=null}={}){return this._encode_plus(r,{text_pair:n,add_special_tokens:a,return_token_type_ids:s}).input_ids}batch_decode(r,n={}){return r instanceof ce&&(r=r.tolist()),r.map(a=>this.decode(a,n))}decode(r,n={}){if(r instanceof ce&&(r=Mm(r)),!Array.isArray(r)||r.length===0||!G0(r[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(r,n)}decode_single(r,{skip_special_tokens:n=!1,clean_up_tokenization_spaces:a=null}){let s=this.model.convert_ids_to_tokens(r);n&&(s=s.filter(o=>!this.special_tokens.includes(o)));let i=this.decoder?this.decoder(s):s.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(i=i.replaceAll(this.decoder.end_of_word_suffix," "),n&&(i=i.trim())),(a??this.clean_up_tokenization_spaces)&&(i=Yo(i)),i}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(r,{chat_template:n=null,add_generation_prompt:a=!1,tokenize:s=!0,padding:i=!1,truncation:o=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!1,tokenizer_kwargs:h={},...m}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null&&this.default_chat_template&&typeof this.default_chat_template=="object"){const v=this.chat_template??this.default_chat_template;if(n!==null&&Object.hasOwn(v,n))n=v[n];else if(n===null&&"default"in v)n=v.default;else if(n===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(v).sort()}.`)}else n??(n=this.chat_template??this.default_chat_template);if(typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let g=this._compiled_template_cache.get(n);g===void 0&&(g=new bb(n),this._compiled_template_cache.set(n,g));const p=Object.create(null);for(const v of fv){const S=this.getToken(v);S&&(p[v]=S)}const w=g.render({messages:r,add_generation_prompt:a,...p,...m});if(s){const v=this._call(w,{add_special_tokens:!1,padding:i,truncation:o,max_length:l,return_tensor:u,...h});return d?v:v.input_ids}return w}}class _v extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class yv extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class wv extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class bv extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class vv extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class $v extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class xv extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class Sv extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class kv extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class Ev extends Ce{}class Cv extends Ce{}class Tv extends Ce{constructor(r,n){super(r,n);B(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 Av extends Ce{constructor(){super(...arguments);B(this,"return_token_type_ids",!0)}}class Iv extends Ce{}class Nm extends Ce{constructor(){super(...arguments);B(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}}class Mv extends Ce{}class Fm extends Ce{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)),this.lang_to_token=n=>n}_build_translation_inputs(e,r,n){return Xo(this,e,r,n)}}class Ov extends Fm{}class zv extends Ce{}class Pv extends Nm{constructor(e,r){var s,i;const n=".,!?…。,、।۔،",a=(i=(s=e.pre_tokenizer)==null?void 0:s.pretokenizers[0])==null?void 0:i.pattern;a&&a.Regex===` ?[^(\\s|[${n}])]+`&&(a.Regex=` ?[^\\s${n}]+`),super(e,r)}}const Ri="▁";class Lm extends Ce{constructor(r,n){super(r,n);B(this,"_default_chat_template",`{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> ' + system_message + ' <> ' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> ' + content.strip() + ' <> ' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`);B(this,"DEFAULT_SYSTEM_PROMPT",`You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.`);B(this,"padding_side","left");this.use_default_system_prompt=n.use_default_system_prompt??!1,this.legacy=n.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Dm({replacement:Ri,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(r){if(r===null)return null;if(this.legacy||r.length===0)return super._encode_text(r);let n=super._encode_text(Ri+r.replaceAll(Ri," "));return n.length>1&&n[0]===Ri&&this.special_tokens.includes(n[1])&&(n=n.slice(1)),n}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll(` `,"\\n").replaceAll("'","\\'"))}}class Rv extends Lm{}class Bv extends Ce{}class Dv extends Ce{}class Nv extends Ce{}class Fv extends Ce{}class Lv extends Ce{}class Uv extends Ce{}class Wv extends Ce{constructor(){super(...arguments);B(this,"_default_chat_template",`{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + ' ' + message['content'] | trim + ' ' }}{% endfor %}{% if add_generation_prompt %}{{'model '}}{% endif %}`)}}class Vv extends Ce{}function Xo(t,e,r,n){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const a=n.src_lang,s=n.tgt_lang;if(!t.language_codes.includes(s))throw new Error(`Target language code "${s}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(a!==void 0){if(!t.language_codes.includes(a))throw new Error(`Source language code "${a}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(const i of t.post_processor.config.single)if("SpecialToken"in i&&t.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=t.lang_to_token(a);break}}return n.forced_bos_token_id=t.model.convert_tokens_to_ids([t.lang_to_token(s)])[0],t._call(e,r)}class Gv extends Ce{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)),this.lang_to_token=n=>n}_build_translation_inputs(e,r,n){return Xo(this,e,r,n)}}class Hv extends Ce{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)).map(n=>n.slice(2,-2)),this.lang_to_token=n=>`__${n}__`}_build_translation_inputs(e,r,n){return Xo(this,e,r,n)}}class jv extends Ce{constructor(){super(...arguments);B(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(r,{return_timestamps:n=!1,return_language:a=!1,time_precision:s=null,force_full_sequences:i=!0}={}){if(s===null)throw Error("Must specify time_precision");let o=null;const l=n==="word";function u(){return{language:o,timestamp:[null,null],text:""}}const d=[];let h=u(),m=0;const g=this.timestamp_begin;let p=[],w=[],v=!1,S=null;const $=new Set(this.all_special_ids);for(const A of r){const z=A.tokens,R=l?A.token_timestamps:null;let V=null,j=g;if("stride"in A){const[ee,ne,se]=A.stride;if(m-=ne,S=ee-se,ne&&(j=ne/s+g),se)for(let D=z.length-1;D>=0;--D){const M=Number(z[D]);if(M>=g){if(V!==null&&(M-g)*s=g){const se=(ne-g)*s+m,D=Xn(se,2);if(V!==null&&ne>=V)v=!0;else if(v||p.length>0&&ne0?(p.push(q),l&&w.push(fe)):p.every(ee=>ee.length===0)&&(h=u(),p=[],q=[],w=[],fe=[])}if(p.length>0){if(i&&n)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[A,z]=this.findLongestCommonSequence(p,w),R=this.decode(A);h.text=R,l&&(h.words=this.collateWordTimestamps(A,z,o)),d.push(h)}let E=Object.create(null);const T=d.map(A=>A.text).join("");if(n||a){for(let A=0;A0;let l=o?[]:null,u=o?n[0]:null;for(let d=1;dD===fe[M]&&u[z+M]<=n[d][j+M]).length:ee=V.filter((D,M)=>D===fe[M]).length;const ne=A/1e4,se=ee/A+ne;ee>1&&se>m&&(m=se,g=[z,R,j,q])}const[w,v,S,$]=g,E=Math.floor((v+w)/2),T=Math.floor(($+S)/2);i.push(...a.slice(0,E)),a=h.slice(T),s=a.length,o&&(l.push(...u.slice(0,E)),u=n[d].slice(T))}return i.push(...a),o?(l.push(...u),[i,l]):[i,[]]}collateWordTimestamps(r,n,a){const[s,i,o]=this.combineTokensIntoWords(r,a),l=[];for(let u=0;u=s){const l=((o-s)*a).toFixed(2);i.push(`<|${l}|>`),i.push([])}else i[i.length-1].push(o);return i=i.map(o=>typeof o=="string"?o:super.decode(o,n)),i.join("")}splitTokensOnUnicode(r){const n=this.decode(r,{decode_with_timestamps:!0}),a="�",s=[],i=[],o=[];let l=[],u=[],d=0;for(let h=0;h=this.model.tokens_to_ids.get("<|endoftext|>"),w=h.startsWith(" "),v=h.trim(),S=u.test(v);if(p||w||S||i.length===0)i.push(h),o.push(m),l.push(g);else{const $=i.length-1;i[$]+=h,o[$].push(...m),l[$].push(...g)}}return[i,o,l]}mergePunctuations(r,n,a,s,i){const o=structuredClone(r),l=structuredClone(n),u=structuredClone(a);let d=o.length-2,h=o.length-1;for(;d>=0;)o[d].startsWith(" ")&&s.includes(o[d].trim())?(o[h]=o[d]+o[h],l[h]=gt(l[d],l[h]),u[h]=gt(u[d],u[h]),o[d]="",l[d]=[],u[d]=[]):h=d,--d;for(d=0,h=1;hm),l.filter(m=>m.length>0),u.filter(m=>m.length>0)]}get_decoder_prompt_ids({language:r=null,task:n=null,no_timestamps:a=!0}={}){const s=[];if(r){const i=Am(r),o=this.model.tokens_to_ids.get(`<|${i}|>`);if(o===void 0)throw new Error(`Unable to find language "${i}" in model vocabulary. Please report this issue at ${qo}.`);s.push(o)}else s.push(null);if(n){if(n=n.toLowerCase(),n!=="transcribe"&&n!=="translate")throw new Error(`Task "${n}" is not supported. Must be one of: ["transcribe", "translate"]`);const i=this.model.tokens_to_ids.get(`<|${n}|>`);if(i===void 0)throw new Error(`Unable to find task "${n}" in model vocabulary. Please report this issue at ${qo}.`);s.push(i)}else s.push(null);if(a){const i=this.model.tokens_to_ids.get("<|notimestamps|>");if(i===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${qo}.`);s.push(i)}return s.map((i,o)=>[o+1,i]).filter(i=>i[1]!==null)}}class qv extends Ce{}class Kv extends Ce{}class Yv extends Ce{}class Xv extends Ce{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(n=>this.languageRegex.test(n)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[r,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(r);if(n.length===2){const[a,s]=n;return this.supported_language_codes.includes(a)||console.warn(`Unsupported language code "${a}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),gt([a],super._encode_text(s))}}}class Qv extends Ce{}class Um extends Ce{constructor(){super(...arguments);B(this,"_default_chat_template","{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}")}}class Zv extends Um{}class Jv extends Ce{}class e1 extends Ce{}class t1 extends Ce{constructor(e,r){super(e,r),this.decoder=new ov({})}}class r1 extends Ce{}class pt{static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:s=!1,revision:i="main",legacy:o=null}={}){var m;const[l,u]=await Im(e,{progress_callback:r,config:n,cache_dir:a,local_files_only:s,revision:i,legacy:o}),d=((m=u.tokenizer_class)==null?void 0:m.replace(/Fast$/,""))??"PreTrainedTokenizer";let h=this.TOKENIZER_CLASS_MAPPING[d];return h||(console.warn(`Unknown tokenizer class "${d}", attempting to construct from base class.`),h=Ce),new h(l,u)}}B(pt,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Iv,DistilBertTokenizer:Ev,CamembertTokenizer:Cv,DebertaTokenizer:vv,DebertaV2Tokenizer:$v,BertTokenizer:_v,HerbertTokenizer:xv,ConvBertTokenizer:Sv,RoFormerTokenizer:kv,XLMTokenizer:Tv,ElectraTokenizer:Av,MobileBertTokenizer:wv,SqueezeBertTokenizer:bv,AlbertTokenizer:yv,GPT2Tokenizer:Nm,BartTokenizer:Mv,MBartTokenizer:Fm,MBart50Tokenizer:Ov,RobertaTokenizer:zv,WhisperTokenizer:jv,CodeGenTokenizer:qv,CLIPTokenizer:Kv,SiglipTokenizer:Yv,MarianTokenizer:Xv,BloomTokenizer:Pv,NllbTokenizer:Gv,M2M100Tokenizer:Hv,LlamaTokenizer:Lm,CodeLlamaTokenizer:Rv,XLMRobertaTokenizer:Bv,MPNetTokenizer:Dv,FalconTokenizer:Nv,GPTNeoXTokenizer:Fv,EsmTokenizer:Lv,Wav2Vec2CTCTokenizer:Qv,BlenderbotTokenizer:Um,BlenderbotSmallTokenizer:Zv,SpeechT5Tokenizer:Jv,NougatTokenizer:e1,VitsTokenizer:t1,Qwen2Tokenizer:Uv,GemmaTokenizer:Wv,Grok1Tokenizer:Vv,CohereTokenizer:r1,PreTrainedTokenizer:Ce});async function n1(t,e){return await Rr(t,"config.json",!0,e)}function wa(t){const e={};let r={};switch(t.model_type){case"llava":case"paligemma":case"florence2":r=wa(t.text_config);break;case"moondream1":r=wa(t.phi_config);break;case"musicgen":r=wa(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":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 a=wa(t.decoder),s="num_decoder_layers"in a,i=$r(t,["model_type","is_encoder_decoder"]);return s?(i.num_decoder_layers=a.num_decoder_layers,i.num_decoder_heads=a.num_decoder_heads,i.decoder_hidden_size=a.decoder_hidden_size,i.num_encoder_layers=a.num_encoder_layers,i.num_encoder_heads=a.num_encoder_heads,i.encoder_hidden_size=a.encoder_hidden_size):(i.num_layers=a.num_layers,i.num_heads=a.num_heads,i.hidden_size=a.hidden_size),i}const n={...r,...$r(t,["model_type","multi_query","is_encoder_decoder"])};for(const a in e)n[a]=t[e[a]];return n}function Wm(t,{prefix:e="past_key_values"}={}){const r={},n=t.normalized_config,a=1;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){const s=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,i=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,o=[a,n.num_encoder_heads,0,s],l=[a,n.num_decoder_heads,0,i];for(let u=0;u=1&&i[i.length-1]>=this.timestamp_begin,l=i.length<2||i[i.length-2]>=this.timestamp_begin;if(o&&(l?s.subarray(this.timestamp_begin).fill(-1/0):s.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){const m=this.timestamp_begin+this.max_initial_timestamp_index;s.subarray(m+1).fill(-1/0)}const u=Z0(s),d=Math.log(u.subarray(this.timestamp_begin).map(Math.exp).reduce((m,g)=>m+g)),h=qt(u.subarray(0,this.timestamp_begin))[0];d>h&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return r}}class u1 extends yr{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const r=e.length,n=[];for(let s=0;s1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);const n=e.length,a=r.slice([0,n],null),s=r.slice([n,r.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(n)||n<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${n}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=n}}class _1 extends Qo{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:n=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,n),this.filter_value=r}}class jm{constructor(e){B(this,"max_length",20);B(this,"max_new_tokens",null);B(this,"min_length",0);B(this,"min_new_tokens",null);B(this,"early_stopping",!1);B(this,"max_time",null);B(this,"do_sample",!1);B(this,"num_beams",1);B(this,"num_beam_groups",1);B(this,"penalty_alpha",null);B(this,"use_cache",!0);B(this,"temperature",1);B(this,"top_k",50);B(this,"top_p",1);B(this,"typical_p",1);B(this,"epsilon_cutoff",0);B(this,"eta_cutoff",0);B(this,"diversity_penalty",0);B(this,"repetition_penalty",1);B(this,"encoder_repetition_penalty",1);B(this,"length_penalty",1);B(this,"no_repeat_ngram_size",0);B(this,"bad_words_ids",null);B(this,"force_words_ids",null);B(this,"renormalize_logits",!1);B(this,"constraints",null);B(this,"forced_bos_token_id",null);B(this,"forced_eos_token_id",null);B(this,"remove_invalid_values",!1);B(this,"exponential_decay_length_penalty",null);B(this,"suppress_tokens",null);B(this,"begin_suppress_tokens",null);B(this,"forced_decoder_ids",null);B(this,"guidance_scale",null);B(this,"num_return_sequences",1);B(this,"output_attentions",!1);B(this,"output_hidden_states",!1);B(this,"output_scores",!1);B(this,"return_dict_in_generate",!1);B(this,"pad_token_id",null);B(this,"bos_token_id",null);B(this,"eos_token_id",null);B(this,"encoder_no_repeat_ngram_size",0);B(this,"decoder_start_token_id",null);B(this,"generation_kwargs",{});Object.assign(this,$r(e,Object.getOwnPropertyNames(this)))}}class Zo extends wt{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}}class Jo extends wt{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof Jo?e=e.criteria:e instanceof Zo&&(e=[e]),this.criteria.push(...e)}_call(e,r){const n=new Array(e.length).fill(!1);for(const a of this.criteria){const s=a(e,r);for(let i=0;ir.length>=this.max_length)}}class w1 extends Zo{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(n=>{const a=n.at(-1);return this.eos_token_id.some(s=>a==s)})}}class Fi extends wt{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,r){let n=e.dims.at(-1),a=e.data;if(r===-1)a=a.slice(-n);else{let s=r*n;a=a.slice(s,s+n)}return a}randomSelect(e){let r=0;for(let a=0;a1)return new $1(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 b1(e)}}class b1 extends Fi{async sample(e){const r=qt(e.data)[1];return[[BigInt(r),0]]}}class v1 extends Fi{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const[n,a]=await An(e,r),s=bt(n.data);return Array.from({length:this.generation_config.num_beams},()=>{const i=this.randomSelect(s);return[a.data[i],Math.log(s[i])]})}}class $1 extends Fi{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const[n,a]=await An(e,r),s=bt(n.data);return Array.from({length:this.generation_config.num_beams},(i,o)=>[a.data[o],Math.log(s[o])])}}class x1 extends jm{constructor(){super(...arguments);B(this,"return_timestamps",null);B(this,"return_token_timestamps",null);B(this,"num_frames",null);B(this,"alignment_heads",null);B(this,"task",null);B(this,"language",null);B(this,"no_timestamps_token_id",null);B(this,"prompt_ids",null);B(this,"is_multilingual",null);B(this,"lang_to_id",null);B(this,"task_to_id",null);B(this,"max_initial_timestamp_index",1)}}const $e={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},Li=new Map,qm=new Map,ba=new Map;async function S1(t,e,r){let n=r.device;n&&typeof n!="string"&&(n.hasOwnProperty(e)?n=n[e]:(console.warn(`device not specified for "${e}". Using the default device.`),n=null));const a=Bw(n);let s=r.dtype;if(typeof s!="string"&&(s&&s.hasOwnProperty(e)?s=s[e]:(s=i1[a[0]],console.warn(`dtype not specified for "${e}". Using the default dtype for this device (${s}).`))),Gm.hasOwnProperty(s)){if(s===Pt.fp16&&!await a1())throw new Error("The device does not support fp16.")}else throw new Error(`Invalid dtype: ${s}. Should be one of: ${Object.keys(Pt).join(", ")}`);const i=Gm[s],o=`${r.subfolder??""}/${e}${i}.onnx`,l={...r.session_options};l.executionProviders??(l.executionProviders=a);const u=ai(t,o,!0,r);let d=[];if(r.use_external_data_format&&(r.use_external_data_format===!0||typeof r.use_external_data_format=="object"&&r.use_external_data_format.hasOwnProperty(e)&&r.use_external_data_format[e]===!0)){if(Hr.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const m=`${e}${i}.onnx_data`,g=`${r.subfolder??""}/${m}`;d.push(new Promise(async(p,w)=>{const v=await ai(t,g,!0,r);p({path:m,data:v})}))}else l.externalData!==void 0&&(d=l.externalData.map(async m=>{if(typeof m.data=="string"){const g=await ai(t,m.data,!0,r);return{...m,data:g}}return m}));if(d.length>0&&(l.externalData=await Promise.all(d)),n==="webgpu"){const m=Wm(r.config,{prefix:"present"});if(Object.keys(m).length>0){const g={};for(const p in m)g[p]="gpu-buffer";l.preferredOutputLocation=g}}return{buffer:await u,session_options:l}}async function sn(t,e,r){const n=Object.keys(e),a=await Promise.all(n.map(async i=>S1(t,e[i],r))),s={};for(let i=0;i0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const a=Object.keys(e).length,s=t.inputNames.length;if(a>s){let i=Object.keys(e).filter(o=>!t.inputNames.includes(o));console.warn(`WARNING: Too many inputs were provided (${a} > ${s}). The following inputs will be ignored: "${i.join(", ")}".`)}return r}async function Lr(t,e){const r=k1(t,e);try{const n=Object.fromEntries(Object.entries(r).map(([s,i])=>[s,i.ort_tensor]));let a=await t.run(n);return a=Km(a),a}catch(n){throw console.error(`An error occurred during model execution: "${n}".`),console.error("Inputs given to model:",r),n}}function Km(t){for(let e in t)mm(t[e])?t[e]=new ce(t[e]):typeof t[e]=="object"&&Km(t[e]);return t}function Ym(t){if(t instanceof ce)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 ce("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new ce("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function Xm(t){return new ce("bool",[t],[1])}async function Qm(t,e){let{encoder_outputs:r,past_key_values:n}=e;if(!r){const l=$r(e,t.sessions.model.inputNames);r=(await Rn(t,l)).last_hidden_state}const{input_ids:a,decoder_input_ids:s,...i}=e;return i.input_ids=s,i.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=e.attention_mask),await Ui(t,i,!0)}async function Rn(t,e){const r=t.sessions.model,n=$r(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!n.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");n.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}return r.inputNames.includes("token_type_ids")&&!n.token_type_ids&&(n.token_type_ids=new ce("int64",new BigInt64Array(n.input_ids.data.length),n.input_ids.dims)),await Lr(r,n)}async function Ui(t,e,r=!1){const n=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:a,...s}=e;n.inputNames.includes("use_cache_branch")&&(s.use_cache_branch=Xm(!!a)),n.inputNames.includes("position_ids")&&s.attention_mask&&!s.position_ids&&(s.position_ids=C1(s,a)),t.addPastKeyValues(s,a);const i=$r(s,n.inputNames);return await Lr(n,i)}async function E1(t,{input_ids:e=null,attention_mask:r=null,pixel_values:n=null,position_ids:a=null,inputs_embeds:s=null,past_key_values:i=null,generation_config:o=null,logits_processor:l=null,...u}){if(!s){if(s=await t.encode_text({input_ids:e}),n&&e.dims[1]!==1){const h=await t.encode_image({pixel_values:n});({inputs_embeds:s,attention_mask:r}=t._merge_input_ids_with_image_features({image_features:h,inputs_embeds:s,input_ids:e,attention_mask:r}))}else if(i&&n&&e.dims[1]===1){const h=e.dims[1],m=Object.values(i)[0].dims.at(-2);r=Xt([In([e.dims[0],m]),r.slice(null,[r.dims[1]-h,r.dims[1]])],1)}}return await Ui(t,{inputs_embeds:s,past_key_values:i,attention_mask:r,position_ids:a,generation_config:o,logits_processor:l},!0)}function C1(t,e=null){const{input_ids:r,inputs_embeds:n,attention_mask:a}=t,[s,i]=a.dims,o=new BigInt64Array(a.data.length);for(let u=0;us.dims[1])){if(ao==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=s.dims[1]-(a-o);r.input_ids=s.slice(null,[-l,null]),r.attention_mask=In([1,a+l])}}}return r}function Jm(t,e,r,n){const{...a}=r;return r.past_key_values&&(e=e.map(i=>[i.at(-1)])),a.decoder_input_ids=Ym(e),a}function T1(t,...e){return t.config.is_encoder_decoder?Jm(t,...e):Zm(t,...e)}class Z extends wt{constructor(r,n){super();B(this,"main_input_name","input_ids");B(this,"forward_params",["input_ids","attention_mask"]);this.config=r,this.sessions=n;const a=ba.get(this.constructor),s=Li.get(a);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,s){case $e.DecoderOnly:this.can_generate=!0,this._forward=Ui,this._prepare_inputs_for_generation=Zm;break;case $e.Seq2Seq:case $e.Vision2Seq:case $e.Musicgen:this.can_generate=!0,this._forward=Qm,this._prepare_inputs_for_generation=Jm;break;case $e.EncoderDecoder:this._forward=Qm;break;case $e.ImageTextToText:this.can_generate=!0,this._forward=E1,this._prepare_inputs_for_generation=T1;break;default:this._forward=Rn;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var n;const r=[];for(const a of Object.values(this.sessions))(n=a==null?void 0:a.handler)!=null&&n.dispose&&r.push(a.handler.dispose());return await Promise.all(r)}static async from_pretrained(r,{progress_callback:n=null,config:a=null,cache_dir:s=null,local_files_only:i=!1,revision:o="main",model_file_name:l=null,subfolder:u="onnx",device:d=null,dtype:h=null,use_external_data_format:m=null,session_options:g={}}={}){let p={progress_callback:n,config:a,cache_dir:s,local_files_only:i,revision:o,model_file_name:l,subfolder:u,device:d,dtype:h,use_external_data_format:m,session_options:g};const w=ba.get(this),v=Li.get(w);a=p.config=await Vm.from_pretrained(r,p);let S;if(v===$e.DecoderOnly)S=await Promise.all([sn(r,{model:p.model_file_name??"model"},p),Rr(r,"generation_config.json",!1,p)]);else if(v===$e.Seq2Seq||v===$e.Vision2Seq)S=await Promise.all([sn(r,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p),Rr(r,"generation_config.json",!1,p)]);else if(v===$e.MaskGeneration)S=await Promise.all([sn(r,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},p)]);else if(v===$e.EncoderDecoder)S=await Promise.all([sn(r,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p)]);else if(v===$e.ImageTextToText){const $={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};a.is_encoder_decoder&&($.model="encoder_model"),S=await Promise.all([sn(r,$,p),Rr(r,"generation_config.json",!1,p)])}else v===$e.Musicgen?S=await Promise.all([sn(r,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},p),Rr(r,"generation_config.json",!1,p)]):(v!==$e.EncoderOnly&&console.warn(`Model type for '${w??(a==null?void 0:a.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),S=await Promise.all([sn(r,{model:p.model_file_name??"model"},p)]));return new this(a,...S)}async _call(r){return await this.forward(r)}async forward(r){return await this._forward(this,r)}_get_logits_warper(r){const n=new Ni;return r.temperature!==null&&r.temperature!==1&&n.push(new m1(r.temperature)),r.top_k!==null&&r.top_k!==0&&n.push(new _1(r.top_k)),r.top_p!==null&&r.top_p<1&&n.push(new g1(r.top_p)),n}_get_logits_processor(r,n,a=null){const s=new Ni;if(r.repetition_penalty!==null&&r.repetition_penalty!==1&&s.push(new d1(r.repetition_penalty)),r.no_repeat_ngram_size!==null&&r.no_repeat_ngram_size>0&&s.push(new u1(r.no_repeat_ngram_size)),r.bad_words_ids!==null&&s.push(new h1(r.bad_words_ids,r.eos_token_id)),r.min_length!==null&&r.eos_token_id!==null&&r.min_length>0&&s.push(new c1(r.min_length,r.eos_token_id)),r.min_new_tokens!==null&&r.eos_token_id!==null&&r.min_new_tokens>0&&s.push(new p1(n,r.min_new_tokens,r.eos_token_id)),r.forced_bos_token_id!==null&&s.push(new s1(r.forced_bos_token_id)),r.forced_eos_token_id!==null&&s.push(new o1(r.max_length,r.forced_eos_token_id)),r.begin_suppress_tokens!==null){const i=n>1||r.forced_bos_token_id===null?n:n+1;s.push(new Hm(r.begin_suppress_tokens,i))}return r.guidance_scale!==null&&r.guidance_scale>1&&s.push(new f1(r.guidance_scale)),a!==null&&s.extend(a),s}_prepare_generation_config(r,n,a=jm){const s={...this.config};for(const o of["decoder","generator","text_config"])o in s&&Object.assign(s,s[o]);const i=new a(s);return"generation_config"in this&&Object.assign(i,this.generation_config),r&&Object.assign(i,r),n&&Object.assign(i,$r(n,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(r,n=null){const a=new Jo;return r.max_length!==null&&a.push(new y1(r.max_length,this.config.max_position_embeddings??null)),r.eos_token_id!==null&&a.push(new w1(r.eos_token_id)),n&&a.extend(n),a}_validate_model_class(){if(!this.can_generate){const r=[ol,ll,sl,il],n=ba.get(this.constructor),a=new Set,s=this.config.model_type;for(const o of r){const l=o.get(s);l&&a.add(l[0])}let i=`The current model class (${n}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw a.size>0&&(i+=` Please use the following class instead: ${[...a].join(", ")}`),Error(i)}}prepare_inputs_for_generation(...r){return this._prepare_inputs_for_generation(this,...r)}_update_model_kwargs_for_generation({generated_input_ids:r,outputs:n,model_inputs:a,is_encoder_decoder:s}){return a.past_key_values=this.getPastKeyValues(n,a.past_key_values),a.input_ids=new ce("int64",r.flat(),[r.length,1]),s||(a.attention_mask=Xt([a.attention_mask,In([a.attention_mask.dims[0],1])],1)),a.position_ids=null,a}_prepare_model_inputs({inputs:r,bos_token_id:n,model_kwargs:a}){const s=$r(a,this.forward_params),i=this.main_input_name;if(i in s){if(r)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else s[i]=r;return{inputs_tensor:s[i],model_inputs:s,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:r,model_inputs:n,model_input_name:a,generation_config:s}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!n.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:o,pixel_values:l,attention_mask:u,...d}=n,h=await this._prepare_inputs_embeds(n);n={...d,...$r(h,["inputs_embeds","attention_mask"])}}let{last_hidden_state:i}=await Rn(this,n);return s.guidance_scale!==null&&s.guidance_scale>1&&(i=Xt([i,Hw(i,0)],0),"attention_mask"in n&&(n.attention_mask=Xt([n.attention_mask,Kw(n.attention_mask)],0))),n.encoder_outputs=i,n}_prepare_decoder_input_ids_for_generation({batch_size:r,model_input_name:n,model_kwargs:a,decoder_start_token_id:s,bos_token_id:i,generation_config:o}){let{decoder_input_ids:l,...u}=a;if(l)Array.isArray(l[0])||(l=Array.from({length:r},()=>l));else if(s??(s=i),this.config.model_type==="musicgen")l=Array.from({length:r*this.config.decoder.num_codebooks},()=>[s]);else if(Array.isArray(s)){if(s.length!==r)throw new Error(`\`decoder_start_token_id\` expcted to have length ${r} but got ${s.length}`);l=s}else l=Array.from({length:r},()=>[s]);return l=Ym(l),a.decoder_attention_mask=jw(l),{input_ids:l,model_inputs:u}}async generate({inputs:r=null,generation_config:n=null,logits_processor:a=null,stopping_criteria:s=null,streamer:i=null,...o}){this._validate_model_class(),n=this._prepare_generation_config(n,o);let{inputs_tensor:l,model_inputs:u,model_input_name:d}=this._prepare_model_inputs({inputs:r,model_kwargs:o});const h=this.config.is_encoder_decoder;h&&("encoder_outputs"in u||(u=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:l,model_inputs:u,model_input_name:d,generation_config:n})));let m;h?{input_ids:m,model_inputs:u}=this._prepare_decoder_input_ids_for_generation({batch_size:u[d].dims.at(0),model_input_name:d,model_kwargs:u,decoder_start_token_id:n.decoder_start_token_id,bos_token_id:n.bos_token_id,generation_config:n}):m=u[d];let g=m.dims.at(-1);n.max_new_tokens!==null&&(n.max_length=g+n.max_new_tokens);const p=this._get_logits_processor(n,g,a),w=this._get_stopping_criteria(n,s),v=u[d].dims.at(0),S=Fi.getSampler(n),$=new Array(v).fill(0),E=m.tolist();i&&i.put(E);let T=null,A={};for(;;){u=this.prepare_inputs_for_generation(E,u,n);const R=await this.forward(u);if(n.output_attentions&&n.return_dict_in_generate){const ee=this.getAttentions(R);for(const ne in ee)ne in A||(A[ne]=[]),A[ne].push(ee[ne])}const V=R.logits.slice(null,-1,null),j=p(E,V),q=[];for(let ee=0;eeee)){n.return_dict_in_generate&&(T=this.getPastKeyValues(R,u.past_key_values,!1));break}u=this._update_model_kwargs_for_generation({generated_input_ids:q,outputs:R,model_inputs:u,is_encoder_decoder:h})}i&&i.end();const z=new ce("int64",E.flat(),[E.length,E[0].length]);return n.return_dict_in_generate?{sequences:z,past_key_values:T,...A}:z}getPastKeyValues(r,n,a=!0){const s=Object.create(null);for(const i in r)if(i.startsWith("present")){const o=i.replace("present","past_key_values");if(n&&i.includes("encoder"))s[o]=n[o];else{if(a&&n){const l=n[o];l.location==="gpu-buffer"&&l.dispose()}s[o]=r[i]}}return s}getAttentions(r){const n={};for(const a of["cross_attentions","encoder_attentions","decoder_attentions"])for(const s in r)s.startsWith(a)&&(a in n||(n[a]=[]),n[a].push(r[s]));return n}addPastKeyValues(r,n){if(n)Object.assign(r,n);else{const a=this.custom_config.kv_cache_dtype??"float32",s=a==="float16"?new Uint16Array:[],i=Wm(this.config);for(const o in i)r[o]=new ce(a,s,i[o])}}async encode_image({pixel_values:r}){const n=(await Lr(this.sessions.vision_encoder,{pixel_values:r})).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 (${n.dims[1]}).`),this.config.num_image_tokens=n.dims[1]),n}async encode_text({input_ids:r}){return(await Lr(this.sessions.embed_tokens,{input_ids:r})).inputs_embeds}}class Wt{}class va extends Z{}class A1 extends va{}class I1 extends va{async _call(e){return new $t(await super._call(e))}}class M1 extends va{async _call(e){return new Me(await super._call(e))}}class O1 extends va{async _call(e){return new vt(await super._call(e))}}class z1 extends va{async _call(e){return new Tt(await super._call(e))}}class P1 extends Z{}class R1 extends P1{}class $a extends Z{}class B1 extends $a{}class D1 extends $a{async _call(e){return new $t(await super._call(e))}}class N1 extends $a{async _call(e){return new Me(await super._call(e))}}class F1 extends $a{async _call(e){return new vt(await super._call(e))}}class L1 extends $a{async _call(e){return new Tt(await super._call(e))}}class xa extends Z{}class U1 extends xa{}class W1 extends xa{async _call(e){return new $t(await super._call(e))}}class V1 extends xa{async _call(e){return new Me(await super._call(e))}}class G1 extends xa{async _call(e){return new vt(await super._call(e))}}class H1 extends xa{async _call(e){return new Tt(await super._call(e))}}class Sa extends Z{}class j1 extends Sa{}class q1 extends Sa{async _call(e){return new $t(await super._call(e))}}class K1 extends Sa{async _call(e){return new Me(await super._call(e))}}class Y1 extends Sa{async _call(e){return new vt(await super._call(e))}}class X1 extends Sa{async _call(e){return new Tt(await super._call(e))}}class ka extends Z{}class Q1 extends ka{}class Z1 extends ka{async _call(e){return new $t(await super._call(e))}}class J1 extends ka{async _call(e){return new Me(await super._call(e))}}class e2 extends ka{async _call(e){return new vt(await super._call(e))}}class t2 extends ka{async _call(e){return new Tt(await super._call(e))}}class Ea extends Z{}class r2 extends Ea{}class n2 extends Ea{async _call(e){return new $t(await super._call(e))}}class a2 extends Ea{async _call(e){return new Me(await super._call(e))}}class i2 extends Ea{async _call(e){return new vt(await super._call(e))}}class s2 extends Ea{async _call(e){return new Tt(await super._call(e))}}class Ca extends Z{}class o2 extends Ca{}class l2 extends Ca{async _call(e){return new $t(await super._call(e))}}class u2 extends Ca{async _call(e){return new Me(await super._call(e))}}class d2 extends Ca{async _call(e){return new vt(await super._call(e))}}class c2 extends Ca{async _call(e){return new Tt(await super._call(e))}}class Ta extends Z{}class p2 extends Ta{}class h2 extends Ta{async _call(e){return new Me(await super._call(e))}}class f2 extends Ta{async _call(e){return new vt(await super._call(e))}}class m2 extends Ta{async _call(e){return new Tt(await super._call(e))}}class g2 extends Ta{async _call(e){return new $t(await super._call(e))}}class Wi extends Z{}class _2 extends Wi{}class y2 extends Wi{async _call(e){return new $t(await super._call(e))}}class w2 extends Wi{async _call(e){return new Me(await super._call(e))}}class b2 extends Wi{async _call(e){return new vt(await super._call(e))}}class Vi extends Z{}class v2 extends Vi{}class $2 extends Vi{async _call(e){return new $t(await super._call(e))}}class x2 extends Vi{async _call(e){return new Me(await super._call(e))}}class S2 extends Vi{async _call(e){return new Tt(await super._call(e))}}class Aa extends Z{}class k2 extends Aa{}class E2 extends Aa{async _call(e){return new $t(await super._call(e))}}class C2 extends Aa{async _call(e){return new Me(await super._call(e))}}class T2 extends Aa{async _call(e){return new vt(await super._call(e))}}class A2 extends Aa{async _call(e){return new Tt(await super._call(e))}}class Gi extends Z{}class I2 extends Gi{}class M2 extends Gi{async _call(e){return new $t(await super._call(e))}}class O2 extends Gi{async _call(e){return new Me(await super._call(e))}}class z2 extends Gi{async _call(e){return new Tt(await super._call(e))}}class Hi extends Z{}class P2 extends Hi{}class R2 extends Hi{async _call(e){return new Me(await super._call(e))}}class B2 extends Hi{async _call(e){return new Tt(await super._call(e))}}class D2 extends Hi{async _call(e){return new $t(await super._call(e))}}class eg extends Z{constructor(r,n,a){super(r,n);B(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=a}}class N2 extends eg{}class F2 extends eg{}class tg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class L2 extends tg{}class U2 extends tg{}class rg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class W2 extends rg{}class V2 extends rg{}class el extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class G2 extends el{}class H2 extends el{}class j2 extends el{async _call(e){return new Me(await super._call(e))}}class ji extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class q2 extends ji{}class K2 extends ji{}class Y2 extends ji{async _call(e){return new Me(await super._call(e))}}class X2 extends ji{}class ng extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class Q2 extends ng{}class Z2 extends ng{}class ag extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class J2 extends ag{}class e$ extends ag{}class Ia extends Z{}class t$ extends Ia{}class r$ extends Ia{async _call(e){return new $t(await super._call(e))}}class n$ extends Ia{async _call(e){return new Me(await super._call(e))}}class a$ extends Ia{async _call(e){return new vt(await super._call(e))}}class i$ extends Ia{async _call(e){return new Tt(await super._call(e))}}class Ma extends Z{}class s$ extends Ma{}class o$ extends Ma{async _call(e){return new $t(await super._call(e))}}class l$ extends Ma{async _call(e){return new Me(await super._call(e))}}class u$ extends Ma{async _call(e){return new vt(await super._call(e))}}class d$ extends Ma{async _call(e){return new Tt(await super._call(e))}}class Oa extends Z{}class c$ extends Oa{}class p$ extends Oa{async _call(e){return new $t(await super._call(e))}}class h$ extends Oa{async _call(e){return new Me(await super._call(e))}}class f$ extends Oa{async _call(e){return new vt(await super._call(e))}}class m$ extends Oa{async _call(e){return new Tt(await super._call(e))}}class ig extends Z{}class g$ extends ig{}class _$ extends ig{}class sg extends Z{constructor(r,n,a){super(r,n);B(this,"requires_attention_mask",!1);B(this,"main_input_name","input_features");B(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=a}}class y$ extends sg{}class w$ extends sg{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,x1)}_retrieve_init_tokens(e){const r=[e.decoder_start_token_id];let n=e.language;const a=e.task;if(e.is_multilingual){n||(console.warn("No language specified - defaulting to English (en)."),n="en");const i=`<|${Am(n)}|>`;r.push(e.lang_to_id[i]),r.push(e.task_to_id[a??"transcribe"])}else if(n||a)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&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(s=>s!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:n=null,stopping_criteria:a=null,...s}){r=this._prepare_generation_config(r,s);const i=this._retrieve_init_tokens(r);if(r.return_timestamps&&(n??(n=new Ni),n.push(new l1(r,i))),r.begin_suppress_tokens&&(n??(n=new Ni),n.push(new Hm(r.begin_suppress_tokens,i.length))),r.return_token_timestamps){if(!r.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.");r.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}const o=await super.generate({inputs:e,generation_config:r,logits_processor:n,decoder_input_ids:i,...s});return r.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,r.alignment_heads,r.num_frames)),o}_extract_token_timestamps(e,r,n=null,a=.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`.");n==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 s=this.config.median_filter_width;s===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),s=7);const i=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(w,v)=>Xt(i.map(S=>S[v]),2)),l=ha(r.map(([w,v])=>{if(w>=o.length)throw new Error(`Layer index ${w} is out of bounds for cross attentions (length ${o.length}).`);return n?o[w].slice(null,v,null,[0,n]):o[w].slice(null,v)})).transpose(1,0,2,3),[u,d]=Ww(l,-2,0,!0),h=l.clone();for(let w=0;wS[R+1]-S[R]),T=gt([1],E).map(z=>!!z),A=[];for(let z=0;zm.findIndex(g=>g==s)),l=o.every(m=>m===-1),u=o.every(m=>m!==-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:a};const d=[],h=[];for(let m=0;ms*i,1);e.input_labels=new ce("int64",new BigInt64Array(a).fill(1n),n)}const r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await Lr(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new cS(await super._call(e))}}class cS extends Wt{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}}class qg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class pS extends qg{}class hS extends qg{}class Kg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class fS extends Kg{}class mS extends Kg{}class on extends Z{}class gS extends on{}class _S extends on{async _call(e){return new Bn(await super._call(e))}}class yS extends on{async _call(e){return new Me(await super._call(e))}}class wS extends on{async _call(e){return new vt(await super._call(e))}}class rl extends Z{}class bS extends rl{}class vS extends rl{async _call(e){return new Bn(await super._call(e))}}class $S extends rl{async _call(e){return new Me(await super._call(e))}}class Ki extends Z{}class xS extends Ki{}class SS extends Ki{async _call(e){return new Bn(await super._call(e))}}class kS extends Ki{async _call(e){return new Me(await super._call(e))}}class ES extends Ki{async _call(e){return new vt(await super._call(e))}}class nl extends Z{}class CS extends nl{}class TS extends nl{async _call(e){return new Bn(await super._call(e))}}class AS extends nl{async _call(e){return new Me(await super._call(e))}}class IS extends on{}class MS extends on{async _call(e){return new Bn(await super._call(e))}}class OS extends on{async _call(e){return new Me(await super._call(e))}}class za extends Z{}class zS extends za{}class PS extends za{async _call(e){return new Bn(await super._call(e))}}class RS extends za{async _call(e){return new Me(await super._call(e))}}class BS extends za{async _call(e){return new xk(await super._call(e))}}class DS extends za{async _call(e){return new vt(await super._call(e))}}class Yg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class NS extends Yg{}class FS extends Yg{async generate_speech(e,r,{threshold:n=.5,minlenratio:a=0,maxlenratio:s=20,vocoder:i=null}={}){const o={input_ids:e},{encoder_outputs:l,encoder_attention_mask:u}=await Rn(this,o),d=l.dims[1]/this.config.reduction_factor,h=Math.floor(d*s),m=Math.floor(d*a),g=this.config.num_mel_bins;let p=[],w=null,v=null,S=0;for(;;){++S;const T=Xm(!!v);let A;v?A=v.output_sequence_out:A=new ce("float32",new Float32Array(g),[1,1,g]);let z={use_cache_branch:T,output_sequence:A,encoder_attention_mask:u,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(z,w),v=await Lr(this.sessions.decoder_model_merged,z),w=this.getPastKeyValues(v,w);const{prob:R,spectrum:V}=v;if(p.push(V),S>=m&&(Array.from(R.data).filter(j=>j>=n).length>0||S>=h))break}const $=Xt(p),{waveform:E}=await Lr(i.sessions.model,{spectrogram:$});return{spectrogram:$,waveform:E}}}class LS extends Z{constructor(){super(...arguments);B(this,"main_input_name","spectrogram")}}class US extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class WS extends US{}class Xg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class VS extends Xg{}class GS extends Xg{}class Qg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class HS extends Qg{}class jS extends Qg{}class Zg extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class qS extends Zg{}class KS extends Zg{}class al extends Z{}class YS extends al{}class XS extends al{static async from_pretrained(e,r={}){return r.model_file_name??(r.model_file_name="text_model"),super.from_pretrained(e,r)}}class QS extends al{static async from_pretrained(e,r={}){return r.model_file_name??(r.model_file_name="audio_model"),super.from_pretrained(e,r)}}class ZS extends Z{}class Jg extends ZS{async _call(e){return new kk(await super._call(e))}}class e_ extends Z{}class JS extends e_{}class ek extends e_{}class t_ extends Z{constructor(e,r,n){super(e,r),this.generation_config=n}}class tk extends t_{}class rk extends t_{}class r_ extends Z{}class nk extends r_{}class ak extends r_{async _call(e){return new Me(await super._call(e))}}class n_ extends Z{constructor(r,n,a){super(r,n);B(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=a}_apply_and_filter_by_delay_pattern_mask(r){const[n,a]=r.dims,s=this.config.decoder.num_codebooks,i=a-s;let o=0;for(let d=0;d0&&g<=i&&(r.data[o++]=r.data[d])}const l=Math.floor(n/s),u=o/(l*s);return new ce(r.type,r.data.slice(0,o),[l,s,u])}prepare_inputs_for_generation(r,n,a){let s=structuredClone(r);for(let o=0;o=l&&(s[o][l]=BigInt(this.config.decoder.pad_token_id));return a.guidance_scale!==null&&a.guidance_scale>1&&(s=s.concat(s)),super.prepare_inputs_for_generation(s,n,a)}async generate(r){const n=await super.generate(r),a=this._apply_and_filter_by_delay_pattern_mask(n).unsqueeze_(0),{audio_values:s}=await Lr(this.sessions.encodec_decode,{audio_codes:a});return s}}class a_ extends Z{}class ik extends a_{}class sk extends a_{async _call(e){return new Me(await super._call(e))}}class i_ extends Z{}class ok extends i_{}class lk extends i_{async _call(e){return new Me(await super._call(e))}}class s_ extends Z{}class uk extends s_{}class dk extends s_{async _call(e){return new Me(await super._call(e))}}class o_ extends Z{}class ck extends o_{}class pk extends o_{async _call(e){return new Me(await super._call(e))}}class Qe{static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:s=!1,revision:i="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:d=null,use_external_data_format:h=null,session_options:m={}}={}){let g={progress_callback:r,config:n,cache_dir:a,local_files_only:s,revision:i,model_file_name:o,subfolder:l,device:u,dtype:d,use_external_data_format:h,session_options:m};if(g.config=await Vm.from_pretrained(e,g),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let p of this.MODEL_CLASS_MAPPINGS){const w=p.get(g.config.model_type);if(w)return await w[1].from_pretrained(e,g)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${g.config.model_type}", attempting to construct from base class.`),await Z.from_pretrained(e,g);throw Error(`Unsupported model type: ${g.config.model_type}`)}}B(Qe,"MODEL_CLASS_MAPPINGS",null),B(Qe,"BASE_IF_FAIL",!1);const hk=new Map([["bert",["BertModel",A1]],["nomic_bert",["NomicBertModel",R1]],["roformer",["RoFormerModel",B1]],["electra",["ElectraModel",j1]],["esm",["EsmModel",_2]],["convbert",["ConvBertModel",U1]],["camembert",["CamembertModel",Q1]],["deberta",["DebertaModel",r2]],["deberta-v2",["DebertaV2Model",o2]],["mpnet",["MPNetModel",k2]],["albert",["AlbertModel",P2]],["distilbert",["DistilBertModel",p2]],["roberta",["RobertaModel",t$]],["xlm",["XLMModel",s$]],["xlm-roberta",["XLMRobertaModel",c$]],["clap",["ClapModel",YS]],["clip",["CLIPModel",S$]],["clipseg",["CLIPSegModel",O$]],["chinese_clip",["ChineseCLIPModel",M$]],["siglip",["SiglipModel",C$]],["mobilebert",["MobileBertModel",v2]],["squeezebert",["SqueezeBertModel",I2]],["wav2vec2",["Wav2Vec2Model",gS]],["wav2vec2-bert",["Wav2Vec2BertModel",CS]],["unispeech",["UniSpeechModel",bS]],["unispeech-sat",["UniSpeechSatModel",xS]],["hubert",["HubertModel",IS]],["wavlm",["WavLMModel",zS]],["audio-spectrogram-transformer",["ASTModel",g$]],["vits",["VitsModel",Jg]],["detr",["DetrModel",Tx]],["rt_detr",["RTDetrModel",Ox]],["table-transformer",["TableTransformerModel",Rx]],["vit",["ViTModel",px]],["fastvit",["FastViTModel",fx]],["mobilevit",["MobileViTModel",yx]],["mobilevitv2",["MobileViTV2Model",bx]],["owlvit",["OwlViTModel",$x]],["owlv2",["Owlv2Model",Sx]],["beit",["BeitModel",Ex]],["deit",["DeiTModel",Nx]],["convnext",["ConvNextModel",eS]],["convnextv2",["ConvNextV2Model",rS]],["dinov2",["Dinov2Model",aS]],["resnet",["ResNetModel",Lx]],["swin",["SwinModel",Wx]],["swin2sr",["Swin2SRModel",Gx]],["donut-swin",["DonutSwinModel",Jx]],["yolos",["YolosModel",sS]],["dpt",["DPTModel",jx]],["glpn",["GLPNModel",Xx]],["hifigan",["SpeechT5HifiGan",LS]],["efficientnet",["EfficientNetModel",nk]],["mobilenet_v1",["MobileNetV1Model",ik]],["mobilenet_v2",["MobileNetV2Model",ok]],["mobilenet_v3",["MobileNetV3Model",uk]],["mobilenet_v4",["MobileNetV4Model",ck]]]),fk=new Map([["t5",["T5Model",N2]],["longt5",["LongT5Model",L2]],["mt5",["MT5Model",W2]],["bart",["BartModel",G2]],["mbart",["MBartModel",q2]],["marian",["MarianModel",pS]],["whisper",["WhisperModel",y$]],["m2m_100",["M2M100Model",fS]],["blenderbot",["BlenderbotModel",Q2]],["blenderbot-small",["BlenderbotSmallModel",J2]]]),mk=new Map([["bloom",["BloomModel",sx]],["gpt2",["GPT2Model",P$]],["gptj",["GPTJModel",L$]],["gpt_bigcode",["GPTBigCodeModel",W$]],["gpt_neo",["GPTNeoModel",B$]],["gpt_neox",["GPTNeoXModel",N$]],["codegen",["CodeGenModel",G$]],["llama",["LlamaModel",j$]],["cohere",["CohereModel",K$]],["gemma",["GemmaModel",X$]],["openelm",["OpenELMModel",Z$]],["qwen2",["Qwen2Model",ex]],["phi",["PhiModel",rx]],["phi3",["Phi3Model",ax]],["mpt",["MptModel",lx]],["opt",["OPTModel",dx]],["mistral",["MistralModel",VS]],["starcoder2",["Starcoder2Model",HS]],["falcon",["FalconModel",qS]],["stablelm",["StableLmModel",tk]]]),il=new Map([["speecht5",["SpeechT5ForSpeechToText",NS]],["whisper",["WhisperForConditionalGeneration",w$]]]),l_=new Map([["speecht5",["SpeechT5ForTextToSpeech",FS]]]),u_=new Map([["vits",["VitsModel",Jg]],["musicgen",["MusicgenForConditionalGeneration",n_]]]),d_=new Map([["bert",["BertForSequenceClassification",M1]],["roformer",["RoFormerForSequenceClassification",N1]],["electra",["ElectraForSequenceClassification",K1]],["esm",["EsmForSequenceClassification",w2]],["convbert",["ConvBertForSequenceClassification",V1]],["camembert",["CamembertForSequenceClassification",J1]],["deberta",["DebertaForSequenceClassification",a2]],["deberta-v2",["DebertaV2ForSequenceClassification",u2]],["mpnet",["MPNetForSequenceClassification",C2]],["albert",["AlbertForSequenceClassification",R2]],["distilbert",["DistilBertForSequenceClassification",h2]],["roberta",["RobertaForSequenceClassification",n$]],["xlm",["XLMForSequenceClassification",l$]],["xlm-roberta",["XLMRobertaForSequenceClassification",h$]],["bart",["BartForSequenceClassification",j2]],["mbart",["MBartForSequenceClassification",Y2]],["mobilebert",["MobileBertForSequenceClassification",x2]],["squeezebert",["SqueezeBertForSequenceClassification",O2]]]),c_=new Map([["bert",["BertForTokenClassification",O1]],["roformer",["RoFormerForTokenClassification",F1]],["electra",["ElectraForTokenClassification",Y1]],["esm",["EsmForTokenClassification",b2]],["convbert",["ConvBertForTokenClassification",G1]],["camembert",["CamembertForTokenClassification",e2]],["deberta",["DebertaForTokenClassification",i2]],["deberta-v2",["DebertaV2ForTokenClassification",d2]],["mpnet",["MPNetForTokenClassification",T2]],["distilbert",["DistilBertForTokenClassification",f2]],["roberta",["RobertaForTokenClassification",a$]],["xlm",["XLMForTokenClassification",u$]],["xlm-roberta",["XLMRobertaForTokenClassification",f$]]]),sl=new Map([["t5",["T5ForConditionalGeneration",F2]],["longt5",["LongT5ForConditionalGeneration",U2]],["mt5",["MT5ForConditionalGeneration",V2]],["bart",["BartForConditionalGeneration",H2]],["mbart",["MBartForConditionalGeneration",K2]],["marian",["MarianMTModel",hS]],["m2m_100",["M2M100ForConditionalGeneration",mS]],["blenderbot",["BlenderbotForConditionalGeneration",Z2]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",e$]]]),ol=new Map([["bloom",["BloomForCausalLM",ox]],["gpt2",["GPT2LMHeadModel",R$]],["gptj",["GPTJForCausalLM",U$]],["gpt_bigcode",["GPTBigCodeForCausalLM",V$]],["gpt_neo",["GPTNeoForCausalLM",D$]],["gpt_neox",["GPTNeoXForCausalLM",F$]],["codegen",["CodeGenForCausalLM",H$]],["llama",["LlamaForCausalLM",q$]],["cohere",["CohereForCausalLM",Y$]],["gemma",["GemmaForCausalLM",Q$]],["openelm",["OpenELMForCausalLM",J$]],["qwen2",["Qwen2ForCausalLM",tx]],["phi",["PhiForCausalLM",nx]],["phi3",["Phi3ForCausalLM",ix]],["mpt",["MptForCausalLM",ux]],["opt",["OPTForCausalLM",cx]],["mbart",["MBartForCausalLM",X2]],["mistral",["MistralForCausalLM",GS]],["starcoder2",["Starcoder2ForCausalLM",jS]],["falcon",["FalconForCausalLM",KS]],["trocr",["TrOCRForCausalLM",WS]],["stablelm",["StableLmForCausalLM",rk]]]),p_=new Map([["bert",["BertForMaskedLM",I1]],["roformer",["RoFormerForMaskedLM",D1]],["electra",["ElectraForMaskedLM",q1]],["esm",["EsmForMaskedLM",y2]],["convbert",["ConvBertForMaskedLM",W1]],["camembert",["CamembertForMaskedLM",Z1]],["deberta",["DebertaForMaskedLM",n2]],["deberta-v2",["DebertaV2ForMaskedLM",l2]],["mpnet",["MPNetForMaskedLM",E2]],["albert",["AlbertForMaskedLM",D2]],["distilbert",["DistilBertForMaskedLM",g2]],["roberta",["RobertaForMaskedLM",r$]],["xlm",["XLMWithLMHeadModel",o$]],["xlm-roberta",["XLMRobertaForMaskedLM",p$]],["mobilebert",["MobileBertForMaskedLM",$2]],["squeezebert",["SqueezeBertForMaskedLM",M2]]]),h_=new Map([["bert",["BertForQuestionAnswering",z1]],["roformer",["RoFormerForQuestionAnswering",L1]],["electra",["ElectraForQuestionAnswering",X1]],["convbert",["ConvBertForQuestionAnswering",H1]],["camembert",["CamembertForQuestionAnswering",t2]],["deberta",["DebertaForQuestionAnswering",s2]],["deberta-v2",["DebertaV2ForQuestionAnswering",c2]],["mpnet",["MPNetForQuestionAnswering",A2]],["albert",["AlbertForQuestionAnswering",B2]],["distilbert",["DistilBertForQuestionAnswering",m2]],["roberta",["RobertaForQuestionAnswering",i$]],["xlm",["XLMForQuestionAnswering",d$]],["xlm-roberta",["XLMRobertaForQuestionAnswering",m$]],["mobilebert",["MobileBertForQuestionAnswering",S2]],["squeezebert",["SqueezeBertForQuestionAnswering",z2]]]),ll=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",og]]]),gk=new Map([["llava",["LlavaForConditionalGeneration",lg]],["moondream1",["Moondream1ForConditionalGeneration",v$]],["florence2",["Florence2ForConditionalGeneration",x$]]]),_k=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",og]]]),f_=new Map([["vit",["ViTForImageClassification",hx]],["fastvit",["FastViTForImageClassification",mx]],["mobilevit",["MobileViTForImageClassification",wx]],["mobilevitv2",["MobileViTV2ForImageClassification",vx]],["beit",["BeitForImageClassification",Cx]],["deit",["DeiTForImageClassification",Fx]],["convnext",["ConvNextForImageClassification",tS]],["convnextv2",["ConvNextV2ForImageClassification",nS]],["dinov2",["Dinov2ForImageClassification",iS]],["resnet",["ResNetForImageClassification",Ux]],["swin",["SwinForImageClassification",Vx]],["segformer",["SegformerForImageClassification",JS]],["efficientnet",["EfficientNetForImageClassification",ak]],["mobilenet_v1",["MobileNetV1ForImageClassification",sk]],["mobilenet_v2",["MobileNetV2ForImageClassification",lk]],["mobilenet_v3",["MobileNetV3ForImageClassification",dk]],["mobilenet_v4",["MobileNetV4ForImageClassification",pk]]]),m_=new Map([["detr",["DetrForObjectDetection",Ax]],["rt_detr",["RTDetrForObjectDetection",zx]],["table-transformer",["TableTransformerForObjectDetection",Bx]],["yolos",["YolosForObjectDetection",oS]]]),g_=new Map([["owlvit",["OwlViTForObjectDetection",xx]],["owlv2",["Owlv2ForObjectDetection",kx]]]),__=new Map([["detr",["DetrForSegmentation",Ix]],["clipseg",["CLIPSegForImageSegmentation",z$]]]),y_=new Map([["segformer",["SegformerForSemanticSegmentation",ek]]]),yk=new Map([["sam",["SamModel",dS]]]),w_=new Map([["wav2vec2",["Wav2Vec2ForCTC",_S]],["wav2vec2-bert",["Wav2Vec2BertForCTC",TS]],["unispeech",["UniSpeechForCTC",vS]],["unispeech-sat",["UniSpeechSatForCTC",SS]],["wavlm",["WavLMForCTC",PS]],["hubert",["HubertForCTC",MS]]]),b_=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",yS]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",AS]],["unispeech",["UniSpeechForSequenceClassification",$S]],["unispeech-sat",["UniSpeechSatForSequenceClassification",kS]],["wavlm",["WavLMForSequenceClassification",RS]],["hubert",["HubertForSequenceClassification",OS]],["audio-spectrogram-transformer",["ASTForAudioClassification",_$]]]),wk=new Map([["wavlm",["WavLMForXVector",BS]]]),bk=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",ES]],["wavlm",["WavLMForAudioFrameClassification",DS]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",wS]]]),vk=new Map([["vitmatte",["VitMatteForImageMatting",_x]]]),v_=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Hx]]]),$_=new Map([["dpt",["DPTForDepthEstimation",qx]],["depth_anything",["DepthAnythingForDepthEstimation",Yx]],["glpn",["GLPNForDepthEstimation",Qx]]]),x_=new Map([["clip",["CLIPVisionModelWithProjection",E$]],["siglip",["SiglipVisionModel",A$]]]),S_=[[hk,$e.EncoderOnly],[fk,$e.EncoderDecoder],[mk,$e.DecoderOnly],[d_,$e.EncoderOnly],[c_,$e.EncoderOnly],[sl,$e.Seq2Seq],[il,$e.Seq2Seq],[ol,$e.DecoderOnly],[p_,$e.EncoderOnly],[h_,$e.EncoderOnly],[ll,$e.Vision2Seq],[gk,$e.ImageTextToText],[f_,$e.EncoderOnly],[__,$e.EncoderOnly],[y_,$e.EncoderOnly],[vk,$e.EncoderOnly],[v_,$e.EncoderOnly],[$_,$e.EncoderOnly],[m_,$e.EncoderOnly],[g_,$e.EncoderOnly],[yk,$e.MaskGeneration],[w_,$e.EncoderOnly],[b_,$e.EncoderOnly],[l_,$e.Seq2Seq],[u_,$e.EncoderOnly],[wk,$e.EncoderOnly],[bk,$e.EncoderOnly],[x_,$e.EncoderOnly]];for(const[t,e]of S_)for(const[r,n]of t.values())Li.set(r,e),ba.set(n,r),qm.set(r,n);const $k=[["MusicgenForConditionalGeneration",n_,$e.Musicgen],["CLIPTextModelWithProjection",k$,$e.EncoderOnly],["SiglipTextModel",T$,$e.EncoderOnly],["ClapTextModelWithProjection",XS,$e.EncoderOnly],["ClapAudioModelWithProjection",QS,$e.EncoderOnly]];for(const[t,e,r]of $k)Li.set(t,r),ba.set(e,t),qm.set(t,e);class ln extends Qe{}B(ln,"MODEL_CLASS_MAPPINGS",S_.map(e=>e[0])),B(ln,"BASE_IF_FAIL",!0);class ul extends Qe{}B(ul,"MODEL_CLASS_MAPPINGS",[d_]);class k_ extends Qe{}B(k_,"MODEL_CLASS_MAPPINGS",[c_]);class Yi extends Qe{}B(Yi,"MODEL_CLASS_MAPPINGS",[sl]);class E_ extends Qe{}B(E_,"MODEL_CLASS_MAPPINGS",[il]);class C_ extends Qe{}B(C_,"MODEL_CLASS_MAPPINGS",[l_]);class T_ extends Qe{}B(T_,"MODEL_CLASS_MAPPINGS",[u_]);class A_ extends Qe{}B(A_,"MODEL_CLASS_MAPPINGS",[ol]);class I_ extends Qe{}B(I_,"MODEL_CLASS_MAPPINGS",[p_]);class M_ extends Qe{}B(M_,"MODEL_CLASS_MAPPINGS",[h_]);class O_ extends Qe{}B(O_,"MODEL_CLASS_MAPPINGS",[ll]);class z_ extends Qe{}B(z_,"MODEL_CLASS_MAPPINGS",[f_]);class P_ extends Qe{}B(P_,"MODEL_CLASS_MAPPINGS",[__]);class R_ extends Qe{}B(R_,"MODEL_CLASS_MAPPINGS",[y_]);class B_ extends Qe{}B(B_,"MODEL_CLASS_MAPPINGS",[m_]);class D_ extends Qe{}B(D_,"MODEL_CLASS_MAPPINGS",[g_]);class N_ extends Qe{}B(N_,"MODEL_CLASS_MAPPINGS",[w_]);class F_ extends Qe{}B(F_,"MODEL_CLASS_MAPPINGS",[b_]);class L_ extends Qe{}B(L_,"MODEL_CLASS_MAPPINGS",[_k]);class U_ extends Qe{}B(U_,"MODEL_CLASS_MAPPINGS",[v_]);class W_ extends Qe{}B(W_,"MODEL_CLASS_MAPPINGS",[$_]);class V_ extends Qe{}B(V_,"MODEL_CLASS_MAPPINGS",[x_]);class Me extends Wt{constructor({logits:e}){super(),this.logits=e}}class xk extends Wt{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}}class vt extends Wt{constructor({logits:e}){super(),this.logits=e}}class $t extends Wt{constructor({logits:e}){super(),this.logits=e}}class Tt extends Wt{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}}class Bn extends Wt{constructor({logits:e}){super(),this.logits=e}}class Sk extends Wt{constructor({alphas:e}){super(),this.alphas=e}}class kk extends Wt{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}}const Zt=typeof self<"u",Ek=Zt&&self.constructor.name==="DedicatedWorkerGlobalScope";let un,G_,Ur;if(Zt)un=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},Ur=self.createImageBitmap,G_=self.ImageData;else if(Ve)Ur=async t=>{const r=(await t.metadata()).channels,{data:n,info:a}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),s=new At(new Uint8ClampedArray(n),a.width,a.height,a.channels);return r!==void 0&&r!==a.channels&&s.convert(r),s};else throw new Error("Unable to load image processing library.");const Ck={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},Tk=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class At{constructor(e,r,n,a){this.data=e,this.width=r,this.height=n,this.channels=a}get size(){return[this.width,this.height]}static async read(e){if(e instanceof At)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!Zt)throw new Error("fromCanvas() is only supported in browser environments.");const n=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new At(n,e.width,e.height,4)}static async fromURL(e){const r=await ni(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);const n=await r.blob();return this.fromBlob(n)}static async fromBlob(e){if(Zt){const r=await Ur(e),n=un(r.width,r.height).getContext("2d");return n.drawImage(r,0,0),new this(n.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=Ve(await e.arrayBuffer());return await Ur(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new At(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,n=0;r=0?l=n:d=-n,a>=0?u=a:h=-a,o.drawImage(i,l,u,e,r,d,h,e,r),new At(o.getImageData(0,0,e,r).data,e,r,4).convert(s)}else{let s=this.toSharp();if(n>=0&&a>=0)s=s.extract({left:Math.floor(n),top:Math.floor(a),width:e,height:r});else if(n<=0&&a<=0){const i=Math.floor(-a),o=Math.floor(-n);s=s.extend({top:i,left:o,right:e-this.width-o,bottom:r-this.height-i})}else{let i=[0,0],o=0;a<0?(i[0]=Math.floor(-a),i[1]=r-this.height-i[0]):o=Math.floor(a);let l=[0,0],u=0;n<0?(l[0]=Math.floor(-n),l[1]=e-this.width-l[0]):u=Math.floor(n),s=s.extend({top:i[0],bottom:i[1],left:l[0],right:l[1]}).extract({left:u,top:o,width:e,height:r})}return await Ur(s)}}async toBlob(e="image/png",r=1){if(!Zt)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new ce("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!Zt)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),r=un(e.width,e.height),n=new G_(e.data,e.width,e.height);return r.getContext("2d").putImageData(n,0,0),r}_update(e,r,n,a=null){return this.data=e,this.width=r,this.height=n,a!==null&&(this.channels=a),this}clone(){return new At(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(Zt){if(Ek)throw new Error("Unable to save an image from a Web Worker.");const r=e.split(".").pop().toLowerCase(),n=Tk.get(r)??"image/png",a=await this.toBlob(n),s=URL.createObjectURL(a),i=document.createElement("a");i.href=s,i.download=e,i.click(),i.remove()}else{if(Mt.useFS)return await this.toSharp().toFile(e);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Zt)throw new Error("toSharp() is only supported in server-side environments.");return Ve(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}async function Ak(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 r=await(await ni(t)).arrayBuffer(),n=new AudioContext({sampleRate:e});typeof e>"u"&&console.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);const a=await n.decodeAudioData(r);let s;if(a.numberOfChannels===2){const i=Math.sqrt(2),o=a.getChannelData(0),l=a.getChannelData(1);s=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,r=15,n=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*n:3*t/200};function dl(t,e="htk"){const r=Ik[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(n=>r(n))}const Mk={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,n=Math.log(6.4)/27)=>t>=r?e*Math.exp(n*(t-r)):200*t/3};function Ok(t,e="htk"){const r=Mk[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(n=>r(n))}function zk(t,e){const r=Float64Array.from({length:e.length-1},(i,o)=>e[o+1]-e[o]),n=Array.from({length:t.length},()=>new Array(e.length));for(let i=0;inew Array(t.length));for(let i=0;it+n*s)}function Pa(t,e,r,n,a,s=null,i="htk",o=!1){if(s!==null&&s!=="slaney")throw new Error('norm must be one of null or "slaney"');const l=dl(r,i),u=dl(n,i),d=j_(l,u,e+2);let h=Ok(d,i),m;if(o){const p=a/(t*2);m=dl(Float64Array.from({length:t},(w,v)=>v*p),i),h=d}else m=j_(0,Math.floor(a/2),t);const g=zk(m,h);if(s!==null&&s==="slaney")for(let p=0;pa)throw Error(`frame_length (${r}) may not be larger than fft_length (${a})`);if(T!==r)throw new Error(`Length of the window (${T}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(s===null&&d!==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 M=Math.floor((a-1)/2)+1;t=Pk(t,M,M)}const A=Math.floor(1+Math.floor((t.length-r)/n)),z=l?Math.floor(a/2)+1:a;let R=A,V=A;S!==null&&(S>A?$&&(V=S):V=R=S);const j=new ey(a),q=new Float64Array(a),fe=new Float64Array(j.outputBufferSize),ee=new Float32Array(z*V);for(let M=0;M=1;--K)q[K]-=u*q[K-1];q[0]*=1-u}for(let K=0;KMath.pow(o,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(i=i.subarray(0,t)),n===null)return i;if(t>n)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${n})`);return i}function Dk([t,e,r,n]){return[t-r/2,e-n/2,t+r/2,e+n/2]}function Zi(t,e=.5,r=null,n=!1){const a=t.logits,s=t.pred_boxes,[i,o,l]=a.dims;if(r!==null&&r.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 d=0;de&&S.push(E)}else{let E=qt(v.data)[1];if(E===l-1||($=bt(v.data),$[E]A*h[(z+1)%2])),m.boxes.push(T),m.classes.push(E),m.scores.push($[E])}}u.push(m)}return u}function Ra(t,e){var r;if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${((r=t==null?void 0:t.constructor)==null?void 0:r.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,r=0,n=null){const a=t/e;let s=ry(a)*e;return n!==null&&s>n&&(s=Math.floor(a)*e),ss?u=Math.floor(s*l/a):s>a&&(l=Math.floor(a*u/s)),await e.resize(u,l,{resample:n}))}async crop_margin(e,r=200){const n=e.clone().grayscale(),a=Bl(n.data)[0],i=qt(n.data)[0]-a;if(i===0)return e;const o=r/255;let l=n.width,u=n.height,d=0,h=0;const m=n.data;for(let g=0;gthis.preprocess(s)));return{pixel_values:ha(n.map(s=>s.pixel_values),0),original_sizes:n.map(s=>s.original_size),reshaped_input_sizes:n.map(s=>s.reshaped_input_size)}}}class Nk extends Ge{post_process_semantic_segmentation(e,r=null){const n=e.logits,a=n.dims[0];if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const s=[];for(let i=0;im[E]&&(m[E]=$[E],g[E]=S)}const p=new Array(l.dims[0]),w=h.data;for(let S=0;SS!==void 0);s.push({segmentation:h,labels:v})}return s}}class Y_ extends Ge{}class Fk extends Y_{}class Lk extends Ge{}class Uk extends Ge{}class X_ extends Ge{}class Wk extends X_{}class Vk extends Ge{}class Gk extends Ge{}class Q_ extends Ge{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){var n;const r=(n=this.size)==null?void 0:n.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){const a=Math.floor(r/this.crop_pct),[s,i]=this.get_resize_output_image_size(e,{shortest_edge:a});e=await e.resize(s,i,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}}class Hk extends Q_{}class jk extends Ge{}class qk extends Ge{}class Kk extends Ge{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}}class Yk extends Ge{}class Xk extends Ge{}class Qk extends Ge{}class Zk extends Ge{}class Z_ extends Ge{}class Jk extends Z_{}class J_ extends Ge{post_process_object_detection(...e){return Zi(...e)}}class e3 extends J_{}class t3 extends Ge{post_process_object_detection(...e){return Zi(...e)}}class r3 extends Ge{}class n3 extends Ge{}class e0 extends Ge{pad_image(e,r,n,a={}){const[s,i,o]=r;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 d=l.map((h,m)=>-h/u[m]);return super.pad_image(e,r,n,{center:!0,constant_values:d,...a})}}class a3 extends e0{}class i3 extends Ge{async _call(e){const r=await super._call(e),n=[r.pixel_values.dims[0],64,64],a=new ce("int64",new BigInt64Array(n.reduce((s,i)=>s*i)).fill(1n),n);return{...r,pixel_mask:a}}post_process_object_detection(...e){return Zi(...e)}remove_low_and_no_objects(e,r,n,a){let s=[],i=[],o=[];for(let l=0;ln&&(s.push(d),i.push(g),o.push(h))}return[s,i,o]}check_segment_validity(e,r,n,a=.5,s=.8){let i=[],o=0,l=0;const u=r[n].data;for(let h=0;h=a&&++l;let d=o>0&&l>0;return d&&(d=o/l>s),[d,i]}compute_segments(e,r,n,a,s,i=null,o=null){let[l,u]=o??e[0].dims,d=new ce("int32",new Int32Array(l*u),[l,u]),h=[];if(o!==null)for(let v=0;vg[E]&&(m[E]=v,g[E]=$[E])}let p=0;const w=d.data;for(let v=0;va!==r.dims[s]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new ce("int64",e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:r=null,input_labels:n=null,input_boxes:a=null}={}){const s=await super._call(e);if(r&&(s.input_points=this.reshape_input_points(r,s.original_sizes,s.reshaped_input_sizes)),n){if(!s.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");s.input_labels=this.add_input_labels(n,s.input_points)}return a&&(s.input_boxes=this.reshape_input_points(a,s.original_sizes,s.reshaped_input_sizes,!0)),s}async post_process_masks(e,r,n,{mask_threshold:a=0,binarize:s=!0,pad_size:i=null}={}){const o=[];i=i??this.pad_size;const l=[i.height,i.width];for(let u=0;ua&&(p[w]=1);m=new ce("bool",p,m.dims)}o.push(m)}return o}generate_crop_boxes(e,r,{crop_n_layers:n=0,overlap_ratio:a=512/1500,points_per_crop:s=32,crop_n_points_downscale_factor:i=1}={}){}}class l3 extends Ge{pad_image(e,r,n,a={}){const[s,i,o]=r;return super.pad_image(e,r,{width:i+(n-i%n)%n,height:s+(n-s%n)%n},{mode:"symmetric",center:!1,constant_values:-1,...a})}}class u3 extends Ge{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);const n=await Promise.all(e.map(i=>this.preprocess(i))),a=await Promise.all(r.map(i=>this.preprocess(i,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:ha(n.map((i,o)=>Xt([i.pixel_values,a[o].pixel_values],0)),0),original_sizes:n.map(i=>i.original_size),reshaped_input_sizes:n.map(i=>i.reshaped_input_size)}}}class d3 extends dn{constructor(e){var r;super(e),(r=this.config).mel_filters??(r.mel_filters=Pa(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=Qi(this.config.n_fft,"hann")}async _extract_fbank_features(e){const r=await Xi(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),n=r.data,a=qt(n)[0];for(let s=0;sthis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,this.config.n_samples)):(r=new Float32Array(this.config.n_samples),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}}class c3 extends dn{_zero_mean_unit_var_norm(e){const n=e.reduce((s,i)=>s+i,0)/e.length,a=e.reduce((s,i)=>s+(i-n)**2,0)/e.length;return e.map(s=>(s-n)/Math.sqrt(a+1e-7))}async _call(e){Ra(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));const n=[1,r.length];return{input_values:new ce("float32",r,n),attention_mask:new ce("int64",new BigInt64Array(r.length).fill(1n),n)}}}class p3 extends dn{constructor(e){super(e);const r=this.config.sampling_rate,n=Pa(256,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);for(let a=0;an*32768),Xi(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:a=!0,return_attention_mask:s=!0}={}){Ra(e,"SeamlessM4TFeatureExtractor");let i=await this._extract_fbank_features(e,this.config.max_length);if(a){const[p,w]=i.dims,v=i.data;for(let S=0;S0){const $=new Float32Array(w*(p+S));$.set(v),$.fill(this.config.padding_value,v.length);const E=p+S;i=new ce(i.type,$,[E,w]),s&&(o=new ce("int64",new BigInt64Array(E),[1,E]),o.data.fill(1n,0,p))}}const[l,u]=i.dims,d=this.config.stride;if(l%d!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${d}).`);const m=i.view(1,Math.floor(l/d),u*d),g={input_features:m};if(s){const p=m.dims[1],w=new BigInt64Array(p);if(o){const v=o.data;for(let S=1,$=0;S0)if(n==="rand_trunc"){const o=Math.floor(Math.random()*(i+1));e=e.subarray(o,o+r),s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${n}" not implemented`);else{if(i<0){let o=new Float64Array(r);if(o.set(e),a==="repeat")for(let l=e.length;l/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const r=[];for(const n of e)if(this.task_prompts_without_inputs.has(n))r.push(this.task_prompts_without_inputs.get(n));else{for(const[a,s]of this.task_prompts_with_input)if(n.includes(a)){r.push(s.replaceAll("{input}",n).replaceAll(a,""));break}r.length!==e.length&&r.push(n)}return r}post_process_generation(e,r,n){const a=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let s;switch(a){case"pure_text":s=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const i=a==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[i]),l=[],u=[];for(const[d,h,...m]of o)l.push(h?h.trim():l.at(-1)??""),u.push(m.map((g,p)=>(Number(g)+.5)/this.size_per_bin*n[p%2]));s={labels:l,[i]:u};break;default:throw new Error(`Task "${r}" (of type "${a}") not yet implemented.`)}return{[r]:s}}}class xt{static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:s=!1,revision:i="main"}={}){let o=n??await Rr(e,"preprocessor_config.json",!0,{progress_callback:r,config:n,cache_dir:a,local_files_only:s,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=Ge;else throw new Error(`Unknown Feature Extractor type: ${l}`);let d=this.PROCESSOR_CLASS_MAPPING[o.processor_class]??cn,h=new u(o);return new d(h)}}B(xt,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:Ge,WhisperFeatureExtractor:d3,ViTFeatureExtractor:jk,MobileViTFeatureExtractor:Z_,MobileViTImageProcessor:Jk,MobileNetV1FeatureExtractor:Yk,MobileNetV2FeatureExtractor:Xk,MobileNetV3FeatureExtractor:Qk,MobileNetV4FeatureExtractor:Zk,OwlViTFeatureExtractor:J_,Owlv2ImageProcessor:e3,CLIPFeatureExtractor:X_,CLIPImageProcessor:Wk,Florence2Processor:t0,ChineseCLIPFeatureExtractor:Vk,SiglipImageProcessor:Gk,ConvNextFeatureExtractor:Q_,ConvNextImageProcessor:Hk,SegformerFeatureExtractor:Nk,BitImageProcessor:Lk,DPTImageProcessor:Fk,DPTFeatureExtractor:Y_,GLPNFeatureExtractor:Uk,BeitFeatureExtractor:n3,DeiTFeatureExtractor:r3,DetrFeatureExtractor:i3,RTDetrImageProcessor:t3,YolosFeatureExtractor:s3,DonutFeatureExtractor:e0,NougatImageProcessor:a3,EfficientNetImageProcessor:Kk,ViTImageProcessor:qk,VitMatteImageProcessor:u3,SamImageProcessor:o3,Swin2SRImageProcessor:l3,Wav2Vec2FeatureExtractor:c3,SeamlessM4TFeatureExtractor:p3,SpeechT5FeatureExtractor:m3,ASTFeatureExtractor:h3,ClapFeatureExtractor:f3}),B(xt,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:_3,Wav2Vec2ProcessorWithLM:y3,SamProcessor:g3,SpeechT5Processor:w3,OwlViTProcessor:b3,Florence2Processor:t0});async function Tr(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>At.read(e)))}async function Ji(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?Ak(r,e):r instanceof Float64Array?new Float32Array(r):r))}function r0(t,e){e&&(t=t.map(i=>i|0));const[r,n,a,s]=t;return{xmin:r,ymin:n,xmax:a,ymax:s}}class tt extends wt{constructor({task:e,model:r,tokenizer:n=null,processor:a=null}){super(),this.task=e,this.model=r,this.tokenizer=n,this.processor=a}async dispose(){await this.model.dispose()}}class v3 extends tt{constructor(e){super(e)}async _call(e,{top_k:r=1}={}){const n=this.tokenizer(e,{padding:!0,truncation:!0}),a=await this.model(n),s=this.model.config.problem_type==="multi_label_classification"?l=>l.sigmoid():l=>new ce("float32",bt(l.data),l.dims),i=this.model.config.id2label,o=[];for(const l of a.logits){const u=s(l),d=await An(u,r),h=d[0].tolist(),g=d[1].tolist().map((p,w)=>({label:i?i[p]:`LABEL_${p}`,score:h[w]}));r===1?o.push(...g):o.push(g)}return Array.isArray(e)||r===1?o:o[0]}}class $3 extends tt{constructor(e){super(e)}async _call(e,{ignore_labels:r=["O"]}={}){const n=Array.isArray(e),a=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(a)).logits,o=this.model.config.id2label,l=[];for(let u=0;uE==this.tokenizer.sep_token_id);l[h].map((E,T)=>E==1&&(T===0||T>g&&u.findIndex(A=>A==m[T])===-1));const p=s[h].tolist(),w=i[h].tolist();for(let E=1;ET==m[E])!==-1)&&(p[E]=-1/0,w[E]=-1/0);const v=bt(p).map((E,T)=>[E,T]),S=bt(w).map((E,T)=>[E,T]);v[0][0]=0,S[0][0]=0;const $=H0(v,S).filter(E=>E[0][1]<=E[1][1]).map(E=>[E[0][1],E[1][1],E[0][0]*E[1][0]]).sort((E,T)=>T[2]-E[2]);for(let E=0;Ep==this.tokenizer.mask_token_id);if(u===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const d=a[o][u],h=await An(new ce("float32",bt(d.data),d.dims),r),m=h[0].tolist(),g=h[1].tolist();s.push(g.map((p,w)=>{const v=l.slice();return v[u]=p,{score:m[w],token:Number(p),token_str:this.tokenizer.model.vocab[p],sequence:this.tokenizer.decode(v,{skip_special_tokens:!0})}}))}return Array.isArray(e)?s:s[0]}}class pl extends tt{constructor(r){super(r);B(this,"_key","generated_text")}async _call(r,n={}){Array.isArray(r)||(r=[r]),this.model.config.prefix&&(r=r.map(u=>this.model.config.prefix+u));const a=this.model.config.task_specific_params;a&&a[this.task]&&a[this.task].prefix&&(r=r.map(u=>a[this.task].prefix+u));const s=this.tokenizer,i={padding:!0,truncation:!0};let o;this instanceof n0&&"_build_translation_inputs"in s?o=s._build_translation_inputs(r,i,n):o=s(r,i);const l=await this.model.generate({...o,...n});return s.batch_decode(l,{skip_special_tokens:!0}).map(u=>({[this._key]:u}))}}class k3 extends pl{constructor(r){super(r);B(this,"_key","summary_text")}}class n0 extends pl{constructor(r){super(r);B(this,"_key","translation_text")}}function a0(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}class E3 extends tt{constructor(e){super(e)}async _call(e,r={}){let n=!1,a=!1,s;if(typeof e=="string")s=e=[e];else if(Array.isArray(e)&&e.every(g=>typeof g=="string"))n=!0,s=e;else{if(a0(e))e=[e];else if(Array.isArray(e)&&e.every(a0))n=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");a=!0,s=e.map(g=>this.tokenizer.apply_chat_template(g,{tokenize:!1,add_generation_prompt:!0}))}const i=r.add_special_tokens??!1,o=a?!1:r.return_full_text??!0;this.tokenizer.padding_side="left";const l=this.tokenizer(s,{add_special_tokens:i,padding:!0,truncation:!0}),u=await this.model.generate({...l,...r}),d=this.tokenizer.batch_decode(u,{skip_special_tokens:!0});let h;!o&&l.input_ids.dims.at(-1)>0&&(h=this.tokenizer.batch_decode(l.input_ids,{skip_special_tokens:!0}).map(g=>g.length));const m=Array.from({length:e.length},g=>[]);for(let g=0;g[r.toLowerCase(),n])),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,r,{hypothesis_template:n="This example is {}.",multi_label:a=!1}={}){const s=Array.isArray(e);s||(e=[e]),Array.isArray(r)||(r=[r]);const i=r.map(u=>n.replace("{}",u)),o=a||r.length===1,l=[];for(const u of e){const d=[];for(const g of i){const p=this.tokenizer(u,{text_pair:g,padding:!0,truncation:!0}),w=await this.model(p);o?d.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):d.push(w.logits.data[this.entailment_id])}const m=(o?d.map(g=>bt(g)[1]):bt(d)).map((g,p)=>[g,p]).sort((g,p)=>p[0]-g[0]);l.push({sequence:u,labels:m.map(g=>r[g[1]]),scores:m.map(g=>g[0])})}return s?l:l[0]}}class T3 extends tt{constructor(e){super(e)}async _call(e,{pooling:r="none",normalize:n=!1,quantize:a=!1,precision:s="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(r!=="none")if(r==="mean")l=Uw(l,i.attention_mask);else if(r==="cls")l=l.slice(null,0);else throw Error(`Pooling method '${r}' not supported.`);return n&&(l=l.normalize(2,-1)),a&&(l=Yw(l,s)),l}}class A3 extends tt{constructor(e){super(e)}async _call(e,{pool:r=null}={}){const n=await Tr(e),{pixel_values:a}=await this.processor(n),s=await this.model({pixel_values:a});let i;if(r){if(!("pooler_output"in s))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");i=s.pooler_output}else i=s.last_hidden_state??s.logits??s.image_embeds;return i}}class I3 extends tt{constructor(e){super(e)}async _call(e,{top_k:r=5}={}){const n=this.processor.feature_extractor.config.sampling_rate,a=await Ji(e,n),s=this.model.config.id2label,i=[];for(const o of a){const l=await this.processor(o),d=(await this.model(l)).logits[0],h=await An(new ce("float32",bt(d.data),d.dims),r),m=h[0].tolist(),p=h[1].tolist().map((w,v)=>({label:s?s[w]:`LABEL_${w}`,score:m[v]}));i.push(p)}return Array.isArray(e)?i:i[0]}}class M3 extends tt{constructor(e){super(e)}async _call(e,r,{hypothesis_template:n="This is a sound of {}."}={}){const a=!Array.isArray(e);a&&(e=[e]);const s=r.map(d=>n.replace("{}",d)),i=this.tokenizer(s,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,l=await Ji(e,o),u=[];for(const d of l){const h=await this.processor(d),m=await this.model({...i,...h}),g=bt(m.logits_per_audio.data);u.push([...g].map((p,w)=>({score:p,label:r[w]})))}return a?u[0]:u}}class O3 extends tt{constructor(e){super(e)}async _call(e,r={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const n=!Array.isArray(e);n&&(e=[e]);const a=this.processor.feature_extractor.config.sampling_rate,s=await Ji(e,a),i=[];for(const o of s){const l=await this.processor(o),d=(await this.model(l)).logits[0],h=[];for(const g of d)h.push(qt(g.data)[1]);const m=this.tokenizer.decode(h);i.push({text:m})}return n?i[0]:i}async _call_whisper(e,r){const n=r.return_timestamps??!1,a=r.chunk_length_s??0,s=r.force_full_sequences??!1;let i=r.stride_length_s??null;const o={...r};n==="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,d=this.processor.feature_extractor.config.hop_length,h=this.processor.feature_extractor.config.sampling_rate,m=await Ji(e,h),g=[];for(const p of m){let w=[];if(a>0){if(i===null)i=a/6;else if(a<=i)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const $=h*a,E=h*i,T=$-2*E;let A=0;for(;;){const z=A+$,R=p.subarray(A,z),V=await this.processor(R),j=A===0,q=z>=p.length;if(w.push({stride:[R.length,j?0:E,q?0:E],input_features:V.input_features,is_last:q}),q)break;A+=T}}else w=[{stride:[p.length,0,0],input_features:(await this.processor(p)).input_features,is_last:!0}];for(const $ of w){o.num_frames=Math.floor($.stride[0]/d);const E=await this.model.generate({inputs:$.input_features,...o});n==="word"?($.tokens=E.sequences.tolist()[0],$.token_timestamps=E.token_timestamps.tolist()[0].map(T=>Xn(T,2))):$.tokens=E[0].tolist(),$.stride=$.stride.map(T=>T/h)}const[v,S]=this.tokenizer._decode_asr(w,{time_precision:u,return_timestamps:n,force_full_sequences:s});g.push({text:v,...S})}return l?g[0]:g}}class z3 extends tt{constructor(e){super(e)}async _call(e,r={}){const n=Array.isArray(e),a=await Tr(e),{pixel_values:s}=await this.processor(a),i=[];for(const o of s){o.dims=[1,...o.dims];const l=await this.model.generate({inputs:o,...r}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(d=>({generated_text:d.trim()}));i.push(u)}return n?i:i[0]}}class P3 extends tt{constructor(e){super(e)}async _call(e,{top_k:r=5}={}){const n=await Tr(e),{pixel_values:a}=await this.processor(n),s=await this.model({pixel_values:a}),i=this.model.config.id2label,o=[];for(const l of s.logits){const u=await An(new ce("float32",bt(l.data),l.dims),r),d=u[0].tolist(),m=u[1].tolist().map((g,p)=>({label:i?i[g]:`LABEL_${g}`,score:d[p]}));o.push(m)}return Array.isArray(e)?o:o[0]}}class R3 extends tt{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:r=.5,mask_threshold:n=.5,overlap_mask_area_threshold:a=.8,label_ids_to_fuse:s=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 Tr(e),d=u.map(S=>[S.height,S.width]),{pixel_values:h,pixel_mask:m}=await this.processor(u),g=await this.model({pixel_values:h,pixel_mask:m});let p=null;if(o!==null)p=this.subtasks_mapping[o];else for(let[S,$]of Object.entries(this.subtasks_mapping))if($ in this.processor.feature_extractor){p=this.processor.feature_extractor[$].bind(this.processor.feature_extractor),o=S;break}const w=this.model.config.id2label,v=[];if(o==="panoptic"||o==="instance"){const S=p(g,r,n,a,s,i??d)[0],$=S.segmentation;for(const E of S.segments_info){const T=new Uint8ClampedArray($.data.length);for(let z=0;z<$.data.length;++z)$.data[z]===E.id&&(T[z]=255);const A=new At(T,$.dims[1],$.dims[0],1);v.push({score:E.score,label:w[E.label_id],mask:A})}}else if(o==="semantic"){const{segmentation:S,labels:$}=p(g,i??d)[0];for(const E of $){const T=new Uint8ClampedArray(S.data.length);for(let z=0;zn.replace("{}",m)),o=this.tokenizer(i,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(s),u=await this.model({...o,pixel_values:l}),d=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>bt(m.data),h=[];for(const m of u.logits_per_image){const p=[...d(m)].map((w,v)=>({score:w,label:r[v]}));p.sort((w,v)=>v.score-w.score),h.push(p)}return a?h:h[0]}}class D3 extends tt{constructor(e){super(e)}async _call(e,{threshold:r=.9,percentage:n=!1}={}){const a=Array.isArray(e);if(a&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const s=await Tr(e),i=n?null:s.map(g=>[g.height,g.width]),{pixel_values:o,pixel_mask:l}=await this.processor(s),u=await this.model({pixel_values:o,pixel_mask:l}),d=this.processor.feature_extractor.post_process_object_detection(u,r,i),h=this.model.config.id2label,m=d.map(g=>g.boxes.map((p,w)=>({score:g.scores[w],label:h[g.classes[w]],box:r0(p,!n)})));return a?m:m[0]}}class N3 extends tt{constructor(e){super(e)}async _call(e,r,{threshold:n=.1,top_k:a=null,percentage:s=!1}={}){const i=Array.isArray(e),o=await Tr(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),u=await this.processor(o),d=[];for(let h=0;h({score:v.scores[E],label:r[v.classes[E]],box:r0($,!s)})).sort(($,E)=>E.score-$.score);a!==null&&(S=S.slice(0,a)),d.push(S)}return i?d:d[0]}}class F3 extends tt{constructor(e){super(e)}async _call(e,r,n={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class L3 extends tt{constructor(r){super(r);B(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=r.vocoder??null}async _call(r,{speaker_embeddings:n=null}={}){return this.processor?this._call_text_to_spectrogram(r,{speaker_embeddings:n}):this._call_text_to_waveform(r)}async _call_text_to_waveform(r){const n=this.tokenizer(r,{padding:!0,truncation:!0}),{waveform:a}=await this.model(n),s=this.model.config.sampling_rate;return{audio:a.data,sampling_rate:s}}async _call_text_to_spectrogram(r,{speaker_embeddings:n}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await ln.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof n=="string"||n instanceof URL)&&(n=new Float32Array(await(await fetch(n)).arrayBuffer())),n instanceof Float32Array)n=new ce("float32",n,[1,n.length]);else if(!(n instanceof ce))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:a}=this.tokenizer(r,{padding:!0,truncation:!0}),{waveform:s}=await this.model.generate_speech(a,n,{vocoder:this.vocoder}),i=this.processor.feature_extractor.config.sampling_rate;return{audio:s.data,sampling_rate:i}}}class U3 extends tt{constructor(e){super(e)}async _call(e){const r=await Tr(e),n=await this.processor(r),a=await this.model(n),s=[];for(const i of a.reconstruction){const o=i.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");s.push(At.fromTensor(o))}return s.length>1?s:s[0]}}class W3 extends tt{constructor(e){super(e)}async _call(e){const r=await Tr(e),n=await this.processor(r),{predicted_depth:a}=await this.model(n),s=[];for(let i=0;i1?s:s[0]}}const i0=Object.freeze({"text-classification":{tokenizer:pt,pipeline:v3,model:ul,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:pt,pipeline:$3,model:k_,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:pt,pipeline:x3,model:M_,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:pt,pipeline:S3,model:I_,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:pt,pipeline:k3,model:Yi,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:pt,pipeline:n0,model:Yi,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:pt,pipeline:pl,model:Yi,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:pt,pipeline:E3,model:A_,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:pt,pipeline:C3,model:ul,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:I3,model:F_,processor:xt,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:pt,pipeline:M3,model:ln,processor:xt,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:pt,pipeline:O3,model:[E_,N_],processor:xt,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:pt,pipeline:L3,model:[T_,C_],processor:[xt,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:pt,pipeline:z3,model:O_,processor:xt,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:P3,model:z_,processor:xt,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:R3,model:[P_,R_],processor:xt,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:pt,pipeline:B3,model:ln,processor:xt,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:D3,model:B_,processor:xt,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:pt,pipeline:N3,model:D_,processor:xt,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:pt,pipeline:F3,model:L_,processor:xt,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:U3,model:U_,processor:xt,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:W3,model:W_,processor:xt,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:pt,pipeline:T3,model:ln,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:xt,pipeline:A3,model:[V_,ln],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),V3=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function G3(t,e=null,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:s=!1,revision:i="main",device:o=null,dtype:l=null,model_file_name:u=null,session_options:d={}}={}){t=V3[t]??t;const h=i0[t.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(i0)}]`);e||(e=h.default.model,console.log(`No model specified. Using default model: "${e}".`));const m={progress_callback:r,config:n,cache_dir:a,local_files_only:s,revision:i,device:o,dtype:l,model_file_name:u,session_options:d},g=new Map([["tokenizer",h.tokenizer],["model",h.model],["processor",h.processor]]),p=await H3(g,e,m);p.task=t,bn(r,{status:"ready",task:t,model:e});const w=h.pipeline;return new w(p)}async function H3(t,e,r){const n=Object.create(null),a=[];for(let[s,i]of t.entries()){if(!i)continue;let o;Array.isArray(i)?o=new Promise(async(l,u)=>{var h,m;let d;for(let g of i){if(g===null){l(null);return}try{l(await g.from_pretrained(e,r));return}catch(p){if((h=p.message)!=null&&h.includes("Unsupported model type"))d=p;else if((m=p.message)!=null&&m.includes("Could not locate file"))d=p;else{u(p);return}}}u(d)}):o=i.from_pretrained(e,r),n[s]=o,a.push(o)}await Promise.all(a);for(let[s,i]of Object.entries(n))n[s]=await i;return n}Hr.IS_PROCESS_AVAILABLE;class es{static async getInstance(e=null){return this.instance??(this.instance=G3("automatic-speech-recognition",this.model_id,{dtype:{encoder_model:"fp32",decoder_model_merged:"q4"},device:"webgpu",progress_callback:e})),this.instance}}B(es,"model_id","onnx-community/whisper-base_timestamped"),B(es,"instance",null);async function j3(){self.postMessage({status:"loading",data:"Loading model..."});const t=await es.getInstance(e=>{self.postMessage(e)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."}),await t(new Float32Array(16e3),{language:"en"}),self.postMessage({status:"ready"})}async function q3({audio:t,language:e}){const r=await es.getInstance(),n=performance.now(),a=await r(t,{language:e,return_timestamps:"word",chunk_length_s:30}),s=performance.now();self.postMessage({status:"complete",result:a,time:s-n})}self.addEventListener("message",async t=>{const{type:e,data:r}=t.data;switch(e){case"load":j3();break;case"run":q3(r);break}})})();