diff --git a/assets/index-CfdOY117.css b/assets/index-CfdOY117.css new file mode 100644 index 0000000000000000000000000000000000000000..aaa23f297c38605a0869dd0f98d6e6910f4e6b7e --- /dev/null +++ b/assets/index-CfdOY117.css @@ -0,0 +1 @@ +*{box-sizing:border-box;padding:0;margin:0;font-family:sans-serif}html,body{height:100%}body{padding:16px 32px;display:flex;flex-direction:column;justify-content:center;align-items:center}#controls{display:flex;padding:1rem;gap:1rem}#controls>div{text-align:center}h1,h4{text-align:center}h4{margin-top:.5rem}#status{min-height:16px;margin:8px 0}button{transition:all .25s;background:#282c340d;border:1px solid transparent;border-radius:6px;color:#3080d0;text-decoration:none!important;display:inline-block;font-size:14px;font-weight:500;padding:8px 16px;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none}button:disabled{background:#282c341a;color:#a0a0a0;cursor:not-allowed}button:hover{background:#282c341a}p{text-align:center;font-size:12px;max-width:600px;padding:8px}#chart-container{position:relative;height:60vh;width:min(90vw,800px);padding-right:50px} diff --git a/assets/index-Cz6LjLeh.js b/assets/index-Cz6LjLeh.js new file mode 100644 index 0000000000000000000000000000000000000000..dd630850e5df16a29e22a348ceb4a6471379af4c --- /dev/null +++ b/assets/index-Cz6LjLeh.js @@ -0,0 +1,1849 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function dispatchCallback(t,e){t&&t(e)}function reverseDictionary(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e]))}const Callable=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 isTypedArray(t){return t?.prototype?.__proto__?.constructor?.name==="TypedArray"}function isIntegralNumber(t){return Number.isInteger(t)||typeof t=="bigint"}function exists(t){return t!=null}function mergeArrays(...t){return Array.prototype.concat.apply([],t)}const sharp={},ONNX_NODE=Object.freeze(Object.defineProperty({__proto__:null,default:sharp},Symbol.toStringTag,{value:"Module"})),VERSION="3.0.0-alpha.0",BROWSER_ENV$1=typeof self<"u",WEB_CACHE_AVAILABLE=BROWSER_ENV$1&&"caches"in self,FS_AVAILABLE=!isEmpty(sharp),PATH_AVAILABLE=!isEmpty(sharp),RUNNING_LOCALLY=FS_AVAILABLE&&PATH_AVAILABLE,__dirname$1=RUNNING_LOCALLY?sharp.dirname(sharp.dirname(sharp.fileURLToPath(import.meta.url))):"./",DEFAULT_CACHE_DIR=RUNNING_LOCALLY?sharp.join(__dirname$1,"/.cache/"):null,DEFAULT_LOCAL_MODEL_PATH="/models/",localModelPath=RUNNING_LOCALLY?sharp.join(__dirname$1,DEFAULT_LOCAL_MODEL_PATH):DEFAULT_LOCAL_MODEL_PATH,env={backends:{onnx:{},tfjs:{}},experimental:{useWebGPU:!1},__dirname:__dirname$1,version:VERSION,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!BROWSER_ENV$1,localModelPath,useFS:FS_AVAILABLE,useBrowserCache:WEB_CACHE_AVAILABLE,useFSCache:FS_AVAILABLE,cacheDir:DEFAULT_CACHE_DIR,useCustomCache:!1,customCache:null};function isEmpty(t){return Object.keys(t).length===0}var define_process_env_default={};class FileResponse{_CONTENT_TYPE_MAP={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=sharp.existsSync(e),this.exists){this.status=200,this.statusText="OK";let n=sharp.statSync(e);this.headers.set("content-length",n.size.toString()),this.updateContentType();let r=this;this.body=new ReadableStream({start(s){r.arrayBuffer().then(i=>{s.enqueue(new Uint8Array(i)),s.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new FileResponse(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 sharp.promises.readFile(this.filePath)).buffer}async blob(){const e=await sharp.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await sharp.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function isValidHttpUrl(t,e=null){let n;try{n=new URL(t)}catch{return!1}return e&&!e.includes(n.hostname)?!1:n.protocol==="http:"||n.protocol==="https:"}async function getFile(t){if(env.useFS&&!isValidHttpUrl(t))return new FileResponse(t);if(typeof process<"u"&&process?.release?.name==="node"){const e=!!define_process_env_default?.TESTING_REMOTELY,n=env.version,r=new Headers;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${e};`),isValidHttpUrl(t,["huggingface.co","hf.co"])){const i=define_process_env_default?.HF_TOKEN??define_process_env_default?.HF_ACCESS_TOKEN;i&&r.set("Authorization",`Bearer ${i}`)}return fetch(t,{headers:r})}else return fetch(t)}const ERROR_MAPPING={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 handleError(t,e,n){if(!n)return null;const r=ERROR_MAPPING[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${r}: "${e}".`)}class FileCache{constructor(e){this.path=e}async match(e){let n=sharp.join(this.path,e),r=new FileResponse(n);if(r.exists)return r}async put(e,n){const r=Buffer.from(await n.arrayBuffer());let s=sharp.join(this.path,e);try{await sharp.promises.mkdir(sharp.dirname(s),{recursive:!0}),await sharp.promises.writeFile(s,r)}catch(i){console.warn("An error occurred while writing the file to cache:",i)}}}async function tryCache(t,...e){for(let n of e)try{let r=await t.match(n);if(r)return r}catch{continue}}async function getModelFile(t,e,n=!0,r={}){if(!env.allowLocalModels&&r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");dispatchCallback(r.progress_callback,{status:"initiate",name:t,file:e});let s;if(!s&&env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{s=await caches.open("transformers-cache")}catch(x){console.warn("An error occurred while opening the browser cache:",x)}}if(!s&&env.useFSCache&&(s=new FileCache(r.cache_dir??env.cacheDir)),!s&&env.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const i=r.revision??"main";let a=pathJoin(t,e),u=pathJoin(env.localModelPath,a),d=pathJoin(env.remoteHost,env.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(i)),e),o=i==="main"?a:pathJoin(t,i,e),l,c=s instanceof FileCache?o:d,h=!1,f;s&&(f=await tryCache(s,u,c));const p=f!==void 0;if(f===void 0){if(env.allowLocalModels)if(isValidHttpUrl(a)){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`)}else try{f=await getFile(u),l=u}catch(y){console.warn(`Unable to load from local path "${u}": "${y}"`)}if(f===void 0||f.status===404){if(r.local_files_only||!env.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${u}".`);return null}if(f=await getFile(d),f.status!==200)return handleError(f.status,d,n);l=c}h=s&&typeof Response<"u"&&f instanceof Response&&f.status===200}dispatchCallback(r.progress_callback,{status:"download",name:t,file:e});const g={status:"progress",name:t,file:e};let b;return r.progress_callback?p&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(b=new Uint8Array(await f.arrayBuffer()),dispatchCallback(r.progress_callback,{...g,progress:100,loaded:b.length,total:b.length})):b=await readResponse(f,x=>{dispatchCallback(r.progress_callback,{...g,...x})}):b=new Uint8Array(await f.arrayBuffer()),h&&l&&await s.match(l)===void 0&&await s.put(l,new Response(b,{headers:f.headers})).catch(x=>{console.warn(`Unable to add response to browser cache: ${x}.`)}),dispatchCallback(r.progress_callback,{status:"done",name:t,file:e}),b}async function getModelJSON(t,e,n=!0,r={}){let s=await getModelFile(t,e,n,r);if(s===null)return{};let a=new TextDecoder("utf-8").decode(s);return JSON.parse(a)}async function readResponse(t,e){const n=t.headers.get("Content-Length");n===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(n??"0"),s=new Uint8Array(r),i=0;const a=t.body.getReader();async function u(){const{done:d,value:o}=await a.read();if(d)return;let l=i+o.length;if(l>r){r=l;let h=new Uint8Array(r);h.set(s),s=h}s.set(o,i),i=l;const c=i/r*100;return e({progress:c,loaded:i,total:r}),u()}return await u(),s}function pathJoin(...t){return t=t.map((e,n)=>(n&&(e=e.replace(new RegExp("^/"),"")),n!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function transpose_data(t,e,n){const r=new Array(n.length),s=new Array(n.length);for(let u=n.length-1,d=1;u>=0;--u)s[u]=d,r[u]=e[n[u]],d*=r[u];const i=n.map((u,d)=>s[n.indexOf(d)]),a=new t.constructor(t.length);for(let u=0;u=0;--o)d+=l%e[o]*i[o],l=Math.floor(l/e[o]);a[d]=t[u]}return[a,r]}function softmax(t){const e=max(t)[0],n=t.map(i=>Math.exp(i-e)),r=n.reduce((i,a)=>i+a,0);return n.map(i=>i/r)}function log_softmax(t){return softmax(t).map(r=>Math.log(r))}function getTopItems(t,e=0){return t=Array.from(t).map((n,r)=>[r,n]).sort((n,r)=>r[1]-n[1]),e!==null&&e>0&&(t=t.slice(0,e)),t}function max(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],n=0;for(let r=1;re&&(e=t[r],n=r);return[Number(e),n]}function medianFilter(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");const n=new t.constructor(t.length),r=new t.constructor(e),s=Math.floor(e/2);for(let i=0;i=t.length&&(d=2*(t.length-1)-d),r[a++]=t[d]}r.sort(),n[i]=r[s]}return n}const scriptRel="modulepreload",assetsURL=function(t){return"/"+t},seen={},__vitePreload=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){const i=document.getElementsByTagName("link");s=Promise.all(n.map(a=>{if(a=assetsURL(a),a in seen)return;seen[a]=!0;const u=a.endsWith(".css"),d=u?'[rel="stylesheet"]':"";if(!!r)for(let c=i.length-1;c>=0;c--){const h=i[c];if(h.href===a&&(!u||h.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${a}"]${d}`))return;const l=document.createElement("link");if(l.rel=u?"stylesheet":scriptRel,u||(l.as="script",l.crossOrigin=""),l.href=a,document.head.appendChild(l),u)return new Promise((c,h)=>{l.addEventListener("load",c),l.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${a}`)))})}))}return s.then(()=>e()).catch(i=>{const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i})};/*! + * ONNX Runtime Web v1.17.1 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var vd=Object.create,En=Object.defineProperty,wd=Object.getOwnPropertyDescriptor,_d=Object.getOwnPropertyNames,Od=Object.getPrototypeOf,Id=Object.prototype.hasOwnProperty,L=(t,e)=>()=>(t&&(e=t(t=0)),e),me=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Pr=(t,e)=>{for(var n in e)En(t,n,{get:e[n],enumerable:!0})},Ha=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _d(e))!Id.call(t,s)&&s!==n&&En(t,s,{get:()=>e[s],enumerable:!(r=wd(e,s))||r.enumerable});return t},Er=(t,e,n)=>(n=t!=null?vd(Od(t)):{},Ha(e||!t||!t.__esModule?En(n,"default",{value:t,enumerable:!0}):n,t)),rr=t=>Ha(En({},"__esModule",{value:!0}),t),Dn,nr,or,Ln,Fn=L(()=>{Dn=new Map,nr=[],or=(t,e,n)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let r=Dn.get(t);if(r===void 0)Dn.set(t,{backend:e,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${n}`)}if(n>=0){let s=nr.indexOf(t);s!==-1&&nr.splice(s,1);for(let i=0;i{let e=t.length===0?nr:t,n=[];for(let r of e){let s=Dn.get(r);if(s){if(s.initialized)return s.backend;if(s.aborted)continue;let i=!!s.initPromise;try{return i||(s.initPromise=s.backend.init(r)),await s.initPromise,s.initialized=!0,s.backend}catch(a){i||n.push({name:r,err:a}),s.aborted=!0}finally{delete s.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map(r=>`[${r.name}] ${r.err}`).join(", ")}`)}}),qa=L(()=>{Fn()}),ja,Ya=L(()=>{ja="1.17.1"}),Xa,ir,Ho=L(()=>{Ya(),Xa="warning",ir={wasm:{},webgl:{},webgpu:{},versions:{common:ja},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}`);Xa=t}},get logLevel(){return Xa}},Object.defineProperty(ir,"logLevel",{enumerable:!0})}),Z,Ka=L(()=>{Ho(),Z=ir}),Ja,Za,Qa=L(()=>{Ja=(t,e)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=t.dims[3],n.height=t.dims[2];let r=n.getContext("2d");if(r!=null){let s,i;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[3]):(s=t.dims[3],i=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",u=e?.norm,d,o;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?o=[0,0,0,0]:typeof u.bias=="number"?o=[u.bias,u.bias,u.bias,u.bias]:(o=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(o[3]=u.bias[3]));let l=i*s,c=0,h=l,f=l*2,p=-1;a==="RGBA"?(c=0,h=l,f=l*2,p=l*3):a==="RGB"?(c=0,h=l,f=l*2):a==="RBG"&&(c=0,f=l,h=l*2);for(let g=0;g{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(n!=null){let s,i,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[1],a=t.dims[3]):(s=t.dims[3],i=t.dims[2],a=t.dims[1]);let u=e!==void 0&&e.format!==void 0?e.format:"RGB",d=e?.norm,o,l;d===void 0||d.mean===void 0?o=[255,255,255,255]:typeof d.mean=="number"?o=[d.mean,d.mean,d.mean,d.mean]:(o=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(o[3]=d.mean[3])),d===void 0||d.bias===void 0?l=[0,0,0,0]:typeof d.bias=="number"?l=[d.bias,d.bias,d.bias,d.bias]:(l=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(l[3]=d.bias[3]));let c=i*s;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,f=0,p=1,g=2,b=3,x=0,y=c,T=c*2,S=-1;u==="RGBA"?(x=0,y=c,T=c*2,S=c*3):u==="RGB"?(x=0,y=c,T=c*2):u==="RBG"&&(x=0,T=c,y=c*2),r=n.createImageData(s,i);for(let E=0;E{$n(),qo=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:r}=e,s=e.norm??{mean:255,bias:0},i,a;typeof s.mean=="number"?i=[s.mean,s.mean,s.mean,s.mean]:i=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?a=[s.bias,s.bias,s.bias,s.bias]:a=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let u=e.format!==void 0?e.format:"RGBA",d=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",o=n*r,l=d==="RGBA"?new Float32Array(o*4):new Float32Array(o*3),c=4,h=0,f=1,p=2,g=3,b=0,x=o,y=o*2,T=-1;u==="RGB"&&(c=3,h=0,f=1,p=2,g=-1),d==="RGBA"?T=o*3:d==="RBG"?(b=0,y=o,x=o*2):d==="BGR"&&(y=0,x=o,b=o*2);for(let S=0;S{let n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,r=typeof ImageData<"u"&&t instanceof ImageData,s=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,i=typeof t=="string",a,u=e??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},o=l=>l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas?l.getContext("2d"):null;if(n){let l=d();l.width=t.width,l.height=t.height;let c=o(l);if(c!=null){let h=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,f=e.resizedWidth),e!==void 0){if(u=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=h,u.width=f}else u.tensorFormat="RGBA",u.height=h,u.width=f;c.drawImage(t,0,0),a=c.getImageData(0,0,f,h).data}else throw new Error("Can not access image data")}else if(r){let l,c;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(l=e.resizedHeight,c=e.resizedWidth):(l=t.height,c=t.width),e!==void 0&&(u=e),u.format="RGBA",u.height=l,u.width=c,e!==void 0){let h=d();h.width=c,h.height=l;let f=o(h);if(f!=null)f.putImageData(t,0,0),a=f.getImageData(0,0,c,l).data;else throw new Error("Can not access image data")}else a=t.data}else if(s){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let l=d();l.width=t.width,l.height=t.height;let c=o(l);if(c!=null){let h=t.height,f=t.width;return c.drawImage(t,0,0,f,h),a=c.getImageData(0,0,f,h).data,u.height=h,u.width=f,qo(a,u)}else throw new Error("Can not access image data")}else{if(i)return new Promise((l,c)=>{let h=d(),f=o(h);if(!t||!f)return c();let p=new Image;p.crossOrigin="Anonymous",p.src=t,p.onload=()=>{h.width=p.width,h.height=p.height,f.drawImage(p,0,0,h.width,h.height);let g=f.getImageData(0,0,h.width,h.height);u.height=h.height,u.width=h.width,l(qo(g.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return qo(a,u);throw new Error("Input data provided is not supported - aborted tensor creation")},ts=(t,e)=>{let{width:n,height:r,download:s,dispose:i}=e,a=[1,r,n,4];return new Ye({location:"texture",type:"float32",texture:t,dims:a,download:s,dispose:i})},rs=(t,e)=>{let{dataType:n,dims:r,download:s,dispose:i}=e;return new Ye({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:s,dispose:i})},ns=(t,e,n)=>new Ye({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]})}),Qr,Cn,is,as,ss=L(()=>{Qr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Cn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),is=!1,as=()=>{if(!is){is=!0;let t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(Qr.set("int64",BigInt64Array),Cn.set(BigInt64Array,"int64")),e&&(Qr.set("uint64",BigUint64Array),Cn.set(BigUint64Array,"uint64"))}}}),us,ls,fs=L(()=>{$n(),us=t=>{let e=1;for(let n=0;n{switch(t.location){case"cpu":return new Ye(t.type,t.data,e);case"cpu-pinned":return new Ye({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Ye({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Ye({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Ye,$n=L(()=>{Qa(),os(),ss(),fs(),Ye=class{constructor(t,e,n){as();let r,s;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,r=t.type,s=t.dims,t.location){case"cpu-pinned":{let a=Qr.get(r);if(!a)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="bool")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,u;if(typeof t=="string")if(r=t,u=n,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let d=Qr.get(t);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");t==="uint64"||t==="int64"?a=d.from(e,BigInt):a=d.from(e)}else if(e instanceof d)a=e;else throw new TypeError(`A ${r} tensor's data must be type of ${d}`)}else if(u=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof t[0];if(d==="string")r="string",a=t;else if(d==="boolean")r="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{let d=Cn.get(t.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);r=d,a=t}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=a,this.dataLocation="cpu"}let i=us(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=r,this.dims=s,this.size=i}static async fromImage(t,e){return es(t,e)}static fromTexture(t,e){return ts(t,e)}static fromGpuBuffer(t,e){return rs(t,e)}static fromPinnedBuffer(t,e,n){return ns(t,e,n)}toDataURL(t){return Ja(this,t)}toImageData(t){return Za(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 ls(this,t)}}}),Re,kn=L(()=>{$n(),Re=Ye}),cs,ps,ar,sr,jo=L(()=>{Ho(),cs=(t,e)=>{ir.wasm.trace&&console.timeStamp(`${t}::ORT::${e}`)},ps=(t,e)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let s=0;s{ir.wasm.trace&&ps("BEGIN",t)},sr=t=>{ir.wasm.trace&&ps("END",t)}}),Bn,ds=L(()=>{Fn(),kn(),jo(),Bn=class Go{constructor(e){this.handler=e}async run(e,n,r){ar();let s={},i={};if(typeof e!="object"||e===null||e instanceof Re||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof Re)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let o of n){if(typeof o!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(o)===-1)throw new RangeError(`'fetches' contains invalid output name: ${o}.`);s[o]=null}if(typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let o=!1,l=Object.getOwnPropertyNames(n);for(let c of this.outputNames)if(l.indexOf(c)!==-1){let h=n[c];(h===null||h instanceof Re)&&(o=!0,a=!1,s[c]=h)}if(o){if(typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else i=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let o of this.inputNames)if(typeof e[o]>"u")throw new Error(`input '${o}' is missing in 'feeds'.`);if(a)for(let o of this.outputNames)s[o]=null;let u=await this.handler.run(e,s,i),d={};for(let o in u)if(Object.hasOwnProperty.call(u,o)){let l=u[o];l instanceof Re?d[o]=l:d[o]=new Re(l.type,l.data,l.dims)}return sr(),d}async release(){return this.handler.dispose()}static async create(e,n,r,s){ar();let i,a={};if(typeof e=="string"){if(i=e,typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(i=e,typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let o=e,l=0,c=e.byteLength;if(typeof n=="object"&&n!==null)a=n;else if(typeof n=="number"){if(l=n,!Number.isSafeInteger(l))throw new RangeError("'byteOffset' must be an integer.");if(l<0||l>=o.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${o.byteLength}).`);if(c=e.byteLength-l,typeof r=="number"){if(c=r,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||l+c>o.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${o.byteLength-l}].`);if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(o,l,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let u=(a.executionProviders||[]).map(o=>typeof o=="string"?o:o.name),d=await(await Ln(u)).createInferenceSessionHandler(i,a);return sr(),new Go(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Sd,hs=L(()=>{ds(),Sd=Bn}),ms=L(()=>{}),Ad,Nn,bs=L(()=>{Fn(),kn(),Ad="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Nn=class Jo{constructor(e,n,r){this.handler=e,this.hasOptimizerModel=n,this.hasEvalModel=r}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,n){let r=e.evalModel||"",s=e.optimizerModel||"",i=n||{},a=(i.executionProviders||[]).map(d=>typeof d=="string"?d:d.name),u=await Ln(a);if(u.createTrainingSessionHandler){let d=await u.createTrainingSessionHandler(e.checkpointState,e.trainModel,r,s,i);return new Jo(d,!!e.optimizerModel,!!e.evalModel)}else throw new Error(Ad)}typeNarrowingForRunStep(e,n,r,s,i){let a={},u={};if(typeof r!="object"||r===null||r instanceof Re||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof Re)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let o of s){if(typeof o!="string")throw new TypeError("'fetches' must be a string array or an object.");if(n.indexOf(o)===-1)throw new RangeError(`'fetches' contains invalid output name: ${o}.`);a[o]=null}if(typeof i=="object"&&i!==null)u=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let o=!1,l=Object.getOwnPropertyNames(s);for(let c of n)if(l.indexOf(c)!==-1){let h=s[c];(h===null||h instanceof Re)&&(o=!0,d=!1,a[c]=h)}if(o){if(typeof i=="object"&&i!==null)u=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else u=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let o of e)if(typeof r[o]>"u")throw new Error(`input '${o}' is missing in 'feeds'.`);if(d)for(let o of n)a[o]=null;return[a,u]}convertHandlerReturnTypeToMapOfTensors(e){let n={};for(let r in e)if(Object.hasOwnProperty.call(e,r)){let s=e[r];s instanceof Re?n[r]=s:n[r]=new Re(s.type,s.data,s.dims)}return n}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,n,r){let[s,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,n,r),a=await this.handler.runTrainStep(e,s,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(e){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(e||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(e,n,r){if(this.hasEvalModel){let[s,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,n,r),a=await this.handler.runEvalStep(e,s,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,n=!0){let r=await this.getParametersSize(n);if(e.length!==4*r)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,n)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}}),Pd,gs=L(()=>{bs(),Pd=Nn}),Yo={};Pr(Yo,{InferenceSession:()=>Sd,TRACE:()=>cs,TRACE_FUNC_BEGIN:()=>ar,TRACE_FUNC_END:()=>sr,Tensor:()=>Re,TrainingSession:()=>Pd,env:()=>Z,registerBackend:()=>or});var vt=L(()=>{qa(),Ka(),hs(),kn(),jo(),ms(),gs()});function jt(t,e,n,r){if(e===void 0)return Dd(t);if(n===void 0)Rn(t,e);else if(typeof n=="number"&&r===void 0)Rn(t,e);else if(typeof n=="string"&&r===void 0)Rn(t,n,1,e);else if(typeof n=="string"&&typeof r=="number")Rn(t,n,r,e);else throw new TypeError("input is valid")}function Dd(t){return{verbose:jt.verbose.bind(null,t),info:jt.info.bind(null,t),warning:jt.warning.bind(null,t),error:jt.error.bind(null,t),fatal:jt.fatal.bind(null,t)}}function Rn(t,e,n,r){let s=en[r||""]||en[""];Ts[t]{Xo=class{log(t,e,n){}},Ko=class{log(t,e,n){console.log(`${this.color(t)} ${n?"\x1B[35m"+n+"\x1B[0m ":""}${e}`)}color(t){switch(t){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${t}`)}}},Ts={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},Ed={none:new Xo,console:new Ko},xs={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},en={"":xs},(t=>{function e(o,l){t("verbose",o,l)}t.verbose=e;function n(o,l){t("info",o,l)}t.info=n;function r(o,l){t("warning",o,l)}t.warning=r;function s(o,l){t("error",o,l)}t.error=s;function i(o,l){t("fatal",o,l)}t.fatal=i;function a(o){en={},u("",o||{})}t.reset=a;function u(o,l){if(o==="*")a(l);else{let c=en[o]||xs;en[o]={provider:l.provider||c.provider,minimalSeverity:l.minimalSeverity||c.minimalSeverity,logDateTime:l.logDateTime===void 0?c.logDateTime:l.logDateTime,logSourceLocation:l.logSourceLocation===void 0?c.logSourceLocation:l.logSourceLocation}}}t.set=u;function d(o){let l={};o.logLevel&&(l.minimalSeverity=o.logLevel),u("",l)}t.setWithEnv=d})(jt||={}),ce=jt,Gn=class{constructor(t,e,n,r,s,i){this.category=t,this.name=e,this.startTime=n,this.endCallback=r,this.timer=s,this.ctx=i}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},Un=class{constructor(t,e,n,r){this.category=t,this.name=e,this.startTime=n,this.endTime=r}},zn=class{constructor(t,e,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=t===void 0?1e4:t,this._flushBatchSize=e===void 0?10:e,this._flushIntervalInMilliseconds=n===void 0?5e3:n}static create(t){return t===void 0?new this:new this(t.maxNumberEvents,t.flushBatchSize,t.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=Mn(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer{a.then(async o=>{s&&await s.end(),u(o)},async o=>{s&&await s.end(),d(o)})});if(!i&&s){let u=s.end();if(u&&typeof u.then=="function")return new Promise((d,o)=>{u.then(()=>{d(a)},l=>{o(l)})})}return a}begin(t,e,n){if(!this._started)throw new Error("profiler is not started yet");if(n===void 0){let r=Mn();return this.flush(r),new Gn(t,e,r,s=>this.endSync(s))}else{let r=n.beginTimer();return new Gn(t,e,0,async s=>this.end(s),r,n)}}async end(t){let e=await t.checkTimer();this._timingEvents.length=this._flushBatchSize||t-this._flushTime>=this._flushIntervalInMilliseconds){for(let e=this._flushPointer;this._flushPointerperformance.now():Date.now});function vs(t,e,n){for(let r of n){let s=r[0],i=r[1],a=r[2],u=r[3],d=r[4];if(t.opType===s){for(let o of e)if((o.domain===i||o.domain==="ai.onnx"&&i==="")&&Ld(o.version,a))return{opImpl:u,opInit:d}}}throw new TypeError(`cannot resolve operator '${t.opType}' with opsets: ${e.map(r=>`${r.domain||"ai.onnx"} v${r.version}`).join(", ")}`)}function Ld(t,e){if(e.endsWith("+")){let n=Number.parseInt(e.substring(0,e.length-1),10);return!isNaN(n)&&n<=t}else if(e.split("-").length===2){let n=e.split("-"),r=Number.parseInt(n[0],10),s=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(s)&&r<=t&&t<=s}else return Number.parseInt(e,10)===t}var ws=L(()=>{}),_s=me(t=>{t.__esModule=!0;var e=function(){function n(r){if(!r)throw new TypeError("Invalid argument; `value` has no value.");this.value=n.EMPTY,r&&n.isGuid(r)&&(this.value=r)}return n.isGuid=function(r){var s=r.toString();return r&&(r instanceof n||n.validator.test(s))},n.create=function(){return new n([n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-"))},n.createEmpty=function(){return new n("emptyguid")},n.parse=function(r){return new n(r)},n.raw=function(){return[n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-")},n.gen=function(r){for(var s="",i=0;i>>=0,(s=0<=t&&t<256)&&(r=Ss[t],r)?r:(n=le(t,0,!0),s&&(Ss[t]=n),n)):(t|=0,(s=-128<=t&&t<128)&&(r=Is[t],r)?r:(n=le(t,t<0?-1:0,!1),s&&(Is[t]=n),n))}function ft(t,e){if(isNaN(t))return e?Ut:wt;if(e){if(t<0)return Ut;if(t>=Ds)return $s}else{if(t<=-Ps)return tt;if(t+1>=Ps)return Fs}return t<0?ft(-t,e).neg():le(t%Lr|0,t/Lr|0,e)}function le(t,e,n){return new be(t,e,n)}function Qo(t,e,n){if(t.length===0)throw Error("empty string");if(typeof e=="number"?(n=e,e=!1):e=!!e,t==="NaN"||t==="Infinity"||t==="+Infinity"||t==="-Infinity")return e?Ut:wt;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return Qo(t.substring(1),e,n).neg();for(var s=ft(Vn(n,8)),i=wt,a=0;a{lt=null;try{lt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}be.prototype.__isLong__,Object.defineProperty(be.prototype,"__isLong__",{value:!0}),be.isLong=We,Is={},Ss={},be.fromInt=ur,be.fromNumber=ft,be.fromBits=le,Vn=Math.pow,be.fromString=Qo,be.fromValue=_t,As=65536,$d=1<<24,Lr=As*As,Ds=Lr*Lr,Ps=Ds/2,Es=ur($d),wt=ur(0),be.ZERO=wt,Ut=ur(0,!0),be.UZERO=Ut,Dr=ur(1),be.ONE=Dr,Ls=ur(1,!0),be.UONE=Ls,Zo=ur(-1),be.NEG_ONE=Zo,Fs=le(-1,2147483647,!1),be.MAX_VALUE=Fs,$s=le(-1,-1,!0),be.MAX_UNSIGNED_VALUE=$s,tt=le(0,-2147483648,!1),be.MIN_VALUE=tt,$=be.prototype,$.toInt=function(){return this.unsigned?this.low>>>0:this.low},$.toNumber=function(){return this.unsigned?(this.high>>>0)*Lr+(this.low>>>0):this.high*Lr+(this.low>>>0)},$.toString=function(t){if(t=t||10,t<2||36>>0,o=d.toString(t);if(i=u,i.isZero())return o+a;for(;o.length<6;)o="0"+o;a=""+o+a}},$.getHighBits=function(){return this.high},$.getHighBitsUnsigned=function(){return this.high>>>0},$.getLowBits=function(){return this.low},$.getLowBitsUnsigned=function(){return this.low>>>0},$.getNumBitsAbs=function(){if(this.isNegative())return this.eq(tt)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0},$.isOdd=function(){return(this.low&1)===1},$.isEven=function(){return(this.low&1)===0},$.equals=function(t){return We(t)||(t=_t(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low},$.eq=$.equals,$.notEquals=function(t){return!this.eq(t)},$.neq=$.notEquals,$.ne=$.notEquals,$.lessThan=function(t){return this.comp(t)<0},$.lt=$.lessThan,$.lessThanOrEqual=function(t){return this.comp(t)<=0},$.lte=$.lessThanOrEqual,$.le=$.lessThanOrEqual,$.greaterThan=function(t){return this.comp(t)>0},$.gt=$.greaterThan,$.greaterThanOrEqual=function(t){return this.comp(t)>=0},$.gte=$.greaterThanOrEqual,$.ge=$.greaterThanOrEqual,$.compare=function(t){if(We(t)||(t=_t(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},$.comp=$.compare,$.negate=function(){return!this.unsigned&&this.eq(tt)?tt:this.not().add(Dr)},$.neg=$.negate,$.add=function(t){We(t)||(t=_t(t));var e=this.high>>>16,n=this.high&65535,r=this.low>>>16,s=this.low&65535,i=t.high>>>16,a=t.high&65535,u=t.low>>>16,d=t.low&65535,o=0,l=0,c=0,h=0;return h+=s+d,c+=h>>>16,h&=65535,c+=r+u,l+=c>>>16,c&=65535,l+=n+a,o+=l>>>16,l&=65535,o+=e+i,o&=65535,le(c<<16|h,o<<16|l,this.unsigned)},$.subtract=function(t){return We(t)||(t=_t(t)),this.add(t.neg())},$.sub=$.subtract,$.multiply=function(t){if(this.isZero())return this;if(We(t)||(t=_t(t)),lt){var e=lt.mul(this.low,this.high,t.low,t.high);return le(e,lt.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Ut:wt;if(this.eq(tt))return t.isOdd()?tt:wt;if(t.eq(tt))return this.isOdd()?tt:wt;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Es)&&t.lt(Es))return ft(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,r=this.high&65535,s=this.low>>>16,i=this.low&65535,a=t.high>>>16,u=t.high&65535,d=t.low>>>16,o=t.low&65535,l=0,c=0,h=0,f=0;return f+=i*o,h+=f>>>16,f&=65535,h+=s*o,c+=h>>>16,h&=65535,h+=i*d,c+=h>>>16,h&=65535,c+=r*o,l+=c>>>16,c&=65535,c+=s*d,l+=c>>>16,c&=65535,c+=i*u,l+=c>>>16,c&=65535,l+=n*o+r*d+s*u+i*a,l&=65535,le(h<<16|f,l<<16|c,this.unsigned)},$.mul=$.multiply,$.divide=function(t){if(We(t)||(t=_t(t)),t.isZero())throw Error("division by zero");if(lt){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?lt.div_u:lt.div_s)(this.low,this.high,t.low,t.high);return le(e,lt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Ut:wt;var n,r,s;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Ut;if(t.gt(this.shru(1)))return Ls;s=Ut}else{if(this.eq(tt)){if(t.eq(Dr)||t.eq(Zo))return tt;if(t.eq(tt))return Dr;var i=this.shr(1);return n=i.div(t).shl(1),n.eq(wt)?t.isNegative()?Dr:Zo:(r=this.sub(t.mul(n)),s=n.add(r.div(t)),s)}else if(t.eq(tt))return this.unsigned?Ut:wt;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=wt}for(r=this;r.gte(t);){n=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),u=a<=48?1:Vn(2,a-48),d=ft(n),o=d.mul(t);o.isNegative()||o.gt(r);)n-=u,d=ft(n,this.unsigned),o=d.mul(t);d.isZero()&&(d=Dr),s=s.add(d),r=r.sub(o)}return s},$.div=$.divide,$.modulo=function(t){if(We(t)||(t=_t(t)),lt){var e=(this.unsigned?lt.rem_u:lt.rem_s)(this.low,this.high,t.low,t.high);return le(e,lt.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},$.mod=$.modulo,$.rem=$.modulo,$.not=function(){return le(~this.low,~this.high,this.unsigned)},$.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},$.clz=$.countLeadingZeros,$.countTrailingZeros=function(){return this.low?Os(this.low):Os(this.high)+32},$.ctz=$.countTrailingZeros,$.and=function(t){return We(t)||(t=_t(t)),le(this.low&t.low,this.high&t.high,this.unsigned)},$.or=function(t){return We(t)||(t=_t(t)),le(this.low|t.low,this.high|t.high,this.unsigned)},$.xor=function(t){return We(t)||(t=_t(t)),le(this.low^t.low,this.high^t.high,this.unsigned)},$.shiftLeft=function(t){return We(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?le(this.low<>>32-t,this.unsigned):le(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):le(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},$.shr=$.shiftRight,$.shiftRightUnsigned=function(t){return We(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?le(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?le(this.high,0,this.unsigned):le(this.high>>>t-32,0,this.unsigned)},$.shru=$.shiftRightUnsigned,$.shr_u=$.shiftRightUnsigned,$.rotateLeft=function(t){var e;return We(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?le(this.high,this.low,this.unsigned):t<32?(e=32-t,le(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,le(this.high<>>e,this.low<>>e,this.unsigned))},$.rotl=$.rotateLeft,$.rotateRight=function(t){var e;return We(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?le(this.high,this.low,this.unsigned):t<32?(e=32-t,le(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,le(this.low<>>t,this.high<>>t,this.unsigned))},$.rotr=$.rotateRight,$.toSigned=function(){return this.unsigned?le(this.low,this.high,!1):this},$.toUnsigned=function(){return this.unsigned?this:le(this.low,this.high,!0)},$.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},$.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]},$.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]},be.fromBytes=function(t,e,n){return n?be.fromBytesLE(t,e):be.fromBytesBE(t,e)},be.fromBytesLE=function(t,e){return new be(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},be.fromBytesBE=function(t,e){return new be(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)},zt=be}),_,Wn=L(()=>{_={},_.Offset,_.Table,_.SIZEOF_SHORT=2,_.SIZEOF_INT=4,_.FILE_IDENTIFIER_LENGTH=4,_.SIZE_PREFIX_LENGTH=4,_.Encoding={UTF8_BYTES:1,UTF16_STRING:2},_.int32=new Int32Array(2),_.float32=new Float32Array(_.int32.buffer),_.float64=new Float64Array(_.int32.buffer),_.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,_.Long=function(t,e){this.low=t|0,this.high=e|0},_.Long.create=function(t,e){return t==0&&e==0?_.Long.ZERO:new _.Long(t,e)},_.Long.prototype.toFloat64=function(){return(this.low>>>0)+this.high*4294967296},_.Long.prototype.equals=function(t){return this.low==t.low&&this.high==t.high},_.Long.ZERO=new _.Long(0,0),_.Builder=function(t){if(t)var e=t;else var e=1024;this.bb=_.ByteBuffer.allocate(e),this.space=e,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},_.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},_.Builder.prototype.forceDefaults=function(t){this.force_defaults=t},_.Builder.prototype.dataBuffer=function(){return this.bb},_.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},_.Builder.prototype.prep=function(t,e){t>this.minalign&&(this.minalign=t);for(var n=~(this.bb.capacity()-this.space+e)+1&t-1;this.space=0&&this.vtable[e]==0;e--);for(var n=e+1;e>=0;e--)this.addInt16(this.vtable[e]!=0?t-this.vtable[e]:0);var r=2;this.addInt16(t-this.object_start);var s=(n+r)*_.SIZEOF_SHORT;this.addInt16(s);var i=0,a=this.space;e:for(e=0;e=0;i--)this.writeInt8(s.charCodeAt(i))}this.prep(this.minalign,_.SIZEOF_INT+r),this.addOffset(t),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},_.Builder.prototype.finishSizePrefixed=function(t,e){this.finish(t,e,!0)},_.Builder.prototype.requiredField=function(t,e){var n=this.bb.capacity()-t,r=n-this.bb.readInt32(n),s=this.bb.readInt16(r+e)!=0;if(!s)throw new Error("FlatBuffers: field "+e+" must be set")},_.Builder.prototype.startVector=function(t,e,n){this.notNested(),this.vector_num_elems=e,this.prep(_.SIZEOF_INT,t*e),this.prep(n,t*e)},_.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},_.Builder.prototype.createString=function(t){if(t instanceof Uint8Array)var e=t;else for(var e=[],n=0;n=56320)r=s;else{var i=t.charCodeAt(n++);r=(s<<10)+i+-56613888}r<128?e.push(r):(r<2048?e.push(r>>6&31|192):(r<65536?e.push(r>>12&15|224):e.push(r>>18&7|240,r>>12&63|128),e.push(r>>6&63|128)),e.push(r&63|128))}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(var n=0,a=this.space,u=this.bb.bytes();n>24},_.ByteBuffer.prototype.readUint8=function(t){return this.bytes_[t]},_.ByteBuffer.prototype.readInt16=function(t){return this.readUint16(t)<<16>>16},_.ByteBuffer.prototype.readUint16=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8},_.ByteBuffer.prototype.readInt32=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24},_.ByteBuffer.prototype.readUint32=function(t){return this.readInt32(t)>>>0},_.ByteBuffer.prototype.readInt64=function(t){return new _.Long(this.readInt32(t),this.readInt32(t+4))},_.ByteBuffer.prototype.readUint64=function(t){return new _.Long(this.readUint32(t),this.readUint32(t+4))},_.ByteBuffer.prototype.readFloat32=function(t){return _.int32[0]=this.readInt32(t),_.float32[0]},_.ByteBuffer.prototype.readFloat64=function(t){return _.int32[_.isLittleEndian?0:1]=this.readInt32(t),_.int32[_.isLittleEndian?1:0]=this.readInt32(t+4),_.float64[0]},_.ByteBuffer.prototype.writeInt8=function(t,e){this.bytes_[t]=e},_.ByteBuffer.prototype.writeUint8=function(t,e){this.bytes_[t]=e},_.ByteBuffer.prototype.writeInt16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},_.ByteBuffer.prototype.writeUint16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},_.ByteBuffer.prototype.writeInt32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},_.ByteBuffer.prototype.writeUint32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},_.ByteBuffer.prototype.writeInt64=function(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)},_.ByteBuffer.prototype.writeUint64=function(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)},_.ByteBuffer.prototype.writeFloat32=function(t,e){_.float32[0]=e,this.writeInt32(t,_.int32[0])},_.ByteBuffer.prototype.writeFloat64=function(t,e){_.float64[0]=e,this.writeInt32(t,_.int32[_.isLittleEndian?0:1]),this.writeInt32(t+4,_.int32[_.isLittleEndian?1:0])},_.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10)+55296,(i&1023)+56320))}return r},_.ByteBuffer.prototype.__indirect=function(t){return t+this.readInt32(t)},_.ByteBuffer.prototype.__vector=function(t){return t+this.readInt32(t)+_.SIZEOF_INT},_.ByteBuffer.prototype.__vector_len=function(t){return this.readInt32(t+this.readInt32(t))},_.ByteBuffer.prototype.__has_identifier=function(t){if(t.length!=_.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+_.FILE_IDENTIFIER_LENGTH);for(var e=0;e<_.FILE_IDENTIFIER_LENGTH;e++)if(t.charCodeAt(e)!=this.readInt8(this.position_+_.SIZEOF_INT+e))return!1;return!0},_.ByteBuffer.prototype.createLong=function(t,e){return _.Long.create(t,e)}}),W,tn=L(()=>{Wn(),(t=>{(e=>{(n=>{(r=>(r[r.UNDEFINED=0]="UNDEFINED",r[r.FLOAT=1]="FLOAT",r[r.INT=2]="INT",r[r.STRING=3]="STRING",r[r.TENSOR=4]="TENSOR",r[r.GRAPH=5]="GRAPH",r[r.FLOATS=6]="FLOATS",r[r.INTS=7]="INTS",r[r.STRINGS=8]="STRINGS",r[r.TENSORS=9]="TENSORS",r[r.GRAPHS=10]="GRAPHS",r[r.SPARSE_TENSOR=11]="SPARSE_TENSOR",r[r.SPARSE_TENSORS=12]="SPARSE_TENSORS"))(n.AttributeType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{(r=>(r[r.UNKNOWN=0]="UNKNOWN",r[r.VALUE=1]="VALUE",r[r.PARAM=2]="PARAM"))(n.DimensionValueType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{(r=>(r[r.UNDEFINED=0]="UNDEFINED",r[r.FLOAT=1]="FLOAT",r[r.UINT8=2]="UINT8",r[r.INT8=3]="INT8",r[r.UINT16=4]="UINT16",r[r.INT16=5]="INT16",r[r.INT32=6]="INT32",r[r.INT64=7]="INT64",r[r.STRING=8]="STRING",r[r.BOOL=9]="BOOL",r[r.FLOAT16=10]="FLOAT16",r[r.DOUBLE=11]="DOUBLE",r[r.UINT32=12]="UINT32",r[r.UINT64=13]="UINT64",r[r.COMPLEX64=14]="COMPLEX64",r[r.COMPLEX128=15]="COMPLEX128",r[r.BFLOAT16=16]="BFLOAT16",r[r.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",r[r.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",r[r.FLOAT8E5M2=19]="FLOAT8E5M2",r[r.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"))(n.TensorDataType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{(r=>(r[r.Primitive=0]="Primitive",r[r.Fused=1]="Fused"))(n.NodeType||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{(r=>(r[r.NONE=0]="NONE",r[r.tensor_type=1]="tensor_type",r[r.sequence_type=2]="sequence_type",r[r.map_type=3]="map_type"))(n.TypeInfoValue||={})})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsShape(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsShape(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}dim(i,a){let u=this.bb.__offset(this.bb_pos,4);return u?(a||new t.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}dimLength(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__vector_len(this.bb_pos+i):0}static startShape(i){i.startObject(1)}static addDim(i,a){i.addFieldOffset(0,a,0)}static createDimVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startDimVector(i,a){i.startVector(4,a,4)}static endShape(i){return i.endObject()}static createShape(i,a){return r.startShape(i),r.addDim(i,a),r.endShape(i)}}n.Shape=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsDimension(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsDimension(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}value(i){let a=this.bb.__offset(this.bb_pos,4);return a?(i||new t.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}denotation(i){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__string(this.bb_pos+a,i):null}static startDimension(i){i.startObject(2)}static addValue(i,a){i.addFieldOffset(0,a,0)}static addDenotation(i,a){i.addFieldOffset(1,a,0)}static endDimension(i){return i.endObject()}static createDimension(i,a,u){return r.startDimension(i),r.addValue(i,a),r.addDenotation(i,u),r.endDimension(i)}}n.Dimension=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsDimensionValue(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsDimensionValue(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}dimType(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.readInt8(this.bb_pos+i):0}dimValue(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.readInt64(this.bb_pos+i):this.bb.createLong(0,0)}dimParam(i){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__string(this.bb_pos+a,i):null}static startDimensionValue(i){i.startObject(3)}static addDimType(i,a){i.addFieldInt8(0,a,0)}static addDimValue(i,a){i.addFieldInt64(1,a,i.createLong(0,0))}static addDimParam(i,a){i.addFieldOffset(2,a,0)}static endDimensionValue(i){return i.endObject()}static createDimensionValue(i,a,u,d){return r.startDimensionValue(i),r.addDimType(i,a),r.addDimValue(i,u),r.addDimParam(i,d),r.endDimensionValue(i)}}n.DimensionValue=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsTensorTypeAndShape(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsTensorTypeAndShape(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}elemType(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.readInt32(this.bb_pos+i):0}shape(i){let a=this.bb.__offset(this.bb_pos,6);return a?(i||new t.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}static startTensorTypeAndShape(i){i.startObject(2)}static addElemType(i,a){i.addFieldInt32(0,a,0)}static addShape(i,a){i.addFieldOffset(1,a,0)}static endTensorTypeAndShape(i){return i.endObject()}static createTensorTypeAndShape(i,a,u){return r.startTensorTypeAndShape(i),r.addElemType(i,a),r.addShape(i,u),r.endTensorTypeAndShape(i)}}n.TensorTypeAndShape=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsMapType(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsMapType(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}keyType(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.readInt32(this.bb_pos+i):0}valueType(i){let a=this.bb.__offset(this.bb_pos,6);return a?(i||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}static startMapType(i){i.startObject(2)}static addKeyType(i,a){i.addFieldInt32(0,a,0)}static addValueType(i,a){i.addFieldOffset(1,a,0)}static endMapType(i){return i.endObject()}static createMapType(i,a,u){return r.startMapType(i),r.addKeyType(i,a),r.addValueType(i,u),r.endMapType(i)}}n.MapType=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsSequenceType(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsSequenceType(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}elemType(i){let a=this.bb.__offset(this.bb_pos,4);return a?(i||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}static startSequenceType(i){i.startObject(1)}static addElemType(i,a){i.addFieldOffset(0,a,0)}static endSequenceType(i){return i.endObject()}static createSequenceType(i,a){return r.startSequenceType(i),r.addElemType(i,a),r.endSequenceType(i)}}n.SequenceType=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(i,a,u,d){return i.prep(4,12),i.writeInt32(d),i.writeInt32(u),i.writeInt32(a),i.offset()}}n.EdgeEnd=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsNodeEdge(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsNodeEdge(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}nodeIndex(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.readUint32(this.bb_pos+i):0}inputEdges(i,a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+u)+i*12,this.bb):null}inputEdgesLength(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.__vector_len(this.bb_pos+i):0}outputEdges(i,a){let u=this.bb.__offset(this.bb_pos,8);return u?(a||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+u)+i*12,this.bb):null}outputEdgesLength(){let i=this.bb.__offset(this.bb_pos,8);return i?this.bb.__vector_len(this.bb_pos+i):0}static startNodeEdge(i){i.startObject(3)}static addNodeIndex(i,a){i.addFieldInt32(0,a,0)}static addInputEdges(i,a){i.addFieldOffset(1,a,0)}static startInputEdgesVector(i,a){i.startVector(12,a,4)}static addOutputEdges(i,a){i.addFieldOffset(2,a,0)}static startOutputEdgesVector(i,a){i.startVector(12,a,4)}static endNodeEdge(i){return i.endObject()}static createNodeEdge(i,a,u,d){return r.startNodeEdge(i),r.addNodeIndex(i,a),r.addInputEdges(i,u),r.addOutputEdges(i,d),r.endNodeEdge(i)}}n.NodeEdge=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsNode(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsNode(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}name(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}docString(i){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__string(this.bb_pos+a,i):null}domain(i){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__string(this.bb_pos+a,i):null}sinceVersion(){let i=this.bb.__offset(this.bb_pos,10);return i?this.bb.readInt32(this.bb_pos+i):0}index(){let i=this.bb.__offset(this.bb_pos,12);return i?this.bb.readUint32(this.bb_pos+i):0}opType(i){let a=this.bb.__offset(this.bb_pos,14);return a?this.bb.__string(this.bb_pos+a,i):null}type(){let i=this.bb.__offset(this.bb_pos,16);return i?this.bb.readInt32(this.bb_pos+i):0}executionProviderType(i){let a=this.bb.__offset(this.bb_pos,18);return a?this.bb.__string(this.bb_pos+a,i):null}inputs(i,a){let u=this.bb.__offset(this.bb_pos,20);return u?this.bb.__string(this.bb.__vector(this.bb_pos+u)+i*4,a):null}inputsLength(){let i=this.bb.__offset(this.bb_pos,20);return i?this.bb.__vector_len(this.bb_pos+i):0}outputs(i,a){let u=this.bb.__offset(this.bb_pos,22);return u?this.bb.__string(this.bb.__vector(this.bb_pos+u)+i*4,a):null}outputsLength(){let i=this.bb.__offset(this.bb_pos,22);return i?this.bb.__vector_len(this.bb_pos+i):0}attributes(i,a){let u=this.bb.__offset(this.bb_pos,24);return u?(a||new t.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}attributesLength(){let i=this.bb.__offset(this.bb_pos,24);return i?this.bb.__vector_len(this.bb_pos+i):0}inputArgCounts(i){let a=this.bb.__offset(this.bb_pos,26);return a?this.bb.readInt32(this.bb.__vector(this.bb_pos+a)+i*4):0}inputArgCountsLength(){let i=this.bb.__offset(this.bb_pos,26);return i?this.bb.__vector_len(this.bb_pos+i):0}inputArgCountsArray(){let i=this.bb.__offset(this.bb_pos,26);return i?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+i),this.bb.__vector_len(this.bb_pos+i)):null}implicitInputs(i,a){let u=this.bb.__offset(this.bb_pos,28);return u?this.bb.__string(this.bb.__vector(this.bb_pos+u)+i*4,a):null}implicitInputsLength(){let i=this.bb.__offset(this.bb_pos,28);return i?this.bb.__vector_len(this.bb_pos+i):0}static startNode(i){i.startObject(13)}static addName(i,a){i.addFieldOffset(0,a,0)}static addDocString(i,a){i.addFieldOffset(1,a,0)}static addDomain(i,a){i.addFieldOffset(2,a,0)}static addSinceVersion(i,a){i.addFieldInt32(3,a,0)}static addIndex(i,a){i.addFieldInt32(4,a,0)}static addOpType(i,a){i.addFieldOffset(5,a,0)}static addType(i,a){i.addFieldInt32(6,a,0)}static addExecutionProviderType(i,a){i.addFieldOffset(7,a,0)}static addInputs(i,a){i.addFieldOffset(8,a,0)}static createInputsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startInputsVector(i,a){i.startVector(4,a,4)}static addOutputs(i,a){i.addFieldOffset(9,a,0)}static createOutputsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startOutputsVector(i,a){i.startVector(4,a,4)}static addAttributes(i,a){i.addFieldOffset(10,a,0)}static createAttributesVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startAttributesVector(i,a){i.startVector(4,a,4)}static addInputArgCounts(i,a){i.addFieldOffset(11,a,0)}static createInputArgCountsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addInt32(a[u]);return i.endVector()}static startInputArgCountsVector(i,a){i.startVector(4,a,4)}static addImplicitInputs(i,a){i.addFieldOffset(12,a,0)}static createImplicitInputsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startImplicitInputsVector(i,a){i.startVector(4,a,4)}static endNode(i){return i.endObject()}static createNode(i,a,u,d,o,l,c,h,f,p,g,b,x,y){return r.startNode(i),r.addName(i,a),r.addDocString(i,u),r.addDomain(i,d),r.addSinceVersion(i,o),r.addIndex(i,l),r.addOpType(i,c),r.addType(i,h),r.addExecutionProviderType(i,f),r.addInputs(i,p),r.addOutputs(i,g),r.addAttributes(i,b),r.addInputArgCounts(i,x),r.addImplicitInputs(i,y),r.endNode(i)}}n.Node=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsValueInfo(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsValueInfo(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}name(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}docString(i){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__string(this.bb_pos+a,i):null}type(i){let a=this.bb.__offset(this.bb_pos,8);return a?(i||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}static startValueInfo(i){i.startObject(3)}static addName(i,a){i.addFieldOffset(0,a,0)}static addDocString(i,a){i.addFieldOffset(1,a,0)}static addType(i,a){i.addFieldOffset(2,a,0)}static endValueInfo(i){return i.endObject()}static createValueInfo(i,a,u,d){return r.startValueInfo(i),r.addName(i,a),r.addDocString(i,u),r.addType(i,d),r.endValueInfo(i)}}n.ValueInfo=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsTypeInfo(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsTypeInfo(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}denotation(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}valueType(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.readUint8(this.bb_pos+i):0}value(i){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__union(i,this.bb_pos+a):null}static startTypeInfo(i){i.startObject(3)}static addDenotation(i,a){i.addFieldOffset(0,a,0)}static addValueType(i,a){i.addFieldInt8(1,a,0)}static addValue(i,a){i.addFieldOffset(2,a,0)}static endTypeInfo(i){return i.endObject()}static createTypeInfo(i,a,u,d){return r.startTypeInfo(i),r.addDenotation(i,a),r.addValueType(i,u),r.addValue(i,d),r.endTypeInfo(i)}}n.TypeInfo=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsOperatorSetId(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsOperatorSetId(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}domain(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}version(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.readInt64(this.bb_pos+i):this.bb.createLong(0,0)}static startOperatorSetId(i){i.startObject(2)}static addDomain(i,a){i.addFieldOffset(0,a,0)}static addVersion(i,a){i.addFieldInt64(1,a,i.createLong(0,0))}static endOperatorSetId(i){return i.endObject()}static createOperatorSetId(i,a,u){return r.startOperatorSetId(i),r.addDomain(i,a),r.addVersion(i,u),r.endOperatorSetId(i)}}n.OperatorSetId=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsTensor(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsTensor(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}name(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}docString(i){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__string(this.bb_pos+a,i):null}dims(i){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.readInt64(this.bb.__vector(this.bb_pos+a)+i*8):this.bb.createLong(0,0)}dimsLength(){let i=this.bb.__offset(this.bb_pos,8);return i?this.bb.__vector_len(this.bb_pos+i):0}dataType(){let i=this.bb.__offset(this.bb_pos,10);return i?this.bb.readInt32(this.bb_pos+i):0}rawData(i){let a=this.bb.__offset(this.bb_pos,12);return a?this.bb.readUint8(this.bb.__vector(this.bb_pos+a)+i):0}rawDataLength(){let i=this.bb.__offset(this.bb_pos,12);return i?this.bb.__vector_len(this.bb_pos+i):0}rawDataArray(){let i=this.bb.__offset(this.bb_pos,12);return i?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+i),this.bb.__vector_len(this.bb_pos+i)):null}stringData(i,a){let u=this.bb.__offset(this.bb_pos,14);return u?this.bb.__string(this.bb.__vector(this.bb_pos+u)+i*4,a):null}stringDataLength(){let i=this.bb.__offset(this.bb_pos,14);return i?this.bb.__vector_len(this.bb_pos+i):0}static startTensor(i){i.startObject(6)}static addName(i,a){i.addFieldOffset(0,a,0)}static addDocString(i,a){i.addFieldOffset(1,a,0)}static addDims(i,a){i.addFieldOffset(2,a,0)}static createDimsVector(i,a){i.startVector(8,a.length,8);for(let u=a.length-1;u>=0;u--)i.addInt64(a[u]);return i.endVector()}static startDimsVector(i,a){i.startVector(8,a,8)}static addDataType(i,a){i.addFieldInt32(3,a,0)}static addRawData(i,a){i.addFieldOffset(4,a,0)}static createRawDataVector(i,a){i.startVector(1,a.length,1);for(let u=a.length-1;u>=0;u--)i.addInt8(a[u]);return i.endVector()}static startRawDataVector(i,a){i.startVector(1,a,1)}static addStringData(i,a){i.addFieldOffset(5,a,0)}static createStringDataVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startStringDataVector(i,a){i.startVector(4,a,4)}static endTensor(i){return i.endObject()}static createTensor(i,a,u,d,o,l,c){return r.startTensor(i),r.addName(i,a),r.addDocString(i,u),r.addDims(i,d),r.addDataType(i,o),r.addRawData(i,l),r.addStringData(i,c),r.endTensor(i)}}n.Tensor=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsSparseTensor(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsSparseTensor(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}values(i){let a=this.bb.__offset(this.bb_pos,4);return a?(i||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}indices(i){let a=this.bb.__offset(this.bb_pos,6);return a?(i||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}dims(i){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.readInt64(this.bb.__vector(this.bb_pos+a)+i*8):this.bb.createLong(0,0)}dimsLength(){let i=this.bb.__offset(this.bb_pos,8);return i?this.bb.__vector_len(this.bb_pos+i):0}static startSparseTensor(i){i.startObject(3)}static addValues(i,a){i.addFieldOffset(0,a,0)}static addIndices(i,a){i.addFieldOffset(1,a,0)}static addDims(i,a){i.addFieldOffset(2,a,0)}static createDimsVector(i,a){i.startVector(8,a.length,8);for(let u=a.length-1;u>=0;u--)i.addInt64(a[u]);return i.endVector()}static startDimsVector(i,a){i.startVector(8,a,8)}static endSparseTensor(i){return i.endObject()}static createSparseTensor(i,a,u,d){return r.startSparseTensor(i),r.addValues(i,a),r.addIndices(i,u),r.addDims(i,d),r.endSparseTensor(i)}}n.SparseTensor=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsAttribute(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsAttribute(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}name(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}docString(i){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__string(this.bb_pos+a,i):null}type(){let i=this.bb.__offset(this.bb_pos,8);return i?this.bb.readInt32(this.bb_pos+i):0}f(){let i=this.bb.__offset(this.bb_pos,10);return i?this.bb.readFloat32(this.bb_pos+i):0}i(){let i=this.bb.__offset(this.bb_pos,12);return i?this.bb.readInt64(this.bb_pos+i):this.bb.createLong(0,0)}s(i){let a=this.bb.__offset(this.bb_pos,14);return a?this.bb.__string(this.bb_pos+a,i):null}t(i){let a=this.bb.__offset(this.bb_pos,16);return a?(i||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}g(i){let a=this.bb.__offset(this.bb_pos,18);return a?(i||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}floats(i){let a=this.bb.__offset(this.bb_pos,20);return a?this.bb.readFloat32(this.bb.__vector(this.bb_pos+a)+i*4):0}floatsLength(){let i=this.bb.__offset(this.bb_pos,20);return i?this.bb.__vector_len(this.bb_pos+i):0}floatsArray(){let i=this.bb.__offset(this.bb_pos,20);return i?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+i),this.bb.__vector_len(this.bb_pos+i)):null}ints(i){let a=this.bb.__offset(this.bb_pos,22);return a?this.bb.readInt64(this.bb.__vector(this.bb_pos+a)+i*8):this.bb.createLong(0,0)}intsLength(){let i=this.bb.__offset(this.bb_pos,22);return i?this.bb.__vector_len(this.bb_pos+i):0}strings(i,a){let u=this.bb.__offset(this.bb_pos,24);return u?this.bb.__string(this.bb.__vector(this.bb_pos+u)+i*4,a):null}stringsLength(){let i=this.bb.__offset(this.bb_pos,24);return i?this.bb.__vector_len(this.bb_pos+i):0}tensors(i,a){let u=this.bb.__offset(this.bb_pos,26);return u?(a||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}tensorsLength(){let i=this.bb.__offset(this.bb_pos,26);return i?this.bb.__vector_len(this.bb_pos+i):0}graphs(i,a){let u=this.bb.__offset(this.bb_pos,28);return u?(a||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}graphsLength(){let i=this.bb.__offset(this.bb_pos,28);return i?this.bb.__vector_len(this.bb_pos+i):0}static startAttribute(i){i.startObject(13)}static addName(i,a){i.addFieldOffset(0,a,0)}static addDocString(i,a){i.addFieldOffset(1,a,0)}static addType(i,a){i.addFieldInt32(2,a,0)}static addF(i,a){i.addFieldFloat32(3,a,0)}static addI(i,a){i.addFieldInt64(4,a,i.createLong(0,0))}static addS(i,a){i.addFieldOffset(5,a,0)}static addT(i,a){i.addFieldOffset(6,a,0)}static addG(i,a){i.addFieldOffset(7,a,0)}static addFloats(i,a){i.addFieldOffset(8,a,0)}static createFloatsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addFloat32(a[u]);return i.endVector()}static startFloatsVector(i,a){i.startVector(4,a,4)}static addInts(i,a){i.addFieldOffset(9,a,0)}static createIntsVector(i,a){i.startVector(8,a.length,8);for(let u=a.length-1;u>=0;u--)i.addInt64(a[u]);return i.endVector()}static startIntsVector(i,a){i.startVector(8,a,8)}static addStrings(i,a){i.addFieldOffset(10,a,0)}static createStringsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startStringsVector(i,a){i.startVector(4,a,4)}static addTensors(i,a){i.addFieldOffset(11,a,0)}static createTensorsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startTensorsVector(i,a){i.startVector(4,a,4)}static addGraphs(i,a){i.addFieldOffset(12,a,0)}static createGraphsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startGraphsVector(i,a){i.startVector(4,a,4)}static endAttribute(i){return i.endObject()}static createAttribute(i,a,u,d,o,l,c,h,f,p,g,b,x,y){return r.startAttribute(i),r.addName(i,a),r.addDocString(i,u),r.addType(i,d),r.addF(i,o),r.addI(i,l),r.addS(i,c),r.addT(i,h),r.addG(i,f),r.addFloats(i,p),r.addInts(i,g),r.addStrings(i,b),r.addTensors(i,x),r.addGraphs(i,y),r.endAttribute(i)}}n.Attribute=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsGraph(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsGraph(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}initializers(i,a){let u=this.bb.__offset(this.bb_pos,4);return u?(a||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}initializersLength(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__vector_len(this.bb_pos+i):0}nodeArgs(i,a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new t.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}nodeArgsLength(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.__vector_len(this.bb_pos+i):0}nodes(i,a){let u=this.bb.__offset(this.bb_pos,8);return u?(a||new t.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}nodesLength(){let i=this.bb.__offset(this.bb_pos,8);return i?this.bb.__vector_len(this.bb_pos+i):0}maxNodeIndex(){let i=this.bb.__offset(this.bb_pos,10);return i?this.bb.readUint32(this.bb_pos+i):0}nodeEdges(i,a){let u=this.bb.__offset(this.bb_pos,12);return u?(a||new t.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}nodeEdgesLength(){let i=this.bb.__offset(this.bb_pos,12);return i?this.bb.__vector_len(this.bb_pos+i):0}inputs(i,a){let u=this.bb.__offset(this.bb_pos,14);return u?this.bb.__string(this.bb.__vector(this.bb_pos+u)+i*4,a):null}inputsLength(){let i=this.bb.__offset(this.bb_pos,14);return i?this.bb.__vector_len(this.bb_pos+i):0}outputs(i,a){let u=this.bb.__offset(this.bb_pos,16);return u?this.bb.__string(this.bb.__vector(this.bb_pos+u)+i*4,a):null}outputsLength(){let i=this.bb.__offset(this.bb_pos,16);return i?this.bb.__vector_len(this.bb_pos+i):0}sparseInitializers(i,a){let u=this.bb.__offset(this.bb_pos,18);return u?(a||new t.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}sparseInitializersLength(){let i=this.bb.__offset(this.bb_pos,18);return i?this.bb.__vector_len(this.bb_pos+i):0}static startGraph(i){i.startObject(8)}static addInitializers(i,a){i.addFieldOffset(0,a,0)}static createInitializersVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startInitializersVector(i,a){i.startVector(4,a,4)}static addNodeArgs(i,a){i.addFieldOffset(1,a,0)}static createNodeArgsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startNodeArgsVector(i,a){i.startVector(4,a,4)}static addNodes(i,a){i.addFieldOffset(2,a,0)}static createNodesVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startNodesVector(i,a){i.startVector(4,a,4)}static addMaxNodeIndex(i,a){i.addFieldInt32(3,a,0)}static addNodeEdges(i,a){i.addFieldOffset(4,a,0)}static createNodeEdgesVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startNodeEdgesVector(i,a){i.startVector(4,a,4)}static addInputs(i,a){i.addFieldOffset(5,a,0)}static createInputsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startInputsVector(i,a){i.startVector(4,a,4)}static addOutputs(i,a){i.addFieldOffset(6,a,0)}static createOutputsVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startOutputsVector(i,a){i.startVector(4,a,4)}static addSparseInitializers(i,a){i.addFieldOffset(7,a,0)}static createSparseInitializersVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startSparseInitializersVector(i,a){i.startVector(4,a,4)}static endGraph(i){return i.endObject()}static createGraph(i,a,u,d,o,l,c,h,f){return r.startGraph(i),r.addInitializers(i,a),r.addNodeArgs(i,u),r.addNodes(i,d),r.addMaxNodeIndex(i,o),r.addNodeEdges(i,l),r.addInputs(i,c),r.addOutputs(i,h),r.addSparseInitializers(i,f),r.endGraph(i)}}n.Graph=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsModel(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsModel(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}irVersion(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.readInt64(this.bb_pos+i):this.bb.createLong(0,0)}opsetImport(i,a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new t.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}opsetImportLength(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.__vector_len(this.bb_pos+i):0}producerName(i){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__string(this.bb_pos+a,i):null}producerVersion(i){let a=this.bb.__offset(this.bb_pos,10);return a?this.bb.__string(this.bb_pos+a,i):null}domain(i){let a=this.bb.__offset(this.bb_pos,12);return a?this.bb.__string(this.bb_pos+a,i):null}modelVersion(){let i=this.bb.__offset(this.bb_pos,14);return i?this.bb.readInt64(this.bb_pos+i):this.bb.createLong(0,0)}docString(i){let a=this.bb.__offset(this.bb_pos,16);return a?this.bb.__string(this.bb_pos+a,i):null}graph(i){let a=this.bb.__offset(this.bb_pos,18);return a?(i||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}graphDocString(i){let a=this.bb.__offset(this.bb_pos,20);return a?this.bb.__string(this.bb_pos+a,i):null}static startModel(i){i.startObject(9)}static addIrVersion(i,a){i.addFieldInt64(0,a,i.createLong(0,0))}static addOpsetImport(i,a){i.addFieldOffset(1,a,0)}static createOpsetImportVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startOpsetImportVector(i,a){i.startVector(4,a,4)}static addProducerName(i,a){i.addFieldOffset(2,a,0)}static addProducerVersion(i,a){i.addFieldOffset(3,a,0)}static addDomain(i,a){i.addFieldOffset(4,a,0)}static addModelVersion(i,a){i.addFieldInt64(5,a,i.createLong(0,0))}static addDocString(i,a){i.addFieldOffset(6,a,0)}static addGraph(i,a){i.addFieldOffset(7,a,0)}static addGraphDocString(i,a){i.addFieldOffset(8,a,0)}static endModel(i){return i.endObject()}static createModel(i,a,u,d,o,l,c,h,f,p){return r.startModel(i),r.addIrVersion(i,a),r.addOpsetImport(i,u),r.addProducerName(i,d),r.addProducerVersion(i,o),r.addDomain(i,l),r.addModelVersion(i,c),r.addDocString(i,h),r.addGraph(i,f),r.addGraphDocString(i,p),r.endModel(i)}}n.Model=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsKernelCreateInfos(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsKernelCreateInfos(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}nodeIndices(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.readUint32(this.bb.__vector(this.bb_pos+a)+i*4):0}nodeIndicesLength(){let i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__vector_len(this.bb_pos+i):0}nodeIndicesArray(){let i=this.bb.__offset(this.bb_pos,4);return i?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+i),this.bb.__vector_len(this.bb_pos+i)):null}kernelDefHashes(i){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.readUint64(this.bb.__vector(this.bb_pos+a)+i*8):this.bb.createLong(0,0)}kernelDefHashesLength(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.__vector_len(this.bb_pos+i):0}static startKernelCreateInfos(i){i.startObject(2)}static addNodeIndices(i,a){i.addFieldOffset(0,a,0)}static createNodeIndicesVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addInt32(a[u]);return i.endVector()}static startNodeIndicesVector(i,a){i.startVector(4,a,4)}static addKernelDefHashes(i,a){i.addFieldOffset(1,a,0)}static createKernelDefHashesVector(i,a){i.startVector(8,a.length,8);for(let u=a.length-1;u>=0;u--)i.addInt64(a[u]);return i.endVector()}static startKernelDefHashesVector(i,a){i.startVector(8,a,8)}static endKernelCreateInfos(i){return i.endObject()}static createKernelCreateInfos(i,a,u){return r.startKernelCreateInfos(i),r.addNodeIndices(i,a),r.addKernelDefHashes(i,u),r.endKernelCreateInfos(i)}}n.KernelCreateInfos=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsSubGraphSessionState(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsSubGraphSessionState(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}graphId(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}sessionState(i){let a=this.bb.__offset(this.bb_pos,6);return a?(i||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}static startSubGraphSessionState(i){i.startObject(2)}static addGraphId(i,a){i.addFieldOffset(0,a,0)}static addSessionState(i,a){i.addFieldOffset(1,a,0)}static endSubGraphSessionState(i){let a=i.endObject();return i.requiredField(a,4),a}static createSubGraphSessionState(i,a,u){return r.startSubGraphSessionState(i),r.addGraphId(i,a),r.addSessionState(i,u),r.endSubGraphSessionState(i)}}n.SubGraphSessionState=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsSessionState(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsSessionState(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}kernels(i){let a=this.bb.__offset(this.bb_pos,4);return a?(i||new t.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}subGraphSessionStates(i,a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new t.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+u)+i*4),this.bb):null}subGraphSessionStatesLength(){let i=this.bb.__offset(this.bb_pos,6);return i?this.bb.__vector_len(this.bb_pos+i):0}static startSessionState(i){i.startObject(2)}static addKernels(i,a){i.addFieldOffset(0,a,0)}static addSubGraphSessionStates(i,a){i.addFieldOffset(1,a,0)}static createSubGraphSessionStatesVector(i,a){i.startVector(4,a.length,4);for(let u=a.length-1;u>=0;u--)i.addOffset(a[u]);return i.endVector()}static startSubGraphSessionStatesVector(i,a){i.startVector(4,a,4)}static endSessionState(i){return i.endObject()}static createSessionState(i,a,u){return r.startSessionState(i),r.addKernels(i,a),r.addSubGraphSessionStates(i,u),r.endSessionState(i)}}n.SessionState=r})(e.fbs||={})})(t.experimental||={})})(W||={}),(t=>{(e=>{(n=>{class r{constructor(){this.bb=null,this.bb_pos=0}__init(i,a){return this.bb_pos=i,this.bb=a,this}static getRootAsInferenceSession(i,a){return(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static getSizePrefixedRootAsInferenceSession(i,a){return i.setPosition(i.position()+_.SIZE_PREFIX_LENGTH),(a||new r).__init(i.readInt32(i.position())+i.position(),i)}static bufferHasIdentifier(i){return i.__has_identifier("ORTM")}ortVersion(i){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__string(this.bb_pos+a,i):null}model(i){let a=this.bb.__offset(this.bb_pos,6);return a?(i||new t.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}sessionState(i){let a=this.bb.__offset(this.bb_pos,8);return a?(i||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+a),this.bb):null}static startInferenceSession(i){i.startObject(3)}static addOrtVersion(i,a){i.addFieldOffset(0,a,0)}static addModel(i,a){i.addFieldOffset(1,a,0)}static addSessionState(i,a){i.addFieldOffset(2,a,0)}static endInferenceSession(i){return i.endObject()}static finishInferenceSessionBuffer(i,a){i.finish(a,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(i,a){i.finish(a,"ORTM",!0)}static createInferenceSession(i,a,u,d){return r.startInferenceSession(i),r.addOrtVersion(i,a),r.addModel(i,u),r.addSessionState(i,d),r.endInferenceSession(i)}}n.InferenceSession=r})(e.fbs||={})})(t.experimental||={})})(W||={})}),ks=me((t,e)=>{e.exports=n;function n(r,s){for(var i=new Array(arguments.length-1),a=0,u=2,d=!0;u{var e=t;e.length=function(a){var u=a.length;if(!u)return 0;for(var d=0;--u%4>1&&a.charAt(u)==="=";)++d;return Math.ceil(a.length*3)/4-d};var n=new Array(64),r=new Array(123);for(s=0;s<64;)r[n[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;var s;e.encode=function(a,u,d){for(var o=null,l=[],c=0,h=0,f;u>2],f=(p&3)<<4,h=1;break;case 1:l[c++]=n[f|p>>4],f=(p&15)<<2,h=2;break;case 2:l[c++]=n[f|p>>6],l[c++]=n[p&63],h=0;break}c>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,l)),c=0)}return h&&(l[c++]=n[f],l[c++]=61,h===1&&(l[c++]=61)),o?(c&&o.push(String.fromCharCode.apply(String,l.slice(0,c))),o.join("")):String.fromCharCode.apply(String,l.slice(0,c))};var i="invalid encoding";e.decode=function(a,u,d){for(var o=d,l=0,c,h=0;h1)break;if((f=r[f])===void 0)throw Error(i);switch(l){case 0:c=f,l=1;break;case 1:u[d++]=c<<2|(f&48)>>4,c=f,l=2;break;case 2:u[d++]=(c&15)<<4|(f&60)>>2,c=f,l=3;break;case 3:u[d++]=(c&3)<<6|f,l=0;break}}if(l===1)throw Error(i);return d-o},e.test=function(a){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a)}}),Us=me((t,e)=>{e.exports=n;function n(){this._listeners={}}n.prototype.on=function(r,s,i){return(this._listeners[r]||(this._listeners[r]=[])).push({fn:s,ctx:i||this}),this},n.prototype.off=function(r,s){if(r===void 0)this._listeners={};else if(s===void 0)this._listeners[r]=[];else for(var i=this._listeners[r],a=0;a{e.exports=n(n);function n(u){return typeof Float32Array<"u"?function(){var d=new Float32Array([-0]),o=new Uint8Array(d.buffer),l=o[3]===128;function c(g,b,x){d[0]=g,b[x]=o[0],b[x+1]=o[1],b[x+2]=o[2],b[x+3]=o[3]}function h(g,b,x){d[0]=g,b[x]=o[3],b[x+1]=o[2],b[x+2]=o[1],b[x+3]=o[0]}u.writeFloatLE=l?c:h,u.writeFloatBE=l?h:c;function f(g,b){return o[0]=g[b],o[1]=g[b+1],o[2]=g[b+2],o[3]=g[b+3],d[0]}function p(g,b){return o[3]=g[b],o[2]=g[b+1],o[1]=g[b+2],o[0]=g[b+3],d[0]}u.readFloatLE=l?f:p,u.readFloatBE=l?p:f}():function(){function d(l,c,h,f){var p=c<0?1:0;if(p&&(c=-c),c===0)l(1/c>0?0:2147483648,h,f);else if(isNaN(c))l(2143289344,h,f);else if(c>34028234663852886e22)l((p<<31|2139095040)>>>0,h,f);else if(c<11754943508222875e-54)l((p<<31|Math.round(c/1401298464324817e-60))>>>0,h,f);else{var g=Math.floor(Math.log(c)/Math.LN2),b=Math.round(c*Math.pow(2,-g)*8388608)&8388607;l((p<<31|g+127<<23|b)>>>0,h,f)}}u.writeFloatLE=d.bind(null,r),u.writeFloatBE=d.bind(null,s);function o(l,c,h){var f=l(c,h),p=(f>>31)*2+1,g=f>>>23&255,b=f&8388607;return g===255?b?NaN:p*(1/0):g===0?p*1401298464324817e-60*b:p*Math.pow(2,g-150)*(b+8388608)}u.readFloatLE=o.bind(null,i),u.readFloatBE=o.bind(null,a)}(),typeof Float64Array<"u"?function(){var d=new Float64Array([-0]),o=new Uint8Array(d.buffer),l=o[7]===128;function c(g,b,x){d[0]=g,b[x]=o[0],b[x+1]=o[1],b[x+2]=o[2],b[x+3]=o[3],b[x+4]=o[4],b[x+5]=o[5],b[x+6]=o[6],b[x+7]=o[7]}function h(g,b,x){d[0]=g,b[x]=o[7],b[x+1]=o[6],b[x+2]=o[5],b[x+3]=o[4],b[x+4]=o[3],b[x+5]=o[2],b[x+6]=o[1],b[x+7]=o[0]}u.writeDoubleLE=l?c:h,u.writeDoubleBE=l?h:c;function f(g,b){return o[0]=g[b],o[1]=g[b+1],o[2]=g[b+2],o[3]=g[b+3],o[4]=g[b+4],o[5]=g[b+5],o[6]=g[b+6],o[7]=g[b+7],d[0]}function p(g,b){return o[7]=g[b],o[6]=g[b+1],o[5]=g[b+2],o[4]=g[b+3],o[3]=g[b+4],o[2]=g[b+5],o[1]=g[b+6],o[0]=g[b+7],d[0]}u.readDoubleLE=l?f:p,u.readDoubleBE=l?p:f}():function(){function d(l,c,h,f,p,g){var b=f<0?1:0;if(b&&(f=-f),f===0)l(0,p,g+c),l(1/f>0?0:2147483648,p,g+h);else if(isNaN(f))l(0,p,g+c),l(2146959360,p,g+h);else if(f>17976931348623157e292)l(0,p,g+c),l((b<<31|2146435072)>>>0,p,g+h);else{var x;if(f<22250738585072014e-324)x=f/5e-324,l(x>>>0,p,g+c),l((b<<31|x/4294967296)>>>0,p,g+h);else{var y=Math.floor(Math.log(f)/Math.LN2);y===1024&&(y=1023),x=f*Math.pow(2,-y),l(x*4503599627370496>>>0,p,g+c),l((b<<31|y+1023<<20|x*1048576&1048575)>>>0,p,g+h)}}}u.writeDoubleLE=d.bind(null,r,0,4),u.writeDoubleBE=d.bind(null,s,4,0);function o(l,c,h,f,p){var g=l(f,p+c),b=l(f,p+h),x=(b>>31)*2+1,y=b>>>20&2047,T=4294967296*(b&1048575)+g;return y===2047?T?NaN:x*(1/0):y===0?x*5e-324*T:x*Math.pow(2,y-1075)*(T+4503599627370496)}u.readDoubleLE=o.bind(null,i,0,4),u.readDoubleBE=o.bind(null,a,4,0)}(),u}function r(u,d,o){d[o]=u&255,d[o+1]=u>>>8&255,d[o+2]=u>>>16&255,d[o+3]=u>>>24}function s(u,d,o){d[o]=u>>>24,d[o+1]=u>>>16&255,d[o+2]=u>>>8&255,d[o+3]=u&255}function i(u,d){return(u[d]|u[d+1]<<8|u[d+2]<<16|u[d+3]<<24)>>>0}function a(u,d){return(u[d]<<24|u[d+1]<<16|u[d+2]<<8|u[d+3])>>>0}}),Xs=me((exports,module)=>{module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}}),Js=me(t=>{var e=t;e.length=function(n){for(var r=0,s=0,i=0;i191&&o<224?u[d++]=(o&31)<<6|n[r++]&63:o>239&&o<365?(o=((o&7)<<18|(n[r++]&63)<<12|(n[r++]&63)<<6|n[r++]&63)-65536,u[d++]=55296+(o>>10),u[d++]=56320+(o&1023)):u[d++]=(o&15)<<12|(n[r++]&63)<<6|n[r++]&63,d>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,u)),d=0);return a?(d&&a.push(String.fromCharCode.apply(String,u.slice(0,d))),a.join("")):String.fromCharCode.apply(String,u.slice(0,d))},e.write=function(n,r,s){for(var i=s,a,u,d=0;d>6|192,r[s++]=a&63|128):(a&64512)===55296&&((u=n.charCodeAt(d+1))&64512)===56320?(a=65536+((a&1023)<<10)+(u&1023),++d,r[s++]=a>>18|240,r[s++]=a>>12&63|128,r[s++]=a>>6&63|128,r[s++]=a&63|128):(r[s++]=a>>12|224,r[s++]=a>>6&63|128,r[s++]=a&63|128);return s-i}}),Qs=me((t,e)=>{e.exports=n;function n(r,s,i){var a=i||8192,u=a>>>1,d=null,o=a;return function(l){if(l<1||l>u)return r(l);o+l>a&&(d=r(a),o=0);var c=s.call(d,o,o+=l);return o&7&&(o=(o|7)+1),c}}}),tu=me((t,e)=>{e.exports=r;var n=Xt();function r(u,d){this.lo=u>>>0,this.hi=d>>>0}var s=r.zero=new r(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var i=r.zeroHash="\0\0\0\0\0\0\0\0";r.fromNumber=function(u){if(u===0)return s;var d=u<0;d&&(u=-u);var o=u>>>0,l=(u-o)/4294967296>>>0;return d&&(l=~l>>>0,o=~o>>>0,++o>4294967295&&(o=0,++l>4294967295&&(l=0))),new r(o,l)},r.from=function(u){if(typeof u=="number")return r.fromNumber(u);if(n.isString(u))if(n.Long)u=n.Long.fromString(u);else return r.fromNumber(parseInt(u,10));return u.low||u.high?new r(u.low>>>0,u.high>>>0):s},r.prototype.toNumber=function(u){if(!u&&this.hi>>>31){var d=~this.lo+1>>>0,o=~this.hi>>>0;return d||(o=o+1>>>0),-(d+o*4294967296)}return this.lo+this.hi*4294967296},r.prototype.toLong=function(u){return n.Long?new n.Long(this.lo|0,this.hi|0,!!u):{low:this.lo|0,high:this.hi|0,unsigned:!!u}};var a=String.prototype.charCodeAt;r.fromHash=function(u){return u===i?s:new r((a.call(u,0)|a.call(u,1)<<8|a.call(u,2)<<16|a.call(u,3)<<24)>>>0,(a.call(u,4)|a.call(u,5)<<8|a.call(u,6)<<16|a.call(u,7)<<24)>>>0)},r.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},r.prototype.zzEncode=function(){var u=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^u)>>>0,this.lo=(this.lo<<1^u)>>>0,this},r.prototype.zzDecode=function(){var u=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^u)>>>0,this.hi=(this.hi>>>1^u)>>>0,this},r.prototype.length=function(){var u=this.lo,d=(this.lo>>>28|this.hi<<4)>>>0,o=this.hi>>>24;return o===0?d===0?u<16384?u<128?1:2:u<2097152?3:4:d<16384?d<128?5:6:d<2097152?7:8:o<128?9:10}}),Xt=me(t=>{var e=t;e.asPromise=ks(),e.base64=Ms(),e.EventEmitter=Us(),e.float=Ys(),e.inquire=Xs(),e.utf8=Js(),e.pool=Qs(),e.LongBits=tu(),e.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),e.global=e.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||t,e.emptyArray=Object.freeze?Object.freeze([]):[],e.emptyObject=Object.freeze?Object.freeze({}):{},e.isInteger=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s},e.isString=function(s){return typeof s=="string"||s instanceof String},e.isObject=function(s){return s&&typeof s=="object"},e.isset=e.isSet=function(s,i){var a=s[i];return a!=null&&s.hasOwnProperty(i)?typeof a!="object"||(Array.isArray(a)?a.length:Object.keys(a).length)>0:!1},e.Buffer=function(){try{var s=e.inquire("buffer").Buffer;return s.prototype.utf8Write?s:null}catch{return null}}(),e._Buffer_from=null,e._Buffer_allocUnsafe=null,e.newBuffer=function(s){return typeof s=="number"?e.Buffer?e._Buffer_allocUnsafe(s):new e.Array(s):e.Buffer?e._Buffer_from(s):typeof Uint8Array>"u"?s:new Uint8Array(s)},e.Array=typeof Uint8Array<"u"?Uint8Array:Array,e.Long=e.global.dcodeIO&&e.global.dcodeIO.Long||e.global.Long||e.inquire("long"),e.key2Re=/^true|false|0|1$/,e.key32Re=/^-?(?:0|[1-9][0-9]*)$/,e.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,e.longToHash=function(s){return s?e.LongBits.from(s).toHash():e.LongBits.zeroHash},e.longFromHash=function(s,i){var a=e.LongBits.fromHash(s);return e.Long?e.Long.fromBits(a.lo,a.hi,i):a.toNumber(!!i)};function n(s,i,a){for(var u=Object.keys(i),d=0;d-1;--d)if(i[u[d]]===1&&this[u[d]]!==void 0&&this[u[d]]!==null)return u[d]}},e.oneOfSetter=function(s){return function(i){for(var a=0;a{e.exports=l;var n=Xt(),r,s=n.LongBits,i=n.base64,a=n.utf8;function u(y,T,S){this.fn=y,this.len=T,this.next=void 0,this.val=S}function d(){}function o(y){this.head=y.head,this.tail=y.tail,this.len=y.len,this.next=y.states}function l(){this.len=0,this.head=new u(d,0,0),this.tail=this.head,this.states=null}var c=function(){return n.Buffer?function(){return(l.create=function(){return new r})()}:function(){return new l}};l.create=c(),l.alloc=function(y){return new n.Array(y)},n.Array!==Array&&(l.alloc=n.pool(l.alloc,n.Array.prototype.subarray)),l.prototype._push=function(y,T,S){return this.tail=this.tail.next=new u(y,T,S),this.len+=T,this};function h(y,T,S){T[S]=y&255}function f(y,T,S){for(;y>127;)T[S++]=y&127|128,y>>>=7;T[S]=y}function p(y,T){this.len=y,this.next=void 0,this.val=T}p.prototype=Object.create(u.prototype),p.prototype.fn=f,l.prototype.uint32=function(y){return this.len+=(this.tail=this.tail.next=new p((y=y>>>0)<128?1:y<16384?2:y<2097152?3:y<268435456?4:5,y)).len,this},l.prototype.int32=function(y){return y<0?this._push(g,10,s.fromNumber(y)):this.uint32(y)},l.prototype.sint32=function(y){return this.uint32((y<<1^y>>31)>>>0)};function g(y,T,S){for(;y.hi;)T[S++]=y.lo&127|128,y.lo=(y.lo>>>7|y.hi<<25)>>>0,y.hi>>>=7;for(;y.lo>127;)T[S++]=y.lo&127|128,y.lo=y.lo>>>7;T[S++]=y.lo}l.prototype.uint64=function(y){var T=s.from(y);return this._push(g,T.length(),T)},l.prototype.int64=l.prototype.uint64,l.prototype.sint64=function(y){var T=s.from(y).zzEncode();return this._push(g,T.length(),T)},l.prototype.bool=function(y){return this._push(h,1,y?1:0)};function b(y,T,S){T[S]=y&255,T[S+1]=y>>>8&255,T[S+2]=y>>>16&255,T[S+3]=y>>>24}l.prototype.fixed32=function(y){return this._push(b,4,y>>>0)},l.prototype.sfixed32=l.prototype.fixed32,l.prototype.fixed64=function(y){var T=s.from(y);return this._push(b,4,T.lo)._push(b,4,T.hi)},l.prototype.sfixed64=l.prototype.fixed64,l.prototype.float=function(y){return this._push(n.float.writeFloatLE,4,y)},l.prototype.double=function(y){return this._push(n.float.writeDoubleLE,8,y)};var x=n.Array.prototype.set?function(y,T,S){T.set(y,S)}:function(y,T,S){for(var E=0;E>>0;if(!T)return this._push(h,1,0);if(n.isString(y)){var S=l.alloc(T=i.length(y));i.decode(y,S,0),y=S}return this.uint32(T)._push(x,T,y)},l.prototype.string=function(y){var T=a.length(y);return T?this.uint32(T)._push(a.write,T,y):this._push(h,1,0)},l.prototype.fork=function(){return this.states=new o(this),this.head=this.tail=new u(d,0,0),this.len=0,this},l.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(d,0,0),this.len=0),this},l.prototype.ldelim=function(){var y=this.head,T=this.tail,S=this.len;return this.reset().uint32(S),S&&(this.tail.next=y.next,this.tail=T,this.len+=S),this},l.prototype.finish=function(){for(var y=this.head.next,T=this.constructor.alloc(this.len),S=0;y;)y.fn(y.val,T,S),S+=y.len,y=y.next;return T},l._configure=function(y){r=y,l.create=c(),r._configure()}}),fu=me((t,e)=>{e.exports=s;var n=li();(s.prototype=Object.create(n.prototype)).constructor=s;var r=Xt();function s(){n.call(this)}s._configure=function(){s.alloc=r._Buffer_allocUnsafe,s.writeBytesBuffer=r.Buffer&&r.Buffer.prototype instanceof Uint8Array&&r.Buffer.prototype.set.name==="set"?function(a,u,d){u.set(a,d)}:function(a,u,d){if(a.copy)a.copy(u,d,0,a.length);else for(var o=0;o>>0;return this.uint32(u),u&&this._push(s.writeBytesBuffer,u,a),this};function i(a,u,d){a.length<40?r.utf8.write(a,u,d):u.utf8Write?u.utf8Write(a,d):u.write(a,d)}s.prototype.string=function(a){var u=r.Buffer.byteLength(a);return this.uint32(u),u&&this._push(i,u,a),this},s._configure()}),pi=me((t,e)=>{e.exports=u;var n=Xt(),r,s=n.LongBits,i=n.utf8;function a(f,p){return RangeError("index out of range: "+f.pos+" + "+(p||1)+" > "+f.len)}function u(f){this.buf=f,this.pos=0,this.len=f.length}var d=typeof Uint8Array<"u"?function(f){if(f instanceof Uint8Array||Array.isArray(f))return new u(f);throw Error("illegal buffer")}:function(f){if(Array.isArray(f))return new u(f);throw Error("illegal buffer")},o=function(){return n.Buffer?function(f){return(u.create=function(p){return n.Buffer.isBuffer(p)?new r(p):d(p)})(f)}:d};u.create=o(),u.prototype._slice=n.Array.prototype.subarray||n.Array.prototype.slice,u.prototype.uint32=function(){var f=4294967295;return function(){if(f=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(f=(f|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(f=(f|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(f=(f|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(f=(f|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return f;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return f}}(),u.prototype.int32=function(){return this.uint32()|0},u.prototype.sint32=function(){var f=this.uint32();return f>>>1^-(f&1)|0};function l(){var f=new s(0,0),p=0;if(this.len-this.pos>4){for(;p<4;++p)if(f.lo=(f.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f;if(f.lo=(f.lo|(this.buf[this.pos]&127)<<28)>>>0,f.hi=(f.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return f;p=0}else{for(;p<3;++p){if(this.pos>=this.len)throw a(this);if(f.lo=(f.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f}return f.lo=(f.lo|(this.buf[this.pos++]&127)<>>0,f}if(this.len-this.pos>4){for(;p<5;++p)if(f.hi=(f.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f}else for(;p<5;++p){if(this.pos>=this.len)throw a(this);if(f.hi=(f.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return f}throw Error("invalid varint encoding")}u.prototype.bool=function(){return this.uint32()!==0};function c(f,p){return(f[p-4]|f[p-3]<<8|f[p-2]<<16|f[p-1]<<24)>>>0}u.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return c(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return c(this.buf,this.pos+=4)|0};function h(){if(this.pos+8>this.len)throw a(this,8);return new s(c(this.buf,this.pos+=4),c(this.buf,this.pos+=4))}u.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var f=n.float.readFloatLE(this.buf,this.pos);return this.pos+=4,f},u.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var f=n.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,f},u.prototype.bytes=function(){var f=this.uint32(),p=this.pos,g=this.pos+f;if(g>this.len)throw a(this,f);return this.pos+=f,Array.isArray(this.buf)?this.buf.slice(p,g):p===g?new this.buf.constructor(0):this._slice.call(this.buf,p,g)},u.prototype.string=function(){var f=this.bytes();return i.read(f,0,f.length)},u.prototype.skip=function(f){if(typeof f=="number"){if(this.pos+f>this.len)throw a(this,f);this.pos+=f}else do if(this.pos>=this.len)throw a(this);while(this.buf[this.pos++]&128);return this},u.prototype.skipType=function(f){switch(f){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(f=this.uint32()&7)!==4;)this.skipType(f);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+f+" at offset "+this.pos)}return this},u._configure=function(f){r=f,u.create=o(),r._configure();var p=n.Long?"toLong":"toNumber";n.merge(u.prototype,{int64:function(){return l.call(this)[p](!1)},uint64:function(){return l.call(this)[p](!0)},sint64:function(){return l.call(this).zzDecode()[p](!1)},fixed64:function(){return h.call(this)[p](!0)},sfixed64:function(){return h.call(this)[p](!1)}})}}),Tu=me((t,e)=>{e.exports=s;var n=pi();(s.prototype=Object.create(n.prototype)).constructor=s;var r=Xt();function s(i){n.call(this,i)}s._configure=function(){r.Buffer&&(s.prototype._slice=r.Buffer.prototype.slice)},s.prototype.string=function(){var i=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+i,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+i,this.len))},s._configure()}),vu=me((t,e)=>{e.exports=r;var n=Xt();(r.prototype=Object.create(n.EventEmitter.prototype)).constructor=r;function r(s,i,a){if(typeof s!="function")throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=s,this.requestDelimited=!!i,this.responseDelimited=!!a}r.prototype.rpcCall=function s(i,a,u,d,o){if(!d)throw TypeError("request must be specified");var l=this;if(!o)return n.asPromise(s,l,i,a,u,d);if(!l.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return l.rpcImpl(i,a[l.requestDelimited?"encodeDelimited":"encode"](d).finish(),function(c,h){if(c)return l.emit("error",c,i),o(c);if(h===null){l.end(!0);return}if(!(h instanceof u))try{h=u[l.responseDelimited?"decodeDelimited":"decode"](h)}catch(f){return l.emit("error",f,i),o(f)}return l.emit("data",h,i),o(null,h)})}catch(c){l.emit("error",c,i),setTimeout(function(){o(c)},0);return}},r.prototype.end=function(s){return this.rpcImpl&&(s||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}}),_u=me(t=>{var e=t;e.Service=vu()}),Iu=me((t,e)=>{e.exports={}}),Pu=me(t=>{var e=t;e.build="minimal",e.Writer=li(),e.BufferWriter=fu(),e.Reader=pi(),e.BufferReader=Tu(),e.util=Xt(),e.rpc=_u(),e.roots=Iu(),e.configure=n;function n(){e.util._configure(),e.Writer._configure(e.BufferWriter),e.Reader._configure(e.BufferReader)}n()}),Du=me((t,e)=>{e.exports=Pu()}),$r=me((t,e)=>{var n=Du(),r=n.Reader,s=n.Writer,i=n.util,a=n.roots.default||(n.roots.default={});a.onnx=function(){var u={};return u.Version=function(){var d={},o=Object.create(d);return o[d[0]="_START_VERSION"]=0,o[d[1]="IR_VERSION_2017_10_10"]=1,o[d[2]="IR_VERSION_2017_10_30"]=2,o[d[3]="IR_VERSION_2017_11_3"]=3,o[d[4]="IR_VERSION_2019_1_22"]=4,o[d[5]="IR_VERSION_2019_3_18"]=5,o[d[6]="IR_VERSION_2019_9_19"]=6,o[d[7]="IR_VERSION_2020_5_8"]=7,o[d[8]="IR_VERSION_2021_7_30"]=8,o[d[9]="IR_VERSION"]=9,o}(),u.AttributeProto=function(){function d(o){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],o)for(var l=Object.keys(o),c=0;c>>3){case 1:{h.name=o.string();break}case 21:{h.refAttrName=o.string();break}case 13:{h.docString=o.string();break}case 20:{h.type=o.int32();break}case 2:{h.f=o.float();break}case 3:{h.i=o.int64();break}case 4:{h.s=o.bytes();break}case 5:{h.t=a.onnx.TensorProto.decode(o,o.uint32());break}case 6:{h.g=a.onnx.GraphProto.decode(o,o.uint32());break}case 22:{h.sparseTensor=a.onnx.SparseTensorProto.decode(o,o.uint32());break}case 14:{h.tp=a.onnx.TypeProto.decode(o,o.uint32());break}case 7:{if(h.floats&&h.floats.length||(h.floats=[]),(f&7)===2)for(var p=o.uint32()+o.pos;o.pos>>0,o.i.high>>>0).toNumber())),o.s!=null&&(typeof o.s=="string"?i.base64.decode(o.s,l.s=i.newBuffer(i.base64.length(o.s)),0):o.s.length>=0&&(l.s=o.s)),o.t!=null){if(typeof o.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");l.t=a.onnx.TensorProto.fromObject(o.t)}if(o.g!=null){if(typeof o.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");l.g=a.onnx.GraphProto.fromObject(o.g)}if(o.sparseTensor!=null){if(typeof o.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");l.sparseTensor=a.onnx.SparseTensorProto.fromObject(o.sparseTensor)}if(o.tp!=null){if(typeof o.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");l.tp=a.onnx.TypeProto.fromObject(o.tp)}if(o.floats){if(!Array.isArray(o.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");l.floats=[];for(var c=0;c>>0,o.ints[c].high>>>0).toNumber())}if(o.strings){if(!Array.isArray(o.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");l.strings=[];for(var c=0;c=0&&(l.strings[c]=o.strings[c])}if(o.tensors){if(!Array.isArray(o.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");l.tensors=[];for(var c=0;c>>0,o.i.high>>>0).toNumber():o.i),o.s!=null&&o.hasOwnProperty("s")&&(c.s=l.bytes===String?i.base64.encode(o.s,0,o.s.length):l.bytes===Array?Array.prototype.slice.call(o.s):o.s),o.t!=null&&o.hasOwnProperty("t")&&(c.t=a.onnx.TensorProto.toObject(o.t,l)),o.g!=null&&o.hasOwnProperty("g")&&(c.g=a.onnx.GraphProto.toObject(o.g,l)),o.floats&&o.floats.length){c.floats=[];for(var f=0;f>>0,o.ints[f].high>>>0).toNumber():o.ints[f]}if(o.strings&&o.strings.length){c.strings=[];for(var f=0;f>>3){case 1:{h.name=o.string();break}case 2:{h.type=a.onnx.TypeProto.decode(o,o.uint32());break}case 3:{h.docString=o.string();break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.name!=null&&o.hasOwnProperty("name")&&!i.isString(o.name))return"name: string expected";if(o.type!=null&&o.hasOwnProperty("type")){var l=a.onnx.TypeProto.verify(o.type);if(l)return"type."+l}return o.docString!=null&&o.hasOwnProperty("docString")&&!i.isString(o.docString)?"docString: string expected":null},d.fromObject=function(o){if(o instanceof a.onnx.ValueInfoProto)return o;var l=new a.onnx.ValueInfoProto;if(o.name!=null&&(l.name=String(o.name)),o.type!=null){if(typeof o.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");l.type=a.onnx.TypeProto.fromObject(o.type)}return o.docString!=null&&(l.docString=String(o.docString)),l},d.toObject=function(o,l){l||(l={});var c={};return l.defaults&&(c.name="",c.type=null,c.docString=""),o.name!=null&&o.hasOwnProperty("name")&&(c.name=o.name),o.type!=null&&o.hasOwnProperty("type")&&(c.type=a.onnx.TypeProto.toObject(o.type,l)),o.docString!=null&&o.hasOwnProperty("docString")&&(c.docString=o.docString),c},d.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},d.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.ValueInfoProto"},d}(),u.NodeProto=function(){function d(o){if(this.input=[],this.output=[],this.attribute=[],o)for(var l=Object.keys(o),c=0;c>>3){case 1:{h.input&&h.input.length||(h.input=[]),h.input.push(o.string());break}case 2:{h.output&&h.output.length||(h.output=[]),h.output.push(o.string());break}case 3:{h.name=o.string();break}case 4:{h.opType=o.string();break}case 7:{h.domain=o.string();break}case 5:{h.attribute&&h.attribute.length||(h.attribute=[]),h.attribute.push(a.onnx.AttributeProto.decode(o,o.uint32()));break}case 6:{h.docString=o.string();break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.input!=null&&o.hasOwnProperty("input")){if(!Array.isArray(o.input))return"input: array expected";for(var l=0;l>>3){case 1:{h.initialization=a.onnx.GraphProto.decode(o,o.uint32());break}case 2:{h.algorithm=a.onnx.GraphProto.decode(o,o.uint32());break}case 3:{h.initializationBinding&&h.initializationBinding.length||(h.initializationBinding=[]),h.initializationBinding.push(a.onnx.StringStringEntryProto.decode(o,o.uint32()));break}case 4:{h.updateBinding&&h.updateBinding.length||(h.updateBinding=[]),h.updateBinding.push(a.onnx.StringStringEntryProto.decode(o,o.uint32()));break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.initialization!=null&&o.hasOwnProperty("initialization")){var l=a.onnx.GraphProto.verify(o.initialization);if(l)return"initialization."+l}if(o.algorithm!=null&&o.hasOwnProperty("algorithm")){var l=a.onnx.GraphProto.verify(o.algorithm);if(l)return"algorithm."+l}if(o.initializationBinding!=null&&o.hasOwnProperty("initializationBinding")){if(!Array.isArray(o.initializationBinding))return"initializationBinding: array expected";for(var c=0;c>>3){case 1:{h.irVersion=o.int64();break}case 8:{h.opsetImport&&h.opsetImport.length||(h.opsetImport=[]),h.opsetImport.push(a.onnx.OperatorSetIdProto.decode(o,o.uint32()));break}case 2:{h.producerName=o.string();break}case 3:{h.producerVersion=o.string();break}case 4:{h.domain=o.string();break}case 5:{h.modelVersion=o.int64();break}case 6:{h.docString=o.string();break}case 7:{h.graph=a.onnx.GraphProto.decode(o,o.uint32());break}case 14:{h.metadataProps&&h.metadataProps.length||(h.metadataProps=[]),h.metadataProps.push(a.onnx.StringStringEntryProto.decode(o,o.uint32()));break}case 20:{h.trainingInfo&&h.trainingInfo.length||(h.trainingInfo=[]),h.trainingInfo.push(a.onnx.TrainingInfoProto.decode(o,o.uint32()));break}case 25:{h.functions&&h.functions.length||(h.functions=[]),h.functions.push(a.onnx.FunctionProto.decode(o,o.uint32()));break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.irVersion!=null&&o.hasOwnProperty("irVersion")&&!i.isInteger(o.irVersion)&&!(o.irVersion&&i.isInteger(o.irVersion.low)&&i.isInteger(o.irVersion.high)))return"irVersion: integer|Long expected";if(o.opsetImport!=null&&o.hasOwnProperty("opsetImport")){if(!Array.isArray(o.opsetImport))return"opsetImport: array expected";for(var l=0;l>>0,o.irVersion.high>>>0).toNumber())),o.opsetImport){if(!Array.isArray(o.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");l.opsetImport=[];for(var c=0;c>>0,o.modelVersion.high>>>0).toNumber())),o.docString!=null&&(l.docString=String(o.docString)),o.graph!=null){if(typeof o.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");l.graph=a.onnx.GraphProto.fromObject(o.graph)}if(o.metadataProps){if(!Array.isArray(o.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");l.metadataProps=[];for(var c=0;c>>0,o.irVersion.high>>>0).toNumber():o.irVersion),o.producerName!=null&&o.hasOwnProperty("producerName")&&(c.producerName=o.producerName),o.producerVersion!=null&&o.hasOwnProperty("producerVersion")&&(c.producerVersion=o.producerVersion),o.domain!=null&&o.hasOwnProperty("domain")&&(c.domain=o.domain),o.modelVersion!=null&&o.hasOwnProperty("modelVersion")&&(typeof o.modelVersion=="number"?c.modelVersion=l.longs===String?String(o.modelVersion):o.modelVersion:c.modelVersion=l.longs===String?i.Long.prototype.toString.call(o.modelVersion):l.longs===Number?new i.LongBits(o.modelVersion.low>>>0,o.modelVersion.high>>>0).toNumber():o.modelVersion),o.docString!=null&&o.hasOwnProperty("docString")&&(c.docString=o.docString),o.graph!=null&&o.hasOwnProperty("graph")&&(c.graph=a.onnx.GraphProto.toObject(o.graph,l)),o.opsetImport&&o.opsetImport.length){c.opsetImport=[];for(var f=0;f>>3){case 1:{h.key=o.string();break}case 2:{h.value=o.string();break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){return typeof o!="object"||o===null?"object expected":o.key!=null&&o.hasOwnProperty("key")&&!i.isString(o.key)?"key: string expected":o.value!=null&&o.hasOwnProperty("value")&&!i.isString(o.value)?"value: string expected":null},d.fromObject=function(o){if(o instanceof a.onnx.StringStringEntryProto)return o;var l=new a.onnx.StringStringEntryProto;return o.key!=null&&(l.key=String(o.key)),o.value!=null&&(l.value=String(o.value)),l},d.toObject=function(o,l){l||(l={});var c={};return l.defaults&&(c.key="",c.value=""),o.key!=null&&o.hasOwnProperty("key")&&(c.key=o.key),o.value!=null&&o.hasOwnProperty("value")&&(c.value=o.value),c},d.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},d.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.StringStringEntryProto"},d}(),u.TensorAnnotation=function(){function d(o){if(this.quantParameterTensorNames=[],o)for(var l=Object.keys(o),c=0;c>>3){case 1:{h.tensorName=o.string();break}case 2:{h.quantParameterTensorNames&&h.quantParameterTensorNames.length||(h.quantParameterTensorNames=[]),h.quantParameterTensorNames.push(a.onnx.StringStringEntryProto.decode(o,o.uint32()));break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.tensorName!=null&&o.hasOwnProperty("tensorName")&&!i.isString(o.tensorName))return"tensorName: string expected";if(o.quantParameterTensorNames!=null&&o.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(o.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var l=0;l>>3){case 1:{h.node&&h.node.length||(h.node=[]),h.node.push(a.onnx.NodeProto.decode(o,o.uint32()));break}case 2:{h.name=o.string();break}case 5:{h.initializer&&h.initializer.length||(h.initializer=[]),h.initializer.push(a.onnx.TensorProto.decode(o,o.uint32()));break}case 15:{h.sparseInitializer&&h.sparseInitializer.length||(h.sparseInitializer=[]),h.sparseInitializer.push(a.onnx.SparseTensorProto.decode(o,o.uint32()));break}case 10:{h.docString=o.string();break}case 11:{h.input&&h.input.length||(h.input=[]),h.input.push(a.onnx.ValueInfoProto.decode(o,o.uint32()));break}case 12:{h.output&&h.output.length||(h.output=[]),h.output.push(a.onnx.ValueInfoProto.decode(o,o.uint32()));break}case 13:{h.valueInfo&&h.valueInfo.length||(h.valueInfo=[]),h.valueInfo.push(a.onnx.ValueInfoProto.decode(o,o.uint32()));break}case 14:{h.quantizationAnnotation&&h.quantizationAnnotation.length||(h.quantizationAnnotation=[]),h.quantizationAnnotation.push(a.onnx.TensorAnnotation.decode(o,o.uint32()));break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.node!=null&&o.hasOwnProperty("node")){if(!Array.isArray(o.node))return"node: array expected";for(var l=0;l>>3){case 1:{if(h.dims&&h.dims.length||(h.dims=[]),(f&7)===2)for(var p=o.uint32()+o.pos;o.pos>>0,o.dims[c].high>>>0).toNumber())}if(o.dataType!=null&&(l.dataType=o.dataType|0),o.segment!=null){if(typeof o.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");l.segment=a.onnx.TensorProto.Segment.fromObject(o.segment)}if(o.floatData){if(!Array.isArray(o.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");l.floatData=[];for(var c=0;c=0&&(l.stringData[c]=o.stringData[c])}if(o.int64Data){if(!Array.isArray(o.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");l.int64Data=[];for(var c=0;c>>0,o.int64Data[c].high>>>0).toNumber())}if(o.name!=null&&(l.name=String(o.name)),o.docString!=null&&(l.docString=String(o.docString)),o.rawData!=null&&(typeof o.rawData=="string"?i.base64.decode(o.rawData,l.rawData=i.newBuffer(i.base64.length(o.rawData)),0):o.rawData.length>=0&&(l.rawData=o.rawData)),o.externalData){if(!Array.isArray(o.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");l.externalData=[];for(var c=0;c>>0,o.uint64Data[c].high>>>0).toNumber(!0))}return l},d.toObject=function(o,l){l||(l={});var c={};if((l.arrays||l.defaults)&&(c.dims=[],c.floatData=[],c.int32Data=[],c.stringData=[],c.int64Data=[],c.doubleData=[],c.uint64Data=[],c.externalData=[]),l.defaults&&(c.dataType=0,c.segment=null,c.name="",l.bytes===String?c.rawData="":(c.rawData=[],l.bytes!==Array&&(c.rawData=i.newBuffer(c.rawData))),c.docString="",c.dataLocation=l.enums===String?"DEFAULT":0),o.dims&&o.dims.length){c.dims=[];for(var h=0;h>>0,o.dims[h].high>>>0).toNumber():o.dims[h]}if(o.dataType!=null&&o.hasOwnProperty("dataType")&&(c.dataType=o.dataType),o.segment!=null&&o.hasOwnProperty("segment")&&(c.segment=a.onnx.TensorProto.Segment.toObject(o.segment,l)),o.floatData&&o.floatData.length){c.floatData=[];for(var h=0;h>>0,o.int64Data[h].high>>>0).toNumber():o.int64Data[h]}if(o.name!=null&&o.hasOwnProperty("name")&&(c.name=o.name),o.rawData!=null&&o.hasOwnProperty("rawData")&&(c.rawData=l.bytes===String?i.base64.encode(o.rawData,0,o.rawData.length):l.bytes===Array?Array.prototype.slice.call(o.rawData):o.rawData),o.doubleData&&o.doubleData.length){c.doubleData=[];for(var h=0;h>>0,o.uint64Data[h].high>>>0).toNumber(!0):o.uint64Data[h]}if(o.docString!=null&&o.hasOwnProperty("docString")&&(c.docString=o.docString),o.externalData&&o.externalData.length){c.externalData=[];for(var h=0;h>>3){case 1:{f.begin=l.int64();break}case 2:{f.end=l.int64();break}default:l.skipType(p&7);break}}return f},o.decodeDelimited=function(l){return l instanceof r||(l=new r(l)),this.decode(l,l.uint32())},o.verify=function(l){return typeof l!="object"||l===null?"object expected":l.begin!=null&&l.hasOwnProperty("begin")&&!i.isInteger(l.begin)&&!(l.begin&&i.isInteger(l.begin.low)&&i.isInteger(l.begin.high))?"begin: integer|Long expected":l.end!=null&&l.hasOwnProperty("end")&&!i.isInteger(l.end)&&!(l.end&&i.isInteger(l.end.low)&&i.isInteger(l.end.high))?"end: integer|Long expected":null},o.fromObject=function(l){if(l instanceof a.onnx.TensorProto.Segment)return l;var c=new a.onnx.TensorProto.Segment;return l.begin!=null&&(i.Long?(c.begin=i.Long.fromValue(l.begin)).unsigned=!1:typeof l.begin=="string"?c.begin=parseInt(l.begin,10):typeof l.begin=="number"?c.begin=l.begin:typeof l.begin=="object"&&(c.begin=new i.LongBits(l.begin.low>>>0,l.begin.high>>>0).toNumber())),l.end!=null&&(i.Long?(c.end=i.Long.fromValue(l.end)).unsigned=!1:typeof l.end=="string"?c.end=parseInt(l.end,10):typeof l.end=="number"?c.end=l.end:typeof l.end=="object"&&(c.end=new i.LongBits(l.end.low>>>0,l.end.high>>>0).toNumber())),c},o.toObject=function(l,c){c||(c={});var h={};if(c.defaults){if(i.Long){var f=new i.Long(0,0,!1);h.begin=c.longs===String?f.toString():c.longs===Number?f.toNumber():f}else h.begin=c.longs===String?"0":0;if(i.Long){var f=new i.Long(0,0,!1);h.end=c.longs===String?f.toString():c.longs===Number?f.toNumber():f}else h.end=c.longs===String?"0":0}return l.begin!=null&&l.hasOwnProperty("begin")&&(typeof l.begin=="number"?h.begin=c.longs===String?String(l.begin):l.begin:h.begin=c.longs===String?i.Long.prototype.toString.call(l.begin):c.longs===Number?new i.LongBits(l.begin.low>>>0,l.begin.high>>>0).toNumber():l.begin),l.end!=null&&l.hasOwnProperty("end")&&(typeof l.end=="number"?h.end=c.longs===String?String(l.end):l.end:h.end=c.longs===String?i.Long.prototype.toString.call(l.end):c.longs===Number?new i.LongBits(l.end.low>>>0,l.end.high>>>0).toNumber():l.end),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TensorProto.Segment"},o}(),d.DataLocation=function(){var o={},l=Object.create(o);return l[o[0]="DEFAULT"]=0,l[o[1]="EXTERNAL"]=1,l}(),d}(),u.SparseTensorProto=function(){function d(o){if(this.dims=[],o)for(var l=Object.keys(o),c=0;c>>3){case 1:{h.values=a.onnx.TensorProto.decode(o,o.uint32());break}case 2:{h.indices=a.onnx.TensorProto.decode(o,o.uint32());break}case 3:{if(h.dims&&h.dims.length||(h.dims=[]),(f&7)===2)for(var p=o.uint32()+o.pos;o.pos>>0,o.dims[c].high>>>0).toNumber())}return l},d.toObject=function(o,l){l||(l={});var c={};if((l.arrays||l.defaults)&&(c.dims=[]),l.defaults&&(c.values=null,c.indices=null),o.values!=null&&o.hasOwnProperty("values")&&(c.values=a.onnx.TensorProto.toObject(o.values,l)),o.indices!=null&&o.hasOwnProperty("indices")&&(c.indices=a.onnx.TensorProto.toObject(o.indices,l)),o.dims&&o.dims.length){c.dims=[];for(var h=0;h>>0,o.dims[h].high>>>0).toNumber():o.dims[h]}return c},d.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},d.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.SparseTensorProto"},d}(),u.TensorShapeProto=function(){function d(o){if(this.dim=[],o)for(var l=Object.keys(o),c=0;c>>3){case 1:{h.dim&&h.dim.length||(h.dim=[]),h.dim.push(a.onnx.TensorShapeProto.Dimension.decode(o,o.uint32()));break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.dim!=null&&o.hasOwnProperty("dim")){if(!Array.isArray(o.dim))return"dim: array expected";for(var l=0;l>>3){case 1:{p.dimValue=c.int64();break}case 2:{p.dimParam=c.string();break}case 3:{p.denotation=c.string();break}default:c.skipType(g&7);break}}return p},o.decodeDelimited=function(c){return c instanceof r||(c=new r(c)),this.decode(c,c.uint32())},o.verify=function(c){if(typeof c!="object"||c===null)return"object expected";var h={};if(c.dimValue!=null&&c.hasOwnProperty("dimValue")&&(h.value=1,!i.isInteger(c.dimValue)&&!(c.dimValue&&i.isInteger(c.dimValue.low)&&i.isInteger(c.dimValue.high))))return"dimValue: integer|Long expected";if(c.dimParam!=null&&c.hasOwnProperty("dimParam")){if(h.value===1)return"value: multiple values";if(h.value=1,!i.isString(c.dimParam))return"dimParam: string expected"}return c.denotation!=null&&c.hasOwnProperty("denotation")&&!i.isString(c.denotation)?"denotation: string expected":null},o.fromObject=function(c){if(c instanceof a.onnx.TensorShapeProto.Dimension)return c;var h=new a.onnx.TensorShapeProto.Dimension;return c.dimValue!=null&&(i.Long?(h.dimValue=i.Long.fromValue(c.dimValue)).unsigned=!1:typeof c.dimValue=="string"?h.dimValue=parseInt(c.dimValue,10):typeof c.dimValue=="number"?h.dimValue=c.dimValue:typeof c.dimValue=="object"&&(h.dimValue=new i.LongBits(c.dimValue.low>>>0,c.dimValue.high>>>0).toNumber())),c.dimParam!=null&&(h.dimParam=String(c.dimParam)),c.denotation!=null&&(h.denotation=String(c.denotation)),h},o.toObject=function(c,h){h||(h={});var f={};return h.defaults&&(f.denotation=""),c.dimValue!=null&&c.hasOwnProperty("dimValue")&&(typeof c.dimValue=="number"?f.dimValue=h.longs===String?String(c.dimValue):c.dimValue:f.dimValue=h.longs===String?i.Long.prototype.toString.call(c.dimValue):h.longs===Number?new i.LongBits(c.dimValue.low>>>0,c.dimValue.high>>>0).toNumber():c.dimValue,h.oneofs&&(f.value="dimValue")),c.dimParam!=null&&c.hasOwnProperty("dimParam")&&(f.dimParam=c.dimParam,h.oneofs&&(f.value="dimParam")),c.denotation!=null&&c.hasOwnProperty("denotation")&&(f.denotation=c.denotation),f},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/onnx.TensorShapeProto.Dimension"},o}(),d}(),u.TypeProto=function(){function d(l){if(l)for(var c=Object.keys(l),h=0;h>>3){case 1:{f.tensorType=a.onnx.TypeProto.Tensor.decode(l,l.uint32());break}case 4:{f.sequenceType=a.onnx.TypeProto.Sequence.decode(l,l.uint32());break}case 5:{f.mapType=a.onnx.TypeProto.Map.decode(l,l.uint32());break}case 9:{f.optionalType=a.onnx.TypeProto.Optional.decode(l,l.uint32());break}case 8:{f.sparseTensorType=a.onnx.TypeProto.SparseTensor.decode(l,l.uint32());break}case 6:{f.denotation=l.string();break}default:l.skipType(p&7);break}}return f},d.decodeDelimited=function(l){return l instanceof r||(l=new r(l)),this.decode(l,l.uint32())},d.verify=function(l){if(typeof l!="object"||l===null)return"object expected";var c={};if(l.tensorType!=null&&l.hasOwnProperty("tensorType")){c.value=1;{var h=a.onnx.TypeProto.Tensor.verify(l.tensorType);if(h)return"tensorType."+h}}if(l.sequenceType!=null&&l.hasOwnProperty("sequenceType")){if(c.value===1)return"value: multiple values";c.value=1;{var h=a.onnx.TypeProto.Sequence.verify(l.sequenceType);if(h)return"sequenceType."+h}}if(l.mapType!=null&&l.hasOwnProperty("mapType")){if(c.value===1)return"value: multiple values";c.value=1;{var h=a.onnx.TypeProto.Map.verify(l.mapType);if(h)return"mapType."+h}}if(l.optionalType!=null&&l.hasOwnProperty("optionalType")){if(c.value===1)return"value: multiple values";c.value=1;{var h=a.onnx.TypeProto.Optional.verify(l.optionalType);if(h)return"optionalType."+h}}if(l.sparseTensorType!=null&&l.hasOwnProperty("sparseTensorType")){if(c.value===1)return"value: multiple values";c.value=1;{var h=a.onnx.TypeProto.SparseTensor.verify(l.sparseTensorType);if(h)return"sparseTensorType."+h}}return l.denotation!=null&&l.hasOwnProperty("denotation")&&!i.isString(l.denotation)?"denotation: string expected":null},d.fromObject=function(l){if(l instanceof a.onnx.TypeProto)return l;var c=new a.onnx.TypeProto;if(l.tensorType!=null){if(typeof l.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");c.tensorType=a.onnx.TypeProto.Tensor.fromObject(l.tensorType)}if(l.sequenceType!=null){if(typeof l.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");c.sequenceType=a.onnx.TypeProto.Sequence.fromObject(l.sequenceType)}if(l.mapType!=null){if(typeof l.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");c.mapType=a.onnx.TypeProto.Map.fromObject(l.mapType)}if(l.optionalType!=null){if(typeof l.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");c.optionalType=a.onnx.TypeProto.Optional.fromObject(l.optionalType)}if(l.sparseTensorType!=null){if(typeof l.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");c.sparseTensorType=a.onnx.TypeProto.SparseTensor.fromObject(l.sparseTensorType)}return l.denotation!=null&&(c.denotation=String(l.denotation)),c},d.toObject=function(l,c){c||(c={});var h={};return c.defaults&&(h.denotation=""),l.tensorType!=null&&l.hasOwnProperty("tensorType")&&(h.tensorType=a.onnx.TypeProto.Tensor.toObject(l.tensorType,c),c.oneofs&&(h.value="tensorType")),l.sequenceType!=null&&l.hasOwnProperty("sequenceType")&&(h.sequenceType=a.onnx.TypeProto.Sequence.toObject(l.sequenceType,c),c.oneofs&&(h.value="sequenceType")),l.mapType!=null&&l.hasOwnProperty("mapType")&&(h.mapType=a.onnx.TypeProto.Map.toObject(l.mapType,c),c.oneofs&&(h.value="mapType")),l.denotation!=null&&l.hasOwnProperty("denotation")&&(h.denotation=l.denotation),l.sparseTensorType!=null&&l.hasOwnProperty("sparseTensorType")&&(h.sparseTensorType=a.onnx.TypeProto.SparseTensor.toObject(l.sparseTensorType,c),c.oneofs&&(h.value="sparseTensorType")),l.optionalType!=null&&l.hasOwnProperty("optionalType")&&(h.optionalType=a.onnx.TypeProto.Optional.toObject(l.optionalType,c),c.oneofs&&(h.value="optionalType")),h},d.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},d.getTypeUrl=function(l){return l===void 0&&(l="type.googleapis.com"),l+"/onnx.TypeProto"},d.Tensor=function(){function l(c){if(c)for(var h=Object.keys(c),f=0;f>>3){case 1:{p.elemType=c.int32();break}case 2:{p.shape=a.onnx.TensorShapeProto.decode(c,c.uint32());break}default:c.skipType(g&7);break}}return p},l.decodeDelimited=function(c){return c instanceof r||(c=new r(c)),this.decode(c,c.uint32())},l.verify=function(c){if(typeof c!="object"||c===null)return"object expected";if(c.elemType!=null&&c.hasOwnProperty("elemType")&&!i.isInteger(c.elemType))return"elemType: integer expected";if(c.shape!=null&&c.hasOwnProperty("shape")){var h=a.onnx.TensorShapeProto.verify(c.shape);if(h)return"shape."+h}return null},l.fromObject=function(c){if(c instanceof a.onnx.TypeProto.Tensor)return c;var h=new a.onnx.TypeProto.Tensor;if(c.elemType!=null&&(h.elemType=c.elemType|0),c.shape!=null){if(typeof c.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");h.shape=a.onnx.TensorShapeProto.fromObject(c.shape)}return h},l.toObject=function(c,h){h||(h={});var f={};return h.defaults&&(f.elemType=0,f.shape=null),c.elemType!=null&&c.hasOwnProperty("elemType")&&(f.elemType=c.elemType),c.shape!=null&&c.hasOwnProperty("shape")&&(f.shape=a.onnx.TensorShapeProto.toObject(c.shape,h)),f},l.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},l.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/onnx.TypeProto.Tensor"},l}(),d.Sequence=function(){function l(c){if(c)for(var h=Object.keys(c),f=0;f>>3){case 1:{p.elemType=a.onnx.TypeProto.decode(c,c.uint32());break}default:c.skipType(g&7);break}}return p},l.decodeDelimited=function(c){return c instanceof r||(c=new r(c)),this.decode(c,c.uint32())},l.verify=function(c){if(typeof c!="object"||c===null)return"object expected";if(c.elemType!=null&&c.hasOwnProperty("elemType")){var h=a.onnx.TypeProto.verify(c.elemType);if(h)return"elemType."+h}return null},l.fromObject=function(c){if(c instanceof a.onnx.TypeProto.Sequence)return c;var h=new a.onnx.TypeProto.Sequence;if(c.elemType!=null){if(typeof c.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");h.elemType=a.onnx.TypeProto.fromObject(c.elemType)}return h},l.toObject=function(c,h){h||(h={});var f={};return h.defaults&&(f.elemType=null),c.elemType!=null&&c.hasOwnProperty("elemType")&&(f.elemType=a.onnx.TypeProto.toObject(c.elemType,h)),f},l.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},l.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/onnx.TypeProto.Sequence"},l}(),d.Map=function(){function l(c){if(c)for(var h=Object.keys(c),f=0;f>>3){case 1:{p.keyType=c.int32();break}case 2:{p.valueType=a.onnx.TypeProto.decode(c,c.uint32());break}default:c.skipType(g&7);break}}return p},l.decodeDelimited=function(c){return c instanceof r||(c=new r(c)),this.decode(c,c.uint32())},l.verify=function(c){if(typeof c!="object"||c===null)return"object expected";if(c.keyType!=null&&c.hasOwnProperty("keyType")&&!i.isInteger(c.keyType))return"keyType: integer expected";if(c.valueType!=null&&c.hasOwnProperty("valueType")){var h=a.onnx.TypeProto.verify(c.valueType);if(h)return"valueType."+h}return null},l.fromObject=function(c){if(c instanceof a.onnx.TypeProto.Map)return c;var h=new a.onnx.TypeProto.Map;if(c.keyType!=null&&(h.keyType=c.keyType|0),c.valueType!=null){if(typeof c.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");h.valueType=a.onnx.TypeProto.fromObject(c.valueType)}return h},l.toObject=function(c,h){h||(h={});var f={};return h.defaults&&(f.keyType=0,f.valueType=null),c.keyType!=null&&c.hasOwnProperty("keyType")&&(f.keyType=c.keyType),c.valueType!=null&&c.hasOwnProperty("valueType")&&(f.valueType=a.onnx.TypeProto.toObject(c.valueType,h)),f},l.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},l.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/onnx.TypeProto.Map"},l}(),d.Optional=function(){function l(c){if(c)for(var h=Object.keys(c),f=0;f>>3){case 1:{p.elemType=a.onnx.TypeProto.decode(c,c.uint32());break}default:c.skipType(g&7);break}}return p},l.decodeDelimited=function(c){return c instanceof r||(c=new r(c)),this.decode(c,c.uint32())},l.verify=function(c){if(typeof c!="object"||c===null)return"object expected";if(c.elemType!=null&&c.hasOwnProperty("elemType")){var h=a.onnx.TypeProto.verify(c.elemType);if(h)return"elemType."+h}return null},l.fromObject=function(c){if(c instanceof a.onnx.TypeProto.Optional)return c;var h=new a.onnx.TypeProto.Optional;if(c.elemType!=null){if(typeof c.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");h.elemType=a.onnx.TypeProto.fromObject(c.elemType)}return h},l.toObject=function(c,h){h||(h={});var f={};return h.defaults&&(f.elemType=null),c.elemType!=null&&c.hasOwnProperty("elemType")&&(f.elemType=a.onnx.TypeProto.toObject(c.elemType,h)),f},l.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},l.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/onnx.TypeProto.Optional"},l}(),d.SparseTensor=function(){function l(c){if(c)for(var h=Object.keys(c),f=0;f>>3){case 1:{p.elemType=c.int32();break}case 2:{p.shape=a.onnx.TensorShapeProto.decode(c,c.uint32());break}default:c.skipType(g&7);break}}return p},l.decodeDelimited=function(c){return c instanceof r||(c=new r(c)),this.decode(c,c.uint32())},l.verify=function(c){if(typeof c!="object"||c===null)return"object expected";if(c.elemType!=null&&c.hasOwnProperty("elemType")&&!i.isInteger(c.elemType))return"elemType: integer expected";if(c.shape!=null&&c.hasOwnProperty("shape")){var h=a.onnx.TensorShapeProto.verify(c.shape);if(h)return"shape."+h}return null},l.fromObject=function(c){if(c instanceof a.onnx.TypeProto.SparseTensor)return c;var h=new a.onnx.TypeProto.SparseTensor;if(c.elemType!=null&&(h.elemType=c.elemType|0),c.shape!=null){if(typeof c.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");h.shape=a.onnx.TensorShapeProto.fromObject(c.shape)}return h},l.toObject=function(c,h){h||(h={});var f={};return h.defaults&&(f.elemType=0,f.shape=null),c.elemType!=null&&c.hasOwnProperty("elemType")&&(f.elemType=c.elemType),c.shape!=null&&c.hasOwnProperty("shape")&&(f.shape=a.onnx.TensorShapeProto.toObject(c.shape,h)),f},l.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},l.getTypeUrl=function(c){return c===void 0&&(c="type.googleapis.com"),c+"/onnx.TypeProto.SparseTensor"},l}(),d}(),u.OperatorSetIdProto=function(){function d(o){if(o)for(var l=Object.keys(o),c=0;c>>3){case 1:{h.domain=o.string();break}case 2:{h.version=o.int64();break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){return typeof o!="object"||o===null?"object expected":o.domain!=null&&o.hasOwnProperty("domain")&&!i.isString(o.domain)?"domain: string expected":o.version!=null&&o.hasOwnProperty("version")&&!i.isInteger(o.version)&&!(o.version&&i.isInteger(o.version.low)&&i.isInteger(o.version.high))?"version: integer|Long expected":null},d.fromObject=function(o){if(o instanceof a.onnx.OperatorSetIdProto)return o;var l=new a.onnx.OperatorSetIdProto;return o.domain!=null&&(l.domain=String(o.domain)),o.version!=null&&(i.Long?(l.version=i.Long.fromValue(o.version)).unsigned=!1:typeof o.version=="string"?l.version=parseInt(o.version,10):typeof o.version=="number"?l.version=o.version:typeof o.version=="object"&&(l.version=new i.LongBits(o.version.low>>>0,o.version.high>>>0).toNumber())),l},d.toObject=function(o,l){l||(l={});var c={};if(l.defaults)if(c.domain="",i.Long){var h=new i.Long(0,0,!1);c.version=l.longs===String?h.toString():l.longs===Number?h.toNumber():h}else c.version=l.longs===String?"0":0;return o.domain!=null&&o.hasOwnProperty("domain")&&(c.domain=o.domain),o.version!=null&&o.hasOwnProperty("version")&&(typeof o.version=="number"?c.version=l.longs===String?String(o.version):o.version:c.version=l.longs===String?i.Long.prototype.toString.call(o.version):l.longs===Number?new i.LongBits(o.version.low>>>0,o.version.high>>>0).toNumber():o.version),c},d.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},d.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.OperatorSetIdProto"},d}(),u.OperatorStatus=function(){var d={},o=Object.create(d);return o[d[0]="EXPERIMENTAL"]=0,o[d[1]="STABLE"]=1,o}(),u.FunctionProto=function(){function d(o){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],o)for(var l=Object.keys(o),c=0;c>>3){case 1:{h.name=o.string();break}case 4:{h.input&&h.input.length||(h.input=[]),h.input.push(o.string());break}case 5:{h.output&&h.output.length||(h.output=[]),h.output.push(o.string());break}case 6:{h.attribute&&h.attribute.length||(h.attribute=[]),h.attribute.push(o.string());break}case 11:{h.attributeProto&&h.attributeProto.length||(h.attributeProto=[]),h.attributeProto.push(a.onnx.AttributeProto.decode(o,o.uint32()));break}case 7:{h.node&&h.node.length||(h.node=[]),h.node.push(a.onnx.NodeProto.decode(o,o.uint32()));break}case 8:{h.docString=o.string();break}case 9:{h.opsetImport&&h.opsetImport.length||(h.opsetImport=[]),h.opsetImport.push(a.onnx.OperatorSetIdProto.decode(o,o.uint32()));break}case 10:{h.domain=o.string();break}default:o.skipType(f&7);break}}return h},d.decodeDelimited=function(o){return o instanceof r||(o=new r(o)),this.decode(o,o.uint32())},d.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.name!=null&&o.hasOwnProperty("name")&&!i.isString(o.name))return"name: string expected";if(o.input!=null&&o.hasOwnProperty("input")){if(!Array.isArray(o.input))return"input: array expected";for(var l=0;l{Wn(),ei(),ye=Er($r()),mr(),cr=class{static arraysEqual(t,e){if(t.length!==e.length)return!1;for(let n=0;n1&&l>1)return;u[a-d]=Math.max(o,l)}return u}static index(e,n){let r=new Array(n.length);return Qt.fillIndex(e,n,r),r}static fillIndex(e,n,r){let s=e.length-n.length;for(let i=0;i=0;y--)o[y]=b%a[y],b=Math.floor(b/a[y]);p||(Qt.fillIndex(o,e.dims,l),h=e.get(l)),g||(Qt.fillIndex(o,n.dims,c),f=n.get(c)),d.set(o,r(h,f))}}return d}}static isValidBroadcast(e,n){let r=e.length,s=n.length;if(r>s)return!1;for(let i=1;i<=r;i++)if(e[r-i]!==1&&e[r-i]!==n[s-i])return!1;return!0}static getBroadcastDims(e,n){let r=e.length,s=[];for(let i=0;i1&&u===1&&s.unshift(a)}return s}},Xn=class{static getShapeOfGemmResult(t,e,n,r,s){if(t.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let i,a,u;e?(i=t[1],a=t[0]):(i=t[0],a=t[1]);let d=-1;if(r?(u=n[0],d=1):(u=n[1],d=0),n[d]!==a)throw new Error("dimension mismatch");if(i<=0||u<=0||a<=0)throw new Error("invalid shape specified");if(s&&!Xe.isValidBroadcast(s,[i,u]))throw new Error("gemm: invalid bias shape for broadcast");return[i,u,a]}},Ve=class Sr{static tensorDataTypeFromProto(e){switch(e){case ye.onnx.TensorProto.DataType.INT8:return"int8";case ye.onnx.TensorProto.DataType.UINT8:return"uint8";case ye.onnx.TensorProto.DataType.BOOL:return"bool";case ye.onnx.TensorProto.DataType.INT16:return"int16";case ye.onnx.TensorProto.DataType.UINT16:return"uint16";case ye.onnx.TensorProto.DataType.INT32:return"int32";case ye.onnx.TensorProto.DataType.UINT32:return"uint32";case ye.onnx.TensorProto.DataType.FLOAT:return"float32";case ye.onnx.TensorProto.DataType.DOUBLE:return"float64";case ye.onnx.TensorProto.DataType.STRING:return"string";case ye.onnx.TensorProto.DataType.INT64:return"int32";case ye.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${ye.onnx.TensorProto.DataType[e]}`)}}static tensorDataTypeStringToEnum(e){switch(e){case"int8":return ye.onnx.TensorProto.DataType.INT8;case"uint8":return ye.onnx.TensorProto.DataType.UINT8;case"bool":return ye.onnx.TensorProto.DataType.BOOL;case"int16":return ye.onnx.TensorProto.DataType.INT16;case"uint16":return ye.onnx.TensorProto.DataType.UINT16;case"int32":return ye.onnx.TensorProto.DataType.INT32;case"uint32":return ye.onnx.TensorProto.DataType.UINT32;case"float32":return ye.onnx.TensorProto.DataType.FLOAT;case"float64":return ye.onnx.TensorProto.DataType.DOUBLE;case"string":return ye.onnx.TensorProto.DataType.STRING;case"int64":return ye.onnx.TensorProto.DataType.INT64;case"uint64":return ye.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${e}`)}}static tensorDimsFromProto(e){return e.map(n=>zt.isLong(n)?n.toNumber():n)}static tensorValueTypeFromProto(e){return{tensorType:Sr.tensorDataTypeFromProto(e.elemType),shape:{dims:Sr.tensorDimsFromProto(e.shape.dim.map(n=>n.dimValue))}}}static tensorDimsFromORTFormat(e){let n=[];for(let r=0;re.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return xt.getSizeFromDimensionRange(e,n,e.length)}static sizeToDimension(e,n){if(n<0||n>e.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${e.length} dimensions.`);return xt.getSizeFromDimensionRange(e,0,n)}static getSizeFromDimensionRange(e,n,r){let s=1;for(let i=n;i=0;--s)r[s]=r[s+1]*e[s+1];return r}static transpose(e){return e.slice().reverse()}static indicesToOffset(e,n,r){r===void 0&&(r=e.length);let s=0;for(let i=0;i=n)throw new Error("unsupported axis for this operation.");return e<0?e+n:e}static normalizeAxes(e,n){return e.map(r=>this.normalizeAxis(r,n))}static incrementIndex(e,n,r){if(n.length===0||e.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(r===void 0)r=n.length;else if(r<=0||r>n.length)throw new Error("Incorrect axis to increment on");for(let s=r-1;s>=0&&(e[s]++,!(e[s]=e.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");s[d]=e[d]}else s[d]=n[d];a*=s[d]}}let u=xt.size(e);if(i!==-1){if(u%a!==0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${n}]`);s[i]=u/a}else if(a!==u)throw new Error("reshapedDims and originalDims don't have matching sizes");return s}static sortBasedOnPerm(e,n){return n?n.map(r=>e[r]):e.slice().reverse()}static padShape(e,n){let r=e.length;return e.map((s,i)=>s+n[i]+n[i+r])}static areEqual(e,n){return e.length!==n.length?!1:e.every((r,s)=>r===n[s])}static validateDimsAndCalcSize(e){if(e.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let n=1;for(let r of e){if(!Number.isInteger(r))throw new TypeError(`Invalid shape: ${r} is not an integer`);if(r<0||r>2147483647)throw new TypeError(`Invalid shape: length ${r} is not allowed`);n*=r}return n}static flattenShape(e,n){n<0&&(n+=e.length);let r=e.reduce((i,a)=>i*a,1),s=e.slice(n).reduce((i,a)=>i*a,1);return[r/s,s]}static squeezeShape(e,n){let r=new Array;n=xt.normalizeAxes(n,e.length);for(let s=0;s=0;if(i&&e[s]!==1)throw new Error("squeeze an axis of size different than 1");(n.length===0&&e[s]>1||n.length>0&&!i)&&r.push(e[s])}return r}static unsqueezeShape(e,n){let r=new Array(e.length+n.length);r.fill(0);for(let i=0;i=r.length)throw new Error("'axes' has an out of range axis");if(r[a]!==0)throw new Error("'axes' has a duplicate axis");r[a]=1}let s=0;for(let i=0;i=r.length?r.push(n[u+2]):r[u]=n[u+2];for(let u=0;u=r[u]||a[u+r.length]>=r[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,n,r,s,i,a){if(a){if(i.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let u=0;u{Cu=Er(_s()),ei(),tn(),te=Er($r()),fe(),mi=W.experimental.fbs,Fe=class Hn{constructor(e,n,r,s,i,a=Cu.Guid.create()){this.dims=e,this.type=n,this.dataProvider=r,this.asyncDataProvider=s,this.cache=i,this.dataId=a,this.size=U.validateDimsAndCalcSize(e);let u=this.size,d=r===void 0&&s===void 0&&i===void 0;if(i!==void 0&&i.length!==u)throw new RangeError("Input dims doesn't match data length.");if(n==="string"){if(i!==void 0&&(!Array.isArray(i)||!i.every(o=>typeof o=="string")))throw new TypeError("cache should be a string array");d&&(this.cache=new Array(u))}else{if(i!==void 0){let o=ku(n);if(!(i instanceof o))throw new TypeError(`cache should be type ${o.name}`)}if(d){let o=new ArrayBuffer(u*Vd(n));this.cache=Wd(o,n)}}}get data(){if(this.cache===void 0){let e=this.dataProvider(this.dataId);if(e.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=e}return this.cache}get stringData(){if(this.type!=="string")throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw new TypeError("type cannot be non-number (string)")}get(e){return this.data[U.indicesToOffset(e,this.strides)]}set(e,n){this.data[U.indicesToOffset(e,this.strides)]=n}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=U.computeStrides(this.dims)),this._strides}static fromProto(e){if(!e)throw new Error("cannot construct Value from an empty tensor");let n=Ve.tensorDataTypeFromProto(e.dataType),r=Ve.tensorDimsFromProto(e.dims),s=new Hn(r,n);if(n==="string")e.stringData.forEach((i,a)=>{s.data[a]=sn(i)});else if(e.rawData&&typeof e.rawData.byteLength=="number"&&e.rawData.byteLength>0){let i=s.data,a=new DataView(e.rawData.buffer,e.rawData.byteOffset,e.rawData.byteLength),u=Fu(e.dataType),d=e.rawData.byteLength/u;if(e.rawData.byteLength%u!==0)throw new Error("invalid buffer length");if(i.length!==d)throw new Error("buffer length mismatch");for(let o=0;o0){let i=s.data,a=new DataView(e.rawDataArray().buffer,e.rawDataArray().byteOffset,e.rawDataLength()),u=Fu(e.dataType()),d=e.rawDataLength()/u;if(e.rawDataLength()%u!==0)throw new Error("invalid buffer length");if(i.length!==d)throw new Error("buffer length mismatch");for(let o=0;o{Hd={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},qd={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"}}),ae=L(()=>{});async function gi(t,e=r=>0,n){return new Promise((r,s)=>{let i=0,a=()=>{if(t()){r();return}i++;let u=e(i);if(n!=null&&i>=n){s();return}setTimeout(a,u)};a()})}function Kn(t){return Cr(typeof t<"u"&&t.length!==0,()=>"empty string found for sampler name"),"get"+t.charAt(0).toUpperCase()+t.slice(1)}function Mu(t){return Cr(typeof t<"u"&&t.length!==0,()=>"empty string found for sampler name"),"get"+t.charAt(0).toUpperCase()+t.slice(1)+"AtOutCoords"}function kr(t,e){let n=JSON.parse(JSON.stringify(t));return n=e,n}function Br(t,e){return e.map(n=>t[n]).join(", ")}function Ke(t){if(t<=1)return"int";if(t===2)return"ivec2";if(t===3)return"ivec3";if(t===4)return"ivec4";if(t===5)return"ivec5";if(t===6)return"ivec6";throw Error(`GPU for rank ${t} is not yet supported`)}function St(t=6){return["x","y","z","w","u","v"].slice(0,t)}var Ft=L(()=>{fe()});function jd(t,e){return St(e).map(n=>`${t}.${n}`)}function Nr(t,e){return e===1?[t]:jd(t,e)}function $t(){return` + float getChannel(vec4 frag, int dim) { + int modCoord = imod(dim, 2); + return modCoord == 0 ? frag.r : frag.g; + } + + float getChannel(vec4 frag, vec2 innerDims) { + vec2 modCoord = mod(innerDims, 2.); + return modCoord.x == 0. ? + (modCoord.y == 0. ? frag.r : frag.g) : + (modCoord.y == 0. ? frag.b : frag.a); + } + `}var br=L(()=>{Ft()});function Xd(t,e,n){if(t===0)return"false";if(t===1)return`rc > ${e[0]}`;let r="";for(let s=t-2;s= ${e[s-t+2]}`,s= ${t[0]} ? 0. : getA(rc + 1), + 0, 0`;let r="r, c",s="r, cp1",i="rp1, c",a="rp1, cp1",u="";if(n>2)for(let d=0;d= ${r}; + bool cEdge = cp1 >= ${n}; + `}var Gu,Yd,Uu,zu=L(()=>{xe(),ae(),Ft(),br(),Gu={name:"pack",inputNames:["A"],inputTypes:[1]},Yd=(t,e)=>{let n=q(t.session.backend.glContext.version),r=e.dims,s=r.length,i=e.dims.length,a=Ke(i),u=Nr("rc",i),d=Jd(i,u,r[r.length-2],r[r.length-1]),o;s===0?o=[1,1]:s===1?o=[r[0],1]:o=[r[i-1],r[i-2]];let l=Xd(i,o,u),c=Kd(r,u),h=` + void main() { + ${a} rc = getOutputCoords(); + + if(${l}) { + ${n.output} = vec4(0); + } else { + ${d} + + ${n.output} = vec4(${c}); + } + } + `;return{...Gu,hasMain:!0,output:{dims:e.dims,type:e.type,textureType:2},shaderSource:h}},Uu=(t,e)=>({...Gu,get:()=>Yd(t,e)})});function yi(t){if(t.length===0)return[1,1,1];let e=1;for(let n=0;n1?t[t.length-2]:1,t[t.length-1]]}function Wu(t,e){let n=!1;return t.length===0||e.length===0?n=!0:t.length<2||e.length<2?n=t[t.length-1]===e[e.length-1]:n=t[t.length-1]===e[e.length-1]&&t[t.length-2]===e[e.length-2],n}function eh(t){let e=U.computeStrides(t),n=["b","r","c"],r="index";return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${e.map((s,i)=>{let a=`int ${n[i]} = ${r} / ${s}`,u=i===e.length-1?`int ${n[i+1]} = ${r} - ${n[i]} * ${s}`:`index -= ${n[i]} * ${s}`;return`${a}; ${u};`}).join("")} + return ivec3(b, r, c); + } + `}function th(t){let e=U.computeStrides(t);return` + int getFlattenedIndex(ivec3 coords) { + // reverse y, z order + return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y; + } +`}var Zd,Qd,Vu,Hu=L(()=>{fe(),xe(),ae(),br(),Zd=t=>({name:"Reshape (packed)",inputTypes:[2],inputNames:["A"],cacheHint:`${t}`}),Qd=(t,e,n,r)=>{let s=e.dims,i=r,a="";for(let o=0;o<4;o++){let l="";switch(o){case 0:l="outputCoords = rc;";break;case 1:l="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:l="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:l="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}a+=` + ${l} + ${o>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} + int flattenedIndex = getFlattenedIndex(outputCoords); + + ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); + vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); + + result[${o}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); + + ${o>0?"}":""} + `}let u=q(t.session.backend.glContext.version),d=` + ${eh(s)} + ${th(i)} + ${$t()} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.0); + + ivec3 outputCoords; + int rows = ${i[2]}; + int cols = ${i[1]}; + + ${a} + ${u.output} = result; + } + `;return{...n,output:{dims:i,type:e.type,textureType:2},shaderSource:d,hasMain:!0}},Vu=(t,e,n)=>{let r=Zd(n);return{...r,get:()=>Qd(t,e,r,n)}}}),Ti,qu=L(()=>{xe(),ae(),Ti=(t,e)=>{let n=e.shape,r=q(t.session.backend.glContext.version),s=` + const float FLOAT_MAX = 1.70141184e38; + const float FLOAT_MIN = 1.17549435e-38; + + bool isNaN(float val) { + return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; + } + + highp vec4 encodeAsUint8(highp float v) { + if (isNaN(v)) { + return vec4(255, 255, 255, 255); + } + + highp float av = abs(v); + + if(av < FLOAT_MIN) { + return vec4(0.0, 0.0, 0.0, 0.0); + } else if(v > FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; + } else if(v < -FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; + } + + highp vec4 c = vec4(0,0,0,0); + + highp float e = floor(log2(av)); + highp float m = exp2(fract(log2(av))) - 1.0; + + c[2] = floor(128.0 * m); + m -= c[2] / 128.0; + c[1] = floor(32768.0 * m); + m -= c[1] / 32768.0; + c[0] = floor(8388608.0 * m); + + highp float ebias = e + 127.0; + c[3] = floor(ebias / 2.0); + ebias -= c[3] * 2.0; + c[2] += floor(ebias) * 128.0; + + c[3] += 128.0 * step(0.0, -v); + + return c / 255.0; + } + + void main() { + float value = ${r.texture2D}(X,TexCoords).r; + ${r.output} = encodeAsUint8(value); + }`,i={name:"Uint8Encode",inputTypes:[0],inputNames:["X"],output:{dims:n,type:e.tensor.type,textureType:3},shaderSource:s,hasMain:!0};return t.executeProgram(i,[e.tensor])}});function nh(t,e){if(t===1)return"rc";let n="";for(let r=0;r{xe(),ae(),Ft(),br(),ju={name:"unpack",inputNames:["A"],inputTypes:[2]},rh=(t,e)=>{let n=e.dims.length,r=Nr("rc",n),s=r.slice(-2),i=Ke(n),a=$t(),u=e.dims.length===0?"":nh(n,r),d=n<=1?"rc":`vec2(${s.join(",")})`,o=q(t.session.backend.glContext.version),l=` + ${a} + void main() { + ${i} rc = getOutputCoords(); + + // Sample the texture with the coords to get the rgba channel value. + vec4 packedInput = getA(${u}); + + ${o.output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0); + } + `;return{...ju,hasMain:!0,output:{dims:e.dims,type:e.type,textureType:0},shaderSource:l}},Yu=(t,e)=>({...ju,get:()=>rh(t,e)})}),Jn,un,Zn,ln=L(()=>{ut(),Jn=class{constructor(t,e=1){if(e===1)this.internalFormat=t.R32F,this.format=t.RED,this.textureType=t.FLOAT,this.channelSize=e;else if(e===4)this.internalFormat=t.RGBA32F,this.format=t.RGBA,this.textureType=t.FLOAT,this.channelSize=e;else throw new Error(`Invalid number of channels: ${e}`)}encode(t,e){let n,r;return t.constructor!==Float32Array&&(ce.warning("Encoder","data was not of type Float32; creating new Float32Array"),r=new Float32Array(t)),e*this.channelSize>t.length?(ce.warning("Encoder","Source data too small. Allocating larger array"),r=t,n=this.allocate(e*this.channelSize),r.forEach((s,i)=>n[i]=s)):(r=t,n=r),n}allocate(t){return new Float32Array(t*4)}decode(t,e){return this.channelSize===1?t.filter((n,r)=>r%4===0).subarray(0,e):t.subarray(0,e)}},un=class{constructor(t,e=1,n){if(e!==1&&e!==4)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.channelSize=e,this.textureType=n||t.FLOAT}encode(t,e){let n=t;return this.channelSize===1&&(ce.verbose("Encoder","Exploding into a larger array"),n=this.allocate(e),t.forEach((r,s)=>n[s*4]=r)),n}allocate(t){return new Float32Array(t*4)}decode(t,e){return this.channelSize===1?t.filter((n,r)=>r%4===0).subarray(0,e):t.subarray(0,e)}},Zn=class{constructor(t,e=1){if(this.channelSize=4,e===1)this.internalFormat=t.ALPHA,this.format=t.ALPHA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else if(e===4)this.internalFormat=t.RGBA,this.format=t.RGBA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else throw new Error(`Invalid number of channels: ${e}`)}encode(t,e){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}allocate(t){return new Uint8Array(t*this.channelSize)}decode(t,e){if(t instanceof Uint8Array)return t.subarray(0,e);throw new Error(`Invalid array type: ${t.constructor}`)}}}),fn,Ku,xi,Ju=L(()=>{fe(),ae(),fn=(t,e,n)=>{let r=n===0||n===1?1:4,s=n===2,i=n===1||n===2,a=n===4?e.length-1:void 0,u=n===4?e.map((d,o)=>o===e.length-1?d*4:d):void 0;return xi(t,e,r,u,{isPacked:s,reverseWH:i,breakAxis:a})},Ku=(t,e,n)=>{let r=fn(t,e,n);return[r.width,r.height]},xi=(t,e,n=1,r,s)=>{let i=!!(s&&s.isPacked),[a,u]=t.computeTextureWH(i&&r||e,s),d=e.length,o=e.slice(0);if(d===0&&(o=[1]),n===1)r=e;else if(i){if(n!==4)throw new Error("a packed texture must be 4-channel");r=e,d>0&&(o[d-1]=Math.ceil(o[d-1]/2)),d>1&&(o[d-2]=Math.ceil(o[d-2]/2))}else if(!r)throw new Error("Unpacked shape is needed when using channels > 1");return{width:a,height:u,channels:n,isPacked:i,shape:o,strides:U.computeStrides(o),unpackedShape:r,reversedWH:s&&s.reverseWH}}}),ih,Qn,Qu=L(()=>{ut(),mr(),fe(),zu(),Hu(),qu(),Xu(),ln(),Ju(),ae(),ih=(t,e)=>{let n=e.map(s=>`${s.unpackedShape.join(",")};${s.width}x${s.height}`).join("_"),r=t.name;return t.cacheHint&&(r+="["+t.cacheHint+"]"),r+=":"+n,r},Qn=class{constructor(t){this.session=t,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(t,e){return Ku(this.session.layoutStrategy,t,e)}executeProgram(t,e){if(e.lengththis.readTexture(i),async a=>this.readTextureAsync(i),void 0,s),texture:n};return this.setTextureData(i.tensor.dataId,i,t.isPacked),i}getTextureData(t,e=!1){return this.session.isInitializer(t)?this.session.getTextureData(t,e):e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){this.session.isInitializer(t)?this.session.setTextureData(t,e,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(t,e)}isTextureLayoutCached(t,e=!1){return!!this.getTextureData(t.dataId,e)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(t=>this.session.textureManager.releaseTexture(t)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(t=>this.session.textureManager.releaseTexture(t)),this.unpackedTextureDataCache=new Map}readTexture(t){return t.isPacked?this.readTexture(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat(Ti(this,t))}async readTextureAsync(t){return t.isPacked?this.readTextureAsync(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat(Ti(this,t))}pack(t){return this.executeProgram(Uu(this,t.tensor),[t.tensor])}unpack(t){return this.executeProgram(Yu(this,t.tensor),[t.tensor])}}}),vi,ee,Ge=L(()=>{vi=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}},ee=t=>new vi(t)}),el,tl,rl,ah,sh,nl=L(()=>{Ge(),xe(),ae(),el={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[0,0,0,0,0]},tl=(t,e,n)=>(sh(e),[t.run({...el,cacheHint:n.cacheKey,get:()=>ah(t,e,n)},e)]),rl=t=>{let e=t.attributes.getFloat("epsilon",1e-5),n=t.attributes.getFloat("momentum",.9),r=t.attributes.getInt("spatial",1);return ee({epsilon:e,momentum:n,spatial:r})},ah=(t,e,n)=>{let r=q(t.session.backend.glContext.version),s=e[0].dims.length,[i,a]=t.calculateTextureWidthAndHeight(e[1].dims,0),u=` + float process(int[${s}] indices) { + vec2 position = offsetToCoords(indices[1], ${i}, ${a}); + float scale = getColorAsFloat(${r.texture2D}(Scale, position)); + float mean = getColorAsFloat(${r.texture2D}(Mean, position)); + float variance = getColorAsFloat(${r.texture2D}(Variance, position)); + float b = getColorAsFloat(${r.texture2D}(B, position)); + + return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b; + }`;return{...el,output:{dims:e[0].dims,type:e[0].type,textureType:0},shaderSource:u}},sh=t=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs.");let e=t[0],n=t[1],r=t[2],s=t[3],i=t[4];if(e.dims.length<3||n.dims.length!==1||r.dims.length!==1||s.dims.length!==1||i.dims.length!==1)throw new Error("invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1]||s.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1])throw new Error("invalid input shape.");if(e.type!=="float32"&&e.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||r.type!=="float32"&&r.type!=="float64"||s.type!=="float32"&&s.type!=="float64"||i.type!=="float32"&&i.type!=="float64")throw new Error("invalid input tensor types.")}}),eo,pt,R,cn,to$1,Vt=L(()=>{eo=class{constructor(t,e,n,r){this.glContext=t,this.programInfo=e,this.inputTextureLayouts=n,this.outputTextureLayout=r}},pt=class{constructor(t){this.context=t}},R=class{constructor(t,e){this.routineBody=t,this.dependencies=e}},cn=class{constructor(t,e,n){this.name=t,n?this.dependencies=n:this.dependencies=[],e&&(this.routineBody=e)}addDependency(t){t&&this.dependencies.push(t)}},to$1=class{static returnOrderedNodes(t){if(!t||t.length===0)return[];if(t.length===1)return t;let e=new Set,n=new Set,r=new Array;return this.createOrderedNodes(t,e,n,r),r}static createOrderedNodes(t,e,n,r){for(let s=0;s0)for(let i=0;i b); + } + vec4 ${t}(vec4 v1, vec4 v2) { + return vec4( v1.r > v2.r , + v1.g > v2.g, + v1.b > v2.b, + v1.a > v2.a ); + } + `,name:t,type:0}}function mh(){let t="less_";return{body:` + float ${t}(float a, float b) { + return float(a < b); + } + vec4 ${t}(vec4 v1, vec4 v2) { + return vec4( v1.r < v2.r , + v1.g < v2.g, + v1.b < v2.b, + v1.a < v2.a ); + } + `,name:t,type:0}}function bh(){let t="and_";return{body:` + float ${t}(float a, float b) { + return float( bool(a) && bool(b) ); + } + vec4 ${t}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r && b2.r , + b1.g && b2.g, + b1.b && b2.b, + b1.a && b2.a ); + } + `,name:t,type:0}}function gh(){let t="or_";return{body:` + float ${t}(float a, float b) { + return float( bool(a) || bool(b) ); + } + vec4 ${t}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r || b2.r , + b1.g || b2.g, + b1.b || b2.b, + b1.a || b2.a ); + } + `,name:t,type:0}}function yh(){let t="xor_";return{body:` + float ${t}(float a, float b) { + return float( bool(a) ^^ bool(b) ); + } + vec4 ${t}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r ^^ b2.r , + b1.g ^^ b2.g, + b1.b ^^ b2.b, + b1.a ^^ b2.a ); + } + `,name:t,type:0}}function Th(){return vh("pow")}function xh(){let t="prelu_";return{body:` + float ${t}(float a, float b) { + return a < 0.0 ? a * b: a; + } + vec4 ${t}(vec4 v1, vec4 v2) { + return vec4( + v1.r < 0.0 ? v1.r * v2.r: v1.r, + v1.g < 0.0 ? v1.g * v2.g: v1.g, + v1.b < 0.0 ? v1.b * v2.b: v1.b, + v1.a < 0.0 ? v1.a * v2.a: v1.a + ); + } + `,name:t,type:0}}function vh(t){let e=`${t}_`;return{body:` + float ${e}(float a, float b) { + return ${t}(a, b); + } + vec4 ${e}(vec4 v1, vec4 v2) { + return ${t}(v1, v2); + } + `,name:e,type:0}}var dt,wh,ol,il,al,sl,ul,ll,fl,cl,pl,dl,hl,ml,bl=L(()=>{fe(),Vt(),xe(),ae(),dt=(t,e,n,r=e[0].type,s)=>{let i=t.session.pack?2:0;return{name:n.name,inputNames:["A","B"],inputTypes:[i,i],cacheHint:s,get:()=>wh(t,e,n,r)}},wh=(t,e,n,r=e[0].type)=>{let s=t.session.pack?2:0,i=!U.areEqual(e[0].dims,e[1].dims),a=e[0].dims,u=t.session.pack;if(i){let l=Xe.calcShape(e[0].dims,e[1].dims,!1);if(!l)throw new Error("Can't perform binary op on the given tensors");a=l;let c=a.length,h=e[0].dims.length!==0?e[0].dims.length:1,f=e[1].dims.length!==0?e[1].dims.length:1,p=e[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",g=e[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",b=q(t.session.backend.glContext.version),x=u?` + ${n.body} + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + vec4 result = ${n.name}(a, b); + ${b.output} = result; + }`:` + ${n.body} + float process(int indices[${c}]) { + int aindices[${h}]; + int bindices[${f}]; + ${p} + ${g} + return ${n.name}(_A(aindices), _B(bindices)); + }`;return{name:n.name,inputNames:["A","B"],inputTypes:[s,s],output:{dims:a,type:r,textureType:s},shaderSource:x,hasMain:u}}let d=q(t.session.backend.glContext.version),o=` + ${n.body} + void main() { + vec4 v1 = ${d.texture2D}(A, TexCoords); + vec4 v2 = ${d.texture2D}(B, TexCoords); + vec4 result = ${n.name}(v1, v2); + ${d.output} = result; + } + `;return{name:n.name,inputNames:["A","B"],inputTypes:[s,s],output:{dims:e[0].dims,type:r,textureType:s},shaderSource:o,hasMain:!0}},ol=(t,e)=>[t.run(dt(t,e,lh()),e)],il=(t,e)=>[t.run(dt(t,e,bh(),"bool"),e)],al=(t,e)=>[t.run(dt(t,e,fh()),e)],sl=(t,e)=>[t.run(dt(t,e,dh(),"bool"),e)],ul=(t,e)=>[t.run(dt(t,e,hh(),"bool"),e)],ll=(t,e)=>[t.run(dt(t,e,mh(),"bool"),e)],fl=(t,e)=>[t.run(dt(t,e,ch()),e)],cl=(t,e)=>[t.run(dt(t,e,gh(),"bool"),e)],pl=(t,e)=>[t.run(dt(t,e,Th()),e)],dl=(t,e)=>[t.run(dt(t,e,xh()),e)],hl=(t,e)=>[t.run(dt(t,e,ph()),e)],ml=(t,e)=>[t.run(dt(t,e,yh(),"bool"),e)]}),gl,yl,Oh,Tl=L(()=>{fe(),gl=(t,e,n)=>(Oh(e),[t.cast(e[0],n)]),yl=t=>Ve.tensorDataTypeFromProto(t.attributes.getInt("to")),Oh=t=>{if(!t||t.length!==1)throw new Error("Cast requires 1 input.");if(t[0].type==="string")throw new Error("Invalid input type.")}}),Ih,Sh,xl,ro,vl=L(()=>{xe(),ae(),Ft(),br(),Ih=(t,e)=>({name:"Concat (packed)",inputNames:Array.from({length:t},(n,r)=>`X${r}`),inputTypes:Array(t).fill(2),cacheHint:e}),Sh=(t,e,n,r)=>{let s=n[0].dims.slice();if(r>=s.length||r<-1*s.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=s.length+r);let i=s.slice(0);for(let E=1;EE.dims),c=St(a),h=new Array(l.length-1);h[0]=l[0][r];for(let E=1;E= ${h[E-1]}) { + return getChannel( + getX${E}(${ro(c,f,N)}), + vec2(${ro(p,f,N)})); + }`}let x=h.length,y=h[h.length-1];b+=` + return getChannel( + getX${x}(${ro(c,f,y)}), + vec2(${ro(p,f,y)}));`;let T=q(t.session.backend.glContext.version),S=` + ${o} + float getValue(${c.map(E=>"int "+E)}) { + ${b} + } + + void main() { + ${d} coords = getOutputCoords(); + int lastDim = coords.${c[a-1]}; + coords.${c[a-1]} = coords.${c[a-2]}; + coords.${c[a-2]} = lastDim; + + vec4 result = vec4(getValue(${u}), 0., 0., 0.); + + ${u[a-1]} = ${u[a-1]} + 1; + if (${u[a-1]} < ${i[a-1]}) { + result.g = getValue(${u}); + } + + ${u[a-2]} = ${u[a-2]} + 1; + if (${u[a-2]} < ${i[a-2]}) { + result.a = getValue(${u}); + } + + ${u[a-1]} = ${u[a-1]} - 1; + if (${u[a-2]} < ${i[a-2]} && + ${u[a-1]} < ${i[a-1]}) { + result.b = getValue(${u}); + } + ${T.output} = result; + } + `;return{...e,output:{dims:i,type:n[0].type,textureType:2},shaderSource:S,hasMain:!0}},xl=(t,e,n)=>{let r=Ih(e.length,n.cacheKey);return{...r,get:()=>Sh(t,r,e,n.axis)}},ro=(t,e,n)=>{let r=t.indexOf(e);return t.map((s,i)=>i===r?`${s} - ${n}`:s).join()}}),wl,Ah,Ph,Eh,_l,Dh,Lh,Fh,Ol,$h,Il=L(()=>{Ge(),ae(),vl(),wl=(t,e,n)=>($h(e),t.session.pack&&e[0].dims.length>1?[t.run(xl(t,e,n),e)]:[t.run(Eh(t,e,n),e)]),Ah=(t,e)=>({name:"Concat",inputNames:Array.from({length:t},(n,r)=>`X${r}`),inputTypes:Array(t).fill(0),cacheHint:e}),Ph=(t,e,n,r)=>{let s=n[0].dims.slice();if(r>=s.length||r<-1*s.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=s.length+r);let i=s.slice(0);for(let f=1;f{let r=Ah(e.length,n.cacheKey);return{...r,get:()=>Ph(t,r,e,n.axis)}},_l=t=>`int getTextureWhereDataResides(int index) { + ${t.map((e,n)=>`if(index<${e}) {return ${n};} +`).join("")} + }`,Dh=t=>_l(t),Lh=(t,e)=>{let n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`];for(let r=0;r{let e=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;nee({axis:t.attributes.getInt("axis")}),$h=t=>{if(!t||t.length<1)throw new Error("too few inputs");let e=t[0].type,n=t[0].dims.length;if(e==="string")throw new Error("string tensor is not supported yet");for(let r of t){if(r.type!==e)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}});function Ch(){return ht("abs")}function kh(){return ht("acos")}function Bh(){return ht("asin")}function Nh(){return ht("atan")}function Rh(){return ht("ceil")}function Mh(){return ht("cos")}function Gh(t){let e="elu";return{body:` + const float alpha = float(${t}); + + float ${e}_(float a) { + return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; + } + vec4 ${e}_(vec4 v) { + return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); + } + `,name:e,type:0}}function Uh(){return ht("exp")}function zh(){return ht("floor")}function wi(t,e){let n="clip";return{body:` + const float min = float(${t}); + const float max = float(${e}); + + float ${n}_(float a) { + return clamp(a, min, max); + } + vec4 ${n}_(vec4 v) { + return clamp(v, min, max); + } + `,name:n,type:0}}function Vh(){let t="indentity";return{body:` + float ${t}_(float a) { + return a; + } + vec4 ${t}_(vec4 v) { + return v; + } + `,name:t,type:0}}function Wh(t){let e="leakyRelu";return{body:` + const float alpha = float(${t}); + + float ${e}_(float a) { + return a < 0.0 ? a * alpha : a; + } + vec4 ${e}_(vec4 v) { + return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); + } + `,name:e,type:0}}function Hh(){return ht("log")}function qh(){let t="neg";return{body:` + float ${t}_(float a) { + return -a; + } + vec4 ${t}_(vec4 v) { + return -v; + } + `,name:t,type:0}}function jh(){let t="not";return{body:` + float ${t}_(float a) { + return float( ! bool(a) ); + } + bool ${t}_(bool a) { + return !a; + } + vec4 ${t}_(vec4 v) { + return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); + } + bvec4 ${t}_(bvec4 v) { + return bvec4(!v.x, !v.y, !v.z, !v.w); + } + `,name:t,type:0}}function Yh(){return ht("sin")}function _i(){let t="relu";return{body:` + float ${t}_(float a) { + return max( a, 0.0 ); + } + vec4 ${t}_(vec4 v) { + return max( v, 0.0 ); + } + `,name:t,type:0}}function Oi(){let t="sigmoid";return{body:` + float ${t}_(float a) { + return 1.0 / (1.0 + exp(-a)); + } + vec4 ${t}_(vec4 v) { + return 1.0 / (1.0 + exp(-v)); + } + `,name:t,type:0}}function Xh(){return ht("sqrt")}function Kh(){return ht("tan")}function Jh(){let t="tanh";return{body:` + float ${t}_(float a) { + a = clamp(a, -10., 10.); + a = exp(2.*a); + return (a - 1.) / (a + 1.); + } + vec4 ${t}_(vec4 v) { + v = clamp(v, -10., 10.); + v = exp(2.*v); + return (v - 1.) / (v + 1.); + } + `,name:t,type:0}}function ht(t){return{body:` + float ${t}_(float a) { + return ${t}(a); + } + vec4 ${t}_(vec4 v) { + return ${t}(v); + } + `,name:t,type:0}}var Zh,Pe,Sl,Al,Pl,El,Ii,Dl,Ll,Qh,Fl,$l,Cl,kl,Bl,Nl,Si,Rl,Ml,Gl,Ul,zl,Vl,Wl,Hl,ql,jl,Yl,Ai=L(()=>{Ge(),fe(),Vt(),xe(),ae(),Zh=(t,e,n,r)=>{let s=t.session.pack?2:0,i=q(t.session.backend.glContext.version);return{...e,output:{dims:n.dims,type:n.type,textureType:s},shaderSource:` + ${r.body} + void main() { + vec4 v = ${i.texture2D}(A, TexCoords); + v = ${r.name}_(v); + ${i.output} = v; + } + `,hasMain:!0}},Pe=(t,e,n,r)=>{let s=t.session.pack?2:0,i={name:n.name,inputTypes:[s],inputNames:["A"],cacheHint:r};return{...i,get:()=>Zh(t,i,e,n)}},Sl=(t,e)=>[t.run(Pe(t,e[0],Ch()),e)],Al=(t,e)=>[t.run(Pe(t,e[0],kh()),e)],Pl=(t,e)=>[t.run(Pe(t,e[0],Bh()),e)],El=(t,e)=>[t.run(Pe(t,e[0],Nh()),e)],Ii=(t,e,n)=>[t.run(Pe(t,e[0],wi(n.min,n.max),n.cacheKey),e)],Dl=t=>ee({min:t.attributes.getFloat("min",dr),max:t.attributes.getFloat("max",hr)}),Ll=(t,e)=>{let n=Qh(t,e);return Ii(t,[e[0]],n)},Qh=(t,e)=>{if(e.length>=3&&(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)))throw new Error("dynamic clip attributes are not allowed");let n=e.length>=3?e[1].numberData[0]:dr,r=e.length>=3?e[2].numberData[0]:hr;return ee({min:n,max:r})},Fl=(t,e)=>[t.run(Pe(t,e[0],Rh()),e)],$l=(t,e)=>[t.run(Pe(t,e[0],Mh()),e)],Cl=(t,e,n)=>[t.run(Pe(t,e[0],Gh(n.alpha),n.cacheKey),e)],kl=t=>ee({alpha:t.attributes.getFloat("alpha",1)}),Bl=(t,e)=>[t.run(Pe(t,e[0],Uh()),e)],Nl=(t,e)=>[t.run(Pe(t,e[0],zh()),e)],Si=(t,e)=>[t.run(Pe(t,e[0],Vh()),e)],Rl=(t,e,n)=>[t.run(Pe(t,e[0],Wh(n.alpha),n.cacheKey),e)],Ml=t=>ee({alpha:t.attributes.getFloat("alpha",.01)}),Gl=(t,e)=>[t.run(Pe(t,e[0],Hh()),e)],Ul=(t,e)=>[t.run(Pe(t,e[0],qh()),e)],zl=(t,e)=>[t.run(Pe(t,e[0],jh()),e)],Vl=(t,e)=>[t.run(Pe(t,e[0],_i()),e)],Wl=(t,e)=>[t.run(Pe(t,e[0],Oi()),e)],Hl=(t,e)=>[t.run(Pe(t,e[0],Yh()),e)],ql=(t,e)=>[t.run(Pe(t,e[0],Xh()),e)],jl=(t,e)=>[t.run(Pe(t,e[0],Kh()),e)],Yl=(t,e)=>[t.run(Pe(t,e[0],Jh()),e)]});function Ct(t){let e;switch(t.activation){case"Relu":e=_i();break;case"Sigmoid":e=Oi();break;case"Clip":e=wi(t.clipMin,t.clipMax);break;default:return{activationFunction:"",applyActivation:""}}let n=e.name,r=e.body,s=`value = ${n}_(value);`;return{activationFunction:r,applyActivation:s}}var Rr,gr=L(()=>{fe(),Ai(),Rr=t=>{let e=t.getString("activation","");if(e==="Clip"){let[n,r]=t.getFloats("activation_params",[dr,hr]);return{activation:e,clipMax:r,clipMin:n,activationCacheKey:`${e}:${n},${r}`}}return{activation:e,activationCacheKey:e}}}),tm,rm,Xl,Kl=L(()=>{ut(),xe(),ae(),no(),gr(),tm=(t,e)=>({name:"GroupedConv",inputNames:t?["X","W","Bias"]:["X","W"],inputTypes:t?[0,0,0]:[0,0],cacheHint:e}),rm=(t,e,n,r)=>{let s=e.length>2?"value += getBias(output_channel);":"",i=e[0].dims.slice(),a=e[1].dims.slice(),u=a[0]/r.group;ce.verbose("GroupedConv",`autpPad:${r.autoPad}, dilations:${r.dilations}, group:${r.group}, kernelShape:${r.kernelShape}, pads:${r.pads}, strides:${r.strides}`);let d=Mr(i,a,r.dilations,r.pads,r.strides),o=q(t.session.backend.glContext.version),{activationFunction:l,applyActivation:c}=Ct(r),h=` + const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]}); + const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]}); + ${l} + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int output_channel = coords.y; + ivec2 xRCCorner = coords.zw * strides - pads; + int group_id = output_channel / ${u}; + + float value = 0.0; + for (int wInChannel = 0; wInChannel < ${a[1]}; wInChannel++) { + int input_channel = group_id * ${a[1]} + wInChannel; + for (int wHeight = 0; wHeight < ${a[2]}; wHeight++) { + int xHeight = xRCCorner.x + wHeight * ${r.dilations[0]}; + + if (xHeight < 0 || xHeight >= ${i[2]}) { + continue; + } + + for (int wWidth = 0; wWidth < ${a[3]}; wWidth++) { + int xWidth = xRCCorner.y + wWidth * ${r.dilations[1]}; + if (xWidth < 0 || xWidth >= ${i[3]}) { + continue; + } + + float xVal = getX(batch, input_channel, xWidth, xHeight); + float wVal = getW(output_channel, wInChannel, wWidth, wHeight); + value += xVal*wVal; + } + } + } + ${s} + ${c} + ${o.output} = vec4(value, .0, .0, .0); + } +`;return{...n,output:{dims:d,type:e[0].type,textureType:0},shaderSource:h,hasMain:!0}},Xl=(t,e,n)=>{let r=tm(e.length>2,n.cacheKey);return{...r,get:()=>rm(t,e,r,n)}}}),nm,om,Jl,Zl=L(()=>{xe(),ae(),br(),nm=t=>({name:"Im2Col (packed)",inputNames:["A"],inputTypes:[2],cacheHint:t}),om=(t,e,n,r,s,i)=>{let a=n.dims,u=r.dims,d=2,o=3,l=s.length,c=[u[1]*u[2]*u[3],s[2]*s[3]],h=u[2]*u[3],f=$t(),p=q(t.session.backend.glContext.version),g="";for(let x=0;x<=1;x++)for(let y=0;y<=1;y++)g+=` + blockIndex = rc.x + ${y}; + pos = rc.y + ${x}; + + if(blockIndex < ${c[1]} && pos < ${c[0]}) { + offsetY = int(blockIndex / (${s[l-1]})) * ${i.strides[0]} - + ${i.pads[0]}; + d0 = offsetY + ${i.dilations[0]} * (imod(pos, ${h}) / ${u[2]}); + + if(d0 < ${a[d]} && d0 >= 0) { + offsetX = imod(blockIndex, ${s[l-1]}) * ${i.strides[1]} - + ${i.pads[1]}; + d1 = offsetX + ${i.dilations[1]} * imod(imod(pos, ${h}), ${u[2]}); + + if(d1 < ${a[o]} && d1 >= 0) { + + ch = int(float(pos)/ ${h}.); + innerDims = vec2(d0, d1); + result[${x*2+y}] = getChannel( + getA(0, ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + + `;let b=` + ${f} + + void main() { + ivec2 rc = getOutputCoords(); + vec4 result = vec4(0.0); + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + ${g} + ${p.output} = result; + } + `;return{...e,output:{dims:c,type:n.type,textureType:2},shaderSource:b,hasMain:!0}},Jl=(t,e,n,r,s)=>{let i=nm(s.cacheKey);return{...i,get:()=>om(t,i,e,n,r,s)}}});function am(t,e,n){let r=e[0].dims,s=e[1].dims,i=Xe.calcShape(r,s,!0);if(!i)throw new Error("Can't use matmul on the given tensors");let a=Ke(i.length),u=St(),{activationFunction:d,applyActivation:o}=Ct(n),l=e.length>2,c=l?"value += getBiasForMatmul();":"",h=l?`${Ei(a,u,e[2].dims,i,!1)}`:"",f=i.length,p=r.length,g=s.length,b=r[r.length-1],x=` + ${d} + ${h} + float process(int indices[${f}]) { + int a[${p}]; + int b[${g}]; + bcastMatmulIndices_A(indices, a); + bcastMatmulIndices_B(indices, b); + + float value; + for (int k=0; k<${b}; ++k) { + a[${p-1}] = k; + b[${g-2}] = k; + value += _A(a) * _B(b); + } + ${c} + ${o} + return value; + }`;return{...t,output:{dims:i,type:e[0].type,textureType:0},shaderSource:x}}function Pi(t,e){let n=im(t.length>2,e.activationCacheKey);return{...n,get:()=>am(n,t,e)}}function Ei(t,e,n,r,s){let i="",a=n.length,u=r.length,d=u-a;u<2&&a>0?i="coords":i=n.map((h,f)=>`coords.${e[f+d]}`).join(", ");let o=Xe.getBroadcastDims(n,r).map(h=>`coords.${e[h+d]} = 0;`).join(` +`),l=U.size(n)===1,c="vec4(outputValue.xx, outputValue.yy)";return l&&(c="vec4(outputValue.x)"),s?` +vec4 getBiasForMatmul() { + ${t} coords = getOutputCoords(); + ${o} + vec4 outputValue = getBias(${i}); + return ${c}; +}`:` +float getBiasForMatmul() { + ${t} coords = getOutputCoords(); + ${o} + return getBias(coords.x); +}`}var Ql,ef,im,sm,oo=L(()=>{fe(),ae(),Ft(),gr(),Di(),Ql=(t,e,n)=>(sm(e),t.session.pack?[t.run(io(t,e,n),e)]:[t.run(Pi(e,n),e)]),ef=t=>Rr(t.attributes),im=(t,e)=>({name:"MatMul",inputNames:t?["A","B","Bias"]:["A","B"],inputTypes:t?[0,0,0]:[0,0],cacheHint:e}),sm=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.");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64")throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")}});function fm(t,e,n,r){let s=[],i=[],a=n[0].dims,u=n[1].dims,d=a.length,o=u.length,l=r.length,c=l-d,h=l-o;s=a.map((y,T)=>`coords.${e[T+c]}`),s[d-1]="i*2",s.join(", "),i=u.map((y,T)=>`coords.${e[T+h]}`),i[o-2]="i*2",i.join(", ");let f=Xe.getBroadcastDims(a,r),p=Xe.getBroadcastDims(u,r),g=f.map(y=>`coords.${e[y+c]} = 0;`).join(` +`),b=p.map(y=>`coords.${e[y+h]} = 0;`).join(` +`),x=`int lastDim = coords.${e[l-1]}; + coords.${e[l-1]} = coords.${e[l-2]}; + coords.${e[l-2]} = lastDim;`;return` +vec4 getAAtOutCoordsMatmul(int i) { + ${t} coords = getOutputCoords(); + ${x} + ${g} + vec4 outputValue = getA(${s}); + return outputValue; +} + +vec4 getBAtOutCoordsMatmul(int i) { + ${t} coords = getOutputCoords(); + ${x} + ${b} + vec4 outputValue = getB(${i}); + return outputValue; +}`}function cm(t,e){let n="";for(let r=0;r{fe(),xe(),ae(),Ft(),gr(),oo(),um=(t,e)=>({name:"MatMul (packed)",inputNames:t?["A","B","Bias"]:["A","B"],inputTypes:t?[2,2,2]:[2,2],cacheHint:e}),lm=(t,e,n,r)=>{let s=n.length>2,i=s?"value += getBiasForMatmul();":"",a=n[0].dims,u=n[1].dims,d=Xe.calcShape(a,u,!0),o=!U.areEqual(n[0].dims,n[1].dims);if(!d)throw new Error("Can't use matmul on the given tensors");let l=a[a.length-1],c=Math.ceil(l/2),h=a.length,f=u.length,p=q(t.session.backend.glContext.version),g=Ke(d.length),b=d.length,x=St(),{activationFunction:y,applyActivation:T}=Ct(r),S=s?`${Ei(g,x,n[2].dims,d,!0)}`:"",E=o?`${fm(g,x,n,d)}`:"",N=o?"getAAtOutCoordsMatmul(i)":`getA(${cm(x,h)})`,B=o?"getBAtOutCoordsMatmul(i)":`getB(${pm(x,f)})`,F=o?"":`${g} rc = + getOutputCoords(); int lastDim = rc.${x[b-1]}; rc.${x[b-1]} = + rc.${x[b-2]}; rc.${x[b-2]} = lastDim; + `,k=` + ${E} + ${S} + ${y} + void main() { + ${F} + + vec4 value = vec4(0); + for (int i = 0; i < ${c}; i++) { + vec4 a = ${N}; + vec4 b = ${B}; + + value += (a.rrbb * b.rgrg); + value += (a.ggaa * b.baba); + } + ${i} + ${T} + ${p.output} = value; + }`;return{...e,output:{dims:d,type:n[0].type,textureType:2},shaderSource:k,hasMain:!0}},io=(t,e,n)=>{let r=um(e.length>2,n.activationCacheKey);return{...r,get:()=>lm(t,r,e,n)}}}),tf,rf=L(()=>{no(),Zl(),Di(),tf=(t,e,n)=>{let r=e[0].dims,s=e[1].dims,i=Mr(r,s,n.dilations,n.pads,n.strides),a=t.run(Jl(t,e[0],e[1],i,n),[e[0]]),u=t.reshapePacked(e[1],[s[0],s[1]*s[2]*s[3]]),d=e.length===3?[u,a,e[2]]:[u,a],o=t.run(io(t,d,n),d);return t.reshapePacked(o,i)}}),dm,hm,nf,Li,Fi=L(()=>{ae(),dm=t=>({name:"Im2Col",inputNames:["X"],inputTypes:[0],cacheHint:t}),hm=(t,e,n,r,s,i)=>{let a=n.dims,u=r.dims,d=s.length,o=Li(a,u,s,4),l=` + const int XC = ${a[1]}; + const int XH = ${a[2]}; + const int XW = ${a[3]}; + const int KH = ${i.kernelShape[0]}; + const int KW = ${i.kernelShape[1]}; + const int dilationH = ${i.dilations[0]}; + const int dilationW = ${i.dilations[1]}; + const int strideH = ${i.strides[0]}; + const int strideW = ${i.strides[1]}; + const int padH = ${i.pads[0]}; + const int padW = ${i.pads[1]}; + const int KHKW = KH*KW; + const int XCKHKW = XC * KHKW; + const int outputChannels = 4; + vec4 process(int indices[${d}]) { + int b = indices[0]; // batch size + int oh = indices[1] * strideH - padH; //output height + int ow = indices[2] * strideW - padW; //output width + int p = indices[3] * outputChannels; //patch + vec4 value = vec4(0.0); + for(int i=0; i < outputChannels; ++i) { + if(p < XCKHKW) { + int patchC = p / KHKW; + int patchH = (p - patchC*KHKW) / KW; + int patchW = (p - patchC*KHKW) - patchH * KW; + int xh2 = oh + patchH * dilationH; + int xw2 = ow + patchW * dilationW; + int x[${a.length}]; + x[0] = b; + x[1] = patchC; + x[2] = xh2; + x[3] = xw2; + if(xh2 >= 0 && + xh2 < XH && + xw2 >= 0 && + xw2 < XW) { + value[i] = _X(x); + } + } + ++p; + } + return value; + } + `;return{...e,output:{dims:o,type:n.type,textureType:4},shaderSource:l}},nf=(t,e,n,r,s)=>{let i=dm(s.cacheKey);return{...i,get:()=>hm(t,i,e,n,r,s)}},Li=(t,e,n,r=4)=>[n[0],n[2],n[3],Math.ceil(t[1]*e[2]*e[3]/r)]}),mm,bm,of,af=L(()=>{fe(),xe(),ae(),gr(),Fi(),mm=(t,e)=>({name:"ConvDotProduct",inputNames:t?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:t?[0,4,0]:[0,4],cacheKey:e.activationCacheKey}),bm=(t,e,n,r,s)=>{let i=n[0].dims,a=n[1].dims,u=[a[0],Math.ceil(i[1]*a[2]*a[3]/4)],d=Li(i,a,r),[o,l]=t.calculateTextureWidthAndHeight(u,4),c=U.computeStrides(d),[h,f]=t.calculateTextureWidthAndHeight(d,4),p=r.length,g=n.length<3?"0.0":"_B(b)",b=Math.ceil(i[1]*a[2]*a[3]/4),{activationFunction:x,applyActivation:y}=Ct(s),T=q(t.session.backend.glContext.version),S=` +${x} +float process(int indices[${p}]) { + int b[1]; + b[0] = indices[1]; + int im2col[4]; + im2col[0] = indices[0]; + im2col[1] = indices[2]; + im2col[2] = indices[3]; + int im2colOffset = im2col[0] * ${c[0]} + im2col[1] * ${c[1]} + im2col[2] * ${c[2]}; + int kernelOffset = indices[1] * ${u[1]}; + float value = ${g}; + for (int i = 0; i < ${b}; ++i) { + vec2 im2colCoords = offsetToCoords(im2colOffset, ${h}, ${f}); + vec2 kernelCoords = offsetToCoords(kernelOffset, ${o}, ${l}); + value += dot(${T.texture2D}(Im2Col, im2colCoords), ${T.texture2D}(K, kernelCoords)); + ++im2colOffset; + ++kernelOffset; + } + ${y} + return value; +}`;return{...e,output:{dims:r,type:n[0].type,textureType:0},shaderSource:S}},of=(t,e,n,r)=>{let s=mm(e.length>2,r);return{...s,get:()=>bm(t,s,e,n,r)}}}),Mr,$i,gm,ym,Tm,xm,Ci,vm,no=L(()=>{Ge(),fe(),Kl(),rf(),af(),gr(),Fi(),oo(),Mr=(t,e,n,r,s)=>{let i=t[0],a=t.slice(2),u=a.length,d=e[0],o=e.slice(2).map((c,h)=>c+(c-1)*(n[h]-1)),l=a.map((c,h)=>c+r[h]+r[h+u]).map((c,h)=>Math.floor((c-o[h]+s[h])/s[h]));return[i,d].concat(...l)},$i=(t,e,n)=>(vm(e,n),gm(t,e,n)),gm=(t,e,n)=>{let r=xm(n,e),s=t.session.pack,i=r.kernelShape[0]===1&&r.kernelShape[1]===1;return r.group>1?[t.run(Xl(t,e,r),e)]:i&&s?[ym(t,e,r)]:s&&e[0].dims.length===4&&e[0].dims[0]===1&&!i?[tf(t,e,r)]:[Tm(t,e,r)]},ym=(t,e,n)=>{let r=e[0].dims,s=e[1].dims,i=Mr(r,s,n.dilations,n.pads,n.strides),a=t.reshapeUnpacked(e[0],[r[1],r[2]*r[3]]),u=t.reshapeUnpacked(e[1],[s[0],s[1]]),d=e.length>2?[u,a,e[2]]:[u,a],o=t.run(Pi(d,n),d);return t.reshapeUnpacked(o,i)},Tm=(t,e,n)=>{let r=e[0].dims,s=e[1].dims,i=Mr(r,s,n.dilations,n.pads,n.strides),a=t.run(nf(t,e[0],e[1],i,n),[e[0]]),u=e.length===3?[a,e[1],e[2]]:[a,e[1]];return t.run(of(t,e,i,n),u)},xm=(t,e)=>{let n=t.kernelShape.slice();if(t.kernelShape.length===0)for(let i=2;i{let e=t.attributes,n=Rr(e),r=e.getString("auto_pad","NOTSET"),s=e.getInts("dilations",[1,1]),i=e.getInt("group",1),a=e.getInts("kernel_shape",[]),u=e.getInts("pads",[0,0,0,0]),d=e.getInts("strides",[1,1]);return ee({autoPad:r,dilations:s,group:i,kernelShape:a,pads:u,strides:d,...n})},vm=(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[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let n=t[0].dims[1],r=t[1].dims[1]*e.group;if(n!==r)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(t.length===3&&(t[2].dims.length!==1||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");let s=t[0].dims.length-2;if(e.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(e.strides.length!==s)throw new Error(`strides should be ${s}D`);if(e.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(t[0].type!=="float32"||t[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(t.length===3&&t[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}}),wm,_m,Om,sf,Im,Sm,Am,Pm,Em,Dm,uf,Lm,lf=L(()=>{Ge(),xe(),ae(),gr(),wm=(t,e,n,r,s,i)=>(t-1)*e+n+(r-1)*s+1-i,_m=(t,e,n,r,s)=>{let i=Math.floor(t/2);e==="SAME_UPPER"?(n[r]=i,n[s]=t-i):e==="SAME_LOWER"&&(n[r]=t-i,n[s]=i)},Om=(t,e,n,r,s,i,a,u)=>{let d=t.length-2,o=u.length===0;for(let l=0;l(Lm(e,n),Im(t,e,n)),Im=(t,e,n)=>{let r=Dm(n,e);return[Em(t,e,r)]},Sm=(t,e)=>({name:"ConvTranspose",inputNames:t?["X","W","B"]:["X","W"],inputTypes:t?[0,0,0]:[0,0],cacheHint:e}),Am=(t,e,n,r)=>{let s=e.length>2?"getB(output_channel)":"0.0",i=e[0].dims,a=e[1].dims,u=a[1],d=a[0]/r.group,o=[e[0].dims[0],e[1].dims[1]*r.group,...r.outputShape],l=q(t.session.backend.glContext.version),{activationFunction:c,applyActivation:h}=Ct(r),f=` + const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]}); + const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]}); + ${c} + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int output_channel = coords.y; + + ivec2 loc = coords.zw + pads; + + int group_id = output_channel / ${u}; + int wOutChannel = output_channel - group_id * ${u}; + + float value = ${s}; + for (int inChannelOffset = 0; inChannelOffset < ${d}; inChannelOffset++) { + int input_channel = group_id * ${d} + inChannelOffset; + for (int wWOff = 0; wWOff < ${a[2]}; wWOff++) { + for (int wHOff = 0; wHOff < ${a[3]}; wHOff++) { + ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]}); + ivec2 wLoc = loc - wOff; + ivec2 wLocIn = wLoc / strides; + if ( + wLocIn * strides == wLoc && + wLocIn.x >= 0 && wLocIn.x < ${i[2]} && + wLocIn.y >= 0 && wLocIn.y < ${i[3]} + ) { + float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); + float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); + value += xVal * wVal; + } + } + } + } + ${h} + ${l.output} = vec4(value, .0, .0, .0); + } +`;return{...n,output:{dims:o,type:e[0].type,textureType:0},shaderSource:f,hasMain:!0}},Pm=(t,e,n)=>{let r=Sm(e.length>2,n.cacheKey);return{...r,get:()=>Am(t,e,r,n)}},Em=(t,e,n)=>t.run(Pm(t,e,n),e),Dm=(t,e)=>{let n=t.kernelShape.slice();if(t.kernelShape.length===0)for(let u=2;u{let e=t.attributes,n=Rr(e),r=e.getString("auto_pad","NOTSET"),s=e.getInts("dilations",[1,1]),i=e.getInt("group",1),a=e.getInts("kernel_shape",[]),u=e.getInts("output_padding",[0,0]),d=e.getInts("output_shape",[]),o=e.getInts("pads",[0,0,0,0]),l=e.getInts("strides",[1,1]);return ee({autoPad:r,dilations:s,group:i,kernelShape:a,outputPadding:u,outputShape:d,pads:o,strides:l,...n})},Lm=(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[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let n=t[0].dims[1],r=t[1].dims[0];if(n!==r)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=t[1].dims[1]*e.group;if(t.length===3&&(t[2].dims.length!==1||t[2].dims[0]!==s))throw new Error("invalid bias");let i=t[0].dims.length-2;if(e.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(e.strides.length!==i)throw new Error(`strides should be ${i}D`);if(e.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(e.outputPadding.length!==i)throw new Error(`output_padding should be ${i}D`);if(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");if(t[0].type!=="float32"||t[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(t.length===3&&t[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}}),ff,yr,cf,Fm,pf,$m,Cm,km,ao=L(()=>{Ge(),fe(),ae(),ff={name:"Transpose",inputNames:["A"],inputTypes:[0]},yr=(t,e,n)=>(km(e),[t.run({...ff,cacheHint:n.cacheKey,get:()=>Fm(t,e[0],n.perm)},e)]),cf=t=>ee({perm:t.attributes.getInts("perm",[])}),Fm=(t,e,n)=>{let r=e.dims;n=pf(r,n);let s=$m(r,n),i=r.length,a=` + ${Cm("perm",n,i)} + float process(int indices[${i}]) { + int a[${i}]; + perm(a, indices); + return _A(a); + }`;return{...ff,output:{dims:s,type:e.type,textureType:0},shaderSource:a}},pf=(t,e)=>(e&&e.length!==t.length&&(e=[...t.keys()].reverse()),e),$m=(t,e)=>(e=pf(t,e),U.sortBasedOnPerm(t,e)),Cm=(t,e,n)=>{let r=[];r.push(`void ${t}(out int a[${n}], int src[${n}]) {`);for(let s=0;s{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("input should be float tensor")}}),df,hf,Bm,mf=L(()=>{ao(),df=(t,e,n)=>{Bm(e);let r=n.blocksize,s=r*r,i=n.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],a=n.mode==="DCR"?[e[0].dims[0],r,r,e[0].dims[1]/s,e[0].dims[2],e[0].dims[3]]:[e[0].dims[0],e[0].dims[1]/s,r,r,e[0].dims[2],e[0].dims[3]],u=t.reshapeUnpacked(e[0],a),d={perm:i,cacheKey:`${i}`},[o]=yr(t,[u],d),l=[e[0].dims[0],e[0].dims[1]/s,e[0].dims[2]*r,e[0].dims[3]*r];return[t.reshapeUnpacked(o,l)]},hf=t=>{let e=t.attributes.getInt("blocksize");if(e<1)throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`);let n=t.attributes.getString("mode","DCR");if(n!=="DCR"&&n!=="CRD")throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:e}},Bm=t=>{if(t.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${t.length}`);if(t[0].type==="string"||t[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}}),bf,gf,Nm,yf=L(()=>{fe(),bf=(t,e,n)=>{Nm(e,n);let r=U.flattenShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],r)]},gf=t=>t.attributes.getInt("axis",1),Nm=(t,e)=>{if(!t||t.length!==1)throw new Error("Flatten requires 1 input.");let n=t[0].dims.length;if(n===0)throw new Error("scalar tensor is not supported.");if(e<-n||e>n)throw new Error("Invalid axis");if(t[0].type==="string")throw new Error("string tensor is not supported.")}}),Jt,pn=L(()=>{Jt=["float32","float64","int32","int16","int8","uint16","uint32","uint8"]}),Tf,xf,Rm,Mm,Gm,Um,vf=L(()=>{Ge(),pn(),fe(),ae(),Tf=(t,e,n)=>(Um(e,n.axis),[t.run(Gm(t,e,n),e)]),xf=t=>ee({axis:t.attributes.getInt("axis",0)}),Rm={name:"Gather",inputNames:["A","B"],inputTypes:[0,0]},Mm=(t,e,n,r)=>{let s=n[0].dims.slice(),i=n[1].dims.slice(),a=new Array(s.length+i.length-1);r=U.normalizeAxis(r,s.length);let u=[];for(let h=0;h{let r={...Rm,cacheHint:n.cacheKey};return{...r,get:()=>Mm(t,r,e,n.axis)}},Um=(t,e)=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.");let n=t[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(e<-n||e>n-1)throw new Error("Invalid axis.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invaid input type.");if(t[1].type!=="int32"&&t[1].type!=="int16")throw new Error("Invaid input type.")}}),ki,wf,_f,Of,zm,Vm,Wm,If=L(()=>{Ge(),fe(),ae(),ki=(t,e,n)=>(Wm(e,n),[t.run(zm(e,n),e)]),wf=(t,e)=>{let n=t.attributes.getInt("transA",0)!==0,r=t.attributes.getInt("transB",0)!==0,s=t.attributes.getFloat("alpha",1),i=t.attributes.getFloat("beta",1);return ee({transA:n,transB:r,alpha:s,beta:i,isOptionalC:e})},_f=t=>wf(t,!1),Of=t=>wf(t,!0),zm=(t,e)=>{let n={name:"Gemm",inputNames:t.length===3?["A","B","C"]:["A","B"],inputTypes:t.length===3?[0,0,0]:[0,0],key:e.cacheKey};return{...n,get:()=>Vm(n,t,e)}},Vm=(t,e,n)=>{let r=e[0].dims.slice(),s=e[1].dims.slice(),[i,a]=Xn.getShapeOfGemmResult(r,n.transA,s,n.transB,e.length===3?e[2].dims:void 0),u=[i,a];if(!u)throw new Error("Can't use gemm on the given tensors");let d=r[r.length-1],o="";n.transA&&(d=r[0]),n.transA&&n.transB?o="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?o="value += _A_T(a) * _B(b);":!n.transA&&n.transB?o="value += _A(a) * _B_T(b);":!n.transA&&!n.transB&&(o="value += _A(a) * _B(b);");let l=u.length,c=e.length===3?`int c[${e[2].dims.length}];`:"",h=e.length===3?"bcastIndices_C(indices, c);":"",f=e.length===3?"value += beta * _C(c);":"",p=` + float process(int indices[${l}]) { + int a[${l}]; + int b[${l}]; + ${c} + + copyVec(indices, a); + copyVec(indices, b); + ${h} + + float value = 0.0; + for (int k=0; k<${d}; ++k) { + a[${l-1}] = k; + b[${l-2}] = k; + ${o} + } + + value = value * alpha; + ${f} + return value; + }`;return{...t,output:{dims:u,type:e[0].type,textureType:0},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:p}},Wm=(t,e)=>{if(!t)throw new Error("Input is missing");if(e.isOptionalC&&(t.length<2||t.length>3))throw new Error("Invaid input shape.");if(!e.isOptionalC&&t.length!==3)throw new Error("Gemm requires 3 inputs");if(t.length===3&&t[2].dims.length!==1&&t[2].dims.length!==2)throw new Error("Invalid input shape of C");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64"||t.length===3&&t[2].type!=="float32"&&t[2].type!=="float64")throw new Error("Invalid input type.");if(t[0].type!==t[1].type||t.length===3&&t[0].type!==t[2].type)throw new Error("Input types are mismatched")}}),Sf,Af,Hm,qm,jm,Ym,Xm,Pf=L(()=>{Ge(),ae(),Sf=(t,e,n)=>(Xm(e),[t.run(jm(t,e,n),e)]),Af=t=>{let e=t.attributes.getFloat("scale"),n=t.attributes.getFloats("bias");return ee({scale:e,bias:n})},Hm={name:"ImageScaler",inputNames:["X"],inputTypes:[0]},qm=(t,e,n,r)=>{let s=n[0].dims.slice(),i=s.length,a=` + ${Ym(r.bias.length)} + float process(int indices[${i}]) { + return _X(indices) * scale + getBias(bias, indices[1]); + }`;return{...e,output:{dims:s,type:n[0].type,textureType:0},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:a}},jm=(t,e,n)=>{let r={...Hm,cacheHint:n.cacheKey};return{...r,get:()=>qm(t,r,e,n)}},Ym=t=>{let e=[`float getBias(float bias[${t}], int channel) {`];for(let n=0;n{if(!t||t.length!==1)throw new Error("ImageScaler requires 1 input.");if(t[0].dims.length!==4)throw new Error("Invalid input shape.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type.")}}),Df,Lf,Ef,Km,Jm,Zm,Qm,eb,tb,Ff=L(()=>{xe(),ae(),Df=(t,e,n)=>{tb(e);let r=t.run(Jm(e[0]),e);return[t.run(eb(t,e[0],n,r.dims),[e[0],r,e[1],e[2]])]},Lf=t=>t.attributes.getFloat("epsilon",1e-5),Ef={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[0]},Km=(t,e)=>{let n=e.dims.slice(),r=n[1],s=n[2]*n[3],i=[n[0],r],a=` + vec4 process(int[2] indices) { + vec4 v = vec4(0.0); + int a[4]; + a[0] = indices[0]; + a[1] = indices[1]; + float temp = 0.0; + for(int a2=0; a2<${n[2]}; a2++) { + a[2] = a2; + for(int a3=0; a3<${n[3]}; a3++) { + a[3] = a3; + float x = _X(a); + temp += x; + } + } + float mean = temp / float(${s}); + temp = 0.0; + for(int a2=0; a2<${n[2]}; a2++) { + a[2] = a2; + for(int a3=0; a3<${n[3]}; a3++) { + a[3] = a3; + float x = _X(a); + temp += (x - mean) * (x - mean); + } + } + v.r = mean; + v.g = temp / float(${s}); + + return v; + }`;return{...t,output:{dims:i,type:e.type,textureType:4},shaderSource:a}},Jm=t=>({...Ef,get:()=>Km(Ef,t)}),Zm={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[0,4,0,0]},Qm=(t,e,n,r,s)=>{let i=q(t.session.backend.glContext.version),[a,u]=t.calculateTextureWidthAndHeight(s,4),[d,o]=[a/4,u],l=` + vec4 get_MeanAndVariance(int[2] mv) { + int offset = indicesToOffset_MeanAndVariance(mv); + vec2 coords = offsetToCoords(offset, ${d}, ${o}); + return ${i.texture2D}(MeanAndVariance, coords); + } + + float process(int[4] indices) { + int mv[2]; + mv[0] = indices[0]; + mv[1] = indices[1]; + vec4 mean_and_variance = get_MeanAndVariance(mv); + float mean = mean_and_variance.r; + float variance = mean_and_variance.g; + + int sb[1]; + sb[0] = indices[1]; + float scale = _Scale(sb); + float b = _B(sb); + + return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; + }`;return{...e,output:{dims:n.dims,type:n.type,textureType:0},variables:[{name:"epsilon",type:"float",data:r}],shaderSource:l}},eb=(t,e,n,r)=>{let s={...Zm,cacheHint:`${n}`};return{...s,get:()=>Qm(t,s,e,n,r)}},tb=t=>{if(!t||t.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");let e=t[0],n=t[1],r=t[2];if(e.dims.length<3||n.dims.length!==1||r.dims.length!==1)throw new Error("Invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1])throw new Error("Input shapes are mismatched.");if(e.type!=="float32"&&e.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||r.type!=="float32"&&r.type!=="float64")throw new Error("Invalid input type.");if(t[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}});function rb(t,e){let n=t[0].dims[1],r=t[0].dims.length,s=-Math.floor((e.size-1)/2),i=Math.ceil((e.size-1)/2),a=`float(${e.alpha}) / float(${e.size})`,u=`float(${e.bias})`,d=`float(${e.beta})`,o=` + float process(int indices[${r}]) { + int c = indices[1]; + float x = _X(indices); + float square_sum = 0.0; + + for (int i = ${s}; i <= ${i}; i++) { + int idx = c + i; + if (c >= 0 && c < ${n}) { + indices[1] = idx; + float j = _X(indices); + square_sum += j * j; + } + } + return x / pow(${u} + ${a} * square_sum, ${d}); + }`;return{...kf,cacheHint:e.cacheKey,output:{dims:t[0].dims,type:t[0].type,textureType:0},shaderSource:o}}function nb(t,e){return{...kf,cacheHint:e.cacheKey,get:()=>rb(t,e)}}var $f,Cf,kf,ob,Bf=L(()=>{Ge(),ae(),$f=(t,e,n)=>(ob(e),[t.run(nb(e,n),e)]),Cf=t=>{let e=t.attributes.getFloat("alpha",1e-4),n=t.attributes.getFloat("beta",.75),r=t.attributes.getFloat("bias",1),s=t.attributes.getInt("size");return ee({alpha:e,beta:n,bias:r,size:s})},kf={name:"LRN",inputNames:["X"],inputTypes:[0]},ob=t=>{if(!t||t.length!==1)throw new Error("LRN requires 1 input.");if(t[0].dims.length!==4)throw new Error('currently only support LRN for input with "NCHW" format');if(t[0].type!=="float32")throw new Error("input should be float type")}}),ib,Bi,Nf,Rf,Mf,ab,sb,ub,lb,fb,cb,pb,db,Gf=L(()=>{Ge(),fe(),xe(),ae(),ib={name:"Pad",inputNames:["A"],inputTypes:[0]},Bi=(t,e,n)=>(ub(e),[t.run({...ib,cacheHint:n.cacheKey,get:()=>sb(t,e[0],n)},e)]),Nf=t=>{let e=t.attributes.getString("mode","constant"),n=t.attributes.getFloat("value",0),r=t.attributes.getInts("pads");return ee({mode:e,value:n,pads:r})},Rf=(t,e,n)=>{lb(e);let r=ab(t,e,n);return Bi(t,[e[0]],r)},Mf=t=>t.attributes.getString("mode","constant"),ab=(t,e,n)=>{if(!t.session.isInitializer(e[1].dataId)||e.length>=3&&!t.session.isInitializer(e[2].dataId))throw new Error("dynamic pad attributes are not allowed");let r=Array.from(e[1].integerData),s=e.length>=3?e[2].floatData[0]:0;return ee({mode:n,pads:r,value:s})},sb=(t,e,n)=>{let r=U.padShape(e.dims.slice(),n.pads),s=r.length,i=` + ${fb(t,e,n)} + float process(int[${s}] indices) { + return padA(indices); + }`;return{name:"Pad",inputNames:["A"],inputTypes:[0],output:{dims:r,type:e.type,textureType:0},shaderSource:i}},ub=t=>{if(!t||t.length!==1)throw new Error("Pad requires 1 input");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type.")},lb=t=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(t[1].type!=="int32")throw new Error("Invalid input type.");if(t.length>=3&&t[2].type==="string")throw new Error("Invalid input type.")},fb=(t,e,n)=>{let r=q(t.session.backend.glContext.version),[s,i]=t.calculateTextureWidthAndHeight(e.dims,0),a=U.computeStrides(e.dims);switch(n.mode){case"constant":return cb(r,e.dims,a,s,i,n.pads,n.value);case"reflect":return pb(r,e.dims,a,s,i,n.pads);case"edge":return db(r,e.dims,a,s,i,n.pads);default:throw new Error("Invalid mode")}},cb=(t,e,n,r,s,i,a)=>{let u=e.length,d="";for(let o=u-1;o>=0;--o)d+=` + k = m[${o}] - ${i[o]}; + if (k < 0) return constant; + if (k >= ${e[o]}) return constant; + offset += k * ${n[o]}; + `;return` + float padA(int m[${u}]) { + const float constant = float(${a}); + int offset = 0; + int k = 0; + ${d} + vec2 coords = offsetToCoords(offset, ${r}, ${s}); + float value = getColorAsFloat(${t.texture2D}(A, coords)); + return value; + } + `},pb=(t,e,n,r,s,i)=>{let a=e.length,u="";for(let d=a-1;d>=0;--d)u+=` + k = m[${d}] - ${i[d]}; + if (k < 0) { k = -k; } + { + const int _2n_1 = ${2*(e[d]-1)}; + k = int( mod( float(k), float(_2n_1) ) ) ; + if(k >= ${e[d]}) { k = _2n_1 - k; } + } + offset += k * ${n[d]}; + `;return` + float padA(int m[${a}]) { + int offset = 0; + int k = 0; + ${u} + vec2 coords = offsetToCoords(offset, ${r}, ${s}); + float value = getColorAsFloat(${t.texture2D}(A, coords)); + return value; + } + `},db=(t,e,n,r,s,i)=>{let a=e.length,u="";for(let d=a-1;d>=0;--d)u+=` + k = m[${d}] - ${i[d]}; + if (k < 0) k = 0; + if (k >= ${e[d]}) k = ${e[d]-1}; + offset += k * ${n[d]}; + `;return` + float padA(int m[${a}]) { + int offset = 0; + int k = 0; + ${u} + vec2 coords = offsetToCoords(offset, ${r}, ${s}); + float value = getColorAsFloat(${t.texture2D}(A, coords)); + return value; + } + `}}),zf,Vf,Wf,Hf,qf,jf,Yf,Xf,Kf,hb,Uf,Jf,uo,Zf,so,mb,Qf=L(()=>{Ge(),fe(),ae(),zf=(t,e,n)=>{uo(e);let r={name:"AveragePool",inputNames:["X"],inputTypes:[0],cacheHint:n.cacheKey};return[t.run({...r,get:()=>Wf(e,r,!1,n)},e)]},Vf=t=>{let e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),r=t.attributes.getInt("count_include_pad",0)!==0,s=t.attributes.getInts("kernel_shape"),i=t.attributes.getInts("strides",[]),a=t.attributes.getInts("pads",[]);if(n!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return ee({autoPad:e,ceilMode:n,countIncludePad:r,kernelShape:s,strides:i,pads:a})},Wf=(t,e,n,r)=>{let[s,i]=Kf(t,r,n),a=U.size(s.kernelShape),u="value += _X(x);",d="";s.countIncludePad?d+=`value /= float(${a});`:d+=`value /= float(${a} - pad);`;let o=` + ${Zf(t[0].dims,s,u,d,"0.0")} + `;return{...e,output:{dims:i,type:t[0].type,textureType:0},shaderSource:o}},Hf=(t,e,n)=>{uo(e);let r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[0],cacheHint:`${n.countIncludePad}`};return[t.run({...r,get:()=>Wf(e,r,!0,n)},e)]},qf=t=>{let e=t.attributes.getInt("count_include_pad",0)!==0;return ee({autoPad:"",ceilMode:0,countIncludePad:e,kernelShape:[],strides:[],pads:[]})},jf=(t,e,n)=>{uo(e);let r={name:"MaxPool",inputNames:["X"],inputTypes:[0],cacheHint:n.cacheKey};return[t.run({...r,get:()=>Xf(e,r,!1,n)},e)]},Yf=t=>{let e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),r=t.attributes.getInts("kernel_shape"),s=t.attributes.getInts("strides",[]),i=t.attributes.getInts("pads",[]),a=t.attributes.getInt("storage_order",0),u=t.attributes.getInts("dilations",[]);if(a!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return ee({autoPad:e,ceilMode:n,countIncludePad:!1,kernelShape:r,strides:s,pads:i,storageOrder:a,dilations:u})},Xf=(t,e,n,r)=>{let[s,i]=Kf(t,r,n),a=` + value = max(_X(x), value); + `,u="",d=` + ${Zf(t[0].dims,s,a,u,"-1e5")} + `;return{...e,output:{dims:i,type:t[0].type,textureType:0},shaderSource:d}},Kf=(t,e,n)=>{let r=t[0].dims.slice(),s=Object.hasOwnProperty.call(e,"dilations"),i=e.kernelShape.slice(),a=e.strides.slice(),u=s?e.dilations.slice():[],d=e.pads.slice();pr.adjustPoolAttributes(n,r,i,a,u,d);let o=pr.computePoolOutputShape(n,r,a,u,i,d,e.autoPad),l=Object.assign({},e);return s?Object.assign(l,{kernelShape:i,strides:a,pads:d,dilations:u,cacheKey:e.cacheKey}):Object.assign(l,{kernelShape:i,strides:a,pads:d,cacheKey:e.cacheKey}),[l,o]},hb={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},Uf={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[0]},Jf=(t,e)=>(uo(e),[t.run({...Uf,get:()=>Xf(e,Uf,!0,hb)},e)]),uo=t=>{if(!t||t.length!==1)throw new Error("Pool ops requires 1 input.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type.")},Zf=(t,e,n,r,s)=>{let i=t.length;if(e.kernelShape.length<=2){let a=e.kernelShape[e.kernelShape.length-1],u=e.strides[e.strides.length-1],d=e.pads[e.pads.length/2-1],o=e.pads[e.pads.length-1],l=t[i-1],c="",h="",f="";if(d+o!==0?c=` + for (int i = 0; i < ${a}; i++) { + x[${i} - 1] = indices[${i} - 1] * ${u} - ${d} + i; + if (x[${i} - 1] < 0 || x[${i} - 1] >= ${l}) { + pad++; + continue; + } + ${n} + }`:c=` + for (int i = 0; i < ${a}; i++) { + x[${i} - 1] = indices[${i} - 1] * ${u} - ${d} + i; + ${n} + }`,e.kernelShape.length===2){let p=e.kernelShape[e.kernelShape.length-2],g=e.strides[e.strides.length-2],b=e.pads[e.pads.length/2-2],x=e.pads[e.pads.length-2],y=t[i-2];b+x!==0?h=` + for (int j = 0; j < ${p}; j++) { + x[${i} - 2] = indices[${i} - 2] * ${g} - ${b} + j; + if (x[${i} - 2] < 0 || x[${i} - 2] >= ${y}) { + pad+= ${a}; + continue; + } + `:h=` + for (int j = 0; j < ${p}; j++) { + x[${i} - 2] = indices[${i} - 2] * ${g} - ${b} + j; + `,f=` + } + `}return` + float process(int indices[${i}]) { + int x[${i}]; + copyVec(indices, x); + + float value = ${s}; + int pad = 0; + ${h} + ${c} + ${f} + ${r} + return value; + } + `}else{let a=U.size(e.kernelShape),u=U.computeStrides(e.kernelShape),d=u.length,o=e.pads.length,l=mb(d),c=so(t,"inputDims"),h=so(e.pads,"pads"),f=so(u,"kernelStrides"),p=so(e.strides,"strides"),g=e.pads.reduce((x,y)=>x+y),b="";return g?b=` + if (x[j] >= inputDims[j] || x[j] < 0) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + ${n} + }`:b=` + } + ${n} + `,` + ${l} + float process(int indices[${i}]) { + int x[${i}]; + copyVec(indices, x); + int offset[${d}]; + int pads[${o}]; + int inputDims[${i}]; + int kernelStrides[${d}]; + int strides[${d}]; + ${h} + ${c} + ${p} + ${f} + + float value = ${s}; + int pad = 0; + bool isPad = false; + for (int i = 0; i < ${a}; i++) { + offsetToIndices(i, kernelStrides, offset); + isPad = false; + for (int j = ${i} - ${d}; j < ${i}; j++) { + x[j] = indices[j] * strides[j - ${i} + ${d}] + + offset[j - ${i} + ${d}] - pads[j - 2]; + ${b} + } + ${r} + + return value; + } + `}},so=(t,e)=>{let n="";for(let r=0;r` + void offsetToIndices(int offset, int[${t}] strides, out int[${t}] indices) { + if (${t} == 0) { + return; + } + for (int i = 0; i < ${t} - 1; ++i) { + indices[i] = offset / strides[i]; + offset -= indices[i] * strides[i]; + } + indices[${t} - 1] = offset; + }`}),Tr,Zt,bb,gb,ec,tc,rc,nc,oc,ic,ac,sc=L(()=>{Ge(),pn(),fe(),ae(),Tr=(t,e,n,r,s)=>{gb(e);let i={name:r,inputNames:["A"],inputTypes:[0]};return[t.run({...i,cacheHint:n.cacheKey,get:()=>bb(t,e,n,r,s,i)},e)]},Zt=t=>{let e=t.attributes.getInts("axes",[]),n=t.attributes.getInt("keepdims",1)===1;return ee({axes:e,keepDims:n})},bb=(t,e,n,r,s,i)=>{let a=[],u=e[0].dims.length||1,d=[],o=U.normalizeAxes(n.axes,e[0].dims.length),l=s(e,o),c=l[1];for(let f=0;f=0||o.length===0?(n.keepDims&&a.push(1),c=` + for(int j${f} = 0; j${f} < ${e[0].dims[f]}; j${f}++) { + inputIdx[${f}] = j${f}; + ${c} + }`):(d.push(`inputIdx[${f}] = outputIdx[${a.length}];`),a.push(e[0].dims[f]));let h=` + float process(int outputIdx[${a.length||1}]) { + float value; // final result + int inputIdx[${u}]; // addressing input data + ${d.join(` +`)} + ${l[0]} // init ops for reduce max/min + ${c} + ${l[2]} // final computation for reduce mean + return value; + }`;return{...i,output:{dims:a,type:e[0].type,textureType:0},shaderSource:h}},gb=t=>{if(!t||t.length!==1)throw new Error("Reduce op requires 1 input.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invalid input type.")},ec=(t,e,n)=>Tr(t,e,n,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),tc=(t,e,n)=>Tr(t,e,n,"ReduceMean",(r,s)=>{let i=1;for(let a=0;a=0||s.length===0)&&(i*=r[0].dims[a]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${i}.;`]}),rc=(t,e,n)=>Tr(t,e,n,"ReduceMax",(r,s)=>{let i=[];for(let a=0;a=0||s.length===0)&&i.push(`inputIdx[${a}] = 0;`);return[`${i.join(` +`)} +value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),nc=(t,e,n)=>Tr(t,e,n,"ReduceMin",(r,s)=>{let i=[];for(let a=0;a=0||s.length===0)&&i.push(`inputIdx[${a}] = 0;`);return[`${i.join(` +`)} +value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),oc=(t,e,n)=>Tr(t,e,n,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),ic=(t,e,n)=>Tr(t,e,n,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),ac=(t,e,n)=>Tr(t,e,n,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])}),uc,lc=L(()=>{fe(),uc=(t,e)=>{let n=U.calculateReshapedDims(e[0].dims,e[1].integerData);return t.session.pack?[t.reshapePacked(e[0],n)]:[t.reshapeUnpacked(e[0],n)]}}),fc,Ni,cc,pc,dn,yb,Ri,lo,Mi=L(()=>{Ge(),xe(),ae(),fc={name:"Upsample",inputNames:["X"],inputTypes:[0]},Ni=(t,e,n)=>(Ri(e,n),[t.run({...fc,cacheHint:n.cacheKey,get:()=>yb(t,e,n)},e)]),cc=t=>dn(t,7),pc=t=>dn(t,9),dn=(t,e)=>{let n=e>=10,r=t.attributes.getString("mode","nearest");if(r!=="nearest"&&r!=="linear"&&(e<11||r!=="cubic"))throw new Error(`unrecognized mode: ${r}`);let s=[];e<9&&(s=t.attributes.getFloats("scales"),lo(s,r,n));let i=t.attributes.getFloat("extrapolation_value",0),a=e>10?t.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(a)===-1)throw new Error(`coordinate_transform_mode '${a}' is not supported`);let u=a==="tf_crop_and_resize",d=u,o=r==="nearest"&&e>=11?t.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(o)===-1)throw new Error(`nearest_mode '${o}' is not supported`);let l=t.attributes.getFloat("cubic_coeff_a",-.75),c=t.attributes.getInt("exclude_outside",0)!==0;if(c&&r!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");let h=e<11?!0:r==="nearest"&&a==="asymmetric"&&o==="floor",f=0,p=0,g=0;return e>10?t.inputs.length>2?(f=1,p=2,g=3):(p=1,g=2):e===9&&(p=1),ee({opset:e,isResize:n,mode:r,scales:s,extrapolationValue:i,coordinateTransformMode:a,useExtrapolation:d,needRoiInput:u,nearestMode:o,cubicCoefficientA:l,excludeOutside:c,useNearest2xOptimization:h,roiInputIdx:f,scalesInputIdx:p,sizesInputIdx:g})},yb=(t,e,n)=>{let r=q(t.session.backend.glContext.version),[s,i]=t.calculateTextureWidthAndHeight(e[0].dims,0),a=e[0].dims.map((g,b)=>Math.floor(g*n.scales[b])),[u,d]=t.calculateTextureWidthAndHeight(a,0),o=a.length,l=new Array(o),c=new Array(o),h=` + int output_pitches[${o}]; + int input_pitches[${o}]; + `;for(let g=o-1;g>=0;g--)l[g]=g===o-1?1:l[g+1]*a[g+1],c[g]=g===o-1?1:c[g+1]*e[0].dims[g+1],h+=` + output_pitches[${g}] = ${l[g]}; + input_pitches[${g}] = ${c[g]}; + `;let f=` + float getInputFloat(int index) { + vec2 coords = offsetToCoords(index, ${s}, ${i}); + float value = getColorAsFloat(${r.texture2D}(X, coords)); + return value; + } + `,p=n.mode==="nearest"?` + ${f} + float process(int indices[${o}]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${u}, ${d}); + + ${h} + + int d, m; + for (int dim = 0; dim < ${o}; ++dim) { + d = output_index / output_pitches[dim]; + m = output_index - d * output_pitches[dim]; + output_index = m; + + if (scales[dim] != 1 && d > 0) { + int d2 = d / scales[dim]; + m = d - d2 * scales[dim]; + d = d2; + } + input_index += input_pitches[dim] * d; + } + + return getInputFloat(input_index); + }`:o===4?` + ${f} + float process(int indices[4]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${u}, ${d}); + + ${h} + + int m; + int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; + index_of_dim0 = output_index / output_pitches[0]; + m = output_index - index_of_dim0 * output_pitches[0]; + index_of_dim1 = m / output_pitches[1]; + m = m - index_of_dim1 * output_pitches[1]; + index_of_dim2 = m / output_pitches[2]; + m = m - index_of_dim2 * output_pitches[2]; + index_of_dim3 = m; + + int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; + index_of_input_dim2 = index_of_dim2 / scales[2]; + y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; + index_of_input_dim3 = index_of_dim3 / scales[3]; + x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; + + input_index = index_of_dim0 * input_pitches[0] + + index_of_dim1 * input_pitches[1] + + index_of_input_dim2 * input_pitches[2] + + index_of_input_dim3; + + float x00 = getInputFloat(input_index); + float x10, x01, x11; + + bool end_of_dim2 = false; + if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) { + // It's the end in dimension 2 + x01 = x00; + end_of_dim2 = true; + } else { + x01 = getInputFloat(input_index + input_pitches[2]); + } + + if (index_of_input_dim3 == (input_pitches[2] - 1)) { + // It's the end in dimension 3 + x10 = x00; + x11 = x01; + } + else { + x10 = getInputFloat(input_index + 1); + x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); + } + + float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); + float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); + return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); + }`:` + ${f} + float process(int indices[2]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${u}, ${d}); + + ${h} + + int m; + int index_of_dim0, index_of_dim1; + index_of_dim0 = output_index / output_pitches[0]; + m = output_index - index_of_dim0 * output_pitches[0]; + index_of_dim1 = m; + + int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; + index_of_input_dim0 = index_of_dim0 / scales[0]; + y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; + index_of_input_dim1 = index_of_dim1 / scales[1]; + x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; + + input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; + + float x00 = getInputFloat(input_index); + float x10, x01, x11; + + bool end_of_dim0 = false; + if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) { + // It's the end in dimension 0 + x01 = x00; + end_of_dim0 = true; + } else { + x01 = getInputFloat(input_index + input_pitches[0]); + } + + if (index_of_input_dim1 == (input_pitches[0] - 1)) { + // It's the end in dimension 1 + x10 = x00; + x11 = x01; + } + else { + x10 = getInputFloat(input_index + 1); + x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); + } + + float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); + float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); + return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); + }`;return{...fc,output:{dims:a,type:e[0].type,textureType:0},shaderSource:p,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map(g=>Math.ceil(g))}]}},Ri=(t,e)=>{if(!t||e.opset<9&&t.length!==1||e.opset>=9&&e.opset<11&&t.length!==2||e.opset>=11&&t.length<2)throw new Error("invalid inputs.");if(e.scales.length>0&&t[0].dims.length!==e.scales.length)throw new Error("Invalid input shape.");if(t[0].type==="string")throw new Error("Invalid input tensor types.")},lo=(t,e,n)=>{if(n){for(let r of t)if(r<=0)throw new Error("Scale value should be greater than 0.")}else for(let r of t)if(r<1)throw new Error("Scale value should be greater than or equal to 1.");if((e==="linear"||e==="cubic")&&t.length!==2&&(t.length!==4||t[0]!==1||t[1]!==1))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}}),Gi,Ui,dc,hc,Tb,xb,vb,wb,mc=L(()=>{xe(),ae(),Ft(),br(),Mi(),Gi={name:"Resize",inputNames:["A"],inputTypes:[2]},Ui=(t,e,n)=>(Ri(e,n),[t.run({...Gi,cacheHint:n.cacheKey,get:()=>Tb(t,e,n)},e)]),dc=t=>dn(t,10),hc=t=>dn(t,11),Tb=(t,e,n)=>{let r=q(t.session.backend.glContext.version),[s,i]=xb(e,n);if(s.every(y=>y===1)&&n.coordinateTransformMode!=="tf_crop_and_resize")return{...Gi,output:{dims:i,type:e[0].type,textureType:2},hasMain:!0,shaderSource:`void main() { + vec4 v = ${r.texture2D}(X, TexCoords); + ${r.output} = v; + }`};let a=i.length;if(a<2)throw new Error(`output dimension should be at least 2, but got ${a}`);let u=i[a-2],d=i[a-1],o=e[0].dims;if(a!==o.length)throw new Error(`output dimension should match input ${o.length}, but got ${a}`);let l=o[a-2],c=o[a-1],h=s[a-2],f=s[a-1],p="";if(n.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":p=` + vec4 getSourceFracIndex(ivec4 coords) { + return vec4(coords) / scaleWHWH; + } + `;break;case"half_pixel":p=` + vec4 getSourceFracIndex(ivec4 coords) { + return (vec4(coords) + 0.5) / scaleWHWH - 0.5; + } + `;break;case"pytorch_half_pixel":p=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 fcoords = vec4(coords); + return vec4( + ${d}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, + ${u}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, + ${d}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, + ${u}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 + ); + } + `;break;case"align_corners":p=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 resized = vec4(${d}.0 - 1.0, ${u}.0 - 1.0, ${d}.0 - 1.0, + ${u}.0 - 1.0); + vec4 original = vec4(${c}.0 - 1.0, ${l}.0 - 1.0, ${c}.0 - 1.0, + ${l}.0 - 1.0); + vec4 new_scale = original / resized; + return vec4(coords) * new_scale; + } + `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}let g=Ke(a),b=$t(),x=` + const vec2 inputWH = vec2(${l}.0, ${c}.0); + const vec4 scaleWHWH = vec4(float(${h}), float(${f}), float(${h}), float(${f})); + ${b} + ${p} + float getAValue(int x10, int r, int c, int d) { + return getChannel(getA(x10, r, c, d), vec2(c, d)); + } + void main() { + ${g} rc = getOutputCoords(); + + int batch = rc[0]; + int depth = rc[1]; + + // retrieve the 4 coordinates that is used in the 4 packed output values. + ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); + + // calculate the source index in fraction + vec4 sourceFrac = getSourceFracIndex(coords); + + // get the lower and upper bound of the 4 values that will be packed into one texel. + ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); + ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); + ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); + ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); + + bool hasNextRow = rc.w < ${u-1}; + bool hasNextCol = rc.z < ${d-1}; + + // pack x00, x01, x10, x11's top-left corner into one vec4 structure + vec4 topLeft = vec4( + getAValue(batch, depth, x00.x, x00.y), + hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); + + // pack x00, x01, x10, x11's top-right corner into one vec4 structure + vec4 topRight = vec4( + getAValue(batch, depth, x00.x, x00.w), + hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); + + // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure + vec4 bottomLeft = vec4( + getAValue(batch, depth, x00.z, x00.y), + hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); + + // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure + vec4 bottomRight = vec4( + getAValue(batch, depth, x00.z, x00.w), + hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); + + // calculate the interpolation fraction on u and v direction + vec4 frac = vec4(sourceFrac) - floor(sourceFrac); + vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); + + vec4 top = mix(topLeft, topRight, clampFrac.ywyw); + vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); + vec4 newValue = mix(top, bottom, clampFrac.xxzz); + + ${r.output} = vec4(newValue); + } + `;return{...Gi,output:{dims:i,type:e[0].type,textureType:2},hasMain:!0,shaderSource:x}},xb=(t,e)=>{let n=t[0].dims,r=e.scales,s;if(r.length===0){let a=t[e.scalesInputIdx];if(a&&a.size!==0){if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");r=vb(a,e.mode,e.isResize)}else{let u=t[e.sizesInputIdx];if(!u||u.size===0)throw new Error("Either scales or sizes MUST be provided as input.");s=Array.from(u.integerData),r=wb(s,n,e.mode,e.isResize)}}else if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");let i=s||n.map((a,u)=>Math.floor(a*r[u]));return[r,i]},vb=(t,e,n)=>{let r=Array.from(t.floatData);return lo(r,e,n),r},wb=(t,e,n,r)=>{let s=e.length,i=new Array(s);for(let a=0,u=s;a{mr(),bc=(t,e)=>(_b(e),[new Fe([e[0].dims.length],"int32",void 0,void 0,new Int32Array(e[0].dims))]),_b=t=>{if(!t||t.length!==1)throw new Error("Shape requires 1 input.")}}),zi,yc,Tc,xc,Ob,vc,Ib,Sb,wc=L(()=>{Ge(),pn(),fe(),ae(),zi={name:"Slice",inputNames:["A"],inputTypes:[0]},yc=(t,e,n)=>(Ob(e),[t.run({...zi,cacheHint:n.cacheKey,get:()=>xc(t,e[0],n)},e)]),Tc=t=>{let e=t.attributes.getInts("starts"),n=t.attributes.getInts("ends"),r=t.attributes.getInts("axes",[]);return ee({starts:e,ends:n,axes:r})},xc=(t,e,n)=>{let r=n.axes.length===0?e.dims.slice(0).map((l,c)=>c):n.axes,s=U.normalizeAxes(r,e.dims.length),i=n.starts.map((l,c)=>l>e.dims[s[c]]-1?e.dims[s[c]]:U.normalizeAxis(l,e.dims[s[c]])),a=n.ends.map((l,c)=>l>e.dims[s[c]]-1?e.dims[s[c]]:U.normalizeAxis(l,e.dims[s[c]])),u=e.dims.slice(),d=[];for(let l=0;l0&&d.push(`outputIdx[${s[l]}] += ${i[l]};`);let o=` + float process(int outputIdx[${u.length}]) { + ${d.join(` + `)} + return _A(outputIdx); + }`;return{...zi,output:{dims:u,type:e.type,textureType:0},shaderSource:o}},Ob=t=>{if(!t||t.length!==1)throw new Error("Slice requires 1 input.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invalid input type.")},vc=(t,e)=>{Sb(e);let n=Ib(t,e);return[t.run({...zi,cacheHint:n.cacheKey,get:()=>xc(t,e[0],n)},[e[0]])]},Ib=(t,e)=>{if(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)||e.length>=4&&!t.session.isInitializer(e[3].dataId)||e.length>=5&&!t.session.isInitializer(e[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(e.length>=5&&e[4].integerData.some(a=>a!==1))throw new Error("currently non-1 steps is not supported for Slice");let n=Array.from(e[1].integerData),r=Array.from(e[2].integerData),s=e.length>=4?Array.from(e[3].integerData):[],i=`${s};${n};${r}`;return{starts:n,ends:r,axes:s,cacheKey:i}},Sb=t=>{if(!t||t.length<3||t.length>5)throw new Error("Invalid input number.");if(t[1].type!=="int32"||t[1].dims.length!==1)throw new Error("Invalid input type.");if(t[2].type!=="int32"||t[2].dims.length!==1)throw new Error("Invalid input type.");if(t.length>=4&&(t[3].type!=="int32"||t[3].dims.length!==1))throw new Error("Invalid input type.");if(t.length>=5&&(t[4].type!=="int32"||t[4].dims.length!==1))throw new Error("Invalid input type.")}}),_c,Oc,Ic,Sc,Ac,Pc,Ec,Dc,Ab,Pb,Eb,Lc,Fc=L(()=>{Ge(),fe(),xe(),ae(),ao(),_c={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[0]},Oc={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[0,0]},Ic={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[0,0,0]},Sc=(t,e,n)=>{Lc(e);let r=e[0].dims.slice(),s=U.normalizeAxis(n.axis,r.length),i=U.sizeToDimension(r,s),a=U.sizeFromDimension(r,s);return Dc(t,e,n,i,a)},Ac=t=>ee({axis:t.attributes.getInt("axis",1)}),Pc=t=>ee({axis:t.attributes.getInt("axis",-1)}),Ec=(t,e,n)=>{Lc(e);let r=e[0].dims.slice(),s=U.normalizeAxis(n.axis,r.length),i=r.length,a=s!==i-1,u=[],d=[],o=[],l;a&&(d=Array.from({length:i}).map((p,g)=>g),d[s]=i-1,d[i-1]=s,d.map(p=>u.push(r[p])),l=ee({perm:d}),o=yr(t,e,l));let c=a?U.sizeToDimension(u,i-1):U.sizeToDimension(r,i-1),h=a?U.sizeFromDimension(u,i-1):U.sizeFromDimension(r,i-1),f=Dc(t,a?o:e,n,c,h);return a?yr(t,f,l):f},Dc=(t,e,n,r,s)=>{let i=Ab(t,e[0],r,s,[r]),a=t.run({..._c,cacheHint:n.cacheKey,get:()=>i},e),u=Pb(t,e[0],r,s,i.output.dims,[r]),d=t.run({...Oc,cacheHint:n.cacheKey,get:()=>u},[e[0],a]),o=Eb(t,e[0],r,s,i.output.dims,u.output.dims);return[t.run({...Ic,cacheHint:n.cacheKey,get:()=>o},[e[0],a,d])]},Ab=(t,e,n,r,s)=>{let[i,a]=t.calculateTextureWidthAndHeight(e.dims,0),u=s.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(s.length!==1)throw new Error("Dimensionality of the output should be 1");if(s[0]!==n)throw new Error("Shape of the output should be equal to logical row count");let d=q(t.session.backend.glContext.version),o=` + float process(int[${u}] indices) { + int logical_row_start_offset = indices[0] * ${r}; + + float max = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset, ${i}, + ${a} ))); + for(int i=1; i<${r}; ++i) + { + float current = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${i}, ${a}))); + if(current > max) + max = current; + } + + return max; + }`;return{..._c,output:{dims:s,type:e.type,textureType:0},shaderSource:o}},Pb=(t,e,n,r,s,i)=>{let[a,u]=t.calculateTextureWidthAndHeight(e.dims,0),d=i.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(i.length!==1)throw new Error("Dimensionality of the output should be 1");if(i[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(s.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(s[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");let o=q(t.session.backend.glContext.version),l=` + float process(int[${d}] indices) { + int logical_row_start_offset = indices[0] * ${r}; + + float norm_factor = 0.0; + float max = _Max(indices); + for(int i=0; i<${r}; ++i) + { + norm_factor += exp(getColorAsFloat(${o.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${a}, ${u}))) - max); + } + + return norm_factor; + }`;return{...Oc,output:{dims:i,type:e.type,textureType:0},shaderSource:l}},Eb=(t,e,n,r,s,i)=>{let[a,u]=t.calculateTextureWidthAndHeight(e.dims,0),d=e.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(s.length!==1||i.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(s[0]!==n||i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");let o=` + float process(int[${d}] indices) { + + // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) + int offset = coordsToOffset(TexCoords, ${a}, ${u}); + + //determine the logical row for this index + int logical_row_index[1]; + logical_row_index[0] = offset / ${r}; + + float norm_factor = _Norm(logical_row_index); + + // avoid possible division by 0 + // if norm_facor is 0, all elements are zero + // if so, return 0 + if(norm_factor == 0.0) + return 0.0; + + return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; + }`;return{...Ic,output:{dims:e.dims,type:e.type,textureType:0},shaderSource:o}},Lc=t=>{if(!t||t.length!==1)throw new Error("Softmax requires 1 input.");if(t[0].type!=="float32"&&t[0].type!=="float64")throw new Error("Invalid input type")}}),$c,Cc,kc,Db,Lb,Fb,Bc=L(()=>{Ge(),fe(),ae(),$c={name:"Split",inputNames:["A"],inputTypes:[0]},Cc=(t,e,n)=>{Fb(e);let r=U.normalizeAxis(n.axis,e[0].dims.length),s=Db(t,e,r,n),i=[];for(let a=0;aLb(t,e[0],n,r,a)},e));return i},kc=t=>{let e=t.attributes.getInt("axis",0),n=t.attributes.getInts("split",[]),r=t.outputs.length;return ee({axis:e,split:n,numOutputs:r})},Db=(t,e,n,r)=>{let[,s]=an.splitShape(e[0].dims,n,r.split,r.numOutputs);return s.length},Lb=(t,e,n,r,s)=>{let[i,a]=an.splitShape(e.dims,r,n.split,n.numOutputs),u=a[s],d=i[s],o=` + float process(int indices[${d.length}]) { + indices[${r}] += ${u}; + return _A(indices); + } + `;return{...$c,cacheHint:`${n.cacheKey}:${s}`,output:{dims:d,type:e.type,textureType:0},shaderSource:o}},Fb=t=>{if(!t||t.length!==1)throw new Error("Split requires one input.");if(t[0].type!=="int8"&&t[0].type!=="uint8"&&t[0].type!=="int16"&&t[0].type!=="uint16"&&t[0].type!=="int32"&&t[0].type!=="uint32"&&t[0].type!=="float32"&&t[0].type!=="float64"&&t[0].type!=="bool")throw new Error("Invalid input type.")}}),Vi,Nc,Rc,$b,Cb,Mc=L(()=>{fe(),Vi=(t,e,n)=>{$b(e);let r=U.squeezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],r)]},Nc=(t,e)=>(Cb(e),Vi(t,[e[0]],Array.from(e[1].integerData))),Rc=t=>t.attributes.getInts("axes"),$b=t=>{if(!t||t.length!==1)throw new Error("Squeeze requires 1 input.");if(t[0].type==="string")throw new Error("invalid input tensor types.")},Cb=t=>{if(!t||t.length!==2)throw new Error("Squeeze requires 2 inputs.");if(t[1].type!=="int32")throw new Error("Invalid input type.")}}),Gc,kb,Bb,Uc=L(()=>{xe(),ae(),Gc=(t,e)=>{Bb(e);let n={name:"Sum",inputNames:e.map((r,s)=>`X${s}`),inputTypes:new Array(e.length).fill(0)};return[t.run({...n,get:()=>kb(t,e,n)},e)]},kb=(t,e,n)=>{let r=q(t.session.backend.glContext.version),s=e[0].dims.slice(),i=` + void main() { + vec4 result = ${e.map((a,u)=>`${r.texture2D}(X${u},TexCoords)`).join(" + ")}; + ${r.output} = result; + } + `;return{...n,output:{dims:s,type:e[0].type,textureType:0},hasMain:!0,shaderSource:i}},Bb=t=>{if(!t||t.length===0)throw new Error("Sum requires inputs.");let e=t[0].dims.length;for(let n=1;n{pn(),ae(),zc=(t,e)=>{Rb(e);let n={name:"Tile",inputNames:["A"],inputTypes:[0]};return[t.run({...n,get:()=>Nb(t,e,n)},e)]},Nb=(t,e,n)=>{let r=e[0].dims.slice(),s=new Array(r.length),i=[];for(let d=0;d{if(!t||t.length!==2)throw new Error("Tile requires 2 input.");if(t[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(t[1].dims[0]!==t[0].dims.length)throw new Error("Invalid input shape.");if(Jt.indexOf(t[0].type)===-1)throw new Error("Invalid input type.");if(t[1].type!=="int32"&&t[1].type!=="int16")throw new Error("Invalid repeat type.")}}),Wi,Wc,Hc,Mb,Gb,qc=L(()=>{fe(),Wi=(t,e,n)=>{Mb(e);let r=U.unsqueezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],r)]},Wc=(t,e)=>(Gb(e),Wi(t,[e[0]],Array.from(e[1].integerData))),Hc=t=>t.attributes.getInts("axes"),Mb=t=>{if(!t||t.length!==1)throw new Error("Unsqueeze requires 1 input.");if(t[0].type==="string")throw new Error("invalid input tensor types.")},Gb=t=>{if(!t||t.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(t[1].type!=="int32")throw new Error("Invalid input type.")}}),jc,Yc=L(()=>{nl(),bl(),Tl(),Il(),no(),lf(),mf(),yf(),vf(),If(),Pf(),Ff(),Bf(),oo(),Gf(),Qf(),sc(),lc(),mc(),gc(),wc(),Fc(),Bc(),Mc(),Uc(),Vc(),ao(),Ai(),qc(),Mi(),jc=[["Abs","","6+",Sl],["Acos","","7+",Al],["Add","","7+",ol],["And","","7+",il],["Asin","","7+",Pl],["Atan","","7+",El],["AveragePool","","7+",zf,Vf],["BatchNormalization","","7+",tl,rl],["Cast","","6+",gl,yl],["Ceil","","6+",Fl],["Clip","","6-10",Ii,Dl],["Clip","","11+",Ll],["Concat","","4+",wl,Ol],["Conv","","1+",$i,Ci],["ConvTranspose","","1+",sf,uf],["Cos","","7+",$l],["Div","","7+",al],["Dropout","","7+",Si],["DepthToSpace","","1+",df,hf],["Equal","","7+",sl],["Elu","","6+",Cl,kl],["Exp","","6+",Bl],["Flatten","","1+",bf,gf],["Floor","","6+",Nl],["FusedConv","com.microsoft","1+",$i,Ci],["Gather","","1+",Tf,xf],["Gemm","","7-10",ki,_f],["Gemm","","11+",ki,Of],["GlobalAveragePool","","1+",Hf,qf],["GlobalMaxPool","","1+",Jf],["Greater","","7+",ul],["Identity","","1+",Si],["ImageScaler","","1+",Sf,Af],["InstanceNormalization","","6+",Df,Lf],["LeakyRelu","","6+",Rl,Ml],["Less","","7+",ll],["LRN","","1+",$f,Cf],["Log","","6+",Gl],["MatMul","","1+",Ql,ef],["MaxPool","","1+",jf,Yf],["Mul","","7+",fl],["Neg","","6+",Ul],["Not","","1+",zl],["Or","","7+",cl],["Pad","","2-10",Bi,Nf],["Pad","","11+",Rf,Mf],["Pow","","7+",pl],["PRelu","","7+",dl],["ReduceLogSum","","1+",ic,Zt],["ReduceMax","","1+",rc,Zt],["ReduceMean","","1+",tc,Zt],["ReduceMin","","1+",nc,Zt],["ReduceProd","","1+",oc,Zt],["ReduceSum","","1-12",ec,Zt],["ReduceSumSquare","","1+",ac,Zt],["Relu","","6+",Vl],["Reshape","","5+",uc],["Resize","","10",Ui,dc],["Resize","","11+",Ui,hc],["Shape","","1+",bc],["Sigmoid","","6+",Wl],["Sin","","7+",Hl],["Slice","","10+",vc],["Slice","","1-9",yc,Tc],["Softmax","","1-12",Sc,Ac],["Softmax","","13+",Ec,Pc],["Split","","2-12",Cc,kc],["Sqrt","","6+",ql],["Squeeze","","1-12",Vi,Rc],["Squeeze","","13+",Nc],["Sub","","7+",hl],["Sum","","6+",Gc],["Tan","","7+",jl],["Tanh","","6+",Yl],["Tile","","6+",zc],["Transpose","","1+",yr,cf],["Upsample","","7-8",Ni,cc],["Upsample","","9",Ni,pc],["Unsqueeze","","1-12",Wi,Hc],["Unsqueeze","","13+",Wc],["Xor","","7+",ml]]});function Kc(t){let e={},n;for(;(n=Xc.exec(t))!==null;){let r=n[3].split(",").map(s=>{let i=s.trim().split(" ");return i&&i.length===2?{type:i[0],name:i[1]}:null}).filter(s=>s!==null);e[n[2]]={params:r,body:n[4]}}for(let r in e){let s=Ub.replace("__FUNC__",r),i=new RegExp(s,"gm");for(;(n=i.exec(t))!==null;){let a=n[1],u=n[2],d=n[3].split(","),o=a?`${a} ${u};`:"",l=e[r].body,c="";e[r].params.forEach((f,p)=>{f&&(c+=`${f.type} ${f.name} = ${d[p]}; +`)}),l=`${c} + ${l}`,l=l.replace("return",`${u} = `);let h=` + ${o} + { + ${l} + } + `;t=t.replace(n[0],h)}}return t=t.replace(Xc,""),t}var Xc,Ub,Jc=L(()=>{Xc=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm,Ub="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"});function Gr(t,e){let n=[],r=[],s=e!=null&&Array.isArray(e)&&e.length===0,i=e==null||s?null:zb(e,t).sort(),a=0;for(let u=0;uu)&&t[u]===1&&(n.push(t[u]),r.push(u)),i[a]<=u&&a++}t[u]!==1&&(n.push(t[u]),r.push(u))}return{newShape:n,keptDims:r}}function zb(t,e){let n=e.length;return t=t==null?e.map((r,s)=>s):[].concat(t),Cr(t.every(r=>r>=-n&&r`All values in axis param must be in range [-${n}, ${n}) but got axis ${t}`),Cr(t.every(Vb),()=>`All values in axis param must be integers but got axis ${t}`),t.map(r=>r<0?n+r:r)}function Vb(t){return t%1===0}function Wb(t){if(t.length===0)return 1;let e=t[0];for(let n=1;n{ut(),fe(),fo=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){let n=this.computeTexture(t,e);return e&&e.isPacked&&(n[0]/=2,n[1]/=2),e&&e.reverseWH?[n[1],n[0]]:n}computeTexture(t,e){let n=e&&e.isPacked;if(t.length===0)return n?[2,2]:[1,1];let r=this.maxTextureSize;if(e&&e.breakAxis!==void 0){let a=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce((d,o)=>d*o),u=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce((d,o)=>d*o);if(a>r||u>r)ce.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`);else return[a,u]}let s=t.slice(0);n&&(r=r*2,s=s.map((a,u)=>u>=s.length-2?s[u]%2===0?s[u]:s[u]+1:s[u]),s.length===1&&(s=[2,s[0]])),s.length!==2&&(s=Gr(s).newShape);let i=Wb(s);return s.length<=1&&i<=r?[1,i]:s.length===2&&s[0]<=r&&s[1]<=r?s:s.length===3&&s[0]*s[1]<=r&&s[2]<=r?[s[0]*s[1],s[2]]:s.length===3&&s[0]<=r&&s[1]*s[2]<=r?[s[0],s[1]*s[2]]:s.length===4&&s[0]*s[1]*s[2]<=r&&s[3]<=r?[s[0]*s[1]*s[2],s[3]]:s.length===4&&s[0]<=r&&s[1]*s[2]*s[3]<=r?[s[0],s[1]*s[2]*s[3]]:n?Zc(i/4).map(a=>a*2):Zc(i)}}}),co,Qc=L(()=>{fe(),Vt(),xe(),Hi(),Ft(),co=class extends pt{constructor(t){super(t)}getFunctions(){return{...this.offsetToCoords(),...this.coordsToOffset(),...this.toVec(),...this.valueFrom(),...this.getCommonUtilFuncs(),...this.getInputsSamplingSnippets(),...this.getOutputSamplingSnippet()}}getCustomTypes(){return{}}offsetToCoords(){let t="offsetToCoords";return{offsetToCoords:new R(` + vec2 ${t}(int offset, int width, int height) { + int t = offset / width; + int s = offset - t*width; + vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); + return coords; + } + `)}}coordsToOffset(){let t="coordsToOffset";return{coordsToOffset:new R(` + int ${t}(vec2 coords, int width, int height) { + float s = coords.s * float(width); + float t = coords.t * float(height); + int offset = int(t) * width + int(s); + return offset; + } + `)}}getOutputSamplingSnippet(){let t=this.context.outputTextureLayout;return t.isPacked?this.getPackedOutputSamplingSnippet(t):this.getUnpackedOutputSamplingSnippet(t)}getPackedOutputSamplingSnippet(t){let e=t.unpackedShape,n=[t.width,t.height],r={},s="getOutputCoords";switch(e.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputPacked1DCoords(e,n);break;case 2:r[s]=this.getOutputPacked2DCoords(e,n);break;case 3:r[s]=this.getOutputPacked3DCoords(e,n);break;default:r[s]=this.getOutputPackedNDCoords(e,n)}let i=` + void setOutput(vec4 val) { + ${q(this.context.glContext.version).output} = val; + } + `,a="floatTextureSetRGBA";return r[a]=new R(i),r}getUnpackedOutputSamplingSnippet(t){let e=t.unpackedShape,n=[t.width,t.height],r={},s="getOutputCoords";switch(e.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputUnpacked1DCoords(e,n);break;case 2:r[s]=this.getOutputUnpacked2DCoords(e,n);break;case 3:r[s]=this.getOutputUnpacked3DCoords(e,n);break;case 4:r[s]=this.getOutputUnpacked4DCoords(e,n);break;case 5:r[s]=this.getOutputUnpacked5DCoords(e,n);break;case 6:r[s]=this.getOutputUnpacked6DCoords(e,n);break;default:throw new Error(`Unsupported output dimensionality: ${e.length}`)}let i=` + void setOutput(float val) { + ${q(this.context.glContext.version).output} = vec4(val, 0, 0, 0); + } + `,a="floatTextureSetR";return r[a]=new R(i),r}getOutputScalarCoords(){return new R(` + int getOutputCoords() { + return 0; + } + `)}getOutputPacked1DCoords(t,e){let n=e,r="";return n[0]===1?(r=` + int getOutputCoords() { + return 2 * int(TexCoords.y * ${n[1]}.0); + } + `,new R(r)):n[1]===1?(r=` + int getOutputCoords() { + return 2 * int(TexCoords.x * ${n[0]}.0); + } + `,new R(r)):(r=` + int getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${n[0]}, ${n[1]})); + return 2 * (resTexRC.y * ${n[0]} + resTexRC.x); + } + `,new R(r))}getOutputPacked2DCoords(t,e){let n="";if(cr.arraysEqual(t,e))return n=` + ivec2 getOutputCoords() { + return 2 * ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]})); + } + `,new R(n);let r=e,s=Math.ceil(t[1]/2);return n=` + ivec2 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${r[0]}, ${r[1]})); + + int index = resTexRC.y * ${r[0]} + resTexRC.x; + + // reverse r and c order for packed texture + int r = imod(index, ${s}) * 2; + int c = 2 * (index / ${s}); + + return ivec2(r, c); + } + `,new R(n)}getOutputPacked3DCoords(t,e){let n=[e[0],e[1]],r=Math.ceil(t[2]/2),s=r*Math.ceil(t[1]/2),i=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${n[0]}, ${n[1]})); + int index = resTexRC.y * ${n[0]} + resTexRC.x; + + int b = index / ${s}; + index -= b * ${s}; + + // reverse r and c order for packed texture + int r = imod(index, ${r}) * 2; + int c = 2 * (index / ${r}); + + return ivec3(b, r, c); + } + `;return new R(i)}getOutputPackedNDCoords(t,e){let n=[e[0],e[1]],r=Math.ceil(t[t.length-1]/2),s=r*Math.ceil(t[t.length-2]/2),i=s,a="",u="b, r, c";for(let o=2;o=0;--u)s[u]=s[u+1]*t[u+1];let i=["r","c","d"],a=s.map((u,d)=>{let o=`int ${i[d]} = index / ${u}`,l=d===s.length-1?`int ${i[d+1]} = index - ${i[d]} * ${u}`:`index -= ${i[d]} * ${u}`;return`${o}; ${l};`}).join("");return n=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${a} + return ivec3(r, c, d); + } + `,new R(n)}getOutputUnpacked4DCoords(t,e){let n="",r=t.length,s=null;r<2&&(s=[]),s=new Array(r-1),s[r-2]=t[r-1];for(let u=r-3;u>=0;--u)s[u]=s[u+1]*t[u+1];let i=["r","c","d","d2"],a=s.map((u,d)=>{let o=`int ${i[d]} = index / ${u}`,l=d===s.length-1?`int ${i[d+1]} = index - ${i[d]} * ${u}`:`index -= ${i[d]} * ${u}`;return`${o}; ${l};`}).join("");return n=` + ivec4 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${a} + return ivec4(r, c, d, d2); + } + `,new R(n)}getOutputUnpacked5DCoords(t,e){let n="",r=t.length,s=null;r<2&&(s=[]),s=new Array(r-1),s[r-2]=t[r-1];for(let u=r-3;u>=0;--u)s[u]=s[u+1]*t[u+1];let i=["r","c","d","d2","d3"],a=s.map((u,d)=>{let o=`int ${i[d]} = index / ${u}`,l=d===s.length-1?`int ${i[d+1]} = index - ${i[d]} * ${u}`:`index -= ${i[d]} * ${u}`;return`${o}; ${l};`}).join("");return n=` + ivec5 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${a} + return ivec5(r, c, d, d2, d3); + } + `,new R(n)}getOutputUnpacked6DCoords(t,e){let n="",r=t.length,s=null;r<2&&(s=[]),s=new Array(r-1),s[r-2]=t[r-1];for(let u=r-3;u>=0;--u)s[u]=s[u+1]*t[u+1];let i=["r","c","d","d2","d3","d4"],a=s.map((u,d)=>{let o=`int ${i[d]} = index / ${u}`,l=d===s.length-1?`int ${i[d+1]} = index - ${i[d]} * ${u}`:`index -= ${i[d]} * ${u}`;return`${o}; ${l};`}).join("");return n=` + ivec6 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${e[0]}, ${e[1]})); + int index = resTexRC.y * ${e[0]} + resTexRC.x; + ${a} + return ivec6(r, c, d, d2, d3, d4); + } + `,new R(n)}getCommonUtilFuncs(){let t={},e="uvFromFlat";t[e]=new R(` + vec2 uvFromFlat(int texNumR, int texNumC, int index) { + int texC = index / texNumR; + int texR = index - texC * texNumR; + // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to + // v. + return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); + } + `),e="packedUVfrom1D",t[e]=new R(` + vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { + int texelIndex = index / 2; + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),e="packedUVfrom2D",t[e]=new R(` + vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { + int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),e="packedUVfrom3D",t[e]=new R(` + vec2 packedUVfrom3D(int texNumR, int texNumC, + int texelsInBatch, int texelsInLogicalRow, int b, + int row, int col) { + int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),e="sampleTexture";let n=q(this.context.glContext.version);return t[e]=new R(` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${n.texture2D}(textureSampler, uv).r; + }`),t}getInputsSamplingSnippets(){let t={},e=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((n,r)=>{let s=this.context.inputTextureLayouts[r],i=Kn(n);s.isPacked?t[i]=this.getPackedSamplerFromInput(i,n,s):t[i]=this.getUnpackedSamplerFromInput(i,n,s);let a=Mu(n);s.unpackedShape.length<=e.unpackedShape.length&&(s.isPacked?t[a]=this.getPackedSamplerAtOutputCoords(a,s,e,n):t[a]=this.getUnpackedSamplerAtOutputCoords(a,s,e,n))}),t}getPackedSamplerAtOutputCoords(t,e,n,r){let s=e.unpackedShape,i=n.unpackedShape,a=Kn(r),u=s.length,d=i.length,o=Xe.getBroadcastDims(s,i),l=Ke(d),c=d-u,h,f=St();u===0?h="":d<2&&o.length>=1?h="coords = 0;":h=o.map(S=>`coords.${f[S+c]} = 0;`).join(` +`);let p="";d<2&&u>0?p="coords":p=s.map((S,E)=>`coords.${f[E+c]}`).join(", ");let g="return outputValue;",b=U.size(s)===1,x=U.size(i)===1;if(u===1&&!b&&!x)g=` + return vec4(outputValue.xy, outputValue.xy); + `;else if(b&&!x)d===1?g=` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:g=` + return vec4(outputValue.x); + `;else if(o.length){let S=u-2,E=u-1;o.indexOf(S)>-1&&o.indexOf(E)>-1?g="return vec4(outputValue.x);":o.indexOf(S)>-1?g="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(E)>-1&&(g="return vec4(outputValue.xx, outputValue.zz);")}let y=` + int lastDim = coords.${f[d-1]}; + coords.${f[d-1]} = coords.${f[d-2]}; + coords.${f[d-2]} = lastDim; + `,T=` + vec4 ${t}() { + ${l} coords = getOutputCoords(); + ${y} + ${h} + vec4 outputValue = ${a}(${p}); + ${g} + } + `;return new R(T,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(t,e,n,r){let s=[n.width,n.height],i=[e.width,e.height],a=e.unpackedShape.length,u=n.unpackedShape.length,d=e.unpackedShape,o=n.unpackedShape,l=Kn(r);if(a===u&&cr.arraysEqual(i,s)){let y=` + float ${t}() { + return sampleTexture(${r}, TexCoords); + } + `;return new R(y,["coordinates.sampleTexture"])}let c=Ke(u),h=Xe.getBroadcastDims(d,o),f=u-a,p,g=St();a===0?p="":u<2&&h.length>=1?p="coords = 0;":p=h.map(y=>`coords.${g[y+f]} = 0;`).join(` +`);let b="";u<2&&a>0?b="coords":b=e.unpackedShape.map((y,T)=>`coords.${g[T+f]}`).join(", ");let x=` + float ${t}() { + ${c} coords = getOutputCoords(); + ${p} + return ${l}(${b}); + } + `;return new R(x,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(t,e,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(t,e);case 1:return this.getPackedSampler1D(t,e,n);case 2:return this.getPackedSampler2D(t,e,n);case 3:return this.getPackedSampler3D(t,e,n);default:return this.getPackedSamplerND(t,e,n)}}getUnpackedSamplerFromInput(t,e,n){let r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(t,e,n);case 1:return this.getUnpackedSampler1D(t,e,n);case 2:return this.getUnpackedSampler2D(t,e,n);case 3:return this.getUnpackedSampler3D(t,e,n);case 4:return this.getUnpackedSampler4D(t,e,n);case 5:return this.getUnpackedSampler5D(t,e,n);case 6:return this.getUnpackedSampler6D(t,e,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(t,e){let n=q(this.context.glContext.version),r=` + vec4 ${t}() { + return ${n.texture2D}(${e}, halfCR); + } + `;return new R(r)}getPackedSampler1D(t,e,n){let r=[n.width,n.height],s=[r[1],r[0]],i=q(this.context.glContext.version),a=`vec4 ${t}(int index) { + vec2 uv = packedUVfrom1D( + ${s[0]}, ${s[1]}, index); + return ${i.texture2D}(${e}, uv); + }`;return new R(a,["coordinates.packedUVfrom1D"])}getPackedSampler2D(t,e,n){let r=n.unpackedShape,s=[n.width,n.height],i=q(this.context.glContext.version),a=s[0],u=s[1];if(s!=null&&cr.arraysEqual(r,s)){let c=`vec4 ${t}(int row, int col) { + vec2 uv = (vec2(col, row) + halfCR) / vec2(${u}.0, ${a}.0); + return ${i.texture2D}(${e}, uv); + }`;return new R(c)}let d=s,o=Math.ceil(r[1]/2),l=`vec4 ${t}(int row, int col) { + vec2 uv = packedUVfrom2D(${d[1]}, ${d[0]}, ${o}, row, col); + return ${i.texture2D}(${e}, uv); + }`;return new R(l,["coordinates.packedUVfrom2D"])}getPackedSampler3D(t,e,n){let r=n.unpackedShape,s=[n.width,n.height],i=[s[0],s[1]],a=q(this.context.glContext.version);if(r[0]===1){let h=r.slice(1),f=[1,2],p=kr(r,h),g=["b","row","col"],b=JSON.parse(JSON.stringify(n));b.unpackedShape=p;let x=this.getPackedSamplerFromInput(t,e,b),y=`${x.routineBody} + vec4 ${t}(int b, int row, int col) { + return ${t}(${Br(g,f)}); + } `;return new R(y,x.dependencies)}let u=i[0],d=i[1],o=Math.ceil(r[2]/2),l=o*Math.ceil(r[1]/2),c=`vec4 ${t}(int b, int row, int col) { + vec2 uv = packedUVfrom3D( + ${d}, ${u}, ${l}, ${o}, b, row, col); + return ${a.texture2D}(${e}, uv);}`;return new R(c,["coordinates.packedUVfrom3D"])}getPackedSamplerND(t,e,n){let r=n.unpackedShape,s=r.length,i=[n.width,n.height],a=q(this.context.glContext.version),u=[i[0],i[1]],d=u[1],o=u[0],l=Math.ceil(r[s-1]/2),c=l*Math.ceil(r[s-2]/2),h="int b, int row, int col",f=`b * ${c} + (row / 2) * ${l} + (col / 2)`;for(let g=2;g{let r=this.context.inputTextureLayouts[n],s=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length,i=`_${e}`;t[i]=new R(this.getValueFromSingle(e,s,r.width,r.height,!1),[`shapeUtils.indicesToOffset${i}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),i=i+"_T",t[i]=new R(this.getValueFromSingle(e,s,r.width,r.height,!0),[`shapeUtils.indicesToOffset${i}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),t}getValueFromSingle(t,e,n,r,s){let i=`_${t}`;s&&(i=i+"_T");let a=q(this.context.glContext.version);return` + float ${i}(int m[${e}]) { + int offset = indicesToOffset${i}(m); + vec2 coords = offsetToCoords(offset, ${n}, ${r}); + float value = getColorAsFloat(${a.texture2D}(${t}, coords)); + return value; + } + `}getPackedValueFrom(t,e,n,r,s){let i=`_${t}_Pack`;s&&(i=i+"_T");let a=q(this.context.glContext.version);return` + vec4 ${i}(int m[${e}]) { + int offset = indicesToOffset_${t}(m); + vec2 coords = offsetToCoords(offset, ${n}, ${r}); + return ${a.texture2D}(${t}, coords); + } + `}}}),po,ep=L(()=>{Vt(),po=class Ar extends pt{constructor(e){super(e)}getFunctions(){return{...this.encodeFloat32(),...this.decodeFloat32()}}getCustomTypes(){return{}}encodeFloat32(){return{encode:new R(`highp vec4 encode(highp float f) { + return vec4(f, 0.0, 0.0, 0.0); + } + `)}}decodeFloat32(){return{decode:new R(`highp float decode(highp vec4 rgba) { + return rgba.r; + } + `)}}encodeUint8(){let e=Ar.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new R(` + highp vec4 encode(highp float f) { + highp float F = abs(f); + highp float Sign = step(0.0,-f); + highp float Exponent = floor(log2(F)); + highp float Mantissa = (exp2(- Exponent) * F); + Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); + highp vec4 rgba; + rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); + rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); + rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); + rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); + ${e} + rgba = rgba / 255.0; // values need to be normalized to [0,1] + return rgba; + } + `)}}decodeUint8(){let e=Ar.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new R(` + highp float decode(highp vec4 rgba) { + rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] + ${e} + highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; + highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; + highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); + highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); + return Result; + } + `)}}static isLittleEndian(){let e=new ArrayBuffer(4),n=new Uint32Array(e),r=new Uint8Array(e);if(n[0]=3735928559,r[0]===239)return!0;if(r[0]===222)return!1;throw new Error("unknown endianness")}}}),ho,tp=L(()=>{Vt(),xe(),ho=class extends pt{constructor(t){super(t)}getFunctions(){return{...this.setFragColor(),...this.getColorAsFloat()}}getCustomTypes(){return{}}setFragColor(){let t=q(this.context.glContext.version);return{setFragColor:new R(` + void setFragColor(float value) { + ${t.output} = encode(value); + } + `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new R(` + float getColorAsFloat(vec4 color) { + return decode(color); + } + `,["encoding.decode"])}}}}),mo,rp=L(()=>{Vt(),mo=class rn extends pt{constructor(e){super(e)}getFunctions(){return{...this.bcastIndex(),...this.bcastMatmulIndex(),...this.offsetToIndices(),...this.indicesToOffset(),...this.incrementIndices()}}getCustomTypes(){return{}}bcastIndex(){let e=this.context.outputTextureLayout.shape.length,n={};return this.context.programInfo.inputNames.forEach((r,s)=>{let i=this.context.inputTextureLayouts[s].unpackedShape;if(i.length<=e){let a=i.length,u=e-a,d=`bcastIndices_${r}`,o="";for(let c=0;c{let i=this.context.inputTextureLayouts[s].shape;if(!(i.length<2||i.length>e)){let a=i.length,u=e-a,d=`bcastMatmulIndices_${r}`,o="";for(let c=0;c{let s=this.context.inputTextureLayouts[r].shape,i=this.context.inputTextureLayouts[r].strides,a=s.length,u=`indicesToOffset_${n}`;e[u]=new R(rn.indexToOffsetSingle(u,a,i)),u=`indicesToOffset_${n}_T`,e[u]=new R(rn.indexToOffsetSingle(u,a,i.slice().reverse()))}),e}static indexToOffsetSingle(e,n,r){let s="";for(let i=n-1;i>=0;--i)s+=` + offset += indices[${i}] * ${r[i]}; + `;return` + int ${e}(int indices[${n}]) { + int offset = 0; + ${s} + return offset; + } + `}offsetToIndices(){let e={};return this.context.programInfo.inputNames.forEach((n,r)=>{let s=this.context.inputTextureLayouts[r].shape,i=this.context.inputTextureLayouts[r].strides,a=s.length,u=`offsetToIndices_${n}`;e[u]=new R(rn.offsetToIndicesSingle(u,a,i)),u=`offsetToIndices_${n}_T`,e[u]=new R(rn.offsetToIndicesSingle(u,a,i.slice().reverse()))}),e}static offsetToIndicesSingle(e,n,r){let s=[];for(let i=0;i{let s=this.context.inputTextureLayouts[r].shape,i=s.length,a=`incrementIndices_${n}`,u="";for(let o=0;o= 0; --i) { + if(i > axis) continue; + indices[i] += 1; + if(indices[i] < shape[i]) { + break; + } + indices[i] = 0; + } + } + `;e[a]=new R(d)}),e}}}),bo,np=L(()=>{Vt(),bo=class extends pt{constructor(t){super(t)}getCustomTypes(){return{}}getFunctions(){return{...this.binaryVecFunctions(),...this.copyVec(),...this.setVecItem(),...this.getVecItem()}}binaryVecFunctions(){let t=this.context.outputTextureLayout.shape.length,e={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(let r in e){let s=`${r}Vec`,i="";for(let u=0;u{Qc(),ep(),tp(),rp(),np(),qi={encoding:po,fragcolor:ho,vec:bo,shapeUtils:mo,coordinates:co}}),go,ip=L(()=>{Vt(),Jc(),op(),xe(),go=class{constructor(t,e,n,r){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new eo(t,e,n,r),Object.keys(qi).forEach(i=>{let a=new qi[i](this.context);this.libs[i]=a});let s=this.glslLibRoutineDependencyGraph;for(let i in this.libs){let a=this.libs[i].getFunctions();for(let u in a){let d=i+"."+u,o;s[d]?(o=s[d],o.routineBody=a[u].routineBody):(o=new cn(d,a[u].routineBody),s[d]=o);let l=a[u].dependencies;if(l)for(let c=0;c{let r=n.split(".")[1];t.indexOf(r)!==-1&&e.push(this.glslLibRoutineDependencyGraph[n])}),to$1.returnOrderedNodes(e)}getUniforms(t,e){let n=[];if(t)for(let r of t)n.push(`uniform sampler2D ${r};`);if(e)for(let r of e)n.push(`uniform ${r.type} ${r.name}${r.arrayLength?`[${r.arrayLength}]`:""};`);return n.join(` +`)}}}),yo,ap=L(()=>{vt(),ut(),ip(),xe(),yo=class{constructor(t,e,n){this.profiler=t,this.glContext=e,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,n){this.profiler.event("op",`ProgramManager.run ${t.programInfo.name??"unknown kernel"}`,()=>{let r=this.glContext.gl,s=t.program;r.useProgram(s);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(t.attribLocations),this.bindUniforms(t.uniformLocations,t.programInfo.variables??[],e)}catch(i){throw ce.error("ProgramManager",t.programInfo.shaderSource),i}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(t=>this.glContext.deleteProgram(t.program))}build(t,e,n){return this.profiler.event("backend","ProgramManager.build",()=>{let r=new go(this.glContext,t,e,n),s=r.preprocess(),i=this.compile(s);return{programInfo:t,program:i,uniformLocations:this.getUniformLocations(i,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(i)}})}compile(t){if(!this.vertexShader){ce.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");let r=Bu(this.glContext.version);this.vertexShader=this.glContext.compileShader(r,this.glContext.gl.VERTEX_SHADER)}Z.debug&&ce.verbose("ProrgramManager",`FragShader: +${t} +`);let e=this.glContext.compileShader(t,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,e);return this.glContext.deleteShader(e),n}bindOutput(t){let e=t.width,n=t.height;ce.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${e}/${n}, shape=${t.shape}, type=${t.tensor.type}`),this.glContext.attachFramebuffer(t.texture,e,n)}bindAttributes(t){let e=t.position,n=t.textureCoord;this.glContext.setVertexAttributes(e,n),this.attributesBound=!0}bindUniforms(t,e,n){let r=this.glContext.gl,s=0;for(let{name:i,type:a,location:u,arrayLength:d}of t){let o=e.find(l=>l.name===i)?.data;if(a!=="sampler2D"&&!o)throw new Error(`variable '${i}' does not have data defined in program info`);switch(a){case"sampler2D":this.bindTexture(n[s],u,s),s++;break;case"float":d?r.uniform1fv(u,o):r.uniform1f(u,o);break;case"int":d?r.uniform1iv(u,o):r.uniform1i(u,o);break;default:throw new Error(`Uniform not implemented: ${a}`)}}}bindTexture(t,e,n){this.glContext.bindTextureToUniform(t.texture,n,e)}getAttribLocations(t){return{position:this.getAttribLocation(t,"position"),textureCoord:this.getAttribLocation(t,"textureCoord")}}getUniformLocations(t,e,n){let r=[];if(e)for(let s of e)r.push({name:s,type:"sampler2D",location:this.getUniformLocation(t,s)});if(n)for(let s of n)r.push({...s,location:this.getUniformLocation(t,s.name)});return r}getUniformLocation(t,e){let n=this.glContext.gl.getUniformLocation(t,e);if(n===null)throw new Error(`Uniform ${e} not found.`);return n}getAttribLocation(t,e){return this.glContext.gl.getAttribLocation(t,e)}}}),To,sp=L(()=>{ut(),ln(),To=class{constructor(t,e,n,r){this.glContext=t,this.layoutStrategy=e,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(t,e,n,r){let s=this.toEncoderType(t),i=this.glContext.getEncoder(s,e.channels||1,r);if(e.isPacked&&r===1)throw new Error("not implemented");let a=e.width,u=e.height,d,o;if(this.config.reuseTextures){d=`${a}x${u}_${i.format}_${i.internalFormat}_${i.textureType}`,o=this.inUseTextures.get(d),o||(o=[],this.inUseTextures.set(d,o));let c=this.idleTextures.get(d);if(c&&c.length>0){let h=c.pop();return o.push(h),r===1&&this.glContext.updateTexture(h,a,u,i,this.toTextureData(t,n)),h}}ce.verbose("TextureManager",`Creating new texture of size ${e.width}x${e.height}`);let l=this.glContext.allocateTexture(a,u,i,this.toTextureData(t,n));return this.config.reuseTextures&&(o.push(l),this.textureLookup.set(l,d)),l}readTexture(t,e,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",()=>{let r=t.shape.reduce((i,a)=>i*a)*n,s=this.glContext.readTexture(t.texture,t.width,t.height,r,this.toEncoderType(e),n);return this.toTensorData(e,s)})}async readTextureAsync(t,e,n){let r=t.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){let s=this.pendingRead.get(r);return new Promise(i=>s?.push(i))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(r,[]);let s=t.shape.reduce((d,o)=>d*o)*n;await this.glContext.createAndWaitForFence();let i=this.glContext.readTexture(t.texture,t.width,t.height,s,this.toEncoderType(e),n),a=this.toTensorData(e,i),u=this.pendingRead.get(r);return this.pendingRead.delete(r),u?.forEach(d=>d(a)),a})}readUint8TextureAsFloat(t){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{let e=t.shape.reduce((r,s)=>r*s),n=this.glContext.readTexture(t.texture,t.width,t.height,e*4,"byte",4);return new Float32Array(n.buffer,n.byteOffset,e)})}releaseTexture(t,e){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(t.texture),n)){e&&this.textureLookup.delete(n);let r=this.inUseTextures.get(n);if(r){let s=r.indexOf(t.texture);if(s!==-1){r.splice(s,1);let i=this.idleTextures.get(n);i||(i=[],this.idleTextures.set(n,i)),i.push(t.texture)}}}(!n||e)&&(ce.verbose("TextureManager",`Deleting texture of size ${t.width}x${t.height}`),this.glContext.deleteTexture(t.texture))}toTensorData(t,e){switch(t){case"int16":return e instanceof Int16Array?e:Int16Array.from(e);case"int32":return e instanceof Int32Array?e:Int32Array.from(e);case"int8":return e instanceof Int8Array?e:Int8Array.from(e);case"uint16":return e instanceof Uint16Array?e:Uint16Array.from(e);case"uint32":return e instanceof Uint32Array?e:Uint32Array.from(e);case"uint8":case"bool":return e instanceof Uint8Array?e:Uint8Array.from(e);case"float32":return e instanceof Float32Array?e:Float32Array.from(e);case"float64":return e instanceof Float64Array?e:Float64Array.from(e);default:throw new Error(`TensorData type ${t} is not supported`)}}toTextureData(t,e){if(e)return e instanceof Float32Array?e:new Float32Array(e)}toEncoderType(t){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}}),xo,up=L(()=>{ut(),ws(),Qu(),Yc(),ap(),Hi(),sp(),xo=class{constructor(t,e){this.backend=t,this.context=e,this.layoutStrategy=new fo(t.glContext.maxTextureSize),this.programManager=new yo(this.context.profiler,t.glContext,this.layoutStrategy),this.textureManager=new To(t.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:t.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=t.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new Qn(this)}onGraphInitialized(t){let e=t.getValues().filter(n=>n.from===-1&&n.tensor).map(n=>n.tensor.dataId);this.initializers=new Set(e)}isInitializer(t){return this.initializers?this.initializers.has(t):!1}addInitializer(t){this.initializers.add(t)}getTextureData(t,e){return e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){ce.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(t,e):this.unpackedTextureDataCache.set(t,e)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(t=>this.textureManager.releaseTexture(t,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(t=>this.textureManager.releaseTexture(t,!0)),this.unpackedTextureDataCache=new Map}resolve(t,e,n){let r=vs(t,e,jc);return{impl:r.opImpl,context:r.opInit?r.opInit(t,n):t}}}});function Hb(t){let e=0;for(;e{vt(),ln(),ln(),Ft(),hn=class{constructor(t,e){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=t,this.version=e,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(t,e,n,r){let s=this.gl,i=s.createTexture();s.bindTexture(s.TEXTURE_2D,i),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);let a=r?n.encode(r,t*e):null;return s.texImage2D(s.TEXTURE_2D,0,n.internalFormat,t,e,0,n.format,n.textureType,a),this.checkError(),i}updateTexture(t,e,n,r,s){let i=this.gl;i.bindTexture(i.TEXTURE_2D,t);let a=r.encode(s,e*n);i.texSubImage2D(i.TEXTURE_2D,0,0,0,e,n,r.format,r.textureType,a),this.checkError()}attachFramebuffer(t,e,n){let r=this.gl;r.bindTexture(r.TEXTURE_2D,t),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t,0),this.checkError(),r.viewport(0,0,e,n),r.scissor(0,0,e,n)}readTexture(t,e,n,r,s,i){let a=this.gl;i||(i=1),this.frameBufferBound||this.attachFramebuffer(t,e,n);let u=this.getEncoder(s,i),d=u.allocate(e*n);return a.bindTexture(a.TEXTURE_2D,t),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t,0),a.readPixels(0,0,e,n,a.RGBA,u.textureType,d),this.checkError(),u.decode(d,r)}isFramebufferReady(){return!0}getActiveTexture(){let t=this.gl;return`TEXTURE${t.getParameter(this.gl.ACTIVE_TEXTURE)-t.TEXTURE0}`}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(t,e){let n=this.gl;n.vertexAttribPointer(t,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(t),e!==-1&&(n.vertexAttribPointer(e,2,n.FLOAT,!1,20,12),n.enableVertexAttribArray(e)),this.checkError()}createProgram(t,e){let n=this.gl,r=n.createProgram();return n.attachShader(r,t),n.attachShader(r,e),n.linkProgram(r),r}compileShader(t,e){let n=this.gl,r=n.createShader(e);if(!r)throw new Error(`createShader() returned null with type ${e}`);if(n.shaderSource(r,t),n.compileShader(r),n.getShaderParameter(r,n.COMPILE_STATUS)===!1)throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(r)} +Shader source: +${t}`);return r}deleteShader(t){this.gl.deleteShader(t)}bindTextureToUniform(t,e,n){let r=this.gl;r.activeTexture(r.TEXTURE0+e),this.checkError(),r.bindTexture(r.TEXTURE_2D,t),this.checkError(),r.uniform1i(n,e),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(Z.debug){let t=this.gl,e=t.getError(),n="";switch(e){case t.NO_ERROR:return;case t.INVALID_ENUM:n="INVALID_ENUM";break;case t.INVALID_VALUE:n="INVALID_VALUE";break;case t.INVALID_OPERATION:n="INVALID_OPERATION";break;case t.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case t.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case t.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${e.toString(16)}`}throw new Error(n)}}deleteTexture(t){this.gl.deleteTexture(t)}deleteProgram(t){this.gl.deleteProgram(t)}getEncoder(t,e,n=0){if(this.version===2)return new Jn(this.gl,e);switch(t){case"float":return n===1||this.isRenderFloat32Supported?new un(this.gl,e):new un(this.gl,e,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new Zn(this.gl,e);default:throw new Error(`Invalid dataType: ${t}`)}}clearActiveTextures(){let t=this.gl;for(let e=0;ethis.isTimerResultAvailable(t)),this.getTimerResult(t)}async createAndWaitForFence(){let t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e,n=t,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),r===null?e=()=>!0:e=()=>{let s=n.clientWaitSync(r,0,0);return s===n.ALREADY_SIGNALED||s===n.CONDITION_SATISFIED},{query:r,isFencePassed:e}}async pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){let t=Hb(this.itemsToPoll.map(e=>e.isDoneFn));for(let e=0;e<=t;++e){let{resolveFn:n}=this.itemsToPoll[e];n()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}async addItemToPoll(t,e){this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),!(this.itemsToPoll.length>1)&&await gi(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function ji(t){let e;if((!t||t==="webgl2")&&"webgl2"in Ur?e=Ur.webgl2:(!t||t==="webgl")&&"webgl"in Ur&&(e=Ur.webgl),!e)try{let r=jb();e=fp(r,t)}catch{let r=qb();e=fp(r,t)}t=t||e.version===1?"webgl":"webgl2";let n=e.gl;return Ur[t]=e,n.isContextLost()?(delete Ur[t],ji(t)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),e)}function fp(t,e){let n={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},r,s=n;if((!e||e==="webgl2")&&(r=t.getContext("webgl2",s),r))try{return new hn(r,2)}catch(i){ce.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${i}`)}if((!e||e==="webgl")&&(r=t.getContext("webgl",s)||t.getContext("experimental-webgl",s),r))try{return new hn(r,1)}catch(i){ce.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${i}`)}throw new Error("WebGL is not supported")}function qb(){if(typeof document>"u")throw new TypeError("failed to create canvas: document is not supported");let t=document.createElement("canvas");return t.width=1,t.height=1,t}function jb(){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var Ur,cp=L(()=>{ut(),lp(),Ur={}}),vo,pp=L(()=>{vt(),ut(),up(),cp(),vo=class{get contextId(){return Z.webgl.contextId}set contextId(t){Z.webgl.contextId=t}get matmulMaxBatchSize(){return Z.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(t){Z.webgl.matmulMaxBatchSize=t}get textureCacheMode(){return Z.webgl.textureCacheMode}set textureCacheMode(t){Z.webgl.textureCacheMode=t}get pack(){return Z.webgl.pack}set pack(t){Z.webgl.pack=t}get async(){return Z.webgl.async}set async(t){Z.webgl.async=t}initialize(){try{return this.glContext=ji(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),ce.setWithEnv(Z),Z.webgl.context||Object.defineProperty(Z.webgl,"context",{value:this.glContext.gl}),ce.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(t){return ce.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${t}`),!1}}createSessionHandler(t){return new xo(this,t)}dispose(){this.glContext.dispose()}}});async function Yi(t){if(t){let e=typeof t=="string"?[t]:t;for(let n of e){let r=dp.get(n);if(r)return r;let s=await Xb(n);if(s)return s}}else return Yi(["webgl"]);throw new Error("no available backend to use")}async function Xb(t){let e=Yb;if(typeof e[t]<"u"&&Kb(e[t])){let n=e[t],r=n.initialize();if(typeof r=="object"&&"then"in r&&(r=await r),r)return dp.set(t,n),n}}function Kb(t){let e=t;return"initialize"in e&&typeof e.initialize=="function"&&"createSessionHandler"in e&&typeof e.createSessionHandler=="function"&&"dispose"in e&&typeof e.dispose=="function"}var dp,Yb,hp=L(()=>{pp(),dp=new Map,Yb={webgl:new vo}}),Xi,wo,mp=L(()=>{ut(),Xi=class{constructor(t,e){this.op=t,this.node=e}},wo=class{constructor(t,e,n){this.graph=t,this.profiler=n,this.initialize(e)}initialize(t){this.profiler.event("session","ExecutionPlan.initialize",()=>{let e=this.graph.getNodes();if(e.length!==t.length)throw new Error("The size of nodes and OPs do not match.");this._ops=t.map((n,r)=>new Xi(n,e[r])),this.reset(),this._starter=[],this._ops.forEach((n,r)=>{let s=!0;for(let i of n.node.inputs)if(!this._values[i]&&this.graph.getInputIndices().indexOf(i)===-1){s=!1;break}s&&this._starter.push(r)})})}reset(){this._values=this.graph.getValues().map(t=>t.tensor)}async execute(t,e){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let n=t.createInferenceHandler(),r=this.graph.getInputIndices();if(e.length!==r.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e.length} expected: ${r.length}`);e.forEach((o,l)=>{let c=r[l];this._values[c]=o});let s=this._starter.slice(0),i=this.graph.getValues(),a=this.graph.getNodes(),u=0;for(;uthis._values[g]);if(c.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${l.node}`);let h=c;ce.verbose("ExecPlan",`Runing op:${l.node.name} (${h.map((g,b)=>`'${l.node.inputs[b]}': ${g.type}[${g.dims.join(",")}]`).join(", ")})`);let f=await this.profiler.event("node",l.node.name,async()=>l.op.impl(n,h,l.op.context));if(f.length!==l.node.outputs.length)throw new Error("the size of output does not match model definition.");f.forEach((g,b)=>{let x=l.node.outputs[b];if(this._values[x])throw new Error(`output [${x}] already has value: op:${l.node.name}`);this._values[x]=g});let p=new Set;f.forEach((g,b)=>{let x=l.node.outputs[b];for(let y of i[x].to){let T=a[y],S=!0;for(let E of T.inputs)if(!this._values[E]){S=!1;break}S&&p.add(y)}}),s.push(...p)}let d=[];for(let o=0;o{tn(),oe=Er($r()),mr(),fe(),mt=W.experimental.fbs,mn=class on{constructor(e){if(this._attributes=new Map,e!=null){for(let n of e)n instanceof oe.onnx.AttributeProto?this._attributes.set(n.name,[on.getValue(n),on.getType(n)]):n instanceof mt.Attribute&&this._attributes.set(n.name(),[on.getValue(n),on.getType(n)]);if(this._attributes.sizeFe.fromProto(s));if(e instanceof mt.Attribute)return r.map(s=>Fe.fromOrtTensor(s))}return n===oe.onnx.AttributeProto.AttributeType.STRING&&e instanceof oe.onnx.AttributeProto?sn(r):n===oe.onnx.AttributeProto.AttributeType.STRINGS&&e instanceof oe.onnx.AttributeProto?r.map(sn):r}static getValueNoCheck(e){return e instanceof oe.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(e):this.getValueNoCheckFromOrtFormat(e)}static getValueNoCheckFromOnnxFormat(e){switch(e.type){case oe.onnx.AttributeProto.AttributeType.FLOAT:return e.f;case oe.onnx.AttributeProto.AttributeType.INT:return e.i;case oe.onnx.AttributeProto.AttributeType.STRING:return e.s;case oe.onnx.AttributeProto.AttributeType.TENSOR:return e.t;case oe.onnx.AttributeProto.AttributeType.GRAPH:return e.g;case oe.onnx.AttributeProto.AttributeType.FLOATS:return e.floats;case oe.onnx.AttributeProto.AttributeType.INTS:return e.ints;case oe.onnx.AttributeProto.AttributeType.STRINGS:return e.strings;case oe.onnx.AttributeProto.AttributeType.TENSORS:return e.tensors;case oe.onnx.AttributeProto.AttributeType.GRAPHS:return e.graphs;default:throw new Error(`unsupported attribute type: ${oe.onnx.AttributeProto.AttributeType[e.type]}`)}}static getValueNoCheckFromOrtFormat(e){switch(e.type()){case mt.AttributeType.FLOAT:return e.f();case mt.AttributeType.INT:return e.i();case mt.AttributeType.STRING:return e.s();case mt.AttributeType.TENSOR:return e.t();case mt.AttributeType.GRAPH:return e.g();case mt.AttributeType.FLOATS:return e.floatsArray();case mt.AttributeType.INTS:{let n=[];for(let r=0;r{bp(),tn(),Ji=Er($r()),mr(),fe(),_o=W.experimental.fbs,Zi={from:(t,e)=>new Ki(t,e)},kt=class{constructor(t){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,t&&(this.type=Ve.tensorValueTypeFromProto(t.type.tensorType))}get from(){return this._from}get to(){return this._to}},Oo=class{constructor(t,e){t instanceof Ji.onnx.NodeProto?(this.name=t.name,this.opType=t.opType,this.attributes=new mn(t.attribute)):t instanceof _o.Node&&(this.name=e??t.name(),this.opType=t.opType(),this.attributes=new mn(Ve.tensorAttributesFromORTFormat(t))),this.inputs=[],this.outputs=[],this.executeNode=!0}},Ki=class{constructor(t,e){if(!t)throw new TypeError("graph is empty");this.buildGraph(t),this.transformGraph(e),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(t){if(t instanceof Ji.onnx.GraphProto)this.buildGraphFromOnnxFormat(t);else if(t instanceof _o.Graph)this.buildGraphFromOrtFormat(t);else throw new TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(t){let e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map;if(!t.input)throw new Error("missing information in graph: input");let r=[];for(let s of t.input){if(e.has(s.name))throw new Error(`duplicated input name: ${s.name}`);let i=this._allData.push(new kt(s))-1;e.set(s.name,i),r.push(s.name)}if(!t.initializer)throw new Error("missing information in graph: initializer");for(let s of t.initializer){let i=e.get(s.name);if(i===void 0){let a=new kt;a.type={shape:{dims:Ve.tensorDimsFromProto(s.dims)},tensorType:Ve.tensorDataTypeFromProto(s.dataType)},i=this._allData.push(a)-1,e.set(s.name,i)}this._allData[i]._from=-1,this._allData[i].tensor=Fe.fromProto(s)}for(let s=0;s"u"&&(d=this._allData.push(new kt)-1,e.set(u,d)),i.outputs.push(d),this._allData[d]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${d}`);if(this._allData[d]._from=s,a.opType==="Constant"){if(!a.attribute||a.attribute.length!==1||!a.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!a.output||a.output.length!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");i.outputs.pop(),i.executeNode=!1,this._allData[d]._from=-1,this._allData[d].tensor=Fe.fromProto(a.attribute[0].t)}}}for(let s=0;s"u"){if(u===""&&(a.input.length===3||a.input.length===4)&&a.opType==="Resize")continue;throw new Error(`unrecognized input '${u}' for node: ${a.name}`)}i.inputs.push(d),this._allData[d]._to.push(s)}}return!0}buildGraphFromOrtFormat(t){let e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map,r=[];for(let s=0;s"u"&&(o=this._allData.push(new kt)-1,e.set(d,o)),i.outputs.push(o),this._allData[o]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${o}`);if(this._allData[o]._from=s,a.opType()==="Constant"){if(a.attributesLength()!==1||!a.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(a.outputsLength()!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");i.outputs.pop(),i.executeNode=!1,this._allData[o]._from=-1,this._allData[o].tensor=Fe.fromOrtTensor(a.attributes(0).t())}}}for(let s=0;s"u")throw new Error(`unrecognized input '${d}' for node: ${a.name()}`);i.inputs.push(o),this._allData[o]._to.push(s)}}}checkIsAcyclic(){let t=new Set;this._allInputIndices.forEach(r=>{this._allData[r]._to.forEach(s=>{t.add(s)})});let e=Array.from(t),n=new Array(this._nodes.length).fill("white");for(;e.length>0;){let r=e.pop();n[r]==="gray"?n[r]="black":(e.push(r),n[r]="gray",this._nodes[r].outputs.forEach(s=>{let i=this._allData[s];if(typeof i.tensor<"u")throw new Error("node outputs should not be initialized");if(i._from!==r)throw new Error("from property of the Value object doesn't match index of Node being processed");i._to.forEach(a=>{if(n[a]==="gray")throw new Error("model graph is cyclic");n[a]==="white"&&e.push(a)})}))}}transformGraph(t){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),t&&t.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let t=0,e=new Array(this._nodes.length,0),n=0;for(let r=0;r{this._allData[s]._from=-2});this._nodes.splice(n,this._nodes.length-n);for(let r=0;r=0)s._to[i]=e[s._to[i]];else throw new Error("Trying to update a removed node")}t=0;for(let r=0;r0){let s=-1;this._allData[r].from!==void 0&&this._allData[r].from!==-1?(s=this._nodes[this._allData[r].from].outputs.indexOf(r+t),s!==-1&&(this._nodes[this._allData[r].from].outputs[s]=r)):(s=this._allInputIndices.indexOf(r+t),s!==-1&&(this._allInputIndices[s]=r)),this._allData[r].to.forEach(i=>{s=this._nodes[i].inputs.indexOf(r+t),s!==-1&&(this._nodes[i].inputs[s]=r)}),this._allData[r].to.length===0&&(s=this._allOutputIndices.indexOf(r+t),s!==-1&&(this._allOutputIndices[s]=r))}}}deleteNode(t){let e=this._nodes[t];if(e.outputs.length>1){for(let a=1;a0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}e.executeNode=!1;let n=e.inputs[0],r=e.outputs[0],s=this._allData[r].to;for(let a=0;a0)for(let a of s){let u=this._nodes[a].inputs.indexOf(r);if(u===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[a].inputs[u]=n,this._allData[n].to.push(a)}}removeAllDropoutNodes(){let t=0;for(let e of this._nodes){if(e.opType==="Dropout"){if(e.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(e.outputs.length!==1&&e.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(e.outputs.length===2&&this._allData[e.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(t)}t++}}removeAllIdentityNodes(){let t=0;for(let e of this._nodes)e.opType==="Identity"&&this.deleteNode(t),t++}isActivation(t){switch(t.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let t of this._nodes)if(t.opType==="Conv"){let e=this._allData[t.outputs[0]]._to;if(e.length===1&&this.isActivation(this._nodes[e[0]])){let n=this._nodes[e[0]];if(n.opType==="Clip")if(n.inputs.length===1)try{t.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch{t.attributes.set("activation_params","floats",[dr,hr])}else if(n.inputs.length>=3&&this._allData[n.inputs[1]].tensor!==void 0&&this._allData[n.inputs[2]].tensor!==void 0)t.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]]);else continue;t.attributes.set("activation","string",n.opType),this.deleteNode(e[0])}}}}}),yp,Jb,Io,Tp=L(()=>{Wn(),gp(),tn(),yp=Er($r()),fe(),Jb=W.experimental.fbs,Io=class{constructor(){}load(t,e,n){if(!n)try{this.loadFromOnnxFormat(t,e);return}catch(r){if(n!==void 0)throw r}this.loadFromOrtFormat(t,e)}loadFromOnnxFormat(t,e){let n=yp.onnx.ModelProto.decode(t);if(nt.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map(r=>({domain:r.domain,version:nt.longToNumber(r.version)})),this._graph=Zi.from(n.graph,e)}loadFromOrtFormat(t,e){let n=new _.ByteBuffer(t),r=Jb.InferenceSession.getRootAsInferenceSession(n).model();if(nt.longToNumber(r.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let s=0;s{hp(),mp(),ut(),Tp(),So=class{constructor(t={}){this._initialized=!1,this.backendHint=t.backendHint,this.profiler=zn.create(t.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(t,e,n){await this.profiler.event("session","Session.loadModel",async()=>{let r=await Yi(this.backendHint);if(this.sessionHandler=r.createSessionHandler(this.context),this._model=new Io,typeof t=="string"){let s=t.endsWith(".ort");if(typeof process<"u"&&process.versions&&process.versions.node){let i=await(void 0)(t);this.initialize(i,s)}else{let i=await(await fetch(t)).arrayBuffer();this.initialize(new Uint8Array(i),s)}}else if(ArrayBuffer.isView(t))this.initialize(t);else{let s=new Uint8Array(t,e||0,n||t.byteLength);this.initialize(s)}})}initialize(t,e){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(t,n,e),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new wo(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(t){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let e=this.normalizeAndValidateInputs(t),n=await this._executionPlan.execute(this.sessionHandler,e);return this.createOutput(n)})}normalizeAndValidateInputs(t){let e=this._model.graph.getInputNames();if(Array.isArray(t)){if(t.length!==e.length)throw new Error(`incorrect input array length: expected ${e.length} but got ${t.length}`)}else{if(t.size!==e.length)throw new Error(`incorrect input map size: expected ${e.length} but got ${t.size}`);let n=new Array(t.size),r=0;for(let s=0;s{vt(),mr(),Ao=class{constructor(t){this.session=t,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(t,e,n){let r=new Map;for(let a in t)if(Object.hasOwnProperty.call(t,a)){let u=t[a];r.set(a,new Fe(u.dims,u.type,void 0,void 0,u.data))}let s=await this.session.run(r),i={};return s.forEach((a,u)=>{i[u]=new Re(a.type,a.data,a.dims)}),i}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),wp={};Pr(wp,{onnxjsBackend:()=>Qb});var Qi,Qb,_p=L(()=>{xp(),vp(),Qi=class{async init(){}async createInferenceSessionHandler(t,e){let n=new So(e);return typeof t=="string"?await n.loadModel(t):await n.loadModel(t),new Ao(n)}},Qb=new Qi}),ea={};Pr(ea,{createReadStream:()=>Op,readFile:()=>eg,readFileSync:()=>tg});var eg,tg,Op,ta=L(()=>{eg=void 0,tg=void 0,Op=void 0}),ra={};Pr(ra,{join:()=>rg});var rg,na=L(()=>{rg=void 0}),Ap=me((t,e)=>{var n=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),function(s={}){var i=s,a,u;i.ready=new Promise((v,P)=>{a=v,u=P});var d=Object.assign({},i),o="./this.program",l=typeof window=="object",c=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",f="",p,g,b;if(h){var x=(ta(),rr(ea)),y=(na(),rr(ra));f=c?y.dirname(f)+"/":__dirname+"/",p=(v,P)=>(v=Te(v)?new URL(v):y.normalize(v),x.readFileSync(v,P?void 0:"utf8")),b=v=>(v=p(v,!0),v.buffer||(v=new Uint8Array(v)),v),g=(v,P,M,C=!0)=>{v=Te(v)?new URL(v):y.normalize(v),x.readFile(v,C?void 0:"utf8",(V,Q)=>{V?M(V):P(C?Q.buffer:Q)})},!i.thisProgram&&1"[Emscripten Module object]"}else(l||c)&&(c?f=self.location.href:typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),r&&(f=r),f.indexOf("blob:")!==0?f=f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):f="",p=v=>{var P=new XMLHttpRequest;return P.open("GET",v,!1),P.send(null),P.responseText},c&&(b=v=>{var P=new XMLHttpRequest;return P.open("GET",v,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),g=(v,P,M)=>{var C=new XMLHttpRequest;C.open("GET",v,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?P(C.response):M()},C.onerror=M,C.send(null)});var T=console.log.bind(console),S=console.error.bind(console);Object.assign(i,d),d=null,typeof WebAssembly!="object"&&we("no native wasm support detected");var E,N=!1,B,F,k,G,re;function ie(){var v=E.buffer;i.HEAP8=B=new Int8Array(v),i.HEAP16=new Int16Array(v),i.HEAPU8=F=new Uint8Array(v),i.HEAPU16=new Uint16Array(v),i.HEAP32=k=new Int32Array(v),i.HEAPU32=G=new Uint32Array(v),i.HEAPF32=new Float32Array(v),i.HEAPF64=re=new Float64Array(v)}var ge=[],X=[],K=[],he=0,se=null;function we(v){throw v="Aborted("+v+")",S(v),N=!0,v=new WebAssembly.RuntimeError(v+". Build with -sASSERTIONS for more info."),u(v),v}var ue=v=>v.startsWith("data:application/octet-stream;base64,"),Te=v=>v.startsWith("file://"),Le;if(Le="ort-wasm.wasm",!ue(Le)){var ze=Le;Le=i.locateFile?i.locateFile(ze,f):f+ze}function qe(v){if(b)return b(v);throw"both async and sync fetching of the wasm failed"}function Ie(v){if(l||c){if(typeof fetch=="function"&&!Te(v))return fetch(v,{credentials:"same-origin"}).then(P=>{if(!P.ok)throw"failed to load wasm binary file at '"+v+"'";return P.arrayBuffer()}).catch(()=>qe(v));if(g)return new Promise((P,M)=>{g(v,C=>P(new Uint8Array(C)),M)})}return Promise.resolve().then(()=>qe(v))}function $e(v,P,M){return Ie(v).then(C=>WebAssembly.instantiate(C,P)).then(C=>C).then(M,C=>{S(`failed to asynchronously prepare wasm: ${C}`),we(C)})}function Ce(v,P){var M=Le;return typeof WebAssembly.instantiateStreaming!="function"||ue(M)||Te(M)||h||typeof fetch!="function"?$e(M,v,P):fetch(M,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,v).then(P,function(V){return S(`wasm streaming compile failed: ${V}`),S("falling back to ArrayBuffer instantiation"),$e(M,v,P)}))}var Ze,Be={919888:(v,P,M,C)=>{if(typeof i>"u"||!i.za)return 1;if(v=Tt(v>>>0),v.startsWith("./")&&(v=v.substring(2)),v=i.za.get(v),!v)return 2;if(P>>>=0,M>>>=0,P+M>v.byteLength)return 3;try{return F.set(v.subarray(P,P+M),C>>>0>>>0),0}catch{return 4}}};function Se(v){this.xa=v-24,this.Ha=function(P){G[this.xa+4>>>2>>>0]=P},this.Ga=function(P){G[this.xa+8>>>2>>>0]=P},this.Aa=function(P,M){this.Fa(),this.Ha(P),this.Ga(M)},this.Fa=function(){G[this.xa+16>>>2>>>0]=0}}var Je=0,at=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ct=(v,P,M)=>{P>>>=0;var C=P+M;for(M=P;v[M]&&!(M>=C);)++M;if(16V?C+=String.fromCharCode(V):(V-=65536,C+=String.fromCharCode(55296|V>>10,56320|V&1023))}}else C+=String.fromCharCode(V)}return C},Tt=(v,P)=>(v>>>=0)?ct(F,v,P):"",gt=v=>{for(var P=0,M=0;M=C?P++:2047>=C?P+=2:55296<=C&&57343>=C?(P+=4,++M):P+=3}return P},ot=(v,P,M,C)=>{if(M>>>=0,!(0=de){var ke=v.charCodeAt(++Q);de=65536+((de&1023)<<10)|ke&1023}if(127>=de){if(M>=C)break;P[M++>>>0]=de}else{if(2047>=de){if(M+1>=C)break;P[M++>>>0]=192|de>>6}else{if(65535>=de){if(M+2>=C)break;P[M++>>>0]=224|de>>12}else{if(M+3>=C)break;P[M++>>>0]=240|de>>18,P[M++>>>0]=128|de>>12&63}P[M++>>>0]=128|de>>6&63}P[M++>>>0]=128|de&63}}return P[M>>>0]=0,M-V},st=v=>v%4===0&&(v%100!==0||v%400===0),_n=[0,31,60,91,121,152,182,213,244,274,305,335],Bt=[0,31,59,90,120,151,181,212,243,273,304,334],xn=v=>{var P=gt(v)+1,M=Lt(P);return M&&ot(v,F,M,P),M},et=[],Dt={},Ot=()=>{if(!Pt){var v={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",_:o||"./this.program"},P;for(P in Dt)Dt[P]===void 0?delete v[P]:v[P]=Dt[P];var M=[];for(P in v)M.push(`${P}=${v[P]}`);Pt=M}return Pt},Pt,wn=[null,[],[]],yt=[31,29,31,30,31,30,31,31,30,31,30,31],Wt=[31,28,31,30,31,30,31,31,30,31,30,31];function vn(v){var P=Array(gt(v)+1);return ot(v,P,0,P.length),P}function Mt(v,P,M,C){function V(I,pe,ve){for(I=typeof I=="number"?I.toString():I||"";I.lengthKt?-1:0rt-I.getDate())pe-=rt-I.getDate()+1,I.setDate(1),11>ve?I.setMonth(ve+1):(I.setMonth(0),I.setFullYear(I.getFullYear()+1));else{I.setDate(I.getDate()+pe);break}}return ve=new Date(I.getFullYear()+1,0,4),pe=ke(new Date(I.getFullYear(),0,4)),ve=ke(ve),0>=de(pe,I)?0>=de(ve,I)?I.getFullYear()+1:I.getFullYear():I.getFullYear()-1}v>>>=0,P>>>=0,M>>>=0,C>>>=0;var je=G[C+40>>>2>>>0];C={Da:k[C>>>2>>>0],Ca:k[C+4>>>2>>>0],va:k[C+8>>>2>>>0],ya:k[C+12>>>2>>>0],wa:k[C+16>>>2>>>0],ua:k[C+20>>>2>>>0],oa:k[C+24>>>2>>>0],ta:k[C+28>>>2>>>0],Ia:k[C+32>>>2>>>0],Ba:k[C+36>>>2>>>0],Ea:je?Tt(je):""},M=Tt(M),je={"%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 Ue in je)M=M.replace(new RegExp(Ue,"g"),je[Ue]);var qt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Yt="January February March April May June July August September October November December".split(" ");je={"%a":I=>qt[I.oa].substring(0,3),"%A":I=>qt[I.oa],"%b":I=>Yt[I.wa].substring(0,3),"%B":I=>Yt[I.wa],"%C":I=>Q((I.ua+1900)/100|0,2),"%d":I=>Q(I.ya,2),"%e":I=>V(I.ya,2," "),"%g":I=>He(I).toString().substring(2),"%G":I=>He(I),"%H":I=>Q(I.va,2),"%I":I=>(I=I.va,I==0?I=12:12{for(var pe=0,ve=0;ve<=I.wa-1;pe+=(st(I.ua+1900)?yt:Wt)[ve++]);return Q(I.ya+pe,3)},"%m":I=>Q(I.wa+1,2),"%M":I=>Q(I.Ca,2),"%n":()=>` +`,"%p":I=>0<=I.va&&12>I.va?"AM":"PM","%S":I=>Q(I.Da,2),"%t":()=>" ","%u":I=>I.oa||7,"%U":I=>Q(Math.floor((I.ta+7-I.oa)/7),2),"%V":I=>{var pe=Math.floor((I.ta+7-(I.oa+6)%7)/7);if(2>=(I.oa+371-I.ta-2)%7&&pe++,pe)pe==53&&(ve=(I.oa+371-I.ta)%7,ve==4||ve==3&&st(I.ua)||(pe=1));else{pe=52;var ve=(I.oa+7-I.ta-1)%7;(ve==4||ve==5&&st(I.ua%400-1))&&pe++}return Q(pe,2)},"%w":I=>I.oa,"%W":I=>Q(Math.floor((I.ta+7-(I.oa+6)%7)/7),2),"%y":I=>(I.ua+1900).toString().substring(2),"%Y":I=>I.ua+1900,"%z":I=>{I=I.Ba;var pe=0<=I;return I=Math.abs(I)/60,(pe?"+":"-")+("0000"+(I/60*100+I%60)).slice(-4)},"%Z":I=>I.Ea,"%%":()=>"%"},M=M.replace(/%%/g,"\0\0");for(Ue in je)M.includes(Ue)&&(M=M.replace(new RegExp(Ue,"g"),je[Ue](C)));return M=M.replace(/\0\0/g,"%"),Ue=vn(M),Ue.length>P?0:(B.set(Ue,v>>>0),Ue.length-1)}var qn={a:function(v,P,M){throw v>>>=0,new Se(v).Aa(P>>>0,M>>>0),Je=v,Je},e:function(){return 0},H:function(){},x:function(){},z:function(){},J:function(){return 0},F:function(){},A:function(){},E:function(){},g:function(){},y:function(){},v:function(){},G:function(){},w:function(){},k:()=>1,n:function(v,P,M){v=P+2097152>>>0<4194305-!!v?(v>>>0)+4294967296*P:NaN,M>>>=0,v=new Date(1e3*v),k[M>>>2>>>0]=v.getUTCSeconds(),k[M+4>>>2>>>0]=v.getUTCMinutes(),k[M+8>>>2>>>0]=v.getUTCHours(),k[M+12>>>2>>>0]=v.getUTCDate(),k[M+16>>>2>>>0]=v.getUTCMonth(),k[M+20>>>2>>>0]=v.getUTCFullYear()-1900,k[M+24>>>2>>>0]=v.getUTCDay(),k[M+28>>>2>>>0]=(v.getTime()-Date.UTC(v.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},o:function(v,P,M){v=P+2097152>>>0<4194305-!!v?(v>>>0)+4294967296*P:NaN,M>>>=0,v=new Date(1e3*v),k[M>>>2>>>0]=v.getSeconds(),k[M+4>>>2>>>0]=v.getMinutes(),k[M+8>>>2>>>0]=v.getHours(),k[M+12>>>2>>>0]=v.getDate(),k[M+16>>>2>>>0]=v.getMonth(),k[M+20>>>2>>>0]=v.getFullYear()-1900,k[M+24>>>2>>>0]=v.getDay(),k[M+28>>>2>>>0]=(st(v.getFullYear())?_n:Bt)[v.getMonth()]+v.getDate()-1|0,k[M+36>>>2>>>0]=-(60*v.getTimezoneOffset()),P=new Date(v.getFullYear(),6,1).getTimezoneOffset();var C=new Date(v.getFullYear(),0,1).getTimezoneOffset();k[M+32>>>2>>>0]=(P!=C&&v.getTimezoneOffset()==Math.min(C,P))|0},p:function(v){v>>>=0;var P=new Date(k[v+20>>>2>>>0]+1900,k[v+16>>>2>>>0],k[v+12>>>2>>>0],k[v+8>>>2>>>0],k[v+4>>>2>>>0],k[v>>>2>>>0],0),M=k[v+32>>>2>>>0],C=P.getTimezoneOffset(),V=new Date(P.getFullYear(),6,1).getTimezoneOffset(),Q=new Date(P.getFullYear(),0,1).getTimezoneOffset(),de=Math.min(Q,V);return 0>M?k[v+32>>>2>>>0]=+(V!=Q&&de==C):0>>2>>>0]=P.getDay(),k[v+28>>>2>>>0]=(st(P.getFullYear())?_n:Bt)[P.getMonth()]+P.getDate()-1|0,k[v>>>2>>>0]=P.getSeconds(),k[v+4>>>2>>>0]=P.getMinutes(),k[v+8>>>2>>>0]=P.getHours(),k[v+12>>>2>>>0]=P.getDate(),k[v+16>>>2>>>0]=P.getMonth(),k[v+20>>>2>>>0]=P.getYear(),v=P.getTime(),isNaN(v)?(k[Ht()>>>2>>>0]=61,v=-1):v/=1e3,On((Ze=v,1<=+Math.abs(Ze)?0>>0:~~+Math.ceil((Ze-+(~~Ze>>>0))/4294967296)>>>0:0)),v>>>0},l:function(){return-52},m:function(){},t:function(v,P,M){function C(He){return(He=He.toTimeString().match(/\(([A-Za-z ]+)\)$/))?He[1]:"GMT"}M>>>=0;var V=new Date().getFullYear(),Q=new Date(V,0,1),de=new Date(V,6,1);V=Q.getTimezoneOffset();var ke=de.getTimezoneOffset();G[v>>>0>>>2>>>0]=60*Math.max(V,ke),k[P>>>0>>>2>>>0]=+(V!=ke),v=C(Q),P=C(de),v=xn(v),P=xn(P),ke>>2>>>0]=v,G[M+4>>>2>>>0]=P):(G[M>>>2>>>0]=P,G[M+4>>>2>>>0]=v)},d:()=>{we("")},B:function(v,P,M){v>>>=0,P>>>=0,M>>>=0,et.length=0;for(var C;C=F[P++>>>0];){var V=C!=105;V&=C!=112,M+=V&&M%8?4:0,et.push(C==112?G[M>>>2>>>0]:C==105?k[M>>>2>>>0]:re[M>>>3>>>0]),M+=V?8:4}return Be[v].apply(null,et)},h:()=>Date.now(),u:function(){return 4294901760},b:()=>performance.now(),I:function(v,P,M){return P>>>=0,F.copyWithin(v>>>0>>>0,P>>>0,P+(M>>>0)>>>0)},s:function(v){v>>>=0;var P=F.length;if(4294901760=M;M*=2){var C=P*(1+.2/M);C=Math.min(C,v+100663296);var V=Math;C=Math.max(v,C);e:{V=(V.min.call(V,4294901760,C+(65536-C%65536)%65536)-E.buffer.byteLength+65535)/65536;try{E.grow(V),ie();var Q=1;break e}catch{}Q=void 0}if(Q)return!0}return!1},C:function(v,P){v>>>=0,P>>>=0;var M=0;return Ot().forEach((C,V)=>{var Q=P+M;for(V=G[v+4*V>>>2>>>0]=Q,Q=0;Q>>0>>>0]=C.charCodeAt(Q);B[V>>>0>>>0]=0,M+=C.length+1}),0},D:function(v,P){v>>>=0,P>>>=0;var M=Ot();G[v>>>2>>>0]=M.length;var C=0;return M.forEach(V=>C+=V.length+1),G[P>>>2>>>0]=C,0},f:()=>52,j:function(){return 52},q:function(){return 70},i:function(v,P,M,C){P>>>=0,M>>>=0,C>>>=0;for(var V=0,Q=0;Q>>2>>>0],ke=G[P+4>>>2>>>0];P+=8;for(var He=0;He>>0],Ue=wn[v];je===0||je===10?((v===1?T:S)(ct(Ue,0)),Ue.length=0):Ue.push(je)}V+=ke}return G[C>>>2>>>0]=V,0},r:Mt,c:function(v,P,M,C){return Mt(v>>>0,P>>>0,M>>>0,C>>>0)}},H=function(){function v(M){return H=M.exports,H=Nt(),E=H.K,ie(),X.unshift(H.L),he--,he==0&&se&&(M=se,se=null,M()),H}var P={a:qn};if(he++,i.instantiateWasm)try{return i.instantiateWasm(P,v)}catch(M){S(`Module.instantiateWasm callback failed with error: ${M}`),u(M)}return Ce(P,function(M){v(M.instance)}).catch(u),{}}();i._OrtInit=(v,P)=>(i._OrtInit=H.M)(v,P),i._OrtGetLastError=(v,P)=>(i._OrtGetLastError=H.N)(v,P),i._OrtCreateSessionOptions=(v,P,M,C,V,Q,de,ke,He,je)=>(i._OrtCreateSessionOptions=H.O)(v,P,M,C,V,Q,de,ke,He,je),i._OrtAppendExecutionProvider=(v,P)=>(i._OrtAppendExecutionProvider=H.P)(v,P),i._OrtAddFreeDimensionOverride=(v,P,M)=>(i._OrtAddFreeDimensionOverride=H.Q)(v,P,M),i._OrtAddSessionConfigEntry=(v,P,M)=>(i._OrtAddSessionConfigEntry=H.R)(v,P,M),i._OrtReleaseSessionOptions=v=>(i._OrtReleaseSessionOptions=H.S)(v),i._OrtCreateSession=(v,P,M)=>(i._OrtCreateSession=H.T)(v,P,M),i._OrtReleaseSession=v=>(i._OrtReleaseSession=H.U)(v),i._OrtGetInputOutputCount=(v,P,M)=>(i._OrtGetInputOutputCount=H.V)(v,P,M),i._OrtGetInputName=(v,P)=>(i._OrtGetInputName=H.W)(v,P),i._OrtGetOutputName=(v,P)=>(i._OrtGetOutputName=H.X)(v,P),i._OrtFree=v=>(i._OrtFree=H.Y)(v),i._OrtCreateTensor=(v,P,M,C,V,Q)=>(i._OrtCreateTensor=H.Z)(v,P,M,C,V,Q),i._OrtGetTensorData=(v,P,M,C,V)=>(i._OrtGetTensorData=H._)(v,P,M,C,V),i._OrtReleaseTensor=v=>(i._OrtReleaseTensor=H.$)(v),i._OrtCreateRunOptions=(v,P,M,C)=>(i._OrtCreateRunOptions=H.aa)(v,P,M,C),i._OrtAddRunConfigEntry=(v,P,M)=>(i._OrtAddRunConfigEntry=H.ba)(v,P,M),i._OrtReleaseRunOptions=v=>(i._OrtReleaseRunOptions=H.ca)(v),i._OrtCreateBinding=v=>(i._OrtCreateBinding=H.da)(v),i._OrtBindInput=(v,P,M)=>(i._OrtBindInput=H.ea)(v,P,M),i._OrtBindOutput=(v,P,M,C)=>(i._OrtBindOutput=H.fa)(v,P,M,C),i._OrtClearBoundOutputs=v=>(i._OrtClearBoundOutputs=H.ga)(v),i._OrtReleaseBinding=v=>(i._OrtReleaseBinding=H.ha)(v),i._OrtRunWithBinding=(v,P,M,C,V)=>(i._OrtRunWithBinding=H.ia)(v,P,M,C,V),i._OrtRun=(v,P,M,C,V,Q,de,ke)=>(i._OrtRun=H.ja)(v,P,M,C,V,Q,de,ke),i._OrtEndProfiling=v=>(i._OrtEndProfiling=H.ka)(v);var Ht=()=>(Ht=H.la)(),Lt=i._malloc=v=>(Lt=i._malloc=H.ma)(v);i._free=v=>(i._free=H.na)(v);var On=v=>(On=H.pa)(v),Gt=()=>(Gt=H.qa)(),Sn=v=>(Sn=H.ra)(v),ne=v=>(ne=H.sa)(v);function Nt(){var v=H;v=Object.assign({},v);var P=C=>()=>C()>>>0,M=C=>V=>C(V)>>>0;return v.la=P(v.la),v.ma=M(v.ma),v.qa=P(v.qa),v.sa=M(v.sa),v}i.stackAlloc=ne,i.stackSave=Gt,i.stackRestore=Sn,i.UTF8ToString=Tt,i.stringToUTF8=(v,P,M)=>ot(v,F,P,M),i.lengthBytesUTF8=gt;var Et;se=function v(){Et||At(),Et||(se=v)};function At(){if(!(0n)}),Pp=me(()=>{}),Ep=me(()=>{}),Dp={};Pr(Dp,{cpus:()=>ng});var ng,Lp=L(()=>{ng=void 0}),Cp=me((t,e)=>{var n=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),function(s={}){function i(){return K.buffer!=ue.buffer&&Ie(),ue}function a(){return K.buffer!=ue.buffer&&Ie(),Te}function u(){return K.buffer!=ue.buffer&&Ie(),Le}function d(){return K.buffer!=ue.buffer&&Ie(),ze}function o(){return K.buffer!=ue.buffer&&Ie(),qe}var l=s,c,h;l.ready=new Promise((m,w)=>{c=m,h=w});var f=Object.assign({},l),p="./this.program",g=(m,w)=>{throw w},b=typeof window=="object",x=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",T=l.ENVIRONMENT_IS_PTHREAD||!1,S="";function E(m){return l.locateFile?l.locateFile(m,S):S+m}var N,B,F;if(y){var k=(ta(),rr(ea)),G=(na(),rr(ra));S=x?G.dirname(S)+"/":__dirname+"/",N=(w,O)=>(w=gt(w)?new URL(w):G.normalize(w),k.readFileSync(w,O?void 0:"utf8")),F=w=>(w=N(w,!0),w.buffer||(w=new Uint8Array(w)),w),B=(w,O,A,j=!0)=>{w=gt(w)?new URL(w):G.normalize(w),k.readFile(w,j?void 0:"utf8",(z,Y)=>{z?A(z):O(j?Y.buffer:Y)})},!l.thisProgram&&1{throw process.exitCode=w,O},l.inspect=()=>"[Emscripten Module object]";let m;try{m=Pp()}catch(w){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),w}global.Worker=m.Worker}else(b||x)&&(x?S=self.location.href:typeof document<"u"&&document.currentScript&&(S=document.currentScript.src),typeof r<"u"&&r&&(S=r),S.indexOf("blob:")!==0?S=S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1):S="",y||(N=m=>{var w=new XMLHttpRequest;return w.open("GET",m,!1),w.send(null),w.responseText},x&&(F=m=>{var w=new XMLHttpRequest;return w.open("GET",m,!1),w.responseType="arraybuffer",w.send(null),new Uint8Array(w.response)}),B=(m,w,O)=>{var A=new XMLHttpRequest;A.open("GET",m,!0),A.responseType="arraybuffer",A.onload=()=>{A.status==200||A.status==0&&A.response?w(A.response):O()},A.onerror=O,A.send(null)}));y&&typeof performance>"u"&&(global.performance=Ep().performance);var re=console.log.bind(console),ie=console.error.bind(console);y&&(re=(...m)=>k.writeSync(1,m.join(" ")+` +`),ie=(...m)=>k.writeSync(2,m.join(" ")+` +`));var ge=re,X=ie;Object.assign(l,f),f=null,typeof WebAssembly!="object"&&ct("no native wasm support detected");var K,he,se=!1,we,ue,Te,Le,ze,qe;function Ie(){var m=K.buffer;l.HEAP8=ue=new Int8Array(m),l.HEAP16=new Int16Array(m),l.HEAPU8=Te=new Uint8Array(m),l.HEAPU16=new Uint16Array(m),l.HEAP32=Le=new Int32Array(m),l.HEAPU32=ze=new Uint32Array(m),l.HEAPF32=new Float32Array(m),l.HEAPF64=qe=new Float64Array(m)}var $e=16777216;if(T)K=l.wasmMemory;else if(l.wasmMemory)K=l.wasmMemory;else if(K=new WebAssembly.Memory({initial:$e/65536,maximum:65536,shared:!0}),!(K.buffer instanceof SharedArrayBuffer))throw X("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"),y&&X("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ie(),$e=K.buffer.byteLength;var Ce=[],Ze=[],Be=[],Se=0,Je=null;function at(){if(Se--,Se==0&&Je){var m=Je;Je=null,m()}}function ct(m){throw m="Aborted("+m+")",X(m),se=!0,we=1,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),h(m),m}var Tt=m=>m.startsWith("data:application/octet-stream;base64,"),gt=m=>m.startsWith("file://"),ot;ot="ort-wasm-threaded.wasm",Tt(ot)||(ot=E(ot));function st(m){if(F)return F(m);throw"both async and sync fetching of the wasm failed"}function _n(m){if(b||x){if(typeof fetch=="function"&&!gt(m))return fetch(m,{credentials:"same-origin"}).then(w=>{if(!w.ok)throw"failed to load wasm binary file at '"+m+"'";return w.arrayBuffer()}).catch(()=>st(m));if(B)return new Promise((w,O)=>{B(m,A=>w(new Uint8Array(A)),O)})}return Promise.resolve().then(()=>st(m))}function Bt(m,w,O){return _n(m).then(A=>WebAssembly.instantiate(A,w)).then(A=>A).then(O,A=>{X(`failed to asynchronously prepare wasm: ${A}`),ct(A)})}function xn(m,w){var O=ot;return typeof WebAssembly.instantiateStreaming!="function"||Tt(O)||gt(O)||y||typeof fetch!="function"?Bt(O,m,w):fetch(O,{credentials:"same-origin"}).then(A=>WebAssembly.instantiateStreaming(A,m).then(w,function(j){return X(`wasm streaming compile failed: ${j}`),X("falling back to ArrayBuffer instantiation"),Bt(O,m,w)}))}var et,Dt={921276:(m,w,O,A)=>{if(typeof l>"u"||!l.cb)return 1;if(m=Mt(m>>>0),m.startsWith("./")&&(m=m.substring(2)),m=l.cb.get(m),!m)return 2;if(w>>>=0,O>>>=0,A>>>=0,w+O>m.byteLength)return 3;try{return a().set(m.subarray(w,w+O),A>>>0),0}catch{return 4}}};function Ot(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}var Pt=m=>{m.terminate(),m.onmessage=()=>{}},wn=m=>{ne.Pa.length==0&&(Gt(),ne.Ya(ne.Pa[0]));var w=ne.Pa.pop();if(!w)return 6;ne.Qa.push(w),ne.Ma[m.Oa]=w,w.Oa=m.Oa;var O={cmd:"run",start_routine:m.kb,arg:m.hb,pthread_ptr:m.Oa};return y&&w.unref(),w.postMessage(O,m.qb),0},yt=0,Wt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,vn=(m,w,O)=>{w>>>=0;var A=w+O;for(O=w;m[O]&&!(O>=A);)++O;if(16j?A+=String.fromCharCode(j):(j-=65536,A+=String.fromCharCode(55296|j>>10,56320|j&1023))}}else A+=String.fromCharCode(j)}return A},Mt=(m,w)=>(m>>>=0)?vn(a(),m,w):"",qn=m=>{var w=vr();return m=m(),In(w),m};function H(m,w){var O=arguments.length-2,A=arguments;return qn(()=>{for(var j=Or(8*O),z=j>>>3,Y=0;Y>>0]=Me}return Mo(m,O,j,w)})}function Ht(m){if(T)return H(0,1,m);we=m,0{if(we=m,T)throw Et(m),"unwind";Ht(m)};function On(){for(var m=l.numThreads;m--;)Gt();Ce.unshift(()=>{Se++,Sn(()=>at())})}function Gt(){var m=E("ort-wasm-threaded.worker.js");m=new Worker(m),ne.Pa.push(m)}function Sn(m){T?m():Promise.all(ne.Pa.map(ne.Ya)).then(m)}var ne={Pa:[],Qa:[],bb:[],Ma:{},Wa(){T?(ne.receiveObjectTransfer=ne.jb,ne.threadInitTLS=ne.ab,ne.setExitStatus=ne.$a):On()},$a:m=>we=m,tb:["$terminateWorker"],lb:()=>{for(var m of ne.Qa)Pt(m);for(m of ne.Pa)Pt(m);ne.Pa=[],ne.Qa=[],ne.Ma=[]},Za:m=>{var w=m.Oa;delete ne.Ma[w],ne.Pa.push(m),ne.Qa.splice(ne.Qa.indexOf(m),1),m.Oa=0,_r(w)},jb(){},ab(){ne.bb.forEach(m=>m())},Ya:m=>new Promise(w=>{m.onmessage=z=>{z=z.data;var Y=z.cmd;if(z.targetThread&&z.targetThread!=An()){var Me=ne.Ma[z.targetThread];Me?Me.postMessage(z,z.transferList):X(`Internal error! Worker sent a message "${Y}" to target pthread ${z.targetThread}, but that thread no longer exists!`)}else Y==="checkMailbox"?Pn():Y==="spawnThread"?wn(z):Y==="cleanupThread"?ne.Za(ne.Ma[z.thread]):Y==="killThread"?(z=z.thread,Y=ne.Ma[z],delete ne.Ma[z],Pt(Y),_r(z),ne.Qa.splice(ne.Qa.indexOf(Y),1),Y.Oa=0):Y==="cancelThread"?ne.Ma[z.thread].postMessage({cmd:"cancel"}):Y==="loaded"?(m.loaded=!0,y&&!m.Oa&&m.unref(),w(m)):Y==="alert"?alert(`Thread ${z.threadId}: ${z.text}`):z.target==="setimmediate"?m.postMessage(z):Y==="callHandler"?l[z.handler](...z.args):Y&&X(`worker sent an unknown command ${Y}`)},m.onerror=z=>{throw X(`worker sent an error! ${z.filename}:${z.lineno}: ${z.message}`),z},y&&(m.on("message",z=>m.onmessage({data:z})),m.on("error",z=>m.onerror(z)));var O=[],A=["onExit"],j;for(j of A)l.hasOwnProperty(j)&&O.push(j);m.postMessage({cmd:"load",handlers:O,urlOrBlob:l.mainScriptUrlOrBlob||r,wasmMemory:K,wasmModule:he})})};l.PThread=ne;var Nt=m=>{for(;0{var m=An(),w=d()[m+52>>>2>>>0];m=d()[m+56>>>2>>>0],Bo(w,w-m),In(w)};function Et(m){if(T)return H(1,0,m);Lt(m)}var At=[],v;l.invokeEntryPoint=(m,w)=>{var O=At[m];O||(m>=At.length&&(At.length=m+1),At[m]=O=v.get(m)),m=O(w),0>>2>>>0]=w},this.fb=function(w){d()[this.Va+8>>>2>>>0]=w},this.Wa=function(w,O){this.eb(),this.gb(w),this.fb(O)},this.eb=function(){d()[this.Va+16>>>2>>>0]=0}}var M=0;function C(m,w,O,A){return T?H(2,1,m,w,O,A):V(m,w,O,A)}function V(m,w,O,A){if(m>>>=0,w>>>=0,O>>>=0,A>>>=0,typeof SharedArrayBuffer>"u")return X("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var j=[];return T&&j.length===0?C(m,w,O,A):(m={kb:O,Oa:m,hb:A,qb:j},T?(m.sb="spawnThread",postMessage(m,j),0):wn(m))}function Q(m,w,O){return T?H(3,1,m,w,O):0}function de(m,w){if(T)return H(4,1,m,w)}var ke=m=>{for(var w=0,O=0;O=A?w++:2047>=A?w+=2:55296<=A&&57343>=A?(w+=4,++O):w+=3}return w},He=(m,w,O,A)=>{if(O>>>=0,!(0=Y){var Me=m.charCodeAt(++z);Y=65536+((Y&1023)<<10)|Me&1023}if(127>=Y){if(O>=A)break;w[O++>>>0]=Y}else{if(2047>=Y){if(O+1>=A)break;w[O++>>>0]=192|Y>>6}else{if(65535>=Y){if(O+2>=A)break;w[O++>>>0]=224|Y>>12}else{if(O+3>=A)break;w[O++>>>0]=240|Y>>18,w[O++>>>0]=128|Y>>12&63}w[O++>>>0]=128|Y>>6&63}w[O++>>>0]=128|Y&63}}return w[O>>>0]=0,O-j},je=(m,w,O)=>He(m,a(),w,O);function Ue(m,w){if(T)return H(5,1,m,w)}function qt(m,w,O){if(T)return H(6,1,m,w,O)}function Yt(m,w,O){return T?H(7,1,m,w,O):0}function I(m,w){if(T)return H(8,1,m,w)}function pe(m,w,O){if(T)return H(9,1,m,w,O)}function ve(m,w,O,A){if(T)return H(10,1,m,w,O,A)}function rt(m,w,O,A){if(T)return H(11,1,m,w,O,A)}function Kt(m,w,O,A){if(T)return H(12,1,m,w,O,A)}function Ir(m){if(T)return H(13,1,m)}function Fr(m,w){if(T)return H(14,1,m,w)}function jr(m,w,O){if(T)return H(15,1,m,w,O)}function Yn(m){m>>>=0,typeof Atomics.rb=="function"&&(Atomics.rb(u(),m>>>2,m).value.then(Pn),m+=128,Atomics.store(u(),m>>>2,1))}l.__emscripten_thread_mailbox_await=Yn;var Pn=()=>{var m=An();if(m&&(Yn(m),m=No,!se))try{if(m(),!(0m%4===0&&(m%100!==0||m%400===0),Hr=[0,31,60,91,121,152,182,213,244,274,305,335],qr=[0,31,59,90,120,151,181,212,243,273,304,334];function Yr(m,w,O,A,j,z,Y,Me){return T?H(16,1,m,w,O,A,j,z,Y,Me):-52}function Xr(m,w,O,A,j,z,Y){if(T)return H(17,1,m,w,O,A,j,z,Y)}var Kr=m=>{var w=ke(m)+1,O=di(w);return O&&je(m,O,w),O},tr=[],lr={},Zr=()=>{if(!fr){var m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"},w;for(w in lr)lr[w]===void 0?delete m[w]:m[w]=lr[w];var O=[];for(w in m)O.push(`${w}=${m[w]}`);fr=O}return fr},fr;function Jr(m,w){if(T)return H(18,1,m,w);m>>>=0,w>>>=0;var O=0;return Zr().forEach((A,j)=>{var z=w+O;for(j=d()[m+4*j>>>2>>>0]=z,z=0;z>>0>>>0]=A.charCodeAt(z);i()[j>>>0>>>0]=0,O+=A.length+1}),0}function ti(m,w){if(T)return H(19,1,m,w);m>>>=0,w>>>=0;var O=Zr();d()[m>>>2>>>0]=O.length;var A=0;return O.forEach(j=>A+=j.length+1),d()[w>>>2>>>0]=A,0}function ni(m){return T?H(20,1,m):52}function ri(m,w,O,A){return T?H(21,1,m,w,O,A):52}function ii(m,w,O,A,j){return T?H(22,1,m,w,O,A,j):70}var Ns=[null,[],[]];function oi(m,w,O,A){if(T)return H(23,1,m,w,O,A);w>>>=0,O>>>=0,A>>>=0;for(var j=0,z=0;z>>2>>>0],Me=d()[w+4>>>2>>>0];w+=8;for(var it=0;it>>0],Qe=Ns[m];Ne===0||Ne===10?((m===1?ge:X)(vn(Qe,0)),Qe.length=0):Qe.push(Ne)}j+=Me}return d()[A>>>2>>>0]=j,0}var si=[31,29,31,30,31,30,31,31,30,31,30,31],ai=[31,28,31,30,31,30,31,31,30,31,30,31];function Rs(m){var w=Array(ke(m)+1);return He(m,w,0,w.length),w}var Bs=(m,w)=>{i().set(m,w>>>0)};function ui(m,w,O,A){function j(D,_e,Ae){for(D=typeof D=="number"?D.toString():D||"";D.length<_e;)D=Ae[0]+D;return D}function z(D,_e){return j(D,_e,"0")}function Y(D,_e){function Ae(Wo){return 0>Wo?-1:0It-D.getDate())_e-=It-D.getDate()+1,D.setDate(1),11>Ae?D.setMonth(Ae+1):(D.setMonth(0),D.setFullYear(D.getFullYear()+1));else{D.setDate(D.getDate()+_e);break}}return Ae=new Date(D.getFullYear()+1,0,4),_e=Me(new Date(D.getFullYear(),0,4)),Ae=Me(Ae),0>=Y(_e,D)?0>=Y(Ae,D)?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}m>>>=0,w>>>=0,O>>>=0,A>>>=0;var Ne=d()[A+40>>>2>>>0];A={ob:u()[A>>>2>>>0],nb:u()[A+4>>>2>>>0],Ta:u()[A+8>>>2>>>0],Xa:u()[A+12>>>2>>>0],Ua:u()[A+16>>>2>>>0],Sa:u()[A+20>>>2>>>0],Na:u()[A+24>>>2>>>0],Ra:u()[A+28>>>2>>>0],ub:u()[A+32>>>2>>>0],mb:u()[A+36>>>2>>>0],pb:Ne?Mt(Ne):""},O=Mt(O),Ne={"%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 Qe in Ne)O=O.replace(new RegExp(Qe,"g"),Ne[Qe]);var zo="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Vo="January February March April May June July August September October November December".split(" ");Ne={"%a":D=>zo[D.Na].substring(0,3),"%A":D=>zo[D.Na],"%b":D=>Vo[D.Ua].substring(0,3),"%B":D=>Vo[D.Ua],"%C":D=>z((D.Sa+1900)/100|0,2),"%d":D=>z(D.Xa,2),"%e":D=>j(D.Xa,2," "),"%g":D=>it(D).toString().substring(2),"%G":D=>it(D),"%H":D=>z(D.Ta,2),"%I":D=>(D=D.Ta,D==0?D=12:12{for(var _e=0,Ae=0;Ae<=D.Ua-1;_e+=(Rt(D.Sa+1900)?si:ai)[Ae++]);return z(D.Xa+_e,3)},"%m":D=>z(D.Ua+1,2),"%M":D=>z(D.nb,2),"%n":()=>` +`,"%p":D=>0<=D.Ta&&12>D.Ta?"AM":"PM","%S":D=>z(D.ob,2),"%t":()=>" ","%u":D=>D.Na||7,"%U":D=>z(Math.floor((D.Ra+7-D.Na)/7),2),"%V":D=>{var _e=Math.floor((D.Ra+7-(D.Na+6)%7)/7);if(2>=(D.Na+371-D.Ra-2)%7&&_e++,_e)_e==53&&(Ae=(D.Na+371-D.Ra)%7,Ae==4||Ae==3&&Rt(D.Sa)||(_e=1));else{_e=52;var Ae=(D.Na+7-D.Ra-1)%7;(Ae==4||Ae==5&&Rt(D.Sa%400-1))&&_e++}return z(_e,2)},"%w":D=>D.Na,"%W":D=>z(Math.floor((D.Ra+7-(D.Na+6)%7)/7),2),"%y":D=>(D.Sa+1900).toString().substring(2),"%Y":D=>D.Sa+1900,"%z":D=>{D=D.mb;var _e=0<=D;return D=Math.abs(D)/60,(_e?"+":"-")+("0000"+(D/60*100+D%60)).slice(-4)},"%Z":D=>D.pb,"%%":()=>"%"},O=O.replace(/%%/g,"\0\0");for(Qe in Ne)O.includes(Qe)&&(O=O.replace(new RegExp(Qe,"g"),Ne[Qe](A)));return O=O.replace(/\0\0/g,"%"),Qe=Rs(O),Qe.length>w?0:(Bs(Qe,m),Qe.length-1)}ne.Wa();var js=[Ht,Et,C,Q,de,Ue,qt,Yt,I,pe,ve,rt,Kt,Ir,Fr,jr,Yr,Xr,Jr,ti,ni,ri,ii,oi],zs={b:function(m,w,O){throw m>>>=0,new P(m).Wa(w>>>0,O>>>0),M=m,M},L:function(m){fi(m>>>0,!x,1,!b,131072,!1),ne.ab()},j:function(m){m>>>=0,T?postMessage({cmd:"cleanupThread",thread:m}):ne.Za(ne.Ma[m])},H:V,h:Q,S:de,D:Ue,F:qt,T:Yt,Q:I,J:pe,P:ve,n:rt,E:Kt,B:Ir,R:Fr,C:jr,p:()=>1,z:function(m,w){m>>>=0,m==w>>>0?setTimeout(()=>Pn()):T?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=ne.Ma[m])&&m.postMessage({cmd:"checkMailbox"})},I:function(m,w,O,A){w>>>=0,er.length=O,A=A>>>0>>>3;for(var j=0;j>>0];return m=0>m?Dt[-m-1]:js[m],ne.ib=w,w=m.apply(null,er),ne.ib=0,w},K:Yn,o:function(m){y&&ne.Ma[m>>>0].ref()},s:function(m,w,O){m=w+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*w:NaN,O>>>=0,m=new Date(1e3*m),u()[O>>>2>>>0]=m.getUTCSeconds(),u()[O+4>>>2>>>0]=m.getUTCMinutes(),u()[O+8>>>2>>>0]=m.getUTCHours(),u()[O+12>>>2>>>0]=m.getUTCDate(),u()[O+16>>>2>>>0]=m.getUTCMonth(),u()[O+20>>>2>>>0]=m.getUTCFullYear()-1900,u()[O+24>>>2>>>0]=m.getUTCDay(),m=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,u()[O+28>>>2>>>0]=m},t:function(m,w,O){m=w+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*w:NaN,O>>>=0,m=new Date(1e3*m),u()[O>>>2>>>0]=m.getSeconds(),u()[O+4>>>2>>>0]=m.getMinutes(),u()[O+8>>>2>>>0]=m.getHours(),u()[O+12>>>2>>>0]=m.getDate(),u()[O+16>>>2>>>0]=m.getMonth(),u()[O+20>>>2>>>0]=m.getFullYear()-1900,u()[O+24>>>2>>>0]=m.getDay(),w=(Rt(m.getFullYear())?Hr:qr)[m.getMonth()]+m.getDate()-1|0,u()[O+28>>>2>>>0]=w,u()[O+36>>>2>>>0]=-(60*m.getTimezoneOffset()),w=new Date(m.getFullYear(),6,1).getTimezoneOffset();var A=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=(w!=A&&m.getTimezoneOffset()==Math.min(A,w))|0,u()[O+32>>>2>>>0]=m},u:function(m){m>>>=0;var w=new Date(u()[m+20>>>2>>>0]+1900,u()[m+16>>>2>>>0],u()[m+12>>>2>>>0],u()[m+8>>>2>>>0],u()[m+4>>>2>>>0],u()[m>>>2>>>0],0),O=u()[m+32>>>2>>>0],A=w.getTimezoneOffset(),j=new Date(w.getFullYear(),6,1).getTimezoneOffset(),z=new Date(w.getFullYear(),0,1).getTimezoneOffset(),Y=Math.min(z,j);return 0>O?u()[m+32>>>2>>>0]=+(j!=z&&Y==A):0>>2>>>0]=w.getDay(),O=(Rt(w.getFullYear())?Hr:qr)[w.getMonth()]+w.getDate()-1|0,u()[m+28>>>2>>>0]=O,u()[m>>>2>>>0]=w.getSeconds(),u()[m+4>>>2>>>0]=w.getMinutes(),u()[m+8>>>2>>>0]=w.getHours(),u()[m+12>>>2>>>0]=w.getDate(),u()[m+16>>>2>>>0]=w.getMonth(),u()[m+20>>>2>>>0]=w.getYear(),m=w.getTime(),isNaN(m)?(u()[ci()>>>2>>>0]=61,m=-1):m/=1e3,Ro((et=m,1<=+Math.abs(et)?0>>0:~~+Math.ceil((et-+(~~et>>>0))/4294967296)>>>0:0)),m>>>0},q:Yr,r:Xr,y:function(m,w,O){function A(Ne){return(Ne=Ne.toTimeString().match(/\(([A-Za-z ]+)\)$/))?Ne[1]:"GMT"}m>>>=0,w>>>=0,O>>>=0;var j=new Date().getFullYear(),z=new Date(j,0,1),Y=new Date(j,6,1);j=z.getTimezoneOffset();var Me=Y.getTimezoneOffset(),it=Math.max(j,Me);d()[m>>>2>>>0]=60*it,u()[w>>>2>>>0]=+(j!=Me),m=A(z),w=A(Y),m=Kr(m),w=Kr(w),Me>>2>>>0]=m,d()[O+4>>>2>>>0]=w):(d()[O>>>2>>>0]=w,d()[O+4>>>2>>>0]=m)},c:()=>{ct("")},O:function(m,w,O){m>>>=0,w>>>=0,O>>>=0,tr.length=0;for(var A;A=a()[w++>>>0];){var j=A!=105;j&=A!=112,O+=j&&O%8?4:0,tr.push(A==112?d()[O>>>2>>>0]:A==105?u()[O>>>2>>>0]:o()[O>>>3>>>0]),O+=j?8:4}return Dt[m].apply(null,tr)},k:()=>{},i:()=>Date.now(),U:()=>{throw yt+=1,"unwind"},A:function(){return 4294901760},e:()=>performance.timeOrigin+performance.now(),f:()=>y?(Lp(),rr(Dp)).cpus().length:navigator.hardwareConcurrency,x:function(m){m>>>=0;var w=a().length;if(m<=w||4294901760=O;O*=2){var A=w*(1+.2/O);A=Math.min(A,m+100663296);var j=Math;A=Math.max(m,A);e:{j=(j.min.call(j,4294901760,A+(65536-A%65536)%65536)-K.buffer.byteLength+65535)/65536;try{K.grow(j),Ie();var z=1;break e}catch{}z=void 0}if(z)return!0}return!1},M:Jr,N:ti,G:Lt,g:ni,m:ri,v:ii,l:oi,a:K||l.wasmMemory,w:ui,d:function(m,w,O,A){return ui(m>>>0,w>>>0,O>>>0,A>>>0)}},J=function(){function m(O,A){return J=O.exports,J=Vs(),ne.bb.push(J.za),v=J.Aa,Ze.unshift(J.V),he=A,at(),J}var w={a:zs};if(Se++,l.instantiateWasm)try{return l.instantiateWasm(w,m)}catch(O){X(`Module.instantiateWasm callback failed with error: ${O}`),h(O)}return xn(w,function(O){m(O.instance,O.module)}).catch(h),{}}();l._OrtInit=(m,w)=>(l._OrtInit=J.W)(m,w),l._OrtGetLastError=(m,w)=>(l._OrtGetLastError=J.X)(m,w),l._OrtCreateSessionOptions=(m,w,O,A,j,z,Y,Me,it,Ne)=>(l._OrtCreateSessionOptions=J.Y)(m,w,O,A,j,z,Y,Me,it,Ne),l._OrtAppendExecutionProvider=(m,w)=>(l._OrtAppendExecutionProvider=J.Z)(m,w),l._OrtAddFreeDimensionOverride=(m,w,O)=>(l._OrtAddFreeDimensionOverride=J._)(m,w,O),l._OrtAddSessionConfigEntry=(m,w,O)=>(l._OrtAddSessionConfigEntry=J.$)(m,w,O),l._OrtReleaseSessionOptions=m=>(l._OrtReleaseSessionOptions=J.aa)(m),l._OrtCreateSession=(m,w,O)=>(l._OrtCreateSession=J.ba)(m,w,O),l._OrtReleaseSession=m=>(l._OrtReleaseSession=J.ca)(m),l._OrtGetInputOutputCount=(m,w,O)=>(l._OrtGetInputOutputCount=J.da)(m,w,O),l._OrtGetInputName=(m,w)=>(l._OrtGetInputName=J.ea)(m,w),l._OrtGetOutputName=(m,w)=>(l._OrtGetOutputName=J.fa)(m,w),l._OrtFree=m=>(l._OrtFree=J.ga)(m),l._OrtCreateTensor=(m,w,O,A,j,z)=>(l._OrtCreateTensor=J.ha)(m,w,O,A,j,z),l._OrtGetTensorData=(m,w,O,A,j)=>(l._OrtGetTensorData=J.ia)(m,w,O,A,j),l._OrtReleaseTensor=m=>(l._OrtReleaseTensor=J.ja)(m),l._OrtCreateRunOptions=(m,w,O,A)=>(l._OrtCreateRunOptions=J.ka)(m,w,O,A),l._OrtAddRunConfigEntry=(m,w,O)=>(l._OrtAddRunConfigEntry=J.la)(m,w,O),l._OrtReleaseRunOptions=m=>(l._OrtReleaseRunOptions=J.ma)(m),l._OrtCreateBinding=m=>(l._OrtCreateBinding=J.na)(m),l._OrtBindInput=(m,w,O)=>(l._OrtBindInput=J.oa)(m,w,O),l._OrtBindOutput=(m,w,O,A)=>(l._OrtBindOutput=J.pa)(m,w,O,A),l._OrtClearBoundOutputs=m=>(l._OrtClearBoundOutputs=J.qa)(m),l._OrtReleaseBinding=m=>(l._OrtReleaseBinding=J.ra)(m),l._OrtRunWithBinding=(m,w,O,A,j)=>(l._OrtRunWithBinding=J.sa)(m,w,O,A,j),l._OrtRun=(m,w,O,A,j,z,Y,Me)=>(l._OrtRun=J.ta)(m,w,O,A,j,z,Y,Me),l._OrtEndProfiling=m=>(l._OrtEndProfiling=J.ua)(m);var ci=()=>(ci=J.va)(),An=l._pthread_self=()=>(An=l._pthread_self=J.wa)(),di=l._malloc=m=>(di=l._malloc=J.xa)(m);l._free=m=>(l._free=J.ya)(m),l.__emscripten_tls_init=()=>(l.__emscripten_tls_init=J.za)();var fi=l.__emscripten_thread_init=(m,w,O,A,j,z)=>(fi=l.__emscripten_thread_init=J.Ba)(m,w,O,A,j,z);l.__emscripten_thread_crashed=()=>(l.__emscripten_thread_crashed=J.Ca)();var Mo=(m,w,O,A)=>(Mo=J.Da)(m,w,O,A),_r=m=>(_r=J.Ea)(m),wr=l.__emscripten_thread_exit=m=>(wr=l.__emscripten_thread_exit=J.Fa)(m),No=()=>(No=J.Ga)(),Ro=m=>(Ro=J.Ha)(m),Bo=(m,w)=>(Bo=J.Ia)(m,w),vr=()=>(vr=J.Ja)(),In=m=>(In=J.Ka)(m),Or=m=>(Or=J.La)(m);function Vs(){var m=J;m=Object.assign({},m);var w=A=>()=>A()>>>0,O=A=>j=>A(j)>>>0;return m.va=w(m.va),m.wa=w(m.wa),m.xa=O(m.xa),m.emscripten_main_runtime_thread_id=w(m.emscripten_main_runtime_thread_id),m.Ja=w(m.Ja),m.La=O(m.La),m}l.wasmMemory=K,l.stackAlloc=Or,l.stackSave=vr,l.stackRestore=In,l.keepRuntimeAlive=()=>0n)}),kp=me((t,e)=>{e.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\n'}),Np,ig,aa,sa,Po,Bp,ag,sg,ug,Rp,Ee,zr=L(()=>{Np=Ap(),ig=Cp(),sa=!1,Po=!1,Bp=!1,ag=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}},sg=()=>{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}},ug=(t,e)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Rp=async t=>{if(sa)return Promise.resolve();if(Po)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bp)throw new Error("previous call to 'initializeWebAssembly()' failed.");Po=!0;let e=t.initTimeout,n=t.numThreads,r=t.simd,s=ag(n),i=r&&sg(),a=t.wasmPaths,u=typeof a=="string"?a:void 0,d=ug(i,s),o=typeof a=="object"?a[d]:void 0,l=!1,c=[];if(e>0&&c.push(new Promise(h=>{setTimeout(()=>{l=!0,h()},e)})),c.push(new Promise((h,f)=>{let p=s?ig:Np,g={locateFile:(b,x)=>s&&b.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([kp()],{type:"text/javascript"})):b.endsWith(".wasm")?o||(u??x)+d:x+b};if(s)if(g.numThreads=n,typeof Blob>"u")g.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let b=`var ortWasmThreaded=${p.toString()};`;g.mainScriptUrlOrBlob=new Blob([b],{type:"text/javascript"})}p(g).then(b=>{Po=!1,sa=!0,aa=b,h()},b=>{Po=!1,Bp=!0,f(b)})})),await Promise.race(c),l)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ee=()=>{if(sa&&aa)return aa;throw new Error("WebAssembly is not initialized yet.")}}),De,bn,Oe,Eo=L(()=>{zr(),De=(t,e)=>{let n=Ee(),r=n.lengthBytesUTF8(t)+1,s=n._malloc(r);return n.stringToUTF8(t,s,r),e.push(s),s},bn=(t,e,n,r)=>{if(typeof t=="object"&&t!==null){if(n.has(t))throw new Error("Circular reference in options");n.add(t)}Object.entries(t).forEach(([s,i])=>{let a=e?e+s:s;if(typeof i=="object")bn(i,a+".",n,r);else if(typeof i=="string"||typeof i=="number")r(a,i.toString());else if(typeof i=="boolean")r(a,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},Oe=t=>{let e=Ee(),n=e.stackSave();try{let r=e.stackAlloc(8);e._OrtGetLastError(r,r+4);let s=e.HEAP32[r/4],i=e.HEAPU32[r/4+1],a=i?e.UTF8ToString(i):"";throw new Error(`${t} ERROR_CODE: ${s}, ERROR_MESSAGE: ${a}`)}finally{e.stackRestore(n)}}}),Mp,Gp=L(()=>{zr(),Eo(),Mp=t=>{let e=Ee(),n=0,r=[],s=t||{};try{if(t?.logSeverityLevel===void 0)s.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(s.terminate=!1);let i=0;return t?.tag!==void 0&&(i=De(t.tag,r)),n=e._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,i),n===0&&Oe("Can't create run options."),t?.extra!==void 0&&bn(t.extra,"",new WeakSet,(a,u)=>{let d=De(a,r),o=De(u,r);e._OrtAddRunConfigEntry(n,d,o)!==0&&Oe(`Can't set a run config entry: ${a} - ${u}.`)}),[n,r]}catch(i){throw n!==0&&e._OrtReleaseRunOptions(n),r.forEach(a=>e._free(a)),i}}}),lg,fg,cg,pg,Up,zp=L(()=>{zr(),Eo(),lg=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}`)}},fg=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},cg=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(t.enableMemPattern=!1)},pg=(t,e,n)=>{for(let r of e){let s=typeof r=="string"?r:r.name;switch(s){case"webnn":if(s="WEBNN",typeof r!="string"){let a=r;if(a?.deviceType){let u=De("deviceType",n),d=De(a.deviceType,n);Ee()._OrtAddSessionConfigEntry(t,u,d)!==0&&Oe(`Can't set a session config entry: 'deviceType' - ${a.deviceType}.`)}if(a?.numThreads){let u=a.numThreads;(typeof u!="number"||!Number.isInteger(u)||u<0)&&(u=0);let d=De("numThreads",n),o=De(u.toString(),n);Ee()._OrtAddSessionConfigEntry(t,d,o)!==0&&Oe(`Can't set a session config entry: 'numThreads' - ${a.numThreads}.`)}if(a?.powerPreference){let u=De("powerPreference",n),d=De(a.powerPreference,n);Ee()._OrtAddSessionConfigEntry(t,u,d)!==0&&Oe(`Can't set a session config entry: 'powerPreference' - ${a.powerPreference}.`)}}break;case"webgpu":if(s="JS",typeof r!="string"){let a=r;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let u=De("preferredLayout",n),d=De(a.preferredLayout,n);Ee()._OrtAddSessionConfigEntry(t,u,d)!==0&&Oe(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let i=De(s,n);Ee()._OrtAppendExecutionProvider(t,i)!==0&&Oe(`Can't append execution provider: ${s}.`)}},Up=t=>{let e=Ee(),n=0,r=[],s=t||{};cg(s);try{let i=lg(s.graphOptimizationLevel??"all"),a=fg(s.executionMode??"sequential"),u=typeof s.logId=="string"?De(s.logId,r):0,d=s.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let o=s.logVerbosityLevel??0;if(!Number.isInteger(o)||o<0||o>4)throw new Error(`log verbosity level is not valid: ${o}`);let l=typeof s.optimizedModelFilePath=="string"?De(s.optimizedModelFilePath,r):0;if(n=e._OrtCreateSessionOptions(i,!!s.enableCpuMemArena,!!s.enableMemPattern,a,!!s.enableProfiling,0,u,d,o,l),n===0&&Oe("Can't create session options."),s.executionProviders&&pg(n,s.executionProviders,r),s.freeDimensionOverrides)for(let[c,h]of Object.entries(s.freeDimensionOverrides)){if(typeof c!="string")throw new Error(`free dimension override name must be a string: ${c}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let f=De(c,r);e._OrtAddFreeDimensionOverride(n,f,h)!==0&&Oe(`Can't set a free dimension override: ${c} - ${h}.`)}return s.extra!==void 0&&bn(s.extra,"",new WeakSet,(c,h)=>{let f=De(c,r),p=De(h,r);e._OrtAddSessionConfigEntry(n,f,p)!==0&&Oe(`Can't set a session config entry: ${c} - ${h}.`)}),[n,r]}catch(i){throw n!==0&&e._OrtReleaseSessionOptions(n),r.forEach(a=>e._free(a)),i}}}),ua,Vp,la,Wp,Hp,Do,qp,fa=L(()=>{ua=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}`)}},Vp=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}`)}},la=t=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][t],Wp=t=>{switch(t){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Hp=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}`)}},Do=t=>t==="float32"||t==="int32"||t==="int64"||t==="bool"||t==="float16"||t==="uint32",qp=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}`)}}}),gn,ca=L(()=>{gn=async t=>{if(typeof t=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let n=(void 0)(t),r=[];for await(let s of n)r.push(s);return new Uint8Array(Buffer.concat(r))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let n=e.headers.get("Content-Length"),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let s=e.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(u){if(u instanceof RangeError){let d=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let a=0;for(;;){let{done:u,value:d}=await s.read();if(u)break;let o=d.byteLength;new Uint8Array(i,a,o).set(d),a+=o}return new Uint8Array(i,0,r)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),dg,Yp,Xp,yn,hg,pa,Kp,Jp,jp,Zp,Qp,ed,td=L(()=>{Gp(),zp(),fa(),zr(),Eo(),ca(),dg=(t,e)=>{Ee()._OrtInit(t,e)!==0&&Oe("Can't initialize onnxruntime.")},Yp=async t=>{dg(t.wasm.numThreads,Hp(t.logLevel))},Xp=async(t,e)=>{},yn=new Map,hg=t=>{let e=Ee(),n=e.stackSave();try{let r=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,r,r+4)!==0&&Oe("Can't get session input/output count."),[e.HEAP32[r/4],e.HEAP32[r/4+1]]}finally{e.stackRestore(n)}},pa=t=>{let e=Ee(),n=e._malloc(t.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,n),[n,t.byteLength]},Kp=async(t,e)=>{let n,r,s=Ee();Array.isArray(t)?[n,r]=t:t.buffer===s.HEAPU8.buffer?[n,r]=[t.byteOffset,t.byteLength]:[n,r]=pa(t);let i=0,a=0,u=[],d=[],o=[];try{if([a,u]=Up(e),e?.externalData&&s.mountExternalData){let b=[];for(let x of e.externalData){let y=typeof x=="string"?x:x.path;b.push(gn(typeof x=="string"?x:x.data).then(T=>{s.mountExternalData(y,T)}))}await Promise.all(b)}i=s._OrtCreateSession(n,r,a),i===0&&Oe("Can't create a session.");let[l,c]=hg(i),h=[],f=[],p=[];for(let b=0;bs._OrtFree(c)),o.forEach(c=>s._OrtFree(c)),i!==0&&s._OrtReleaseSession(i),l}finally{s._free(n),a!==0&&s._OrtReleaseSessionOptions(a),u.forEach(l=>s._free(l)),s.unmountExternalData?.()}},Jp=t=>{let e=Ee(),n=yn.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[r,s,i,a]=n;a&&e._OrtReleaseBinding(a.handle),e.jsepUnregisterBuffers?.(t),s.forEach(u=>e._OrtFree(u)),i.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(r),yn.delete(t)},jp=(t,e,n,r,s)=>{if(!t){e.push(0);return}let i=Ee(),a=t[0],u=t[1],d=t[3],o,l;if(a==="string"&&d==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(d==="gpu-buffer"){let f=t[2].gpuBuffer,p=la(ua(a));l=u.reduce((g,b)=>g*b,1)*p,o=i.jsepRegisterBuffer(r,s,f,l)}else{let f=t[2];if(Array.isArray(f)){l=4*f.length,o=i._malloc(l),n.push(o);let p=o/4;for(let g=0;gi.HEAP32[f++]=g);let p=i._OrtCreateTensor(ua(a),o,l,h,u.length,qp(d));p===0&&Oe(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(p)}finally{i.stackRestore(c)}},Zp=async(t,e,n,r,s,i)=>{let a=Ee(),u=yn.get(t);if(!u)throw new Error(`cannot run inference. invalid session id: ${t}`);let[d,o,l,c]=u,h=e.length,f=r.length,p=0,g=[],b=[],x=[],y=[],T=a.stackSave(),S=a.stackAlloc(h*4),E=a.stackAlloc(h*4),N=a.stackAlloc(f*4),B=a.stackAlloc(f*4);try{[p,g]=Mp(i);for(let X=0;XBe*Se,1);ue=Vp(ze);let Ze=c?.outputPreferredLocations[r[X]];if(ue==="string"){if(Ze==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Be=[],Se=Te/4;for(let Je=0;Je0){let Be=a.jsepGetBuffer(Te),Se=la(ze);if(Se===void 0||!Do(ue))throw new Error(`Unsupported data type: ${ue}`);we=!0,ge.push([ue,$e,{gpuBuffer:Be,download:a.jsepCreateDownloader(Be,Ce*Se,ue),dispose:()=>{a._OrtReleaseTensor(K)}},"gpu-buffer"])}else{let Be=Wp(ue),Se=new Be(Ce);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Te,Te+Se.byteLength)),ge.push([ue,$e,Se,"cpu"])}}finally{a.stackRestore(he),ue==="string"&&Te&&a._free(Te),we||a._OrtReleaseTensor(K)}}return c&&a._OrtClearBoundOutputs(c.handle),ge}finally{a.stackRestore(T),b.forEach(F=>a._OrtReleaseTensor(F)),x.forEach(F=>a._OrtReleaseTensor(F)),y.forEach(F=>a._free(F)),p!==0&&a._OrtReleaseRunOptions(p),g.forEach(F=>a._free(F))}},Qp=t=>{let e=Ee(),n=yn.get(t);if(!n)throw new Error("invalid session id");let r=n[0],s=e._OrtEndProfiling(r);s===0&&Oe("Can't get an profile file name."),e._OrtFree(s)},ed=t=>{let e=[];for(let n of t){let r=n[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),rd=me((t,e)=>{e.exports='/*!\n * ONNX Runtime Web v1.17.1\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var Et=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Xr=Object.getOwnPropertyNames;var Qr=Object.prototype.hasOwnProperty;var St=(u,d)=>()=>(u&&(d=u(u=0)),d);var et=(u,d)=>()=>(d||u((d={exports:{}}).exports,d),d.exports),Tt=(u,d)=>{for(var a in d)Et(u,a,{get:d[a],enumerable:!0})},Zr=(u,d,a,h)=>{if(d&&typeof d=="object"||typeof d=="function")for(let l of Xr(d))!Qr.call(u,l)&&l!==a&&Et(u,l,{get:()=>d[l],enumerable:!(h=Jr(d,l))||h.enumerable});return u};var tt=u=>Zr(Et({},"__esModule",{value:!0}),u);var At={};Tt(At,{createReadStream:()=>dr,readFile:()=>Kr,readFileSync:()=>en});var Kr,en,dr,Mt=St(()=>{Kr=void 0,en=void 0,dr=void 0});var Ct={};Tt(Ct,{join:()=>tn});var tn,Dt=St(()=>{tn=void 0});var gr=et((mr,xt)=>{"use strict";var pr=(()=>{var u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(u=u||__filename),function(d={}){var a=d,h,l;a.ready=new Promise((r,o)=>{h=r,l=o});var w=Object.assign({},a),g="./this.program",i=typeof window=="object",A=typeof importScripts=="function",D=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I="",B,F,U;if(D){var k=(Mt(),tt(At)),L=(Dt(),tt(Ct));I=A?L.dirname(I)+"/":__dirname+"/",B=(r,o)=>(r=ye(r)?new URL(r):L.normalize(r),k.readFileSync(r,o?void 0:"utf8")),U=r=>(r=B(r,!0),r.buffer||(r=new Uint8Array(r)),r),F=(r,o,s,m=!0)=>{r=ye(r)?new URL(r):L.normalize(r),k.readFile(r,m?void 0:"utf8",(O,S)=>{O?s(O):o(m?S.buffer:S)})},!a.thisProgram&&1"[Emscripten Module object]"}else(i||A)&&(A?I=self.location.href:typeof document<"u"&&document.currentScript&&(I=document.currentScript.src),u&&(I=u),I.indexOf("blob:")!==0?I=I.substr(0,I.replace(/[?#].*/,"").lastIndexOf("/")+1):I="",B=r=>{var o=new XMLHttpRequest;return o.open("GET",r,!1),o.send(null),o.responseText},A&&(U=r=>{var o=new XMLHttpRequest;return o.open("GET",r,!1),o.responseType="arraybuffer",o.send(null),new Uint8Array(o.response)}),F=(r,o,s)=>{var m=new XMLHttpRequest;m.open("GET",r,!0),m.responseType="arraybuffer",m.onload=()=>{m.status==200||m.status==0&&m.response?o(m.response):s()},m.onerror=s,m.send(null)});var _=console.log.bind(console),x=console.error.bind(console);Object.assign(a,w),w=null,typeof WebAssembly!="object"&&de("no native wasm support detected");var N,he=!1,ie,ae,E,Y,ue;function Re(){var r=N.buffer;a.HEAP8=ie=new Int8Array(r),a.HEAP16=new Int16Array(r),a.HEAPU8=ae=new Uint8Array(r),a.HEAPU16=new Uint16Array(r),a.HEAP32=E=new Int32Array(r),a.HEAPU32=Y=new Uint32Array(r),a.HEAPF32=new Float32Array(r),a.HEAPF64=ue=new Float64Array(r)}var Ie=[],ee=[],j=[],ce=0,P=null,te=null;function de(r){throw r="Aborted("+r+")",x(r),he=!0,r=new WebAssembly.RuntimeError(r+". Build with -sASSERTIONS for more info."),l(r),r}var ge=r=>r.startsWith("data:application/octet-stream;base64,"),ye=r=>r.startsWith("file://"),J;if(J="ort-wasm.wasm",!ge(J)){var fe=J;J=a.locateFile?a.locateFile(fe,I):I+fe}function we(r){if(U)return U(r);throw"both async and sync fetching of the wasm failed"}function Ae(r){if(i||A){if(typeof fetch=="function"&&!ye(r))return fetch(r,{credentials:"same-origin"}).then(o=>{if(!o.ok)throw"failed to load wasm binary file at \'"+r+"\'";return o.arrayBuffer()}).catch(()=>we(r));if(F)return new Promise((o,s)=>{F(r,m=>o(new Uint8Array(m)),s)})}return Promise.resolve().then(()=>we(r))}function Me(r,o,s){return Ae(r).then(m=>WebAssembly.instantiate(m,o)).then(m=>m).then(s,m=>{x(`failed to asynchronously prepare wasm: ${m}`),de(m)})}function Fe(r,o){var s=J;return typeof WebAssembly.instantiateStreaming!="function"||ge(s)||ye(s)||D||typeof fetch!="function"?Me(s,r,o):fetch(s,{credentials:"same-origin"}).then(m=>WebAssembly.instantiateStreaming(m,r).then(o,function(O){return x(`wasm streaming compile failed: ${O}`),x("falling back to ArrayBuffer instantiation"),Me(s,r,o)}))}var Ee,pe={919888:(r,o,s,m)=>{if(typeof a>"u"||!a.za)return 1;if(r=be(r>>>0),r.startsWith("./")&&(r=r.substring(2)),r=a.za.get(r),!r)return 2;if(o>>>=0,s>>>=0,o+s>r.byteLength)return 3;try{return ae.set(r.subarray(o,o+s),m>>>0>>>0),0}catch{return 4}}};function Oe(r){this.xa=r-24,this.Ha=function(o){Y[this.xa+4>>>2>>>0]=o},this.Ga=function(o){Y[this.xa+8>>>2>>>0]=o},this.Aa=function(o,s){this.Fa(),this.Ha(o),this.Ga(s)},this.Fa=function(){Y[this.xa+16>>>2>>>0]=0}}var ve=0,re=0,Z=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ce=(r,o,s)=>{o>>>=0;var m=o+s;for(s=o;r[s]&&!(s>=m);)++s;if(16O?m+=String.fromCharCode(O):(O-=65536,m+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else m+=String.fromCharCode(O)}return m},be=(r,o)=>(r>>>=0)?Ce(ae,r,o):"",_e=r=>{for(var o=0,s=0;s=m?o++:2047>=m?o+=2:55296<=m&&57343>=m?(o+=4,++s):o+=3}return o},ke=(r,o,s,m)=>{if(s>>>=0,!(0=R){var K=r.charCodeAt(++S);R=65536+((R&1023)<<10)|K&1023}if(127>=R){if(s>=m)break;o[s++>>>0]=R}else{if(2047>=R){if(s+1>=m)break;o[s++>>>0]=192|R>>6}else{if(65535>=R){if(s+2>=m)break;o[s++>>>0]=224|R>>12}else{if(s+3>=m)break;o[s++>>>0]=240|R>>18,o[s++>>>0]=128|R>>12&63}o[s++>>>0]=128|R>>6&63}o[s++>>>0]=128|R&63}}return o[s>>>0]=0,s-O},Ue=r=>r%4===0&&(r%100!==0||r%400===0),ze=[0,31,60,91,121,152,182,213,244,274,305,335],at=[0,31,59,90,120,151,181,212,243,273,304,334],De=r=>{var o=_e(r)+1,s=st(o);return s&&ke(r,ae,s,o),s},Ne=[],Pe={},He=()=>{if(!$e){var r={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",_:g||"./this.program"},o;for(o in Pe)Pe[o]===void 0?delete r[o]:r[o]=Pe[o];var s=[];for(o in r)s.push(`${o}=${r[o]}`);$e=s}return $e},$e,Le=[null,[],[]],qe=[31,29,31,30,31,30,31,31,30,31,30,31],Ve=[31,28,31,30,31,30,31,31,30,31,30,31];function Ge(r){var o=Array(_e(r)+1);return ke(r,o,0,o.length),o}function ot(r,o,s,m){function O(c,W,G){for(c=typeof c=="number"?c.toString():c||"";c.lengthKe?-1:0Se-c.getDate())W-=Se-c.getDate()+1,c.setDate(1),11>G?c.setMonth(G+1):(c.setMonth(0),c.setFullYear(c.getFullYear()+1));else{c.setDate(c.getDate()+W);break}}return G=new Date(c.getFullYear()+1,0,4),W=K(new Date(c.getFullYear(),0,4)),G=K(G),0>=R(W,c)?0>=R(G,c)?c.getFullYear()+1:c.getFullYear():c.getFullYear()-1}r>>>=0,o>>>=0,s>>>=0,m>>>=0;var oe=Y[m+40>>>2>>>0];m={Da:E[m>>>2>>>0],Ca:E[m+4>>>2>>>0],va:E[m+8>>>2>>>0],ya:E[m+12>>>2>>>0],wa:E[m+16>>>2>>>0],ua:E[m+20>>>2>>>0],oa:E[m+24>>>2>>>0],ta:E[m+28>>>2>>>0],Ia:E[m+32>>>2>>>0],Ba:E[m+36>>>2>>>0],Ea:oe?be(oe):""},s=be(s),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 se in oe)s=s.replace(new RegExp(se,"g"),oe[se]);var Qe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ze="January February March April May June July August September October November December".split(" ");oe={"%a":c=>Qe[c.oa].substring(0,3),"%A":c=>Qe[c.oa],"%b":c=>Ze[c.wa].substring(0,3),"%B":c=>Ze[c.wa],"%C":c=>S((c.ua+1900)/100|0,2),"%d":c=>S(c.ya,2),"%e":c=>O(c.ya,2," "),"%g":c=>le(c).toString().substring(2),"%G":c=>le(c),"%H":c=>S(c.va,2),"%I":c=>(c=c.va,c==0?c=12:12{for(var W=0,G=0;G<=c.wa-1;W+=(Ue(c.ua+1900)?qe:Ve)[G++]);return S(c.ya+W,3)},"%m":c=>S(c.wa+1,2),"%M":c=>S(c.Ca,2),"%n":()=>`\n`,"%p":c=>0<=c.va&&12>c.va?"AM":"PM","%S":c=>S(c.Da,2),"%t":()=>" ","%u":c=>c.oa||7,"%U":c=>S(Math.floor((c.ta+7-c.oa)/7),2),"%V":c=>{var W=Math.floor((c.ta+7-(c.oa+6)%7)/7);if(2>=(c.oa+371-c.ta-2)%7&&W++,W)W==53&&(G=(c.oa+371-c.ta)%7,G==4||G==3&&Ue(c.ua)||(W=1));else{W=52;var G=(c.oa+7-c.ta-1)%7;(G==4||G==5&&Ue(c.ua%400-1))&&W++}return S(W,2)},"%w":c=>c.oa,"%W":c=>S(Math.floor((c.ta+7-(c.oa+6)%7)/7),2),"%y":c=>(c.ua+1900).toString().substring(2),"%Y":c=>c.ua+1900,"%z":c=>{c=c.Ba;var W=0<=c;return c=Math.abs(c)/60,(W?"+":"-")+("0000"+(c/60*100+c%60)).slice(-4)},"%Z":c=>c.Ea,"%%":()=>"%"},s=s.replace(/%%/g,"\\0\\0");for(se in oe)s.includes(se)&&(s=s.replace(new RegExp(se,"g"),oe[se](m)));return s=s.replace(/\\0\\0/g,"%"),se=Ge(s),se.length>o?0:(ie.set(se,r>>>0),se.length-1)}var $={a:function(r,o,s){throw r>>>=0,new Oe(r).Aa(o>>>0,s>>>0),ve=r,re++,ve},e:function(){return 0},H:function(){},x:function(){},z:function(){},J:function(){return 0},F:function(){},A:function(){},E:function(){},g:function(){},y:function(){},v:function(){},G:function(){},w:function(){},k:()=>1,n:function(r,o,s){r=o+2097152>>>0<4194305-!!r?(r>>>0)+4294967296*o:NaN,s>>>=0,r=new Date(1e3*r),E[s>>>2>>>0]=r.getUTCSeconds(),E[s+4>>>2>>>0]=r.getUTCMinutes(),E[s+8>>>2>>>0]=r.getUTCHours(),E[s+12>>>2>>>0]=r.getUTCDate(),E[s+16>>>2>>>0]=r.getUTCMonth(),E[s+20>>>2>>>0]=r.getUTCFullYear()-1900,E[s+24>>>2>>>0]=r.getUTCDay(),E[s+28>>>2>>>0]=(r.getTime()-Date.UTC(r.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},o:function(r,o,s){r=o+2097152>>>0<4194305-!!r?(r>>>0)+4294967296*o:NaN,s>>>=0,r=new Date(1e3*r),E[s>>>2>>>0]=r.getSeconds(),E[s+4>>>2>>>0]=r.getMinutes(),E[s+8>>>2>>>0]=r.getHours(),E[s+12>>>2>>>0]=r.getDate(),E[s+16>>>2>>>0]=r.getMonth(),E[s+20>>>2>>>0]=r.getFullYear()-1900,E[s+24>>>2>>>0]=r.getDay(),E[s+28>>>2>>>0]=(Ue(r.getFullYear())?ze:at)[r.getMonth()]+r.getDate()-1|0,E[s+36>>>2>>>0]=-(60*r.getTimezoneOffset()),o=new Date(r.getFullYear(),6,1).getTimezoneOffset();var m=new Date(r.getFullYear(),0,1).getTimezoneOffset();E[s+32>>>2>>>0]=(o!=m&&r.getTimezoneOffset()==Math.min(m,o))|0},p:function(r){r>>>=0;var o=new Date(E[r+20>>>2>>>0]+1900,E[r+16>>>2>>>0],E[r+12>>>2>>>0],E[r+8>>>2>>>0],E[r+4>>>2>>>0],E[r>>>2>>>0],0),s=E[r+32>>>2>>>0],m=o.getTimezoneOffset(),O=new Date(o.getFullYear(),6,1).getTimezoneOffset(),S=new Date(o.getFullYear(),0,1).getTimezoneOffset(),R=Math.min(S,O);return 0>s?E[r+32>>>2>>>0]=+(O!=S&&R==m):0>>2>>>0]=o.getDay(),E[r+28>>>2>>>0]=(Ue(o.getFullYear())?ze:at)[o.getMonth()]+o.getDate()-1|0,E[r>>>2>>>0]=o.getSeconds(),E[r+4>>>2>>>0]=o.getMinutes(),E[r+8>>>2>>>0]=o.getHours(),E[r+12>>>2>>>0]=o.getDate(),E[r+16>>>2>>>0]=o.getMonth(),E[r+20>>>2>>>0]=o.getYear(),r=o.getTime(),isNaN(r)?(E[Ye()>>>2>>>0]=61,r=-1):r/=1e3,Je((Ee=r,1<=+Math.abs(Ee)?0>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)),r>>>0},l:function(){return-52},m:function(){},t:function(r,o,s){function m(le){return(le=le.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?le[1]:"GMT"}s>>>=0;var O=new Date().getFullYear(),S=new Date(O,0,1),R=new Date(O,6,1);O=S.getTimezoneOffset();var K=R.getTimezoneOffset();Y[r>>>0>>>2>>>0]=60*Math.max(O,K),E[o>>>0>>>2>>>0]=+(O!=K),r=m(S),o=m(R),r=De(r),o=De(o),K>>2>>>0]=r,Y[s+4>>>2>>>0]=o):(Y[s>>>2>>>0]=o,Y[s+4>>>2>>>0]=r)},d:()=>{de("")},B:function(r,o,s){r>>>=0,o>>>=0,s>>>=0,Ne.length=0;for(var m;m=ae[o++>>>0];){var O=m!=105;O&=m!=112,s+=O&&s%8?4:0,Ne.push(m==112?Y[s>>>2>>>0]:m==105?E[s>>>2>>>0]:ue[s>>>3>>>0]),s+=O?8:4}return pe[r].apply(null,Ne)},h:()=>Date.now(),u:function(){return 4294901760},b:()=>performance.now(),I:function(r,o,s){return o>>>=0,ae.copyWithin(r>>>0>>>0,o>>>0,o+(s>>>0)>>>0)},s:function(r){r>>>=0;var o=ae.length;if(4294901760=s;s*=2){var m=o*(1+.2/s);m=Math.min(m,r+100663296);var O=Math;m=Math.max(r,m);e:{O=(O.min.call(O,4294901760,m+(65536-m%65536)%65536)-N.buffer.byteLength+65535)/65536;try{N.grow(O),Re();var S=1;break e}catch{}S=void 0}if(S)return!0}return!1},C:function(r,o){r>>>=0,o>>>=0;var s=0;return He().forEach((m,O)=>{var S=o+s;for(O=Y[r+4*O>>>2>>>0]=S,S=0;S>>0>>>0]=m.charCodeAt(S);ie[O>>>0>>>0]=0,s+=m.length+1}),0},D:function(r,o){r>>>=0,o>>>=0;var s=He();Y[r>>>2>>>0]=s.length;var m=0;return s.forEach(O=>m+=O.length+1),Y[o>>>2>>>0]=m,0},f:()=>52,j:function(){return 52},q:function(){return 70},i:function(r,o,s,m){o>>>=0,s>>>=0,m>>>=0;for(var O=0,S=0;S>>2>>>0],K=Y[o+4>>>2>>>0];o+=8;for(var le=0;le>>0],se=Le[r];oe===0||oe===10?((r===1?_:x)(Ce(se,0)),se.length=0):se.push(oe)}O+=K}return Y[m>>>2>>>0]=O,0},r:ot,c:function(r,o,s,m){return ot(r>>>0,o>>>0,s>>>0,m>>>0)}},C=function(){function r(s){return C=s.exports,C=ut(),N=C.K,Re(),ee.unshift(C.L),ce--,ce==0&&(P!==null&&(clearInterval(P),P=null),te&&(s=te,te=null,s())),C}var o={a:$};if(ce++,a.instantiateWasm)try{return a.instantiateWasm(o,r)}catch(s){x(`Module.instantiateWasm callback failed with error: ${s}`),l(s)}return Fe(o,function(s){r(s.instance)}).catch(l),{}}();a._OrtInit=(r,o)=>(a._OrtInit=C.M)(r,o),a._OrtGetLastError=(r,o)=>(a._OrtGetLastError=C.N)(r,o),a._OrtCreateSessionOptions=(r,o,s,m,O,S,R,K,le,oe)=>(a._OrtCreateSessionOptions=C.O)(r,o,s,m,O,S,R,K,le,oe),a._OrtAppendExecutionProvider=(r,o)=>(a._OrtAppendExecutionProvider=C.P)(r,o),a._OrtAddFreeDimensionOverride=(r,o,s)=>(a._OrtAddFreeDimensionOverride=C.Q)(r,o,s),a._OrtAddSessionConfigEntry=(r,o,s)=>(a._OrtAddSessionConfigEntry=C.R)(r,o,s),a._OrtReleaseSessionOptions=r=>(a._OrtReleaseSessionOptions=C.S)(r),a._OrtCreateSession=(r,o,s)=>(a._OrtCreateSession=C.T)(r,o,s),a._OrtReleaseSession=r=>(a._OrtReleaseSession=C.U)(r),a._OrtGetInputOutputCount=(r,o,s)=>(a._OrtGetInputOutputCount=C.V)(r,o,s),a._OrtGetInputName=(r,o)=>(a._OrtGetInputName=C.W)(r,o),a._OrtGetOutputName=(r,o)=>(a._OrtGetOutputName=C.X)(r,o),a._OrtFree=r=>(a._OrtFree=C.Y)(r),a._OrtCreateTensor=(r,o,s,m,O,S)=>(a._OrtCreateTensor=C.Z)(r,o,s,m,O,S),a._OrtGetTensorData=(r,o,s,m,O)=>(a._OrtGetTensorData=C._)(r,o,s,m,O),a._OrtReleaseTensor=r=>(a._OrtReleaseTensor=C.$)(r),a._OrtCreateRunOptions=(r,o,s,m)=>(a._OrtCreateRunOptions=C.aa)(r,o,s,m),a._OrtAddRunConfigEntry=(r,o,s)=>(a._OrtAddRunConfigEntry=C.ba)(r,o,s),a._OrtReleaseRunOptions=r=>(a._OrtReleaseRunOptions=C.ca)(r),a._OrtCreateBinding=r=>(a._OrtCreateBinding=C.da)(r),a._OrtBindInput=(r,o,s)=>(a._OrtBindInput=C.ea)(r,o,s),a._OrtBindOutput=(r,o,s,m)=>(a._OrtBindOutput=C.fa)(r,o,s,m),a._OrtClearBoundOutputs=r=>(a._OrtClearBoundOutputs=C.ga)(r),a._OrtReleaseBinding=r=>(a._OrtReleaseBinding=C.ha)(r),a._OrtRunWithBinding=(r,o,s,m,O)=>(a._OrtRunWithBinding=C.ia)(r,o,s,m,O),a._OrtRun=(r,o,s,m,O,S,R,K)=>(a._OrtRun=C.ja)(r,o,s,m,O,S,R,K),a._OrtEndProfiling=r=>(a._OrtEndProfiling=C.ka)(r);var Ye=()=>(Ye=C.la)(),st=a._malloc=r=>(st=a._malloc=C.ma)(r);a._free=r=>(a._free=C.na)(r);var Je=r=>(Je=C.pa)(r),it=()=>(it=C.qa)(),M=r=>(M=C.ra)(r),Be=r=>(Be=C.sa)(r);function ut(){var r=C;r=Object.assign({},r);var o=m=>()=>m()>>>0,s=m=>O=>m(O)>>>0;return r.la=o(r.la),r.ma=s(r.ma),r.qa=o(r.qa),r.sa=s(r.sa),r}a.stackAlloc=Be,a.stackSave=it,a.stackRestore=M,a.UTF8ToString=be,a.stringToUTF8=(r,o,s)=>ke(r,ae,o,s),a.lengthBytesUTF8=_e;var xe;te=function r(){xe||Xe(),xe||(te=r)};function Xe(){if(!(0pr)});var hr=et(()=>{});var yr=et(()=>{});var br={};Tt(br,{cpus:()=>rn});var rn,wr=St(()=>{rn=void 0});var _r=et((vr,Ft)=>{"use strict";var Or=(()=>{var u=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(u=u||__filename),function(d={}){function a(){return j.buffer!=de.buffer&&we(),de}function h(){return j.buffer!=de.buffer&&we(),ge}function l(){return j.buffer!=de.buffer&&we(),ye}function w(){return j.buffer!=de.buffer&&we(),J}function g(){return j.buffer!=de.buffer&&we(),fe}var i=d,A,D;i.ready=new Promise((e,t)=>{A=e,D=t});var I=Object.assign({},i),B="./this.program",F=(e,t)=>{throw t},U=typeof window=="object",k=typeof importScripts=="function",L=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_=i.ENVIRONMENT_IS_PTHREAD||!1,x="";function N(e){return i.locateFile?i.locateFile(e,x):x+e}var he,ie,ae;if(L){var E=(Mt(),tt(At)),Y=(Dt(),tt(Ct));x=k?Y.dirname(x)+"/":__dirname+"/",he=(t,n)=>(t=be(t)?new URL(t):Y.normalize(t),E.readFileSync(t,n?void 0:"utf8")),ae=t=>(t=he(t,!0),t.buffer||(t=new Uint8Array(t)),t),ie=(t,n,f,y=!0)=>{t=be(t)?new URL(t):Y.normalize(t),E.readFile(t,y?void 0:"utf8",(b,v)=>{b?f(b):n(y?v.buffer:v)})},!i.thisProgram&&1{throw process.exitCode=t,n},i.inspect=()=>"[Emscripten Module object]";let e;try{e=hr()}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}global.Worker=e.Worker}else(U||k)&&(k?x=self.location.href:typeof document<"u"&&document.currentScript&&(x=document.currentScript.src),typeof u<"u"&&u&&(x=u),x.indexOf("blob:")!==0?x=x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):x="",L||(he=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},k&&(ae=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),ie=(e,t,n)=>{var f=new XMLHttpRequest;f.open("GET",e,!0),f.responseType="arraybuffer",f.onload=()=>{f.status==200||f.status==0&&f.response?t(f.response):n()},f.onerror=n,f.send(null)}));L&&typeof performance>"u"&&(global.performance=yr().performance);var ue=console.log.bind(console),Re=console.error.bind(console);L&&(ue=(...e)=>E.writeSync(1,e.join(" ")+`\n`),Re=(...e)=>E.writeSync(2,e.join(" ")+`\n`));var Ie=ue,ee=Re;Object.assign(i,I),I=null,typeof WebAssembly!="object"&&Z("no native wasm support detected");var j,ce,P=!1,te,de,ge,ye,J,fe;function we(){var e=j.buffer;i.HEAP8=de=new Int8Array(e),i.HEAP16=new Int16Array(e),i.HEAPU8=ge=new Uint8Array(e),i.HEAPU16=new Uint16Array(e),i.HEAP32=ye=new Int32Array(e),i.HEAPU32=J=new Uint32Array(e),i.HEAPF32=new Float32Array(e),i.HEAPF64=fe=new Float64Array(e)}var Ae=16777216;if(_)j=i.wasmMemory;else if(i.wasmMemory)j=i.wasmMemory;else if(j=new WebAssembly.Memory({initial:Ae/65536,maximum:65536,shared:!0}),!(j.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"),L&&ee("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");we(),Ae=j.buffer.byteLength;var Me=[],Fe=[],Ee=[],pe=0,Oe=null,ve=null;function re(){if(pe--,pe==0&&(Oe!==null&&(clearInterval(Oe),Oe=null),ve)){var e=ve;ve=null,e()}}function Z(e){throw e="Aborted("+e+")",ee(e),P=!0,te=1,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),D(e),e}var Ce=e=>e.startsWith("data:application/octet-stream;base64,"),be=e=>e.startsWith("file://"),_e;_e="ort-wasm-threaded.wasm",Ce(_e)||(_e=N(_e));function ke(e){if(ae)return ae(e);throw"both async and sync fetching of the wasm failed"}function Ue(e){if(U||k){if(typeof fetch=="function"&&!be(e))return fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw"failed to load wasm binary file at \'"+e+"\'";return t.arrayBuffer()}).catch(()=>ke(e));if(ie)return new Promise((t,n)=>{ie(e,f=>t(new Uint8Array(f)),n)})}return Promise.resolve().then(()=>ke(e))}function ze(e,t,n){return Ue(e).then(f=>WebAssembly.instantiate(f,t)).then(f=>f).then(n,f=>{ee(`failed to asynchronously prepare wasm: ${f}`),Z(f)})}function at(e,t){var n=_e;return typeof WebAssembly.instantiateStreaming!="function"||Ce(n)||be(n)||L||typeof fetch!="function"?ze(n,e,t):fetch(n,{credentials:"same-origin"}).then(f=>WebAssembly.instantiateStreaming(f,e).then(t,function(y){return ee(`wasm streaming compile failed: ${y}`),ee("falling back to ArrayBuffer instantiation"),ze(n,e,t)}))}var De,Ne={921276:(e,t,n,f)=>{if(typeof i>"u"||!i.cb)return 1;if(e=Ge(e>>>0),e.startsWith("./")&&(e=e.substring(2)),e=i.cb.get(e),!e)return 2;if(t>>>=0,n>>>=0,f>>>=0,t+n>e.byteLength)return 3;try{return h().set(e.subarray(t,t+n),f>>>0),0}catch{return 4}}};function Pe(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var He=e=>{e.terminate(),e.onmessage=()=>{}},$e=e=>{M.Pa.length==0&&(Je(),M.Ya(M.Pa[0]));var t=M.Pa.pop();if(!t)return 6;M.Qa.push(t),M.Ma[e.Oa]=t,t.Oa=e.Oa;var n={cmd:"run",start_routine:e.kb,arg:e.hb,pthread_ptr:e.Oa};return L&&t.unref(),t.postMessage(n,e.qb),0},Le=0,qe=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ve=(e,t,n)=>{t>>>=0;var f=t+n;for(n=t;e[n]&&!(n>=f);)++n;if(16y?f+=String.fromCharCode(y):(y-=65536,f+=String.fromCharCode(55296|y>>10,56320|y&1023))}}else f+=String.fromCharCode(y)}return f},Ge=(e,t)=>(e>>>=0)?Ve(h(),e,t):"",ot=e=>{var t=vt();return e=e(),ct(t),e};function $(e,t){var n=arguments.length-2,f=arguments;return ot(()=>{for(var y=_t(8*n),b=y>>>3,v=0;v>>0]=z}return ar(e,n,y,t)})}function C(e){if(_)return $(0,1,e);te=e,0{if(te=e,_)throw ut(e),"unwind";C(e)};function st(){for(var e=i.numThreads;e--;)Je();Me.unshift(()=>{pe++,it(()=>re())})}function Je(){var e=N("ort-wasm-threaded.worker.js");e=new Worker(e),M.Pa.push(e)}function it(e){_?e():Promise.all(M.Pa.map(M.Ya)).then(e)}var M={Pa:[],Qa:[],bb:[],Ma:{},Wa(){_?(M.receiveObjectTransfer=M.jb,M.threadInitTLS=M.ab,M.setExitStatus=M.$a):st()},$a:e=>te=e,tb:["$terminateWorker"],lb:()=>{for(var e of M.Qa)He(e);for(e of M.Pa)He(e);M.Pa=[],M.Qa=[],M.Ma=[]},Za:e=>{var t=e.Oa;delete M.Ma[t],M.Pa.push(e),M.Qa.splice(M.Qa.indexOf(e),1),e.Oa=0,wt(t)},jb(){},ab(){M.bb.forEach(e=>e())},Ya:e=>new Promise(t=>{e.onmessage=b=>{b=b.data;var v=b.cmd;if(b.targetThread&&b.targetThread!=lt()){var z=M.Ma[b.targetThread];z?z.postMessage(b,b.transferList):ee(`Internal error! Worker sent a message "${v}" to target pthread ${b.targetThread}, but that thread no longer exists!`)}else v==="checkMailbox"?ft():v==="spawnThread"?$e(b):v==="cleanupThread"?M.Za(M.Ma[b.thread]):v==="killThread"?(b=b.thread,v=M.Ma[b],delete M.Ma[b],He(v),wt(b),M.Qa.splice(M.Qa.indexOf(v),1),v.Oa=0):v==="cancelThread"?M.Ma[b.thread].postMessage({cmd:"cancel"}):v==="loaded"?(e.loaded=!0,L&&!e.Oa&&e.unref(),t(e)):v==="alert"?alert(`Thread ${b.threadId}: ${b.text}`):b.target==="setimmediate"?e.postMessage(b):v==="callHandler"?i[b.handler](...b.args):v&&ee(`worker sent an unknown command ${v}`)},e.onerror=b=>{throw ee(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b},L&&(e.on("message",b=>e.onmessage({data:b})),e.on("error",b=>e.onerror(b)));var n=[],f=["onExit"],y;for(y of f)i.hasOwnProperty(y)&&n.push(y);e.postMessage({cmd:"load",handlers:n,urlOrBlob:i.mainScriptUrlOrBlob||u,wasmMemory:j,wasmModule:ce})})};i.PThread=M;var Be=e=>{for(;0{var e=lt(),t=w()[e+52>>>2>>>0];e=w()[e+56>>>2>>>0],ir(t,t-e),ct(t)};function ut(e){if(_)return $(1,0,e);Ye(e)}var xe=[],Xe;i.invokeEntryPoint=(e,t)=>{var n=xe[e];n||(e>=xe.length&&(xe.length=e+1),xe[e]=n=Xe.get(e)),e=n(t),0>>2>>>0]=t},this.fb=function(t){w()[this.Va+8>>>2>>>0]=t},this.Wa=function(t,n){this.eb(),this.gb(t),this.fb(n)},this.eb=function(){w()[this.Va+16>>>2>>>0]=0}}var o=0,s=0;function m(e,t,n,f){return _?$(2,1,e,t,n,f):O(e,t,n,f)}function O(e,t,n,f){if(e>>>=0,t>>>=0,n>>>=0,f>>>=0,typeof SharedArrayBuffer>"u")return ee("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var y=[];return _&&y.length===0?m(e,t,n,f):(e={kb:n,Oa:e,hb:f,qb:y},_?(e.sb="spawnThread",postMessage(e,y),0):$e(e))}function S(e,t,n){return _?$(3,1,e,t,n):0}function R(e,t){if(_)return $(4,1,e,t)}var K=e=>{for(var t=0,n=0;n=f?t++:2047>=f?t+=2:55296<=f&&57343>=f?(t+=4,++n):t+=3}return t},le=(e,t,n,f)=>{if(n>>>=0,!(0=v){var z=e.charCodeAt(++b);v=65536+((v&1023)<<10)|z&1023}if(127>=v){if(n>=f)break;t[n++>>>0]=v}else{if(2047>=v){if(n+1>=f)break;t[n++>>>0]=192|v>>6}else{if(65535>=v){if(n+2>=f)break;t[n++>>>0]=224|v>>12}else{if(n+3>=f)break;t[n++>>>0]=240|v>>18,t[n++>>>0]=128|v>>12&63}t[n++>>>0]=128|v>>6&63}t[n++>>>0]=128|v&63}}return t[n>>>0]=0,n-y},oe=(e,t,n)=>le(e,h(),t,n);function se(e,t){if(_)return $(5,1,e,t)}function Qe(e,t,n){if(_)return $(6,1,e,t,n)}function Ze(e,t,n){return _?$(7,1,e,t,n):0}function c(e,t){if(_)return $(8,1,e,t)}function W(e,t,n){if(_)return $(9,1,e,t,n)}function G(e,t,n,f){if(_)return $(10,1,e,t,n,f)}function Se(e,t,n,f){if(_)return $(11,1,e,t,n,f)}function Ke(e,t,n,f){if(_)return $(12,1,e,t,n,f)}function Bt(e){if(_)return $(13,1,e)}function Wt(e,t){if(_)return $(14,1,e,t)}function kt(e,t,n){if(_)return $(15,1,e,t,n)}function mt(e){e>>>=0,typeof Atomics.rb=="function"&&(Atomics.rb(l(),e>>>2,e).value.then(ft),e+=128,Atomics.store(l(),e>>>2,1))}i.__emscripten_thread_mailbox_await=mt;var ft=()=>{var e=lt();if(e&&(mt(e),e=or,!P))try{if(e(),!(0e%4===0&&(e%100!==0||e%400===0),Nt=[0,31,60,91,121,152,182,213,244,274,305,335],Ht=[0,31,59,90,120,151,181,212,243,273,304,334];function $t(e,t,n,f,y,b,v,z){return _?$(16,1,e,t,n,f,y,b,v,z):-52}function Gt(e,t,n,f,y,b,v){if(_)return $(17,1,e,t,n,f,y,b,v)}var Yt=e=>{var t=K(e)+1,n=rr(t);return n&&oe(e,n,t),n},ht=[],yt={},jt=()=>{if(!bt){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:B||"./this.program"},t;for(t in yt)yt[t]===void 0?delete e[t]:e[t]=yt[t];var n=[];for(t in e)n.push(`${t}=${e[t]}`);bt=n}return bt},bt;function zt(e,t){if(_)return $(18,1,e,t);e>>>=0,t>>>=0;var n=0;return jt().forEach((f,y)=>{var b=t+n;for(y=w()[e+4*y>>>2>>>0]=b,b=0;b>>0>>>0]=f.charCodeAt(b);a()[y>>>0>>>0]=0,n+=f.length+1}),0}function qt(e,t){if(_)return $(19,1,e,t);e>>>=0,t>>>=0;var n=jt();w()[e>>>2>>>0]=n.length;var f=0;return n.forEach(y=>f+=y.length+1),w()[t>>>2>>>0]=f,0}function Vt(e){return _?$(20,1,e):52}function Jt(e,t,n,f){return _?$(21,1,e,t,n,f):52}function Xt(e,t,n,f,y){return _?$(22,1,e,t,n,f,y):70}var Gr=[null,[],[]];function Qt(e,t,n,f){if(_)return $(23,1,e,t,n,f);t>>>=0,n>>>=0,f>>>=0;for(var y=0,b=0;b>>2>>>0],z=w()[t+4>>>2>>>0];t+=8;for(var Te=0;Te>>0],me=Gr[e];ne===0||ne===10?((e===1?Ie:ee)(Ve(me,0)),me.length=0):me.push(ne)}y+=z}return w()[f>>>2>>>0]=y,0}var Zt=[31,29,31,30,31,30,31,31,30,31,30,31],Kt=[31,28,31,30,31,30,31,31,30,31,30,31];function Yr(e){var t=Array(K(e)+1);return le(e,t,0,t.length),t}var jr=(e,t)=>{a().set(e,t>>>0)};function er(e,t,n,f){function y(p,H,q){for(p=typeof p=="number"?p.toString():p||"";p.lengthcr?-1:0We-p.getDate())H-=We-p.getDate()+1,p.setDate(1),11>q?p.setMonth(q+1):(p.setMonth(0),p.setFullYear(p.getFullYear()+1));else{p.setDate(p.getDate()+H);break}}return q=new Date(p.getFullYear()+1,0,4),H=z(new Date(p.getFullYear(),0,4)),q=z(q),0>=v(H,p)?0>=v(q,p)?p.getFullYear()+1:p.getFullYear():p.getFullYear()-1}e>>>=0,t>>>=0,n>>>=0,f>>>=0;var ne=w()[f+40>>>2>>>0];f={ob:l()[f>>>2>>>0],nb:l()[f+4>>>2>>>0],Ta:l()[f+8>>>2>>>0],Xa:l()[f+12>>>2>>>0],Ua:l()[f+16>>>2>>>0],Sa:l()[f+20>>>2>>>0],Na:l()[f+24>>>2>>>0],Ra:l()[f+28>>>2>>>0],ub:l()[f+32>>>2>>>0],mb:l()[f+36>>>2>>>0],pb:ne?Ge(ne):""},n=Ge(n),ne={"%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 me in ne)n=n.replace(new RegExp(me,"g"),ne[me]);var fr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),lr="January February March April May June July August September October November December".split(" ");ne={"%a":p=>fr[p.Na].substring(0,3),"%A":p=>fr[p.Na],"%b":p=>lr[p.Ua].substring(0,3),"%B":p=>lr[p.Ua],"%C":p=>b((p.Sa+1900)/100|0,2),"%d":p=>b(p.Xa,2),"%e":p=>y(p.Xa,2," "),"%g":p=>Te(p).toString().substring(2),"%G":p=>Te(p),"%H":p=>b(p.Ta,2),"%I":p=>(p=p.Ta,p==0?p=12:12{for(var H=0,q=0;q<=p.Ua-1;H+=(je(p.Sa+1900)?Zt:Kt)[q++]);return b(p.Xa+H,3)},"%m":p=>b(p.Ua+1,2),"%M":p=>b(p.nb,2),"%n":()=>`\n`,"%p":p=>0<=p.Ta&&12>p.Ta?"AM":"PM","%S":p=>b(p.ob,2),"%t":()=>" ","%u":p=>p.Na||7,"%U":p=>b(Math.floor((p.Ra+7-p.Na)/7),2),"%V":p=>{var H=Math.floor((p.Ra+7-(p.Na+6)%7)/7);if(2>=(p.Na+371-p.Ra-2)%7&&H++,H)H==53&&(q=(p.Na+371-p.Ra)%7,q==4||q==3&&je(p.Sa)||(H=1));else{H=52;var q=(p.Na+7-p.Ra-1)%7;(q==4||q==5&&je(p.Sa%400-1))&&H++}return b(H,2)},"%w":p=>p.Na,"%W":p=>b(Math.floor((p.Ra+7-(p.Na+6)%7)/7),2),"%y":p=>(p.Sa+1900).toString().substring(2),"%Y":p=>p.Sa+1900,"%z":p=>{p=p.mb;var H=0<=p;return p=Math.abs(p)/60,(H?"+":"-")+("0000"+(p/60*100+p%60)).slice(-4)},"%Z":p=>p.pb,"%%":()=>"%"},n=n.replace(/%%/g,"\\0\\0");for(me in ne)n.includes(me)&&(n=n.replace(new RegExp(me,"g"),ne[me](f)));return n=n.replace(/\\0\\0/g,"%"),me=Yr(n),me.length>t?0:(jr(me,e),me.length-1)}M.Wa();var zr=[C,ut,m,S,R,se,Qe,Ze,c,W,G,Se,Ke,Bt,Wt,kt,$t,Gt,zt,qt,Vt,Jt,Xt,Qt],qr={b:function(e,t,n){throw e>>>=0,new r(e).Wa(t>>>0,n>>>0),o=e,s++,o},L:function(e){nr(e>>>0,!k,1,!U,131072,!1),M.ab()},j:function(e){e>>>=0,_?postMessage({cmd:"cleanupThread",thread:e}):M.Za(M.Ma[e])},H:O,h:S,S:R,D:se,F:Qe,T:Ze,Q:c,J:W,P:G,n:Se,E:Ke,B:Bt,R:Wt,C:kt,p:()=>1,z:function(e,t){e>>>=0,e==t>>>0?setTimeout(()=>ft()):_?postMessage({targetThread:e,cmd:"checkMailbox"}):(e=M.Ma[e])&&e.postMessage({cmd:"checkMailbox"})},I:function(e,t,n,f){t>>>=0,gt.length=n,f=f>>>0>>>3;for(var y=0;y>>0];return e=0>e?Ne[-e-1]:zr[e],M.ib=t,t=e.apply(null,gt),M.ib=0,t},K:mt,o:function(e){L&&M.Ma[e>>>0].ref()},s:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),l()[n>>>2>>>0]=e.getUTCSeconds(),l()[n+4>>>2>>>0]=e.getUTCMinutes(),l()[n+8>>>2>>>0]=e.getUTCHours(),l()[n+12>>>2>>>0]=e.getUTCDate(),l()[n+16>>>2>>>0]=e.getUTCMonth(),l()[n+20>>>2>>>0]=e.getUTCFullYear()-1900,l()[n+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,l()[n+28>>>2>>>0]=e},t:function(e,t,n){e=t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN,n>>>=0,e=new Date(1e3*e),l()[n>>>2>>>0]=e.getSeconds(),l()[n+4>>>2>>>0]=e.getMinutes(),l()[n+8>>>2>>>0]=e.getHours(),l()[n+12>>>2>>>0]=e.getDate(),l()[n+16>>>2>>>0]=e.getMonth(),l()[n+20>>>2>>>0]=e.getFullYear()-1900,l()[n+24>>>2>>>0]=e.getDay(),t=(je(e.getFullYear())?Nt:Ht)[e.getMonth()]+e.getDate()-1|0,l()[n+28>>>2>>>0]=t,l()[n+36>>>2>>>0]=-(60*e.getTimezoneOffset()),t=new Date(e.getFullYear(),6,1).getTimezoneOffset();var f=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=(t!=f&&e.getTimezoneOffset()==Math.min(f,t))|0,l()[n+32>>>2>>>0]=e},u:function(e){e>>>=0;var t=new Date(l()[e+20>>>2>>>0]+1900,l()[e+16>>>2>>>0],l()[e+12>>>2>>>0],l()[e+8>>>2>>>0],l()[e+4>>>2>>>0],l()[e>>>2>>>0],0),n=l()[e+32>>>2>>>0],f=t.getTimezoneOffset(),y=new Date(t.getFullYear(),6,1).getTimezoneOffset(),b=new Date(t.getFullYear(),0,1).getTimezoneOffset(),v=Math.min(b,y);return 0>n?l()[e+32>>>2>>>0]=+(y!=b&&v==f):0>>2>>>0]=t.getDay(),n=(je(t.getFullYear())?Nt:Ht)[t.getMonth()]+t.getDate()-1|0,l()[e+28>>>2>>>0]=n,l()[e>>>2>>>0]=t.getSeconds(),l()[e+4>>>2>>>0]=t.getMinutes(),l()[e+8>>>2>>>0]=t.getHours(),l()[e+12>>>2>>>0]=t.getDate(),l()[e+16>>>2>>>0]=t.getMonth(),l()[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),isNaN(e)?(l()[tr()>>>2>>>0]=61,e=-1):e/=1e3,sr((De=e,1<=+Math.abs(De)?0>>0:~~+Math.ceil((De-+(~~De>>>0))/4294967296)>>>0:0)),e>>>0},q:$t,r:Gt,y:function(e,t,n){function f(ne){return(ne=ne.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?ne[1]:"GMT"}e>>>=0,t>>>=0,n>>>=0;var y=new Date().getFullYear(),b=new Date(y,0,1),v=new Date(y,6,1);y=b.getTimezoneOffset();var z=v.getTimezoneOffset(),Te=Math.max(y,z);w()[e>>>2>>>0]=60*Te,l()[t>>>2>>>0]=+(y!=z),e=f(b),t=f(v),e=Yt(e),t=Yt(t),z>>2>>>0]=e,w()[n+4>>>2>>>0]=t):(w()[n>>>2>>>0]=t,w()[n+4>>>2>>>0]=e)},c:()=>{Z("")},O:function(e,t,n){e>>>=0,t>>>=0,n>>>=0,ht.length=0;for(var f;f=h()[t++>>>0];){var y=f!=105;y&=f!=112,n+=y&&n%8?4:0,ht.push(f==112?w()[n>>>2>>>0]:f==105?l()[n>>>2>>>0]:g()[n>>>3>>>0]),n+=y?8:4}return Ne[e].apply(null,ht)},k:()=>{},i:()=>Date.now(),U:()=>{throw Le+=1,"unwind"},A:function(){return 4294901760},e:()=>performance.timeOrigin+performance.now(),f:()=>L?(wr(),tt(br)).cpus().length:navigator.hardwareConcurrency,x:function(e){e>>>=0;var t=h().length;if(e<=t||4294901760=n;n*=2){var f=t*(1+.2/n);f=Math.min(f,e+100663296);var y=Math;f=Math.max(e,f);e:{y=(y.min.call(y,4294901760,f+(65536-f%65536)%65536)-j.buffer.byteLength+65535)/65536;try{j.grow(y),we();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1},M:zt,N:qt,G:Ye,g:Vt,m:Jt,v:Xt,l:Qt,a:j||i.wasmMemory,w:er,d:function(e,t,n,f){return er(e>>>0,t>>>0,n>>>0,f>>>0)}},T=function(){function e(n,f){return T=n.exports,T=Vr(),M.bb.push(T.za),Xe=T.Aa,Fe.unshift(T.V),ce=f,re(),T}var t={a:qr};if(pe++,i.instantiateWasm)try{return i.instantiateWasm(t,e)}catch(n){ee(`Module.instantiateWasm callback failed with error: ${n}`),D(n)}return at(t,function(n){e(n.instance,n.module)}).catch(D),{}}();i._OrtInit=(e,t)=>(i._OrtInit=T.W)(e,t),i._OrtGetLastError=(e,t)=>(i._OrtGetLastError=T.X)(e,t),i._OrtCreateSessionOptions=(e,t,n,f,y,b,v,z,Te,ne)=>(i._OrtCreateSessionOptions=T.Y)(e,t,n,f,y,b,v,z,Te,ne),i._OrtAppendExecutionProvider=(e,t)=>(i._OrtAppendExecutionProvider=T.Z)(e,t),i._OrtAddFreeDimensionOverride=(e,t,n)=>(i._OrtAddFreeDimensionOverride=T._)(e,t,n),i._OrtAddSessionConfigEntry=(e,t,n)=>(i._OrtAddSessionConfigEntry=T.$)(e,t,n),i._OrtReleaseSessionOptions=e=>(i._OrtReleaseSessionOptions=T.aa)(e),i._OrtCreateSession=(e,t,n)=>(i._OrtCreateSession=T.ba)(e,t,n),i._OrtReleaseSession=e=>(i._OrtReleaseSession=T.ca)(e),i._OrtGetInputOutputCount=(e,t,n)=>(i._OrtGetInputOutputCount=T.da)(e,t,n),i._OrtGetInputName=(e,t)=>(i._OrtGetInputName=T.ea)(e,t),i._OrtGetOutputName=(e,t)=>(i._OrtGetOutputName=T.fa)(e,t),i._OrtFree=e=>(i._OrtFree=T.ga)(e),i._OrtCreateTensor=(e,t,n,f,y,b)=>(i._OrtCreateTensor=T.ha)(e,t,n,f,y,b),i._OrtGetTensorData=(e,t,n,f,y)=>(i._OrtGetTensorData=T.ia)(e,t,n,f,y),i._OrtReleaseTensor=e=>(i._OrtReleaseTensor=T.ja)(e),i._OrtCreateRunOptions=(e,t,n,f)=>(i._OrtCreateRunOptions=T.ka)(e,t,n,f),i._OrtAddRunConfigEntry=(e,t,n)=>(i._OrtAddRunConfigEntry=T.la)(e,t,n),i._OrtReleaseRunOptions=e=>(i._OrtReleaseRunOptions=T.ma)(e),i._OrtCreateBinding=e=>(i._OrtCreateBinding=T.na)(e),i._OrtBindInput=(e,t,n)=>(i._OrtBindInput=T.oa)(e,t,n),i._OrtBindOutput=(e,t,n,f)=>(i._OrtBindOutput=T.pa)(e,t,n,f),i._OrtClearBoundOutputs=e=>(i._OrtClearBoundOutputs=T.qa)(e),i._OrtReleaseBinding=e=>(i._OrtReleaseBinding=T.ra)(e),i._OrtRunWithBinding=(e,t,n,f,y)=>(i._OrtRunWithBinding=T.sa)(e,t,n,f,y),i._OrtRun=(e,t,n,f,y,b,v,z)=>(i._OrtRun=T.ta)(e,t,n,f,y,b,v,z),i._OrtEndProfiling=e=>(i._OrtEndProfiling=T.ua)(e);var tr=()=>(tr=T.va)(),lt=i._pthread_self=()=>(lt=i._pthread_self=T.wa)(),rr=i._malloc=e=>(rr=i._malloc=T.xa)(e);i._free=e=>(i._free=T.ya)(e),i.__emscripten_tls_init=()=>(i.__emscripten_tls_init=T.za)();var nr=i.__emscripten_thread_init=(e,t,n,f,y,b)=>(nr=i.__emscripten_thread_init=T.Ba)(e,t,n,f,y,b);i.__emscripten_thread_crashed=()=>(i.__emscripten_thread_crashed=T.Ca)();var ar=(e,t,n,f)=>(ar=T.Da)(e,t,n,f),wt=e=>(wt=T.Ea)(e),Ot=i.__emscripten_thread_exit=e=>(Ot=i.__emscripten_thread_exit=T.Fa)(e),or=()=>(or=T.Ga)(),sr=e=>(sr=T.Ha)(e),ir=(e,t)=>(ir=T.Ia)(e,t),vt=()=>(vt=T.Ja)(),ct=e=>(ct=T.Ka)(e),_t=e=>(_t=T.La)(e);function Vr(){var e=T;e=Object.assign({},e);var t=f=>()=>f()>>>0,n=f=>y=>f(y)>>>0;return e.va=t(e.va),e.wa=t(e.wa),e.xa=n(e.xa),e.emscripten_main_runtime_thread_id=t(e.emscripten_main_runtime_thread_id),e.Ja=t(e.Ja),e.La=n(e.La),e}i.wasmMemory=j,i.stackAlloc=_t,i.stackSave=vt,i.stackRestore=ct,i.keepRuntimeAlive=()=>0Or)});var Er=et((On,nn)=>{nn.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\\n\'});var Tr;Tr=gr();var an=_r(),Ut,Pt=!1,pt=!1,Sr=!1,on=u=>{if(u===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+u+", 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 "+u+", 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}},sn=()=>{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}},un=(u,d)=>u?d?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":d?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Ar=async u=>{if(Pt)return Promise.resolve();if(pt)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Sr)throw new Error("previous call to \'initializeWebAssembly()\' failed.");pt=!0;let d=u.initTimeout,a=u.numThreads,h=u.simd,l=on(a),w=h&&sn(),g=u.wasmPaths,i=typeof g=="string"?g:void 0,A=un(w,l),D=typeof g=="object"?g[A]:void 0,I=!1,B=[];if(d>0&&B.push(new Promise(F=>{setTimeout(()=>{I=!0,F()},d)})),B.push(new Promise((F,U)=>{let k=l?an:Tr,L={locateFile:(_,x)=>l&&_.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([Er()],{type:"text/javascript"})):_.endsWith(".wasm")?D||(i??x)+A:x+_};if(l)if(L.numThreads=a,typeof Blob>"u")L.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let _=`var ortWasmThreaded=${k.toString()};`;L.mainScriptUrlOrBlob=new Blob([_],{type:"text/javascript"})}k(L).then(_=>{pt=!1,Pt=!0,Ut=_,F()},_=>{pt=!1,Sr=!0,U(_)})})),await Promise.race(B),I)throw new Error(`WebAssembly backend initializing failed due to timeout: ${d}ms`)},X=()=>{if(Pt&&Ut)return Ut;throw new Error("WebAssembly is not initialized yet.")};var Q=(u,d)=>{let a=X(),h=a.lengthBytesUTF8(u)+1,l=a._malloc(h);return a.stringToUTF8(u,l,h),d.push(l),l},rt=(u,d,a,h)=>{if(typeof u=="object"&&u!==null){if(a.has(u))throw new Error("Circular reference in options");a.add(u)}Object.entries(u).forEach(([l,w])=>{let g=d?d+l:l;if(typeof w=="object")rt(w,g+".",a,h);else if(typeof w=="string"||typeof w=="number")h(g,w.toString());else if(typeof w=="boolean")h(g,w?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof w}`)})},V=u=>{let d=X(),a=d.stackSave();try{let h=d.stackAlloc(8);d._OrtGetLastError(h,h+4);let l=d.HEAP32[h/4],w=d.HEAPU32[h/4+1],g=w?d.UTF8ToString(w):"";throw new Error(`${u} ERROR_CODE: ${l}, ERROR_MESSAGE: ${g}`)}finally{d.stackRestore(a)}};var Mr=u=>{let d=X(),a=0,h=[],l=u||{};try{if(u?.logSeverityLevel===void 0)l.logSeverityLevel=2;else if(typeof u.logSeverityLevel!="number"||!Number.isInteger(u.logSeverityLevel)||u.logSeverityLevel<0||u.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${u.logSeverityLevel}`);if(u?.logVerbosityLevel===void 0)l.logVerbosityLevel=0;else if(typeof u.logVerbosityLevel!="number"||!Number.isInteger(u.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${u.logVerbosityLevel}`);u?.terminate===void 0&&(l.terminate=!1);let w=0;return u?.tag!==void 0&&(w=Q(u.tag,h)),a=d._OrtCreateRunOptions(l.logSeverityLevel,l.logVerbosityLevel,!!l.terminate,w),a===0&&V("Can\'t create run options."),u?.extra!==void 0&&rt(u.extra,"",new WeakSet,(g,i)=>{let A=Q(g,h),D=Q(i,h);d._OrtAddRunConfigEntry(a,A,D)!==0&&V(`Can\'t set a run config entry: ${g} - ${i}.`)}),[a,h]}catch(w){throw a!==0&&d._OrtReleaseRunOptions(a),h.forEach(g=>d._free(g)),w}};var fn=u=>{switch(u){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${u}`)}},ln=u=>{switch(u){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${u}`)}},cn=u=>{u.extra||(u.extra={}),u.extra.session||(u.extra.session={});let d=u.extra.session;d.use_ort_model_bytes_directly||(d.use_ort_model_bytes_directly="1"),u.executionProviders&&u.executionProviders.some(a=>(typeof a=="string"?a:a.name)==="webgpu")&&(u.enableMemPattern=!1)},dn=(u,d,a)=>{for(let h of d){let l=typeof h=="string"?h:h.name;switch(l){case"webnn":if(l="WEBNN",typeof h!="string"){let g=h;if(g?.deviceType){let i=Q("deviceType",a),A=Q(g.deviceType,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'deviceType\' - ${g.deviceType}.`)}if(g?.numThreads){let i=g.numThreads;(typeof i!="number"||!Number.isInteger(i)||i<0)&&(i=0);let A=Q("numThreads",a),D=Q(i.toString(),a);X()._OrtAddSessionConfigEntry(u,A,D)!==0&&V(`Can\'t set a session config entry: \'numThreads\' - ${g.numThreads}.`)}if(g?.powerPreference){let i=Q("powerPreference",a),A=Q(g.powerPreference,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'powerPreference\' - ${g.powerPreference}.`)}}break;case"webgpu":if(l="JS",typeof h!="string"){let g=h;if(g?.preferredLayout){if(g.preferredLayout!=="NCHW"&&g.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${g.preferredLayout}`);let i=Q("preferredLayout",a),A=Q(g.preferredLayout,a);X()._OrtAddSessionConfigEntry(u,i,A)!==0&&V(`Can\'t set a session config entry: \'preferredLayout\' - ${g.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let w=Q(l,a);X()._OrtAppendExecutionProvider(u,w)!==0&&V(`Can\'t append execution provider: ${l}.`)}},Cr=u=>{let d=X(),a=0,h=[],l=u||{};cn(l);try{let w=fn(l.graphOptimizationLevel??"all"),g=ln(l.executionMode??"sequential"),i=typeof l.logId=="string"?Q(l.logId,h):0,A=l.logSeverityLevel??2;if(!Number.isInteger(A)||A<0||A>4)throw new Error(`log serverity level is not valid: ${A}`);let D=l.logVerbosityLevel??0;if(!Number.isInteger(D)||D<0||D>4)throw new Error(`log verbosity level is not valid: ${D}`);let I=typeof l.optimizedModelFilePath=="string"?Q(l.optimizedModelFilePath,h):0;if(a=d._OrtCreateSessionOptions(w,!!l.enableCpuMemArena,!!l.enableMemPattern,g,!!l.enableProfiling,0,i,A,D,I),a===0&&V("Can\'t create session options."),l.executionProviders&&dn(a,l.executionProviders,h),l.freeDimensionOverrides)for(let[B,F]of Object.entries(l.freeDimensionOverrides)){if(typeof B!="string")throw new Error(`free dimension override name must be a string: ${B}`);if(typeof F!="number"||!Number.isInteger(F)||F<0)throw new Error(`free dimension override value must be a non-negative integer: ${F}`);let U=Q(B,h);d._OrtAddFreeDimensionOverride(a,U,F)!==0&&V(`Can\'t set a free dimension override: ${B} - ${F}.`)}return l.extra!==void 0&&rt(l.extra,"",new WeakSet,(B,F)=>{let U=Q(B,h),k=Q(F,h);d._OrtAddSessionConfigEntry(a,U,k)!==0&&V(`Can\'t set a session config entry: ${B} - ${F}.`)}),[a,h]}catch(w){throw a!==0&&d._OrtReleaseSessionOptions(a),h.forEach(g=>d._free(g)),w}};var Rt=u=>{switch(u){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: ${u}`)}},Dr=u=>{switch(u){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: ${u}`)}},It=u=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][u],xr=u=>{switch(u){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${u}`)}},Fr=u=>{switch(u){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: ${u}`)}},Ur=u=>u==="float32"||u==="int32"||u==="int64"||u==="bool"||u==="float16"||u==="uint32",Pr=u=>{switch(u){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: ${u}`)}};var Rr=async u=>{if(typeof u=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(u))}catch(d){if(d.code==="ERR_FS_FILE_TOO_LARGE"){let a=(void 0)(u),h=[];for await(let l of a)h.push(l);return new Uint8Array(Buffer.concat(h))}throw d}else{let d=await fetch(u);if(!d.ok)throw new Error(`failed to load external data file: ${u}`);let a=d.headers.get("Content-Length"),h=a?parseInt(a,10):0;if(h<1073741824)return new Uint8Array(await d.arrayBuffer());{if(!d.body)throw new Error(`failed to load external data file: ${u}, no response body.`);let l=d.body.getReader(),w;try{w=new ArrayBuffer(h)}catch(i){if(i instanceof RangeError){let A=Math.ceil(h/65536);w=new WebAssembly.Memory({initial:A,maximum:A}).buffer}else throw i}let g=0;for(;;){let{done:i,value:A}=await l.read();if(i)break;let D=A.byteLength;new Uint8Array(w,g,D).set(A),g+=D}return new Uint8Array(w,0,h)}}else return u instanceof Blob?new Uint8Array(await u.arrayBuffer()):u instanceof Uint8Array?u:new Uint8Array(u)};var pn=(u,d)=>{X()._OrtInit(u,d)!==0&&V("Can\'t initialize onnxruntime.")},Lr=async u=>{pn(u.wasm.numThreads,Fr(u.logLevel))},Br=async(u,d)=>{},nt=new Map,mn=u=>{let d=X(),a=d.stackSave();try{let h=d.stackAlloc(8);return d._OrtGetInputOutputCount(u,h,h+4)!==0&&V("Can\'t get session input/output count."),[d.HEAP32[h/4],d.HEAP32[h/4+1]]}finally{d.stackRestore(a)}},Lt=u=>{let d=X(),a=d._malloc(u.byteLength);if(a===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${u.byteLength}.`);return d.HEAPU8.set(u,a),[a,u.byteLength]},Wr=async(u,d)=>{let a,h,l=X();Array.isArray(u)?[a,h]=u:u.buffer===l.HEAPU8.buffer?[a,h]=[u.byteOffset,u.byteLength]:[a,h]=Lt(u);let w=0,g=0,i=0,A=[],D=[],I=[];try{if([g,A]=Cr(d),d?.externalData&&l.mountExternalData){let x=[];for(let N of d.externalData){let he=typeof N=="string"?N:N.path;x.push(Rr(typeof N=="string"?N:N.data).then(ie=>{l.mountExternalData(he,ie)}))}await Promise.all(x)}w=l._OrtCreateSession(a,h,g),w===0&&V("Can\'t create a session.");let[B,F]=mn(w),U=[],k=[],L=[];for(let x=0;xl._OrtFree(F)),I.forEach(F=>l._OrtFree(F)),i!==0&&l._OrtReleaseBinding(i),w!==0&&l._OrtReleaseSession(w),B}finally{l._free(a),g!==0&&l._OrtReleaseSessionOptions(g),A.forEach(B=>l._free(B)),l.unmountExternalData?.()}},kr=u=>{let d=X(),a=nt.get(u);if(!a)throw new Error(`cannot release session. invalid session id: ${u}`);let[h,l,w,g]=a;g&&d._OrtReleaseBinding(g.handle),d.jsepUnregisterBuffers?.(u),l.forEach(i=>d._OrtFree(i)),w.forEach(i=>d._OrtFree(i)),d._OrtReleaseSession(h),nt.delete(u)},Ir=(u,d,a,h,l)=>{if(!u){d.push(0);return}let w=X(),g=u[0],i=u[1],A=u[3],D,I;if(g==="string"&&A==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(A==="gpu-buffer"){let U=u[2].gpuBuffer,k=It(Rt(g));I=i.reduce((L,_)=>L*_,1)*k,D=w.jsepRegisterBuffer(h,l,U,I)}else{let U=u[2];if(Array.isArray(U)){I=4*U.length,D=w._malloc(I),a.push(D);let k=D/4;for(let L=0;Lw.HEAP32[U++]=L);let k=w._OrtCreateTensor(Rt(g),D,I,F,i.length,Pr(A));k===0&&V(`Can\'t create tensor for input/output. session=${h}, index=${l}.`),d.push(k)}finally{w.stackRestore(B)}},Nr=async(u,d,a,h,l,w)=>{let g=X(),i=nt.get(u);if(!i)throw new Error(`cannot run inference. invalid session id: ${u}`);let[A,D,I,B]=i,F=d.length,U=h.length,k=0,L=[],_=[],x=[],N=[],he=g.stackSave(),ie=g.stackAlloc(F*4),ae=g.stackAlloc(F*4),E=g.stackAlloc(U*4),Y=g.stackAlloc(U*4);try{[k,L]=Mr(w);for(let P=0;Pre*Z,1);J=Dr(Me);let ve=B?.outputPreferredLocations[h[P]];if(J==="string"){if(ve==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let re=[],Z=fe/4;for(let Ce=0;Ce0){let re=g.jsepGetBuffer(fe),Z=It(Me);if(Z===void 0||!Ur(J))throw new Error(`Unsupported data type: ${J}`);ye=!0,ce.push([J,pe,{gpuBuffer:re,download:g.jsepCreateDownloader(re,Oe*Z,J),dispose:()=>{g._OrtReleaseTensor(te)}},"gpu-buffer"])}else{let re=xr(J),Z=new re(Oe);new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength).set(g.HEAPU8.subarray(fe,fe+Z.byteLength)),ce.push([J,pe,Z,"cpu"])}}finally{g.stackRestore(de),J==="string"&&fe&&g._free(fe),ye||g._OrtReleaseTensor(te)}}return B&&g._OrtClearBoundOutputs(B.handle),ce}finally{g.stackRestore(he),_.forEach(ue=>g._OrtReleaseTensor(ue)),x.forEach(ue=>g._OrtReleaseTensor(ue)),N.forEach(ue=>g._free(ue)),k!==0&&g._OrtReleaseRunOptions(k),L.forEach(ue=>g._free(ue))}},Hr=u=>{let d=X(),a=nt.get(u);if(!a)throw new Error("invalid session id");let h=a[0],l=d._OrtEndProfiling(h);l===0&&V("Can\'t get an profile file name."),d._OrtFree(l)},$r=u=>{let d=[];for(let a of u){let h=a[2];!Array.isArray(h)&&"buffer"in h&&d.push(h.buffer)}return d};self.onmessage=u=>{let{type:d,in:a}=u.data;try{switch(d){case"init-wasm":Ar(a.wasm).then(()=>{Lr(a).then(()=>{postMessage({type:d})},h=>{postMessage({type:d,err:h})})},h=>{postMessage({type:d,err:h})});break;case"init-ep":{let{epName:h,env:l}=a;Br(l,h).then(()=>{postMessage({type:d})},w=>{postMessage({type:d,err:w})});break}case"copy-from":{let{buffer:h}=a,l=Lt(h);postMessage({type:d,out:l});break}case"create":{let{model:h,options:l}=a;Wr(h,l).then(w=>{postMessage({type:d,out:w})},w=>{postMessage({type:d,err:w})});break}case"release":kr(a),postMessage({type:d});break;case"run":{let{sessionId:h,inputIndices:l,inputs:w,outputIndices:g,options:i}=a;Nr(h,l,w,g,new Array(g.length).fill(null),i).then(A=>{A.some(D=>D[3]!=="cpu")?postMessage({type:d,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:d,out:A},$r(A))},A=>{postMessage({type:d,err:A})});break}case"end-profiling":Hr(a),postMessage({type:d});break;default:}}catch(h){postMessage({type:d,err:h})}};})();\n'}),xr,bt,Tn,Fo,$o,da,ha,Vr,Wr,gg,Lo,nd,od,id,ad,sd,ud,ld,ma=L(()=>{vt(),td(),zr(),xr=()=>!!Z.wasm.proxy&&typeof document<"u",Tn=!1,Fo=!1,$o=!1,ha=new Map,Vr=(t,e)=>{let n=ha.get(t);n?n.push(e):ha.set(t,[e])},Wr=()=>{if(Tn||!Fo||$o||!bt)throw new Error("worker not ready")},gg=t=>{switch(t.data.type){case"init-wasm":Tn=!1,t.data.err?($o=!0,da[1](t.data.err)):(Fo=!0,da[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ha.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},Lo=typeof document<"u"?document?.currentScript?.src:void 0,nd=async()=>{if(!Fo){if(Tn)throw new Error("multiple calls to 'initWasm()' detected.");if($o)throw new Error("previous call to 'initWasm()' failed.");if(Tn=!0,xr())return Z.wasm.wasmPaths===void 0&&Lo&&Lo.indexOf("blob:")!==0&&(Z.wasm.wasmPaths=Lo.substr(0,+Lo.lastIndexOf("/")+1)),new Promise((t,e)=>{bt?.terminate();let n=URL.createObjectURL(new Blob([rd()],{type:"text/javascript"}));bt=new Worker(n,{name:"ort-wasm-proxy-worker"}),bt.onerror=s=>e(s),bt.onmessage=gg,URL.revokeObjectURL(n),da=[t,e];let r={type:"init-wasm",in:Z};bt.postMessage(r)});try{await Rp(Z.wasm),await Yp(Z),Fo=!0}catch(t){throw $o=!0,t}finally{Tn=!1}}},od=async t=>{if(xr())return Wr(),new Promise((e,n)=>{Vr("init-ep",[e,n]);let r={type:"init-ep",in:{epName:t,env:Z}};bt.postMessage(r)});await Xp(Z,t)},id=async t=>xr()?(Wr(),new Promise((e,n)=>{Vr("copy-from",[e,n]);let r={type:"copy-from",in:{buffer:t}};bt.postMessage(r,[t.buffer])})):pa(t),ad=async(t,e)=>{if(xr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wr(),new Promise((n,r)=>{Vr("create",[n,r]);let s={type:"create",in:{model:t,options:e}},i=[];t instanceof Uint8Array&&i.push(t.buffer),bt.postMessage(s,i)})}else return Kp(t,e)},sd=async t=>{if(xr())return Wr(),new Promise((e,n)=>{Vr("release",[e,n]);let r={type:"release",in:t};bt.postMessage(r)});Jp(t)},ud=async(t,e,n,r,s,i)=>{if(xr()){if(n.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wr(),new Promise((a,u)=>{Vr("run",[a,u]);let d=n,o={type:"run",in:{sessionId:t,inputIndices:e,inputs:d,outputIndices:r,options:i}};bt.postMessage(o,ed(d))})}else return Zp(t,e,n,r,s,i)},ld=async t=>{if(xr())return Wr(),new Promise((e,n)=>{Vr("end-profiling",[e,n]);let r={type:"end-profiling",in:t};bt.postMessage(r)});Qp(t)}}),fd,yg,Co,cd=L(()=>{vt(),ma(),fa(),ca(),fd=(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()}`)}},yg=t=>{switch(t[3]){case"cpu":return new Re(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Do(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:s}=t[2];return Re.fromGpuBuffer(n,{dataType:e,dims:t[1],download:r,dispose:s})}default:throw new Error(`invalid data location: ${t[3]}`)}},Co=class{async fetchModelAndCopyToWasmMemory(t){return id(await gn(t))}async loadModel(t,e){ar();let n;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?n=await gn(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await ad(n,e),sr()}async dispose(){return sd(this.sessionId)}async run(t,e,n){ar();let r=[],s=[];Object.entries(t).forEach(c=>{let h=c[0],f=c[1],p=this.inputNames.indexOf(h);if(p===-1)throw new Error(`invalid input '${h}'`);r.push(f),s.push(p)});let i=[],a=[];Object.entries(e).forEach(c=>{let h=c[0],f=c[1],p=this.outputNames.indexOf(h);if(p===-1)throw new Error(`invalid output '${h}'`);i.push(f),a.push(p)});let u=r.map((c,h)=>fd(c,()=>`input "${this.inputNames[s[h]]}"`)),d=i.map((c,h)=>c?fd(c,()=>`output "${this.outputNames[a[h]]}"`):null),o=await ud(this.sessionId,s,u,a,d,n),l={};for(let c=0;c{vt(),ma(),cd(),Tg=()=>{if((typeof Z.wasm.initTimeout!="number"||Z.wasm.initTimeout<0)&&(Z.wasm.initTimeout=0),typeof Z.wasm.simd!="boolean"&&(Z.wasm.simd=!0),typeof Z.wasm.proxy!="boolean"&&(Z.wasm.proxy=!1),typeof Z.wasm.trace!="boolean"&&(Z.wasm.trace=!1),typeof Z.wasm.numThreads!="number"||!Number.isInteger(Z.wasm.numThreads)||Z.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Z.wasm.numThreads=1);let t=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Z.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ko=class{async init(t){Tg(),await nd(),await od(t)}async createInferenceSessionHandler(t,e){let n=new Co;return await n.loadModel(t,e),Promise.resolve(n)}}}),dd={};Pr(dd,{wasmBackend:()=>xg});var xg,hd=L(()=>{pd(),xg=new ko});vt();vt();vt();var ys="1.17.1",zO=Yo;{let t=(_p(),rr(wp)).onnxjsBackend;or("webgl",t,-10)}{let t=(hd(),rr(dd)).wasmBackend;or("cpu",t,10),or("wasm",t,10),or("webnn",t,9)}Object.defineProperty(Z.versions,"web",{value:ys,enumerable:!0});/*! Bundled license information: + +long/index.js: + (** + * @license + * Copyright 2009 The Closure Library Authors + * Copyright 2020 Daniel Wirtz / The long.js Authors. + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + *) +*/const ONNX_WEB=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Sd},get TRACE(){return cs},get TRACE_FUNC_BEGIN(){return ar},get TRACE_FUNC_END(){return sr},get Tensor(){return Re},get TrainingSession(){return Pd},default:zO,get env(){return Z},get registerBackend(){return or}},Symbol.toStringTag,{value:"Module"})),tensorToDataURL=(t,e)=>{const n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=t.dims[3],n.height=t.dims[2];const r=n.getContext("2d");if(r!=null){let s,i;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[3]):(s=t.dims[3],i=t.dims[2]);const a=e?.format!==void 0?e.format:"RGB",u=e?.norm;let d,o;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?o=[0,0,0,0]:typeof u.bias=="number"?o=[u.bias,u.bias,u.bias,u.bias]:(o=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(o[3]=u.bias[3]));const l=i*s;let c=0,h=l,f=l*2,p=-1;a==="RGBA"?(c=0,h=l,f=l*2,p=l*3):a==="RGB"?(c=0,h=l,f=l*2):a==="RBG"&&(c=0,f=l,h=l*2);for(let g=0;g{const n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(n!=null){let s,i,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=t.dims[2],i=t.dims[1],a=t.dims[3]):(s=t.dims[3],i=t.dims[2],a=t.dims[1]);const u=e!==void 0&&e.format!==void 0?e.format:"RGB",d=e?.norm;let o,l;d===void 0||d.mean===void 0?o=[255,255,255,255]:typeof d.mean=="number"?o=[d.mean,d.mean,d.mean,d.mean]:(o=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(o[3]=d.mean[3])),d===void 0||d.bias===void 0?l=[0,0,0,0]:typeof d.bias=="number"?l=[d.bias,d.bias,d.bias,d.bias]:(l=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(l[3]=d.bias[3]));const c=i*s;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let f=0,p=1,g=2,b=3,x=0,y=c,T=c*2,S=-1;u==="RGBA"?(x=0,y=c,T=c*2,S=c*3):u==="RGB"?(x=0,y=c,T=c*2):u==="RBG"&&(x=0,T=c,y=c*2),r=n.createImageData(s,i);for(let E=0;E{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:n,width:r}=e,s=e.norm??{mean:255,bias:0};let i,a;typeof s.mean=="number"?i=[s.mean,s.mean,s.mean,s.mean]:i=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?a=[s.bias,s.bias,s.bias,s.bias]:a=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];const u=e.format!==void 0?e.format:"RGBA",d=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",o=n*r,l=d==="RGBA"?new Float32Array(o*4):new Float32Array(o*3);let c=4,h=0,f=1,p=2,g=3,b=0,x=o,y=o*2,T=-1;u==="RGB"&&(c=3,h=0,f=1,p=2,g=-1),d==="RGBA"?T=o*3:d==="RBG"?(b=0,y=o,x=o*2):d==="BGR"&&(y=0,x=o,b=o*2);for(let E=0;E{const n=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,r=typeof ImageData<"u"&&t instanceof ImageData,s=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,i=typeof t=="string";let a,u=e??{};const d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},o=l=>l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas?l.getContext("2d"):null;if(n){const l=d();l.width=t.width,l.height=t.height;const c=o(l);if(c!=null){let h=t.height,f=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(h=e.resizedHeight,f=e.resizedWidth),e!==void 0){if(u=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=h,u.width=f}else u.tensorFormat="RGBA",u.height=h,u.width=f;c.drawImage(t,0,0),a=c.getImageData(0,0,f,h).data}else throw new Error("Can not access image data")}else if(r){let l,c;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(l=e.resizedHeight,c=e.resizedWidth):(l=t.height,c=t.width),e!==void 0&&(u=e),u.format="RGBA",u.height=l,u.width=c,e!==void 0){const h=d();h.width=c,h.height=l;const f=o(h);if(f!=null)f.putImageData(t,0,0),a=f.getImageData(0,0,c,l).data;else throw new Error("Can not access image data")}else a=t.data}else if(s){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");const l=d();l.width=t.width,l.height=t.height;const c=o(l);if(c!=null){const h=t.height,f=t.width;return c.drawImage(t,0,0,f,h),a=c.getImageData(0,0,f,h).data,u.height=h,u.width=f,bufferToTensor(a,u)}else throw new Error("Can not access image data")}else{if(i)return new Promise((l,c)=>{const h=d(),f=o(h);if(!t||!f)return c();const p=new Image;p.crossOrigin="Anonymous",p.src=t,p.onload=()=>{h.width=p.width,h.height=p.height,f.drawImage(p,0,0,h.width,h.height);const g=f.getImageData(0,0,h.width,h.height);u.height=h.height,u.width=h.width,l(bufferToTensor(g.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return bufferToTensor(a,u);throw new Error("Input data provided is not supported - aborted tensor creation")},tensorFromTexture=(t,e)=>{const{width:n,height:r,download:s,dispose:i}=e,a=[1,r,n,4];return new Tensor$2({location:"texture",type:"float32",texture:t,dims:a,download:s,dispose:i})},tensorFromGpuBuffer=(t,e)=>{const{dataType:n,dims:r,download:s,dispose:i}=e;return new Tensor$2({location:"gpu-buffer",type:n??"float32",gpuBuffer:t,dims:r,download:s,dispose:i})},tensorFromPinnedBuffer=(t,e,n)=>new Tensor$2({location:"cpu-pinned",type:t,data:e,dims:n??[e.length]}),NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let isBigIntChecked=!1;const checkBigInt=()=>{if(!isBigIntChecked){isBigIntChecked=!0;const t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")),e&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64"))}},calculateSize=t=>{let e=1;for(let n=0;n{switch(t.location){case"cpu":return new Tensor$2(t.type,t.data,e);case"cpu-pinned":return new Tensor$2({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Tensor$2({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Tensor$2({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let Tensor$2=class{constructor(e,n,r){checkBigInt();let s,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,i=e.dims,e.location){case"cpu-pinned":{const u=NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(s);if(!u)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof u))throw new TypeError(`buffer should be of type ${u.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="bool")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let u,d;if(typeof e=="string")if(s=e,d=r,e==="string"){if(!Array.isArray(n))throw new TypeError("A string tensor's data must be a string array.");u=n}else{const o=NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(o===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(n)){if(e==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?u=o.from(n,BigInt):u=o.from(n)}else if(n instanceof o)u=n;else throw new TypeError(`A ${s} tensor's data must be type of ${o}`)}else if(d=n,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const o=typeof e[0];if(o==="string")s="string",u=e;else if(o==="boolean")s="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${o}.`)}else{const o=NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(e.constructor);if(o===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=o,u=e}if(d===void 0)d=[u.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");i=d,this.cpuData=u,this.dataLocation="cpu"}const a=calculateSize(i);if(this.cpuData&&a!==this.cpuData.length)throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=i,this.size=a}static async fromImage(e,n){return tensorFromImage(e,n)}static fromTexture(e,n){return tensorFromTexture(e,n)}static fromGpuBuffer(e,n){return tensorFromGpuBuffer(e,n)}static fromPinnedBuffer(e,n,r){return tensorFromPinnedBuffer(e,n,r)}toDataURL(e){return tensorToDataURL(this,e)}toImageData(e){return tensorToImageData(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const n=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=n,e&&this.disposer&&(this.disposer(),this.disposer=void 0),n}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return tensorReshape(this,e)}};const Tensor$1=Tensor$2;let ONNX;const WEBGPU_AVAILABLE=typeof navigator<"u"&&"gpu"in navigator,USE_ONNXRUNTIME_NODE=typeof process<"u"&&process?.release?.name==="node",ONNX_MODULES=new Map;USE_ONNXRUNTIME_NODE?(ONNX=sharp??ONNX_NODE,ONNX_MODULES.set("node",ONNX)):(ONNX=zO??ONNX_WEB,ONNX_MODULES.set("web",ONNX),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(ONNX.env.wasm.simd=!1));async function createInferenceSession(t,e){let n,r;if(USE_ONNXRUNTIME_NODE){const i=ONNX_MODULES.get("node");r=i.InferenceSession,n=["cpu"],Object.assign(i.env,env.backends.onnx)}else if(WEBGPU_AVAILABLE&&env.experimental.useWebGPU){let i=ONNX_MODULES.get("webgpu");i===void 0&&(i=await __vitePreload(()=>import("./ort.webgpu.min-BaaO-cT5.js"),__vite__mapDeps([])),ONNX_MODULES.set("webgpu",i)),r=i.InferenceSession,n=["webgpu","wasm"],Object.assign(i.env,env.backends.onnx)}else{const i=ONNX_MODULES.get("web");r=i.InferenceSession,n=["wasm"],Object.assign(i.env,env.backends.onnx)}const s={executionProviders:n,...e};return await r.create(t,s)}function isONNXTensor(t){for(const e of ONNX_MODULES.values())if(t instanceof e.Tensor)return!0;return!1}function isONNXProxy(){return ONNX.env.wasm.proxy}ONNX.env.wasm.wasmPaths=RUNNING_LOCALLY?sharp.join(env.__dirname,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${env.version}/dist/`;env.backends.onnx=ONNX.env;const DataTypeMap=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 Tensor{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}ort_tensor;constructor(...e){return isONNXTensor(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Tensor$1(e[0],e[1],e[2]),new Proxy(this,{get:(n,r)=>{if(typeof r=="string"){let s=Number(r);if(Number.isInteger(s))return n._getitem(s)}return n[r]},set:(n,r,s)=>n[r]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...n]=this.dims;if(n.length>0){const r=n.reduce((s,i)=>s*i);for(let s=0;s0){const s=r.reduce((i,a)=>i*a);return this._subarray(e,s,r)}else return new Tensor(this.type,[this.data[e]],r)}indexOf(e){for(let n=0;no[1])throw new Error(`Invalid slice: ${o}`);let l=[Math.max(o[0],0),Math.min(o[1],this.dims[d])];r.push(l),n.push(l[1]-l[0])}else throw new Error(`Invalid slice: ${o}`)}let s=r.map(([d,o])=>o-d),i=s.reduce((d,o)=>d*o),a=new this.data.constructor(i);const u=this.stride();for(let d=0;d=0;--l){const h=s[l];o+=(c%h+r[l][0])*u[l],c=Math.floor(c/h)}a[d]=this.data[o]}return new Tensor(this.type,a,n)}transpose(...e){return transpose(this,e)}sum(e=null,n=!1){return this.norm(1,e,n)}norm(e="fro",n=null,r=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);if(n===null){let a=this.data.reduce((u,d)=>u+d**e,0)**(1/e);return new Tensor(this.type,[a],[])}n=safeIndex(n,this.dims.length);const s=this.dims.slice();s[n]=1;const i=new this.data.constructor(this.data.length/this.dims[n]);for(let a=0;a=0;--d){const c=this.dims[d];if(d!==n){const h=o%c;u+=h*l,l*=s[d]}o=Math.floor(o/c)}i[u]+=this.data[a]**e}if(e!==1)for(let a=0;a=0;--a){const o=this.dims[a];if(a!==n){const l=u%o;i+=l*d,d*=this.dims[a]}u=Math.floor(u/o)}this.data[s]/=r.data[i]}return this}normalize(e=2,n=1){return this.clone().normalize_(e,n)}stride(){return dimsToStride(this.dims)}squeeze(e=null){return new Tensor(this.type,this.data,calc_squeeze_dims(this.dims,e))}squeeze_(e=null){return this.dims=calc_squeeze_dims(this.dims,e),this}unsqueeze(e=null){return new Tensor(this.type,this.data,calc_unsqueeze_dims(this.dims,e))}unsqueeze_(e=null){return this.dims=calc_unsqueeze_dims(this.dims,e),this}flatten_(e=0,n=-1){n=(n+this.dims.length)%this.dims.length;let r=this.dims.slice(0,e),s=this.dims.slice(e,n+1),i=this.dims.slice(n+1);return this.dims=[...r,s.reduce((a,u)=>a*u,1),...i],this}flatten(e=0,n=-1){return this.clone().flatten_(e,n)}view(...e){let n=-1;for(let r=0;ra!==n?s*i:s,1);e[n]=this.data.length/r}return new Tensor(this.type,this.data,e)}neg_(){for(let e=0;ei*a);if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${e})`);let s=t;for(let i=e.length-1;i>=0;i--)s=s.reduce((a,u)=>{let d=a[a.length-1];return d.lengthn!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((n,r)=>n!==1||!e.includes(r))),t}function calc_unsqueeze_dims(t,e){return e=safeIndex(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function safeIndex(t,e,n=null){if(t<-e||t>=e)throw new Error(`IndexError: index ${t} is out of bounds for dimension${n===null?"":" "+n} with size ${e}`);return t<0&&(t=(t%e+e)%e),t}function cat(t,e=0){e=safeIndex(e,t[0].dims.length);const n=t[0].dims.slice();n[e]=t.reduce((a,u)=>a+u.dims[e],0);const r=n.reduce((a,u)=>a*u,1),s=new t[0].data.constructor(r),i=t[0].type;if(e===0){let a=0;for(let u of t)s.set(u.data,a),a+=u.data.length}else{let a=0;for(let u=0;u=0;--c){const p=d.dims[c];let g=h%p;c===e&&(g+=a),l+=g*f,f*=n[c],h=Math.floor(h/p)}s[l]=d.data[o]}a+=d.dims[e]}}return new Tensor(i,s,n)}function stack(t,e=0){return cat(t.map(n=>n.unsqueeze(e)),e)}function std_mean(t,e=null,n=1,r=!1){if(e===null){const o=t.data.reduce((f,p)=>f+p,0)/t.data.length,l=Math.sqrt(t.data.reduce((f,p)=>f+(p-o)**2,0)/(t.data.length-n)),c=new Tensor(t.type,[o],[]);return[new Tensor(t.type,[l],[]),c]}e=safeIndex(e,t.dims.length);const s=mean(t,e,r),i=t.dims.slice();i[e]=1;const a=new t.data.constructor(t.data.length/t.dims[e]);for(let d=0;d=0;--l){const f=t.dims[l];if(l!==e){const p=c%f;o+=p*h,h*=i[l]}c=Math.floor(c/f)}a[o]+=(t.data[d]-s.data[o])**2}for(let d=0;da+u,0);return new Tensor(t.type,[i/t.data.length],[])}e=safeIndex(e,t.dims.length);const r=t.dims.slice();r[e]=1;const s=new t.data.constructor(t.data.length/t.dims[e]);for(let i=0;i=0;--u){const l=t.dims[u];if(u!==e){const c=d%l;a+=c*o,o*=r[u]}d=Math.floor(d/l)}s[a]+=t.data[i]}if(t.dims[e]!==1)for(let i=0;i0||u>0;)switch(d.push(a-1),o.push(u-1),i[a][u].item()){case 0:--a,--u;break;case 1:--a;break;case 2:--u;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${u}]. Please file a bug report.`)}return d.reverse(),o.reverse(),[d,o]}function dimsToStride(t){const e=new Array(t.length);for(let n=t.length-1,r=1;n>=0;--n)e[n]=r,r*=t[n];return e}function ones(t){const e=t.reduce((n,r)=>n*r,1);return new Tensor("int64",new BigInt64Array(e).fill(1n),t)}function ones_like(t){return ones(t.dims)}var TOKEN_TYPES=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"});Object.freeze({set:TOKEN_TYPES.Set,for:TOKEN_TYPES.For,in:TOKEN_TYPES.In,is:TOKEN_TYPES.Is,if:TOKEN_TYPES.If,else:TOKEN_TYPES.Else,endif:TOKEN_TYPES.EndIf,elif:TOKEN_TYPES.ElseIf,endfor:TOKEN_TYPES.EndFor,and:TOKEN_TYPES.And,or:TOKEN_TYPES.Or,not:TOKEN_TYPES.Not,"not in":TOKEN_TYPES.NotIn,true:TOKEN_TYPES.BooleanLiteral,false:TOKEN_TYPES.BooleanLiteral});TOKEN_TYPES.OpenStatement,TOKEN_TYPES.CloseStatement,TOKEN_TYPES.OpenExpression,TOKEN_TYPES.CloseExpression,TOKEN_TYPES.OpenParen,TOKEN_TYPES.CloseParen,TOKEN_TYPES.OpenCurlyBracket,TOKEN_TYPES.CloseCurlyBracket,TOKEN_TYPES.OpenSquareBracket,TOKEN_TYPES.CloseSquareBracket,TOKEN_TYPES.Comma,TOKEN_TYPES.Dot,TOKEN_TYPES.Colon,TOKEN_TYPES.Pipe,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.ComparisonBinaryOperator,TOKEN_TYPES.AdditiveBinaryOperator,TOKEN_TYPES.AdditiveBinaryOperator,TOKEN_TYPES.MultiplicativeBinaryOperator,TOKEN_TYPES.MultiplicativeBinaryOperator,TOKEN_TYPES.MultiplicativeBinaryOperator,TOKEN_TYPES.Equals;const BYTES_TO_UNICODE=(()=>{const t=[...Array.from({length:94},(s,i)=>i+33),...Array.from({length:12},(s,i)=>i+161),...Array.from({length:82},(s,i)=>i+174)],e=t.slice();let n=0;for(let s=0;s<256;++s)t.includes(s)||(t.push(s),e.push(256+n),n+=1);const r=e.map(s=>String.fromCharCode(s));return Object.fromEntries(t.map((s,i)=>[s,r[i]]))})();reverseDictionary(BYTES_TO_UNICODE);const WHISPER_LANGUAGES=[["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"]];new Map(WHISPER_LANGUAGES);async function loadConfig(t,e){return await getModelJSON(t,"config.json",!0,e)}class PretrainedConfig{constructor(e){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,e)}static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:i=!1,revision:a="main"}={}){let u=r??await loadConfig(e,{progress_callback:n,config:r,cache_dir:s,local_files_only:i,revision:a});return new this(u)}}class AutoConfig{static async from_pretrained(...e){return PretrainedConfig.from_pretrained(...e)}}class LogitsProcessorList extends Callable{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,n){for(let r of n)this.processors.forEach(s=>s(e,r))}[Symbol.iterator](){return this.processors.values()}}class LogitsProcessor extends Callable{_call(e,n){throw Error("`_call` should be implemented in a subclass")}}class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.force_token_map=Object.fromEntries(e??[])}_call(e,n){let r=this.force_token_map[e.length];return exists(r)&&(n.data.fill(-1/0),n.data[r]=0),n}}class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.bos_token_id=e}_call(e,n){return e.length===1&&(n.data.fill(-1/0),n.data[this.bos_token_id]=0),n}}class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(e,n){super(),this.max_length=e,this.forced_eos_token_id=n}_call(e,n){}}class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor{constructor(e,n){super(),this.begin_suppress_tokens=e,this.begin_index=n}_call(e,n){if(e.length===this.begin_index)for(let r of this.begin_suppress_tokens)n.data[r]=-1/0;return n}}class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.eos_token_id=e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(e.forced_decoder_ids||[]).length+2,e.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,n){const r=n.data;if(r[this.no_timestamps_token_id]=-1/0,e.length===this.begin_index-1)return r.fill(-1/0),r[this.timestamp_begin]=0,n;const s=e.slice(this.begin_index),i=s.length>=1&&s[s.length-1]>=this.timestamp_begin,a=s.length<2||s[s.length-2]>=this.timestamp_begin;if(i&&(a?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e.length===this.begin_index&&this.max_initial_timestamp_index!==null){const l=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(l+1).fill(-1/0)}const u=log_softmax(r),d=Math.log(u.subarray(this.timestamp_begin).map(Math.exp).reduce((l,c)=>l+c)),o=max(u.subarray(0,this.timestamp_begin))[0];return d>o&&r.subarray(0,this.timestamp_begin).fill(-1/0),n}}class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const n=e.length,r=[];for(let i=0;i0&&(s=s.map(i=>i/this.generation_config.temperature)),s}randomSelect(e){let n=e.reduce((s,i)=>s+i,0),r=Math.random()*n;for(let s=0;s1)return new BeamSearchSampler(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 GreedySampler(e)}}class GreedySampler extends Sampler{sample(e,n=-1){let r=this.getLogits(e,n);return[[max(r)[1],0]]}}class MultinomialSampler extends Sampler{sample(e,n=-1){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const s=this.getLogits(e,n),i=getTopItems(s,r),a=softmax(i.map(u=>u[1]));return Array.from({length:this.generation_config.num_beams},()=>{const u=this.randomSelect(a);return[i[u][0],Math.log(a[u])]})}}class BeamSearchSampler extends Sampler{sample(e,n=-1){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const s=this.getLogits(e,n),i=getTopItems(s,r),a=softmax(i.map(u=>u[1]));return Array.from({length:this.generation_config.num_beams},(u,d)=>[i[d][0],Math.log(a[d])])}}const MODEL_TYPES={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5},MODEL_TYPE_MAPPING=new Map,MODEL_NAME_TO_CLASS_MAPPING=new Map,MODEL_CLASS_TO_NAME_MAPPING=new Map;async function constructSession(t,e,n){const r=`onnx/${e}${n.quantized?"_quantized":""}.onnx`,s=await getModelFile(t,r,!0,n);let i=n.session_options||{};return await createInferenceSession(s,i)}function validateInputs(t,e){const n=Object.create(null),r=[];for(const a of t.inputNames){const u=e[a];if(!(u instanceof Tensor)){r.push(a);continue}n[a]=isONNXProxy()?u.clone():u}if(r.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const s=Object.keys(e).length,i=t.inputNames.length;if(s>i){let a=Object.keys(e).filter(u=>!t.inputNames.includes(u));console.warn(`WARNING: Too many inputs were provided (${s} > ${i}). The following inputs will be ignored: "${a.join(", ")}".`)}return n}async function sessionRun(t,e){const n=validateInputs(t,e);try{const r=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,a.ort_tensor]));let s=await t.run(r);s=replaceTensors(s);for(const[i,a]of Object.entries(n))i.startsWith("past_key_values")&&a.dispose();return s}catch(r){throw console.error(`An error occurred during model execution: "${r}".`),console.error("Inputs given to model:",n),r}}function replaceTensors(t){for(let e in t)isONNXTensor(t[e])?t[e]=new Tensor(t[e]):typeof t[e]=="object"&&replaceTensors(t[e]);return t}function toI64Tensor(t){if(t instanceof Tensor)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 Tensor("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new Tensor("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function prepareAttentionMask(t,e){let n=t.config.pad_token_id??null,r=t.config.eos_token_id??null;isIntegralNumber(r)&&(r=[r]);let s=e.indexOf(n)!==-1,i=r===null||!r.includes(n);if(s&&i){let a=BigInt64Array.from(e.data.map(u=>u!=n));return new Tensor("int64",a,e.dims)}else return ones_like(e)}function preparePositionIds(t,e,n){if(!t.inputNames.includes("position_ids"))return;const r=new BigInt64Array(e.attention_mask.data.length);for(let s=0;s0&&s.push(new NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&s.push(new NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&s.push(new MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&s.push(new MinNewTokensLengthLogitsProcessor(n,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&s.push(new ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&s.push(new ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let i=n>1||e.forced_bos_token_id===null?n:n+1;e.forced_decoder_ids!==null&&(i+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]),s.push(new SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,i))}return e.forced_decoder_ids!==null&&s.push(new ForceTokensLogitsProcessor(e.forced_decoder_ids)),r!==null&&s.extend(r),s}_get_generation_config(e){let n=new GenerationConfig(this.config);return"generation_config"in this&&Object.assign(n,this.generation_config),e!==null&&Object.assign(n,e),n}async generate(e,n=null,r=null,{inputs_attention_mask:s=null}={}){if(!this.can_generate){let b=`The current model class (${MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor)}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;const x=this.config.model_type,y=MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(x)??MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(x)??MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(x)??MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(x);throw y&&(b+=` Please use the following class instead: '${y[0]}'`),Error(b)}if(!(e instanceof Tensor)&&!isTypedArray(e)&&!Array.isArray(e))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${e.constructor.name}".`);let i;if(this.config.is_encoder_decoder)i=0;else if(i=e instanceof Tensor?e.dims.at(-1):e.length,i===0)throw Error("Must supply a non-empty array of input token ids.");n=this._get_generation_config(n),r=r??new LogitsProcessorList,r=this._get_logits_processor(n,i,r);let a=n.eos_token_id;a!==null&&!Array.isArray(a)&&(a=[a]);let u=1;const d=u+(n.max_new_tokens??1/0),o=Number.isInteger(n.max_length)&&(n.max_new_tokens??null)===null;let l=Sampler.getSampler(n),c=this.getStartBeams(e,n,u,s);for(;c.some(g=>!g.done)&&u=n.max_length){b.done=!0,g.push(b);continue}let x=await this.runBeam(b);n.output_attentions&&this.addAttentionsToBeam(b,x),n.output_scores;let y=x.logits.slice(null,-1,null);r(b.output_token_ids,y);let T=l(y);for(let[S,E]of T){let N={...b};this.updateBeam(N,S),N.score+=E,a&&a.includes(S)&&(N.done=!0),g.push(N)}}++u,g=this.groupBeams(g).map(b=>b.sort((x,y)=>y.score-x.score).slice(0,n.num_beams)),c=g.flat(),n.callback_function&&n.callback_function(c)}const h=this.groupBeams(c),f=g=>h.map(b=>n.num_return_sequences>1?b.slice(0,n.num_return_sequences).map(x=>x[g]):[b[0][g]]).flat(),p=f("output_token_ids");if(n.return_dict_in_generate){const g=f("decoder_attentions"),b=f("cross_attentions");return{sequences:p,decoder_attentions:g,cross_attentions:b}}else return p}addAttentionsToBeam(e,n){if(this.config.is_encoder_decoder){if(!n.cross_attentions||n.cross_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.cross_attentions||(e.cross_attentions=[]),e.cross_attentions.push(n.cross_attentions)}if(!n.decoder_attentions||n.decoder_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");e.decoder_attentions||(e.decoder_attentions=[]),e.decoder_attentions.push(n.decoder_attentions)}groupBeams(e){const n=Object.create(null);for(const r of e)n[r.id]===void 0?n[r.id]=[r]:n[r.id].push(r);return Object.values(n)}getPastKeyValues(e,n){const r=Object.create(null);for(const s in e)if(s.startsWith("present")){let i=s.replace("present","past_key_values");n&&s.includes("encoder")?r[i]=n[i]:r[i]=e[s]}return r}getAttentions(e){const n=Object.create(null);for(const r of["cross_attentions","decoder_attentions"]){const s=[];for(const i in e)if(i.startsWith(r)){const a=i.split(".").pop();s[a]=e[i]}n[r]=s}return n}addPastKeyValues(e,n){if(n)Object.assign(e,n);else{const s=this.config.precision||"float32",i=s==="float16"?new Uint16Array:[];if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??!0)){let a=[1,this.num_encoder_heads,0,this.encoder_dim_kv],u=[1,this.num_decoder_heads,0,this.decoder_dim_kv];for(let d=0;d{let l=Array.from({length:this.config.decoder_layers},(b,x)=>cat(o.map(y=>y[x]),2)),c=stack(n.map(([b,x])=>r?l[b].slice(null,x,null,[0,r]):l[b].slice(null,x)));c=c.transpose(1,0,2,3);let[h,f]=std_mean(c,-2,0,!0),p=c.clone();for(let b=0;bc[x+1]-c[x]),p=mergeArrays([1],f).map(b=>!!b),g=[];for(let b=0;bs*i,1);e.input_labels=new Tensor("int64",new BigInt64Array(r).fill(1n),n)}return await sessionRun(this.prompt_encoder_mask_decoder,{input_points:e.input_points,input_labels:e.input_labels,image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings})}async _call(e){return new SamImageSegmentationOutput(await super._call(e))}}class SamImageSegmentationOutput extends ModelOutput{constructor({iou_scores:e,pred_masks:n}){super(),this.iou_scores=e,this.pred_masks=n}}class MarianPreTrainedModel extends PreTrainedModel{}class MarianModel extends MarianPreTrainedModel{}class MarianMTModel extends MarianPreTrainedModel{constructor(e,n,r,s){super(e,n),this.decoder_merged_session=r,this.generation_config=s,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class M2M100PreTrainedModel extends PreTrainedModel{}class M2M100Model extends M2M100PreTrainedModel{}class M2M100ForConditionalGeneration extends M2M100PreTrainedModel{constructor(e,n,r,s){super(e,n),this.decoder_merged_session=r,this.generation_config=s,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class Wav2Vec2PreTrainedModel extends PreTrainedModel{}class Wav2Vec2Model extends Wav2Vec2PreTrainedModel{}class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class UniSpeechPreTrainedModel extends PreTrainedModel{}class UniSpeechModel extends UniSpeechPreTrainedModel{}class UniSpeechForCTC extends UniSpeechPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class UniSpeechSatPreTrainedModel extends PreTrainedModel{}class UniSpeechSatModel extends UniSpeechSatPreTrainedModel{}class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class Wav2Vec2BertPreTrainedModel extends PreTrainedModel{}class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel{}class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class HubertModel extends Wav2Vec2PreTrainedModel{}class HubertForCTC extends Wav2Vec2PreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class WavLMPreTrainedModel extends PreTrainedModel{}class WavLMModel extends WavLMPreTrainedModel{}class WavLMForCTC extends WavLMPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class WavLMForSequenceClassification extends WavLMPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class WavLMForXVector extends WavLMPreTrainedModel{async _call(e){return new XVectorOutput(await super._call(e))}}class WavLMForAudioFrameClassification extends WavLMPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class SpeechT5PreTrainedModel extends PreTrainedModel{}class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel{}class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel{constructor(e,n,r,s){super(e,n),this.decoder_merged_session=r,this.generation_config=s,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.hidden_size/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.hidden_size/this.num_encoder_heads}async generate_speech(e,n,{threshold:r=.5,minlenratio:s=0,maxlenratio:i=20,vocoder:a=null}={}){const u={input_ids:e},{encoder_outputs:d,encoder_attention_mask:o}=await encoderForward(this,u),l=d.dims[1]/this.config.reduction_factor,c=Math.floor(l*i),h=Math.floor(l*s),f=this.config.num_mel_bins;let p=[],g=null,b=null,x=0;for(;;){++x;const S=boolTensor(!!b);let E;b?E=b.output_sequence_out:E=new Tensor("float32",new Float32Array(f),[1,1,f]);let N={use_cache_branch:S,output_sequence:E,encoder_attention_mask:o,speaker_embeddings:n,encoder_hidden_states:d};this.addPastKeyValues(N,g),b=await sessionRun(this.decoder_merged_session,N),g=this.getPastKeyValues(b,g);const{prob:B,spectrum:F}=b;if(p.push(F),x>=h&&(Array.from(B.data).filter(k=>k>=r).length>0||x>=c))break}const y=cat(p),{waveform:T}=await sessionRun(a.session,{spectrogram:y});return{spectrogram:y,waveform:T}}}class SpeechT5HifiGan extends PreTrainedModel{main_input_name="spectrogram"}class TrOCRPreTrainedModel extends PreTrainedModel{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,this.num_encoder_layers=this.num_decoder_layers=this.config.decoder_layers,this.num_encoder_heads=this.num_decoder_heads=this.config.decoder_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads}}class TrOCRForCausalLM extends TrOCRPreTrainedModel{}class MistralPreTrainedModel extends PreTrainedModel{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class MistralModel extends MistralPreTrainedModel{}class MistralForCausalLM extends MistralPreTrainedModel{}class Starcoder2PreTrainedModel extends PreTrainedModel{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Starcoder2Model extends Starcoder2PreTrainedModel{}class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel{}class FalconPreTrainedModel extends PreTrainedModel{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class FalconModel extends FalconPreTrainedModel{}class FalconForCausalLM extends FalconPreTrainedModel{}class ClapPreTrainedModel extends PreTrainedModel{}class ClapModel extends ClapPreTrainedModel{}class ClapTextModelWithProjection extends ClapPreTrainedModel{static async from_pretrained(e,n={}){return n.model_file_name??="text_model",super.from_pretrained(e,n)}}class ClapAudioModelWithProjection extends ClapPreTrainedModel{static async from_pretrained(e,n={}){return n.model_file_name??="audio_model",super.from_pretrained(e,n)}}class VitsPreTrainedModel extends PreTrainedModel{}class VitsModel extends VitsPreTrainedModel{async _call(e){return new VitsModelOutput(await super._call(e))}}class SegformerPreTrainedModel extends PreTrainedModel{}class SegformerForImageClassification extends SegformerPreTrainedModel{}class SegformerForSemanticSegmentation extends SegformerPreTrainedModel{}class StableLmPreTrainedModel extends PreTrainedModel{constructor(e,n,r){super(e,n),this.generation_config=r,this.config.pad_token_id=this.config.eos_token_id,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.num_heads}}class StableLmForCausalLM extends StableLmPreTrainedModel{}class PretrainedMixin{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{quantized:n=!0,progress_callback:r=null,config:s=null,cache_dir:i=null,local_files_only:a=!1,revision:u="main",model_file_name:d=null,session_options:o={}}={}){let l={quantized:n,progress_callback:r,config:s,cache_dir:i,local_files_only:a,revision:u,model_file_name:d,session_options:o};if(s=await AutoConfig.from_pretrained(e,l),l.config||(l.config=s),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let c of this.MODEL_CLASS_MAPPINGS){const h=c.get(s.model_type);if(h)return await h[1].from_pretrained(e,l)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${s.model_type}", attempting to construct from base class.`),await PreTrainedModel.from_pretrained(e,l);throw Error(`Unsupported model type: ${s.model_type}`)}}const MODEL_MAPPING_NAMES_ENCODER_ONLY=new Map([["bert",["BertModel",BertModel]],["nomic_bert",["NomicBertModel",NomicBertModel]],["roformer",["RoFormerModel",RoFormerModel]],["electra",["ElectraModel",ElectraModel]],["esm",["EsmModel",EsmModel]],["convbert",["ConvBertModel",ConvBertModel]],["camembert",["CamembertModel",CamembertModel]],["deberta",["DebertaModel",DebertaModel]],["deberta-v2",["DebertaV2Model",DebertaV2Model]],["mpnet",["MPNetModel",MPNetModel]],["albert",["AlbertModel",AlbertModel]],["distilbert",["DistilBertModel",DistilBertModel]],["roberta",["RobertaModel",RobertaModel]],["xlm",["XLMModel",XLMModel]],["xlm-roberta",["XLMRobertaModel",XLMRobertaModel]],["clap",["ClapModel",ClapModel]],["clip",["CLIPModel",CLIPModel]],["clipseg",["CLIPSegModel",CLIPSegModel]],["chinese_clip",["ChineseCLIPModel",ChineseCLIPModel]],["siglip",["SiglipModel",SiglipModel]],["mobilebert",["MobileBertModel",MobileBertModel]],["squeezebert",["SqueezeBertModel",SqueezeBertModel]],["wav2vec2",["Wav2Vec2Model",Wav2Vec2Model]],["wav2vec2-bert",["Wav2Vec2BertModel",Wav2Vec2BertModel]],["unispeech",["UniSpeechModel",UniSpeechModel]],["unispeech-sat",["UniSpeechSatModel",UniSpeechSatModel]],["hubert",["HubertModel",HubertModel]],["wavlm",["WavLMModel",WavLMModel]],["audio-spectrogram-transformer",["ASTModel",ASTModel]],["vits",["VitsModel",VitsModel]],["detr",["DetrModel",DetrModel]],["table-transformer",["TableTransformerModel",TableTransformerModel]],["vit",["ViTModel",ViTModel]],["mobilevit",["MobileViTModel",MobileViTModel]],["owlvit",["OwlViTModel",OwlViTModel]],["owlv2",["Owlv2Model",Owlv2Model]],["beit",["BeitModel",BeitModel]],["deit",["DeiTModel",DeiTModel]],["convnext",["ConvNextModel",ConvNextModel]],["convnextv2",["ConvNextV2Model",ConvNextV2Model]],["dinov2",["Dinov2Model",Dinov2Model]],["resnet",["ResNetModel",ResNetModel]],["swin",["SwinModel",SwinModel]],["swin2sr",["Swin2SRModel",Swin2SRModel]],["donut-swin",["DonutSwinModel",DonutSwinModel]],["yolos",["YolosModel",YolosModel]],["dpt",["DPTModel",DPTModel]],["glpn",["GLPNModel",GLPNModel]],["hifigan",["SpeechT5HifiGan",SpeechT5HifiGan]],["sam",["SamModel",SamModel]]]),MODEL_MAPPING_NAMES_ENCODER_DECODER=new Map([["t5",["T5Model",T5Model]],["longt5",["LongT5Model",LongT5Model]],["mt5",["MT5Model",MT5Model]],["bart",["BartModel",BartModel]],["mbart",["MBartModel",MBartModel]],["marian",["MarianModel",MarianModel]],["whisper",["WhisperModel",WhisperModel]],["m2m_100",["M2M100Model",M2M100Model]],["blenderbot",["BlenderbotModel",BlenderbotModel]],["blenderbot-small",["BlenderbotSmallModel",BlenderbotSmallModel]]]),MODEL_MAPPING_NAMES_DECODER_ONLY=new Map([["bloom",["BloomModel",BloomModel]],["gpt2",["GPT2Model",GPT2Model]],["gptj",["GPTJModel",GPTJModel]],["gpt_bigcode",["GPTBigCodeModel",GPTBigCodeModel]],["gpt_neo",["GPTNeoModel",GPTNeoModel]],["gpt_neox",["GPTNeoXModel",GPTNeoXModel]],["codegen",["CodeGenModel",CodeGenModel]],["llama",["LlamaModel",LlamaModel]],["qwen2",["Qwen2Model",Qwen2Model]],["phi",["PhiModel",PhiModel]],["mpt",["MptModel",MptModel]],["opt",["OPTModel",OPTModel]],["mistral",["MistralModel",MistralModel]],["starcoder2",["Starcoder2Model",Starcoder2Model]],["falcon",["FalconModel",FalconModel]]]),MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES=new Map([["speecht5",["SpeechT5ForSpeechToText",SpeechT5ForSpeechToText]],["whisper",["WhisperForConditionalGeneration",WhisperForConditionalGeneration]]]),MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES=new Map([["speecht5",["SpeechT5ForTextToSpeech",SpeechT5ForTextToSpeech]]]),MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES=new Map([["vits",["VitsModel",VitsModel]]]),MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES=new Map([["bert",["BertForSequenceClassification",BertForSequenceClassification]],["roformer",["RoFormerForSequenceClassification",RoFormerForSequenceClassification]],["electra",["ElectraForSequenceClassification",ElectraForSequenceClassification]],["esm",["EsmForSequenceClassification",EsmForSequenceClassification]],["convbert",["ConvBertForSequenceClassification",ConvBertForSequenceClassification]],["camembert",["CamembertForSequenceClassification",CamembertForSequenceClassification]],["deberta",["DebertaForSequenceClassification",DebertaForSequenceClassification]],["deberta-v2",["DebertaV2ForSequenceClassification",DebertaV2ForSequenceClassification]],["mpnet",["MPNetForSequenceClassification",MPNetForSequenceClassification]],["albert",["AlbertForSequenceClassification",AlbertForSequenceClassification]],["distilbert",["DistilBertForSequenceClassification",DistilBertForSequenceClassification]],["roberta",["RobertaForSequenceClassification",RobertaForSequenceClassification]],["xlm",["XLMForSequenceClassification",XLMForSequenceClassification]],["xlm-roberta",["XLMRobertaForSequenceClassification",XLMRobertaForSequenceClassification]],["bart",["BartForSequenceClassification",BartForSequenceClassification]],["mbart",["MBartForSequenceClassification",MBartForSequenceClassification]],["mobilebert",["MobileBertForSequenceClassification",MobileBertForSequenceClassification]],["squeezebert",["SqueezeBertForSequenceClassification",SqueezeBertForSequenceClassification]]]),MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES=new Map([["bert",["BertForTokenClassification",BertForTokenClassification]],["roformer",["RoFormerForTokenClassification",RoFormerForTokenClassification]],["electra",["ElectraForTokenClassification",ElectraForTokenClassification]],["esm",["EsmForTokenClassification",EsmForTokenClassification]],["convbert",["ConvBertForTokenClassification",ConvBertForTokenClassification]],["camembert",["CamembertForTokenClassification",CamembertForTokenClassification]],["deberta",["DebertaForTokenClassification",DebertaForTokenClassification]],["deberta-v2",["DebertaV2ForTokenClassification",DebertaV2ForTokenClassification]],["mpnet",["MPNetForTokenClassification",MPNetForTokenClassification]],["distilbert",["DistilBertForTokenClassification",DistilBertForTokenClassification]],["roberta",["RobertaForTokenClassification",RobertaForTokenClassification]],["xlm",["XLMForTokenClassification",XLMForTokenClassification]],["xlm-roberta",["XLMRobertaForTokenClassification",XLMRobertaForTokenClassification]]]),MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES=new Map([["t5",["T5ForConditionalGeneration",T5ForConditionalGeneration]],["longt5",["LongT5ForConditionalGeneration",LongT5ForConditionalGeneration]],["mt5",["MT5ForConditionalGeneration",MT5ForConditionalGeneration]],["bart",["BartForConditionalGeneration",BartForConditionalGeneration]],["mbart",["MBartForConditionalGeneration",MBartForConditionalGeneration]],["marian",["MarianMTModel",MarianMTModel]],["m2m_100",["M2M100ForConditionalGeneration",M2M100ForConditionalGeneration]],["blenderbot",["BlenderbotForConditionalGeneration",BlenderbotForConditionalGeneration]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",BlenderbotSmallForConditionalGeneration]]]),MODEL_WITH_LM_HEAD_MAPPING_NAMES=new Map([["bloom",["BloomForCausalLM",BloomForCausalLM]],["gpt2",["GPT2LMHeadModel",GPT2LMHeadModel]],["gptj",["GPTJForCausalLM",GPTJForCausalLM]],["gpt_bigcode",["GPTBigCodeForCausalLM",GPTBigCodeForCausalLM]],["gpt_neo",["GPTNeoForCausalLM",GPTNeoForCausalLM]],["gpt_neox",["GPTNeoXForCausalLM",GPTNeoXForCausalLM]],["codegen",["CodeGenForCausalLM",CodeGenForCausalLM]],["llama",["LlamaForCausalLM",LlamaForCausalLM]],["qwen2",["Qwen2ForCausalLM",Qwen2ForCausalLM]],["phi",["PhiForCausalLM",PhiForCausalLM]],["mpt",["MptForCausalLM",MptForCausalLM]],["opt",["OPTForCausalLM",OPTForCausalLM]],["mbart",["MBartForCausalLM",MBartForCausalLM]],["mistral",["MistralForCausalLM",MistralForCausalLM]],["starcoder2",["Starcoder2ForCausalLM",Starcoder2ForCausalLM]],["falcon",["FalconForCausalLM",FalconForCausalLM]],["trocr",["TrOCRForCausalLM",TrOCRForCausalLM]],["stablelm",["StableLmForCausalLM",StableLmForCausalLM]]]),MODEL_FOR_MASKED_LM_MAPPING_NAMES=new Map([["bert",["BertForMaskedLM",BertForMaskedLM]],["roformer",["RoFormerForMaskedLM",RoFormerForMaskedLM]],["electra",["ElectraForMaskedLM",ElectraForMaskedLM]],["esm",["EsmForMaskedLM",EsmForMaskedLM]],["convbert",["ConvBertForMaskedLM",ConvBertForMaskedLM]],["camembert",["CamembertForMaskedLM",CamembertForMaskedLM]],["deberta",["DebertaForMaskedLM",DebertaForMaskedLM]],["deberta-v2",["DebertaV2ForMaskedLM",DebertaV2ForMaskedLM]],["mpnet",["MPNetForMaskedLM",MPNetForMaskedLM]],["albert",["AlbertForMaskedLM",AlbertForMaskedLM]],["distilbert",["DistilBertForMaskedLM",DistilBertForMaskedLM]],["roberta",["RobertaForMaskedLM",RobertaForMaskedLM]],["xlm",["XLMWithLMHeadModel",XLMWithLMHeadModel]],["xlm-roberta",["XLMRobertaForMaskedLM",XLMRobertaForMaskedLM]],["mobilebert",["MobileBertForMaskedLM",MobileBertForMaskedLM]],["squeezebert",["SqueezeBertForMaskedLM",SqueezeBertForMaskedLM]]]),MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES=new Map([["bert",["BertForQuestionAnswering",BertForQuestionAnswering]],["roformer",["RoFormerForQuestionAnswering",RoFormerForQuestionAnswering]],["electra",["ElectraForQuestionAnswering",ElectraForQuestionAnswering]],["convbert",["ConvBertForQuestionAnswering",ConvBertForQuestionAnswering]],["camembert",["CamembertForQuestionAnswering",CamembertForQuestionAnswering]],["deberta",["DebertaForQuestionAnswering",DebertaForQuestionAnswering]],["deberta-v2",["DebertaV2ForQuestionAnswering",DebertaV2ForQuestionAnswering]],["mpnet",["MPNetForQuestionAnswering",MPNetForQuestionAnswering]],["albert",["AlbertForQuestionAnswering",AlbertForQuestionAnswering]],["distilbert",["DistilBertForQuestionAnswering",DistilBertForQuestionAnswering]],["roberta",["RobertaForQuestionAnswering",RobertaForQuestionAnswering]],["xlm",["XLMForQuestionAnswering",XLMForQuestionAnswering]],["xlm-roberta",["XLMRobertaForQuestionAnswering",XLMRobertaForQuestionAnswering]],["mobilebert",["MobileBertForQuestionAnswering",MobileBertForQuestionAnswering]],["squeezebert",["SqueezeBertForQuestionAnswering",SqueezeBertForQuestionAnswering]]]),MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",VisionEncoderDecoderModel]]]),MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES=new Map([["vit",["ViTForImageClassification",ViTForImageClassification]],["mobilevit",["MobileViTForImageClassification",MobileViTForImageClassification]],["beit",["BeitForImageClassification",BeitForImageClassification]],["deit",["DeiTForImageClassification",DeiTForImageClassification]],["convnext",["ConvNextForImageClassification",ConvNextForImageClassification]],["convnextv2",["ConvNextV2ForImageClassification",ConvNextV2ForImageClassification]],["dinov2",["Dinov2ForImageClassification",Dinov2ForImageClassification]],["resnet",["ResNetForImageClassification",ResNetForImageClassification]],["swin",["SwinForImageClassification",SwinForImageClassification]],["segformer",["SegformerForImageClassification",SegformerForImageClassification]]]),MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES=new Map([["detr",["DetrForObjectDetection",DetrForObjectDetection]],["table-transformer",["TableTransformerForObjectDetection",TableTransformerForObjectDetection]],["yolos",["YolosForObjectDetection",YolosForObjectDetection]]]),MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES=new Map([["owlvit",["OwlViTForObjectDetection",OwlViTForObjectDetection]],["owlv2",["Owlv2ForObjectDetection",Owlv2ForObjectDetection]]]),MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES=new Map([["detr",["DetrForSegmentation",DetrForSegmentation]],["clipseg",["CLIPSegForImageSegmentation",CLIPSegForImageSegmentation]]]),MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES=new Map([["segformer",["SegformerForSemanticSegmentation",SegformerForSemanticSegmentation]]]),MODEL_FOR_MASK_GENERATION_MAPPING_NAMES=new Map([["sam",["SamModel",SamModel]]]),MODEL_FOR_CTC_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForCTC",Wav2Vec2ForCTC]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Wav2Vec2BertForCTC]],["unispeech",["UniSpeechForCTC",UniSpeechForCTC]],["unispeech-sat",["UniSpeechSatForCTC",UniSpeechSatForCTC]],["wavlm",["WavLMForCTC",WavLMForCTC]],["hubert",["HubertForCTC",HubertForCTC]]]),MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Wav2Vec2ForSequenceClassification]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Wav2Vec2BertForSequenceClassification]],["unispeech",["UniSpeechForSequenceClassification",UniSpeechForSequenceClassification]],["unispeech-sat",["UniSpeechSatForSequenceClassification",UniSpeechSatForSequenceClassification]],["wavlm",["WavLMForSequenceClassification",WavLMForSequenceClassification]],["hubert",["HubertForSequenceClassification",HubertForSequenceClassification]],["audio-spectrogram-transformer",["ASTForAudioClassification",ASTForAudioClassification]]]),MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES=new Map([["wavlm",["WavLMForXVector",WavLMForXVector]]]),MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",UniSpeechSatForAudioFrameClassification]],["wavlm",["WavLMForAudioFrameClassification",WavLMForAudioFrameClassification]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Wav2Vec2ForAudioFrameClassification]]]),MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES=new Map([["vitmatte",["VitMatteForImageMatting",VitMatteForImageMatting]]]),MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Swin2SRForImageSuperResolution]]]),MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES=new Map([["dpt",["DPTForDepthEstimation",DPTForDepthEstimation]],["depth_anything",["DepthAnythingForDepthEstimation",DepthAnythingForDepthEstimation]],["glpn",["GLPNForDepthEstimation",GLPNForDepthEstimation]]]),MODEL_CLASS_TYPE_MAPPING=[[MODEL_MAPPING_NAMES_ENCODER_ONLY,MODEL_TYPES.EncoderOnly],[MODEL_MAPPING_NAMES_ENCODER_DECODER,MODEL_TYPES.EncoderDecoder],[MODEL_MAPPING_NAMES_DECODER_ONLY,MODEL_TYPES.DecoderOnly],[MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_WITH_LM_HEAD_MAPPING_NAMES,MODEL_TYPES.DecoderOnly],[MODEL_FOR_MASKED_LM_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,MODEL_TYPES.Vision2Seq],[MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_MASK_GENERATION_MAPPING_NAMES,MODEL_TYPES.MaskGeneration],[MODEL_FOR_CTC_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly]];for(const[t,e]of MODEL_CLASS_TYPE_MAPPING)for(const[n,r]of t.values())MODEL_TYPE_MAPPING.set(n,e),MODEL_CLASS_TO_NAME_MAPPING.set(r,n),MODEL_NAME_TO_CLASS_MAPPING.set(n,r);const CUSTOM_MAPPING=[["CLIPTextModelWithProjection",CLIPTextModelWithProjection,MODEL_TYPES.EncoderOnly],["CLIPVisionModelWithProjection",CLIPVisionModelWithProjection,MODEL_TYPES.EncoderOnly],["SiglipTextModel",SiglipTextModel,MODEL_TYPES.EncoderOnly],["SiglipVisionModel",SiglipVisionModel,MODEL_TYPES.EncoderOnly],["ClapTextModelWithProjection",ClapTextModelWithProjection,MODEL_TYPES.EncoderOnly],["ClapAudioModelWithProjection",ClapAudioModelWithProjection,MODEL_TYPES.EncoderOnly]];for(const[t,e,n]of CUSTOM_MAPPING)MODEL_TYPE_MAPPING.set(t,n),MODEL_CLASS_TO_NAME_MAPPING.set(e,t),MODEL_NAME_TO_CLASS_MAPPING.set(t,e);class AutoModel extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=MODEL_CLASS_TYPE_MAPPING.map(e=>e[0]);static BASE_IF_FAIL=!0}class Seq2SeqLMOutput extends ModelOutput{constructor({logits:e,past_key_values:n,encoder_outputs:r,decoder_attentions:s=null,cross_attentions:i=null}){super(),this.logits=e,this.past_key_values=n,this.encoder_outputs=r,this.decoder_attentions=s,this.cross_attentions=i}}class SequenceClassifierOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class XVectorOutput extends ModelOutput{constructor({logits:e,embeddings:n}){super(),this.logits=e,this.embeddings=n}}class TokenClassifierOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class MaskedLMOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class QuestionAnsweringModelOutput extends ModelOutput{constructor({start_logits:e,end_logits:n}){super(),this.start_logits=e,this.end_logits=n}}class CausalLMOutput extends ModelOutput{constructor({logits:e}){super(),this.logits=e}}class ImageMattingOutput extends ModelOutput{constructor({alphas:e}){super(),this.alphas=e}}class VitsModelOutput extends ModelOutput{constructor({waveform:e,spectrogram:n}){super(),this.waveform=e,this.spectrogram=n}}const BROWSER_ENV=typeof self<"u";if(!BROWSER_ENV){if(!sharp)throw new Error("Unable to load image processing library.")}/*! + * @kurkle/color v0.3.2 + * https://github.com/kurkle/color#readme + * (c) 2023 Jukka Kurkela + * Released under the MIT License + */function round(t){return t+.5|0}const lim=(t,e,n)=>Math.max(Math.min(t,n),e);function p2b(t){return lim(round(t*2.55),0,255)}function n2b(t){return lim(round(t*255),0,255)}function b2n(t){return lim(round(t/2.55)/100,0,1)}function n2p(t){return lim(round(t*100),0,100)}const map$1={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},hex=[..."0123456789ABCDEF"],h1=t=>hex[t&15],h2=t=>hex[(t&240)>>4]+hex[t&15],eq=t=>(t&240)>>4===(t&15),isShort=t=>eq(t.r)&&eq(t.g)&&eq(t.b)&&eq(t.a);function hexParse(t){var e=t.length,n;return t[0]==="#"&&(e===4||e===5?n={r:255&map$1[t[1]]*17,g:255&map$1[t[2]]*17,b:255&map$1[t[3]]*17,a:e===5?map$1[t[4]]*17:255}:(e===7||e===9)&&(n={r:map$1[t[1]]<<4|map$1[t[2]],g:map$1[t[3]]<<4|map$1[t[4]],b:map$1[t[5]]<<4|map$1[t[6]],a:e===9?map$1[t[7]]<<4|map$1[t[8]]:255})),n}const alpha=(t,e)=>t<255?e(t):"";function hexString(t){var e=isShort(t)?h1:h2;return t?"#"+e(t.r)+e(t.g)+e(t.b)+alpha(t.a,e):void 0}const HUE_RE=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function hsl2rgbn(t,e,n){const r=e*Math.min(n,1-n),s=(i,a=(i+t/30)%12)=>n-r*Math.max(Math.min(a-3,9-a,1),-1);return[s(0),s(8),s(4)]}function hsv2rgbn(t,e,n){const r=(s,i=(s+t/60)%6)=>n-n*e*Math.max(Math.min(i,4-i,1),0);return[r(5),r(3),r(1)]}function hwb2rgbn(t,e,n){const r=hsl2rgbn(t,1,.5);let s;for(e+n>1&&(s=1/(e+n),e*=s,n*=s),s=0;s<3;s++)r[s]*=1-e-n,r[s]+=e;return r}function hueValue(t,e,n,r,s){return t===s?(e-n)/r+(e.5?l/(2-i-a):l/(i+a),d=hueValue(n,r,s,l,i),d=d*60+.5),[d|0,o||0,u]}function calln(t,e,n,r){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,n,r)).map(n2b)}function hsl2rgb(t,e,n){return calln(hsl2rgbn,t,e,n)}function hwb2rgb(t,e,n){return calln(hwb2rgbn,t,e,n)}function hsv2rgb(t,e,n){return calln(hsv2rgbn,t,e,n)}function hue(t){return(t%360+360)%360}function hueParse(t){const e=HUE_RE.exec(t);let n=255,r;if(!e)return;e[5]!==r&&(n=e[6]?p2b(+e[5]):n2b(+e[5]));const s=hue(+e[2]),i=+e[3]/100,a=+e[4]/100;return e[1]==="hwb"?r=hwb2rgb(s,i,a):e[1]==="hsv"?r=hsv2rgb(s,i,a):r=hsl2rgb(s,i,a),{r:r[0],g:r[1],b:r[2],a:n}}function rotate(t,e){var n=rgb2hsl(t);n[0]=hue(n[0]+e),n=hsl2rgb(n),t.r=n[0],t.g=n[1],t.b=n[2]}function hslString(t){if(!t)return;const e=rgb2hsl(t),n=e[0],r=n2p(e[1]),s=n2p(e[2]);return t.a<255?`hsla(${n}, ${r}%, ${s}%, ${b2n(t.a)})`:`hsl(${n}, ${r}%, ${s}%)`}const map$2={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},names$1={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};function unpack(){const t={},e=Object.keys(names$1),n=Object.keys(map$2);let r,s,i,a,u;for(r=0;r>16&255,i>>8&255,i&255]}return t}let names;function nameParse(t){names||(names=unpack(),names.transparent=[0,0,0,0]);const e=names[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:e.length===4?e[3]:255}}const RGB_RE=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;function rgbParse(t){const e=RGB_RE.exec(t);let n=255,r,s,i;if(e){if(e[7]!==r){const a=+e[7];n=e[8]?p2b(a):lim(a*255,0,255)}return r=+e[1],s=+e[3],i=+e[5],r=255&(e[2]?p2b(r):lim(r,0,255)),s=255&(e[4]?p2b(s):lim(s,0,255)),i=255&(e[6]?p2b(i):lim(i,0,255)),{r,g:s,b:i,a:n}}}function rgbString(t){return t&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${b2n(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`)}const to=t=>t<=.0031308?t*12.92:Math.pow(t,1/2.4)*1.055-.055,from=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function interpolate$1(t,e,n){const r=from(b2n(t.r)),s=from(b2n(t.g)),i=from(b2n(t.b));return{r:n2b(to(r+n*(from(b2n(e.r))-r))),g:n2b(to(s+n*(from(b2n(e.g))-s))),b:n2b(to(i+n*(from(b2n(e.b))-i))),a:t.a+n*(e.a-t.a)}}function modHSL(t,e,n){if(t){let r=rgb2hsl(t);r[e]=Math.max(0,Math.min(r[e]+r[e]*n,e===0?360:1)),r=hsl2rgb(r),t.r=r[0],t.g=r[1],t.b=r[2]}}function clone$1(t,e){return t&&Object.assign(e||{},t)}function fromObject(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=n2b(t[3]))):(e=clone$1(t,{r:0,g:0,b:0,a:1}),e.a=n2b(e.a)),e}function functionParse(t){return t.charAt(0)==="r"?rgbParse(t):hueParse(t)}class Color{constructor(e){if(e instanceof Color)return e;const n=typeof e;let r;n==="object"?r=fromObject(e):n==="string"&&(r=hexParse(e)||nameParse(e)||functionParse(e)),this._rgb=r,this._valid=!!r}get valid(){return this._valid}get rgb(){var e=clone$1(this._rgb);return e&&(e.a=b2n(e.a)),e}set rgb(e){this._rgb=fromObject(e)}rgbString(){return this._valid?rgbString(this._rgb):void 0}hexString(){return this._valid?hexString(this._rgb):void 0}hslString(){return this._valid?hslString(this._rgb):void 0}mix(e,n){if(e){const r=this.rgb,s=e.rgb;let i;const a=n===i?.5:n,u=2*a-1,d=r.a-s.a,o=((u*d===-1?u:(u+d)/(1+u*d))+1)/2;i=1-o,r.r=255&o*r.r+i*s.r+.5,r.g=255&o*r.g+i*s.g+.5,r.b=255&o*r.b+i*s.b+.5,r.a=a*r.a+(1-a)*s.a,this.rgb=r}return this}interpolate(e,n){return e&&(this._rgb=interpolate$1(this._rgb,e._rgb,n)),this}clone(){return new Color(this.rgb)}alpha(e){return this._rgb.a=n2b(e),this}clearer(e){const n=this._rgb;return n.a*=1-e,this}greyscale(){const e=this._rgb,n=round(e.r*.3+e.g*.59+e.b*.11);return e.r=e.g=e.b=n,this}opaquer(e){const n=this._rgb;return n.a*=1+e,this}negate(){const e=this._rgb;return e.r=255-e.r,e.g=255-e.g,e.b=255-e.b,this}lighten(e){return modHSL(this._rgb,2,e),this}darken(e){return modHSL(this._rgb,2,-e),this}saturate(e){return modHSL(this._rgb,1,e),this}desaturate(e){return modHSL(this._rgb,1,-e),this}rotate(e){return rotate(this._rgb,e),this}}/*! + * Chart.js v4.4.2 + * https://www.chartjs.org + * (c) 2024 Chart.js Contributors + * Released under the MIT License + */function noop(){}const uid=(()=>{let t=0;return()=>t++})();function isNullOrUndef(t){return t===null||typeof t>"u"}function isArray(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return e.slice(0,7)==="[object"&&e.slice(-6)==="Array]"}function isObject(t){return t!==null&&Object.prototype.toString.call(t)==="[object Object]"}function isNumberFinite(t){return(typeof t=="number"||t instanceof Number)&&isFinite(+t)}function finiteOrDefault(t,e){return isNumberFinite(t)?t:e}function valueOrDefault(t,e){return typeof t>"u"?e:t}const toPercentage=(t,e)=>typeof t=="string"&&t.endsWith("%")?parseFloat(t)/100:+t/e,toDimension=(t,e)=>typeof t=="string"&&t.endsWith("%")?parseFloat(t)/100*e:+t;function callback(t,e,n){if(t&&typeof t.call=="function")return t.apply(n,e)}function each(t,e,n,r){let s,i,a;if(isArray(t))if(i=t.length,r)for(s=i-1;s>=0;s--)e.call(n,t[s],s);else for(s=0;st,x:t=>t.x,y:t=>t.y};function _splitKey(t){const e=t.split("."),n=[];let r="";for(const s of e)r+=s,r.endsWith("\\")?r=r.slice(0,-1)+".":(n.push(r),r="");return n}function _getKeyResolver(t){const e=_splitKey(t);return n=>{for(const r of e){if(r==="")break;n=n&&n[r]}return n}}function resolveObjectKey(t,e){return(keyResolvers[e]||(keyResolvers[e]=_getKeyResolver(e)))(t)}function _capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}const defined=t=>typeof t<"u",isFunction=t=>typeof t=="function",setsEqual=(t,e)=>{if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0};function _isClickEvent(t){return t.type==="mouseup"||t.type==="click"||t.type==="contextmenu"}const PI=Math.PI,TAU=2*PI,PITAU=TAU+PI,INFINITY=Number.POSITIVE_INFINITY,RAD_PER_DEG=PI/180,HALF_PI=PI/2,QUARTER_PI=PI/4,TWO_THIRDS_PI=PI*2/3,log10=Math.log10,sign=Math.sign;function almostEquals(t,e,n){return Math.abs(t-e)s-i).pop(),e}function isNumber(t){return!isNaN(parseFloat(t))&&isFinite(t)}function almostWhole(t,e){const n=Math.round(t);return n-e<=t&&n+e>=t}function _setMinAndMaxByKey(t,e,n){let r,s,i;for(r=0,s=t.length;rd&&o=Math.min(e,n)-r&&t<=Math.max(e,n)+r}function _lookup(t,e,n){n=n||(a=>t[a]1;)i=s+r>>1,n(i)?s=i:r=i;return{lo:s,hi:r}}const _lookupByKey=(t,e,n,r)=>_lookup(t,n,r?s=>{const i=t[s][e];return it[s][e]_lookup(t,n,r=>t[r][e]>=n);function _filterBetween(t,e,n){let r=0,s=t.length;for(;rr&&t[s-1]>n;)s--;return r>0||s{const r="_onData"+_capitalize(n),s=t[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!1,value(...i){const a=s.apply(this,i);return t._chartjs.listeners.forEach(u=>{typeof u[r]=="function"&&u[r](...i)}),a}})})}function unlistenArrayEvents(t,e){const n=t._chartjs;if(!n)return;const r=n.listeners,s=r.indexOf(e);s!==-1&&r.splice(s,1),!(r.length>0)&&(arrayEvents.forEach(i=>{delete t[i]}),delete t._chartjs)}function _arrayUnique(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const requestAnimFrame=function(){return typeof window>"u"?function(t){return t()}:window.requestAnimationFrame}();function throttled(t,e){let n=[],r=!1;return function(...s){n=s,r||(r=!0,requestAnimFrame.call(window,()=>{r=!1,t.apply(e,n)}))}}function debounce(t,e){let n;return function(...r){return e?(clearTimeout(n),n=setTimeout(t,e,r)):t.apply(this,r),e}}const _toLeftRightCenter=t=>t==="start"?"left":t==="end"?"right":"center",_alignStartEnd=(t,e,n)=>t==="start"?e:t==="end"?n:(e+n)/2,_textX=(t,e,n,r)=>t===(r?"left":"right")?n:t==="center"?(e+n)/2:e;function _getStartAndCountOfVisiblePoints(t,e,n){const r=e.length;let s=0,i=r;if(t._sorted){const{iScale:a,_parsed:u}=t,d=a.axis,{min:o,max:l,minDefined:c,maxDefined:h}=a.getUserBounds();c&&(s=_limitValue(Math.min(_lookupByKey(u,d,o).lo,n?r:_lookupByKey(e,d,a.getPixelForValue(o)).lo),0,r-1)),h?i=_limitValue(Math.max(_lookupByKey(u,a.axis,l,!0).hi+1,n?0:_lookupByKey(e,d,a.getPixelForValue(l),!0).hi+1),s,r)-s:i=r-s}return{start:s,count:i}}function _scaleRangesChanged(t){const{xScale:e,yScale:n,_scaleRanges:r}=t,s={xmin:e.min,xmax:e.max,ymin:n.min,ymax:n.max};if(!r)return t._scaleRanges=s,!0;const i=r.xmin!==e.min||r.xmax!==e.max||r.ymin!==n.min||r.ymax!==n.max;return Object.assign(r,s),i}const atEdge=t=>t===0||t===1,elasticIn=(t,e,n)=>-(Math.pow(2,10*(t-=1))*Math.sin((t-e)*TAU/n)),elasticOut=(t,e,n)=>Math.pow(2,-10*t)*Math.sin((t-e)*TAU/n)+1,effects={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>-Math.cos(t*HALF_PI)+1,easeOutSine:t=>Math.sin(t*HALF_PI),easeInOutSine:t=>-.5*(Math.cos(PI*t)-1),easeInExpo:t=>t===0?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>t===1?1:-Math.pow(2,-10*t)+1,easeInOutExpo:t=>atEdge(t)?t:t<.5?.5*Math.pow(2,10*(t*2-1)):.5*(-Math.pow(2,-10*(t*2-1))+2),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>atEdge(t)?t:elasticIn(t,.075,.3),easeOutElastic:t=>atEdge(t)?t:elasticOut(t,.075,.3),easeInOutElastic(t){return atEdge(t)?t:t<.5?.5*elasticIn(t*2,.1125,.45):.5+.5*elasticOut(t*2-1,.1125,.45)},easeInBack(t){return t*t*((1.70158+1)*t-1.70158)},easeOutBack(t){return(t-=1)*t*((1.70158+1)*t+1.70158)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?.5*(t*t*(((e*=1.525)+1)*t-e)):.5*((t-=2)*t*(((e*=1.525)+1)*t+e)+2)},easeInBounce:t=>1-effects.easeOutBounce(1-t),easeOutBounce(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},easeInOutBounce:t=>t<.5?effects.easeInBounce(t*2)*.5:effects.easeOutBounce(t*2-1)*.5+.5};function isPatternOrGradient(t){if(t&&typeof t=="object"){const e=t.toString();return e==="[object CanvasPattern]"||e==="[object CanvasGradient]"}return!1}function color(t){return isPatternOrGradient(t)?t:new Color(t)}function getHoverColor(t){return isPatternOrGradient(t)?t:new Color(t).saturate(.5).darken(.1).hexString()}const numbers=["x","y","borderWidth","radius","tension"],colors=["color","borderColor","backgroundColor"];function applyAnimationsDefaults(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:e=>e!=="onProgress"&&e!=="onComplete"&&e!=="fn"}),t.set("animations",{colors:{type:"color",properties:colors},numbers:{type:"number",properties:numbers}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:e=>e|0}}}})}function applyLayoutsDefaults(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}const intlCache=new Map;function getNumberFormat(t,e){e=e||{};const n=t+JSON.stringify(e);let r=intlCache.get(n);return r||(r=new Intl.NumberFormat(t,e),intlCache.set(n,r)),r}function formatNumber(t,e,n){return getNumberFormat(e,n).format(t)}const formatters={values(t){return isArray(t)?t:""+t},numeric(t,e,n){if(t===0)return"0";const r=this.chart.options.locale;let s,i=t;if(n.length>1){const o=Math.max(Math.abs(n[0].value),Math.abs(n[n.length-1].value));(o<1e-4||o>1e15)&&(s="scientific"),i=calculateDelta(t,n)}const a=log10(Math.abs(i)),u=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),d={notation:s,minimumFractionDigits:u,maximumFractionDigits:u};return Object.assign(d,this.options.ticks.format),formatNumber(t,r,d)},logarithmic(t,e,n){if(t===0)return"0";const r=n[e].significand||t/Math.pow(10,Math.floor(log10(t)));return[1,2,3,5,10,15].includes(r)||e>.8*n.length?formatters.numeric.call(this,t,e,n):""}};function calculateDelta(t,e){let n=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;return Math.abs(n)>=1&&t!==Math.floor(t)&&(n=t-Math.floor(t)),n}var Ticks={formatters};function applyScaleDefaults(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(e,n)=>n.lineWidth,tickColor:(e,n)=>n.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:Ticks.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:e=>!e.startsWith("before")&&!e.startsWith("after")&&e!=="callback"&&e!=="parser",_indexable:e=>e!=="borderDash"&&e!=="tickBorderDash"&&e!=="dash"}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:e=>e!=="backdropPadding"&&e!=="callback",_indexable:e=>e!=="backdropPadding"})}const overrides=Object.create(null),descriptors=Object.create(null);function getScope$1(t,e){if(!e)return t;const n=e.split(".");for(let r=0,s=n.length;rr.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(r,s)=>getHoverColor(s.backgroundColor),this.hoverBorderColor=(r,s)=>getHoverColor(s.borderColor),this.hoverColor=(r,s)=>getHoverColor(s.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(e),this.apply(n)}set(e,n){return set(this,e,n)}get(e){return getScope$1(this,e)}describe(e,n){return set(descriptors,e,n)}override(e,n){return set(overrides,e,n)}route(e,n,r,s){const i=getScope$1(this,e),a=getScope$1(this,r),u="_"+n;Object.defineProperties(i,{[u]:{value:i[n],writable:!0},[n]:{enumerable:!0,get(){const d=this[u],o=a[s];return isObject(d)?Object.assign({},o,d):valueOrDefault(d,o)},set(d){this[u]=d}}})}apply(e){e.forEach(n=>n(this))}}var defaults=new Defaults({_scriptable:t=>!t.startsWith("on"),_indexable:t=>t!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[applyAnimationsDefaults,applyLayoutsDefaults,applyScaleDefaults]);function toFontString(t){return!t||isNullOrUndef(t.size)||isNullOrUndef(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function _measureText(t,e,n,r,s){let i=e[s];return i||(i=e[s]=t.measureText(s).width,n.push(s)),i>r&&(r=i),r}function _longestText(t,e,n,r){r=r||{};let s=r.data=r.data||{},i=r.garbageCollect=r.garbageCollect||[];r.font!==e&&(s=r.data={},i=r.garbageCollect=[],r.font=e),t.save(),t.font=e;let a=0;const u=n.length;let d,o,l,c,h;for(d=0;dn.length){for(d=0;d0&&t.stroke()}}function _isPointInArea(t,e,n){return n=n||.5,!e||t&&t.x>e.left-n&&t.xe.top-n&&t.y0&&i.strokeColor!=="";let d,o;for(t.save(),t.font=s.string,setRenderOpts(t,i),d=0;d+t||0;function _readValueToProps(t,e){const n={},r=isObject(e),s=r?Object.keys(e):e,i=isObject(t)?r?a=>valueOrDefault(t[a],t[e[a]]):a=>t[a]:()=>t;for(const a of s)n[a]=numberOrZero(i(a));return n}function toTRBL(t){return _readValueToProps(t,{top:"y",right:"x",bottom:"y",left:"x"})}function toTRBLCorners(t){return _readValueToProps(t,["topLeft","topRight","bottomLeft","bottomRight"])}function toPadding(t){const e=toTRBL(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function toFont(t,e){t=t||{},e=e||defaults.font;let n=valueOrDefault(t.size,e.size);typeof n=="string"&&(n=parseInt(n,10));let r=valueOrDefault(t.style,e.style);r&&!(""+r).match(FONT_STYLE)&&(console.warn('Invalid font style specified: "'+r+'"'),r=void 0);const s={family:valueOrDefault(t.family,e.family),lineHeight:toLineHeight(valueOrDefault(t.lineHeight,e.lineHeight),n),size:n,style:r,weight:valueOrDefault(t.weight,e.weight),string:""};return s.string=toFontString(s),s}function resolve(t,e,n,r){let s=!0,i,a,u;for(i=0,a=t.length;in&&u===0?0:u+d;return{min:a(r,-Math.abs(i)),max:a(s,i)}}function createContext(t,e){return Object.assign(Object.create(t),e)}function _createResolver(t,e=[""],n,r,s=()=>t[0]){const i=n||t;typeof r>"u"&&(r=_resolve("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:i,_fallback:r,_getTarget:s,override:u=>_createResolver([u,...t],e,i,r)};return new Proxy(a,{deleteProperty(u,d){return delete u[d],delete u._keys,delete t[0][d],!0},get(u,d){return _cached(u,d,()=>_resolveWithPrefixes(d,e,t,u))},getOwnPropertyDescriptor(u,d){return Reflect.getOwnPropertyDescriptor(u._scopes[0],d)},getPrototypeOf(){return Reflect.getPrototypeOf(t[0])},has(u,d){return getKeysFromAllScopes(u).includes(d)},ownKeys(u){return getKeysFromAllScopes(u)},set(u,d,o){const l=u._storage||(u._storage=s());return u[d]=l[d]=o,delete u._keys,!0}})}function _attachContext(t,e,n,r){const s={_cacheable:!1,_proxy:t,_context:e,_subProxy:n,_stack:new Set,_descriptors:_descriptors(t,r),setContext:i=>_attachContext(t,i,n,r),override:i=>_attachContext(t.override(i),e,n,r)};return new Proxy(s,{deleteProperty(i,a){return delete i[a],delete t[a],!0},get(i,a,u){return _cached(i,a,()=>_resolveWithContext(i,a,u))},getOwnPropertyDescriptor(i,a){return i._descriptors.allKeys?Reflect.has(t,a)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,a)},getPrototypeOf(){return Reflect.getPrototypeOf(t)},has(i,a){return Reflect.has(t,a)},ownKeys(){return Reflect.ownKeys(t)},set(i,a,u){return t[a]=u,delete i[a],!0}})}function _descriptors(t,e={scriptable:!0,indexable:!0}){const{_scriptable:n=e.scriptable,_indexable:r=e.indexable,_allKeys:s=e.allKeys}=t;return{allKeys:s,scriptable:n,indexable:r,isScriptable:isFunction(n)?n:()=>n,isIndexable:isFunction(r)?r:()=>r}}const readKey=(t,e)=>t?t+_capitalize(e):e,needsSubResolver=(t,e)=>isObject(e)&&t!=="adapters"&&(Object.getPrototypeOf(e)===null||e.constructor===Object);function _cached(t,e,n){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const r=n();return t[e]=r,r}function _resolveWithContext(t,e,n){const{_proxy:r,_context:s,_subProxy:i,_descriptors:a}=t;let u=r[e];return isFunction(u)&&a.isScriptable(e)&&(u=_resolveScriptable(e,u,t,n)),isArray(u)&&u.length&&(u=_resolveArray(e,u,t,a.isIndexable)),needsSubResolver(e,u)&&(u=_attachContext(u,s,i&&i[e],a)),u}function _resolveScriptable(t,e,n,r){const{_proxy:s,_context:i,_subProxy:a,_stack:u}=n;if(u.has(t))throw new Error("Recursion detected: "+Array.from(u).join("->")+"->"+t);u.add(t);let d=e(i,a||r);return u.delete(t),needsSubResolver(t,d)&&(d=createSubResolver(s._scopes,s,t,d)),d}function _resolveArray(t,e,n,r){const{_proxy:s,_context:i,_subProxy:a,_descriptors:u}=n;if(typeof i.index<"u"&&r(t))return e[i.index%e.length];if(isObject(e[0])){const d=e,o=s._scopes.filter(l=>l!==d);e=[];for(const l of d){const c=createSubResolver(o,s,t,l);e.push(_attachContext(c,i,a&&a[t],u))}}return e}function resolveFallback(t,e,n){return isFunction(t)?t(e,n):t}const getScope=(t,e)=>t===!0?e:typeof t=="string"?resolveObjectKey(e,t):void 0;function addScopes(t,e,n,r,s){for(const i of e){const a=getScope(n,i);if(a){t.add(a);const u=resolveFallback(a._fallback,n,s);if(typeof u<"u"&&u!==n&&u!==r)return u}else if(a===!1&&typeof r<"u"&&n!==r)return null}return!1}function createSubResolver(t,e,n,r){const s=e._rootScopes,i=resolveFallback(e._fallback,n,r),a=[...t,...s],u=new Set;u.add(r);let d=addScopesFromKey(u,a,n,i||n,r);return d===null||typeof i<"u"&&i!==n&&(d=addScopesFromKey(u,a,i,d,r),d===null)?!1:_createResolver(Array.from(u),[""],s,i,()=>subGetTarget(e,n,r))}function addScopesFromKey(t,e,n,r,s){for(;n;)n=addScopes(t,e,n,r,s);return n}function subGetTarget(t,e,n){const r=t._getTarget();e in r||(r[e]={});const s=r[e];return isArray(s)&&isObject(n)?n:s||{}}function _resolveWithPrefixes(t,e,n,r){let s;for(const i of e)if(s=_resolve(readKey(i,t),n),typeof s<"u")return needsSubResolver(t,s)?createSubResolver(n,r,t,s):s}function _resolve(t,e){for(const n of e){if(!n)continue;const r=n[t];if(typeof r<"u")return r}}function getKeysFromAllScopes(t){let e=t._keys;return e||(e=t._keys=resolveKeysFromAllScopes(t._scopes)),e}function resolveKeysFromAllScopes(t){const e=new Set;for(const n of t)for(const r of Object.keys(n).filter(s=>!s.startsWith("_")))e.add(r);return Array.from(e)}function _parseObjectDataRadialScale(t,e,n,r){const{iScale:s}=t,{key:i="r"}=this._parsing,a=new Array(r);let u,d,o,l;for(u=0,d=r;uet==="x"?"y":"x";function splineCurve(t,e,n,r){const s=t.skip?e:t,i=e,a=n.skip?e:n,u=distanceBetweenPoints(i,s),d=distanceBetweenPoints(a,i);let o=u/(u+d),l=d/(u+d);o=isNaN(o)?0:o,l=isNaN(l)?0:l;const c=r*o,h=r*l;return{previous:{x:i.x-c*(a.x-s.x),y:i.y-c*(a.y-s.y)},next:{x:i.x+h*(a.x-s.x),y:i.y+h*(a.y-s.y)}}}function monotoneAdjust(t,e,n){const r=t.length;let s,i,a,u,d,o=getPoint(t,0);for(let l=0;l!o.skip)),e.cubicInterpolationMode==="monotone")splineCurveMonotone(t,s);else{let o=r?t[t.length-1]:t[0];for(i=0,a=t.length;it.ownerDocument.defaultView.getComputedStyle(t,null);function getStyle(t,e){return getComputedStyle(t).getPropertyValue(e)}const positions=["top","right","bottom","left"];function getPositionedStyle(t,e,n){const r={};n=n?"-"+n:"";for(let s=0;s<4;s++){const i=positions[s];r[i]=parseFloat(t[e+"-"+i+n])||0}return r.width=r.left+r.right,r.height=r.top+r.bottom,r}const useOffsetPos=(t,e,n)=>(t>0||e>0)&&(!n||!n.shadowRoot);function getCanvasPosition(t,e){const n=t.touches,r=n&&n.length?n[0]:t,{offsetX:s,offsetY:i}=r;let a=!1,u,d;if(useOffsetPos(s,i,t.target))u=s,d=i;else{const o=e.getBoundingClientRect();u=r.clientX-o.left,d=r.clientY-o.top,a=!0}return{x:u,y:d,box:a}}function getRelativePosition(t,e){if("native"in t)return t;const{canvas:n,currentDevicePixelRatio:r}=e,s=getComputedStyle(n),i=s.boxSizing==="border-box",a=getPositionedStyle(s,"padding"),u=getPositionedStyle(s,"border","width"),{x:d,y:o,box:l}=getCanvasPosition(t,n),c=a.left+(l&&u.left),h=a.top+(l&&u.top);let{width:f,height:p}=e;return i&&(f-=a.width+u.width,p-=a.height+u.height),{x:Math.round((d-c)/f*n.width/r),y:Math.round((o-h)/p*n.height/r)}}function getContainerSize(t,e,n){let r,s;if(e===void 0||n===void 0){const i=_getParentNode(t);if(!i)e=t.clientWidth,n=t.clientHeight;else{const a=i.getBoundingClientRect(),u=getComputedStyle(i),d=getPositionedStyle(u,"border","width"),o=getPositionedStyle(u,"padding");e=a.width-o.width-d.width,n=a.height-o.height-d.height,r=parseMaxStyle(u.maxWidth,i,"clientWidth"),s=parseMaxStyle(u.maxHeight,i,"clientHeight")}}return{width:e,height:n,maxWidth:r||INFINITY,maxHeight:s||INFINITY}}const round1=t=>Math.round(t*10)/10;function getMaximumSize(t,e,n,r){const s=getComputedStyle(t),i=getPositionedStyle(s,"margin"),a=parseMaxStyle(s.maxWidth,t,"clientWidth")||INFINITY,u=parseMaxStyle(s.maxHeight,t,"clientHeight")||INFINITY,d=getContainerSize(t,e,n);let{width:o,height:l}=d;if(s.boxSizing==="content-box"){const h=getPositionedStyle(s,"border","width"),f=getPositionedStyle(s,"padding");o-=f.width+h.width,l-=f.height+h.height}return o=Math.max(0,o-i.width),l=Math.max(0,r?o/r:l-i.height),o=round1(Math.min(o,a,d.maxWidth)),l=round1(Math.min(l,u,d.maxHeight)),o&&!l&&(l=round1(o/2)),(e!==void 0||n!==void 0)&&r&&d.height&&l>d.height&&(l=d.height,o=round1(Math.floor(l*r))),{width:o,height:l}}function retinaScale(t,e,n){const r=e||1,s=Math.floor(t.height*r),i=Math.floor(t.width*r);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(n||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),t.currentDevicePixelRatio!==r||a.height!==s||a.width!==i?(t.currentDevicePixelRatio=r,a.height=s,a.width=i,t.ctx.setTransform(r,0,0,r,0,0),!0):!1}const supportsEventListenerOptions=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};_isDomSupported()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch{}return t}();function readUsedSize(t,e){const n=getStyle(t,e),r=n&&n.match(/^(\d+)(\.\d+)?px$/);return r?+r[1]:void 0}function _pointInLine(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:t.y+n*(e.y-t.y)}}function _steppedInterpolation(t,e,n,r){return{x:t.x+n*(e.x-t.x),y:r==="middle"?n<.5?t.y:e.y:r==="after"?n<1?t.y:e.y:n>0?e.y:t.y}}function _bezierInterpolation(t,e,n,r){const s={x:t.cp2x,y:t.cp2y},i={x:e.cp1x,y:e.cp1y},a=_pointInLine(t,s,n),u=_pointInLine(s,i,n),d=_pointInLine(i,e,n),o=_pointInLine(a,u,n),l=_pointInLine(u,d,n);return _pointInLine(o,l,n)}const getRightToLeftAdapter=function(t,e){return{x(n){return t+t+e-n},setWidth(n){e=n},textAlign(n){return n==="center"?n:n==="right"?"left":"right"},xPlus(n,r){return n-r},leftForLtr(n,r){return n-r}}},getLeftToRightAdapter=function(){return{x(t){return t},setWidth(t){},textAlign(t){return t},xPlus(t,e){return t+e},leftForLtr(t,e){return t}}};function getRtlAdapter(t,e,n){return t?getRightToLeftAdapter(e,n):getLeftToRightAdapter()}function overrideTextDirection(t,e){let n,r;(e==="ltr"||e==="rtl")&&(n=t.canvas.style,r=[n.getPropertyValue("direction"),n.getPropertyPriority("direction")],n.setProperty("direction",e,"important"),t.prevTextDirection=r)}function restoreTextDirection(t,e){e!==void 0&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function propertyFn(t){return t==="angle"?{between:_angleBetween,compare:_angleDiff,normalize:_normalizeAngle}:{between:_isBetween,compare:(e,n)=>e-n,normalize:e=>e}}function normalizeSegment({start:t,end:e,count:n,loop:r,style:s}){return{start:t%n,end:e%n,loop:r&&(e-t+1)%n===0,style:s}}function getSegment(t,e,n){const{property:r,start:s,end:i}=n,{between:a,normalize:u}=propertyFn(r),d=e.length;let{start:o,end:l,loop:c}=t,h,f;if(c){for(o+=d,l+=d,h=0,f=d;hd(s,T,x)&&u(s,T)!==0,E=()=>u(i,x)===0||d(i,T,x),N=()=>g||S(),B=()=>!g||E();for(let F=l,k=l;F<=c;++F)y=e[F%a],!y.skip&&(x=o(y[r]),x!==T&&(g=d(x,s,i),b===null&&N()&&(b=u(x,s)===0?F:k),b!==null&&B()&&(p.push(normalizeSegment({start:b,end:F,loop:h,count:a,style:f})),b=null),k=F,T=x));return b!==null&&p.push(normalizeSegment({start:b,end:c,loop:h,count:a,style:f})),p}function _boundSegments(t,e){const n=[],r=t.segments;for(let s=0;ss&&t[i%e].skip;)i--;return i%=e,{start:s,end:i}}function solidSegments(t,e,n,r){const s=t.length,i=[];let a=e,u=t[e],d;for(d=e+1;d<=n;++d){const o=t[d%s];o.skip||o.stop?u.skip||(r=!1,i.push({start:e%s,end:(d-1)%s,loop:r}),e=a=o.stop?d:null):(a=d,u.skip&&(e=d)),u=o}return a!==null&&i.push({start:e%s,end:a%s,loop:r}),i}function _computeSegments(t,e){const n=t.points,r=t.options.spanGaps,s=n.length;if(!s)return[];const i=!!t._loop,{start:a,end:u}=findStartAndEnd(n,s,i,r);if(r===!0)return splitByStyles(t,[{start:a,end:u,loop:i}],n,e);const d=uu({chart:e,initial:n.initial,numSteps:a,currentStep:Math.min(r-n.start,a)}))}_refresh(){this._request||(this._running=!0,this._request=requestAnimFrame.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(e=Date.now()){let n=0;this._charts.forEach((r,s)=>{if(!r.running||!r.items.length)return;const i=r.items;let a=i.length-1,u=!1,d;for(;a>=0;--a)d=i[a],d._active?(d._total>r.duration&&(r.duration=d._total),d.tick(e),u=!0):(i[a]=i[i.length-1],i.pop());u&&(s.draw(),this._notify(s,r,e,"progress")),i.length||(r.running=!1,this._notify(s,r,e,"complete"),r.initial=!1),n+=i.length}),this._lastDate=e,n===0&&(this._running=!1)}_getAnims(e){const n=this._charts;let r=n.get(e);return r||(r={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},n.set(e,r)),r}listen(e,n,r){this._getAnims(e).listeners[n].push(r)}add(e,n){!n||!n.length||this._getAnims(e).items.push(...n)}has(e){return this._getAnims(e).items.length>0}start(e){const n=this._charts.get(e);n&&(n.running=!0,n.start=Date.now(),n.duration=n.items.reduce((r,s)=>Math.max(r,s._duration),0),this._refresh())}running(e){if(!this._running)return!1;const n=this._charts.get(e);return!(!n||!n.running||!n.items.length)}stop(e){const n=this._charts.get(e);if(!n||!n.items.length)return;const r=n.items;let s=r.length-1;for(;s>=0;--s)r[s].cancel();n.items=[],this._notify(e,n,Date.now(),"complete")}remove(e){return this._charts.delete(e)}}var animator=new Animator;const transparent="transparent",interpolators={boolean(t,e,n){return n>.5?e:t},color(t,e,n){const r=color(t||transparent),s=r.valid&&color(e||transparent);return s&&s.valid?s.mix(r,n).hexString():e},number(t,e,n){return t+(e-t)*n}};class Animation{constructor(e,n,r,s){const i=n[r];s=resolve([e.to,s,i,e.from]);const a=resolve([e.from,i,s]);this._active=!0,this._fn=e.fn||interpolators[e.type||typeof a],this._easing=effects[e.easing]||effects.linear,this._start=Math.floor(Date.now()+(e.delay||0)),this._duration=this._total=Math.floor(e.duration),this._loop=!!e.loop,this._target=n,this._prop=r,this._from=a,this._to=s,this._promises=void 0}active(){return this._active}update(e,n,r){if(this._active){this._notify(!1);const s=this._target[this._prop],i=r-this._start,a=this._duration-i;this._start=r,this._duration=Math.floor(Math.max(a,e.duration)),this._total+=i,this._loop=!!e.loop,this._to=resolve([e.to,n,s,e.from]),this._from=resolve([e.from,s,n])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(e){const n=e-this._start,r=this._duration,s=this._prop,i=this._from,a=this._loop,u=this._to;let d;if(this._active=i!==u&&(a||n1?2-d:d,d=this._easing(Math.min(1,Math.max(0,d))),this._target[s]=this._fn(i,u,d)}wait(){const e=this._promises||(this._promises=[]);return new Promise((n,r)=>{e.push({res:n,rej:r})})}_notify(e){const n=e?"res":"rej",r=this._promises||[];for(let s=0;s{const i=e[s];if(!isObject(i))return;const a={};for(const u of n)a[u]=i[u];(isArray(i.properties)&&i.properties||[s]).forEach(u=>{(u===s||!r.has(u))&&r.set(u,a)})})}_animateOptions(e,n){const r=n.options,s=resolveTargetOptions(e,r);if(!s)return[];const i=this._createAnimations(s,r);return r.$shared&&awaitAll(e.options.$animations,r).then(()=>{e.options=r},()=>{}),i}_createAnimations(e,n){const r=this._properties,s=[],i=e.$animations||(e.$animations={}),a=Object.keys(n),u=Date.now();let d;for(d=a.length-1;d>=0;--d){const o=a[d];if(o.charAt(0)==="$")continue;if(o==="options"){s.push(...this._animateOptions(e,n));continue}const l=n[o];let c=i[o];const h=r.get(o);if(c)if(h&&c.active()){c.update(h,l,u);continue}else c.cancel();if(!h||!h.duration){e[o]=l;continue}i[o]=c=new Animation(h,e,o,l),s.push(c)}return s}update(e,n){if(this._properties.size===0){Object.assign(e,n);return}const r=this._createAnimations(e,n);if(r.length)return animator.add(this._chart,r),!0}}function awaitAll(t,e){const n=[],r=Object.keys(e);for(let s=0;s0||!n&&i<0)return s.index}return null}function updateStacks(t,e){const{chart:n,_cachedMeta:r}=t,s=n._stacks||(n._stacks={}),{iScale:i,vScale:a,index:u}=r,d=i.axis,o=a.axis,l=getStackKey(i,a,r),c=e.length;let h;for(let f=0;fn[r].axis===e).shift()}function createDatasetContext(t,e){return createContext(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}function createDataContext(t,e,n){return createContext(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:n,index:e,mode:"default",type:"data"})}function clearStacks(t,e){const n=t.controller.index,r=t.vScale&&t.vScale.axis;if(r){e=e||t._parsed;for(const s of e){const i=s._stacks;if(!i||i[r]===void 0||i[r][n]===void 0)return;delete i[r][n],i[r]._visualValues!==void 0&&i[r]._visualValues[n]!==void 0&&delete i[r]._visualValues[n]}}}const isDirectUpdateMode=t=>t==="reset"||t==="none",cloneIfNotShared=(t,e)=>e?t:Object.assign({},t),createStack=(t,e,n)=>t&&!e.hidden&&e._stacked&&{keys:getSortedDatasetIndices(n,!0),values:null};class DatasetController{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(e,n){this.chart=e,this._ctx=e.ctx,this.index=n,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const e=this._cachedMeta;this.configure(),this.linkScales(),e._stacked=isStacked(e.vScale,e),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(e){this.index!==e&&clearStacks(this._cachedMeta),this.index=e}linkScales(){const e=this.chart,n=this._cachedMeta,r=this.getDataset(),s=(c,h,f,p)=>c==="x"?h:c==="r"?p:f,i=n.xAxisID=valueOrDefault(r.xAxisID,getFirstScaleId(e,"x")),a=n.yAxisID=valueOrDefault(r.yAxisID,getFirstScaleId(e,"y")),u=n.rAxisID=valueOrDefault(r.rAxisID,getFirstScaleId(e,"r")),d=n.indexAxis,o=n.iAxisID=s(d,i,a,u),l=n.vAxisID=s(d,a,i,u);n.xScale=this.getScaleForId(i),n.yScale=this.getScaleForId(a),n.rScale=this.getScaleForId(u),n.iScale=this.getScaleForId(o),n.vScale=this.getScaleForId(l)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(e){return this.chart.scales[e]}_getOtherScale(e){const n=this._cachedMeta;return e===n.iScale?n.vScale:n.iScale}reset(){this._update("reset")}_destroy(){const e=this._cachedMeta;this._data&&unlistenArrayEvents(this._data,this),e._stacked&&clearStacks(e)}_dataCheck(){const e=this.getDataset(),n=e.data||(e.data=[]),r=this._data;if(isObject(n))this._data=convertObjectDataToArray(n);else if(r!==n){if(r){unlistenArrayEvents(r,this);const s=this._cachedMeta;clearStacks(s),s._parsed=[]}n&&Object.isExtensible(n)&&listenArrayEvents(n,this),this._syncList=[],this._data=n}}addElements(){const e=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(e.dataset=new this.datasetElementType)}buildOrUpdateElements(e){const n=this._cachedMeta,r=this.getDataset();let s=!1;this._dataCheck();const i=n._stacked;n._stacked=isStacked(n.vScale,n),n.stack!==r.stack&&(s=!0,clearStacks(n),n.stack=r.stack),this._resyncElements(e),(s||i!==n._stacked)&&updateStacks(this,n._parsed)}configure(){const e=this.chart.config,n=e.datasetScopeKeys(this._type),r=e.getOptionScopes(this.getDataset(),n,!0);this.options=e.createResolver(r,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(e,n){const{_cachedMeta:r,_data:s}=this,{iScale:i,_stacked:a}=r,u=i.axis;let d=e===0&&n===s.length?!0:r._sorted,o=e>0&&r._parsed[e-1],l,c,h;if(this._parsing===!1)r._parsed=s,r._sorted=!0,h=s;else{isArray(s[e])?h=this.parseArrayData(r,s,e,n):isObject(s[e])?h=this.parseObjectData(r,s,e,n):h=this.parsePrimitiveData(r,s,e,n);const f=()=>c[u]===null||o&&c[u]g||c=0;--h)if(!p()){this.updateRangeFromParsed(o,e,f,d);break}}return o}getAllParsedValues(e){const n=this._cachedMeta._parsed,r=[];let s,i,a;for(s=0,i=n.length;s=0&&ethis.getContext(r,s,n),g=o.resolveNamedOptions(h,f,p,c);return g.$shared&&(g.$shared=d,i[a]=Object.freeze(cloneIfNotShared(g,d))),g}_resolveAnimations(e,n,r){const s=this.chart,i=this._cachedDataOpts,a=`animation-${n}`,u=i[a];if(u)return u;let d;if(s.options.animation!==!1){const l=this.chart.config,c=l.datasetAnimationScopeKeys(this._type,n),h=l.getOptionScopes(this.getDataset(),c);d=l.createResolver(h,this.getContext(e,r,n))}const o=new Animations(s,d&&d.animations);return d&&d._cacheable&&(i[a]=Object.freeze(o)),o}getSharedOptions(e){if(e.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},e))}includeOptions(e,n){return!n||isDirectUpdateMode(e)||this.chart._animationsDisabled}_getSharedOptions(e,n){const r=this.resolveDataElementOptions(e,n),s=this._sharedOptions,i=this.getSharedOptions(r),a=this.includeOptions(n,i)||i!==s;return this.updateSharedOptions(i,n,r),{sharedOptions:i,includeOptions:a}}updateElement(e,n,r,s){isDirectUpdateMode(s)?Object.assign(e,r):this._resolveAnimations(n,s).update(e,r)}updateSharedOptions(e,n,r){e&&!isDirectUpdateMode(n)&&this._resolveAnimations(void 0,n).update(e,r)}_setStyle(e,n,r,s){e.active=s;const i=this.getStyle(n,s);this._resolveAnimations(n,r,s).update(e,{options:!s&&this.getSharedOptions(i)||i})}removeHoverStyle(e,n,r){this._setStyle(e,r,"active",!1)}setHoverStyle(e,n,r){this._setStyle(e,r,"active",!0)}_removeDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!1)}_setDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!0)}_resyncElements(e){const n=this._data,r=this._cachedMeta.data;for(const[u,d,o]of this._syncList)this[u](d,o);this._syncList=[];const s=r.length,i=n.length,a=Math.min(i,s);a&&this.parse(0,a),i>s?this._insertElements(s,i-s,e):i{for(o.length+=n,u=o.length-1;u>=a;u--)o[u]=o[u-n]};for(d(i),u=e;us-i))}return t._cache.$bar}function computeMinSampleSize(t){const e=t.iScale,n=getAllScaleValues(e,t.type);let r=e._length,s,i,a,u;const d=()=>{a===32767||a===-32768||(defined(u)&&(r=Math.min(r,Math.abs(a-u)||r)),u=a)};for(s=0,i=n.length;s0?s[t-1]:null,u=tMath.abs(u)&&(d=u,o=a),e[n.axis]=o,e._custom={barStart:d,barEnd:o,start:s,end:i,min:a,max:u}}function parseValue(t,e,n,r){return isArray(t)?parseFloatBar(t,e,n,r):e[n.axis]=n.parse(t,r),e}function parseArrayOrPrimitive(t,e,n,r){const s=t.iScale,i=t.vScale,a=s.getLabels(),u=s===i,d=[];let o,l,c,h;for(o=n,l=n+r;o=n?1:-1)}function borderProps(t){let e,n,r,s,i;return t.horizontal?(e=t.base>t.x,n="left",r="right"):(e=t.based.controller.options.grouped),i=r.options.stacked,a=[],u=d=>{const o=d.controller.getParsed(n),l=o&&o[d.vScale.axis];if(isNullOrUndef(l)||isNaN(l))return!0};for(const d of s)if(!(n!==void 0&&u(d))&&((i===!1||a.indexOf(d.stack)===-1||i===void 0&&d.stack===void 0)&&a.push(d.stack),d.index===e))break;return a.length||a.push(void 0),a}_getStackCount(e){return this._getStacks(void 0,e).length}_getStackIndex(e,n,r){const s=this._getStacks(e,r),i=n!==void 0?s.indexOf(n):-1;return i===-1?s.length-1:i}_getRuler(){const e=this.options,n=this._cachedMeta,r=n.iScale,s=[];let i,a;for(i=0,a=n.data.length;i=0;--r)n=Math.max(n,e[r].size(this.resolveDataElementOptions(r))/2);return n>0&&n}getLabelAndValue(e){const n=this._cachedMeta,r=this.chart.data.labels||[],{xScale:s,yScale:i}=n,a=this.getParsed(e),u=s.getLabelForValue(a.x),d=i.getLabelForValue(a.y),o=a._custom;return{label:r[e]||"",value:"("+u+", "+d+(o?", "+o:"")+")"}}update(e){const n=this._cachedMeta.data;this.updateElements(n,0,n.length,e)}updateElements(e,n,r,s){const i=s==="reset",{iScale:a,vScale:u}=this._cachedMeta,{sharedOptions:d,includeOptions:o}=this._getSharedOptions(n,s),l=a.axis,c=u.axis;for(let h=n;h_angleBetween(T,u,d,!0)?1:Math.max(S,S*n,E,E*n),p=(T,S,E)=>_angleBetween(T,u,d,!0)?-1:Math.min(S,S*n,E,E*n),g=f(0,o,c),b=f(HALF_PI,l,h),x=p(PI,o,c),y=p(PI+HALF_PI,l,h);r=(g-x)/2,s=(b-y)/2,i=-(g+x)/2,a=-(b+y)/2}return{ratioX:r,ratioY:s,offsetX:i,offsetY:a}}class DoughnutController extends DatasetController{static id="doughnut";static defaults={datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,indexAxis:"r"};static descriptors={_scriptable:e=>e!=="spacing",_indexable:e=>e!=="spacing"&&!e.startsWith("borderDash")&&!e.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(e){const n=e.data;if(n.labels.length&&n.datasets.length){const{labels:{pointStyle:r,color:s}}=e.legend.options;return n.labels.map((i,a)=>{const d=e.getDatasetMeta(0).controller.getStyle(a);return{text:i,fillStyle:d.backgroundColor,strokeStyle:d.borderColor,fontColor:s,lineWidth:d.borderWidth,pointStyle:r,hidden:!e.getDataVisibility(a),index:a}})}return[]}},onClick(e,n,r){r.chart.toggleDataVisibility(n.index),r.chart.update()}}}};constructor(e,n){super(e,n),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(e,n){const r=this.getDataset().data,s=this._cachedMeta;if(this._parsing===!1)s._parsed=r;else{let i=d=>+r[d];if(isObject(r[e])){const{key:d="value"}=this._parsing;i=o=>+resolveObjectKey(r[o],d)}let a,u;for(a=e,u=e+n;a0&&!isNaN(e)?TAU*(Math.abs(e)/n):0}getLabelAndValue(e){const n=this._cachedMeta,r=this.chart,s=r.data.labels||[],i=formatNumber(n._parsed[e],r.options.locale);return{label:s[e]||"",value:i}}getMaxBorderWidth(e){let n=0;const r=this.chart;let s,i,a,u,d;if(!e){for(s=0,i=r.data.datasets.length;s0&&this.getParsed(n-1);for(let E=0;E=y){B.skip=!0;continue}const F=this.getParsed(E),k=isNullOrUndef(F[f]),G=B[h]=a.getPixelForValue(F[h],E),re=B[f]=i||k?u.getBasePixel():u.getPixelForValue(d?this.applyStack(u,F,d):F[f],E);B.skip=isNaN(G)||isNaN(re)||k,B.stop=E>0&&Math.abs(F[h]-S[h])>b,g&&(B.parsed=F,B.raw=o.data[E]),c&&(B.options=l||this.resolveDataElementOptions(E,N.active?"active":s)),x||this.updateElement(N,E,B,s),S=F}}getMaxOverflow(){const e=this._cachedMeta,n=e.dataset,r=n.options&&n.options.borderWidth||0,s=e.data||[];if(!s.length)return r;const i=s[0].size(this.resolveDataElementOptions(0)),a=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(r,i,a)/2}draw(){const e=this._cachedMeta;e.dataset.updateControlPoints(this.chart.chartArea,e.iScale.axis),super.draw()}}class PolarAreaController extends DatasetController{static id="polarArea";static defaults={dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(e){const n=e.data;if(n.labels.length&&n.datasets.length){const{labels:{pointStyle:r,color:s}}=e.legend.options;return n.labels.map((i,a)=>{const d=e.getDatasetMeta(0).controller.getStyle(a);return{text:i,fillStyle:d.backgroundColor,strokeStyle:d.borderColor,fontColor:s,lineWidth:d.borderWidth,pointStyle:r,hidden:!e.getDataVisibility(a),index:a}})}return[]}},onClick(e,n,r){r.chart.toggleDataVisibility(n.index),r.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(e,n){super(e,n),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(e){const n=this._cachedMeta,r=this.chart,s=r.data.labels||[],i=formatNumber(n._parsed[e].r,r.options.locale);return{label:s[e]||"",value:i}}parseObjectData(e,n,r,s){return _parseObjectDataRadialScale.bind(this)(e,n,r,s)}update(e){const n=this._cachedMeta.data;this._updateRadius(),this.updateElements(n,0,n.length,e)}getMinMax(){const e=this._cachedMeta,n={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return e.data.forEach((r,s)=>{const i=this.getParsed(s).r;!isNaN(i)&&this.chart.getDataVisibility(s)&&(in.max&&(n.max=i))}),n}_updateRadius(){const e=this.chart,n=e.chartArea,r=e.options,s=Math.min(n.right-n.left,n.bottom-n.top),i=Math.max(s/2,0),a=Math.max(r.cutoutPercentage?i/100*r.cutoutPercentage:1,0),u=(i-a)/e.getVisibleDatasetCount();this.outerRadius=i-u*this.index,this.innerRadius=this.outerRadius-u}updateElements(e,n,r,s){const i=s==="reset",a=this.chart,d=a.options.animation,o=this._cachedMeta.rScale,l=o.xCenter,c=o.yCenter,h=o.getIndexAngle(0)-.5*PI;let f=h,p;const g=360/this.countVisibleElements();for(p=0;p{!isNaN(this.getParsed(s).r)&&this.chart.getDataVisibility(s)&&n++}),n}_computeAngle(e,n,r){return this.chart.getDataVisibility(e)?toRadians(this.resolveDataElementOptions(e,n).angle||r):0}}class PieController extends DoughnutController{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}}class RadarController extends DatasetController{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(e){const n=this._cachedMeta.vScale,r=this.getParsed(e);return{label:n.getLabels()[e],value:""+n.getLabelForValue(r[n.axis])}}parseObjectData(e,n,r,s){return _parseObjectDataRadialScale.bind(this)(e,n,r,s)}update(e){const n=this._cachedMeta,r=n.dataset,s=n.data||[],i=n.iScale.getLabels();if(r.points=s,e!=="resize"){const a=this.resolveDatasetElementOptions(e);this.options.showLine||(a.borderWidth=0);const u={_loop:!0,_fullLoop:i.length===s.length,options:a};this.updateElement(r,void 0,u,e)}this.updateElements(s,0,s.length,e)}updateElements(e,n,r,s){const i=this._cachedMeta.rScale,a=s==="reset";for(let u=n;u0&&this.getParsed(n-1);for(let S=n;S0&&Math.abs(N[f]-T[f])>x,b&&(B.parsed=N,B.raw=o.data[S]),h&&(B.options=c||this.resolveDataElementOptions(S,E.active?"active":s)),y||this.updateElement(E,S,B,s),T=N}this.updateSharedOptions(c,s,l)}getMaxOverflow(){const e=this._cachedMeta,n=e.data||[];if(!this.options.showLine){let u=0;for(let d=n.length-1;d>=0;--d)u=Math.max(u,n[d].size(this.resolveDataElementOptions(d))/2);return u>0&&u}const r=e.dataset,s=r.options&&r.options.borderWidth||0;if(!n.length)return s;const i=n[0].size(this.resolveDataElementOptions(0)),a=n[n.length-1].size(this.resolveDataElementOptions(n.length-1));return Math.max(s,i,a)/2}}var controllers=Object.freeze({__proto__:null,BarController,BubbleController,DoughnutController,LineController,PieController,PolarAreaController,RadarController,ScatterController});function abstract(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class DateAdapterBase{static override(e){Object.assign(DateAdapterBase.prototype,e)}options;constructor(e){this.options=e||{}}init(){}formats(){return abstract()}parse(){return abstract()}format(){return abstract()}add(){return abstract()}diff(){return abstract()}startOf(){return abstract()}endOf(){return abstract()}}var adapters={_date:DateAdapterBase};function binarySearch(t,e,n,r){const{controller:s,data:i,_sorted:a}=t,u=s._cachedMeta.iScale;if(u&&e===u.axis&&e!=="r"&&a&&i.length){const d=u._reversePixels?_rlookupByKey:_lookupByKey;if(r){if(s._sharedOptions){const o=i[0],l=typeof o.getRange=="function"&&o.getRange(e);if(l){const c=d(i,e,n-l),h=d(i,e,n+l);return{lo:c.lo,hi:h.hi}}}}else return d(i,e,n)}return{lo:0,hi:i.length-1}}function evaluateInteractionItems(t,e,n,r,s){const i=t.getSortedVisibleDatasetMetas(),a=n[e];for(let u=0,d=i.length;u{d[a](e[n],s)&&(i.push({element:d,datasetIndex:o,index:l}),u=u||d.inRange(e.x,e.y,s))}),r&&!u?[]:i}var Interaction={evaluateInteractionItems,modes:{index(t,e,n,r){const s=getRelativePosition(e,t),i=n.axis||"x",a=n.includeInvisible||!1,u=n.intersect?getIntersectItems(t,s,i,r,a):getNearestItems(t,s,i,!1,r,a),d=[];return u.length?(t.getSortedVisibleDatasetMetas().forEach(o=>{const l=u[0].index,c=o.data[l];c&&!c.skip&&d.push({element:c,datasetIndex:o.index,index:l})}),d):[]},dataset(t,e,n,r){const s=getRelativePosition(e,t),i=n.axis||"xy",a=n.includeInvisible||!1;let u=n.intersect?getIntersectItems(t,s,i,r,a):getNearestItems(t,s,i,!1,r,a);if(u.length>0){const d=u[0].datasetIndex,o=t.getDatasetMeta(d).data;u=[];for(let l=0;ln.pos===e)}function filterDynamicPositionByAxis(t,e){return t.filter(n=>STATIC_POSITIONS.indexOf(n.pos)===-1&&n.box.axis===e)}function sortByWeight(t,e){return t.sort((n,r)=>{const s=e?r:n,i=e?n:r;return s.weight===i.weight?s.index-i.index:s.weight-i.weight})}function wrapBoxes(t){const e=[];let n,r,s,i,a,u;for(n=0,r=(t||[]).length;no.box.fullSize),!0),r=sortByWeight(filterByPosition(e,"left"),!0),s=sortByWeight(filterByPosition(e,"right")),i=sortByWeight(filterByPosition(e,"top"),!0),a=sortByWeight(filterByPosition(e,"bottom")),u=filterDynamicPositionByAxis(e,"x"),d=filterDynamicPositionByAxis(e,"y");return{fullSize:n,leftAndTop:r.concat(i),rightAndBottom:s.concat(d).concat(a).concat(u),chartArea:filterByPosition(e,"chartArea"),vertical:r.concat(s).concat(d),horizontal:i.concat(a).concat(u)}}function getCombinedMax(t,e,n,r){return Math.max(t[n],e[n])+Math.max(t[r],e[r])}function updateMaxPadding(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function updateDims(t,e,n,r){const{pos:s,box:i}=n,a=t.maxPadding;if(!isObject(s)){n.size&&(t[s]-=n.size);const c=r[n.stack]||{size:0,count:1};c.size=Math.max(c.size,n.horizontal?i.height:i.width),n.size=c.size/c.count,t[s]+=n.size}i.getPadding&&updateMaxPadding(a,i.getPadding());const u=Math.max(0,e.outerWidth-getCombinedMax(a,t,"left","right")),d=Math.max(0,e.outerHeight-getCombinedMax(a,t,"top","bottom")),o=u!==t.w,l=d!==t.h;return t.w=u,t.h=d,n.horizontal?{same:o,other:l}:{same:l,other:o}}function handleMaxPadding(t){const e=t.maxPadding;function n(r){const s=Math.max(e[r]-t[r],0);return t[r]+=s,s}t.y+=n("top"),t.x+=n("left"),n("right"),n("bottom")}function getMargins(t,e){const n=e.maxPadding;function r(s){const i={left:0,top:0,right:0,bottom:0};return s.forEach(a=>{i[a]=Math.max(e[a],n[a])}),i}return r(t?["left","right"]:["top","bottom"])}function fitBoxes(t,e,n,r){const s=[];let i,a,u,d,o,l;for(i=0,a=t.length,o=0;i{typeof g.beforeLayout=="function"&&g.beforeLayout()});const l=d.reduce((g,b)=>b.box.options&&b.box.options.display===!1?g:g+1,0)||1,c=Object.freeze({outerWidth:e,outerHeight:n,padding:s,availableWidth:i,availableHeight:a,vBoxMaxWidth:i/2/l,hBoxMaxHeight:a/2}),h=Object.assign({},s);updateMaxPadding(h,toPadding(r));const f=Object.assign({maxPadding:h,w:i,h:a,x:s.left,y:s.top},s),p=setLayoutDims(d.concat(o),c);fitBoxes(u.fullSize,f,c,p),fitBoxes(d,f,c,p),fitBoxes(o,f,c,p)&&fitBoxes(d,f,c,p),handleMaxPadding(f),placeBoxes(u.leftAndTop,f,c,p),f.x+=f.w,f.y+=f.h,placeBoxes(u.rightAndBottom,f,c,p),t.chartArea={left:f.left,top:f.top,right:f.left+f.w,bottom:f.top+f.h,height:f.h,width:f.w},each(u.chartArea,g=>{const b=g.box;Object.assign(b,t.chartArea),b.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})})}};class BasePlatform{acquireContext(e,n){}releaseContext(e){return!1}addEventListener(e,n,r){}removeEventListener(e,n,r){}getDevicePixelRatio(){return 1}getMaximumSize(e,n,r,s){return n=Math.max(0,n||e.width),r=r||e.height,{width:n,height:Math.max(0,s?Math.floor(n/s):r)}}isAttached(e){return!0}updateConfig(e){}}class BasicPlatform extends BasePlatform{acquireContext(e){return e&&e.getContext&&e.getContext("2d")||null}updateConfig(e){e.options.animation=!1}}const EXPANDO_KEY="$chartjs",EVENT_TYPES={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},isNullOrEmpty=t=>t===null||t==="";function initCanvas(t,e){const n=t.style,r=t.getAttribute("height"),s=t.getAttribute("width");if(t[EXPANDO_KEY]={initial:{height:r,width:s,style:{display:n.display,height:n.height,width:n.width}}},n.display=n.display||"block",n.boxSizing=n.boxSizing||"border-box",isNullOrEmpty(s)){const i=readUsedSize(t,"width");i!==void 0&&(t.width=i)}if(isNullOrEmpty(r))if(t.style.height==="")t.height=t.width/(e||2);else{const i=readUsedSize(t,"height");i!==void 0&&(t.height=i)}return t}const eventListenerOptions=supportsEventListenerOptions?{passive:!0}:!1;function addListener(t,e,n){t&&t.addEventListener(e,n,eventListenerOptions)}function removeListener(t,e,n){t&&t.canvas&&t.canvas.removeEventListener(e,n,eventListenerOptions)}function fromNativeEvent(t,e){const n=EVENT_TYPES[t.type]||t.type,{x:r,y:s}=getRelativePosition(t,e);return{type:n,chart:e,native:t,x:r!==void 0?r:null,y:s!==void 0?s:null}}function nodeListContains(t,e){for(const n of t)if(n===e||n.contains(e))return!0}function createAttachObserver(t,e,n){const r=t.canvas,s=new MutationObserver(i=>{let a=!1;for(const u of i)a=a||nodeListContains(u.addedNodes,r),a=a&&!nodeListContains(u.removedNodes,r);a&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}function createDetachObserver(t,e,n){const r=t.canvas,s=new MutationObserver(i=>{let a=!1;for(const u of i)a=a||nodeListContains(u.removedNodes,r),a=a&&!nodeListContains(u.addedNodes,r);a&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}const drpListeningCharts=new Map;let oldDevicePixelRatio=0;function onWindowResize(){const t=window.devicePixelRatio;t!==oldDevicePixelRatio&&(oldDevicePixelRatio=t,drpListeningCharts.forEach((e,n)=>{n.currentDevicePixelRatio!==t&&e()}))}function listenDevicePixelRatioChanges(t,e){drpListeningCharts.size||window.addEventListener("resize",onWindowResize),drpListeningCharts.set(t,e)}function unlistenDevicePixelRatioChanges(t){drpListeningCharts.delete(t),drpListeningCharts.size||window.removeEventListener("resize",onWindowResize)}function createResizeObserver(t,e,n){const r=t.canvas,s=r&&_getParentNode(r);if(!s)return;const i=throttled((u,d)=>{const o=s.clientWidth;n(u,d),o{const d=u[0],o=d.contentRect.width,l=d.contentRect.height;o===0&&l===0||i(o,l)});return a.observe(s),listenDevicePixelRatioChanges(t,i),a}function releaseObserver(t,e,n){n&&n.disconnect(),e==="resize"&&unlistenDevicePixelRatioChanges(t)}function createProxyAndListen(t,e,n){const r=t.canvas,s=throttled(i=>{t.ctx!==null&&n(fromNativeEvent(i,t))},t);return addListener(r,e,s),s}class DomPlatform extends BasePlatform{acquireContext(e,n){const r=e&&e.getContext&&e.getContext("2d");return r&&r.canvas===e?(initCanvas(e,n),r):null}releaseContext(e){const n=e.canvas;if(!n[EXPANDO_KEY])return!1;const r=n[EXPANDO_KEY].initial;["height","width"].forEach(i=>{const a=r[i];isNullOrUndef(a)?n.removeAttribute(i):n.setAttribute(i,a)});const s=r.style||{};return Object.keys(s).forEach(i=>{n.style[i]=s[i]}),n.width=n.width,delete n[EXPANDO_KEY],!0}addEventListener(e,n,r){this.removeEventListener(e,n);const s=e.$proxies||(e.$proxies={}),a={attach:createAttachObserver,detach:createDetachObserver,resize:createResizeObserver}[n]||createProxyAndListen;s[n]=a(e,n,r)}removeEventListener(e,n){const r=e.$proxies||(e.$proxies={}),s=r[n];if(!s)return;({attach:releaseObserver,detach:releaseObserver,resize:releaseObserver}[n]||removeListener)(e,n,s),r[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(e,n,r,s){return getMaximumSize(e,n,r,s)}isAttached(e){const n=_getParentNode(e);return!!(n&&n.isConnected)}}function _detectPlatform(t){return!_isDomSupported()||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas?BasicPlatform:DomPlatform}class Element{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(e){const{x:n,y:r}=this.getProps(["x","y"],e);return{x:n,y:r}}hasValue(){return isNumber(this.x)&&isNumber(this.y)}getProps(e,n){const r=this.$animations;if(!n||!r)return this;const s={};return e.forEach(i=>{s[i]=r[i]&&r[i].active()?r[i]._to:this[i]}),s}}function autoSkip(t,e){const n=t.options.ticks,r=determineMaxTicks(t),s=Math.min(n.maxTicksLimit||r,r),i=n.major.enabled?getMajorIndices(e):[],a=i.length,u=i[0],d=i[a-1],o=[];if(a>s)return skipMajors(e,o,i,a/s),o;const l=calculateSpacing(i,e,s);if(a>0){let c,h;const f=a>1?Math.round((d-u)/(a-1)):null;for(skip(e,o,l,isNullOrUndef(f)?0:u-f,u),c=0,h=a-1;cs)return d}return Math.max(s,1)}function getMajorIndices(t){const e=[];let n,r;for(n=0,r=t.length;nt==="left"?"right":t==="right"?"left":t,offsetFromEdge=(t,e,n)=>e==="top"||e==="left"?t[e]+n:t[e]-n,getTicksLimit=(t,e)=>Math.min(e||t,t);function sample(t,e){const n=[],r=t.length/e,s=t.length;let i=0;for(;ia+u)))return d}function garbageCollect(t,e){each(t,n=>{const r=n.gc,s=r.length/2;let i;if(s>e){for(i=0;ir?r:n,r=s&&n>r?n:r,{min:finiteOrDefault(n,finiteOrDefault(r,n)),max:finiteOrDefault(r,finiteOrDefault(n,r))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const e=this.chart.data;return this.options.labels||(this.isHorizontal()?e.xLabels:e.yLabels)||e.labels||[]}getLabelItems(e=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(e))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){callback(this.options.beforeUpdate,[this])}update(e,n,r){const{beginAtZero:s,grace:i,ticks:a}=this.options,u=a.sampleSize;this.beforeUpdate(),this.maxWidth=e,this.maxHeight=n,this._margins=r=Object.assign({left:0,right:0,top:0,bottom:0},r),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+r.left+r.right:this.height+r.top+r.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=_addGrace(this,i,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const d=u=i||r<=1||!this.isHorizontal()){this.labelRotation=s;return}const l=this._getLabelSizes(),c=l.widest.width,h=l.highest.height,f=_limitValue(this.chart.width-c,0,this.maxWidth);u=e.offset?this.maxWidth/r:f/(r-1),c+6>u&&(u=f/(r-(e.offset?.5:1)),d=this.maxHeight-getTickMarkLength(e.grid)-n.padding-getTitleHeight(e.title,this.chart.options.font),o=Math.sqrt(c*c+h*h),a=toDegrees(Math.min(Math.asin(_limitValue((l.highest.height+6)/u,-1,1)),Math.asin(_limitValue(d/o,-1,1))-Math.asin(_limitValue(h/o,-1,1)))),a=Math.max(s,Math.min(i,a))),this.labelRotation=a}afterCalculateLabelRotation(){callback(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){callback(this.options.beforeFit,[this])}fit(){const e={width:0,height:0},{chart:n,options:{ticks:r,title:s,grid:i}}=this,a=this._isVisible(),u=this.isHorizontal();if(a){const d=getTitleHeight(s,n.options.font);if(u?(e.width=this.maxWidth,e.height=getTickMarkLength(i)+d):(e.height=this.maxHeight,e.width=getTickMarkLength(i)+d),r.display&&this.ticks.length){const{first:o,last:l,widest:c,highest:h}=this._getLabelSizes(),f=r.padding*2,p=toRadians(this.labelRotation),g=Math.cos(p),b=Math.sin(p);if(u){const x=r.mirror?0:b*c.width+g*h.height;e.height=Math.min(this.maxHeight,e.height+x+f)}else{const x=r.mirror?0:g*c.width+b*h.height;e.width=Math.min(this.maxWidth,e.width+x+f)}this._calculatePadding(o,l,b,g)}}this._handleMargins(),u?(this.width=this._length=n.width-this._margins.left-this._margins.right,this.height=e.height):(this.width=e.width,this.height=this._length=n.height-this._margins.top-this._margins.bottom)}_calculatePadding(e,n,r,s){const{ticks:{align:i,padding:a},position:u}=this.options,d=this.labelRotation!==0,o=u!=="top"&&this.axis==="x";if(this.isHorizontal()){const l=this.getPixelForTick(0)-this.left,c=this.right-this.getPixelForTick(this.ticks.length-1);let h=0,f=0;d?o?(h=s*e.width,f=r*n.height):(h=r*e.height,f=s*n.width):i==="start"?f=n.width:i==="end"?h=e.width:i!=="inner"&&(h=e.width/2,f=n.width/2),this.paddingLeft=Math.max((h-l+a)*this.width/(this.width-l),0),this.paddingRight=Math.max((f-c+a)*this.width/(this.width-c),0)}else{let l=n.height/2,c=e.height/2;i==="start"?(l=0,c=e.height):i==="end"&&(l=n.height,c=0),this.paddingTop=l+a,this.paddingBottom=c+a}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){callback(this.options.afterFit,[this])}isHorizontal(){const{axis:e,position:n}=this.options;return n==="top"||n==="bottom"||e==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(e){this.beforeTickToLabelConversion(),this.generateTickLabels(e);let n,r;for(n=0,r=e.length;n({width:a[k]||0,height:u[k]||0});return{first:F(0),last:F(n-1),widest:F(N),highest:F(B),widths:a,heights:u}}getLabelForValue(e){return e}getPixelForValue(e,n){return NaN}getValueForPixel(e){}getPixelForTick(e){const n=this.ticks;return e<0||e>n.length-1?null:this.getPixelForValue(n[e].value)}getPixelForDecimal(e){this._reversePixels&&(e=1-e);const n=this._startPixel+e*this._length;return _int16Range(this._alignToPixels?_alignPixel(this.chart,n,0):n)}getDecimalForPixel(e){const n=(e-this._startPixel)/this._length;return this._reversePixels?1-n:n}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:e,max:n}=this;return e<0&&n<0?n:e>0&&n>0?e:0}getContext(e){const n=this.ticks||[];if(e>=0&&eu*s?u/r:d/s:d*s0}_computeGridLineItems(e){const n=this.axis,r=this.chart,s=this.options,{grid:i,position:a,border:u}=s,d=i.offset,o=this.isHorizontal(),c=this.ticks.length+(d?1:0),h=getTickMarkLength(i),f=[],p=u.setContext(this.getContext()),g=p.display?p.width:0,b=g/2,x=function(he){return _alignPixel(r,he,g)};let y,T,S,E,N,B,F,k,G,re,ie,ge;if(a==="top")y=x(this.bottom),B=this.bottom-h,k=y-b,re=x(e.top)+b,ge=e.bottom;else if(a==="bottom")y=x(this.top),re=e.top,ge=x(e.bottom)-b,B=y+b,k=this.top+h;else if(a==="left")y=x(this.right),N=this.right-h,F=y-b,G=x(e.left)+b,ie=e.right;else if(a==="right")y=x(this.left),G=e.left,ie=x(e.right)-b,N=y+b,F=this.left+h;else if(n==="x"){if(a==="center")y=x((e.top+e.bottom)/2+.5);else if(isObject(a)){const he=Object.keys(a)[0],se=a[he];y=x(this.chart.scales[he].getPixelForValue(se))}re=e.top,ge=e.bottom,B=y+b,k=B+h}else if(n==="y"){if(a==="center")y=x((e.left+e.right)/2);else if(isObject(a)){const he=Object.keys(a)[0],se=a[he];y=x(this.chart.scales[he].getPixelForValue(se))}N=y-b,F=N-h,G=e.left,ie=e.right}const X=valueOrDefault(s.ticks.maxTicksLimit,c),K=Math.max(1,Math.ceil(c/X));for(T=0;T0&&(Ce-=Ie/2);break}Le={left:Ce,top:$e,width:Ie+ze.width,height:qe+ze.height,color:K.backdropColor}}b.push({label:S,font:k,textOffset:ie,options:{rotation:g,color:se,strokeColor:we,strokeWidth:ue,textAlign:Te,textBaseline:ge,translation:[E,N],backdrop:Le}})}return b}_getXAxisLabelAlignment(){const{position:e,ticks:n}=this.options;if(-toRadians(this.labelRotation))return e==="top"?"left":"right";let s="center";return n.align==="start"?s="left":n.align==="end"?s="right":n.align==="inner"&&(s="inner"),s}_getYAxisLabelAlignment(e){const{position:n,ticks:{crossAlign:r,mirror:s,padding:i}}=this.options,a=this._getLabelSizes(),u=e+i,d=a.widest.width;let o,l;return n==="left"?s?(l=this.right+i,r==="near"?o="left":r==="center"?(o="center",l+=d/2):(o="right",l+=d)):(l=this.right-u,r==="near"?o="right":r==="center"?(o="center",l-=d/2):(o="left",l=this.left)):n==="right"?s?(l=this.left+i,r==="near"?o="right":r==="center"?(o="center",l-=d/2):(o="left",l-=d)):(l=this.left+u,r==="near"?o="left":r==="center"?(o="center",l+=d/2):(o="right",l=this.right)):o="right",{textAlign:o,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const e=this.chart,n=this.options.position;if(n==="left"||n==="right")return{top:0,left:this.left,bottom:e.height,right:this.right};if(n==="top"||n==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:e.width}}drawBackground(){const{ctx:e,options:{backgroundColor:n},left:r,top:s,width:i,height:a}=this;n&&(e.save(),e.fillStyle=n,e.fillRect(r,s,i,a),e.restore())}getLineWidthForValue(e){const n=this.options.grid;if(!this._isVisible()||!n.display)return 0;const s=this.ticks.findIndex(i=>i.value===e);return s>=0?n.setContext(this.getContext(s)).lineWidth:0}drawGrid(e){const n=this.options.grid,r=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(e));let i,a;const u=(d,o,l)=>{!l.width||!l.color||(r.save(),r.lineWidth=l.width,r.strokeStyle=l.color,r.setLineDash(l.borderDash||[]),r.lineDashOffset=l.borderDashOffset,r.beginPath(),r.moveTo(d.x,d.y),r.lineTo(o.x,o.y),r.stroke(),r.restore())};if(n.display)for(i=0,a=s.length;i{this.draw(i)}}]:[{z:r,draw:i=>{this.drawBackground(),this.drawGrid(i),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:n,draw:i=>{this.drawLabels(i)}}]}getMatchingVisibleMetas(e){const n=this.chart.getSortedVisibleDatasetMetas(),r=this.axis+"AxisID",s=[];let i,a;for(i=0,a=n.length;i{const r=n.split("."),s=r.pop(),i=[t].concat(r).join("."),a=e[n].split("."),u=a.pop(),d=a.join(".");defaults.route(i,s,d,u)})}function isIChartComponent(t){return"id"in t&&"defaults"in t}class Registry{constructor(){this.controllers=new TypedRegistry(DatasetController,"datasets",!0),this.elements=new TypedRegistry(Element,"elements"),this.plugins=new TypedRegistry(Object,"plugins"),this.scales=new TypedRegistry(Scale,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...e){this._each("register",e)}remove(...e){this._each("unregister",e)}addControllers(...e){this._each("register",e,this.controllers)}addElements(...e){this._each("register",e,this.elements)}addPlugins(...e){this._each("register",e,this.plugins)}addScales(...e){this._each("register",e,this.scales)}getController(e){return this._get(e,this.controllers,"controller")}getElement(e){return this._get(e,this.elements,"element")}getPlugin(e){return this._get(e,this.plugins,"plugin")}getScale(e){return this._get(e,this.scales,"scale")}removeControllers(...e){this._each("unregister",e,this.controllers)}removeElements(...e){this._each("unregister",e,this.elements)}removePlugins(...e){this._each("unregister",e,this.plugins)}removeScales(...e){this._each("unregister",e,this.scales)}_each(e,n,r){[...n].forEach(s=>{const i=r||this._getRegistryForType(s);r||i.isForType(s)||i===this.plugins&&s.id?this._exec(e,i,s):each(s,a=>{const u=r||this._getRegistryForType(a);this._exec(e,u,a)})})}_exec(e,n,r){const s=_capitalize(e);callback(r["before"+s],[],r),n[e](r),callback(r["after"+s],[],r)}_getRegistryForType(e){for(let n=0;ni.filter(u=>!a.some(d=>u.plugin.id===d.plugin.id));this._notify(s(n,r),e,"stop"),this._notify(s(r,n),e,"start")}}function allPlugins(t){const e={},n=[],r=Object.keys(registry.plugins.items);for(let i=0;i1&&idMatchesAxis(t[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function getAxisFromDataset(t,e,n){if(n[e+"AxisID"]===t)return{axis:e}}function retrieveAxisFromDatasets(t,e){if(e.data&&e.data.datasets){const n=e.data.datasets.filter(r=>r.xAxisID===t||r.yAxisID===t);if(n.length)return getAxisFromDataset(t,"x",n[0])||getAxisFromDataset(t,"y",n[0])}return{}}function mergeScaleConfig(t,e){const n=overrides[t.type]||{scales:{}},r=e.scales||{},s=getIndexAxis(t.type,e),i=Object.create(null);return Object.keys(r).forEach(a=>{const u=r[a];if(!isObject(u))return console.error(`Invalid scale configuration for scale: ${a}`);if(u._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${a}`);const d=determineAxis(a,u,retrieveAxisFromDatasets(a,t),defaults.scales[u.type]),o=getDefaultScaleIDFromAxis(d,s),l=n.scales||{};i[a]=mergeIf(Object.create(null),[{axis:d},u,l[d],l[o]])}),t.data.datasets.forEach(a=>{const u=a.type||t.type,d=a.indexAxis||getIndexAxis(u,e),l=(overrides[u]||{}).scales||{};Object.keys(l).forEach(c=>{const h=getAxisFromDefaultScaleID(c,d),f=a[h+"AxisID"]||h;i[f]=i[f]||Object.create(null),mergeIf(i[f],[{axis:h},r[f],l[c]])})}),Object.keys(i).forEach(a=>{const u=i[a];mergeIf(u,[defaults.scales[u.type],defaults.scale])}),i}function initOptions(t){const e=t.options||(t.options={});e.plugins=valueOrDefault(e.plugins,{}),e.scales=mergeScaleConfig(t,e)}function initData(t){return t=t||{},t.datasets=t.datasets||[],t.labels=t.labels||[],t}function initConfig(t){return t=t||{},t.data=initData(t.data),initOptions(t),t}const keyCache=new Map,keysCached=new Set;function cachedKeys(t,e){let n=keyCache.get(t);return n||(n=e(),keyCache.set(t,n),keysCached.add(n)),n}const addIfFound=(t,e,n)=>{const r=resolveObjectKey(e,n);r!==void 0&&t.add(r)};class Config{constructor(e){this._config=initConfig(e),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(e){this._config.type=e}get data(){return this._config.data}set data(e){this._config.data=initData(e)}get options(){return this._config.options}set options(e){this._config.options=e}get plugins(){return this._config.plugins}update(){const e=this._config;this.clearCache(),initOptions(e)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(e){return cachedKeys(e,()=>[[`datasets.${e}`,""]])}datasetAnimationScopeKeys(e,n){return cachedKeys(`${e}.transition.${n}`,()=>[[`datasets.${e}.transitions.${n}`,`transitions.${n}`],[`datasets.${e}`,""]])}datasetElementScopeKeys(e,n){return cachedKeys(`${e}-${n}`,()=>[[`datasets.${e}.elements.${n}`,`datasets.${e}`,`elements.${n}`,""]])}pluginScopeKeys(e){const n=e.id,r=this.type;return cachedKeys(`${r}-plugin-${n}`,()=>[[`plugins.${n}`,...e.additionalOptionScopes||[]]])}_cachedScopes(e,n){const r=this._scopeCache;let s=r.get(e);return(!s||n)&&(s=new Map,r.set(e,s)),s}getOptionScopes(e,n,r){const{options:s,type:i}=this,a=this._cachedScopes(e,r),u=a.get(n);if(u)return u;const d=new Set;n.forEach(l=>{e&&(d.add(e),l.forEach(c=>addIfFound(d,e,c))),l.forEach(c=>addIfFound(d,s,c)),l.forEach(c=>addIfFound(d,overrides[i]||{},c)),l.forEach(c=>addIfFound(d,defaults,c)),l.forEach(c=>addIfFound(d,descriptors,c))});const o=Array.from(d);return o.length===0&&o.push(Object.create(null)),keysCached.has(n)&&a.set(n,o),o}chartOptionScopes(){const{options:e,type:n}=this;return[e,overrides[n]||{},defaults.datasets[n]||{},{type:n},defaults,descriptors]}resolveNamedOptions(e,n,r,s=[""]){const i={$shared:!0},{resolver:a,subPrefixes:u}=getResolver(this._resolverCache,e,s);let d=a;if(needContext(a,n)){i.$shared=!1,r=isFunction(r)?r():r;const o=this.createResolver(e,r,u);d=_attachContext(a,r,o)}for(const o of n)i[o]=d[o];return i}createResolver(e,n,r=[""],s){const{resolver:i}=getResolver(this._resolverCache,e,r);return isObject(n)?_attachContext(i,n,void 0,s):i}}function getResolver(t,e,n){let r=t.get(e);r||(r=new Map,t.set(e,r));const s=n.join();let i=r.get(s);return i||(i={resolver:_createResolver(e,n),subPrefixes:n.filter(u=>!u.toLowerCase().includes("hover"))},r.set(s,i)),i}const hasFunction=t=>isObject(t)&&Object.getOwnPropertyNames(t).some(e=>isFunction(t[e]));function needContext(t,e){const{isScriptable:n,isIndexable:r}=_descriptors(t);for(const s of e){const i=n(s),a=r(s),u=(a||i)&&t[s];if(i&&(isFunction(u)||hasFunction(u))||a&&isArray(u))return!0}return!1}var version="4.4.2";const KNOWN_POSITIONS=["top","bottom","left","right","chartArea"];function positionIsHorizontal(t,e){return t==="top"||t==="bottom"||KNOWN_POSITIONS.indexOf(t)===-1&&e==="x"}function compare2Level(t,e){return function(n,r){return n[t]===r[t]?n[e]-r[e]:n[t]-r[t]}}function onAnimationsComplete(t){const e=t.chart,n=e.options.animation;e.notifyPlugins("afterRender"),callback(n&&n.onComplete,[t],e)}function onAnimationProgress(t){const e=t.chart,n=e.options.animation;callback(n&&n.onProgress,[t],e)}function getCanvas(t){return _isDomSupported()&&typeof t=="string"?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const instances={},getChart=t=>{const e=getCanvas(t);return Object.values(instances).filter(n=>n.canvas===e).pop()};function moveNumericKeys(t,e,n){const r=Object.keys(t);for(const s of r){const i=+s;if(i>=e){const a=t[s];delete t[s],(n>0||i>e)&&(t[i+n]=a)}}}function determineLastEvent(t,e,n,r){return!n||t.type==="mouseout"?null:r?e:t}function getSizeForArea(t,e,n){return t.options.clip?t[n]:e[n]}function getDatasetArea(t,e){const{xScale:n,yScale:r}=t;return n&&r?{left:getSizeForArea(n,e,"left"),right:getSizeForArea(n,e,"right"),top:getSizeForArea(r,e,"top"),bottom:getSizeForArea(r,e,"bottom")}:e}class Chart{static defaults=defaults;static instances=instances;static overrides=overrides;static registry=registry;static version=version;static getChart=getChart;static register(...e){registry.add(...e),invalidatePlugins()}static unregister(...e){registry.remove(...e),invalidatePlugins()}constructor(e,n){const r=this.config=new Config(n),s=getCanvas(e),i=getChart(s);if(i)throw new Error("Canvas is already in use. Chart with ID '"+i.id+"' must be destroyed before the canvas with ID '"+i.canvas.id+"' can be reused.");const a=r.createResolver(r.chartOptionScopes(),this.getContext());this.platform=new(r.platform||_detectPlatform(s)),this.platform.updateConfig(r);const u=this.platform.acquireContext(s,a.aspectRatio),d=u&&u.canvas,o=d&&d.height,l=d&&d.width;if(this.id=uid(),this.ctx=u,this.canvas=d,this.width=l,this.height=o,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new PluginService,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=debounce(c=>this.update(c),a.resizeDelay||0),this._dataChanges=[],instances[this.id]=this,!u||!d){console.error("Failed to create chart: can't acquire context from the given item");return}animator.listen(this,"complete",onAnimationsComplete),animator.listen(this,"progress",onAnimationProgress),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:e,maintainAspectRatio:n},width:r,height:s,_aspectRatio:i}=this;return isNullOrUndef(e)?n&&i?i:s?r/s:null:e}get data(){return this.config.data}set data(e){this.config.data=e}get options(){return this._options}set options(e){this.config.options=e}get registry(){return registry}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():retinaScale(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return clearCanvas(this.canvas,this.ctx),this}stop(){return animator.stop(this),this}resize(e,n){animator.running(this)?this._resizeBeforeDraw={width:e,height:n}:this._resize(e,n)}_resize(e,n){const r=this.options,s=this.canvas,i=r.maintainAspectRatio&&this.aspectRatio,a=this.platform.getMaximumSize(s,e,n,i),u=r.devicePixelRatio||this.platform.getDevicePixelRatio(),d=this.width?"resize":"attach";this.width=a.width,this.height=a.height,this._aspectRatio=this.aspectRatio,retinaScale(this,u,!0)&&(this.notifyPlugins("resize",{size:a}),callback(r.onResize,[this,a],this),this.attached&&this._doResize(d)&&this.render())}ensureScalesHaveIDs(){const n=this.options.scales||{};each(n,(r,s)=>{r.id=s})}buildOrUpdateScales(){const e=this.options,n=e.scales,r=this.scales,s=Object.keys(r).reduce((a,u)=>(a[u]=!1,a),{});let i=[];n&&(i=i.concat(Object.keys(n).map(a=>{const u=n[a],d=determineAxis(a,u),o=d==="r",l=d==="x";return{options:u,dposition:o?"chartArea":l?"bottom":"left",dtype:o?"radialLinear":l?"category":"linear"}}))),each(i,a=>{const u=a.options,d=u.id,o=determineAxis(d,u),l=valueOrDefault(u.type,a.dtype);(u.position===void 0||positionIsHorizontal(u.position,o)!==positionIsHorizontal(a.dposition))&&(u.position=a.dposition),s[d]=!0;let c=null;if(d in r&&r[d].type===l)c=r[d];else{const h=registry.getScale(l);c=new h({id:d,type:l,ctx:this.ctx,chart:this}),r[c.id]=c}c.init(u,e)}),each(s,(a,u)=>{a||delete r[u]}),each(r,a=>{layouts.configure(this,a,a.options),layouts.addBox(this,a)})}_updateMetasets(){const e=this._metasets,n=this.data.datasets.length,r=e.length;if(e.sort((s,i)=>s.index-i.index),r>n){for(let s=n;sn.length&&delete this._stacks,e.forEach((r,s)=>{n.filter(i=>i===r._dataset).length===0&&this._destroyDatasetMeta(s)})}buildOrUpdateControllers(){const e=[],n=this.data.datasets;let r,s;for(this._removeUnreferencedMetasets(),r=0,s=n.length;r{this.getDatasetMeta(n).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(e){const n=this.config;n.update();const r=this._options=n.createResolver(n.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!r.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:e,cancelable:!0})===!1)return;const i=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let a=0;for(let o=0,l=this.data.datasets.length;o{o.reset()}),this._updateDatasets(e),this.notifyPlugins("afterUpdate",{mode:e}),this._layers.sort(compare2Level("z","_idx"));const{_active:u,_lastEvent:d}=this;d?this._eventHandler(d,!0):u.length&&this._updateHoverStyles(u,u,!0),this.render()}_updateScales(){each(this.scales,e=>{layouts.removeBox(this,e)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const e=this.options,n=new Set(Object.keys(this._listeners)),r=new Set(e.events);(!setsEqual(n,r)||!!this._responsiveListeners!==e.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:e}=this,n=this._getUniformDataChanges()||[];for(const{method:r,start:s,count:i}of n){const a=r==="_removeElements"?-i:i;moveNumericKeys(e,s,a)}}_getUniformDataChanges(){const e=this._dataChanges;if(!e||!e.length)return;this._dataChanges=[];const n=this.data.datasets.length,r=i=>new Set(e.filter(a=>a[0]===i).map((a,u)=>u+","+a.splice(1).join(","))),s=r(0);for(let i=1;ii.split(",")).map(i=>({method:i[1],start:+i[2],count:+i[3]}))}_updateLayout(e){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;layouts.update(this,this.width,this.height,e);const n=this.chartArea,r=n.width<=0||n.height<=0;this._layers=[],each(this.boxes,s=>{r&&s.position==="chartArea"||(s.configure&&s.configure(),this._layers.push(...s._layers()))},this),this._layers.forEach((s,i)=>{s._idx=i}),this.notifyPlugins("afterLayout")}_updateDatasets(e){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:e,cancelable:!0})!==!1){for(let n=0,r=this.data.datasets.length;n=0;--n)this._drawDataset(e[n]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(e){const n=this.ctx,r=e._clip,s=!r.disabled,i=getDatasetArea(e,this.chartArea),a={meta:e,index:e.index,cancelable:!0};this.notifyPlugins("beforeDatasetDraw",a)!==!1&&(s&&clipArea(n,{left:r.left===!1?0:i.left-r.left,right:r.right===!1?this.width:i.right+r.right,top:r.top===!1?0:i.top-r.top,bottom:r.bottom===!1?this.height:i.bottom+r.bottom}),e.controller.draw(),s&&unclipArea(n),a.cancelable=!1,this.notifyPlugins("afterDatasetDraw",a))}isPointInArea(e){return _isPointInArea(e,this.chartArea,this._minPadding)}getElementsAtEventForMode(e,n,r,s){const i=Interaction.modes[n];return typeof i=="function"?i(this,e,r,s):[]}getDatasetMeta(e){const n=this.data.datasets[e],r=this._metasets;let s=r.filter(i=>i&&i._dataset===n).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:n&&n.order||0,index:e,_dataset:n,_parsed:[],_sorted:!1},r.push(s)),s}getContext(){return this.$context||(this.$context=createContext(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(e){const n=this.data.datasets[e];if(!n)return!1;const r=this.getDatasetMeta(e);return typeof r.hidden=="boolean"?!r.hidden:!n.hidden}setDatasetVisibility(e,n){const r=this.getDatasetMeta(e);r.hidden=!n}toggleDataVisibility(e){this._hiddenIndices[e]=!this._hiddenIndices[e]}getDataVisibility(e){return!this._hiddenIndices[e]}_updateVisibility(e,n,r){const s=r?"show":"hide",i=this.getDatasetMeta(e),a=i.controller._resolveAnimations(void 0,s);defined(n)?(i.data[n].hidden=!r,this.update()):(this.setDatasetVisibility(e,r),a.update(i,{visible:r}),this.update(u=>u.datasetIndex===e?s:void 0))}hide(e,n){this._updateVisibility(e,n,!1)}show(e,n){this._updateVisibility(e,n,!0)}_destroyDatasetMeta(e){const n=this._metasets[e];n&&n.controller&&n.controller._destroy(),delete this._metasets[e]}_stop(){let e,n;for(this.stop(),animator.remove(this),e=0,n=this.data.datasets.length;e{n.addEventListener(this,i,a),e[i]=a},s=(i,a,u)=>{i.offsetX=a,i.offsetY=u,this._eventHandler(i)};each(this.options.events,i=>r(i,s))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const e=this._responsiveListeners,n=this.platform,r=(d,o)=>{n.addEventListener(this,d,o),e[d]=o},s=(d,o)=>{e[d]&&(n.removeEventListener(this,d,o),delete e[d])},i=(d,o)=>{this.canvas&&this.resize(d,o)};let a;const u=()=>{s("attach",u),this.attached=!0,this.resize(),r("resize",i),r("detach",a)};a=()=>{this.attached=!1,s("resize",i),this._stop(),this._resize(0,0),r("attach",u)},n.isAttached(this.canvas)?u():a()}unbindEvents(){each(this._listeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._listeners={},each(this._responsiveListeners,(e,n)=>{this.platform.removeEventListener(this,n,e)}),this._responsiveListeners=void 0}updateHoverStyle(e,n,r){const s=r?"set":"remove";let i,a,u,d;for(n==="dataset"&&(i=this.getDatasetMeta(e[0].datasetIndex),i.controller["_"+s+"DatasetHoverStyle"]()),u=0,d=e.length;u{const u=this.getDatasetMeta(i);if(!u)throw new Error("No dataset found at index "+i);return{datasetIndex:i,element:u.data[a],index:a}});!_elementsEqual(r,n)&&(this._active=r,this._lastEvent=null,this._updateHoverStyles(r,n))}notifyPlugins(e,n,r){return this._plugins.notify(this,e,n,r)}isPluginEnabled(e){return this._plugins._cache.filter(n=>n.plugin.id===e).length===1}_updateHoverStyles(e,n,r){const s=this.options.hover,i=(d,o)=>d.filter(l=>!o.some(c=>l.datasetIndex===c.datasetIndex&&l.index===c.index)),a=i(n,e),u=r?e:i(e,n);a.length&&this.updateHoverStyle(a,s.mode,!1),u.length&&s.mode&&this.updateHoverStyle(u,s.mode,!0)}_eventHandler(e,n){const r={event:e,replay:n,cancelable:!0,inChartArea:this.isPointInArea(e)},s=a=>(a.options.events||this.options.events).includes(e.native.type);if(this.notifyPlugins("beforeEvent",r,s)===!1)return;const i=this._handleEvent(e,n,r.inChartArea);return r.cancelable=!1,this.notifyPlugins("afterEvent",r,s),(i||r.changed)&&this.render(),this}_handleEvent(e,n,r){const{_active:s=[],options:i}=this,a=n,u=this._getActiveElements(e,s,r,a),d=_isClickEvent(e),o=determineLastEvent(e,this._lastEvent,r,d);r&&(this._lastEvent=null,callback(i.onHover,[e,u,this],this),d&&callback(i.onClick,[e,u,this],this));const l=!_elementsEqual(u,s);return(l||n)&&(this._active=u,this._updateHoverStyles(u,s,n)),this._lastEvent=o,l}_getActiveElements(e,n,r,s){if(e.type==="mouseout")return[];if(!r)return n;const i=this.options.hover;return this.getElementsAtEventForMode(e,i.mode,i,s)}}function invalidatePlugins(){return each(Chart.instances,t=>t._plugins.invalidate())}function clipArc(t,e,n){const{startAngle:r,pixelMargin:s,x:i,y:a,outerRadius:u,innerRadius:d}=e;let o=s/u;t.beginPath(),t.arc(i,a,u,r-o,n+o),d>s?(o=s/d,t.arc(i,a,d,n+o,r-o,!0)):t.arc(i,a,s,n+HALF_PI,r-HALF_PI),t.closePath(),t.clip()}function toRadiusCorners(t){return _readValueToProps(t,["outerStart","outerEnd","innerStart","innerEnd"])}function parseBorderRadius$1(t,e,n,r){const s=toRadiusCorners(t.options.borderRadius),i=(n-e)/2,a=Math.min(i,r*e/2),u=d=>{const o=(n-Math.min(i,d))*r/2;return _limitValue(d,0,Math.min(i,o))};return{outerStart:u(s.outerStart),outerEnd:u(s.outerEnd),innerStart:_limitValue(s.innerStart,0,a),innerEnd:_limitValue(s.innerEnd,0,a)}}function rThetaToXY(t,e,n,r){return{x:n+t*Math.cos(e),y:r+t*Math.sin(e)}}function pathArc(t,e,n,r,s,i){const{x:a,y:u,startAngle:d,pixelMargin:o,innerRadius:l}=e,c=Math.max(e.outerRadius+r+n-o,0),h=l>0?l+r+n+o:0;let f=0;const p=s-d;if(r){const K=l>0?l-r:0,he=c>0?c-r:0,se=(K+he)/2,we=se!==0?p*se/(se+r):p;f=(p-we)/2}const g=Math.max(.001,p*c-n/PI)/c,b=(p-g)/2,x=d+b+f,y=s-b-f,{outerStart:T,outerEnd:S,innerStart:E,innerEnd:N}=parseBorderRadius$1(e,h,c,y-x),B=c-T,F=c-S,k=x+T/B,G=y-S/F,re=h+E,ie=h+N,ge=x+E/re,X=y-N/ie;if(t.beginPath(),i){const K=(k+G)/2;if(t.arc(a,u,c,k,K),t.arc(a,u,c,K,G),S>0){const ue=rThetaToXY(F,G,a,u);t.arc(ue.x,ue.y,S,G,y+HALF_PI)}const he=rThetaToXY(ie,y,a,u);if(t.lineTo(he.x,he.y),N>0){const ue=rThetaToXY(ie,X,a,u);t.arc(ue.x,ue.y,N,y+HALF_PI,X+Math.PI)}const se=(y-N/h+(x+E/h))/2;if(t.arc(a,u,h,y-N/h,se,!0),t.arc(a,u,h,se,x+E/h,!0),E>0){const ue=rThetaToXY(re,ge,a,u);t.arc(ue.x,ue.y,E,ge+Math.PI,x-HALF_PI)}const we=rThetaToXY(B,x,a,u);if(t.lineTo(we.x,we.y),T>0){const ue=rThetaToXY(B,k,a,u);t.arc(ue.x,ue.y,T,x-HALF_PI,k)}}else{t.moveTo(a,u);const K=Math.cos(k)*c+a,he=Math.sin(k)*c+u;t.lineTo(K,he);const se=Math.cos(G)*c+a,we=Math.sin(G)*c+u;t.lineTo(se,we)}t.closePath()}function drawArc(t,e,n,r,s){const{fullCircles:i,startAngle:a,circumference:u}=e;let d=e.endAngle;if(i){pathArc(t,e,n,r,d,s);for(let o=0;oe!=="borderDash"};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(e){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,e&&Object.assign(this,e)}inRange(e,n,r){const s=this.getProps(["x","y"],r),{angle:i,distance:a}=getAngleFromPoint(s,{x:e,y:n}),{startAngle:u,endAngle:d,innerRadius:o,outerRadius:l,circumference:c}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],r),h=(this.options.spacing+this.options.borderWidth)/2,p=valueOrDefault(c,d-u)>=TAU||_angleBetween(i,u,d),g=_isBetween(a,o+h,l+h);return p&&g}getCenterPoint(e){const{x:n,y:r,startAngle:s,endAngle:i,innerRadius:a,outerRadius:u}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],e),{offset:d,spacing:o}=this.options,l=(s+i)/2,c=(a+u+o+d)/2;return{x:n+Math.cos(l)*c,y:r+Math.sin(l)*c}}tooltipPosition(e){return this.getCenterPoint(e)}draw(e){const{options:n,circumference:r}=this,s=(n.offset||0)/4,i=(n.spacing||0)/2,a=n.circular;if(this.pixelMargin=n.borderAlign==="inner"?.33:0,this.fullCircles=r>TAU?Math.floor(r/TAU):0,r===0||this.innerRadius<0||this.outerRadius<0)return;e.save();const u=(this.startAngle+this.endAngle)/2;e.translate(Math.cos(u)*s,Math.sin(u)*s);const d=1-Math.sin(Math.min(PI,r||0)),o=s*d;e.fillStyle=n.backgroundColor,e.strokeStyle=n.borderColor,drawArc(e,this,o,i,a),drawBorder(e,this,o,i,a),e.restore()}}function setStyle(t,e,n=e){t.lineCap=valueOrDefault(n.borderCapStyle,e.borderCapStyle),t.setLineDash(valueOrDefault(n.borderDash,e.borderDash)),t.lineDashOffset=valueOrDefault(n.borderDashOffset,e.borderDashOffset),t.lineJoin=valueOrDefault(n.borderJoinStyle,e.borderJoinStyle),t.lineWidth=valueOrDefault(n.borderWidth,e.borderWidth),t.strokeStyle=valueOrDefault(n.borderColor,e.borderColor)}function lineTo(t,e,n){t.lineTo(n.x,n.y)}function getLineMethod(t){return t.stepped?_steppedLineTo:t.tension||t.cubicInterpolationMode==="monotone"?_bezierCurveTo:lineTo}function pathVars(t,e,n={}){const r=t.length,{start:s=0,end:i=r-1}=n,{start:a,end:u}=e,d=Math.max(s,a),o=Math.min(i,u),l=su&&i>u;return{count:r,start:d,loop:e.loop,ilen:o(a+(o?u-S:S))%i,T=()=>{g!==b&&(t.lineTo(l,b),t.lineTo(l,g),t.lineTo(l,x))};for(d&&(f=s[y(0)],t.moveTo(f.x,f.y)),h=0;h<=u;++h){if(f=s[y(h)],f.skip)continue;const S=f.x,E=f.y,N=S|0;N===p?(Eb&&(b=E),l=(c*l+S)/++c):(T(),t.lineTo(S,E),p=N,c=0,g=b=E),x=E}T()}function _getSegmentMethod(t){const e=t.options,n=e.borderDash&&e.borderDash.length;return!t._decimated&&!t._loop&&!e.tension&&e.cubicInterpolationMode!=="monotone"&&!e.stepped&&!n?fastPathSegment:pathSegment}function _getInterpolationMethod(t){return t.stepped?_steppedInterpolation:t.tension||t.cubicInterpolationMode==="monotone"?_bezierInterpolation:_pointInLine}function strokePathWithCache(t,e,n,r){let s=e._path;s||(s=e._path=new Path2D,e.path(s,n,r)&&s.closePath()),setStyle(t,e.options),t.stroke(s)}function strokePathDirect(t,e,n,r){const{segments:s,options:i}=e,a=_getSegmentMethod(e);for(const u of s)setStyle(t,i,u.style),t.beginPath(),a(t,e,u,{start:n,end:n+r-1})&&t.closePath(),t.stroke()}const usePath2D=typeof Path2D=="function";function draw(t,e,n,r){usePath2D&&!e.options.segment?strokePathWithCache(t,e,n,r):strokePathDirect(t,e,n,r)}class LineElement extends Element{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:e=>e!=="borderDash"&&e!=="fill"};constructor(e){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,e&&Object.assign(this,e)}updateControlPoints(e,n){const r=this.options;if((r.tension||r.cubicInterpolationMode==="monotone")&&!r.stepped&&!this._pointsUpdated){const s=r.spanGaps?this._loop:this._fullLoop;_updateBezierControlPoints(this._points,r,e,s,n),this._pointsUpdated=!0}}set points(e){this._points=e,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=_computeSegments(this,this.options.segment))}first(){const e=this.segments,n=this.points;return e.length&&n[e[0].start]}last(){const e=this.segments,n=this.points,r=e.length;return r&&n[e[r-1].end]}interpolate(e,n){const r=this.options,s=e[n],i=this.points,a=_boundSegments(this,{property:n,start:s,end:s});if(!a.length)return;const u=[],d=_getInterpolationMethod(r);let o,l;for(o=0,l=a.length;ot.replace("rgb(","rgba(").replace(")",", 0.5)"));function getBorderColor(t){return BORDER_COLORS[t%BORDER_COLORS.length]}function getBackgroundColor(t){return BACKGROUND_COLORS[t%BACKGROUND_COLORS.length]}function colorizeDefaultDataset(t,e){return t.borderColor=getBorderColor(e),t.backgroundColor=getBackgroundColor(e),++e}function colorizeDoughnutDataset(t,e){return t.backgroundColor=t.data.map(()=>getBorderColor(e++)),e}function colorizePolarAreaDataset(t,e){return t.backgroundColor=t.data.map(()=>getBackgroundColor(e++)),e}function getColorizer(t){let e=0;return(n,r)=>{const s=t.getDatasetMeta(r).controller;s instanceof DoughnutController?e=colorizeDoughnutDataset(n,e):s instanceof PolarAreaController?e=colorizePolarAreaDataset(n,e):s&&(e=colorizeDefaultDataset(n,e))}}function containsColorsDefinitions(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}function containsColorsDefinition(t){return t&&(t.borderColor||t.backgroundColor)}var plugin_colors={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,n){if(!n.enabled)return;const{data:{datasets:r},options:s}=t.config,{elements:i}=s;if(!n.forceOverride&&(containsColorsDefinitions(r)||containsColorsDefinition(s)||i&&containsColorsDefinitions(i)))return;const a=getColorizer(t);r.forEach(a)}};function lttbDecimation(t,e,n,r,s){const i=s.samples||r;if(i>=n)return t.slice(e,e+n);const a=[],u=(n-2)/(i-2);let d=0;const o=e+n-1;let l=e,c,h,f,p,g;for(a[d++]=t[l],c=0;cf&&(f=p,h=t[y],g=y);a[d++]=h,l=g}return a[d++]=t[o],a}function minMaxDecimation(t,e,n,r){let s=0,i=0,a,u,d,o,l,c,h,f,p,g;const b=[],x=e+n-1,y=t[e].x,S=t[x].x-y;for(a=e;ag&&(g=o,h=a),s=(i*s+u.x)/++i;else{const N=a-1;if(!isNullOrUndef(c)&&!isNullOrUndef(h)){const B=Math.min(c,h),F=Math.max(c,h);B!==f&&B!==N&&b.push({...t[B],x:s}),F!==f&&F!==N&&b.push({...t[F],x:s})}a>0&&N!==f&&b.push(t[N]),b.push(u),l=E,i=0,p=g=o,c=h=f=a}}return b}function cleanDecimatedDataset(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function cleanDecimatedData(t){t.data.datasets.forEach(e=>{cleanDecimatedDataset(e)})}function getStartAndCountOfVisiblePointsSimplified(t,e){const n=e.length;let r=0,s;const{iScale:i}=t,{min:a,max:u,minDefined:d,maxDefined:o}=i.getUserBounds();return d&&(r=_limitValue(_lookupByKey(e,i.axis,a).lo,0,n-1)),o?s=_limitValue(_lookupByKey(e,i.axis,u).hi+1,r,n)-r:s=n-r,{start:r,count:s}}var plugin_decimation={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,n)=>{if(!n.enabled){cleanDecimatedData(t);return}const r=t.width;t.data.datasets.forEach((s,i)=>{const{_data:a,indexAxis:u}=s,d=t.getDatasetMeta(i),o=a||s.data;if(resolve([u,t.options.indexAxis])==="y"||!d.controller.supportsDecimation)return;const l=t.scales[d.xAxisID];if(l.type!=="linear"&&l.type!=="time"||t.options.parsing)return;let{start:c,count:h}=getStartAndCountOfVisiblePointsSimplified(d,o);const f=n.threshold||4*r;if(h<=f){cleanDecimatedDataset(s);return}isNullOrUndef(a)&&(s._data=o,delete s.data,Object.defineProperty(s,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(g){this._data=g}}));let p;switch(n.algorithm){case"lttb":p=lttbDecimation(o,c,h,r,n);break;case"min-max":p=minMaxDecimation(o,c,h,r);break;default:throw new Error(`Unsupported decimation algorithm '${n.algorithm}'`)}s._decimated=p})},destroy(t){cleanDecimatedData(t)}};function _segments(t,e,n){const r=t.segments,s=t.points,i=e.points,a=[];for(const u of r){let{start:d,end:o}=u;o=_findSegmentEnd(d,o,s);const l=_getBounds(n,s[d],s[o],u.loop);if(!e.segments){a.push({source:u,target:l,start:s[d],end:s[o]});continue}const c=_boundSegments(e,l);for(const h of c){const f=_getBounds(n,i[h.start],i[h.end],h.loop),p=_boundSegment(u,s,f);for(const g of p)a.push({source:g,target:h,start:{[n]:_getEdge(l,f,"start",Math.max)},end:{[n]:_getEdge(l,f,"end",Math.min)}})}}return a}function _getBounds(t,e,n,r){if(r)return;let s=e[t],i=n[t];return t==="angle"&&(s=_normalizeAngle(s),i=_normalizeAngle(i)),{property:t,start:s,end:i}}function _pointsFromSegments(t,e){const{x:n=null,y:r=null}=t||{},s=e.points,i=[];return e.segments.forEach(({start:a,end:u})=>{u=_findSegmentEnd(a,u,s);const d=s[a],o=s[u];r!==null?(i.push({x:d.x,y:r}),i.push({x:o.x,y:r})):n!==null&&(i.push({x:n,y:d.y}),i.push({x:n,y:o.y}))}),i}function _findSegmentEnd(t,e,n){for(;e>t;e--){const r=n[e];if(!isNaN(r.x)&&!isNaN(r.y))break}return e}function _getEdge(t,e,n,r){return t&&e?r(t[n],e[n]):t?t[n]:e?e[n]:0}function _createBoundaryLine(t,e){let n=[],r=!1;return isArray(t)?(r=!0,n=t):n=_pointsFromSegments(t,e),n.length?new LineElement({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function _shouldApplyFill(t){return t&&t.fill!==!1}function _resolveTarget(t,e,n){let s=t[e].fill;const i=[e];let a;if(!n)return s;for(;s!==!1&&i.indexOf(s)===-1;){if(!isNumberFinite(s))return s;if(a=t[s],!a)return!1;if(a.visible)return s;i.push(s),s=a.fill}return!1}function _decodeFill(t,e,n){const r=parseFillOption(t);if(isObject(r))return isNaN(r.value)?!1:r;let s=parseFloat(r);return isNumberFinite(s)&&Math.floor(s)===s?decodeTargetIndex(r[0],e,s,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function decodeTargetIndex(t,e,n,r){return(t==="-"||t==="+")&&(n=e+n),n===e||n<0||n>=r?!1:n}function _getTargetPixel(t,e){let n=null;return t==="start"?n=e.bottom:t==="end"?n=e.top:isObject(t)?n=e.getPixelForValue(t.value):e.getBasePixel&&(n=e.getBasePixel()),n}function _getTargetValue(t,e,n){let r;return t==="start"?r=n:t==="end"?r=e.options.reverse?e.min:e.max:isObject(t)?r=t.value:r=e.getBaseValue(),r}function parseFillOption(t){const e=t.options,n=e.fill;let r=valueOrDefault(n&&n.target,n);return r===void 0&&(r=!!e.backgroundColor),r===!1||r===null?!1:r===!0?"origin":r}function _buildStackLine(t){const{scale:e,index:n,line:r}=t,s=[],i=r.segments,a=r.points,u=getLinesBelow(e,n);u.push(_createBoundaryLine({x:null,y:e.bottom},r));for(let d=0;d=0;--a){const u=s[a].$filler;u&&(u.line.updateControlPoints(i,u.axis),r&&u.fill&&_drawfill(t.ctx,u,i))}},beforeDatasetsDraw(t,e,n){if(n.drawTime!=="beforeDatasetsDraw")return;const r=t.getSortedVisibleDatasetMetas();for(let s=r.length-1;s>=0;--s){const i=r[s].$filler;_shouldApplyFill(i)&&_drawfill(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,n){const r=e.meta.$filler;!_shouldApplyFill(r)||n.drawTime!=="beforeDatasetDraw"||_drawfill(t.ctx,r,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const getBoxSize=(t,e)=>{let{boxHeight:n=e,boxWidth:r=e}=t;return t.usePointStyle&&(n=Math.min(n,e),r=t.pointStyleWidth||Math.min(r,e)),{boxWidth:r,boxHeight:n,itemHeight:Math.max(e,n)}},itemsEqual=(t,e)=>t!==null&&e!==null&&t.datasetIndex===e.datasetIndex&&t.index===e.index;class Legend extends Element{constructor(e){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=e.chart,this.options=e.options,this.ctx=e.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(e,n,r){this.maxWidth=e,this.maxHeight=n,this._margins=r,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const e=this.options.labels||{};let n=callback(e.generateLabels,[this.chart],this)||[];e.filter&&(n=n.filter(r=>e.filter(r,this.chart.data))),e.sort&&(n=n.sort((r,s)=>e.sort(r,s,this.chart.data))),this.options.reverse&&n.reverse(),this.legendItems=n}fit(){const{options:e,ctx:n}=this;if(!e.display){this.width=this.height=0;return}const r=e.labels,s=toFont(r.font),i=s.size,a=this._computeTitleHeight(),{boxWidth:u,itemHeight:d}=getBoxSize(r,i);let o,l;n.font=s.string,this.isHorizontal()?(o=this.maxWidth,l=this._fitRows(a,i,u,d)+10):(l=this.maxHeight,o=this._fitCols(a,s,u,d)+10),this.width=Math.min(o,e.maxWidth||this.maxWidth),this.height=Math.min(l,e.maxHeight||this.maxHeight)}_fitRows(e,n,r,s){const{ctx:i,maxWidth:a,options:{labels:{padding:u}}}=this,d=this.legendHitBoxes=[],o=this.lineWidths=[0],l=s+u;let c=e;i.textAlign="left",i.textBaseline="middle";let h=-1,f=-l;return this.legendItems.forEach((p,g)=>{const b=r+n/2+i.measureText(p.text).width;(g===0||o[o.length-1]+b+2*u>a)&&(c+=l,o[o.length-(g>0?0:1)]=0,f+=l,h++),d[g]={left:0,top:f,row:h,width:b,height:s},o[o.length-1]+=b+u}),c}_fitCols(e,n,r,s){const{ctx:i,maxHeight:a,options:{labels:{padding:u}}}=this,d=this.legendHitBoxes=[],o=this.columnSizes=[],l=a-e;let c=u,h=0,f=0,p=0,g=0;return this.legendItems.forEach((b,x)=>{const{itemWidth:y,itemHeight:T}=calculateItemSize(r,n,i,b,s);x>0&&f+T+2*u>l&&(c+=h+u,o.push({width:h,height:f}),p+=h+u,g++,h=f=0),d[x]={left:p,top:f,col:g,width:y,height:T},h=Math.max(h,y),f+=T+u}),c+=h,o.push({width:h,height:f}),c}adjustHitBoxes(){if(!this.options.display)return;const e=this._computeTitleHeight(),{legendHitBoxes:n,options:{align:r,labels:{padding:s},rtl:i}}=this,a=getRtlAdapter(i,this.left,this.width);if(this.isHorizontal()){let u=0,d=_alignStartEnd(r,this.left+s,this.right-this.lineWidths[u]);for(const o of n)u!==o.row&&(u=o.row,d=_alignStartEnd(r,this.left+s,this.right-this.lineWidths[u])),o.top+=this.top+e+s,o.left=a.leftForLtr(a.x(d),o.width),d+=o.width+s}else{let u=0,d=_alignStartEnd(r,this.top+e+s,this.bottom-this.columnSizes[u].height);for(const o of n)o.col!==u&&(u=o.col,d=_alignStartEnd(r,this.top+e+s,this.bottom-this.columnSizes[u].height)),o.top=d,o.left+=this.left+s,o.left=a.leftForLtr(a.x(o.left),o.width),d+=o.height+s}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){const e=this.ctx;clipArea(e,this),this._draw(),unclipArea(e)}}_draw(){const{options:e,columnSizes:n,lineWidths:r,ctx:s}=this,{align:i,labels:a}=e,u=defaults.color,d=getRtlAdapter(e.rtl,this.left,this.width),o=toFont(a.font),{padding:l}=a,c=o.size,h=c/2;let f;this.drawTitle(),s.textAlign=d.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=o.string;const{boxWidth:p,boxHeight:g,itemHeight:b}=getBoxSize(a,c),x=function(N,B,F){if(isNaN(p)||p<=0||isNaN(g)||g<0)return;s.save();const k=valueOrDefault(F.lineWidth,1);if(s.fillStyle=valueOrDefault(F.fillStyle,u),s.lineCap=valueOrDefault(F.lineCap,"butt"),s.lineDashOffset=valueOrDefault(F.lineDashOffset,0),s.lineJoin=valueOrDefault(F.lineJoin,"miter"),s.lineWidth=k,s.strokeStyle=valueOrDefault(F.strokeStyle,u),s.setLineDash(valueOrDefault(F.lineDash,[])),a.usePointStyle){const G={radius:g*Math.SQRT2/2,pointStyle:F.pointStyle,rotation:F.rotation,borderWidth:k},re=d.xPlus(N,p/2),ie=B+h;drawPointLegend(s,G,re,ie,a.pointStyleWidth&&p)}else{const G=B+Math.max((c-g)/2,0),re=d.leftForLtr(N,p),ie=toTRBLCorners(F.borderRadius);s.beginPath(),Object.values(ie).some(ge=>ge!==0)?addRoundedRectPath(s,{x:re,y:G,w:p,h:g,radius:ie}):s.rect(re,G,p,g),s.fill(),k!==0&&s.stroke()}s.restore()},y=function(N,B,F){renderText(s,F.text,N,B+b/2,o,{strikethrough:F.hidden,textAlign:d.textAlign(F.textAlign)})},T=this.isHorizontal(),S=this._computeTitleHeight();T?f={x:_alignStartEnd(i,this.left+l,this.right-r[0]),y:this.top+l+S,line:0}:f={x:this.left+l,y:_alignStartEnd(i,this.top+S+l,this.bottom-n[0].height),line:0},overrideTextDirection(this.ctx,e.textDirection);const E=b+l;this.legendItems.forEach((N,B)=>{s.strokeStyle=N.fontColor,s.fillStyle=N.fontColor;const F=s.measureText(N.text).width,k=d.textAlign(N.textAlign||(N.textAlign=a.textAlign)),G=p+h+F;let re=f.x,ie=f.y;d.setWidth(this.width),T?B>0&&re+G+l>this.right&&(ie=f.y+=E,f.line++,re=f.x=_alignStartEnd(i,this.left+l,this.right-r[f.line])):B>0&&ie+E>this.bottom&&(re=f.x=re+n[f.line].width+l,f.line++,ie=f.y=_alignStartEnd(i,this.top+S+l,this.bottom-n[f.line].height));const ge=d.x(re);if(x(ge,ie,N),re=_textX(k,re+p+h,T?re+G:this.right,e.rtl),y(d.x(re),ie,N),T)f.x+=G+l;else if(typeof N.text!="string"){const X=o.lineHeight;f.y+=calculateLegendItemHeight(N,X)+l}else f.y+=E}),restoreTextDirection(this.ctx,e.textDirection)}drawTitle(){const e=this.options,n=e.title,r=toFont(n.font),s=toPadding(n.padding);if(!n.display)return;const i=getRtlAdapter(e.rtl,this.left,this.width),a=this.ctx,u=n.position,d=r.size/2,o=s.top+d;let l,c=this.left,h=this.width;if(this.isHorizontal())h=Math.max(...this.lineWidths),l=this.top+o,c=_alignStartEnd(e.align,c,this.right-h);else{const p=this.columnSizes.reduce((g,b)=>Math.max(g,b.height),0);l=o+_alignStartEnd(e.align,this.top,this.bottom-p-e.labels.padding-this._computeTitleHeight())}const f=_alignStartEnd(u,c,c+h);a.textAlign=i.textAlign(_toLeftRightCenter(u)),a.textBaseline="middle",a.strokeStyle=n.color,a.fillStyle=n.color,a.font=r.string,renderText(a,n.text,f,l,r)}_computeTitleHeight(){const e=this.options.title,n=toFont(e.font),r=toPadding(e.padding);return e.display?n.lineHeight+r.height:0}_getLegendItemAt(e,n){let r,s,i;if(_isBetween(e,this.left,this.right)&&_isBetween(n,this.top,this.bottom)){for(i=this.legendHitBoxes,r=0;ri.length>a.length?i:a)),e+n.size/2+r.measureText(s).width}function calculateItemHeight(t,e,n){let r=t;return typeof e.text!="string"&&(r=calculateLegendItemHeight(e,n)),r}function calculateLegendItemHeight(t,e){const n=t.text?t.text.length:0;return e*n}function isListened(t,e){return!!((t==="mousemove"||t==="mouseout")&&(e.onHover||e.onLeave)||e.onClick&&(t==="click"||t==="mouseup"))}var plugin_legend={id:"legend",_element:Legend,start(t,e,n){const r=t.legend=new Legend({ctx:t.ctx,options:n,chart:t});layouts.configure(t,r,n),layouts.addBox(t,r)},stop(t){layouts.removeBox(t,t.legend),delete t.legend},beforeUpdate(t,e,n){const r=t.legend;layouts.configure(t,r,n),r.options=n},afterUpdate(t){const e=t.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(t,e){e.replay||t.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(t,e,n){const r=e.datasetIndex,s=n.chart;s.isDatasetVisible(r)?(s.hide(r),e.hidden=!0):(s.show(r),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:t=>t.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:n,pointStyle:r,textAlign:s,color:i,useBorderRadius:a,borderRadius:u}}=t.legend.options;return t._getSortedDatasetMetas().map(d=>{const o=d.controller.getStyle(n?0:void 0),l=toPadding(o.borderWidth);return{text:e[d.index].label,fillStyle:o.backgroundColor,fontColor:i,hidden:!d.visible,lineCap:o.borderCapStyle,lineDash:o.borderDash,lineDashOffset:o.borderDashOffset,lineJoin:o.borderJoinStyle,lineWidth:(l.width+l.height)/4,strokeStyle:o.borderColor,pointStyle:r||o.pointStyle,rotation:o.rotation,textAlign:s||o.textAlign,borderRadius:a&&(u||o.borderRadius),datasetIndex:d.index}},this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class Title extends Element{constructor(e){super(),this.chart=e.chart,this.options=e.options,this.ctx=e.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(e,n){const r=this.options;if(this.left=0,this.top=0,!r.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=e,this.height=this.bottom=n;const s=isArray(r.text)?r.text.length:1;this._padding=toPadding(r.padding);const i=s*toFont(r.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=i:this.width=i}isHorizontal(){const e=this.options.position;return e==="top"||e==="bottom"}_drawArgs(e){const{top:n,left:r,bottom:s,right:i,options:a}=this,u=a.align;let d=0,o,l,c;return this.isHorizontal()?(l=_alignStartEnd(u,r,i),c=n+e,o=i-r):(a.position==="left"?(l=r+e,c=_alignStartEnd(u,s,n),d=PI*-.5):(l=i-e,c=_alignStartEnd(u,n,s),d=PI*.5),o=s-n),{titleX:l,titleY:c,maxWidth:o,rotation:d}}draw(){const e=this.ctx,n=this.options;if(!n.display)return;const r=toFont(n.font),i=r.lineHeight/2+this._padding.top,{titleX:a,titleY:u,maxWidth:d,rotation:o}=this._drawArgs(i);renderText(e,n.text,0,0,r,{color:n.color,maxWidth:d,rotation:o,textAlign:_toLeftRightCenter(n.align),textBaseline:"middle",translation:[a,u]})}}function createTitle(t,e){const n=new Title({ctx:t.ctx,options:e,chart:t});layouts.configure(t,n,e),layouts.addBox(t,n),t.titleBlock=n}var plugin_title={id:"title",_element:Title,start(t,e,n){createTitle(t,n)},stop(t){const e=t.titleBlock;layouts.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,n){const r=t.titleBlock;layouts.configure(t,r,n),r.options=n},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const map=new WeakMap;var plugin_subtitle={id:"subtitle",start(t,e,n){const r=new Title({ctx:t.ctx,options:n,chart:t});layouts.configure(t,r,n),layouts.addBox(t,r),map.set(t,r)},stop(t){layouts.removeBox(t,map.get(t)),map.delete(t)},beforeUpdate(t,e,n){const r=map.get(t);layouts.configure(t,r,n),r.options=n},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const positioners={average(t){if(!t.length)return!1;let e,n,r=new Set,s=0,i=0;for(e=0,n=t.length;eu+d)/r.size,y:s/i}},nearest(t,e){if(!t.length)return!1;let n=e.x,r=e.y,s=Number.POSITIVE_INFINITY,i,a,u;for(i=0,a=t.length;i-1?t.split(` +`):t}function createTooltipItem(t,e){const{element:n,datasetIndex:r,index:s}=e,i=t.getDatasetMeta(r).controller,{label:a,value:u}=i.getLabelAndValue(s);return{chart:t,label:a,parsed:i.getParsed(s),raw:t.data.datasets[r].data[s],formattedValue:u,dataset:i.getDataset(),dataIndex:s,datasetIndex:r,element:n}}function getTooltipSize(t,e){const n=t.chart.ctx,{body:r,footer:s,title:i}=t,{boxWidth:a,boxHeight:u}=e,d=toFont(e.bodyFont),o=toFont(e.titleFont),l=toFont(e.footerFont),c=i.length,h=s.length,f=r.length,p=toPadding(e.padding);let g=p.height,b=0,x=r.reduce((S,E)=>S+E.before.length+E.lines.length+E.after.length,0);if(x+=t.beforeBody.length+t.afterBody.length,c&&(g+=c*o.lineHeight+(c-1)*e.titleSpacing+e.titleMarginBottom),x){const S=e.displayColors?Math.max(u,d.lineHeight):d.lineHeight;g+=f*S+(x-f)*d.lineHeight+(x-1)*e.bodySpacing}h&&(g+=e.footerMarginTop+h*l.lineHeight+(h-1)*e.footerSpacing);let y=0;const T=function(S){b=Math.max(b,n.measureText(S).width+y)};return n.save(),n.font=o.string,each(t.title,T),n.font=d.string,each(t.beforeBody.concat(t.afterBody),T),y=e.displayColors?a+2+e.boxPadding:0,each(r,S=>{each(S.before,T),each(S.lines,T),each(S.after,T)}),y=0,n.font=l.string,each(t.footer,T),n.restore(),b+=p.width,{width:b,height:g}}function determineYAlign(t,e){const{y:n,height:r}=e;return nt.height-r/2?"bottom":"center"}function doesNotFitWithAlign(t,e,n,r){const{x:s,width:i}=r,a=n.caretSize+n.caretPadding;if(t==="left"&&s+i+a>e.width||t==="right"&&s-i-a<0)return!0}function determineXAlign(t,e,n,r){const{x:s,width:i}=n,{width:a,chartArea:{left:u,right:d}}=t;let o="center";return r==="center"?o=s<=(u+d)/2?"left":"right":s<=i/2?o="left":s>=a-i/2&&(o="right"),doesNotFitWithAlign(o,t,e,n)&&(o="center"),o}function determineAlignment(t,e,n){const r=n.yAlign||e.yAlign||determineYAlign(t,n);return{xAlign:n.xAlign||e.xAlign||determineXAlign(t,e,n,r),yAlign:r}}function alignX(t,e){let{x:n,width:r}=t;return e==="right"?n-=r:e==="center"&&(n-=r/2),n}function alignY(t,e,n){let{y:r,height:s}=t;return e==="top"?r+=n:e==="bottom"?r-=s+n:r-=s/2,r}function getBackgroundPoint(t,e,n,r){const{caretSize:s,caretPadding:i,cornerRadius:a}=t,{xAlign:u,yAlign:d}=n,o=s+i,{topLeft:l,topRight:c,bottomLeft:h,bottomRight:f}=toTRBLCorners(a);let p=alignX(e,u);const g=alignY(e,d,o);return d==="center"?u==="left"?p+=o:u==="right"&&(p-=o):u==="left"?p-=Math.max(l,h)+s:u==="right"&&(p+=Math.max(c,f)+s),{x:_limitValue(p,0,r.width-e.width),y:_limitValue(g,0,r.height-e.height)}}function getAlignedX(t,e,n){const r=toPadding(n.padding);return e==="center"?t.x+t.width/2:e==="right"?t.x+t.width-r.right:t.x+r.left}function getBeforeAfterBodyLines(t){return pushOrConcat([],splitNewlines(t))}function createTooltipContext(t,e,n){return createContext(t,{tooltip:e,tooltipItems:n,type:"tooltip"})}function overrideCallbacks(t,e){const n=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return n?t.override(n):t}const defaultCallbacks={beforeTitle:noop,title(t){if(t.length>0){const e=t[0],n=e.chart.data.labels,r=n?n.length:0;if(this&&this.options&&this.options.mode==="dataset")return e.dataset.label||"";if(e.label)return e.label;if(r>0&&e.dataIndex"u"?defaultCallbacks[e].call(n,r):s}class Tooltip extends Element{static positioners=positioners;constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const e=this._cachedAnimations;if(e)return e;const n=this.chart,r=this.options.setContext(this.getContext()),s=r.enabled&&n.options.animation&&r.animations,i=new Animations(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(i)),i}getContext(){return this.$context||(this.$context=createTooltipContext(this.chart.getContext(),this,this._tooltipItems))}getTitle(e,n){const{callbacks:r}=n,s=invokeCallbackWithFallback(r,"beforeTitle",this,e),i=invokeCallbackWithFallback(r,"title",this,e),a=invokeCallbackWithFallback(r,"afterTitle",this,e);let u=[];return u=pushOrConcat(u,splitNewlines(s)),u=pushOrConcat(u,splitNewlines(i)),u=pushOrConcat(u,splitNewlines(a)),u}getBeforeBody(e,n){return getBeforeAfterBodyLines(invokeCallbackWithFallback(n.callbacks,"beforeBody",this,e))}getBody(e,n){const{callbacks:r}=n,s=[];return each(e,i=>{const a={before:[],lines:[],after:[]},u=overrideCallbacks(r,i);pushOrConcat(a.before,splitNewlines(invokeCallbackWithFallback(u,"beforeLabel",this,i))),pushOrConcat(a.lines,invokeCallbackWithFallback(u,"label",this,i)),pushOrConcat(a.after,splitNewlines(invokeCallbackWithFallback(u,"afterLabel",this,i))),s.push(a)}),s}getAfterBody(e,n){return getBeforeAfterBodyLines(invokeCallbackWithFallback(n.callbacks,"afterBody",this,e))}getFooter(e,n){const{callbacks:r}=n,s=invokeCallbackWithFallback(r,"beforeFooter",this,e),i=invokeCallbackWithFallback(r,"footer",this,e),a=invokeCallbackWithFallback(r,"afterFooter",this,e);let u=[];return u=pushOrConcat(u,splitNewlines(s)),u=pushOrConcat(u,splitNewlines(i)),u=pushOrConcat(u,splitNewlines(a)),u}_createItems(e){const n=this._active,r=this.chart.data,s=[],i=[],a=[];let u=[],d,o;for(d=0,o=n.length;de.filter(l,c,h,r))),e.itemSort&&(u=u.sort((l,c)=>e.itemSort(l,c,r))),each(u,l=>{const c=overrideCallbacks(e.callbacks,l);s.push(invokeCallbackWithFallback(c,"labelColor",this,l)),i.push(invokeCallbackWithFallback(c,"labelPointStyle",this,l)),a.push(invokeCallbackWithFallback(c,"labelTextColor",this,l))}),this.labelColors=s,this.labelPointStyles=i,this.labelTextColors=a,this.dataPoints=u,u}update(e,n){const r=this.options.setContext(this.getContext()),s=this._active;let i,a=[];if(!s.length)this.opacity!==0&&(i={opacity:0});else{const u=positioners[r.position].call(this,s,this._eventPosition);a=this._createItems(r),this.title=this.getTitle(a,r),this.beforeBody=this.getBeforeBody(a,r),this.body=this.getBody(a,r),this.afterBody=this.getAfterBody(a,r),this.footer=this.getFooter(a,r);const d=this._size=getTooltipSize(this,r),o=Object.assign({},u,d),l=determineAlignment(this.chart,r,o),c=getBackgroundPoint(r,o,l,this.chart);this.xAlign=l.xAlign,this.yAlign=l.yAlign,i={opacity:1,x:c.x,y:c.y,width:d.width,height:d.height,caretX:u.x,caretY:u.y}}this._tooltipItems=a,this.$context=void 0,i&&this._resolveAnimations().update(this,i),e&&r.external&&r.external.call(this,{chart:this.chart,tooltip:this,replay:n})}drawCaret(e,n,r,s){const i=this.getCaretPosition(e,r,s);n.lineTo(i.x1,i.y1),n.lineTo(i.x2,i.y2),n.lineTo(i.x3,i.y3)}getCaretPosition(e,n,r){const{xAlign:s,yAlign:i}=this,{caretSize:a,cornerRadius:u}=r,{topLeft:d,topRight:o,bottomLeft:l,bottomRight:c}=toTRBLCorners(u),{x:h,y:f}=e,{width:p,height:g}=n;let b,x,y,T,S,E;return i==="center"?(S=f+g/2,s==="left"?(b=h,x=b-a,T=S+a,E=S-a):(b=h+p,x=b+a,T=S-a,E=S+a),y=b):(s==="left"?x=h+Math.max(d,l)+a:s==="right"?x=h+p-Math.max(o,c)-a:x=this.caretX,i==="top"?(T=f,S=T-a,b=x-a,y=x+a):(T=f+g,S=T+a,b=x+a,y=x-a),E=T),{x1:b,x2:x,x3:y,y1:T,y2:S,y3:E}}drawTitle(e,n,r){const s=this.title,i=s.length;let a,u,d;if(i){const o=getRtlAdapter(r.rtl,this.x,this.width);for(e.x=getAlignedX(this,r.titleAlign,r),n.textAlign=o.textAlign(r.titleAlign),n.textBaseline="middle",a=toFont(r.titleFont),u=r.titleSpacing,n.fillStyle=r.titleColor,n.font=a.string,d=0;dy!==0)?(e.beginPath(),e.fillStyle=i.multiKeyBackground,addRoundedRectPath(e,{x:g,y:p,w:o,h:d,radius:x}),e.fill(),e.stroke(),e.fillStyle=a.backgroundColor,e.beginPath(),addRoundedRectPath(e,{x:b,y:p+1,w:o-2,h:d-2,radius:x}),e.fill()):(e.fillStyle=i.multiKeyBackground,e.fillRect(g,p,o,d),e.strokeRect(g,p,o,d),e.fillStyle=a.backgroundColor,e.fillRect(b,p+1,o-2,d-2))}e.fillStyle=this.labelTextColors[r]}drawBody(e,n,r){const{body:s}=this,{bodySpacing:i,bodyAlign:a,displayColors:u,boxHeight:d,boxWidth:o,boxPadding:l}=r,c=toFont(r.bodyFont);let h=c.lineHeight,f=0;const p=getRtlAdapter(r.rtl,this.x,this.width),g=function(F){n.fillText(F,p.x(e.x+f),e.y+h/2),e.y+=h+i},b=p.textAlign(a);let x,y,T,S,E,N,B;for(n.textAlign=a,n.textBaseline="middle",n.font=c.string,e.x=getAlignedX(this,b,r),n.fillStyle=r.bodyColor,each(this.beforeBody,g),f=u&&b!=="right"?a==="center"?o/2+l:o+2+l:0,S=0,N=s.length;S0&&n.stroke()}_updateAnimationTarget(e){const n=this.chart,r=this.$animations,s=r&&r.x,i=r&&r.y;if(s||i){const a=positioners[e.position].call(this,this._active,this._eventPosition);if(!a)return;const u=this._size=getTooltipSize(this,e),d=Object.assign({},a,this._size),o=determineAlignment(n,e,d),l=getBackgroundPoint(e,d,o,n);(s._to!==l.x||i._to!==l.y)&&(this.xAlign=o.xAlign,this.yAlign=o.yAlign,this.width=u.width,this.height=u.height,this.caretX=a.x,this.caretY=a.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(e){const n=this.options.setContext(this.getContext());let r=this.opacity;if(!r)return;this._updateAnimationTarget(n);const s={width:this.width,height:this.height},i={x:this.x,y:this.y};r=Math.abs(r)<.001?0:r;const a=toPadding(n.padding),u=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;n.enabled&&u&&(e.save(),e.globalAlpha=r,this.drawBackground(i,e,s,n),overrideTextDirection(e,n.textDirection),i.y+=a.top,this.drawTitle(i,e,n),this.drawBody(i,e,n),this.drawFooter(i,e,n),restoreTextDirection(e,n.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,n){const r=this._active,s=e.map(({datasetIndex:u,index:d})=>{const o=this.chart.getDatasetMeta(u);if(!o)throw new Error("Cannot find a dataset at index "+u);return{datasetIndex:u,element:o.data[d],index:d}}),i=!_elementsEqual(r,s),a=this._positionChanged(s,n);(i||a)&&(this._active=s,this._eventPosition=n,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,n,r=!0){if(n&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,i=this._active||[],a=this._getActiveElements(e,i,n,r),u=this._positionChanged(a,e),d=n||!_elementsEqual(a,i)||u;return d&&(this._active=a,(s.enabled||s.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,n))),d}_getActiveElements(e,n,r,s){const i=this.options;if(e.type==="mouseout")return[];if(!s)return n.filter(u=>this.chart.data.datasets[u.datasetIndex]&&this.chart.getDatasetMeta(u.datasetIndex).controller.getParsed(u.index)!==void 0);const a=this.chart.getElementsAtEventForMode(e,i.mode,i,r);return i.reverse&&a.reverse(),a}_positionChanged(e,n){const{caretX:r,caretY:s,options:i}=this,a=positioners[i.position].call(this,e,n);return a!==!1&&(r!==a.x||s!==a.y)}}var plugin_tooltip={id:"tooltip",_element:Tooltip,positioners,afterInit(t,e,n){n&&(t.tooltip=new Tooltip({chart:t,options:n}))},beforeUpdate(t,e,n){t.tooltip&&t.tooltip.initialize(n)},reset(t,e,n){t.tooltip&&t.tooltip.initialize(n)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const n={tooltip:e};if(t.notifyPlugins("beforeTooltipDraw",{...n,cancelable:!0})===!1)return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",n)}},afterEvent(t,e){if(t.tooltip){const n=e.replay;t.tooltip.handleEvent(e.event,n,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:defaultCallbacks},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>t!=="filter"&&t!=="itemSort"&&t!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]},plugins=Object.freeze({__proto__:null,Colors:plugin_colors,Decimation:plugin_decimation,Filler:index,Legend:plugin_legend,SubTitle:plugin_subtitle,Title:plugin_title,Tooltip:plugin_tooltip});const addIfString=(t,e,n,r)=>(typeof e=="string"?(n=t.push(e)-1,r.unshift({index:n,label:e})):isNaN(e)&&(n=null),n);function findOrAddLabel(t,e,n,r){const s=t.indexOf(e);if(s===-1)return addIfString(t,e,n,r);const i=t.lastIndexOf(e);return s!==i?n:s}const validIndex=(t,e)=>t===null?null:_limitValue(Math.round(t),0,e);function _getLabelForValue(t){const e=this.getLabels();return t>=0&&tn.length-1?null:this.getPixelForValue(n[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}}function generateTicks$1(t,e){const n=[],{bounds:s,step:i,min:a,max:u,precision:d,count:o,maxTicks:l,maxDigits:c,includeBounds:h}=t,f=i||1,p=l-1,{min:g,max:b}=e,x=!isNullOrUndef(a),y=!isNullOrUndef(u),T=!isNullOrUndef(o),S=(b-g)/(c+1);let E=niceNum((b-g)/p/f)*f,N,B,F,k;if(E<1e-14&&!x&&!y)return[{value:g},{value:b}];k=Math.ceil(b/E)-Math.floor(g/E),k>p&&(E=niceNum(k*E/p/f)*f),isNullOrUndef(d)||(N=Math.pow(10,d),E=Math.ceil(E*N)/N),s==="ticks"?(B=Math.floor(g/E)*E,F=Math.ceil(b/E)*E):(B=g,F=b),x&&y&&i&&almostWhole((u-a)/i,E/1e3)?(k=Math.round(Math.min((u-a)/E,l)),E=(u-a)/k,B=a,F=u):T?(B=x?a:B,F=y?u:F,k=o-1,E=(F-B)/k):(k=(F-B)/E,almostEquals(k,Math.round(k),E/1e3)?k=Math.round(k):k=Math.ceil(k));const G=Math.max(_decimalPlaces(E),_decimalPlaces(B));N=Math.pow(10,isNullOrUndef(d)?G:d),B=Math.round(B*N)/N,F=Math.round(F*N)/N;let re=0;for(x&&(h&&B!==a?(n.push({value:a}),Bu)break;n.push({value:ie})}return y&&h&&F!==u?n.length&&almostEquals(n[n.length-1].value,u,relativeLabelSize(u,S,t))?n[n.length-1].value=u:n.push({value:u}):(!y||F===u)&&n.push({value:F}),n}function relativeLabelSize(t,e,{horizontal:n,minRotation:r}){const s=toRadians(r),i=(n?Math.sin(s):Math.cos(s))||.001,a=.75*e*(""+t).length;return Math.min(e/i,a)}class LinearScaleBase extends Scale{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,n){return isNullOrUndef(e)||(typeof e=="number"||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){const{beginAtZero:e}=this.options,{minDefined:n,maxDefined:r}=this.getUserBounds();let{min:s,max:i}=this;const a=d=>s=n?s:d,u=d=>i=r?i:d;if(e){const d=sign(s),o=sign(i);d<0&&o<0?u(0):d>0&&o>0&&a(0)}if(s===i){let d=i===0?1:Math.abs(i*.05);u(i+d),e||a(s-d)}this.min=s,this.max=i}getTickLimit(){const e=this.options.ticks;let{maxTicksLimit:n,stepSize:r}=e,s;return r?(s=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,s>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${s} ticks. Limiting to 1000.`),s=1e3)):(s=this.computeTickLimit(),n=n||11),n&&(s=Math.min(n,s)),s}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const e=this.options,n=e.ticks;let r=this.getTickLimit();r=Math.max(2,r);const s={maxTicks:r,bounds:e.bounds,min:e.min,max:e.max,precision:n.precision,step:n.stepSize,count:n.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:n.minRotation||0,includeBounds:n.includeBounds!==!1},i=this._range||this,a=generateTicks$1(s,i);return e.bounds==="ticks"&&_setMinAndMaxByKey(a,this,"value"),e.reverse?(a.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),a}configure(){const e=this.ticks;let n=this.min,r=this.max;if(super.configure(),this.options.offset&&e.length){const s=(r-n)/Math.max(e.length-1,1)/2;n-=s,r+=s}this._startValue=n,this._endValue=r,this._valueRange=r-n}getLabelForValue(e){return formatNumber(e,this.chart.options.locale,this.options.ticks.format)}}class LinearScale extends LinearScaleBase{static id="linear";static defaults={ticks:{callback:Ticks.formatters.numeric}};determineDataLimits(){const{min:e,max:n}=this.getMinMax(!0);this.min=isNumberFinite(e)?e:0,this.max=isNumberFinite(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const e=this.isHorizontal(),n=e?this.width:this.height,r=toRadians(this.options.ticks.minRotation),s=(e?Math.sin(r):Math.cos(r))||.001,i=this._resolveTickFontOptions(0);return Math.ceil(n/Math.min(40,i.lineHeight/s))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}}const log10Floor=t=>Math.floor(log10(t)),changeExponent=(t,e)=>Math.pow(10,log10Floor(t)+e);function isMajor(t){return t/Math.pow(10,log10Floor(t))===1}function steps(t,e,n){const r=Math.pow(10,n),s=Math.floor(t/r);return Math.ceil(e/r)-s}function startExp(t,e){const n=e-t;let r=log10Floor(n);for(;steps(t,e,r)>10;)r++;for(;steps(t,e,r)<10;)r--;return Math.min(r,log10Floor(t))}function generateTicks(t,{min:e,max:n}){e=finiteOrDefault(t.min,e);const r=[],s=log10Floor(e);let i=startExp(e,n),a=i<0?Math.pow(10,Math.abs(i)):1;const u=Math.pow(10,i),d=s>i?Math.pow(10,s):0,o=Math.round((e-d)*a)/a,l=Math.floor((e-d)/u/10)*u*10;let c=Math.floor((o-l)/Math.pow(10,i)),h=finiteOrDefault(t.min,Math.round((d+l+c*Math.pow(10,i))*a)/a);for(;h=10?c=c<15?15:20:c++,c>=20&&(i++,c=2,a=i>=0?1:a),h=Math.round((d+l+c*Math.pow(10,i))*a)/a;const f=finiteOrDefault(t.max,h);return r.push({value:f,major:isMajor(f),significand:c}),r}class LogarithmicScale extends Scale{static id="logarithmic";static defaults={ticks:{callback:Ticks.formatters.logarithmic,major:{enabled:!0}}};constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(e,n){const r=LinearScaleBase.prototype.parse.apply(this,[e,n]);if(r===0){this._zero=!0;return}return isNumberFinite(r)&&r>0?r:null}determineDataLimits(){const{min:e,max:n}=this.getMinMax(!0);this.min=isNumberFinite(e)?Math.max(0,e):null,this.max=isNumberFinite(n)?Math.max(0,n):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!isNumberFinite(this._userMin)&&(this.min=e===changeExponent(this.min,0)?changeExponent(this.min,-1):changeExponent(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:e,maxDefined:n}=this.getUserBounds();let r=this.min,s=this.max;const i=u=>r=e?r:u,a=u=>s=n?s:u;r===s&&(r<=0?(i(1),a(10)):(i(changeExponent(r,-1)),a(changeExponent(s,1)))),r<=0&&i(changeExponent(s,-1)),s<=0&&a(changeExponent(r,1)),this.min=r,this.max=s}buildTicks(){const e=this.options,n={min:this._userMin,max:this._userMax},r=generateTicks(n,this);return e.bounds==="ticks"&&_setMinAndMaxByKey(r,this,"value"),e.reverse?(r.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),r}getLabelForValue(e){return e===void 0?"0":formatNumber(e,this.chart.options.locale,this.options.ticks.format)}configure(){const e=this.min;super.configure(),this._startValue=log10(e),this._valueRange=log10(this.max)-log10(e)}getPixelForValue(e){return(e===void 0||e===0)&&(e=this.min),e===null||isNaN(e)?NaN:this.getPixelForDecimal(e===this.min?0:(log10(e)-this._startValue)/this._valueRange)}getValueForPixel(e){const n=this.getDecimalForPixel(e);return Math.pow(10,this._startValue+n*this._valueRange)}}function getTickBackdropHeight(t){const e=t.ticks;if(e.display&&t.display){const n=toPadding(e.backdropPadding);return valueOrDefault(e.font&&e.font.size,defaults.font.size)+n.height}return 0}function measureLabelSize(t,e,n){return n=isArray(n)?n:[n],{w:_longestText(t,e.string,n),h:n.length*e.lineHeight}}function determineLimits(t,e,n,r,s){return t===r||t===s?{start:e-n/2,end:e+n/2}:ts?{start:e-n,end:e}:{start:e,end:e+n}}function fitWithPointLabels(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},n=Object.assign({},e),r=[],s=[],i=t._pointLabels.length,a=t.options.pointLabels,u=a.centerPointLabels?PI/i:0;for(let d=0;de.r&&(u=(r.end-e.r)/i,t.r=Math.max(t.r,e.r+u)),s.starte.b&&(d=(s.end-e.b)/a,t.b=Math.max(t.b,e.b+d))}function createPointLabelItem(t,e,n){const r=t.drawingArea,{extra:s,additionalAngle:i,padding:a,size:u}=n,d=t.getPointPosition(e,r+s+a,i),o=Math.round(toDegrees(_normalizeAngle(d.angle+HALF_PI))),l=yForAngle(d.y,u.h,o),c=getTextAlignForAngle(o),h=leftForTextAlign(d.x,u.w,c);return{visible:!0,x:d.x,y:l,textAlign:c,left:h,top:l,right:h+u.w,bottom:l+u.h}}function isNotOverlapped(t,e){if(!e)return!0;const{left:n,top:r,right:s,bottom:i}=t;return!(_isPointInArea({x:n,y:r},e)||_isPointInArea({x:n,y:i},e)||_isPointInArea({x:s,y:r},e)||_isPointInArea({x:s,y:i},e))}function buildPointLabelItems(t,e,n){const r=[],s=t._pointLabels.length,i=t.options,{centerPointLabels:a,display:u}=i.pointLabels,d={extra:getTickBackdropHeight(i)/2,additionalAngle:a?PI/s:0};let o;for(let l=0;l270||n<90)&&(t-=e),t}function drawPointLabelBox(t,e,n){const{left:r,top:s,right:i,bottom:a}=n,{backdropColor:u}=e;if(!isNullOrUndef(u)){const d=toTRBLCorners(e.borderRadius),o=toPadding(e.backdropPadding);t.fillStyle=u;const l=r-o.left,c=s-o.top,h=i-r+o.width,f=a-s+o.height;Object.values(d).some(p=>p!==0)?(t.beginPath(),addRoundedRectPath(t,{x:l,y:c,w:h,h:f,radius:d}),t.fill()):t.fillRect(l,c,h,f)}}function drawPointLabels(t,e){const{ctx:n,options:{pointLabels:r}}=t;for(let s=e-1;s>=0;s--){const i=t._pointLabelItems[s];if(!i.visible)continue;const a=r.setContext(t.getPointLabelContext(s));drawPointLabelBox(n,a,i);const u=toFont(a.font),{x:d,y:o,textAlign:l}=i;renderText(n,t._pointLabels[s],d,o+u.lineHeight/2,u,{color:a.color,textAlign:l,textBaseline:"middle"})}}function pathRadiusLine(t,e,n,r){const{ctx:s}=t;if(n)s.arc(t.xCenter,t.yCenter,e,0,TAU);else{let i=t.getPointPosition(0,e);s.moveTo(i.x,i.y);for(let a=1;a{const s=callback(this.options.pointLabels.callback,[n,r],this);return s||s===0?s:""}).filter((n,r)=>this.chart.getDataVisibility(r))}fit(){const e=this.options;e.display&&e.pointLabels.display?fitWithPointLabels(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(e,n,r,s){this.xCenter+=Math.floor((e-n)/2),this.yCenter+=Math.floor((r-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(e,n,r,s))}getIndexAngle(e){const n=TAU/(this._pointLabels.length||1),r=this.options.startAngle||0;return _normalizeAngle(e*n+toRadians(r))}getDistanceFromCenterForValue(e){if(isNullOrUndef(e))return NaN;const n=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-e)*n:(e-this.min)*n}getValueForDistanceFromCenter(e){if(isNullOrUndef(e))return NaN;const n=e/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-n:this.min+n}getPointLabelContext(e){const n=this._pointLabels||[];if(e>=0&&e{if(c!==0||c===0&&this.min<0){d=this.getDistanceFromCenterForValue(l.value);const h=this.getContext(c),f=s.setContext(h),p=i.setContext(h);drawRadiusLine(this,f,d,a,p)}}),r.display){for(e.save(),u=a-1;u>=0;u--){const l=r.setContext(this.getPointLabelContext(u)),{color:c,lineWidth:h}=l;!h||!c||(e.lineWidth=h,e.strokeStyle=c,e.setLineDash(l.borderDash),e.lineDashOffset=l.borderDashOffset,d=this.getDistanceFromCenterForValue(n.ticks.reverse?this.min:this.max),o=this.getPointPosition(u,d),e.beginPath(),e.moveTo(this.xCenter,this.yCenter),e.lineTo(o.x,o.y),e.stroke())}e.restore()}}drawBorder(){}drawLabels(){const e=this.ctx,n=this.options,r=n.ticks;if(!r.display)return;const s=this.getIndexAngle(0);let i,a;e.save(),e.translate(this.xCenter,this.yCenter),e.rotate(s),e.textAlign="center",e.textBaseline="middle",this.ticks.forEach((u,d)=>{if(d===0&&this.min>=0&&!n.reverse)return;const o=r.setContext(this.getContext(d)),l=toFont(o.font);if(i=this.getDistanceFromCenterForValue(this.ticks[d].value),o.showLabelBackdrop){e.font=l.string,a=e.measureText(u.label).width,e.fillStyle=o.backdropColor;const c=toPadding(o.backdropPadding);e.fillRect(-a/2-c.left,-i-l.size/2-c.top,a+c.width,l.size+c.height)}renderText(e,u.label,0,-i,l,{color:o.color,strokeColor:o.textStrokeColor,strokeWidth:o.textStrokeWidth})}),e.restore()}drawTitle(){}}const INTERVALS={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},UNITS=Object.keys(INTERVALS);function sorter(t,e){return t-e}function parse(t,e){if(isNullOrUndef(e))return null;const n=t._adapter,{parser:r,round:s,isoWeekday:i}=t._parseOpts;let a=e;return typeof r=="function"&&(a=r(a)),isNumberFinite(a)||(a=typeof r=="string"?n.parse(a,r):n.parse(a)),a===null?null:(s&&(a=s==="week"&&(isNumber(i)||i===!0)?n.startOf(a,"isoWeek",i):n.startOf(a,s)),+a)}function determineUnitForAutoTicks(t,e,n,r){const s=UNITS.length;for(let i=UNITS.indexOf(t);i=UNITS.indexOf(n);i--){const a=UNITS[i];if(INTERVALS[a].common&&t._adapter.diff(s,r,a)>=e-1)return a}return UNITS[n?UNITS.indexOf(n):0]}function determineMajorUnit(t){for(let e=UNITS.indexOf(t)+1,n=UNITS.length;e=e?n[r]:n[s];t[i]=!0}}function setMajorTicks(t,e,n,r){const s=t._adapter,i=+s.startOf(e[0].value,r),a=e[e.length-1].value;let u,d;for(u=i;u<=a;u=+s.add(u,1,r))d=n[u],d>=0&&(e[d].major=!0);return e}function ticksFromTimestamps(t,e,n){const r=[],s={},i=e.length;let a,u;for(a=0;a+e.value))}initOffsets(e=[]){let n=0,r=0,s,i;this.options.offset&&e.length&&(s=this.getDecimalForValue(e[0]),e.length===1?n=1-s:n=(this.getDecimalForValue(e[1])-s)/2,i=this.getDecimalForValue(e[e.length-1]),e.length===1?r=i:r=(i-this.getDecimalForValue(e[e.length-2]))/2);const a=e.length<3?.5:.25;n=_limitValue(n,0,a),r=_limitValue(r,0,a),this._offsets={start:n,end:r,factor:1/(n+1+r)}}_generate(){const e=this._adapter,n=this.min,r=this.max,s=this.options,i=s.time,a=i.unit||determineUnitForAutoTicks(i.minUnit,n,r,this._getLabelCapacity(n)),u=valueOrDefault(s.ticks.stepSize,1),d=a==="week"?i.isoWeekday:!1,o=isNumber(d)||d===!0,l={};let c=n,h,f;if(o&&(c=+e.startOf(c,"isoWeek",d)),c=+e.startOf(c,o?"day":a),e.diff(r,n,a)>1e5*u)throw new Error(n+" and "+r+" are too far apart with stepSize of "+u+" "+a);const p=s.ticks.source==="data"&&this.getDataTimestamps();for(h=c,f=0;h+g)}getLabelForValue(e){const n=this._adapter,r=this.options.time;return r.tooltipFormat?n.format(e,r.tooltipFormat):n.format(e,r.displayFormats.datetime)}format(e,n){const s=this.options.time.displayFormats,i=this._unit,a=n||s[i];return this._adapter.format(e,a)}_tickFormatFunction(e,n,r,s){const i=this.options,a=i.ticks.callback;if(a)return callback(a,[e,n,r],this);const u=i.time.displayFormats,d=this._unit,o=this._majorUnit,l=d&&u[d],c=o&&u[o],h=r[n],f=o&&c&&h&&h.major;return this._adapter.format(e,s||(f?c:l))}generateTickLabels(e){let n,r,s;for(n=0,r=e.length;n0?u:1}getDataTimestamps(){let e=this._cache.data||[],n,r;if(e.length)return e;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(n=0,r=s.length;n=t[r].pos&&e<=t[s].pos&&({lo:r,hi:s}=_lookupByKey(t,"pos",e)),{pos:i,time:u}=t[r],{pos:a,time:d}=t[s]):(e>=t[r].time&&e<=t[s].time&&({lo:r,hi:s}=_lookupByKey(t,"time",e)),{time:i,pos:u}=t[r],{time:a,pos:d}=t[s]);const o=a-i;return o?u+(d-u)*(e-i)/o:u}class TimeSeriesScale extends TimeScale{static id="timeseries";static defaults=TimeScale.defaults;constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const e=this._getTimestampsForTable(),n=this._table=this.buildLookupTable(e);this._minPos=interpolate(n,this.min),this._tableRange=interpolate(n,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){const{min:n,max:r}=this,s=[],i=[];let a,u,d,o,l;for(a=0,u=e.length;a=n&&o<=r&&s.push(o);if(s.length<2)return[{time:n,pos:0},{time:r,pos:1}];for(a=0,u=s.length;as-i)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;const n=this.getDataTimestamps(),r=this.getLabelTimestamps();return n.length&&r.length?e=this.normalize(n.concat(r)):e=n.length?n:r,e=this._cache.all=e,e}getDecimalForValue(e){return(interpolate(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){const n=this._offsets,r=this.getDecimalForPixel(e)/n.factor-n.end;return interpolate(this._table,r*this._tableRange+this._minPos,!0)}}var scales=Object.freeze({__proto__:null,CategoryScale,LinearScale,LogarithmicScale,RadialLinearScale,TimeScale,TimeSeriesScale});const registerables=[controllers,elements,plugins,scales];Chart.register(...registerables);env.backends.onnx.wasm.proxy=!0;env.backends.onnx.wasm.wasmPaths=location.href;env.backends.onnx.wasm.numThreads=1;env.experimental.useWebGPU=!0;const ctx=document.getElementById("chart"),batchSizes=document.getElementById("batch-sizes"),xscale=document.getElementById("x-scale"),yscale=document.getElementById("y-scale"),sequenceLength=document.getElementById("sequence-length"),status=document.getElementById("status"),start=document.getElementById("start"),stop=document.getElementById("stop"),quantized=!1,NUM_WARMUP_STEPS=3,config={type:"line",data:{labels:[],datasets:[{label:"WASM",data:[],borderColor:"red",backgroundColor:"rgba(255, 0, 0, 0.5)"},{label:"WebGPU",data:[],borderColor:"blue",backgroundColor:"rgba(0, 0, 255, 0.5)"}]},options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{position:"top"}},scales:{x:{title:{display:!0,text:"Batch size"},min:1},y:{title:{display:!0,text:"Time (ms)"}}}}},toggleScale=(t,e,n)=>{t.options.scales[e].type=n?"logarithmic":"linear",t.update()};xscale.addEventListener("change",()=>toggleScale(chart,"x",xscale.checked));yscale.addEventListener("change",()=>toggleScale(chart,"y",yscale.checked));const chart=new Chart(ctx,config);let interrupted=!1;const model_id="Xenova/all-MiniLM-L6-v2";status.textContent="Loading model...";const model_CPU=await AutoModel.from_pretrained(model_id,{quantized,session_options:{executionProviders:["wasm"]}}),model_GPU=await AutoModel.from_pretrained(model_id,{quantized,session_options:{executionProviders:["webgpu"]}});status.textContent="Ready";start.addEventListener("click",async()=>{start.disabled=!0,stop.disabled=!1,interrupted=!1,chart.data.labels=[];for(let r=0;r{const s=ones([r,t]);return{input_ids:s,attention_mask:s}};for(let r=0;rparseInt(r));for(const r of n){if(interrupted)break;const s=e(r);let i;{const u=performance.now();await model_CPU(s),i=performance.now()-u}let a;{const u=performance.now();await model_GPU(s),a=performance.now()-u}chart.data.labels.push(r),chart.data.datasets[0].data.push(i),chart.data.datasets[1].data.push(a),chart.update()}status.textContent="Done!",start.disabled=!1});start.disabled=!1;stop.addEventListener("click",()=>{status.textContent="Stopping...",interrupted=!0,stop.disabled=!0}); +function __vite__mapDeps(indexes) { + if (!__vite__mapDeps.viteFileDeps) { + __vite__mapDeps.viteFileDeps = [] + } + return indexes.map((i) => __vite__mapDeps.viteFileDeps[i]) +} diff --git a/assets/ort.webgpu.min-BaaO-cT5.js b/assets/ort.webgpu.min-BaaO-cT5.js new file mode 100644 index 0000000000000000000000000000000000000000..df47632458bc5c5f1226a03a089ad91b99d7ac0b --- /dev/null +++ b/assets/ort.webgpu.min-BaaO-cT5.js @@ -0,0 +1,2151 @@ +/*! + * ONNX Runtime Web v1.17.1 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var ha=Object.defineProperty,Tp=Object.getOwnPropertyDescriptor,Ap=Object.getOwnPropertyNames,Op=Object.prototype.hasOwnProperty,H=(e,t)=>()=>(e&&(t=e(e=0)),t),Xt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Qt=(e,t)=>{for(var r in t)ha(e,r,{get:t[r],enumerable:!0})},kp=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ap(t))!Op.call(e,i)&&i!==r&&ha(e,i,{get:()=>t[i],enumerable:!(a=Tp(t,i))||a.enumerable});return e},Pt=e=>kp(ha({},"__esModule",{value:!0}),e),gr,It,Ir,fa,ma=H(()=>{gr=new Map,It=[],Ir=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let a=gr.get(e);if(a===void 0)gr.set(e,{backend:t,priority:r});else{if(a.priority>r)return;if(a.priority===r&&a.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let i=It.indexOf(e);i!==-1&&It.splice(i,1);for(let n=0;n{let t=e.length===0?It:e,r=[];for(let a of t){let i=gr.get(a);if(i){if(i.initialized)return i.backend;if(i.aborted)continue;let n=!!i.initPromise;try{return n||(i.initPromise=i.backend.init(a)),await i.initPromise,i.initialized=!0,i.backend}catch(s){n||r.push({name:a,err:s}),i.aborted=!0}finally{delete i.initPromise}}}throw new Error(`no available backend found. ERR: ${r.map(a=>`[${a.name}] ${a.err}`).join(", ")}`)}}),Rp=H(()=>{ma()}),Qo,zp=H(()=>{Qo="1.17.1"}),En,Yt,Jo=H(()=>{zp(),En="warning",Yt={wasm:{},webgl:{},webgpu:{},versions:{common:Qo},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}`);En=e}},get logLevel(){return En}},Object.defineProperty(Yt,"logLevel",{enumerable:!0})}),Oe,Bp=H(()=>{Jo(),Oe=Yt}),eu,tu,Mp=H(()=>{eu=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let a=r.getContext("2d");if(a!=null){let i,n;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);let s=t?.format!==void 0?t.format:"RGB",u=t?.norm,d,c;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?c=[0,0,0,0]:typeof u.bias=="number"?c=[u.bias,u.bias,u.bias,u.bias]:(c=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(c[3]=u.bias[3]));let m=n*i,l=0,f=m,y=m*2,$=-1;s==="RGBA"?(l=0,f=m,y=m*2,$=m*3):s==="RGB"?(l=0,f=m,y=m*2):s==="RBG"&&(l=0,y=m,f=m*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),a;if(r!=null){let i,n,s;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],s=e.dims[3]):(i=e.dims[3],n=e.dims[2],s=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t?.norm,c,m;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean=="number"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias=="number"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let l=n*i;if(t!==void 0&&(t.format!==void 0&&s===4&&t.format!=="RGBA"||s===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,y=0,$=1,x=2,C=3,b=0,E=l,T=l*2,S=-1;u==="RGBA"?(b=0,E=l,T=l*2,S=l*3):u==="RGB"?(b=0,E=l,T=l*2):u==="RBG"&&(b=0,T=l,E=l*2),a=r.createImageData(i,n);for(let B=0;B{ga(),Kr=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:a}=t,i=t.norm??{mean:255,bias:0},n,s;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*a,m=d==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),l=4,f=0,y=1,$=2,x=3,C=0,b=c,E=c*2,T=-1;u==="RGB"&&(l=3,f=0,y=1,$=2,x=-1),d==="RGBA"?T=c*3:d==="RBG"?(C=0,E=c,b=c*2):d==="BGR"&&(E=0,b=c,C=c*2);for(let S=0;S{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",s,u=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=m=>m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(r){let m=d();m.width=e.width,m.height=e.height;let l=c(m);if(l!=null){let f=e.height,y=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(f=t.resizedHeight,y=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=f,u.width=y}else u.tensorFormat="RGBA",u.height=f,u.width=y;l.drawImage(e,0,0),s=l.getImageData(0,0,y,f).data}else throw new Error("Can not access image data")}else if(a){let m,l;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,l=t.resizedWidth):(m=e.height,l=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=m,u.width=l,t!==void 0){let f=d();f.width=l,f.height=m;let y=c(f);if(y!=null)y.putImageData(e,0,0),s=y.getImageData(0,0,l,m).data;else throw new Error("Can not access image data")}else s=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=d();m.width=e.width,m.height=e.height;let l=c(m);if(l!=null){let f=e.height,y=e.width;return l.drawImage(e,0,0,y,f),s=l.getImageData(0,0,y,f).data,u.height=f,u.width=y,Kr(s,u)}else throw new Error("Can not access image data")}else{if(n)return new Promise((m,l)=>{let f=d(),y=c(f);if(!e||!y)return l();let $=new Image;$.crossOrigin="Anonymous",$.src=e,$.onload=()=>{f.width=$.width,f.height=$.height,y.drawImage($,0,0,f.width,f.height);let x=y.getImageData(0,0,f.width,f.height);u.height=f.height,u.width=f.width,m(Kr(x.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return Kr(s,u);throw new Error("Input data provided is not supported - aborted tensor creation")},nu=(e,t)=>{let{width:r,height:a,download:i,dispose:n}=t,s=[1,a,r,4];return new ut({location:"texture",type:"float32",texture:e,dims:s,download:i,dispose:n})},au=(e,t)=>{let{dataType:r,dims:a,download:i,dispose:n}=t;return new ut({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:a,download:i,dispose:n})},iu=(e,t,r)=>new ut({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Cr,rn,In,su,Pp=H(()=>{Cr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),rn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),In=!1,su=()=>{if(!In){In=!0;let e=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",t=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";e&&(Cr.set("int64",BigInt64Array),rn.set(BigInt64Array,"int64")),t&&(Cr.set("uint64",BigUint64Array),rn.set(BigUint64Array,"uint64"))}}}),ou,uu,Np=H(()=>{ga(),ou=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new ut(e.type,e.data,t);case"cpu-pinned":return new ut({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new ut({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new ut({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ut,ga=H(()=>{Mp(),Dp(),Pp(),Np(),ut=class{constructor(e,t,r){su();let a,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,a=e.type,i=e.dims,e.location){case"cpu-pinned":{let s=Cr.get(a);if(!s)throw new TypeError(`unsupported type "${a}" to create tensor from pinned buffer`);if(!(e.data instanceof s))throw new TypeError(`buffer should be of type ${s.name}`);this.cpuData=e.data;break}case"texture":{if(a!=="float32")throw new TypeError(`unsupported type "${a}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(a!=="float32"&&a!=="float16"&&a!=="int32"&&a!=="int64"&&a!=="uint32"&&a!=="bool")throw new TypeError(`unsupported type "${a}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,u;if(typeof e=="string")if(a=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");s=t}else{let d=Cr.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?s=d.from(t,BigInt):s=d.from(t)}else if(t instanceof d)s=t;else throw new TypeError(`A ${a} tensor's data must be type of ${d}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")a="string",s=e;else if(d==="boolean")a="bool",s=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{let d=rn.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);a=d,s=e}if(u===void 0)u=[s.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=s,this.dataLocation="cpu"}let n=ou(i);if(this.cpuData&&n!==this.cpuData.length)throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=a,this.dims=i,this.size=n}static async fromImage(e,t){return ru(e,t)}static fromTexture(e,t){return nu(e,t)}static fromGpuBuffer(e,t){return au(e,t)}static fromPinnedBuffer(e,t,r){return iu(e,t,r)}toDataURL(e){return eu(this,e)}toImageData(e){return tu(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;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}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 uu(this,e)}}}),Ke,ya=H(()=>{ga(),Ke=ut}),on,Cn,mt,gt,lu=H(()=>{Jo(),on=(e,t)=>{Yt.wasm.trace&&console.timeStamp(`${e}::ORT::${t}`)},Cn=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],a=!1;for(let i=0;i{Yt.wasm.trace&&Cn("BEGIN",e)},gt=e=>{Yt.wasm.trace&&Cn("END",e)}}),du,Wp=H(()=>{ma(),ya(),lu(),du=class pu{constructor(t){this.handler=t}async run(t,r,a){mt();let i={},n={};if(typeof t!="object"||t===null||t instanceof Ke||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Ke)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);i[c]=null}if(typeof a=="object"&&a!==null)n=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,m=Object.getOwnPropertyNames(r);for(let l of this.outputNames)if(m.indexOf(l)!==-1){let f=r[l];(f===null||f instanceof Ke)&&(c=!0,s=!1,i[l]=f)}if(c){if(typeof a=="object"&&a!==null)n=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else n=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(s)for(let c of this.outputNames)i[c]=null;let u=await this.handler.run(t,i,n),d={};for(let c in u)if(Object.hasOwnProperty.call(u,c)){let m=u[c];m instanceof Ke?d[c]=m:d[c]=new Ke(m.type,m.data,m.dims)}return gt(),d}async release(){return this.handler.dispose()}static async create(t,r,a,i){mt();let n,s={};if(typeof t=="string"){if(n=t,typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(n=t,typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let c=t,m=0,l=t.byteLength;if(typeof r=="object"&&r!==null)s=r;else if(typeof r=="number"){if(m=r,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.byteLength}).`);if(l=t.byteLength-m,typeof a=="number"){if(l=a,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||m+l>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.byteLength-m}].`);if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof a<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(c,m,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let u=(s.executionProviders||[]).map(c=>typeof c=="string"?c:c.name),d=await(await fa(u)).createInferenceSessionHandler(n,s);return gt(),new pu(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),cu,Up=H(()=>{Wp(),cu=du}),Vp=H(()=>{}),ei,hu,Hp=H(()=>{ma(),ya(),ei="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",hu=class fu{constructor(t,r,a){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=a}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(t,r){let a=t.evalModel||"",i=t.optimizerModel||"",n=r||{},s=(n.executionProviders||[]).map(d=>typeof d=="string"?d:d.name),u=await fa(s);if(u.createTrainingSessionHandler){let d=await u.createTrainingSessionHandler(t.checkpointState,t.trainModel,a,i,n);return new fu(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(ei)}typeNarrowingForRunStep(t,r,a,i,n){let s={},u={};if(typeof a!="object"||a===null||a instanceof Ke||Array.isArray(a))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof Ke)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let c of i){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,m=Object.getOwnPropertyNames(i);for(let l of r)if(m.indexOf(l)!==-1){let f=i[l];(f===null||f instanceof Ke)&&(c=!0,d=!1,s[l]=f)}if(c){if(typeof n=="object"&&n!==null)u=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else u=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of t)if(typeof a[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(d)for(let c of r)s[c]=null;return[s,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let a in t)if(Object.hasOwnProperty.call(t,a)){let i=t[a];i instanceof Ke?r[a]=i:r[a]=new Ke(i.type,i.data,i.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,a){let[i,n]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,a),s=await this.handler.runTrainStep(t,i,n);return this.convertHandlerReturnTypeToMapOfTensors(s)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,a){if(this.hasEvalModel){let[i,n]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,a),s=await this.handler.runEvalStep(t,i,n);return this.convertHandlerReturnTypeToMapOfTensors(s)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let a=await this.getParametersSize(r);if(t.length!==4*a)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(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),mu,Lp=H(()=>{Hp(),mu=hu}),gu={};Qt(gu,{InferenceSession:()=>cu,TRACE:()=>on,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>gt,Tensor:()=>Ke,TrainingSession:()=>mu,env:()=>Oe,registerBackend:()=>Ir});var lt=H(()=>{Rp(),Bp(),Up(),ya(),lu(),Vp(),Lp()}),wa={};Qt(wa,{createReadStream:()=>$u,readFile:()=>yu,readFileSync:()=>wu});var yu,wu,$u,vu=H(()=>{yu=void 0,wu=void 0,$u=void 0}),$a={};Qt($a,{join:()=>bu});var bu,_u=H(()=>{bu=void 0}),Gp=Xt((e,t)=>{var r=(()=>{var a=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(a=a||__filename),function(i={}){var n=i,s,u;n.ready=new Promise((p,g)=>{s=p,u=g}),n.mountExternalData=(p,g)=>{(n.Fa||(n.Fa=new Map)).set(p,g)},n.unmountExternalData=()=>{delete n.Fa},n.jsepInit=(p,g,v,I,z,V,q,ue)=>{n.ab=p,n.Qa=g,n.Sa=v,n.La=I,n.Ra=z,n.sa=V,n.Ta=q,n.Ua=ue,g=(X,J,se)=>(...$e)=>{let Ee=Ye,O=J?.();$e=X(...$e);let oe=J?.();return O!==oe&&(X=oe,se(O),J=se=null),Ye!=Ee?Pr():$e},v=X=>async(...J)=>{try{if(n.Ea)throw Error("Session already started");let se=n.Ea={Va:J[0],errors:[]},$e=await X(...J);if(n.Ea!==se)throw Error("Session mismatch");p.flush();let Ee=se.errors;if(0oe),0n._OrtRun,X=>n._OrtRun=X)),n._OrtRunWithBinding=v(g(n._OrtRunWithBinding,()=>n._OrtRunWithBinding,X=>n._OrtRunWithBinding=X)),n._OrtBindInput=g(n._OrtBindInput,()=>n._OrtBindInput,X=>n._OrtBindInput=X),n.jsepRegisterBuffer=(X,J,se,$e)=>p.registerBuffer(X,J,se,$e),n.jsepUnregisterBuffers=X=>{p.unregisterBuffers(X)},n.jsepGetBuffer=X=>p.getBuffer(X),n.jsepCreateDownloader=(X,J,se)=>p.createDownloader(X,J,se)};var d=Object.assign({},n),c="./this.program",m=(p,g)=>{throw g},l=typeof window=="object",f=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",$="",x,C,b;if(y){var E=(vu(),Pt(wa)),T=(_u(),Pt($a));$=f?T.dirname($)+"/":__dirname+"/",x=(p,g)=>(p=ye(p)?new URL(p):T.normalize(p),E.readFileSync(p,g?void 0:"utf8")),b=p=>(p=x(p,!0),p.buffer||(p=new Uint8Array(p)),p),C=(p,g,v,I=!0)=>{p=ye(p)?new URL(p):T.normalize(p),E.readFile(p,I?void 0:"utf8",(z,V)=>{z?v(z):g(I?V.buffer:V)})},!n.thisProgram&&1{throw process.exitCode=p,g},n.inspect=()=>"[Emscripten Module object]"}else(l||f)&&(f?$=self.location.href:typeof document<"u"&&document.currentScript&&($=document.currentScript.src),a&&($=a),$.indexOf("blob:")!==0?$=$.substr(0,$.replace(/[?#].*/,"").lastIndexOf("/")+1):$="",x=p=>{var g=new XMLHttpRequest;return g.open("GET",p,!1),g.send(null),g.responseText},f&&(b=p=>{var g=new XMLHttpRequest;return g.open("GET",p,!1),g.responseType="arraybuffer",g.send(null),new Uint8Array(g.response)}),C=(p,g,v)=>{var I=new XMLHttpRequest;I.open("GET",p,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?g(I.response):v()},I.onerror=v,I.send(null)});var S=console.log.bind(console),B=console.error.bind(console);Object.assign(n,d),d=null,typeof WebAssembly!="object"&&N("no native wasm support detected");var D,U=!1,P,G,K,R,j,me,Q;function Ce(){var p=D.buffer;n.HEAP8=G=new Int8Array(p),n.HEAP16=new Int16Array(p),n.HEAPU8=K=new Uint8Array(p),n.HEAPU16=new Uint16Array(p),n.HEAP32=R=new Int32Array(p),n.HEAPU32=j=new Uint32Array(p),n.HEAPF32=me=new Float32Array(p),n.HEAPF64=Q=new Float64Array(p)}var ve=[],we=[],ce=[],he=0,ge=null;function N(p){throw p="Aborted("+p+")",B(p),U=!0,P=1,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),u(p),p}var re=p=>p.startsWith("data:application/octet-stream;base64,"),ye=p=>p.startsWith("file://"),Me;if(Me="ort-wasm-simd.wasm",!re(Me)){var Re=Me;Me=n.locateFile?n.locateFile(Re,$):$+Re}function We(p){if(b)return b(p);throw"both async and sync fetching of the wasm failed"}function At(p){if(l||f){if(typeof fetch=="function"&&!ye(p))return fetch(p,{credentials:"same-origin"}).then(g=>{if(!g.ok)throw"failed to load wasm binary file at '"+p+"'";return g.arrayBuffer()}).catch(()=>We(p));if(C)return new Promise((g,v)=>{C(p,I=>g(new Uint8Array(I)),v)})}return Promise.resolve().then(()=>We(p))}function Ne(p,g,v){return At(p).then(I=>WebAssembly.instantiate(I,g)).then(I=>I).then(v,I=>{B(`failed to asynchronously prepare wasm: ${I}`),N(I)})}function Ue(p,g){var v=Me;return typeof WebAssembly.instantiateStreaming!="function"||re(v)||ye(v)||y||typeof fetch!="function"?Ne(v,p,g):fetch(v,{credentials:"same-origin"}).then(I=>WebAssembly.instantiateStreaming(I,p).then(g,function(z){return B(`wasm streaming compile failed: ${z}`),B("falling back to ArrayBuffer instantiation"),Ne(v,p,g)}))}var Qe,Je={931056:(p,g,v,I)=>{if(typeof n>"u"||!n.Fa)return 1;if(p=Pe(p>>>0),p.startsWith("./")&&(p=p.substring(2)),p=n.Fa.get(p),!p)return 2;if(g>>>=0,v>>>=0,g+v>p.byteLength)return 3;try{return K.set(p.subarray(g,g+v),I>>>0>>>0),0}catch{return 4}},931557:p=>n.Qa(p),931590:p=>n.Sa(p),931622:(p,g,v)=>{n.La(p,g,v,!0)},931661:(p,g,v)=>{n.La(p,g,v)},931694:p=>{n.sa("Abs",p,void 0)},931745:p=>{n.sa("Neg",p,void 0)},931796:p=>{n.sa("Floor",p,void 0)},931849:p=>{n.sa("Ceil",p,void 0)},931901:p=>{n.sa("Reciprocal",p,void 0)},931959:p=>{n.sa("Sqrt",p,void 0)},932011:p=>{n.sa("Exp",p,void 0)},932062:p=>{n.sa("Erf",p,void 0)},932113:p=>{n.sa("Sigmoid",p,void 0)},932168:p=>{n.sa("Log",p,void 0)},932219:p=>{n.sa("Sin",p,void 0)},932270:p=>{n.sa("Cos",p,void 0)},932321:p=>{n.sa("Tan",p,void 0)},932372:p=>{n.sa("Asin",p,void 0)},932424:p=>{n.sa("Acos",p,void 0)},932476:p=>{n.sa("Atan",p,void 0)},932528:p=>{n.sa("Sinh",p,void 0)},932580:p=>{n.sa("Cosh",p,void 0)},932632:p=>{n.sa("Asinh",p,void 0)},932685:p=>{n.sa("Acosh",p,void 0)},932738:p=>{n.sa("Atanh",p,void 0)},932791:p=>{n.sa("Tanh",p,void 0)},932843:p=>{n.sa("Not",p,void 0)},932894:(p,g,v)=>{n.sa("Clip",p,{min:g,max:v})},932963:p=>{n.sa("Clip",p,void 0)},933015:(p,g)=>{n.sa("Elu",p,{alpha:g})},933073:p=>{n.sa("Relu",p,void 0)},933125:(p,g)=>{n.sa("LeakyRelu",p,{alpha:g})},933189:(p,g)=>{n.sa("ThresholdedRelu",p,{alpha:g})},933259:(p,g)=>{n.sa("Cast",p,{to:g})},933317:p=>{n.sa("Add",p,void 0)},933368:p=>{n.sa("Sub",p,void 0)},933419:p=>{n.sa("Mul",p,void 0)},933470:p=>{n.sa("Div",p,void 0)},933521:p=>{n.sa("Pow",p,void 0)},933572:p=>{n.sa("Equal",p,void 0)},933625:p=>{n.sa("Greater",p,void 0)},933680:p=>{n.sa("GreaterOrEqual",p,void 0)},933742:p=>{n.sa("Less",p,void 0)},933794:p=>{n.sa("LessOrEqual",p,void 0)},933853:(p,g,v,I,z)=>{n.sa("ReduceMean",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},934012:(p,g,v,I,z)=>{n.sa("ReduceMax",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},934170:(p,g,v,I,z)=>{n.sa("ReduceMin",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},934328:(p,g,v,I,z)=>{n.sa("ReduceProd",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},934487:(p,g,v,I,z)=>{n.sa("ReduceSum",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},934645:(p,g,v,I,z)=>{n.sa("ReduceL1",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},934802:(p,g,v,I,z)=>{n.sa("ReduceL2",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},934959:(p,g,v,I,z)=>{n.sa("ReduceLogSum",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},935120:(p,g,v,I,z)=>{n.sa("ReduceSumSquare",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},935284:(p,g,v,I,z)=>{n.sa("ReduceLogSumExp",p,{keepDims:!!g,noopWithEmptyAxes:!!v,axes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},935448:p=>{n.sa("Where",p,void 0)},935501:(p,g,v)=>{n.sa("Transpose",p,{perm:g?Array.from(R.subarray(g>>>0,v>>>0)):[]})},935609:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O,oe)=>{n.sa("ConvTranspose",p,{format:X?"NHWC":"NCHW",autoPad:g,dilations:[v],group:I,kernel_shape:[z],pads:[V,q],strides:[ue],wIsConst:()=>!!G[J>>>0],outputPadding:se?Array.from(R.subarray(se>>>0,$e>>>0)):[],outputShape:Ee?Array.from(R.subarray(Ee>>>0,O>>>0)):[],activation:Pe(oe)})},936011:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O)=>{n.sa("ConvTranspose",p,{format:ue?"NHWC":"NCHW",autoPad:g,dilations:Array.from(R.subarray(v>>>0,(v>>>0)+2>>>0)),group:I,kernelShape:Array.from(R.subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(R.subarray(V>>>0,(V>>>0)+4>>>0)),strides:Array.from(R.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!G[X>>>0],outputPadding:J?Array.from(R.subarray(J>>>0,se>>>0)):[],outputShape:$e?Array.from(R.subarray($e>>>0,Ee>>>0)):[],activation:Pe(O)})},936576:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O,oe)=>{n.sa("ConvTranspose",p,{format:X?"NHWC":"NCHW",autoPad:g,dilations:[v],group:I,kernel_shape:[z],pads:[V,q],strides:[ue],wIsConst:()=>!!G[J>>>0],outputPadding:se?Array.from(R.subarray(se>>>0,$e>>>0)):[],outputShape:Ee?Array.from(R.subarray(Ee>>>0,O>>>0)):[],activation:Pe(oe)})},936978:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O)=>{n.sa("ConvTranspose",p,{format:ue?"NHWC":"NCHW",autoPad:g,dilations:Array.from(R.subarray(v>>>0,(v>>>0)+2>>>0)),group:I,kernelShape:Array.from(R.subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(R.subarray(V>>>0,(V>>>0)+4>>>0)),strides:Array.from(R.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!G[X>>>0],outputPadding:J?Array.from(R.subarray(J>>>0,se>>>0)):[],outputShape:$e?Array.from(R.subarray($e>>>0,Ee>>>0)):[],activation:Pe(O)})},937543:(p,g)=>{n.sa("GlobalAveragePool",p,{format:g?"NHWC":"NCHW"})},937634:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O,oe,_e)=>{n.sa("AveragePool",p,{format:_e?"NHWC":"NCHW",auto_pad:g,ceil_mode:v,count_include_pad:I,storage_order:z,dilations:[V,q],kernel_shape:[ue,X],pads:[J,se,$e,Ee],strides:[O,oe]})},937918:(p,g)=>{n.sa("GlobalAveragePool",p,{format:g?"NHWC":"NCHW"})},938009:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O,oe,_e)=>{n.sa("AveragePool",p,{format:_e?"NHWC":"NCHW",auto_pad:g,ceil_mode:v,count_include_pad:I,storage_order:z,dilations:[V,q],kernel_shape:[ue,X],pads:[J,se,$e,Ee],strides:[O,oe]})},938293:(p,g)=>{n.sa("GlobalMaxPool",p,{format:g?"NHWC":"NCHW"})},938380:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O,oe,_e)=>{n.sa("MaxPool",p,{format:_e?"NHWC":"NCHW",auto_pad:g,ceil_mode:v,count_include_pad:I,storage_order:z,dilations:[V,q],kernel_shape:[ue,X],pads:[J,se,$e,Ee],strides:[O,oe]})},938660:(p,g)=>{n.sa("GlobalMaxPool",p,{format:g?"NHWC":"NCHW"})},938747:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O,oe,_e)=>{n.sa("MaxPool",p,{format:_e?"NHWC":"NCHW",auto_pad:g,ceil_mode:v,count_include_pad:I,storage_order:z,dilations:[V,q],kernel_shape:[ue,X],pads:[J,se,$e,Ee],strides:[O,oe]})},939027:(p,g,v,I,z)=>{n.sa("Gemm",p,{alpha:g,beta:v,transA:I,transB:z})},939131:p=>{n.sa("MatMul",p,void 0)},939185:(p,g,v,I)=>{n.sa("ArgMax",p,{keepDims:!!g,selectLastIndex:!!v,axis:I})},939293:(p,g,v,I)=>{n.sa("ArgMin",p,{keepDims:!!g,selectLastIndex:!!v,axis:I})},939401:(p,g)=>{n.sa("Softmax",p,{axis:g})},939464:(p,g)=>{n.sa("Concat",p,{axis:g})},939524:(p,g,v,I,z)=>{n.sa("Split",p,{axis:g,numOutputs:v,splitSizes:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},939664:p=>{n.sa("Expand",p,void 0)},939718:(p,g)=>{n.sa("Gather",p,{axis:Number(g)})},939789:(p,g)=>{n.sa("GatherElements",p,{axis:Number(g)})},939868:(p,g,v,I,z,V,q,ue,X,J,se)=>{n.sa("Resize",p,{antialias:g,axes:v?Array.from(R.subarray(v>>>0,I>>>0)):[],coordinateTransformMode:Pe(z),cubicCoeffA:V,excludeOutside:q,extrapolationValue:ue,keepAspectRatioPolicy:Pe(X),mode:Pe(J),nearestMode:Pe(se)})},940214:(p,g,v,I,z,V,q)=>{n.sa("Slice",p,{starts:g?Array.from(R.subarray(g>>>0,v>>>0)):[],ends:I?Array.from(R.subarray(I>>>0,z>>>0)):[],axes:V?Array.from(R.subarray(V>>>0,q>>>0)):[]})},940430:p=>{n.sa("Tile",p,void 0)},940482:(p,g,v)=>{n.sa("LayerNormalization",p,{axis:Number(g),epsilon:Number(v)})},940589:(p,g,v)=>{n.sa("InstanceNormalization",p,{epsilon:g,format:v?"NHWC":"NCHW"})},940703:(p,g,v)=>{n.sa("InstanceNormalization",p,{epsilon:g,format:v?"NHWC":"NCHW"})},940817:p=>{n.sa("Range",p,void 0)},940870:(p,g)=>{n.sa("Einsum",p,{equation:Pe(g)})},940951:(p,g,v,I,z)=>{n.sa("Pad",p,{mode:g,value:v,pads:I?Array.from(R.subarray(I>>>0,z>>>0)):[]})},941078:(p,g,v,I,z,V)=>{n.sa("BatchNormalization",p,{epsilon:g,momentum:v,spatial:!!z,trainingMode:!!I,format:V?"NHWC":"NCHW"})},941247:(p,g,v,I,z,V)=>{n.sa("BatchNormalization",p,{epsilon:g,momentum:v,spatial:!!z,trainingMode:!!I,format:V?"NHWC":"NCHW"})},941416:(p,g,v)=>{n.sa("CumSum",p,{exclusive:Number(g),reverse:Number(v)})},941513:(p,g,v,I,z,V,q,ue,X)=>{n.sa("Attention",p,{numHeads:g,isUnidirectional:v,maskFilterValue:I,scale:z,doRotary:V,qkvHiddenSizes:q?Array.from(R.subarray(Number(ue)>>>0,Number(ue)+q>>>0)):[],pastPresentShareBuffer:!!X})},941785:p=>{n.sa("Gelu",p,void 0)},941837:(p,g,v,I,z,V)=>{n.sa("MultiHeadAttention",p,{numHeads:g,isUnidirectional:v,maskFilterValue:I,scale:z,doRotary:V})},941996:p=>{n.sa("BiasAdd",p,void 0)},942051:p=>{n.sa("BiasSplitGelu",p,void 0)},942112:(p,g)=>{n.sa("SkipLayerNormalization",p,{epsilon:g})},942193:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee)=>{n.sa("Conv",p,{format:X?"NHWC":"NCHW",auto_pad:g,dilations:[v],group:I,kernel_shape:[z],pads:V?Array.from(R.subarray(V>>>0,q>>>0)):[],strides:[ue],w_is_const:()=>!!G[J>>>0],activation:Pe(se),activation_params:$e?Array.from(me.subarray($e>>>0,Ee>>>0)):[]})},942563:(p,g,v,I,z,V,q,ue,X,J,se,$e,Ee,O,oe,_e)=>{n.sa("Conv",p,{format:$e?"NHWC":"NCHW",auto_pad:g,dilations:[v,I],group:z,kernel_shape:[V,q],pads:ue?Array.from(R.subarray(ue>>>0,X>>>0)):[],strides:[J,se],w_is_const:()=>!!G[Ee>>>0],activation:Pe(O),activation_params:oe?Array.from(me.subarray(oe>>>0,_e>>>0)):[]})},942954:p=>{n.Ta(p)},942988:(p,g)=>n.Ua(p,g,n.Ea.Va,n.Ea.errors)};function rt(p){this.name="ExitStatus",this.message=`Program terminated with exit(${p})`,this.status=p}function kr(p){this.Ja=p-24,this.Oa=function(g){j[this.Ja+4>>>2>>>0]=g},this.Na=function(g){j[this.Ja+8>>>2>>>0]=g},this.$a=function(g,v){this.Ma(),this.Oa(g),this.Na(v)},this.Ma=function(){j[this.Ja+16>>>2>>>0]=0}}var _t=0,er=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ot=(p,g,v)=>{g>>>=0;var I=g+v;for(v=g;p[v]&&!(v>=I);)++v;if(16z?I+=String.fromCharCode(z):(z-=65536,I+=String.fromCharCode(55296|z>>10,56320|z&1023))}}else I+=String.fromCharCode(z)}return I},Pe=(p,g)=>(p>>>=0)?Ot(K,p,g):"",Ut=p=>{for(var g=0,v=0;v=I?g++:2047>=I?g+=2:55296<=I&&57343>=I?(g+=4,++v):g+=3}return g},tr=(p,g,v,I)=>{if(v>>>=0,!(0=q){var ue=p.charCodeAt(++V);q=65536+((q&1023)<<10)|ue&1023}if(127>=q){if(v>=I)break;g[v++>>>0]=q}else{if(2047>=q){if(v+1>=I)break;g[v++>>>0]=192|q>>6}else{if(65535>=q){if(v+2>=I)break;g[v++>>>0]=224|q>>12}else{if(v+3>=I)break;g[v++>>>0]=240|q>>18,g[v++>>>0]=128|q>>12&63}g[v++>>>0]=128|q>>6&63}g[v++>>>0]=128|q&63}}return g[v>>>0]=0,v-z},wt=p=>p%4===0&&(p%100!==0||p%400===0),Rr=[0,31,60,91,121,152,182,213,244,274,305,335],$t=[0,31,59,90,120,151,181,212,243,273,304,334],Vt=p=>{var g=Ut(p)+1,v=qt(g);return v&&tr(p,K,v,g),v},kt=[],Ht=(p,g)=>{kt.length=0;for(var v;v=K[p++>>>0];){var I=v!=105;I&=v!=112,g+=I&&g%8?4:0,kt.push(v==112?j[g>>>2>>>0]:v==105?R[g>>>2>>>0]:Q[g>>>3>>>0]),g+=I?8:4}return kt},Lt={},dt=()=>{if(!Gt){var p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:c||"./this.program"},g;for(g in Lt)Lt[g]===void 0?delete p[g]:p[g]=Lt[g];var v=[];for(g in p)v.push(`${g}=${p[g]}`);Gt=v}return Gt},Gt,zr=[null,[],[]],Le=[31,29,31,30,31,30,31,31,30,31,30,31],Br=[31,28,31,30,31,30,31,31,30,31,30,31];function ke(p){var g=Array(Ut(p)+1);return tr(p,g,0,g.length),g}function rr(p,g,v,I){function z(O,oe,_e){for(O=typeof O=="number"?O.toString():O||"";O.lengthHr?-1:0ct-O.getDate())oe-=ct-O.getDate()+1,O.setDate(1),11>_e?O.setMonth(_e+1):(O.setMonth(0),O.setFullYear(O.getFullYear()+1));else{O.setDate(O.getDate()+oe);break}}return _e=new Date(O.getFullYear()+1,0,4),oe=ue(new Date(O.getFullYear(),0,4)),_e=ue(_e),0>=q(oe,O)?0>=q(_e,O)?O.getFullYear()+1:O.getFullYear():O.getFullYear()-1}p>>>=0,g>>>=0,v>>>=0,I>>>=0;var J=j[I+40>>>2>>>0];I={Ya:R[I>>>2>>>0],Xa:R[I+4>>>2>>>0],Ga:R[I+8>>>2>>>0],Ka:R[I+12>>>2>>>0],Ha:R[I+16>>>2>>>0],Da:R[I+20>>>2>>>0],xa:R[I+24>>>2>>>0],Ca:R[I+28>>>2>>>0],bb:R[I+32>>>2>>>0],Wa:R[I+36>>>2>>>0],Za:J?Pe(J):""},v=Pe(v),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 se in J)v=v.replace(new RegExp(se,"g"),J[se]);var $e="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ee="January February March April May June July August September October November December".split(" ");J={"%a":O=>$e[O.xa].substring(0,3),"%A":O=>$e[O.xa],"%b":O=>Ee[O.Ha].substring(0,3),"%B":O=>Ee[O.Ha],"%C":O=>V((O.Da+1900)/100|0,2),"%d":O=>V(O.Ka,2),"%e":O=>z(O.Ka,2," "),"%g":O=>X(O).toString().substring(2),"%G":O=>X(O),"%H":O=>V(O.Ga,2),"%I":O=>(O=O.Ga,O==0?O=12:12{for(var oe=0,_e=0;_e<=O.Ha-1;oe+=(wt(O.Da+1900)?Le:Br)[_e++]);return V(O.Ka+oe,3)},"%m":O=>V(O.Ha+1,2),"%M":O=>V(O.Xa,2),"%n":()=>` +`,"%p":O=>0<=O.Ga&&12>O.Ga?"AM":"PM","%S":O=>V(O.Ya,2),"%t":()=>" ","%u":O=>O.xa||7,"%U":O=>V(Math.floor((O.Ca+7-O.xa)/7),2),"%V":O=>{var oe=Math.floor((O.Ca+7-(O.xa+6)%7)/7);if(2>=(O.xa+371-O.Ca-2)%7&&oe++,oe)oe==53&&(_e=(O.xa+371-O.Ca)%7,_e==4||_e==3&&wt(O.Da)||(oe=1));else{oe=52;var _e=(O.xa+7-O.Ca-1)%7;(_e==4||_e==5&&wt(O.Da%400-1))&&oe++}return V(oe,2)},"%w":O=>O.xa,"%W":O=>V(Math.floor((O.Ca+7-(O.xa+6)%7)/7),2),"%y":O=>(O.Da+1900).toString().substring(2),"%Y":O=>O.Da+1900,"%z":O=>{O=O.Wa;var oe=0<=O;return O=Math.abs(O)/60,(oe?"+":"-")+("0000"+(O/60*100+O%60)).slice(-4)},"%Z":O=>O.Za,"%%":()=>"%"},v=v.replace(/%%/g,"\0\0");for(se in J)v.includes(se)&&(v=v.replace(new RegExp(se,"g"),J[se](I)));return v=v.replace(/\0\0/g,"%"),se=ke(v),se.length>g?0:(G.set(se,p>>>0),se.length-1)}var xt=p=>{try{p()}catch(g){N(g)}};function nr(){var p=ne,g={};for(let[v,I]of Object.entries(p))g[v]=typeof I=="function"?function(){ie.push(v);try{return I.apply(null,arguments)}finally{U||(ie.pop(),Ye&&pt===1&&ie.length===0&&(pt=0,xt(hr),typeof Fibers<"u"&&Fibers.cb()))}}:I;return g}var pt=0,Ye=null,Mr=0,ie=[],Rt={},ar={},wn=0,Ft=null,Dr=[];function Pr(){return new Promise((p,g)=>{Ft={resolve:p,reject:g}})}function Nr(){var p=qt(65548),g=p+12;j[p>>>2>>>0]=g,j[p+4>>>2>>>0]=g+65536,g=ie[0];var v=Rt[g];return v===void 0&&(v=wn++,Rt[g]=v,ar[v]=g),R[p+8>>>2>>>0]=v,p}function Wr(p){if(!U){if(pt===0){var g=!1,v=!1;p((I=0)=>{if(!U&&(Mr=I,g=!0,v)){pt=2,xt(()=>fr(Ye)),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.resume(),I=!1;try{var z=(0,ne[ar[R[Ye+8>>>2>>>0]]])()}catch(ue){z=ue,I=!0}var V=!1;if(!Ye){var q=Ft;q&&(Ft=null,(I?q.reject:q.resolve)(z),V=!0)}if(I&&!V)throw z}}),v=!0,g||(pt=1,Ye=Nr(),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.pause(),xt(()=>cr(Ye)))}else pt===2?(pt=0,xt(mr),or(Ye),Ye=null,Dr.forEach(I=>{if(!U)try{I();try{P=P=I=P,n.onExit?.(I),U=!0,m(I,new rt(I))}catch(z){z instanceof rt||z=="unwind"||m(1,z)}}catch(z){z instanceof rt||z=="unwind"||m(1,z)}})):N(`invalid state: ${pt}`);return Mr}}function ir(p){return Wr(g=>{p().then(g)})}var Ur={n:function(p,g,v){return ir(async()=>{await n.Ra(p,g,v)})},a:function(p,g,v){throw p>>>=0,new kr(p).$a(g>>>0,v>>>0),_t=p,_t},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(p,g,v){p=g+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*g:NaN,v>>>=0,p=new Date(1e3*p),R[v>>>2>>>0]=p.getUTCSeconds(),R[v+4>>>2>>>0]=p.getUTCMinutes(),R[v+8>>>2>>>0]=p.getUTCHours(),R[v+12>>>2>>>0]=p.getUTCDate(),R[v+16>>>2>>>0]=p.getUTCMonth(),R[v+20>>>2>>>0]=p.getUTCFullYear()-1900,R[v+24>>>2>>>0]=p.getUTCDay(),R[v+28>>>2>>>0]=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(p,g,v){p=g+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*g:NaN,v>>>=0,p=new Date(1e3*p),R[v>>>2>>>0]=p.getSeconds(),R[v+4>>>2>>>0]=p.getMinutes(),R[v+8>>>2>>>0]=p.getHours(),R[v+12>>>2>>>0]=p.getDate(),R[v+16>>>2>>>0]=p.getMonth(),R[v+20>>>2>>>0]=p.getFullYear()-1900,R[v+24>>>2>>>0]=p.getDay(),R[v+28>>>2>>>0]=(wt(p.getFullYear())?Rr:$t)[p.getMonth()]+p.getDate()-1|0,R[v+36>>>2>>>0]=-(60*p.getTimezoneOffset()),g=new Date(p.getFullYear(),6,1).getTimezoneOffset();var I=new Date(p.getFullYear(),0,1).getTimezoneOffset();R[v+32>>>2>>>0]=(g!=I&&p.getTimezoneOffset()==Math.min(I,g))|0},s:function(p){p>>>=0;var g=new Date(R[p+20>>>2>>>0]+1900,R[p+16>>>2>>>0],R[p+12>>>2>>>0],R[p+8>>>2>>>0],R[p+4>>>2>>>0],R[p>>>2>>>0],0),v=R[p+32>>>2>>>0],I=g.getTimezoneOffset(),z=new Date(g.getFullYear(),6,1).getTimezoneOffset(),V=new Date(g.getFullYear(),0,1).getTimezoneOffset(),q=Math.min(V,z);return 0>v?R[p+32>>>2>>>0]=+(z!=V&&q==I):0>>2>>>0]=g.getDay(),R[p+28>>>2>>>0]=(wt(g.getFullYear())?Rr:$t)[g.getMonth()]+g.getDate()-1|0,R[p>>>2>>>0]=g.getSeconds(),R[p+4>>>2>>>0]=g.getMinutes(),R[p+8>>>2>>>0]=g.getHours(),R[p+12>>>2>>>0]=g.getDate(),R[p+16>>>2>>>0]=g.getMonth(),R[p+20>>>2>>>0]=g.getYear(),p=g.getTime(),isNaN(p)?(R[sr()>>>2>>>0]=61,p=-1):p/=1e3,ur((Qe=p,1<=+Math.abs(Qe)?0>>0:~~+Math.ceil((Qe-+(~~Qe>>>0))/4294967296)>>>0:0)),p>>>0},o:function(){return-52},p:function(){},w:function(p,g,v){function I(X){return(X=X.toTimeString().match(/\(([A-Za-z ]+)\)$/))?X[1]:"GMT"}v>>>=0;var z=new Date().getFullYear(),V=new Date(z,0,1),q=new Date(z,6,1);z=V.getTimezoneOffset();var ue=q.getTimezoneOffset();j[p>>>0>>>2>>>0]=60*Math.max(z,ue),R[g>>>0>>>2>>>0]=+(z!=ue),p=I(V),g=I(q),p=Vt(p),g=Vt(g),ue>>2>>>0]=p,j[v+4>>>2>>>0]=g):(j[v>>>2>>>0]=g,j[v+4>>>2>>>0]=p)},e:()=>{N("")},b:function(p,g,v){return p>>>=0,g=Ht(g>>>0,v>>>0),Je[p].apply(null,g)},i:function(p,g,v){return p>>>=0,g=Ht(g>>>0,v>>>0),Je[p].apply(null,g)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(p,g,v){return g>>>=0,K.copyWithin(p>>>0>>>0,g>>>0,g+(v>>>0)>>>0)},u:function(p){p>>>=0;var g=K.length;if(4294901760=v;v*=2){var I=g*(1+.2/v);I=Math.min(I,p+100663296);var z=Math;I=Math.max(p,I);e:{z=(z.min.call(z,4294901760,I+(65536-I%65536)%65536)-D.buffer.byteLength+65535)/65536;try{D.grow(z),Ce();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1},E:function(p,g){p>>>=0,g>>>=0;var v=0;return dt().forEach((I,z)=>{var V=g+v;for(z=j[p+4*z>>>2>>>0]=V,V=0;V>>0>>>0]=I.charCodeAt(V);G[z>>>0>>>0]=0,v+=I.length+1}),0},F:function(p,g){p>>>=0,g>>>=0;var v=dt();j[p>>>2>>>0]=v.length;var I=0;return v.forEach(z=>I+=z.length+1),j[g>>>2>>>0]=I,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(p,g,v,I){g>>>=0,v>>>=0,I>>>=0;for(var z=0,V=0;V>>2>>>0],ue=j[g+4>>>2>>>0];g+=8;for(var X=0;X>>0],se=zr[p];J===0||J===10?((p===1?S:B)(Ot(se,0)),se.length=0):se.push(J)}z+=ue}return j[I>>>2>>>0]=z,0},v:rr,d:function(p,g,v,I){return rr(p>>>0,g>>>0,v>>>0,I>>>0)}},ne=function(){function p(v){return ne=v.exports,ne=nr(),ne=Vr(),D=ne.M,Ce(),we.unshift(ne.N),he--,he==0&&ge&&(v=ge,ge=null,v()),ne}var g={a:Ur};if(he++,n.instantiateWasm)try{return n.instantiateWasm(g,p)}catch(v){B(`Module.instantiateWasm callback failed with error: ${v}`),u(v)}return Ue(g,function(v){p(v.instance)}).catch(u),{}}();n._OrtInit=(p,g)=>(n._OrtInit=ne.O)(p,g),n._OrtGetLastError=(p,g)=>(n._OrtGetLastError=ne.P)(p,g),n._OrtCreateSessionOptions=(p,g,v,I,z,V,q,ue,X,J)=>(n._OrtCreateSessionOptions=ne.Q)(p,g,v,I,z,V,q,ue,X,J),n._OrtAppendExecutionProvider=(p,g)=>(n._OrtAppendExecutionProvider=ne.R)(p,g),n._OrtAddFreeDimensionOverride=(p,g,v)=>(n._OrtAddFreeDimensionOverride=ne.S)(p,g,v),n._OrtAddSessionConfigEntry=(p,g,v)=>(n._OrtAddSessionConfigEntry=ne.T)(p,g,v),n._OrtReleaseSessionOptions=p=>(n._OrtReleaseSessionOptions=ne.U)(p),n._OrtCreateSession=(p,g,v)=>(n._OrtCreateSession=ne.V)(p,g,v),n._OrtReleaseSession=p=>(n._OrtReleaseSession=ne.W)(p),n._OrtGetInputOutputCount=(p,g,v)=>(n._OrtGetInputOutputCount=ne.X)(p,g,v),n._OrtGetInputName=(p,g)=>(n._OrtGetInputName=ne.Y)(p,g),n._OrtGetOutputName=(p,g)=>(n._OrtGetOutputName=ne.Z)(p,g),n._OrtFree=p=>(n._OrtFree=ne._)(p),n._OrtCreateTensor=(p,g,v,I,z,V)=>(n._OrtCreateTensor=ne.$)(p,g,v,I,z,V),n._OrtGetTensorData=(p,g,v,I,z)=>(n._OrtGetTensorData=ne.aa)(p,g,v,I,z),n._OrtReleaseTensor=p=>(n._OrtReleaseTensor=ne.ba)(p),n._OrtCreateRunOptions=(p,g,v,I)=>(n._OrtCreateRunOptions=ne.ca)(p,g,v,I),n._OrtAddRunConfigEntry=(p,g,v)=>(n._OrtAddRunConfigEntry=ne.da)(p,g,v),n._OrtReleaseRunOptions=p=>(n._OrtReleaseRunOptions=ne.ea)(p),n._OrtCreateBinding=p=>(n._OrtCreateBinding=ne.fa)(p),n._OrtBindInput=(p,g,v)=>(n._OrtBindInput=ne.ga)(p,g,v),n._OrtBindOutput=(p,g,v,I)=>(n._OrtBindOutput=ne.ha)(p,g,v,I),n._OrtClearBoundOutputs=p=>(n._OrtClearBoundOutputs=ne.ia)(p),n._OrtReleaseBinding=p=>(n._OrtReleaseBinding=ne.ja)(p),n._OrtRunWithBinding=(p,g,v,I,z)=>(n._OrtRunWithBinding=ne.ka)(p,g,v,I,z),n._OrtRun=(p,g,v,I,z,V,q,ue)=>(n._OrtRun=ne.la)(p,g,v,I,z,V,q,ue),n._OrtEndProfiling=p=>(n._OrtEndProfiling=ne.ma)(p),n._JsepOutput=(p,g,v)=>(n._JsepOutput=ne.na)(p,g,v),n._JsepGetNodeName=p=>(n._JsepGetNodeName=ne.oa)(p);var sr=()=>(sr=ne.pa)(),qt=n._malloc=p=>(qt=n._malloc=ne.qa)(p),or=n._free=p=>(or=n._free=ne.ra)(p),ur=p=>(ur=ne.ta)(p),lr=()=>(lr=ne.ua)(),dr=p=>(dr=ne.va)(p),pr=p=>(pr=ne.wa)(p),cr=p=>(cr=ne.ya)(p),hr=()=>(hr=ne.za)(),fr=p=>(fr=ne.Aa)(p),mr=()=>(mr=ne.Ba)();n.___start_em_js=943100,n.___stop_em_js=943261;function Vr(){var p=ne;p=Object.assign({},p);var g=I=>()=>I()>>>0,v=I=>z=>I(z)>>>0;return p.pa=g(p.pa),p.qa=v(p.qa),p.ua=g(p.ua),p.wa=v(p.wa),p}n.stackAlloc=pr,n.stackSave=lr,n.stackRestore=dr,n.UTF8ToString=Pe,n.stringToUTF8=(p,g,v)=>tr(p,K,g,v),n.lengthBytesUTF8=Ut;var St;ge=function p(){St||zt(),St||(ge=p)};function zt(){if(!(0r)}),Fp=Xt(()=>{}),qp=Xt(()=>{}),xu={};Qt(xu,{cpus:()=>Su});var Su,jp=H(()=>{Su=void 0}),Kp=Xt((e,t)=>{var r=(()=>{var a=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(a=a||__filename),function(i={}){function n(){return ve.buffer!=ge.buffer&&We(),ge}function s(){return ve.buffer!=ge.buffer&&We(),N}function u(){return ve.buffer!=ge.buffer&&We(),re}function d(){return ve.buffer!=ge.buffer&&We(),ye}function c(){return ve.buffer!=ge.buffer&&We(),Me}function m(){return ve.buffer!=ge.buffer&&We(),Re}var l=i,f,y;l.ready=new Promise((o,h)=>{f=o,y=h}),l.mountExternalData=(o,h)=>{(l.cb||(l.cb=new Map)).set(o,h)},l.unmountExternalData=()=>{delete l.cb},l.jsepInit=(o,h,w,_,A,M,W,ae)=>{l.Mb=o,l.wb=h,l.yb=w,l.kb=_,l.xb=A,l.Ea=M,l.zb=W,l.Ab=ae,h=(ee,te,le)=>(...Se)=>{let Ae=ht,k=te?.();Se=ee(...Se);let de=te?.();return k!==de&&(ee=de,le(k),te=le=null),ht!=Ae?vp():Se},w=ee=>async(...te)=>{try{if(l.bb)throw Error("Session already started");let le=l.bb={Cb:te[0],errors:[]},Se=await ee(...te);if(l.bb!==le)throw Error("Session mismatch");o.flush();let Ae=le.errors;if(0de),0l._OrtRun,ee=>l._OrtRun=ee)),l._OrtRunWithBinding=w(h(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,ee=>l._OrtRunWithBinding=ee)),l._OrtBindInput=h(l._OrtBindInput,()=>l._OrtBindInput,ee=>l._OrtBindInput=ee),l.jsepRegisterBuffer=(ee,te,le,Se)=>o.registerBuffer(ee,te,le,Se),l.jsepUnregisterBuffers=ee=>{o.unregisterBuffers(ee)},l.jsepGetBuffer=ee=>o.getBuffer(ee),l.jsepCreateDownloader=(ee,te,le)=>o.createDownloader(ee,te,le)};var $=Object.assign({},l),x="./this.program",C=(o,h)=>{throw h},b=typeof window=="object",E=typeof importScripts=="function",T=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",S=l.ENVIRONMENT_IS_PTHREAD||!1,B="";function D(o){return l.locateFile?l.locateFile(o,B):B+o}var U,P,G;if(T){var K=(vu(),Pt(wa)),R=(_u(),Pt($a));B=E?R.dirname(B)+"/":__dirname+"/",U=(h,w)=>(h=Ot(h)?new URL(h):R.normalize(h),K.readFileSync(h,w?void 0:"utf8")),G=h=>(h=U(h,!0),h.buffer||(h=new Uint8Array(h)),h),P=(h,w,_,A=!0)=>{h=Ot(h)?new URL(h):R.normalize(h),K.readFile(h,A?void 0:"utf8",(M,W)=>{M?_(M):w(A?W.buffer:W)})},!l.thisProgram&&1{throw process.exitCode=h,w},l.inspect=()=>"[Emscripten Module object]";let o;try{o=Fp()}catch(h){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),h}global.Worker=o.Worker}else(b||E)&&(E?B=self.location.href:typeof document<"u"&&document.currentScript&&(B=document.currentScript.src),typeof a<"u"&&a&&(B=a),B.indexOf("blob:")!==0?B=B.substr(0,B.replace(/[?#].*/,"").lastIndexOf("/")+1):B="",T||(U=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.send(null),h.responseText},E&&(G=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),P=(o,h,w)=>{var _=new XMLHttpRequest;_.open("GET",o,!0),_.responseType="arraybuffer",_.onload=()=>{_.status==200||_.status==0&&_.response?h(_.response):w()},_.onerror=w,_.send(null)}));T&&typeof performance>"u"&&(global.performance=qp().performance);var j=console.log.bind(console),me=console.error.bind(console);T&&(j=(...o)=>K.writeSync(1,o.join(" ")+` +`),me=(...o)=>K.writeSync(2,o.join(" ")+` +`));var Q=j,Ce=me;Object.assign(l,$),$=null,typeof WebAssembly!="object"&&_t("no native wasm support detected");var ve,we,ce=!1,he,ge,N,re,ye,Me,Re;function We(){var o=ve.buffer;l.HEAP8=ge=new Int8Array(o),l.HEAP16=new Int16Array(o),l.HEAPU8=N=new Uint8Array(o),l.HEAPU16=new Uint16Array(o),l.HEAP32=re=new Int32Array(o),l.HEAPU32=ye=new Uint32Array(o),l.HEAPF32=Me=new Float32Array(o),l.HEAPF64=Re=new Float64Array(o)}var At=16777216;if(S)ve=l.wasmMemory;else if(l.wasmMemory)ve=l.wasmMemory;else if(ve=new WebAssembly.Memory({initial:At/65536,maximum:65536,shared:!0}),!(ve.buffer instanceof SharedArrayBuffer))throw Ce("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"),T&&Ce("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");We(),At=ve.buffer.byteLength;var Ne=[],Ue=[],Qe=[],Je=0,rt=null;function kr(){if(Je--,Je==0&&rt){var o=rt;rt=null,o()}}function _t(o){throw o="Aborted("+o+")",Ce(o),ce=!0,he=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),y(o),o}var er=o=>o.startsWith("data:application/octet-stream;base64,"),Ot=o=>o.startsWith("file://"),Pe;Pe="ort-wasm-simd-threaded.wasm",er(Pe)||(Pe=D(Pe));function Ut(o){if(G)return G(o);throw"both async and sync fetching of the wasm failed"}function tr(o){if(b||E){if(typeof fetch=="function"&&!Ot(o))return fetch(o,{credentials:"same-origin"}).then(h=>{if(!h.ok)throw"failed to load wasm binary file at '"+o+"'";return h.arrayBuffer()}).catch(()=>Ut(o));if(P)return new Promise((h,w)=>{P(o,_=>h(new Uint8Array(_)),w)})}return Promise.resolve().then(()=>Ut(o))}function wt(o,h,w){return tr(o).then(_=>WebAssembly.instantiate(_,h)).then(_=>_).then(w,_=>{Ce(`failed to asynchronously prepare wasm: ${_}`),_t(_)})}function Rr(o,h){var w=Pe;return typeof WebAssembly.instantiateStreaming!="function"||er(w)||Ot(w)||T||typeof fetch!="function"?wt(w,o,h):fetch(w,{credentials:"same-origin"}).then(_=>WebAssembly.instantiateStreaming(_,o).then(h,function(A){return Ce(`wasm streaming compile failed: ${A}`),Ce("falling back to ArrayBuffer instantiation"),wt(w,o,h)}))}var $t,Vt={932428:(o,h,w,_)=>{if(typeof l>"u"||!l.cb)return 1;if(o=Le(o>>>0),o.startsWith("./")&&(o=o.substring(2)),o=l.cb.get(o),!o)return 2;if(h>>>=0,w>>>=0,_>>>=0,h+w>o.byteLength)return 3;try{return s().set(o.subarray(h,h+w),_>>>0),0}catch{return 4}},932929:o=>l.wb(o),932962:o=>l.yb(o),932994:(o,h,w)=>{l.kb(o,h,w,!0)},933033:(o,h,w)=>{l.kb(o,h,w)},933066:o=>{l.Ea("Abs",o,void 0)},933117:o=>{l.Ea("Neg",o,void 0)},933168:o=>{l.Ea("Floor",o,void 0)},933221:o=>{l.Ea("Ceil",o,void 0)},933273:o=>{l.Ea("Reciprocal",o,void 0)},933331:o=>{l.Ea("Sqrt",o,void 0)},933383:o=>{l.Ea("Exp",o,void 0)},933434:o=>{l.Ea("Erf",o,void 0)},933485:o=>{l.Ea("Sigmoid",o,void 0)},933540:o=>{l.Ea("Log",o,void 0)},933591:o=>{l.Ea("Sin",o,void 0)},933642:o=>{l.Ea("Cos",o,void 0)},933693:o=>{l.Ea("Tan",o,void 0)},933744:o=>{l.Ea("Asin",o,void 0)},933796:o=>{l.Ea("Acos",o,void 0)},933848:o=>{l.Ea("Atan",o,void 0)},933900:o=>{l.Ea("Sinh",o,void 0)},933952:o=>{l.Ea("Cosh",o,void 0)},934004:o=>{l.Ea("Asinh",o,void 0)},934057:o=>{l.Ea("Acosh",o,void 0)},934110:o=>{l.Ea("Atanh",o,void 0)},934163:o=>{l.Ea("Tanh",o,void 0)},934215:o=>{l.Ea("Not",o,void 0)},934266:(o,h,w)=>{l.Ea("Clip",o,{min:h,max:w})},934335:o=>{l.Ea("Clip",o,void 0)},934387:(o,h)=>{l.Ea("Elu",o,{alpha:h})},934445:o=>{l.Ea("Relu",o,void 0)},934497:(o,h)=>{l.Ea("LeakyRelu",o,{alpha:h})},934561:(o,h)=>{l.Ea("ThresholdedRelu",o,{alpha:h})},934631:(o,h)=>{l.Ea("Cast",o,{to:h})},934689:o=>{l.Ea("Add",o,void 0)},934740:o=>{l.Ea("Sub",o,void 0)},934791:o=>{l.Ea("Mul",o,void 0)},934842:o=>{l.Ea("Div",o,void 0)},934893:o=>{l.Ea("Pow",o,void 0)},934944:o=>{l.Ea("Equal",o,void 0)},934997:o=>{l.Ea("Greater",o,void 0)},935052:o=>{l.Ea("GreaterOrEqual",o,void 0)},935114:o=>{l.Ea("Less",o,void 0)},935166:o=>{l.Ea("LessOrEqual",o,void 0)},935225:(o,h,w,_,A)=>{l.Ea("ReduceMean",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},935384:(o,h,w,_,A)=>{l.Ea("ReduceMax",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},935542:(o,h,w,_,A)=>{l.Ea("ReduceMin",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},935700:(o,h,w,_,A)=>{l.Ea("ReduceProd",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},935859:(o,h,w,_,A)=>{l.Ea("ReduceSum",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},936017:(o,h,w,_,A)=>{l.Ea("ReduceL1",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},936174:(o,h,w,_,A)=>{l.Ea("ReduceL2",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},936331:(o,h,w,_,A)=>{l.Ea("ReduceLogSum",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},936492:(o,h,w,_,A)=>{l.Ea("ReduceSumSquare",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},936656:(o,h,w,_,A)=>{l.Ea("ReduceLogSumExp",o,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},936820:o=>{l.Ea("Where",o,void 0)},936873:(o,h,w)=>{l.Ea("Transpose",o,{perm:h?Array.from(u().subarray(h>>>0,w>>>0)):[]})},936981:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k,de)=>{l.Ea("ConvTranspose",o,{format:ee?"NHWC":"NCHW",autoPad:h,dilations:[w],group:_,kernel_shape:[A],pads:[M,W],strides:[ae],wIsConst:()=>!!n()[te>>>0],outputPadding:le?Array.from(u().subarray(le>>>0,Se>>>0)):[],outputShape:Ae?Array.from(u().subarray(Ae>>>0,k>>>0)):[],activation:Le(de)})},937383:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k)=>{l.Ea("ConvTranspose",o,{format:ae?"NHWC":"NCHW",autoPad:h,dilations:Array.from(u().subarray(w>>>0,(w>>>0)+2>>>0)),group:_,kernelShape:Array.from(u().subarray(A>>>0,(A>>>0)+2>>>0)),pads:Array.from(u().subarray(M>>>0,(M>>>0)+4>>>0)),strides:Array.from(u().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!n()[ee>>>0],outputPadding:te?Array.from(u().subarray(te>>>0,le>>>0)):[],outputShape:Se?Array.from(u().subarray(Se>>>0,Ae>>>0)):[],activation:Le(k)})},937948:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k,de)=>{l.Ea("ConvTranspose",o,{format:ee?"NHWC":"NCHW",autoPad:h,dilations:[w],group:_,kernel_shape:[A],pads:[M,W],strides:[ae],wIsConst:()=>!!n()[te>>>0],outputPadding:le?Array.from(u().subarray(le>>>0,Se>>>0)):[],outputShape:Ae?Array.from(u().subarray(Ae>>>0,k>>>0)):[],activation:Le(de)})},938350:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k)=>{l.Ea("ConvTranspose",o,{format:ae?"NHWC":"NCHW",autoPad:h,dilations:Array.from(u().subarray(w>>>0,(w>>>0)+2>>>0)),group:_,kernelShape:Array.from(u().subarray(A>>>0,(A>>>0)+2>>>0)),pads:Array.from(u().subarray(M>>>0,(M>>>0)+4>>>0)),strides:Array.from(u().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!n()[ee>>>0],outputPadding:te?Array.from(u().subarray(te>>>0,le>>>0)):[],outputShape:Se?Array.from(u().subarray(Se>>>0,Ae>>>0)):[],activation:Le(k)})},938915:(o,h)=>{l.Ea("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},939006:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k,de,Ie)=>{l.Ea("AveragePool",o,{format:Ie?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:_,storage_order:A,dilations:[M,W],kernel_shape:[ae,ee],pads:[te,le,Se,Ae],strides:[k,de]})},939290:(o,h)=>{l.Ea("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},939381:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k,de,Ie)=>{l.Ea("AveragePool",o,{format:Ie?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:_,storage_order:A,dilations:[M,W],kernel_shape:[ae,ee],pads:[te,le,Se,Ae],strides:[k,de]})},939665:(o,h)=>{l.Ea("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},939752:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k,de,Ie)=>{l.Ea("MaxPool",o,{format:Ie?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:_,storage_order:A,dilations:[M,W],kernel_shape:[ae,ee],pads:[te,le,Se,Ae],strides:[k,de]})},940032:(o,h)=>{l.Ea("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},940119:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k,de,Ie)=>{l.Ea("MaxPool",o,{format:Ie?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:_,storage_order:A,dilations:[M,W],kernel_shape:[ae,ee],pads:[te,le,Se,Ae],strides:[k,de]})},940399:(o,h,w,_,A)=>{l.Ea("Gemm",o,{alpha:h,beta:w,transA:_,transB:A})},940503:o=>{l.Ea("MatMul",o,void 0)},940557:(o,h,w,_)=>{l.Ea("ArgMax",o,{keepDims:!!h,selectLastIndex:!!w,axis:_})},940665:(o,h,w,_)=>{l.Ea("ArgMin",o,{keepDims:!!h,selectLastIndex:!!w,axis:_})},940773:(o,h)=>{l.Ea("Softmax",o,{axis:h})},940836:(o,h)=>{l.Ea("Concat",o,{axis:h})},940896:(o,h,w,_,A)=>{l.Ea("Split",o,{axis:h,numOutputs:w,splitSizes:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},941036:o=>{l.Ea("Expand",o,void 0)},941090:(o,h)=>{l.Ea("Gather",o,{axis:Number(h)})},941161:(o,h)=>{l.Ea("GatherElements",o,{axis:Number(h)})},941240:(o,h,w,_,A,M,W,ae,ee,te,le)=>{l.Ea("Resize",o,{antialias:h,axes:w?Array.from(u().subarray(w>>>0,_>>>0)):[],coordinateTransformMode:Le(A),cubicCoeffA:M,excludeOutside:W,extrapolationValue:ae,keepAspectRatioPolicy:Le(ee),mode:Le(te),nearestMode:Le(le)})},941586:(o,h,w,_,A,M,W)=>{l.Ea("Slice",o,{starts:h?Array.from(u().subarray(h>>>0,w>>>0)):[],ends:_?Array.from(u().subarray(_>>>0,A>>>0)):[],axes:M?Array.from(u().subarray(M>>>0,W>>>0)):[]})},941802:o=>{l.Ea("Tile",o,void 0)},941854:(o,h,w)=>{l.Ea("LayerNormalization",o,{axis:Number(h),epsilon:Number(w)})},941961:(o,h,w)=>{l.Ea("InstanceNormalization",o,{epsilon:h,format:w?"NHWC":"NCHW"})},942075:(o,h,w)=>{l.Ea("InstanceNormalization",o,{epsilon:h,format:w?"NHWC":"NCHW"})},942189:o=>{l.Ea("Range",o,void 0)},942242:(o,h)=>{l.Ea("Einsum",o,{equation:Le(h)})},942323:(o,h,w,_,A)=>{l.Ea("Pad",o,{mode:h,value:w,pads:_?Array.from(u().subarray(_>>>0,A>>>0)):[]})},942450:(o,h,w,_,A,M)=>{l.Ea("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!A,trainingMode:!!_,format:M?"NHWC":"NCHW"})},942619:(o,h,w,_,A,M)=>{l.Ea("BatchNormalization",o,{epsilon:h,momentum:w,spatial:!!A,trainingMode:!!_,format:M?"NHWC":"NCHW"})},942788:(o,h,w)=>{l.Ea("CumSum",o,{exclusive:Number(h),reverse:Number(w)})},942885:(o,h,w,_,A,M,W,ae,ee)=>{l.Ea("Attention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:_,scale:A,doRotary:M,qkvHiddenSizes:W?Array.from(u().subarray(Number(ae)>>>0,Number(ae)+W>>>0)):[],pastPresentShareBuffer:!!ee})},943157:o=>{l.Ea("Gelu",o,void 0)},943209:(o,h,w,_,A,M)=>{l.Ea("MultiHeadAttention",o,{numHeads:h,isUnidirectional:w,maskFilterValue:_,scale:A,doRotary:M})},943368:o=>{l.Ea("BiasAdd",o,void 0)},943423:o=>{l.Ea("BiasSplitGelu",o,void 0)},943484:(o,h)=>{l.Ea("SkipLayerNormalization",o,{epsilon:h})},943565:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae)=>{l.Ea("Conv",o,{format:ee?"NHWC":"NCHW",auto_pad:h,dilations:[w],group:_,kernel_shape:[A],pads:M?Array.from(u().subarray(M>>>0,W>>>0)):[],strides:[ae],w_is_const:()=>!!n()[te>>>0],activation:Le(le),activation_params:Se?Array.from(c().subarray(Se>>>0,Ae>>>0)):[]})},943935:(o,h,w,_,A,M,W,ae,ee,te,le,Se,Ae,k,de,Ie)=>{l.Ea("Conv",o,{format:Se?"NHWC":"NCHW",auto_pad:h,dilations:[w,_],group:A,kernel_shape:[M,W],pads:ae?Array.from(u().subarray(ae>>>0,ee>>>0)):[],strides:[te,le],w_is_const:()=>!!n()[Ae>>>0],activation:Le(k),activation_params:de?Array.from(c().subarray(de>>>0,Ie>>>0)):[]})},944326:o=>{l.zb(o)},944360:(o,h)=>l.Ab(o,h,l.bb.Cb,l.bb.errors)};function kt(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Ht=o=>{o.terminate(),o.onmessage=()=>{}},Lt=o=>{ie.Ya.length==0&&(Ye(),ie.lb(ie.Ya[0]));var h=ie.Ya.pop();if(!h)return 6;ie.Za.push(h),ie.Qa[o.Xa]=h,h.Xa=o.Xa;var w={cmd:"run",start_routine:o.Db,arg:o.tb,pthread_ptr:o.Xa};return T&&h.unref(),h.postMessage(w,o.Jb),0},dt=0,Gt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,zr=(o,h,w)=>{h>>>=0;var _=h+w;for(w=h;o[w]&&!(w>=_);)++w;if(16A?_+=String.fromCharCode(A):(A-=65536,_+=String.fromCharCode(55296|A>>10,56320|A&1023))}}else _+=String.fromCharCode(A)}return _},Le=(o,h)=>(o>>>=0)?zr(s(),o,h):"",Br=o=>{var h=xn();return o=o(),qr(h),o};function ke(o,h){var w=arguments.length-2,_=arguments;return Br(()=>{for(var A=Sn(8*w),M=A>>>3,W=0;W>>0]=ae}return La(o,w,A,h)})}function rr(o){if(S)return ke(0,1,o);he=o,0{if(he=o,S)throw ar(o),"unwind";rr(o)},nr=o=>{o instanceof kt||o=="unwind"||C(1,o)};function pt(){for(var o=l.numThreads;o--;)Ye();Ne.unshift(()=>{Je++,Mr(()=>kr())})}function Ye(){var o=D("ort-wasm-simd-threaded.worker.js");o=new Worker(o),ie.Ya.push(o)}function Mr(o){S?o():Promise.all(ie.Ya.map(ie.lb)).then(o)}var ie={Ya:[],Za:[],pb:[],Qa:{},hb(){S?(ie.receiveObjectTransfer=ie.Bb,ie.threadInitTLS=ie.ob,ie.setExitStatus=ie.nb):pt()},nb:o=>he=o,Nb:["$terminateWorker"],Eb:()=>{for(var o of ie.Za)Ht(o);for(o of ie.Ya)Ht(o);ie.Ya=[],ie.Za=[],ie.Qa=[]},mb:o=>{var h=o.Xa;delete ie.Qa[h],ie.Ya.push(o),ie.Za.splice(ie.Za.indexOf(o),1),o.Xa=0,bn(h)},Bb(){},ob(){ie.pb.forEach(o=>o())},lb:o=>new Promise(h=>{o.onmessage=M=>{M=M.data;var W=M.cmd;if(M.targetThread&&M.targetThread!=Fr()){var ae=ie.Qa[M.targetThread];ae?ae.postMessage(M,M.transferList):Ce(`Internal error! Worker sent a message "${W}" to target pthread ${M.targetThread}, but that thread no longer exists!`)}else W==="checkMailbox"?zt():W==="spawnThread"?Lt(M):W==="cleanupThread"?ie.mb(ie.Qa[M.thread]):W==="killThread"?(M=M.thread,W=ie.Qa[M],delete ie.Qa[M],Ht(W),bn(M),ie.Za.splice(ie.Za.indexOf(W),1),W.Xa=0):W==="cancelThread"?ie.Qa[M.thread].postMessage({cmd:"cancel"}):W==="loaded"?(o.loaded=!0,T&&!o.Xa&&o.unref(),h(o)):W==="alert"?alert(`Thread ${M.threadId}: ${M.text}`):M.target==="setimmediate"?o.postMessage(M):W==="callHandler"?l[M.handler](...M.args):W&&Ce(`worker sent an unknown command ${W}`)},o.onerror=M=>{throw Ce(`worker sent an error! ${M.filename}:${M.lineno}: ${M.message}`),M},T&&(o.on("message",M=>o.onmessage({data:M})),o.on("error",M=>o.onerror(M)));var w=[],_=["onExit"],A;for(A of _)l.hasOwnProperty(A)&&w.push(A);o.postMessage({cmd:"load",handlers:w,urlOrBlob:l.mainScriptUrlOrBlob||a,wasmMemory:ve,wasmModule:we})})};l.PThread=ie;var Rt=o=>{for(;0{var o=Fr(),h=d()[o+52>>>2>>>0];o=d()[o+56>>>2>>>0],qa(h,h-o),qr(h)};function ar(o){if(S)return ke(1,0,o);xt(o)}l.invokeEntryPoint=(o,h)=>{o=ja.apply(null,[o,h]),0>>2>>>0]=h},this.rb=function(h){d()[this.gb+8>>>2>>>0]=h},this.hb=function(h,w){this.qb(),this.sb(h),this.rb(w)},this.qb=function(){d()[this.gb+16>>>2>>>0]=0}}var Ft=0;function Dr(o,h,w,_){return S?ke(2,1,o,h,w,_):Pr(o,h,w,_)}function Pr(o,h,w,_){if(o>>>=0,h>>>=0,w>>>=0,_>>>=0,typeof SharedArrayBuffer>"u")return Ce("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var A=[];return S&&A.length===0?Dr(o,h,w,_):(o={Db:w,Xa:o,tb:_,Jb:A},S?(o.Lb="spawnThread",postMessage(o,A),0):Lt(o))}function Nr(o,h,w){return S?ke(3,1,o,h,w):0}function Wr(o,h){if(S)return ke(4,1,o,h)}var ir=o=>{for(var h=0,w=0;w=_?h++:2047>=_?h+=2:55296<=_&&57343>=_?(h+=4,++w):h+=3}return h},Ur=(o,h,w,_)=>{if(w>>>=0,!(0<_))return 0;var A=w;_=w+_-1;for(var M=0;M=W){var ae=o.charCodeAt(++M);W=65536+((W&1023)<<10)|ae&1023}if(127>=W){if(w>=_)break;h[w++>>>0]=W}else{if(2047>=W){if(w+1>=_)break;h[w++>>>0]=192|W>>6}else{if(65535>=W){if(w+2>=_)break;h[w++>>>0]=224|W>>12}else{if(w+3>=_)break;h[w++>>>0]=240|W>>18,h[w++>>>0]=128|W>>12&63}h[w++>>>0]=128|W>>6&63}h[w++>>>0]=128|W&63}}return h[w>>>0]=0,w-A},ne=(o,h,w)=>Ur(o,s(),h,w);function sr(o,h){if(S)return ke(5,1,o,h)}function qt(o,h,w){if(S)return ke(6,1,o,h,w)}function or(o,h,w){return S?ke(7,1,o,h,w):0}function ur(o,h){if(S)return ke(8,1,o,h)}function lr(o,h,w){if(S)return ke(9,1,o,h,w)}function dr(o,h,w,_){if(S)return ke(10,1,o,h,w,_)}function pr(o,h,w,_){if(S)return ke(11,1,o,h,w,_)}function cr(o,h,w,_){if(S)return ke(12,1,o,h,w,_)}function hr(o){if(S)return ke(13,1,o)}function fr(o,h){if(S)return ke(14,1,o,h)}function mr(o,h,w){if(S)return ke(15,1,o,h,w)}var Vr=()=>{if(!(0>>=0,typeof Atomics.Kb=="function"&&(Atomics.Kb(u(),o>>>2,o).value.then(zt),o+=128,Atomics.store(u(),o>>>2,1))}l.__emscripten_thread_mailbox_await=St;var zt=()=>{var o=Fr();if(o&&(St(o),!ce))try{Ga(),Vr()}catch(h){nr(h)}};l.checkMailbox=zt;var p=[],g=o=>o%4===0&&(o%100!==0||o%400===0),v=[0,31,60,91,121,152,182,213,244,274,305,335],I=[0,31,59,90,120,151,181,212,243,273,304,334];function z(o,h,w,_,A,M,W,ae){return S?ke(16,1,o,h,w,_,A,M,W,ae):-52}function V(o,h,w,_,A,M,W){if(S)return ke(17,1,o,h,w,_,A,M,W)}var q=o=>{var h=ir(o)+1,w=vn(h);return w&&ne(o,w,h),w},ue=[],X=(o,h)=>{ue.length=0;for(var w;w=s()[o++>>>0];){var _=w!=105;_&=w!=112,h+=_&&h%8?4:0,ue.push(w==112?d()[h>>>2>>>0]:w==105?u()[h>>>2>>>0]:m()[h>>>3>>>0]),h+=_?8:4}return ue},J={},se=()=>{if(!$e){var o={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",_:x||"./this.program"},h;for(h in J)J[h]===void 0?delete o[h]:o[h]=J[h];var w=[];for(h in o)w.push(`${h}=${o[h]}`);$e=w}return $e},$e;function Ee(o,h){if(S)return ke(18,1,o,h);o>>>=0,h>>>=0;var w=0;return se().forEach((_,A)=>{var M=h+w;for(A=d()[o+4*A>>>2>>>0]=M,M=0;M<_.length;++M)n()[A++>>>0>>>0]=_.charCodeAt(M);n()[A>>>0>>>0]=0,w+=_.length+1}),0}function O(o,h){if(S)return ke(19,1,o,h);o>>>=0,h>>>=0;var w=se();d()[o>>>2>>>0]=w.length;var _=0;return w.forEach(A=>_+=A.length+1),d()[h>>>2>>>0]=_,0}function oe(o){return S?ke(20,1,o):52}function _e(o,h,w,_){return S?ke(21,1,o,h,w,_):52}function ct(o,h,w,_,A){return S?ke(22,1,o,h,w,_,A):70}var Hr=[null,[],[]];function za(o,h,w,_){if(S)return ke(23,1,o,h,w,_);h>>>=0,w>>>=0,_>>>=0;for(var A=0,M=0;M>>2>>>0],ae=d()[h+4>>>2>>>0];h+=8;for(var ee=0;ee>>0],le=Hr[o];te===0||te===10?((o===1?Q:Ce)(zr(le,0)),le.length=0):le.push(te)}A+=ae}return d()[_>>>2>>>0]=A,0}var Ba=[31,29,31,30,31,30,31,31,30,31,30,31],Ma=[31,28,31,30,31,30,31,31,30,31,30,31];function mp(o){var h=Array(ir(o)+1);return Ur(o,h,0,h.length),h}var gp=(o,h)=>{n().set(o,h>>>0)};function Da(o,h,w,_){function A(k,de,Ie){for(k=typeof k=="number"?k.toString():k||"";k.lengthJa?-1:0Bt-k.getDate())de-=Bt-k.getDate()+1,k.setDate(1),11>Ie?k.setMonth(Ie+1):(k.setMonth(0),k.setFullYear(k.getFullYear()+1));else{k.setDate(k.getDate()+de);break}}return Ie=new Date(k.getFullYear()+1,0,4),de=ae(new Date(k.getFullYear(),0,4)),Ie=ae(Ie),0>=W(de,k)?0>=W(Ie,k)?k.getFullYear()+1:k.getFullYear():k.getFullYear()-1}o>>>=0,h>>>=0,w>>>=0,_>>>=0;var te=d()[_+40>>>2>>>0];_={Hb:u()[_>>>2>>>0],Gb:u()[_+4>>>2>>>0],eb:u()[_+8>>>2>>>0],jb:u()[_+12>>>2>>>0],fb:u()[_+16>>>2>>>0],ab:u()[_+20>>>2>>>0],Wa:u()[_+24>>>2>>>0],$a:u()[_+28>>>2>>>0],Ob:u()[_+32>>>2>>>0],Fb:u()[_+36>>>2>>>0],Ib:te?Le(te):""},w=Le(w),te={"%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 le in te)w=w.replace(new RegExp(le,"g"),te[le]);var Se="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ae="January February March April May June July August September October November December".split(" ");te={"%a":k=>Se[k.Wa].substring(0,3),"%A":k=>Se[k.Wa],"%b":k=>Ae[k.fb].substring(0,3),"%B":k=>Ae[k.fb],"%C":k=>M((k.ab+1900)/100|0,2),"%d":k=>M(k.jb,2),"%e":k=>A(k.jb,2," "),"%g":k=>ee(k).toString().substring(2),"%G":k=>ee(k),"%H":k=>M(k.eb,2),"%I":k=>(k=k.eb,k==0?k=12:12{for(var de=0,Ie=0;Ie<=k.fb-1;de+=(g(k.ab+1900)?Ba:Ma)[Ie++]);return M(k.jb+de,3)},"%m":k=>M(k.fb+1,2),"%M":k=>M(k.Gb,2),"%n":()=>` +`,"%p":k=>0<=k.eb&&12>k.eb?"AM":"PM","%S":k=>M(k.Hb,2),"%t":()=>" ","%u":k=>k.Wa||7,"%U":k=>M(Math.floor((k.$a+7-k.Wa)/7),2),"%V":k=>{var de=Math.floor((k.$a+7-(k.Wa+6)%7)/7);if(2>=(k.Wa+371-k.$a-2)%7&&de++,de)de==53&&(Ie=(k.Wa+371-k.$a)%7,Ie==4||Ie==3&&g(k.ab)||(de=1));else{de=52;var Ie=(k.Wa+7-k.$a-1)%7;(Ie==4||Ie==5&&g(k.ab%400-1))&&de++}return M(de,2)},"%w":k=>k.Wa,"%W":k=>M(Math.floor((k.$a+7-(k.Wa+6)%7)/7),2),"%y":k=>(k.ab+1900).toString().substring(2),"%Y":k=>k.ab+1900,"%z":k=>{k=k.Fb;var de=0<=k;return k=Math.abs(k)/60,(de?"+":"-")+("0000"+(k/60*100+k%60)).slice(-4)},"%Z":k=>k.Ib,"%%":()=>"%"},w=w.replace(/%%/g,"\0\0");for(le in te)w.includes(le)&&(w=w.replace(new RegExp(le,"g"),te[le](_)));return w=w.replace(/\0\0/g,"%"),le=mp(w),le.length>h?0:(gp(le,o),le.length-1)}var Lr=o=>{try{o()}catch(h){_t(h)}};function yp(){var o=Z,h={};for(let[w,_]of Object.entries(o))h[w]=typeof _=="function"?function(){Gr.push(w);try{return _.apply(null,arguments)}finally{ce||(Gr.pop(),ht&&Et===1&&Gr.length===0&&(Et=0,dt+=1,Lr(Ya),typeof Fibers<"u"&&Fibers.Pb()))}}:_;return h}var Et=0,ht=null,Pa=0,Gr=[],Na={},Wa={},wp=0,$n=null,$p=[];function vp(){return new Promise((o,h)=>{$n={resolve:o,reject:h}})}function bp(){var o=vn(65548),h=o+12;d()[o>>>2>>>0]=h,d()[o+4>>>2>>>0]=h+65536,h=Gr[0];var w=Na[h];return w===void 0&&(w=wp++,Na[h]=w,Wa[w]=h),h=w,u()[o+8>>>2>>>0]=h,o}function _p(){var o=u()[ht+8>>>2>>>0];return o=Z[Wa[o]],--dt,o()}function xp(o){if(!ce){if(Et===0){var h=!1,w=!1;o((_=0)=>{if(!ce&&(Pa=_,h=!0,w)){Et=2,Lr(()=>Za(ht)),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.resume(),_=!1;try{var A=_p()}catch(ae){A=ae,_=!0}var M=!1;if(!ht){var W=$n;W&&($n=null,(_?W.reject:W.resolve)(A),M=!0)}if(_&&!M)throw A}}),w=!0,h||(Et=1,ht=bp(),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.pause(),Lr(()=>Ka(ht)))}else Et===2?(Et=0,Lr(Xa),Va(ht),ht=null,$p.forEach(_=>{if(!ce)try{_(),Vr()}catch(A){nr(A)}})):_t(`invalid state: ${Et}`);return Pa}}function Sp(o){return xp(h=>{o().then(h)})}ie.hb();var Ep=[rr,ar,Dr,Nr,Wr,sr,qt,or,ur,lr,dr,pr,cr,hr,fr,mr,z,V,Ee,O,oe,_e,ct,za],Ip={r:function(o,h,w){return Sp(async()=>{await l.xb(o,h,w)})},b:function(o,h,w){throw o>>>=0,new wn(o).hb(h>>>0,w>>>0),Ft=o,Ft},N:function(o){Ha(o>>>0,!E,1,!b,131072,!1),ie.ob()},l:function(o){o>>>=0,S?postMessage({cmd:"cleanupThread",thread:o}):ie.mb(ie.Qa[o])},J:Pr,i:Nr,T:Wr,F:sr,H:qt,U:or,R:ur,L:lr,Q:dr,p:pr,G:cr,D:hr,S:fr,E:mr,q:()=>1,B:function(o,h){o>>>=0,o==h>>>0?setTimeout(()=>zt()):S?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=ie.Qa[o])&&o.postMessage({cmd:"checkMailbox"})},K:function(o,h,w,_){h>>>=0,p.length=w,_=_>>>0>>>3;for(var A=0;A>>0];return o=0>o?Vt[-o-1]:Ep[o],ie.ub=h,h=o.apply(null,p),ie.ub=0,h},M:St,W:function(o){T&&ie.Qa[o>>>0].ref()},u:function(o,h,w){o=h+2097152>>>0<4194305-!!o?(o>>>0)+4294967296*h:NaN,w>>>=0,o=new Date(1e3*o),u()[w>>>2>>>0]=o.getUTCSeconds(),u()[w+4>>>2>>>0]=o.getUTCMinutes(),u()[w+8>>>2>>>0]=o.getUTCHours(),u()[w+12>>>2>>>0]=o.getUTCDate(),u()[w+16>>>2>>>0]=o.getUTCMonth(),u()[w+20>>>2>>>0]=o.getUTCFullYear()-1900,u()[w+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,u()[w+28>>>2>>>0]=o},v:function(o,h,w){o=h+2097152>>>0<4194305-!!o?(o>>>0)+4294967296*h:NaN,w>>>=0,o=new Date(1e3*o),u()[w>>>2>>>0]=o.getSeconds(),u()[w+4>>>2>>>0]=o.getMinutes(),u()[w+8>>>2>>>0]=o.getHours(),u()[w+12>>>2>>>0]=o.getDate(),u()[w+16>>>2>>>0]=o.getMonth(),u()[w+20>>>2>>>0]=o.getFullYear()-1900,u()[w+24>>>2>>>0]=o.getDay(),h=(g(o.getFullYear())?v:I)[o.getMonth()]+o.getDate()-1|0,u()[w+28>>>2>>>0]=h,u()[w+36>>>2>>>0]=-(60*o.getTimezoneOffset()),h=new Date(o.getFullYear(),6,1).getTimezoneOffset();var _=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=(h!=_&&o.getTimezoneOffset()==Math.min(_,h))|0,u()[w+32>>>2>>>0]=o},w:function(o){o>>>=0;var h=new Date(u()[o+20>>>2>>>0]+1900,u()[o+16>>>2>>>0],u()[o+12>>>2>>>0],u()[o+8>>>2>>>0],u()[o+4>>>2>>>0],u()[o>>>2>>>0],0),w=u()[o+32>>>2>>>0],_=h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset(),M=new Date(h.getFullYear(),0,1).getTimezoneOffset(),W=Math.min(M,A);return 0>w?u()[o+32>>>2>>>0]=+(A!=M&&W==_):0>>2>>>0]=h.getDay(),w=(g(h.getFullYear())?v:I)[h.getMonth()]+h.getDate()-1|0,u()[o+28>>>2>>>0]=w,u()[o>>>2>>>0]=h.getSeconds(),u()[o+4>>>2>>>0]=h.getMinutes(),u()[o+8>>>2>>>0]=h.getHours(),u()[o+12>>>2>>>0]=h.getDate(),u()[o+16>>>2>>>0]=h.getMonth(),u()[o+20>>>2>>>0]=h.getYear(),o=h.getTime(),isNaN(o)?(u()[Ua()>>>2>>>0]=61,o=-1):o/=1e3,Fa(($t=o,1<=+Math.abs($t)?0<$t?+Math.floor($t/4294967296)>>>0:~~+Math.ceil(($t-+(~~$t>>>0))/4294967296)>>>0:0)),o>>>0},s:z,t:V,A:function(o,h,w){function _(te){return(te=te.toTimeString().match(/\(([A-Za-z ]+)\)$/))?te[1]:"GMT"}o>>>=0,h>>>=0,w>>>=0;var A=new Date().getFullYear(),M=new Date(A,0,1),W=new Date(A,6,1);A=M.getTimezoneOffset();var ae=W.getTimezoneOffset(),ee=Math.max(A,ae);d()[o>>>2>>>0]=60*ee,u()[h>>>2>>>0]=+(A!=ae),o=_(M),h=_(W),o=q(o),h=q(h),ae>>2>>>0]=o,d()[w+4>>>2>>>0]=h):(d()[w>>>2>>>0]=h,d()[w+4>>>2>>>0]=o)},d:()=>{_t("")},c:function(o,h,w){return o>>>=0,h=X(h>>>0,w>>>0),Vt[o].apply(null,h)},k:function(o,h,w){return o>>>=0,h=X(h>>>0,w>>>0),Vt[o].apply(null,h)},m:()=>{},j:()=>Date.now(),V:()=>{throw dt+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>T?(jp(),Pt(xu)).cpus().length:navigator.hardwareConcurrency,y:function(o){o>>>=0;var h=s().length;if(o<=h||4294901760=w;w*=2){var _=h*(1+.2/w);_=Math.min(_,o+100663296);var A=Math;_=Math.max(o,_);e:{A=(A.min.call(A,4294901760,_+(65536-_%65536)%65536)-ve.buffer.byteLength+65535)/65536;try{ve.grow(A),We();var M=1;break e}catch{}M=void 0}if(M)return!0}return!1},O:Ee,P:O,I:xt,h:oe,o:_e,x:ct,n:za,a:ve||l.wasmMemory,z:Da,e:function(o,h,w,_){return Da(o>>>0,h>>>0,w>>>0,_>>>0)}},Z=function(){function o(w,_){return Z=w.exports,Z=yp(),Z=Cp(),ie.pb.push(Z.Da),Ue.unshift(Z.X),we=_,kr(),Z}var h={a:Ip};if(Je++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(w){Ce(`Module.instantiateWasm callback failed with error: ${w}`),y(w)}return Rr(h,function(w){o(w.instance,w.module)}).catch(y),{}}();l._OrtInit=(o,h)=>(l._OrtInit=Z.Y)(o,h),l._OrtGetLastError=(o,h)=>(l._OrtGetLastError=Z.Z)(o,h),l._OrtCreateSessionOptions=(o,h,w,_,A,M,W,ae,ee,te)=>(l._OrtCreateSessionOptions=Z._)(o,h,w,_,A,M,W,ae,ee,te),l._OrtAppendExecutionProvider=(o,h)=>(l._OrtAppendExecutionProvider=Z.$)(o,h),l._OrtAddFreeDimensionOverride=(o,h,w)=>(l._OrtAddFreeDimensionOverride=Z.aa)(o,h,w),l._OrtAddSessionConfigEntry=(o,h,w)=>(l._OrtAddSessionConfigEntry=Z.ba)(o,h,w),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Z.ca)(o),l._OrtCreateSession=(o,h,w)=>(l._OrtCreateSession=Z.da)(o,h,w),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Z.ea)(o),l._OrtGetInputOutputCount=(o,h,w)=>(l._OrtGetInputOutputCount=Z.fa)(o,h,w),l._OrtGetInputName=(o,h)=>(l._OrtGetInputName=Z.ga)(o,h),l._OrtGetOutputName=(o,h)=>(l._OrtGetOutputName=Z.ha)(o,h),l._OrtFree=o=>(l._OrtFree=Z.ia)(o),l._OrtCreateTensor=(o,h,w,_,A,M)=>(l._OrtCreateTensor=Z.ja)(o,h,w,_,A,M),l._OrtGetTensorData=(o,h,w,_,A)=>(l._OrtGetTensorData=Z.ka)(o,h,w,_,A),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Z.la)(o),l._OrtCreateRunOptions=(o,h,w,_)=>(l._OrtCreateRunOptions=Z.ma)(o,h,w,_),l._OrtAddRunConfigEntry=(o,h,w)=>(l._OrtAddRunConfigEntry=Z.na)(o,h,w),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Z.oa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Z.pa)(o),l._OrtBindInput=(o,h,w)=>(l._OrtBindInput=Z.qa)(o,h,w),l._OrtBindOutput=(o,h,w,_)=>(l._OrtBindOutput=Z.ra)(o,h,w,_),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Z.sa)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Z.ta)(o),l._OrtRunWithBinding=(o,h,w,_,A)=>(l._OrtRunWithBinding=Z.ua)(o,h,w,_,A),l._OrtRun=(o,h,w,_,A,M,W,ae)=>(l._OrtRun=Z.va)(o,h,w,_,A,M,W,ae),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Z.wa)(o),l._JsepOutput=(o,h,w)=>(l._JsepOutput=Z.xa)(o,h,w),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Z.ya)(o);var Ua=()=>(Ua=Z.za)(),Fr=l._pthread_self=()=>(Fr=l._pthread_self=Z.Aa)(),vn=l._malloc=o=>(vn=l._malloc=Z.Ba)(o),Va=l._free=o=>(Va=l._free=Z.Ca)(o);l.__emscripten_tls_init=()=>(l.__emscripten_tls_init=Z.Da)();var Ha=l.__emscripten_thread_init=(o,h,w,_,A,M)=>(Ha=l.__emscripten_thread_init=Z.Fa)(o,h,w,_,A,M);l.__emscripten_thread_crashed=()=>(l.__emscripten_thread_crashed=Z.Ga)();var La=(o,h,w,_)=>(La=Z.Ha)(o,h,w,_),bn=o=>(bn=Z.Ia)(o),_n=l.__emscripten_thread_exit=o=>(_n=l.__emscripten_thread_exit=Z.Ja)(o),Ga=()=>(Ga=Z.Ka)(),Fa=o=>(Fa=Z.La)(o),qa=(o,h)=>(qa=Z.Ma)(o,h),xn=()=>(xn=Z.Na)(),qr=o=>(qr=Z.Oa)(o),Sn=o=>(Sn=Z.Pa)(o),ja=l.dynCall_ii=(o,h)=>(ja=l.dynCall_ii=Z.Ra)(o,h),Ka=o=>(Ka=Z.Sa)(o),Ya=()=>(Ya=Z.Ta)(),Za=o=>(Za=Z.Ua)(o),Xa=()=>(Xa=Z.Va)();l.___start_em_js=944472,l.___stop_em_js=944633;function Cp(){var o=Z;o=Object.assign({},o);var h=_=>()=>_()>>>0,w=_=>A=>_(A)>>>0;return o.za=h(o.za),o.Aa=h(o.Aa),o.Ba=w(o.Ba),o.emscripten_main_runtime_thread_id=h(o.emscripten_main_runtime_thread_id),o.Na=h(o.Na),o.Pa=w(o.Pa),o}l.wasmMemory=ve,l.stackAlloc=Sn,l.stackSave=xn,l.stackRestore=qr,l.keepRuntimeAlive=()=>0r)}),Yp=Xt((e,t)=>{t.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\n'}),ti,ri,Tn,Yr,yr,An,ni,ai,ii,Eu,He,Ar=H(()=>{ti=Gp(),ri=Kp(),Yr=!1,yr=!1,An=!1,ni=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}},ai=()=>{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}},ii=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Eu=async e=>{if(Yr)return Promise.resolve();if(yr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(An)throw new Error("previous call to 'initializeWebAssembly()' failed.");yr=!0;let t=e.initTimeout,r=e.numThreads,a=e.simd,i=ni(r),n=a&&ai(),s=e.wasmPaths,u=typeof s=="string"?s:void 0,d=ii(n,i),c=typeof s=="object"?s[d]:void 0,m=!1,l=[];if(t>0&&l.push(new Promise(f=>{setTimeout(()=>{m=!0,f()},t)})),l.push(new Promise((f,y)=>{let $=i?ri:ti,x={locateFile:(C,b)=>{if(i&&C.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Yp()],{type:"text/javascript"}));if(C.endsWith(".wasm")){if(c)return c;let E=u??b;return d==="ort-wasm-simd.wasm"?E+"ort-wasm-simd.jsep.wasm":d==="ort-wasm-simd-threaded.wasm"?E+"ort-wasm-simd-threaded.jsep.wasm":E+d}return b+C}};if(i)if(x.numThreads=r,typeof Blob>"u")x.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let C=`var ortWasmThreaded=${$.toString()};`;x.mainScriptUrlOrBlob=new Blob([C],{type:"text/javascript"})}$(x).then(C=>{yr=!1,Yr=!0,Tn=C,f()},C=>{yr=!1,An=!0,y(C)})})),await Promise.race(l),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},He=()=>{if(Yr&&Tn)return Tn;throw new Error("WebAssembly is not initialized yet.")}}),Ve,un,ze,va=H(()=>{Ar(),Ve=(e,t)=>{let r=He(),a=r.lengthBytesUTF8(e)+1,i=r._malloc(a);return r.stringToUTF8(e,i,a),t.push(i),i},un=(e,t,r,a)=>{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,n])=>{let s=t?t+i:i;if(typeof n=="object")un(n,s+".",r,a);else if(typeof n=="string"||typeof n=="number")a(s,n.toString());else if(typeof n=="boolean")a(s,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},ze=e=>{let t=He(),r=t.stackSave();try{let a=t.stackAlloc(8);t._OrtGetLastError(a,a+4);let i=t.HEAP32[a/4],n=t.HEAPU32[a/4+1],s=n?t.UTF8ToString(n):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{t.stackRestore(r)}}}),Iu,Zp=H(()=>{Ar(),va(),Iu=e=>{let t=He(),r=0,a=[],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 n=0;return e?.tag!==void 0&&(n=Ve(e.tag,a)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,n),r===0&&ze("Can't create run options."),e?.extra!==void 0&&un(e.extra,"",new WeakSet,(s,u)=>{let d=Ve(s,a),c=Ve(u,a);t._OrtAddRunConfigEntry(r,d,c)!==0&&ze(`Can't set a run config entry: ${s} - ${u}.`)}),[r,a]}catch(n){throw r!==0&&t._OrtReleaseRunOptions(r),a.forEach(s=>t._free(s)),n}}}),si,oi,ui,li,Cu,Xp=H(()=>{Ar(),va(),si=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}`)}},oi=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ui=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)},li=(e,t,r)=>{for(let a of t){let i=typeof a=="string"?a:a.name;switch(i){case"webnn":if(i="WEBNN",typeof a!="string"){let s=a;if(s?.deviceType){let u=Ve("deviceType",r),d=Ve(s.deviceType,r);He()._OrtAddSessionConfigEntry(e,u,d)!==0&&ze(`Can't set a session config entry: 'deviceType' - ${s.deviceType}.`)}if(s?.numThreads){let u=s.numThreads;(typeof u!="number"||!Number.isInteger(u)||u<0)&&(u=0);let d=Ve("numThreads",r),c=Ve(u.toString(),r);He()._OrtAddSessionConfigEntry(e,d,c)!==0&&ze(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s?.powerPreference){let u=Ve("powerPreference",r),d=Ve(s.powerPreference,r);He()._OrtAddSessionConfigEntry(e,u,d)!==0&&ze(`Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof a!="string"){let s=a;if(s?.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let u=Ve("preferredLayout",r),d=Ve(s.preferredLayout,r);He()._OrtAddSessionConfigEntry(e,u,d)!==0&&ze(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let n=Ve(i,r);He()._OrtAppendExecutionProvider(e,n)!==0&&ze(`Can't append execution provider: ${i}.`)}},Cu=e=>{let t=He(),r=0,a=[],i=e||{};ui(i);try{let n=si(i.graphOptimizationLevel??"all"),s=oi(i.executionMode??"sequential"),u=typeof i.logId=="string"?Ve(i.logId,a):0,d=i.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let m=typeof i.optimizedModelFilePath=="string"?Ve(i.optimizedModelFilePath,a):0;if(r=t._OrtCreateSessionOptions(n,!!i.enableCpuMemArena,!!i.enableMemPattern,s,!!i.enableProfiling,0,u,d,c,m),r===0&&ze("Can't create session options."),i.executionProviders&&li(r,i.executionProviders,a),i.freeDimensionOverrides)for(let[l,f]of Object.entries(i.freeDimensionOverrides)){if(typeof l!="string")throw new Error(`free dimension override name must be a string: ${l}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let y=Ve(l,a);t._OrtAddFreeDimensionOverride(r,y,f)!==0&&ze(`Can't set a free dimension override: ${l} - ${f}.`)}return i.extra!==void 0&&un(i.extra,"",new WeakSet,(l,f)=>{let y=Ve(l,a),$=Ve(f,a);t._OrtAddSessionConfigEntry(r,y,$)!==0&&ze(`Can't set a session config entry: ${l} - ${f}.`)}),[r,a]}catch(n){throw r!==0&&t._OrtReleaseSessionOptions(r),a.forEach(s=>t._free(s)),n}}}),ta,ft,ln,ba,dn,_a,ra,De=H(()=>{ta=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}`)}},ft=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}`)}},ln=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],ba=e=>{switch(e){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},dn=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}`)}},_a=e=>e==="float32"||e==="int32"||e==="int64"||e==="bool"||e==="float16"||e==="uint32",ra=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}`)}}}),pn,Tu=H(()=>{pn=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),a=[];for await(let i of r)a.push(i);return new Uint8Array(Buffer.concat(a))}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"),a=r?parseInt(r,10):0;if(a<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(),n;try{n=new ArrayBuffer(a)}catch(u){if(u instanceof RangeError){let d=Math.ceil(a/65536);n=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let s=0;for(;;){let{done:u,value:d}=await i.read();if(u)break;let c=d.byteLength;new Uint8Array(n,s,c).set(d),s+=c}return new Uint8Array(n,0,a)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),di,pi,ci,hi,Au,fi,Ge,Nt=H(()=>{De(),di=["V","I","W","E","F"],pi=(e,t)=>{console.log(`[${di[e]},${new Date().toISOString()}]${t}`)},Au=(e,t)=>{ci=e,hi=t},fi=(e,t)=>{let r=dn(e),a=dn(ci);r>=a&&pi(r,typeof t=="function"?t():t)},Ge=(...e)=>{hi&&fi(...e)}}),Ou,Qp=H(()=>{De(),Ou=(e,t)=>new(ba(t))(e)}),xa=H(()=>{}),wr,mi,On,na,gi,ku,Jp=H(()=>{Nt(),xa(),wr=e=>Math.ceil(e/16)*16,mi=1,On=()=>mi++,na=async(e,t,r,a)=>{let i=wr(r),n=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=e.getCommandEncoder();e.endComputePass(),s.copyBufferToBuffer(t,0,n,0,i),e.flush(),await n.mapAsync(GPUMapMode.READ);let u=n.getMappedRange();if(a){let d=a();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{n.destroy()}},gi=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map}upload(e,t){let r=t.buffer,a=t.byteOffset,i=t.byteLength,n=wr(i),s=this.storageCache.get(e);if(!s)throw new Error("gpu data for uploading does not exist");if(s.originalSize!==i)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${i}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(r,a,i)),u.unmap();let c=this.backend.getCommandEncoder();this.backend.endComputePass(),c.copyBufferToBuffer(u,0,s.gpuData.buffer,0,n),Ge("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let a=this.storageCache.get(t);if(!a)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==a.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=wr(r.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(r.gpuData.buffer,0,a.gpuData.buffer,0,i)}registerExternalBuffer(e,t,r){let a;if(r){if(a=this.externalBuffers.get(r),a===void 0)throw new Error("previous buffer is not registered");if(e===r)return Ge("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${a}, buffer is the same, skip.`),a;this.externalBuffers.delete(r)}else a=On();return this.storageCache.set(a,{gpuData:{id:a,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,a),Ge("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${a}, registered.`),a}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),Ge("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=wr(e),a,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||n){let u=i?this.freeBuffers:this.freeUniformBuffers,d=u.get(r);d||(d=[],u.set(r,d)),d.length>0?a=d.pop():a=this.backend.device.createBuffer({size:r,usage:t})}else a=this.backend.device.createBuffer({size:r,usage:t});let s={id:On(),type:0,buffer:a};return this.storageCache.set(s.id,{gpuData:s,originalSize:e}),Ge("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${s.id}`),s}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return Ge("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await na(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();this.buffersForUploadingPending=[];for(let e of this.buffersPending)(e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(e.size).push(e):(e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(e.size).push(e):e.destroy();this.buffersPending=[]}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map}},ku=(...e)=>new gi(...e)}),yi,Be,qe=H(()=>{yi=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Be=e=>new yi(e)}),wi,Zt,F,cn,Ru,Sa,Ea,xe=H(()=>{wi=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Zt=class{static calcShape(e,t,r=!1){let a=e.length,i=t.length;if(a===0)return t;if(i===0)return e;let n=Math.max(e.length,t.length),s=new Array(n);if(r){if(a<2||i<2)return;let u=wi.calcMatMulShape([e[a-2],e[a-1]],[t[i-2],t[i-1]]);if(u===void 0)return;[s[n-2],s[n-1]]=u}for(let u=r?3:1;u<=n;u++){let d=a-u<0?1:e[a-u],c=i-u<0?1:t[i-u];if(d!==c&&d>1&&c>1)return;s[n-u]=Math.max(d,c)}return s}static isValidBroadcast(e,t){let r=e.length,a=t.length;if(r>a)return!1;for(let i=1;i<=r;i++)if(e[r-i]!==1&&e[r-i]!==t[a-i])return!1;return!0}},F=class nn{static size(t){return nn.getSizeFromDimensionRange(t,0,t.length)}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return nn.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 nn.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,a){let i=1;for(let n=r;n=0;--i)a[i]=a[i+1]*t[i+1];return a}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(a=>this.normalizeAxis(a,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(a=>t[a]):t.slice().reverse()}static padShape(t,r){let a=t.length;return t.map((i,n)=>i+r[n]+r[n+a])}static areEqual(t,r){return t.length!==r.length?!1:t.every((a,i)=>a===r[i])}},cn=class Er{static adjustPoolAttributes(t,r,a,i,n,s){if(!t&&a.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 u=0;u=a.length?a.push(r[u+2]):a[u]=r[u+2];for(let u=0;u=a[u]||s[u+a.length]>=a[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,a,i,n,s,u){if(u){if(n.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 d=0;d{De(),xe(),$i=64,Zr=(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}`)}},tt=(e,t=1)=>{let r=Zr(e,t);return typeof r=="string"?r:r[0]},vt=(e,t=1)=>{let r=Zr(e,t);return typeof r=="string"?r:r[1]},Y=e=>e.length===0?[]:[{type:"uint32",data:e},{type:"uint32",data:F.computeStrides(e)}],Xe=e=>e%4===0?4:e%2===0?2:1,Ze=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,bt=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}f(${r})`,yt=(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)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?`${e}[(${t}) / 4][(${t}) % 4]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Xr=(e,t,r,a,i)=>{let n=typeof r=="number",s=n?r:r.length,u=[...new Array(s).keys()],d=s<2?"u32":s<=4?`vec${s}`:`array`,c=Zr(t,i),m=typeof c=="string"?c:c[1],l=typeof c=="string"?c:c[0],f={indices:d,value:m,storage:l,tensor:t},y=N=>typeof N=="string"?N:`${N}u`,$={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},x=n?"uniforms.":"",C=`${x}${e}_shape`,b=`${x}${e}_strides`,E="";for(let N=0;N ${f.indices} { + var indices: ${f.indices}; + var current = offset; + ${E} + return indices; + }`,S=N=>($.offsetToIndices=!0,s<2?N:`o2i_${e}(${N})`),B=[];if(s>=2)for(let N=s-1;N>=0;N--)B.push(`${fe(b,N,s)} * (indices[${N}])`);let D=s<2?"":` + fn i2o_${e}(indices: ${f.indices}) -> u32 { + return ${B.join("+")}; + }`,U=N=>($.indicesToOffset=!0,s<2?N:`i2o_${e}(${N})`),P=(...N)=>s===0?"0u":`${f.indices}(${N.map(y).join(",")})`,G=(N,re)=>s<2?`${N}`:`${fe(N,re,s)}`,K=(N,re,ye)=>s<2?`${N}=${ye};`:`${fe(N,re,s)}=${ye};`,R={},j=(N,re)=>{$.broadcastedIndicesToOffset=!0;let ye=`${re.name}broadcastedIndicesTo${e}Offset`;if(ye in R)return`${ye}(${N})`;let Me=[];for(let Re=s-1;Re>=0;Re--){let We=re.indicesGet("outputIndices",Re+re.rank-s);Me.push(`${G(b,Re)} * (${We} % ${G(C,Re)})`)}return R[ye]=`fn ${ye}(outputIndices: ${re.type.indices}) -> u32 { + return ${Me.length>0?Me.join("+"):"0u"}; + }`,`${ye}(${N})`},me=(N,re)=>(()=>{if(f.storage===f.value)return`${e}[${N}]=${re};`;if(f.storage==="vec2"&&f.value==="i32")return`${e}[${N}]=vec2(u32(${re}), select(0u, 0xFFFFFFFFu, ${re} < 0));`;if(f.storage==="vec2"&&f.value==="u32")return`${e}[${N}]=vec2(u32(${re}), 0u);`;if(f.storage==="u32"&&f.value==="vec4")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${re}));`;throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`)})(),Q=N=>(()=>{if(f.storage===f.value)return`${e}[${N}]`;if(f.storage==="vec2"&&f.value==="i32")return`i32(${e}[${N}].x)`;if(f.storage==="vec2"&&f.value==="u32")return`u32(${e}[${N}].x)`;if(f.storage==="u32"&&f.value==="vec4")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`)})(),Ce=s<2?"":` + fn get_${e}ByIndices(indices: ${f.indices}) -> ${m} { + return ${Q(`i2o_${e}(indices)`)}; + }`,ve=s<2?"":(()=>{let N=u.map(ye=>`d${ye}: u32`).join(", "),re=u.map(ye=>`d${ye}`).join(", ");return` + fn get_${e}(${N}) -> ${m} { + return get_${e}ByIndices(${P(re)}); + }`})(),we=(...N)=>{if(N.length!==s)throw new Error(`indices length must be ${s}`);let re=N.map(y).join(",");return s===0?Q("0u"):s===1?Q(re[0]):($.get=!0,$.getByIndices=!0,$.indicesToOffset=!0,`get_${e}(${re})`)},ce=N=>s<2?Q(N):($.getByIndices=!0,$.indicesToOffset=!0,`get_${e}ByIndices(${N})`),he=s<2?"":` + fn set_${e}ByIndices(indices: ${f.indices}, value: ${m}) { + ${me(`i2o_${e}(indices)`,"value")} + }`,ge=s<2?"":(()=>{let N=u.map(ye=>`d${ye}: u32`).join(", "),re=u.map(ye=>`d${ye}`).join(", ");return` + fn set_${e}(${N}, value: ${m}) { + set_${e}ByIndices(${P(re)}, value); + }`})();return{impl:()=>{let N=[],re=!1;return $.offsetToIndices&&(N.push(T),re=!0),$.indicesToOffset&&(N.push(D),re=!0),$.broadcastedIndicesToOffset&&(Object.values(R).forEach(ye=>N.push(ye)),re=!0),$.set&&(N.push(ge),re=!0),$.setByIndices&&(N.push(he),re=!0),$.get&&(N.push(ve),re=!0),$.getByIndices&&(N.push(Ce),re=!0),!n&&re&&N.unshift(`const ${C} = ${f.indices}(${r.join(",")});`,`const ${b} = ${f.indices}(${F.computeStrides(r).join(",")});`),N.join(` +`)},type:f,offsetToIndices:S,indicesToOffset:U,broadcastedIndicesToOffset:j,indices:P,indicesGet:G,indicesSet:K,set:(...N)=>{if(N.length!==s+1)throw new Error(`indices length must be ${s}`);let re=N[s];if(typeof re!="string")throw new Error("value must be string");let ye=N.slice(0,s).map(y).join(",");return s===0?me("0u",re):s===1?me(ye[0],re):($.set=!0,$.setByIndices=!0,$.indicesToOffset=!0,`set_${e}(${ye}, ${re})`)},setByOffset:me,setByIndices:(N,re)=>s<2?me(N,re):($.setByIndices=!0,$.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${re});`),get:we,getByOffset:Q,getByIndices:ce,usage:a,name:e,strides:b,shape:C,rank:s}},L=(e,t,r,a=1)=>Xr(e,t,r,"input",a),pe=(e,t,r,a=1)=>Xr(e,t,r,"output",a),Ia=(e,t,r,a=1)=>Xr(e,t,r,"internal",a),vi=class{constructor(e){this.normalizedDispatchGroup=e,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=$i){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],a=typeof e=="number"?1:e[2],i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=i?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,s=i?"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) * ${t*r*a}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${a}) + fn main(${n}) { + ${s} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",a=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${a}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:a}of this.uniforms)if(a&&a>4)e.push(`${t}:array, ${Math.ceil(a/4)}>`);else{let i=a==null||a===1?r:`vec${a}<${r}>`;e.push(`${t}:${i}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}},zu=e=>new vi(e),Tr=(e,t)=>{let r=e.length,a=[];for(let i=0;i1&&s===1&&a.unshift(n)}return a},Fe=e=>!0}),bi,kn,_i,xi,Tt,Bu,Mu,Or=H(()=>{xe(),qe(),be(),bi=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},kn=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,_i=(e,t)=>F.sortBasedOnPerm(e,kn(e.length,t)),xi=(e,t,r,a)=>{let i=[];i.push(`fn perm(i: ${a.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let n=0;n{let r=e.dataType,a=e.dims.length,i=kn(a,t),n=Fe(a),s=_i(e.dims,i),u=n?s.length:s,d=n?a:e.dims,c=pe("output",r,u),m=L("a",r,d),l=f=>` + ${f.registerUniform("output_size","u32").declareVariables(m,c)} + + ${xi(i,a,m,c)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${c.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${c.setByOffset("global_idx",m.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:n?["rank"]:["dims"]},getRunData:f=>{let y=F.size(s);return{outputs:[{dims:s,dataType:f[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:n?[{type:"uint32",data:y},...Y(f[0].dims),...Y(s)]:[{type:"uint32",data:y}]}},getShaderSource:l}},Bu=(e,t)=>{bi(e.inputs),e.compute(Tt(e.inputs[0],t.perm))},Mu=e=>Be({perm:e.perm})}),Si,Ei,Ii,Ci,Ti,Ai,Oi,ki,Ri,zi,nt,Du,Pu,Nu,Wu,Uu,Vu,Hu,Lu,Gu,Fu,ec=H(()=>{xe(),be(),Ca(),Or(),Si={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"},Ei={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"},Ii={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Ci={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ti=(e,t)=>{let r=[];for(let a=t-e;a{let r=[],a=e.length;for(let n=0;ne[n]);return[r,i]},Oi=(e,t)=>{let r=e.length+t.length,a=[],i=0;for(let n=0;n{for(let r=0;r{let r=[];if(!ki(e,t)){for(let a=0;ar.push(a))}return r},zi=(e,t,r,a,i,n,s)=>{let u=r[0].dims,d=F.size(n),c=F.size(s),m=L("_A",r[0].dataType,u),l=pe("output",i,n),f=32,y=` + var aBestValues : array<${l.type.storage}, ${f}>; + `;return{name:e,shaderCache:t,getShaderSource:$=>` + ${$.registerUniform("reduceSize","u32").declareVariables(m,l)} + ${y} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${$.mainStart(f)} + + let outputIndex = global_idx / ${f}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = ${l.type.storage}(${Ii[a]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${f}) { + let candidate = ${l.type.storage}(${m.getByOffset("offset + k")}); + bestValue = ${Si[a]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${f}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 = ${Ei[a]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${l.setByOffset("outputIndex",`${a==="mean"?`bestValue / ${l.type.storage}(uniforms.reduceSize)`:`${Ci[a]}`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:d},programUniforms:[{type:"uint32",data:c}]})}},nt=(e,t,r,a)=>{let i=e.inputs.length===1?r:aa(e.inputs,r),n=i.axes;n.length===0&&!i.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((y,$)=>$));let s=F.normalizeAxes(n,e.inputs[0].dims.length),u=s,d=e.inputs[0],c=Ri(u,e.inputs[0].dims.length);c.length>0&&(d=e.compute(Tt(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],u=Ti(u.length,d.dims.length));let[m,l]=Ai(d.dims,u),f=m;i.keepDims&&(f=Oi(m,s)),e.compute(zi(t,{hint:i.cacheKey,inputDependencies:["type"]},[d],a,e.inputs[0].dataType,f,l),{inputs:[d]})},Du=(e,t)=>{nt(e,"ReduceMeanShared",t,"mean")},Pu=(e,t)=>{nt(e,"ReduceL1Shared",t,"l1")},Nu=(e,t)=>{nt(e,"ReduceL2Shared",t,"l2")},Wu=(e,t)=>{nt(e,"ReduceLogSumExpShared",t,"logSumExp")},Uu=(e,t)=>{nt(e,"ReduceMaxShared",t,"max")},Vu=(e,t)=>{nt(e,"ReduceMinShared",t,"min")},Hu=(e,t)=>{nt(e,"ReduceProdShared",t,"prod")},Lu=(e,t)=>{nt(e,"ReduceSumShared",t,"sum")},Gu=(e,t)=>{nt(e,"ReduceSumSquareShared",t,"sumSquare")},Fu=(e,t)=>{nt(e,"ReduceLogSumShared",t,"logSum")}}),at,Bi,hn,aa,it,Mi,Di,Pi,Ni,Wi,Ui,Vi,Hi,Li,Gi,st,qu,ju,Ku,Yu,Zu,Xu,Qu,Ju,el,tl,Ca=H(()=>{xe(),qe(),be(),ec(),at=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.")},Bi=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],hn=(e,t,r,a,i,n,s=!1,u=!1)=>{let d=[],c=r[0].dims,m=c.length,l=F.normalizeAxes(i,m),f=!u&&l.length===0;c.forEach((x,C)=>{f||l.indexOf(C)>=0?s&&d.push(1):d.push(x)});let y=d.length,$=F.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let C=[],b=L("_A",r[0].dataType,m),E=pe("output",n,y),T=a(b,E,l),S=T[2];for(let B=0,D=0;B=0?(s&&D++,S=`for(var j${B}: u32 = 0; j${B} < ${c[B]}; j${B}++) { + ${T[2].includes("last_index")?`let last_index = j${B};`:""} + ${b.indicesSet("input_indices",B,`j${B}`)} + ${S} + }`):(C.push(`${b.indicesSet("input_indices",B,E.indicesGet("output_indices",D))};`),D++);return` + + ${x.registerUniform("output_size","u32").declareVariables(b,E)} + + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${b.type.indices}; + let output_indices = ${E.offsetToIndices("global_idx")}; + + ${C.join(` +`)} + ${T[0]} // init ops for reduce max/min + ${T[1]} + ${S} + ${T[3]} + ${T.length===4?E.setByOffset("global_idx","value"):T.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:d,dataType:n}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:"uint32",data:$},...Y(c),...Y(d)]})}},aa=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(a=>r.push(Number(a))),Be({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},it=(e,t,r,a)=>{let i=e.inputs,n=i.length===1?r:aa(i,r);e.compute(hn(t,{hint:n.cacheKey,inputDependencies:["rank"]},[i[0]],n.noopWithEmptyAxes&&n.axes.length===0?Bi:a,n.axes,i[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},Mi=(e,t)=>{at(e.inputs),it(e,"ReduceLogSum",t,(r,a)=>[`var value = ${a.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Di=(e,t)=>{at(e.inputs),it(e,"ReduceL1",t,(r,a)=>[`var value = ${a.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Pi=(e,t)=>{at(e.inputs),it(e,"ReduceL2",t,(r,a)=>[`var t = ${a.type.value}(0); var value = ${a.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ni=(e,t)=>{at(e.inputs),it(e,"ReduceLogSumExp",t,(r,a)=>[`var value = ${a.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Wi=(e,t)=>{at(e.inputs),it(e,"ReduceMax",t,(r,a,i)=>{let n=[];for(let s=0;s=0||i.length===0)&&n.push(r.indicesSet("input_indices",s,0));return[`${n.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},Ui=(e,t)=>{at(e.inputs),it(e,"ReduceMean",t,(r,a,i)=>{let n=1;for(let s=0;s=0||i.length===0)&&(n*=e.inputs[0].dims[s]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${a.type.value}(sum / ${n});`]})},Vi=(e,t)=>{at(e.inputs),it(e,"ReduceMin",t,(r,a,i)=>{let n=[];for(let s=0;s=0||i.length===0)&&n.push(`input_indices[${s}] = 0;`);return[`${n.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},Hi=(e,t)=>{at(e.inputs),it(e,"ReduceProd",t,(r,a)=>[`var value = ${a.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Li=(e,t)=>{at(e.inputs),it(e,"ReduceSum",t,(r,a)=>[`var value = ${a.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Gi=(e,t)=>{at(e.inputs),it(e,"ReduceSumSquare",t,(r,a)=>[`var t = ${a.type.value}(0); var value = ${a.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},st=(e,t,r)=>{if(t.length===0)return r;let a=1,i=1;for(let n=0;n1024},qu=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ui(e,t):Du(e,t)},ju=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Di(e,t):Pu(e,t)},Ku=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pi(e,t):Nu(e,t)},Yu=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ni(e,t):Wu(e,t)},Zu=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wi(e,t):Uu(e,t)},Xu=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vi(e,t):Vu(e,t)},Qu=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hi(e,t):Hu(e,t)},Ju=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Li(e,t):Lu(e,t)},el=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gi(e,t):Gu(e,t)},tl=(e,t)=>{st(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Mi(e,t):Fu(e,t)}}),Rn,rl,nl,ia,tc=H(()=>{De(),qe(),Ca(),Rn=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.")},rl=(e,t)=>{Rn(e.inputs);let r=(a,i,n)=>{let s=[];for(let u=0;u=0||n.length===0)&&s.push(`input_indices[${u}] = 0;`);return[`${s.join(` +`)}`,`var value = ${a.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${a.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${a.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(hn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},nl=(e,t)=>{Rn(e.inputs);let r=(a,i,n)=>{let s=[];for(let u=0;u=0||n.length===0)&&s.push(`input_indices[${u}] = 0;`);return[`${s.join(` +`)}`,`var value = ${a.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${a.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${a.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(hn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ia=e=>Be(e)}),Fi,qi,ji,Ki,fn,Yi,al,il=H(()=>{De(),xa(),be(),Fi=(e,t)=>{let r=e[0],a=e[1],i=e[2],n=e[3],s=e[4],u=e[5];if(s&&u)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 d=r.dims[0],c=r.dims[1],m=r.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(a.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(a.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==a.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let l=i.dims[0]/3,f=l,y=f;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let T of t.qkvHiddenSizes)if(T%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");l=t.qkvHiddenSizes[0],f=t.qkvHiddenSizes[1],y=t.qkvHiddenSizes[2]}let $=c;if(l!==f)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==l+f+y)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let x=0;if(s){if(f!==y)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(s.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(s.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==f/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(x=s.dims[3])}let C=$+x,b=-1,E=0;if(n)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");if(u)throw new Error("relativePositionBias is not supported");return{batchSize:d,sequenceLength:c,pastSequenceLength:x,kvSequenceLength:$,totalSequenceLength:C,maxSequenceLength:b,inputHiddenSize:m,hiddenSize:l,vHiddenSize:y,headSize:Math.floor(l/t.numHeads),vHeadSize:Math.floor(y/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:E,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},qi=(e,t,r,a)=>{let i=Xe(a),n=64,s=a/i;s{let f=pe("x",t.dataType,t.dims,i),y="thread_max_vector";i===2?y="max(thread_max_vector.x, thread_max_vector.y)":i===4&&(y="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let $=vt(t.dataType),x=[{name:"d_inv",type:$},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return` + var wgMax: array; + var wgSum: array; + ${l.registerUniforms(x).declareVariables(f)} + ${l.mainStart([n,1,1])} + let localOffset = local_idx * uniforms.elements_per_wg; + let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset; + + var thread_max_vector = ${Ze("f32",i,"-3.402823e+38f")}; + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + thread_max_vector = max(${bt($,i,"x[offset + i]")}, thread_max_vector); + } + wgMax[local_idx] = ${y}; + workgroupBarrier(); + + var maxValue = -3.402823e+38f; + for (var i = 0u; i < ${n}; i++) { + maxValue = max(wgMax[i], maxValue); + } + + var sumVector = ${Ze("f32",i,"0")}; + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + sumVector += exp(${bt($,i,"x[offset + i]")} - maxValue); + } + wgSum[local_idx] = ${yt("sumVector",i)}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${n}; i++) { + sum += wgSum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + x[offset + i] = ${Ze("f32",i,"uniforms.d_inv")}; + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { + let f32input = ${bt($,i,"x[offset + i]")}; + x[offset + i] = ${f.type.value}(exp(f32input - maxValue) / sum); + } + } + }`};e.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${n};${c};${i}`},getShaderSource:m,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:d})},{inputs:[t],outputs:[]})},ji=(e,t,r,a,i,n)=>{let s=[i.batchSize,i.numHeads,i.sequenceLength,i.kvSequenceLength+i.pastSequenceLength],u=n.scale===0?1/Math.sqrt(i.headSize):n.scale,d=Xe(i.headSize),c=i.headSize/d,m=12,l={x:Math.ceil(i.totalSequenceLength/m),y:Math.ceil(i.sequenceLength/m),z:i.batchSize*i.numHeads},f=ft(t.dataType),y=[{type:"uint32",data:i.sequenceLength},{type:"uint32",data:c},{type:"uint32",data:i.totalSequenceLength},{type:"uint32",data:i.kvSequenceLength},{type:f,data:u}],$=[t,r],x=b=>{let E=L("q",t.dataType,t.dims,d),T=L("key",r.dataType,r.dims,d),S=pe("output",t.dataType,s),B=tt(t.dataType),D=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:B}];return` + const beta: ${B} = 1.0; + const TILE_SIZE = ${m}u; + + var tileQ: array<${E.type.storage}, ${m*m}>; + var tileK: array<${E.type.storage}, ${m*m}>; + ${b.registerUniforms(D).declareVariables(E,T,S)} + ${b.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 lm = m + local_id.y; + let ln = n + local_id.x; + + let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K; + + var value = ${Ze(B,d)}; + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m + local_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x]; + } + workgroupBarrier(); + + for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:t.dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:y}),getShaderSource:x},{inputs:$,outputs:[-1]})[0];return qi(e,C,i.batchSize*i.numHeads*i.sequenceLength,i.totalSequenceLength),C},Ki=(e,t,r,a)=>{let i=[a.batchSize,a.sequenceLength,a.vHiddenSize],n=12,s={x:Math.ceil(a.vHeadSize/n),y:Math.ceil(a.sequenceLength/n),z:a.batchSize*a.numHeads},u=[{type:"uint32",data:a.sequenceLength},{type:"uint32",data:a.totalSequenceLength},{type:"uint32",data:a.vHeadSize},{type:"uint32",data:a.numHeads},{type:"uint32",data:a.vHiddenSize}],d=c=>{let m=L("probs",t.dataType,t.dims),l=L("v",r.dataType,r.dims),f=pe("output",t.dataType,i),y=[{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 = ${n}u; + var tileQ: array<${m.type.value}, ${n*n}>; + var tileK: array<${m.type.value}, ${n*n}>; + ${c.registerUniforms(y).declareVariables(m,l,f)} + ${c.mainStart([n,n,1])} + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE + local_id.y; + let n = workgroup_id.x * TILE_SIZE + local_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + let offsetB = headIdx * (uniforms.N * uniforms.K) + n; + + var value = ${m.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:i,dataType:t.dataType,gpuDataType:0}],dispatchGroup:s,programUniforms:u}),getShaderSource:d},{inputs:[t,r],outputs:[0]})[0]},fn=(e,t,r,a,i,n,s,u,d,c,m)=>{let l=ji(e,t,r,d,c,m);Ki(e,l,a,c)},Yi=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],a=t.sequenceLength,i=t.inputHiddenSize,n=t.headSize,s=12,u={x:Math.ceil(t.headSize/s),y:Math.ceil(t.sequenceLength/s),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:"uint32",data:a},{type:"uint32",data:i},{type:"uint32",data:n},{type:"uint32",data:t.numHeads},{type:"uint32",data:t.headSize},{type:"uint32",data:t.hiddenSize},{type:"uint32",data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=l=>{let f=pe("output_q",d[0].dataType,r),y=pe("output_k",d[0].dataType,r),$=pe("output_v",d[0].dataType,r),x=L("input",d[0].dataType,d[0].dims),C=L("weight",d[1].dataType,d[1].dims),b=L("bias",d[2].dataType,d[2].dims),E=x.type.storage,T=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${s}u; + var tileInput: array<${E}, ${s*s}>; + var tileWeightQ: array<${E}, ${s*s}>; + var tileWeightK: array<${E}, ${s*s}>; + var tileWeightV: array<${E}, ${s*s}>; + ${l.registerUniforms(T).declareVariables(x,C,b,f,y,$)} + ${l.mainStart([s,s,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE + local_id.y; + let n = workgroup_id.x * TILE_SIZE + local_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${E}(0); + var valueK = ${E}(0); + var valueV = ${E}(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: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:u,programUniforms:c}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},al=(e,t)=>{let r=Fi(e.inputs,t),[a,i,n]=Yi(e,r);return fn(e,a,i,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),Zi,Xi,Qi,sl,rc=H(()=>{lt(),xe(),qe(),be(),Zi=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(a,i,n)=>{let s=i.length;if(s!==a.length)throw new Error(`${n}: num dimensions != ${s}`);i.forEach((u,d)=>{if(u!==a[d])throw new Error(`${n}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let a=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,a,"Invalid input scale"),r(e[2].dims,a,"Invalid input B"),r(e[3].dims,a,"Invalid input mean"),r(e[4].dims,a,"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")},Xi=(e,t)=>{let{epsilon:r,spatial:a,format:i}=t,n=e[0].dims,s=a?Xe(n[n.length-1]):1,u=i==="NHWC"&&n.length>1?s:1,d=F.size(n)/s,c=Fe(n.length)&&a,m=c?n.length:n,l=L("x",e[0].dataType,e[0].dims,s),f=L("scale",e[1].dataType,e[1].dims,u),y=L("bias",e[2].dataType,e[2].dims,u),$=L("inputMean",e[3].dataType,e[3].dims,u),x=L("inputVar",e[4].dataType,e[4].dims,u),C=pe("y",e[0].dataType,m,s),b=()=>{let T="";if(a)T=`let cOffset = ${n.length===1?"0u":i==="NHWC"?`outputIndices[${n.length-1}] / ${s}`:"outputIndices[1]"};`;else if(i==="NCHW")T=` + ${C.indicesSet("outputIndices","0","0")} + let cOffset = ${C.indicesToOffset("outputIndices")};`;else{T=`var cIndices = ${f.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let S=1;S` + const epsilon = ${r}; + ${T.registerUniform("outputSize","u32").declareVariables(l,f,y,$,x,C)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${C.offsetToIndices(`global_idx * ${s}`)}; + ${b()} + let scale = ${f.getByOffset("cOffset")}; + let bias = ${y.getByOffset("cOffset")}; + let inputMean = ${$.getByOffset("cOffset")}; + let inputVar = ${x.getByOffset("cOffset")}; + let x = ${l.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${C.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${a}_${s}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:"uint32",data:d},...Y(n)]:[{type:"uint32",data:d}]})}},Qi=e=>Be(e),sl=(e,t)=>{let{inputs:r,outputCount:a}=e,i=Qi({...t,outputCount:a});if(Oe.webgpu.validateInputContent&&Zi(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Xi(r,i))}}),Ji,es,ol,nc=H(()=>{xe(),be(),Ji=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")},es=e=>{let t=e[0].dims,r=e[0].dims[2],a=F.size(t)/4,i=e[0].dataType,n=L("input",i,t,4),s=L("bias",i,[r],4),u=L("residual",i,t,4),d=pe("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:c=>` + const channels = ${r}u / 4; + ${c.declareVariables(n,s,u,d)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let value = ${n.getByOffset("global_idx")} + + ${s.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${d.setByOffset("global_idx","value")} + }`}},ol=e=>{Ji(e.inputs),e.compute(es(e.inputs))}}),ts,Te,ul,ll,dl,pl,cl,hl,fl,ml,gl,rs,yl,wl,$l,vl,an,bl,sn,_l,xl,Sl,El,Il,Cl,Tl,Al,Ol,kl,Rl,zl,Bl,Ml,Dl,Pl,Nl,Wl=H(()=>{De(),xe(),qe(),be(),ts=(e,t,r,a,i,n)=>{let s=Math.ceil(t/4),u="";typeof i=="string"?u=`${i}(a)`:u=i("a");let d=L("inputData",r,[s],4),c=pe("outputData",a,[s],4);return` + ${e.registerUniform("vec_size","u32").declareVariables(d,c)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${d.getByOffset("global_idx")}; + ${c.setByOffset("global_idx",u)} + }`},Te=(e,t,r,a,i,n=e.dataType)=>({name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:s=>ts(s,F.size(e.dims),e.dataType,n,r,a),getRunData:s=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(F.size(s[0].dims)/64/4)},programUniforms:[{type:"uint32",data:Math.ceil(F.size(e.dims)/4)}]})}),ul=e=>{e.compute(Te(e.inputs[0],"Abs","abs"))},ll=e=>{e.compute(Te(e.inputs[0],"Acos","acos"))},dl=e=>{e.compute(Te(e.inputs[0],"Acosh","acosh"))},pl=e=>{e.compute(Te(e.inputs[0],"Asin","asin"))},cl=e=>{e.compute(Te(e.inputs[0],"Asinh","asinh"))},hl=e=>{e.compute(Te(e.inputs[0],"Atan","atan"))},fl=e=>{e.compute(Te(e.inputs[0],"Atanh","atanh"))},ml=e=>Be(e),gl=(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(Te(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},rs=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Sa,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:Ea;return Be({min:t,max:r})},yl=(e,t)=>{let r=e.inputs.length===1?t:rs(e.inputs),a=vt(e.inputs[0].dataType);e.compute(Te(e.inputs[0],"Clip",i=>`clamp(${i}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${a}> = vec4(${a}(${r.min})); + const clip_max_: vec4<${a}> = vec4(${a}(${r.max})); +`,r.cacheKey),{inputs:[0]})},wl=e=>{e.compute(Te(e.inputs[0],"Ceil","ceil"))},$l=e=>{e.compute(Te(e.inputs[0],"Cos","cos"))},vl=e=>{e.compute(Te(e.inputs[0],"Cosh","cosh"))},an=e=>Be(e),bl=(e,t)=>{let r=vt(e.inputs[0].dataType);e.compute(Te(e.inputs[0],"Elu",a=>`elu_vf32(${a})`,` + const elu_alpha_ = ${r}(${t.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)); + }`,t.cacheKey))},sn=(e,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: ${e}) -> ${e} { + 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)); +}`,_l=e=>{let t=vt(e.inputs[0].dataType);e.compute(Te(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,sn(`vec4<${t}>`,t)))},xl=e=>{e.compute(Te(e.inputs[0],"Exp","exp"))},Sl=e=>{e.compute(Te(e.inputs[0],"Floor","floor"))},El=e=>{let t=vt(e.inputs[0].dataType);e.compute(Te(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,sn(`vec4<${t}>`,t)))},Il=(e,t)=>{let r=vt(e.inputs[0].dataType);e.compute(Te(e.inputs[0],"LeakyRelu",a=>`select(leaky_relu_alpha_ * ${a}, ${a}, ${a} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Cl=e=>{e.compute(Te(e.inputs[0],"Not",t=>`!${t}`))},Tl=e=>{e.compute(Te(e.inputs[0],"Neg",t=>`-${t}`))},Al=e=>{e.compute(Te(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Ol=e=>{let t=vt(e.inputs[0].dataType);e.compute(Te(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},kl=e=>{e.compute(Te(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Rl=e=>{e.compute(Te(e.inputs[0],"Sin","sin"))},zl=e=>{e.compute(Te(e.inputs[0],"Sinh","sinh"))},Bl=e=>{e.compute(Te(e.inputs[0],"Sqrt","sqrt"))},Ml=e=>{e.compute(Te(e.inputs[0],"Tan","tan"))},Dl=e=>{e.compute(Te(e.inputs[0],"Tanh","tanh"))},Pl=(e,t)=>{let r=vt(e.inputs[0].dataType);return e.compute(Te(e.inputs[0],"ThresholdedRelu",a=>`select(vec4<${r}>(0.0), ${a}, ${a} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},Nl=e=>{e.compute(Te(e.inputs[0],"Log","log"))}}),ns,as,Ul,ac=H(()=>{xe(),be(),Wl(),ns=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")},as=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=L("input",e[0].dataType,e[0].dims,4),a=L("bias",e[0].dataType,[e[0].dims[2]],4),i=pe("output",e[0].dataType,t,4),n=F.size(t)/4,s=tt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(r,a,i)} + + ${sn(`vec4<${s}>`,s)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(n)} + 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); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Ul=e=>{ns(e.inputs),e.compute(as(e.inputs))}}),is,ss,ot,Vl,Hl,Ll,Gl,Fl,ql,jl,Kl,Yl,Zl,ic=H(()=>{De(),xe(),be(),is=(e,t,r,a,i,n,s,u,d,c,m,l,f)=>{let y,$;typeof u=="string"?y=$=(D,U)=>`${u}((${D}),(${U}))`:typeof u=="function"?y=$=u:(y=u.scalar,$=u.vector);let x=l?t.length:t,C=l?r.length:r,b=l?a.length:a,E=pe("outputData",m,b,4),T=L("aData",d,x,4),S=L("bData",c,C,4),B;if(i)if(n){let D=F.size(t)===1,U=F.size(r)===1,P=t.length>0&&t[t.length-1]%4===0,G=r.length>0&&r[r.length-1]%4===0;D||U?B=E.setByOffset("global_idx",$(D?`${T.type.value}(${T.getByOffset("0")}.x)`:T.getByOffset("global_idx"),U?`${S.type.value}(${S.getByOffset("0")}.x)`:S.getByOffset("global_idx"))):B=` + let outputIndices = ${E.offsetToIndices("global_idx * 4u")}; + let offsetA = ${T.broadcastedIndicesToOffset("outputIndices",E)}; + let offsetB = ${S.broadcastedIndicesToOffset("outputIndices",E)}; + ${E.setByOffset("global_idx",$(s||P?T.getByOffset("offsetA / 4u"):`${T.type.value}(${T.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||G?S.getByOffset("offsetB / 4u"):`${S.type.value}(${S.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else B=E.setByOffset("global_idx",$(T.getByOffset("global_idx"),S.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let D=(U,P,G="")=>{let K=`aData[indexA${P}][componentA${P}]`,R=`bData[indexB${P}][componentB${P}]`;return` + let outputIndices${P} = ${E.offsetToIndices(`global_idx * 4u + ${P}u`)}; + let offsetA${P} = ${T.broadcastedIndicesToOffset(`outputIndices${P}`,E)}; + let offsetB${P} = ${S.broadcastedIndicesToOffset(`outputIndices${P}`,E)}; + let indexA${P} = offsetA${P} / 4u; + let indexB${P} = offsetB${P} / 4u; + let componentA${P} = offsetA${P} % 4u; + let componentB${P} = offsetB${P} % 4u; + ${U}[${P}] = ${G}(${y(K,R)}); + `};m===9?B=` + var data = vec4(0); + ${D("data",0,"u32")} + ${D("data",1,"u32")} + ${D("data",2,"u32")} + ${D("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:B=` + ${D("outputData[global_idx]",0)} + ${D("outputData[global_idx]",1)} + ${D("outputData[global_idx]",2)} + ${D("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(T,S,E)} + + ${f??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${B} + }`},ss=(e,t,r,a,i,n,s=r.dataType)=>{let u=!F.areEqual(r.dims,a.dims),d=r.dims,c=F.size(r.dims),m=!1,l=!1,f=[u];if(u){let $=Zt.calcShape(r.dims,a.dims,!1);if(!$)throw new Error("Can't perform binary op on the given tensors");d=$,c=F.size(d);let x=F.size(r.dims)===1,C=F.size(a.dims)===1,b=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,E=a.dims.length>0&&a.dims[a.dims.length-1]%4===0;f.push(x),f.push(C),f.push(b),f.push(E);let T=1;for(let S=1;S$.toString()).join("_"),inputDependencies:y?["rank","rank"]:["dims","dims"]},getShaderSource:$=>is($,r.dims,a.dims,d,m,u,l,i,r.dataType,a.dataType,s,y,n),getRunData:()=>({outputs:[{dims:d,dataType:s}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:y?[{type:"uint32",data:Math.ceil(F.size(d)/4)},...Y(r.dims),...Y(a.dims),...Y(d)]:[{type:"uint32",data:Math.ceil(F.size(d)/4)}]})}},ot=(e,t,r,a,i,n)=>{e.compute(ss(t,i??"",e.inputs[0],e.inputs[1],r,a,n))},Vl=e=>{ot(e,"Add",(t,r)=>`${t}+${r}`)},Hl=e=>{ot(e,"Div",(t,r)=>`${t}/${r}`)},Ll=e=>{ot(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Gl=e=>{ot(e,"Mul",(t,r)=>`${t}*${r}`)},Fl=e=>{let t=L("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ot(e,"Pow",{scalar:(r,a)=>`pow_custom(${r},${a})`,vector:(r,a)=>`pow_vector_custom(${r},${a})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + 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)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + 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)); + } + `)},ql=e=>{ot(e,"Sub",(t,r)=>`${t}-${r}`)},jl=e=>{ot(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Kl=e=>{ot(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Yl=e=>{ot(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Zl=e=>{ot(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),os,us,ls,ds,Xl,Ql,sc=H(()=>{xe(),qe(),be(),os=e=>{if(!e||e.length<1)throw new Error("too few inputs");let t=e[0].dataType,r=e[0].dims.length;for(let a of e){if(a.dataType!==t)throw new Error("input tensors should be one type");if(a.dims.length!==r)throw new Error("input tensors should have the same shape")}},us=(e,t)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${t}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,ls=(e,t)=>{let r=e.length,a=[];for(let i=0;i{let r=e[0].dims.slice();if(t>=r.length||t<-1*r.length)throw new Error("axis specified for concat doesn't match input dimensionality");let a=t<0?r.length+t:t,i=r.slice(0);for(let S=1;S`uniforms.sizeInConcatAxis${S}`).join(","),T=S=>` + + ${(()=>{S.registerUniform("outputSize","u32");for(let B=0;B(${E}); + ${b} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${ls(u,C)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:y}),getShaderSource:T}},Xl=(e,t)=>{os(e.inputs),e.compute(ds(e.inputs,t.axis))},Ql=e=>Be({axis:e.axis})}),Jt,Ta,Wt=H(()=>{xe(),Jt=(e,t)=>{switch(e.activation){case"Relu":return{activationFunction:"",applyActivation:`value = max(value, ${t}(0.0));`};case"Sigmoid":return{activationFunction:"",applyActivation:`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`};case"Clip":return{activationFunction:`const clip_min_=${t}(${e.clipMin});const clip_max_=${t}(${e.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},Ta=e=>{let t=e?.activation||"";if(t==="Clip"){let[r,a]=e?.activation_params||[Sa,Ea];return{activation:t,clipMax:a,clipMin:r,activationCacheKey:`${t}:${r},${a}`}}return{activation:t,activationCacheKey:t}}}),je,Aa,Oa=H(()=>{je=(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.`)}},Aa=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),ka,Jl=H(()=>{ka=e=>` +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(${e}.x), i32(${e}.y), i32(${e}.z), 1)); +} +`}),ps,cs,mn,zn,hs,gn,fs,Ra,yn=H(()=>{xe(),be(),Wt(),Oa(),ps=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${t?", batchIndices":""}); + `,cs=(e,t)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${t===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]; + ${t===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]; + ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,mn=(e,t,r="f32",a,i=!1,n=32,s=!1,u=32)=>{let d=t[1]*e[1],c=t[0]*e[0],m=i?d:n,l=i?n:d,f=m/t[0],y=n/t[1];if(!((i&&f===4&&e[1]===4||!i&&(f===3||f===4))&&m%t[0]===0&&n%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${f} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${f} must be 3 or 4. + tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${m/f}>, ${l}>; +var mm_Bsub: array, ${c/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${f}; +const tileInner = ${n}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${s?"0":"i32(globalId.z)"}; + ${a?`let batchIndices = ${a.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${d}; + + let numTiles = ${s?`${Math.ceil(u/n)}`:"(uniforms.dimInner - 1) / tileInner + 1"}; + var kStart = ${s?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${y}; + for (var t = 0; t < numTiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${ps(i,a)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${y}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${a?", 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]; + ${f===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${cs(i,f)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},zn=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${t?", batchIndices":""}); + `,hs=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",gn=(e,t,r="f32",a,i=!1,n=32,s=!1,u=32,d=!1)=>{let c=e[1]*t[1],m=e[0]*t[0],l=i?c:n,f=i?n:c;if(!(f%t[1]===0&&l%t[0]===0&&n%t[1]===0))throw new Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${l} must be divisible by workgroupSize[0]${t[0]}, tileInner ${n} must be divisible by workgroupSize[1]${t[1]}`);let y=f/t[1],$=l/t[0],x=n/t[1],C=d?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${c}; + let globalColStart = i32(workgroupId.x) * ${m}; + + // Loop over shared dimension. + for (var t = 0; t < numTiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${l}; inputCol = inputCol + ${t[0]}) { + ${zn(i,a)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${a?", 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 * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[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 * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[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) * ${c}; + +let tileRowA = i32(localId.y) * ${y}; +let tileColA = i32(localId.x) * ${$}; +let tileRowB = i32(localId.y) * ${x}; +// Loop over shared dimension. +for (var t = 0; t < numTiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${y}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${$}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${zn(i,a)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${x}; 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${a?", 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) { + ${hs(i)} + 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, ${f}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${s?"0":"i32(globalId.z)"}; + ${a?`let batchIndices = ${a.offsetToIndices("u32(batch)")};`:""} + let numTiles = ${s?`${Math.ceil(u/n)}`:"(uniforms.dimInner - 1) / tileInner + 1"}; + var kStart = ${s?`i32(globalId.z) * ${u}`:"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; + } + } + ${C} + } +`},fs=(e,t,r,a,i,n=!1)=>{let[s,u,d]=i,[c,m,l,f]=a,y=Tr(s,d),$=Tr(u,d),x=tt(a[0].type.tensor),C=()=>{let E=m.rank,T=c.rank,S=`var aIndices: ${m.type.indices};`;for(let B=E-2-1,D=T-1;B>=0;B--,D--)S+=` +aIndices[${B}] = ${T>1?`batchIndices[${D}]`:"batchIndices"};`;return y.forEach(B=>{S+=` +aIndices[${B}] = 0;`}),S+=` +aIndices[${E-2}] = u32(row); + aIndices[${E-1}] = u32(colIn);`,S},b=()=>{let E=l.rank,T=c.rank,S=`var bIndices: ${l.type.indices};`;for(let B=E-2-1,D=T-1;B>=0;B--,D--)S+=` +bIndices[${B}] = ${T>1?`batchIndices[${D}]`:"batchIndices"};`;return $.forEach(B=>{S+=` +bIndices[${B}] = 0;`}),S+=` +bIndices[${E-2}] = u32(row); + bIndices[${E-1}] = u32(colIn);`,S};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${je(e,x)} { + var value = ${je(e,x)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dimAOuter && col < uniforms.dimInner) + { + ${C()} + value = ${m.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${je(e,x)} { + var value = ${je(e,x)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dimInner && col < uniforms.dimBOuter) + { + ${b()} + value = ${l.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${je(e,x)}) { + let col = colIn * ${e}; + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${n?"bias[colIn]":`${je(e,x)}(bias[row])`};`:""} + ${r} + ${f.setByIndices("vec3(coords)","value")} + } + } + `},Ra=(e,t,r,a,i=!1)=>{let n=e[0].dims,s=e[1].dims,u=n.slice(0,-2),d=s.slice(0,-2),c=a?a.slice(0,-2):r.slice(0,-2),m=Fe(c.length),l=m?c.length:c,f=Ia("batchDims",e[0].dataType,l,1),y=F.size(c),$=n[n.length-2],x=n[n.length-1],C=s[s.length-1],b=x%4===0&&C%4===0,E=$<=8?[4,1,1]:[4,4,1],T=[8,8,1],S=[Math.ceil(C/T[0]/E[0]),Math.ceil($/T[1]/E[1]),Math.ceil(y/T[2]/E[2])],B=tt(e[0].dataType),D=b?4:1,U=[...u,$,x/D],P=Fe(U.length),G=P?U.length:U,K=[...d,x,C/D],R=Fe(K.length),j=R?K.length:K,me=[y,$,C/D],Q=L("a",e[0].dataType,G,D),Ce=L("b",e[1].dataType,j,D),ve=pe("result",e[0].dataType,me.length,D),we=[Q,Ce],ce=[{type:"int32",data:$},{type:"int32",data:C},{type:"int32",data:x}];m&&ce.push(...Y(c)),P&&ce.push(...Y(U)),R&&ce.push(...Y(K));let he=[];he.push(P?"rank":"dims"),he.push(R?"rank":"dims");let ge=e.length>2,{activationFunction:N,applyActivation:re}=Jt(t,ve.type.value),ye=fs(D,ge,re,[f,Q,Ce,ve],[u,d,c],i);if(ge){let Re=i?D:1;we.push(L("bias",e[2].dataType,e[2].dims.length,Re)),ce.push(...Y(e[2].dims)),he.push("rank")}ce.push(...Y(me));let Me=Re=>` + ${Re.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").registerInternalVariables(f).declareVariables(...we,ve)} + ${N} + ${ye} + ${b?mn(E,T,B,f):gn(E,T,B,f)} + `;return{name:"MatMul",shaderCache:{hint:t.activationCacheKey+`${E}${b}${i}`,inputDependencies:he},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:ce}),getShaderSource:Me}}}),ms,ed,oc=H(()=>{Nt(),be(),Wt(),Oa(),Jl(),yn(),ms=(e,t,r,a,i=!1,n,s=4,u=4,d=4,c="f32")=>{let m=K=>{switch(K){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${K} is not supported.`)}},l=K=>{switch(K){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${K} is not supported.`)}},f=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,y=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,$=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",x=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",C=e?"row":"col",b=e?"col":"row",E=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${C} / outWidth; + let outCol = ${C} % outWidth; + + let WRow = ${b} / (filterDims[1] * inChannels); + let WCol = ${b} / inChannels % filterDims[1]; + let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0]; + let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1]; + let xCh = ${b} % inChannels; + var resData = ${je(s,c)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${$} && xCol >= 0 && xCol < ${x}) { + ${f} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${m(s)} + } + return resData;`,T=e?t&&a?` + let col = colIn * ${s}; + ${E}`:` + let col = colIn * ${s}; + if (row < uniforms.dimAOuter && col < uniforms.dimInner) { + ${E} + } + return ${je(s,c)}(0.0);`:a&&r?` + let col = colIn * ${s}; + ${E}`:` + let col = colIn * ${s}; + if (row < uniforms.dimInner && col < uniforms.dimBOuter) { + ${E} + } + return ${je(s,c)}(0.0);`,S=`${l(u)}`,B=je(d,c),D=je(e?s:u,c),U=je(e?u:s,c),{activationFunction:P,applyActivation:G}=Jt(n,B);return` + ${P} + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${D} { + ${e?T:S} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${U} { + ${e?S:T} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${B}) { + let col = colIn * ${d}; + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${y} + ${Aa(i)} + ${G} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},ed=(e,t,r,a,i,n,s,u)=>{let d=t.format==="NHWC",c=d?e[0].dims[3]:e[0].dims[1],m=r[0],l=d?r[2]:r[3],f=d?r[1]:r[2],y=d?r[3]:r[1],$=d&&(c%4===0||c%3===0)&&y%4===0,x=d?y:l*f,C=d?l*f:y,b=[8,8,1],E=a<=8?[4,1,1]:[4,4,1],T=[Math.ceil(x/b[0]/E[0]),Math.ceil(C/b[1]/E[1]),Math.ceil(m/b[2]/E[2])];Ge("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let S=$?d&&c%4!==0?3:4:1,B=b[1]*E[1],D=b[0]*E[0],U=Math.max(b[0]*S,b[1]),P=a%B===0,G=i%D===0,K=n%U===0,R=$?[S,4,4]:[1,1,1],j=tt(e[0].dataType),me=$?4:1,Q=[{type:"int32",data:a},{type:"int32",data:i},{type:"int32",data:n}],Ce=L("x",e[0].dataType,e[0].dims.length,S===3?1:S),ve=L("w",e[1].dataType,e[1].dims.length,me),we=[Ce,ve];Q.push(...Y(e[0].dims)),Q.push(...Y(e[1].dims));let ce=` + fn setOutputAtIndex(flatIndex : i32, value : ${$?`vec4<${j}>`:j}) { + result[flatIndex] = ${$?`vec4<${j}>`:j}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${$?`vec4<${j}>`:j}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${$?"/ 4":""}, value); + }`;if(s){let ge=L("bias",e[2].dataType,e[2].dims.length,me);we.push(ge),Q.push(...Y(e[2].dims)),ce+=` + fn getBiasByOutputCoords(coords : vec4) -> ${$?`vec4<${j}>`:j} { + return bias[coords.${d?"w":"y"}${$?"/ 4":""}]; + }`}let he=pe("result",e[0].dataType,r.length,me);return Q.push(...Y(r)),{name:"Conv2DMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:Q}),getShaderSource:ge=>` + ${ka("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 }; + ${ge.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...we,he)} + const filterDims : vec2 = vec2(${t.kernelShape[0]}, ${t.kernelShape[1]}); + const pad : vec2 = vec2(${t.pads[0]}, ${t.pads[1]}); + const stride : vec2 = vec2(${t.strides[0]}, ${t.strides[1]}); + const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]}); + ${ce} + ${ms(d,P,G,K,s,t,R[0],R[1],R[2],j)} + ${$?mn(E,b,j,void 0,!d,U):gn(E,b,j,void 0,!d,U,!1,void 0,u)}`}}}),sa,uc=H(()=>{xe(),be(),nd(),Wt(),sa=(e,t,r)=>{let a=e.length>2,i=a?"value += b[output_channel];":"",n=e[0].dims,s=e[1].dims,u=s[0]/t.group,d=t.format==="NHWC",c=ua(n,s,t.dilations,t.pads,t.strides,d),m=F.size(c),l=pe("output",e[0].dataType,c),{activationFunction:f,applyActivation:y}=Jt(t,l.type.value),$=L("x",e[0].dataType,n),x=L("w",e[1].dataType,s),C=[$,x];a&&C.push(L("b",e[2].dataType,e[2].dims));let b=E=>` + const strides: vec2 = vec2(${t.strides[0]}u, ${t.strides[1]}u); + const pads: vec2 = vec2(${t.pads[0]}u, ${t.pads[1]}u); + + ${E.declareVariables(...C,l)} + + ${f} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes(m)} + + let outputIndices = ${l.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${d?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * strides - pads; + let group_id: u32 = output_channel / ${u}u; + + var value: ${l.type.value} = ${l.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < ${s[1]}u; wInChannel++) { + let input_channel = group_id * ${s[1]}u + wInChannel; + for (var wHeight: u32 = 0u; wHeight < ${s[2]}u; wHeight++) { + let xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}u; + + if (xHeight < 0u || xHeight >= ${n[d?1:2]}u) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < ${s[3]}u; wWidth++) { + let xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}u; + if (xWidth < 0u || xWidth >= ${n[d?2:3]}u) { + continue; + } + + let xVal = ${d?$.get("batch","xHeight","xWidth","input_channel"):$.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${x.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${i} + ${y} + ${l.setByOffset("global_idx","value")} + }`;return{name:"GroupedConv",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r?r(c):c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)}}),getShaderSource:b}}}),oa,gs,td,rd=H(()=>{xe(),yn(),be(),Wt(),oa=(e,t,r,a,i=!1)=>{let n=e[0].dims,s=e[1].dims,u=n[n.length-2],d=s[s.length-1],c=n[n.length-1],m=Xe(d),l=Xe(c),f=Xe(u),y=F.size(r)/m/f,$=e.length>2,x=a?a.slice(0,-2):r.slice(0,-2),C=[F.size(x),u,d],b=[{type:"uint32",data:y},{type:"uint32",data:u},{type:"uint32",data:d},{type:"uint32",data:c},...Y(x),...Y(n),...Y(s)];$&&b.push(...Y(e[2].dims)),b.push(...Y(C));let E=T=>{let S=Ia("batch_dims",e[0].dataType,x.length),B=L("a",e[0].dataType,n.length,l),D=L("b",e[1].dataType,s.length,m),U=pe("output",e[0].dataType,C.length,m),{activationFunction:P,applyActivation:G}=Jt(t,U.type.value),K=[B,D],R="";if($){let ce=i?m:1;K.push(L("bias",e[2].dataType,e[2].dims.length,ce)),R=`${i?`value += bias[col / ${ce}];`:`value += ${U.type.value}(bias[row + i]);`}`}let j=n.slice(0,-2),me=s.slice(0,-2),Q=Tr(j,x),Ce=Tr(me,x),ve=(ce,he)=>{let ge=ce.rank,N=ce.name;if(ge===2)return`var ${N}_indices = ${ce.type.indices}(0u, 0u);`;let re=S.rank,ye=`var ${N}_indices: ${ce.type.indices};`;for(let Me=ge-2-1,Re=re-1;Me>=0;Me--,Re--)ye+=` +${N}_indices[${Me}] = ${re>1?`batch_indices[${Re}]`:"batch_indices"};`;return he.forEach(Me=>{ye+=` +${N}_indices[${Me}] = 0;`}),ye+=`${N}_indices[${ge-2}] = 0u; + ${N}_indices[${ge-1}] = 0u;`,ye},we=()=>{let ce=`var a_data: ${B.type.value};`;for(let he=0;he; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { + ${we()} + } + for (var i = 0u; i < ${f}u; i++) { + var value = values[i]; + ${R} + ${G} + let cur_indices = ${U.type.indices}(batch, row + i, col); + let offset = ${U.indicesToOffset("cur_indices")}; + ${U.setByOffset(`offset / ${m}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activationCacheKey}_${m}_${l}_${f}_${i}`,inputDependencies:$?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:b}),getShaderSource:E}},gs=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.")},td=e=>{gs(e.inputs);let t=Zt.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],a=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&a<8?e.compute(oa(e.inputs,{activation:"",activationCacheKey:""},t)):e.compute(Ra(e.inputs,{activation:"",activationCacheKey:""},t))}}),ua,Bn,ys,Mn,la,ws,$s,da,nd=H(()=>{xe(),qe(),oc(),yn(),uc(),Wt(),rd(),Or(),ua=(e,t,r,a,i,n)=>{let s=e[0],u=e.slice(n?1:2,n?3:4),d=u.length,c=t[0],m=t.slice(2).map((f,y)=>f+(f-1)*(r[y]-1)),l=u.map((f,y)=>f+a[y]+a[y+d]).map((f,y)=>Math.floor((f-m[y]+i[y])/i[y]));return l.splice(0,0,s),l.splice(n?3:1,0,c),l},Bn=[2,3,1,0],ys=(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],a=e[1].dims[1]*t.group;if(r!==a)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")},Mn=(e,t)=>{let r=e.kernelShape.slice();for(let n=2;n{let t=Ta(e),r=e.format,a=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,n=e.group,s=e.kernel_shape,u=e.pads,d=e.strides,c=e.w_is_const();return Be({autoPad:a,format:r,dilations:i,group:n,kernelShape:s,pads:u,strides:d,wIsConst:c,...t})},ws=(e,t,r)=>{let a=Mn(r,t),i=r.format==="NHWC";if(r.group!==1){e.compute(sa(t,a));return}let n=t.length===3,s=t[0].dims[i?1:2],u=t[0].dims[i?2:3],d=t[0].dims[i?3:1],c=t[1].dims[2],m=t[1].dims[3],l=ua(t[0].dims,t[1].dims,r.dilations,a.pads,r.strides,i),f=l[i?1:2],y=l[i?2:3],$=l[i?3:1],x=i&&c===s&&m===u&&r.pads[0]===0&&r.pads[1]===0;if(x||c===1&&m===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let D=l[0],U,P,G,K=[];if(i){let me=e.kernelCustomData.wT??e.compute(Tt(t[1],Bn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=me),x){let Q=s*u*d;U=t[0].reshape([1,D,Q]),P=me.reshape([1,Q,$]),G=[1,D,$]}else U=t[0].reshape([D,s*u,d]),P=me.reshape([1,d,$]),G=[D,f*y,$];K.push(U),K.push(P)}else U=t[0].reshape([D,d,s*u]),P=t[1].reshape([1,$,d]),G=[D,$,f*y],K.push(P),K.push(U);n&&K.push(t[2]);let R=G[2],j=K[0].dims[K[0].dims.length-1];R<8&&j<8?e.compute(oa(K,a,l,G,i),{inputs:K}):e.compute(Ra(K,a,l,G,i),{inputs:K});return}let C=!0,b=e.kernelCustomData.wT??e.compute(Tt(t[1],Bn),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=b);let E=[t[0],b];n&&E.push(t[2]);let T=i?f*y:$,S=i?$:f*y,B=c*m*d;e.compute(ed(E,a,l,T,S,B,n,C),{inputs:E})},$s=(e,t)=>{let r=t.format==="NHWC",a=[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&&a.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],n=[1].concat(t.strides),s=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=Mn({...t,pads:i,strides:n,dilations:s,kernelShape:u},a);e.compute(sa(a,d,c=>r?[c[0],c[2],c[3]]:[]))},da=(e,t)=>{ys(e.inputs,t),e.inputs[0].dims.length===3?$s(e,t):ws(e,e.inputs,t)}}),vs,ad,lc=H(()=>{Nt(),be(),Wt(),Oa(),Jl(),yn(),vs=(e,t=!1,r,a=4)=>{let i=je(a,"f32"),n=b=>{switch(b){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` + let coord1 = vec4(coordX, coordY, col + 1, rowInner); + let coord2 = vec4(coordX, coordY, col + 2, rowInner); + let coord3 = vec4(coordX, coordY, col + 3, rowInner); + let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; + let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; + let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; + let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; + return vec4(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${b} is not supported.`)}},s=e?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,u=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,d=e?"outBackprop[1]":"outBackprop[2]",c=e?"outBackprop[2]":"outBackprop[3]",m=e?"row":"col",l=e?"col":"row",f=` + let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"}; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${m} / outWidth; + let outCol = ${m} % outWidth; + + let WRow = ${l} / (filterDims[1] * inChannels); + let WCol = ${l} / inChannels % filterDims[1]; + let xR = f32(outRow - pads[0] + dilation[0] * WRow) / f32(strides[0]); + let xC = f32(outCol - pads[1] + dilation[1] * WCol) / f32(strides[1]); + if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) { + return ${i}(0.0); + } + if (xC < 0.0 || xC >= f32(${c}) || fract(xC) > 0.0) { + return ${i}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${l} % inChannels; + ${s} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${a}];`,y=e?` + let col = colIn * ${a}; + if (row < uniforms.dimAOuter && col < uniforms.dimInner) { + ${f} + } + return ${i}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dimInner && col < uniforms.dimBOuter) { + ${f} + } + return ${i}(0.0);`,$=` + let col = colIn * ${a}; + let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"}; + let coordX = filterDims.x - 1 - row / (filterDims[1] * inChannels); + let coordY = filterDims.y - 1 - (row / inChannels) % filterDims[1]; + if (${e?"row < uniforms.dimInner && col < uniforms.dimBOuter":"row < uniforms.dimInner && col < uniforms.dimAOuter"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4(coordX, coordY, col, rowInner); + ${n(a)} + } + return ${i}(0.0); + `,{activationFunction:x,applyActivation:C}=Jt(r,i);return` + ${x} + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${i} { + ${e?y:$} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${i} { + ${e?$:y} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${i}) { + let col = colIn * ${a}; + if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { + var value = valueInput; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${u} + ${Aa(t)} + ${C} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${a}] = value; + } + }`},ad=(e,t,r,a,i,n,s,u)=>{let d=t.format==="NHWC",c=d?e[0].dims[3]:e[0].dims[1],m=r[0],l=d?r[2]:r[3],f=d?r[1]:r[2],y=d?r[3]:r[1],$=d?c%4===0&&y%4===0:l%4===0&&y%4===0,x=d?y:l*f,C=d?l*f:y,b=$?[8,8,1]:[x<=4||C<=4?4:16,x>4&&C<=4?4:16,1],E=$?[4,4,1]:[x<=4?1:4,x>4&&C<=4?1:4,1],T=[Math.ceil(x/b[0]/E[0]),Math.ceil(C/b[1]/E[1]),Math.ceil(m/b[2]/E[2])];Ge("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${T}`);let S=$?4:1,B=Math.max(b[0]*S,b[1]),D=$?4:1,U=[{type:"int32",data:a},{type:"int32",data:i},{type:"int32",data:n}],P=L("x",e[0].dataType,e[0].dims.length,D),G=L("w",e[1].dataType,e[1].dims.length,1),K=pe("result",e[0].dataType,r.length,D),R=[P,G];U.push(...Y(e[0].dims)),U.push(...Y(e[1].dims));let j="";if(s){let me=L("bias",e[2].dataType,e[2].dims.length,D);R.push(me),U.push(...Y(e[2].dims)),j+=` + fn getBiasByOutputCoords(coords : vec4) -> ${$?"vec4":"f32"} { + return bias[coords.${d?"w":"y"}${$?"/ 4":""}]; + }`}return U.push(...Y(r)),{name:"Conv2DTransposeMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:U}),getShaderSource:me=>` + ${ka("uniforms.result_strides")} + ${me.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...R,K)}; + const outBackprop : vec4 = vec4(${e[0].dims.join(",")}); + const filterDims : vec2 = vec2(${t.kernelShape[d?1:2]}, ${t.kernelShape[d?2:3]}); + const effectiveFilterDims : vec2 = filterDims + vec2( + ${t.dilations[0]<=1?0:(t.kernelShape[d?1:2]-1)*(t.dilations[0]-1)}, + ${t.dilations[1]<=1?0:(t.kernelShape[d?2:3]-1)*(t.dilations[1]-1)}); + const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${t.pads[0]+t.pads[2]})/2, + i32(effectiveFilterDims[1]) - 1 - (${t.pads[1]+t.pads[3]})/2); + const strides : vec2 = vec2(${t.strides[0]}, ${t.strides[1]}); + const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]}); + const dimAOuter : i32 = ${a}; + const dimBOuter : i32 = ${i}; + const dimInner : i32 = ${n}; + ${j} + ${vs(d,s,t,S)} + ${$?mn(E,b,"f32",void 0,!d,B):gn(E,b,"f32",void 0,!d,B,!1,void 0,u)}`}}}),bs,pa,dc=H(()=>{Nt(),xe(),be(),bs=(e,t,r,a,i,n,s=!1,u)=>{let d=r.format==="NHWC",c=d?1:2,m=d?2:3,l=d?3:1,f=F.size(a),y=s?2:1,$=r.group,x=t[1].dims,C=x[0]/$,b=x[1],E=` + fn setOutputAtIndex(flatIndex : u32, value : ${s?`vec4<${u}>`:u}) { + result[flatIndex] = ${s?`vec4<${u}>`:u}(value); + }`;i&&(E+=` + fn getBiasByOutputCoords(coords : vec4) -> ${s?`vec4<${u}>`:u} { + return bias[coords.${d?"w":"y"}${s?"/ 4":""}]; + }`);let T=s?4:1,S=L("W",t[1].dataType,t[1].dims,T),B=L("Dy",t[0].dataType,t[0].dims,T),D=[B,S];i&&D.push(L("bias",t[2].dataType,[a[l]],T));let U=pe("result",t[0].dataType,a,T),P=`{ + let batch: u32 = ${n?"global_id.z":"workgroup_id.z"} / outShape[1]; + let r = ${n?"global_id.z":"workgroup_id.z"} % outShape[1]; + let c = ${n?"global_id.y":"workgroup_id.y"} * ${y}; + let d1: u32 = ${n?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2(i32(r), i32(c)) - vec2(pads); + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${y}>; + for (var i = 0; i < ${y}; i++) { + dotProd[i] = vec4<${u}>(0.0); + } + for (var wR: u32 = 0; wR < filterDims[0]; wR = wR + 1) { + var dyR = (${u}(dyCorner.x) + ${u}(wR)) / ${u}(strides.x); + let wRPerm = filterDims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${u}(outBackprop[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < filterDims[1]; wC = wC + 1) { + let dyC = (${u}(dyCorner.y) + ${u}(wC)) / ${u}(strides.y); + let dyC2 = (${u}(dyCorner.y) + 1.0 + ${u}(wC)) / ${u}(strides.y); + let wCPerm = filterDims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${u}(outBackprop[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${u}(outBackprop[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = outBackprop[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${B.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${u}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${B.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${u}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = outBackprop[${l}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${B.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${u}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = outBackprop[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${B.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${u}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${y}; i = i + 1) { + let value = dotProd[i] + ${i?"bias[c+i]":`vec4<${u}>(0.0)`}; + ${U.set("batch","r","c + i","d1","value")}; + } + }`,G=` + let outputIndices = ${U.offsetToIndices("global_idx")}; + let batch = ${U.indicesGet("outputIndices",0)}; + let d1 = ${U.indicesGet("outputIndices",l)}; + let r = ${U.indicesGet("outputIndices",c)}; + let c = ${U.indicesGet("outputIndices",m)}; + let dyCorner = vec2(i32(r), i32(c)) - pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / ${b}; + let wOutChannel = d1 - groupId * ${b}; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${u}(0.0); + for (var wR: u32 = 0; wR < effectiveFilterDims.x; wR = wR + 1) { + if (wR % dilations.x != 0) { + continue; + } + let dyR = (${u}(dyRCorner) + ${u}(wR)) / ${u}(strides[0]); + let wRPerm = filterDims.x - 1 - wR / dilations.x; + if (dyR < 0.0 || dyR >= ${u}(outBackprop[${c}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < effectiveFilterDims.y; wC = wC + 1) { + if (wC % dilations.y != 0) { + continue; + } + let dyC = (${u}(dyCCorner) + ${u}(wC)) / ${u}(strides.y); + let wCPerm = filterDims.y - 1 - wC / dilations.y; + if (dyC < 0.0 || dyC >= ${u}(outBackprop[${m}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * ${C}; + for (var d2: u32 = 0; d2 < ${C}; d2 = d2 + 1) { + let xValue = ${d?B.get("batch","idyR","idyC","inputChannel"):B.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${S.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${i?"bias[d1]":`${u}(0.0)`}; + ${U.setByOffset("global_idx","value")}; + `;return` + ${e.declareVariables(...D,U)} + ${E} + const outShape : vec4 = vec4(${a.join(",")}); + const outBackprop : vec4 = vec4(${t[0].dims.join(",")}); + const strides : vec2 = vec2(${r.strides[0]}, ${r.strides[1]}); + const filterDims : vec2 = vec2(${r.kernelShape[d?1:2]}, ${r.kernelShape[d?2:3]}); + const dilations : vec2 = vec2(${r.dilations[0]}, ${r.dilations[1]}); + const effectiveFilterDims : vec2 = filterDims + vec2( + ${r.dilations[0]<=1?0:(r.kernelShape[d?1:2]-1)*(r.dilations[0]-1)}, + ${r.dilations[1]<=1?0:(r.kernelShape[d?2:3]-1)*(r.dilations[1]-1)}); + const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${r.pads[0]+r.pads[2]})/2, + i32(effectiveFilterDims[1]) - 1 - (${r.pads[1]+r.pads[3]})/2); + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes(f)}; + ${s?P:G}}`},pa=(e,t,r)=>{let a=e.length>2,i=t.outputShape,n=F.size(i),s=[Math.ceil(n/64),1,1];Ge("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let u=tt(e[0].dataType);return{name:"ConvTranspose2D",shaderCache:{hint:t.cacheKey},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}]}),getShaderSource:d=>bs(d,e,t,i,a,s[1]===1&&s[2]===1,!1,u)}}}),_s,xs,Ss,Dn,id,Es,Is,Cs,Ts,sd,pc=H(()=>{qe(),lc(),dc(),Wt(),Or(),_s=(e,t,r,a,i,n)=>(e-1)*t+r+(a-1)*i+1-n,xs=(e,t,r,a,i)=>{let n=Math.floor(e/2);t==="SAME_UPPER"?(r[a]=n,r[i]=e-n):t==="SAME_LOWER"&&(r[a]=e-n,r[i]=n)},Ss=(e,t,r,a,i,n,s,u,d,c)=>{let m=e.length-2,l=c.length===0;if(d.length===0)for(let $=0;${let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((f,y)=>f*y,1)===0){r.length=0;for(let f=2;ff+y,0)===0){let f=t[0].dims.length-2;d=new Array(f).fill(1)}let c=e.strides.slice();if(c.reduce((f,y)=>f+y,0)===0){let f=t[0].dims.length-2;c=new Array(f).fill(1)}Ss(u,r,d,e.autoPad,e.group,i,c,a,s,n);let m=Object.assign({},e),l=e.cacheKey+[r.join("n,"),i.join(","),c.join(","),s.join(","),n.join(","),d.join(",")].join("_");return Object.assign(m,{kernelShape:r,pads:i,outputPadding:s,outputShape:n,dilations:d,strides:c,cacheKey:l}),m},id=e=>{let t=Ta(e),r=e.format,a=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,n=e.group,s=e.kernelShape,u=e.pads,d=e.strides,c=e.wIsConst(),m=e.outputPadding,l=e.outputShape;return Be({autoPad:a,format:r,dilations:i,group:n,kernelShape:s,outputPadding:m,outputShape:l,pads:u,strides:d,wIsConst:c,...t})},Es=(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],a=e[1].dims[0];if(r!==a)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 n=e[0].dims.length-2;if(t.dilations.reduce((s,u)=>s+u,0)>0&&t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.reduce((s,u)=>s+u,0)>0&&t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.reduce((s,u)=>s+u,0)>0&&t.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(t.outputPadding.length!==n&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(t.kernelShape.reduce((s,u)=>s+u,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")},Is=[2,3,1,0],Cs=(e,t,r)=>{let a=Dn(r,t),i=r.format==="NHWC",n=a.outputShape,s=n[i?3:1],u=t[0].dims[i?3:1];if(a.group!==1||s===1&&u===1){e.compute(pa(t,a));return}let d=n[i?1:2],c=n[i?2:3],m=t[1].dims[2],l=t[1].dims[3],f=i?d*c:s,y=i?s:d*c,$=m*l*u,x=!0,C=e.kernelCustomData.wT??e.compute(Tt(t[1],Is),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=C);let b=[t[0],C],E=t.length===3;E&&(!i&&t[2].dims.length===1?b.push(t[2].reshape([t[2].dims[0],1,1])):b.push(t[2])),e.compute(ad(b,a,n,f,y,$,E,x),{inputs:b})},Ts=(e,t)=>{let r=t.format==="NHWC",a=[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]])];a.length===3&&a.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let n=t.dilations;(n.length===0||n[0]===0)&&(n=[1]);let s=t.strides;(s.length===0||s[0]===0)&&(s=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],s=[1].concat(s),n=[1].concat(n),i=[1].concat(i);let d=Dn({...t,pads:u,strides:s,dilations:n,kernelShape:i},a);e.compute(pa(a,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},sd=(e,t)=>{Es(e.inputs,t),e.inputs[0].dims.length===3?Ts(e,t):Cs(e,e.inputs,t)}}),As,od,ud,cc=H(()=>{De(),xe(),qe(),be(),As=(e,t,r,a)=>{let i=F.size(t),n=t.length,s=L("input",e,n),u=pe("output",e,n),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=F.normalizeAxis(d,n),m=l=>{let f=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,y=fe("uniforms.input_shape","uniforms.axis",n),$=a.reverse?f+(a.exclusive?" + 1":""):"0",x=a.reverse?y:f+(a.exclusive?"":" + 1");return` + ${l.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,u)} + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${$}; + let last : i32 = ${x}; + for (var i : i32 = first; i < last; i++) { + ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${s.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:a.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:"uint32",data:i},{type:"int32",data:c},...Y(t),...Y(t)]}),getShaderSource:m}},od=(e,t)=>{let r=e.inputs[0].dims,a=e.inputs[0].dataType,i=e.inputs[1];e.compute(As(a,r,i,t),{inputs:[0]})},ud=e=>{let t=e.exclusive===1,r=e.reverse===1;return Be({exclusive:t,reverse:r})}}),Qr,$r,Pn,Os,ks,Rs,zs,Nn,Bs,ld,dd,hc=H(()=>{xe(),qe(),be(),Qr="[a-zA-Z]|\\.\\.\\.",$r="("+Qr+")+",Pn="^"+$r+"$",Os="("+$r+",)*"+$r,ks="^"+Os+"$",Rs=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},zs=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,a]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(ks)))throw new Error("Invalid LHS term");if(r.split(",").forEach((i,n)=>{let s=e[n].dims.slice();if(!i.match(RegExp(Pn)))throw new Error("Invalid LHS term");let u=this.processTerm(i,!0,s,n);this.lhs.push(u)}),a==="")a+=[...this.symbolToInfo.entries()].filter(([i,n])=>n.count===1||i==="...").map(([i])=>i).join("");else if(!a.match(RegExp($r)))throw new Error("Invalid RHS");a.match(RegExp(Qr,"g"))?.forEach(i=>{if(i==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let n=this.symbolToInfo.get(i);if(n===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(n.dimValue)}}),this.rhs=this.processTerm(a,!1,this.outputDims)}addSymbol(e,t,r){let a=this.symbolToInfo.get(e);if(a!==void 0){if(a.dimValue!==t&&a.count!==1)throw new Error("Dimension mismatch");a.count++,a.inputIndices.push(r)}else a={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,a)}processTerm(e,t,r,a=-1){let i=r.length,n=!1,s=[],u=0;if(!e.match(RegExp(Pn))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Qr,"g")),c=new Rs(a);return d?.forEach((m,l)=>{if(m==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let f=i-d.length+1;if(f<0)throw new Error("Ellipsis out of bounds");if(s=r.slice(u,u+f),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=s;else throw new Error("Ellipsis must be specified in the LHS");for(let y=0;ye+"_max",Bs=(e,t,r,a,i)=>{let n=t.map((f,y)=>e[y]?f.length:f).map((f,y)=>L(`input${y}`,r,f)),s=F.size(i),u=Fe(i.length),d=u?i.length:i,c=pe("output",r,d),m=[...a.symbolToInfo.keys()].filter(f=>!a.rhs.symbolToIndices.has(f)),l=f=>{let y=[],$="var prod = 1.0;",x="var sum = 0.0;",C="sum += prod;",b=[],E=[],T=[],S=[],B=a.symbolToInfo.size===a.rhs.symbolToIndices.size;a.symbolToInfo.forEach((U,P)=>{if(a.rhs.symbolToIndices.has(P)){let G=a.rhs.symbolToIndices.get(P)?.[0];G!==void 0&&a.lhs.forEach((K,R)=>{if(U.inputIndices.includes(R)){let j=K.symbolToIndices.get(P);if(j===void 0)throw new Error("Invalid symbol error");j.forEach(me=>{y.push(`${n[R].indicesSet(`input${R}Indices`,me,c.indicesGet("outputIndices",G))}`)})}})}else a.lhs.forEach((G,K)=>{if(U.inputIndices.includes(K)){let R=G.symbolToIndices.get(P);if(R===void 0)throw new Error("Invalid symbol error");R.forEach(j=>{b.push(`${n[K].indicesSet(`input${K}Indices`,j,`${P}`)}`)}),S.push(`prod *= ${n[K].getByIndices(`input${K}Indices`)};`)}}),E.push(`for(var ${P}: u32 = 0; ${P} < uniforms.${Nn(P)}; ${P}++) {`),T.push("}")});let D=B?[...y,`let sum = ${n.map((U,P)=>U.getByIndices(`input${P}Indices`)).join(" * ")};`]:[...y,x,...E,...b,$,...S,C,...T];return` + ${f.registerUniforms(m.map(U=>({name:`${Nn(U)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,c)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${c.offsetToIndices("global_idx")}; + ${n.map((U,P)=>`var input${P}Indices: ${n[P].type.indices};`).join(` +`)} + ${D.join(` +`)}; + ${c.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:a.equation,inputDependencies:e.map(f=>f?"rank":"dims")},getRunData:()=>{let f=m.filter($=>a.symbolToInfo.has($)).map($=>({type:"uint32",data:a.symbolToInfo.get($)?.dimValue||0}));f.push({type:"uint32",data:s});let y=t.filter(($,x)=>e[x]).map(($,x)=>[...Y($)]).reduce(($,x)=>$.concat(x),f);return u&&y.push(...Y(i)),{outputs:[{dims:i,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:y}},getShaderSource:l}},ld=(e,t)=>{let r=new zs(e.inputs,t.equation),a=e.inputs.map((s,u)=>Fe(s.dims.length)),i=r.outputDims,n=e.inputs.map((s,u)=>s.dims);e.compute(Bs(a,n,e.inputs[0].dataType,r,i))},dd=e=>{let t=e.equation.replace(/\s+/g,"");return Be({equation:t})}}),Ms,Wn,Ds,Ps,pd,fc=H(()=>{De(),xe(),be(),Ms=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),a=r.length{let r=e.length-t.length,a=[];for(let i=0;ie.length>t.length?Wn(e,t):Wn(t,e),Ps=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),a=Ds(t,r),i=e[0].dataType,n=i===9?4:1,s=Math.ceil(F.size(a)/n),u=Fe(t.length),d=Fe(a.length),c=l=>{let f=u?t.length:t,y=d?a.length:a,$=L("input",i,f,n),x=pe("output",i,y,n),C;if(i===9){let b=(E,T,S="")=>` + let outputIndices${T} = ${x.offsetToIndices(`outputOffset + ${T}u`)}; + let offset${T} = ${$.broadcastedIndicesToOffset(`outputIndices${T}`,x)}; + let index${T} = offset${T} / 4u; + let component${T} = offset${T} % 4u; + ${E}[${T}] = ${S}(${$.getByOffset(`index${T}`)}[component${T}]); + `;C=` + let outputOffset = global_idx * ${n}; + var data = vec4(0); + ${b("data",0,"u32")} + ${b("data",1,"u32")} + ${b("data",2,"u32")} + ${b("data",3,"u32")} + ${x.setByOffset("global_idx","data")} + }`}else C=` + let outputIndices = ${x.offsetToIndices("global_idx")}; + let inputOffset = ${$.broadcastedIndicesToOffset("outputIndices",x)}; + ${x.setByOffset("global_idx",$.getByOffset("inputOffset"))} + }`;return` + ${l.registerUniform("vec_size","u32").declareVariables($,x)} + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${C}`},m=[{type:"uint32",data:s}];return u&&m.push(...Y(t)),d&&m.push(...Y(a)),{name:"Expand",shaderCache:{hint:`${a.length}`,inputDependencies:[u?"rank":"dims"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:m})}},pd=e=>{Ms(e.inputs),e.compute(Ps(e.inputs),{inputs:[0]})}}),Ns,Ws,cd,hd,mc=H(()=>{De(),xe(),qe(),be(),Ns=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ws=(e,t)=>{let r=e[0].dims,a=e[1].dims,i=r.length,n=F.normalizeAxis(t.axis,i),s=r.slice(0);s.splice(n,1,...a);let u=r[n],d=e[0].dataType===9?4:1,c=Math.ceil(F.size(s)/d),m=Fe(e[0].dims.length),l=m?e[0].dims.length:e[0].dims,f=Fe(e[1].dims.length),y=f?e[1].dims.length:e[1].dims,$=Fe(s.length),x=$?s.length:s,C=[{type:"uint32",data:c},{type:"int32",data:u},{type:"uint32",data:n}];m&&C.push(...Y(e[0].dims)),f&&C.push(...Y(e[1].dims)),$&&C.push(...Y(s));let b=[];b.push(m?"rank":"dims"),b.push(f?"rank":"dims");let E=T=>{let S=L("data",e[0].dataType,l,d),B=L("inputIndices",e[1].dataType,y),D=pe("output",e[0].dataType,x,d),U=G=>{let K=a.length,R=`var indicesIndices${G} = ${B.type.indices}(0);`;for(let j=0;j1?`indicesIndices${G}[${j}]`:`indicesIndices${G}`} = ${s.length>1?`outputIndices${G}[uniforms.axis + ${j}]`:`outputIndices${G}`};`;R+=` + var idx${G} = ${B.getByIndices(`indicesIndices${G}`)}; + if (idx${G} < 0) { + idx${G} = idx${G} + uniforms.axisDimLimit; + } + var dataIndices${G} = ${S.type.indices}(0); + `;for(let j=0,me=0;j1?`dataIndices${G}[${j}]`:`dataIndices${G}`} = u32(idx${G});`,me+=K):(R+=`${i>1?`dataIndices${G}[${j}]`:`dataIndices${G}`} = ${s.length>1?`outputIndices${G}[${me}]`:`outputIndices${G}`};`,me++);return R},P;if(e[0].dataType===9){let G=(K,R,j="")=>` + let outputIndices${R} = ${D.offsetToIndices(`outputOffset + ${R}u`)}; + ${U(R)}; + let offset${R} = ${S.indicesToOffset(`dataIndices${R}`)}; + let index${R} = offset${R} / 4u; + let component${R} = offset${R} % 4u; + ${K}[${R}] = ${j}(${S.getByOffset(`index${R}`)}[component${R}]); + `;P=` + let outputOffset = global_idx * ${d}; + var value = vec4(0); + ${G("value",0,"u32")} + ${G("value",1,"u32")} + ${G("value",2,"u32")} + ${G("value",3,"u32")} + ${D.setByOffset("global_idx","value")} + `}else P=` + let outputIndices = ${D.offsetToIndices("global_idx")}; + ${U("")}; + let value = ${S.getByIndices("dataIndices")}; + ${D.setByOffset("global_idx","value")}; + `;return` + ${T.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(S,B,D)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${P} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:b},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:C}),getShaderSource:E}},cd=e=>Be({axis:e.axis}),hd=(e,t)=>{let r=e.inputs;Ns(r),e.compute(Ws(e.inputs,t))}}),Us,Vs,fd,md,gc=H(()=>{xe(),qe(),be(),Us=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 + indices input tensors be of same rank.`)},Vs=(e,t)=>{let r=e[0].dims,a=e[0].dataType,i=r.length,n=e[1].dims,s=e[1].dataType,u=F.normalizeAxis(t.axis,i),d=r[u],c=n.slice(0),m=F.size(c),l=L("input",a,i),f=L("indicesInput",s,n.length),y=pe("output",a,c.length),$=[{type:"uint32",data:m},{type:"int32",data:d},{type:"uint32",data:u}];return $.push(...Y(r)),$.push(...Y(n)),$.push(...Y(c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:$}),getShaderSource:x=>` + ${x.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(l,f,y)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${y.offsetToIndices("global_idx")}; + + var idx = ${f.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${l.type.indices}(outputIndices); + ${l.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${l.getByIndices("inputIndices")}; + + ${y.setByOffset("global_idx","value")}; + }`}},fd=e=>Be({axis:e.axis}),md=(e,t)=>{let r=e.inputs;Us(r),e.compute(Vs(e.inputs,t))}}),Hs,Ls,gd,yd,yc=H(()=>{xe(),be(),Hs=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")},Ls=(e,t)=>{let r=e[0].dims.slice(),a=e[1].dims.slice(),[i,n,s]=Ru.getShapeOfGemmResult(r,t.transA,a,t.transB,e.length===3?e[2].dims:void 0),u=[i,n];if(!u)throw new Error("Can't use gemm on the given tensors");let d=F.size(u),c=[{type:"uint32",data:d},{type:"uint32",data:i},{type:"uint32",data:n},{type:"uint32",data:s},{type:"float32",data:t.alpha},{type:"float32",data:t.beta}],m=["type","type"];e.length===3&&(c.push(...Y(e[2].dims)),m.push("rank")),c.push(...Y(u));let l=f=>{let y="";t.transA&&t.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let $=t.alpha===1?"":"value *= uniforms.alpha;",x=L("a",e[0].dataType,e[0].dims),C=L("b",e[1].dataType,e[1].dims),b=x.type.value,E=null,T=[x,C];e.length===3&&(E=L("c",e[2].dataType,e[2].dims.length),T.push(E));let S=pe("output",e[0].dataType,u.length);T.push(S);let B=[{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` + ${f.registerUniforms(B).declareVariables(...T)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${b}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${y} + } + + ${$} + ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",S)}; value += ${b}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:l}},gd=e=>{let t=e.transA,r=e.transB,a=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:a,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},yd=(e,t)=>{Hs(e.inputs),e.compute(Ls(e.inputs,t))}}),Gs,Fs,qs,wd,wc=H(()=>{De(),xe(),be(),Gs=(e,t)=>{let r=e[0].dims,a=r,i=2,n=F.sizeToDimension(r,i),s=F.sizeFromDimension(r,i),u=Xe(s),d=s/u,c=[r[0],r[1],d],m=["rank","type","type"],l=[{type:"uint32",data:s},{type:"uint32",data:d}];l.push(...Y(c),...Y(c));let f=y=>{let $=L("x",e[0].dataType,c.length,u),x=L("scale",e[1].dataType,e[1].dims),C=L("bias",e[2].dataType,e[2].dims),b=pe("output",e[0].dataType,c.length,u),E=[$,x,C,b],T=$.type.value,S=u===1?"f32":`vec${u}`,B=64,D=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${S}, ${B}>; + const workgroupSize = ${B}u; + ${y.registerUniforms(D).declareVariables(...E)} + ${y.mainStart(B)} + let norm = global_idx / workgroupSize; + let batch = norm / uniforms.x_shape[1]; + let channel = norm % uniforms.x_shape[1]; + let localIndex = local_id.x; + + // initialize workgroup memory + var initial = ${S}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${S}(${$.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 = ${yt("workgroupShared[0]",u)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${S}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${S}(${$.get("batch","channel","h")}) - ${S}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${yt("workgroupShared[0]",u)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); + let channelScale = invStdDev * f32(${x.getByOffset("channel")}); + let channelShift = f32(${C.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${$.get("batch","channel","h")} * ${T}(${S}(channelScale)) + ${T}(${S}(channelShift)); + ${b.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${u}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:n},programUniforms:l}),getShaderSource:f}},Fs=(e,t,r,a,i,n,s,u)=>{let d=Xe(s),c=64,m=d===1?"vec2f":`mat2x${d}f`,l=d===1?"f32":`vec${d}f`,f=(D,U)=>`${m}(${D}, ${U})`,y=i*s/d,$=Math.ceil(n/c),x=["type"],C=[{type:"uint32",data:$},{type:"uint32",data:n},{type:"uint32",data:Math.floor(s/d)},{type:"uint32",data:Math.floor(n*s/d)}],b=D=>{let U=L("input",t.dataType,t.dims,d);return` + ${D.declareVariables(U)} + @group(0) @binding(1) var output : array<${m}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${D.mainStart(c)} + let currentImageNumber = global_idx / ${c} / uniforms.C; + let currentChannelNumber = (global_idx / ${c}) % uniforms.C; + let wgId = global_idx % ${c}; + let wgOffset = wgId * uniforms.wg_size; + if (wgOffset >= uniforms.H) { + return; + } + let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); + + let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; + var sum = ${Ze("f32",d)}; + var squaredSum = ${Ze("f32",d)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${l}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${f("sum","squaredSum")}; + }`},E=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${d}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:[i,s,c,2],dataType:1}],dispatchGroup:{x:i*s/d},programUniforms:C}),getShaderSource:b},{inputs:[t],outputs:[-1]})[0],T=[{type:"uint32",data:y},{type:"uint32",data:n},{type:"uint32",data:Math.floor(s/d)},{type:"uint32",data:Math.floor(c*s/d)}],S=["type","type","type"],B=D=>{let U=L("scale",r.dataType,r.dims,d),P=L("bias",a.dataType,a.dims,d);return` + @group(0) @binding(0) var input : array<${m}>; + @group(0) @binding(1) var scale : array<${U.type.storage}>; + @group(0) @binding(2) var bias : array<${P.type.storage}>; + @group(0) @binding(3) var output : array<${m}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${D.mainStart()} + ${D.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 = ${Ze("f32",d)}; + var squaredSum = ${Ze("f32",d)}; + for (var i: u32 = 0; i < ${c}; i++) { + let value = input[offset + i + currentChannelNumber * ${c}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${u})); + let channelScale = invStdDev * ${l}(scale[currentChannelNumber]); + let channelShift = ${l}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${f("channelScale","channelShift")}; + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:[i,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:T}),getShaderSource:B},{inputs:[E,r,a],outputs:[-1]})[0]},qs=(e,t,r)=>{let a=t[0].dims,i=a,n=a[0],s=a[a.length-1],u=F.sizeFromDimension(a,1)/s,d=Xe(s),c=F.size(i)/d,m=[{type:"uint32",data:u},{type:"uint32",data:Math.floor(s/d)}],l=["type","type"],f=Fs(e,t[0],t[1],t[2],n,u,s,r.epsilon),y=$=>{let x=tt(t[0].dataType),C=d===1?"vec2f":`mat2x${d}f`,b=d===1?x:`vec${d}<${x}>`,E=L("input",t[0].dataType,t[0].dims,d),T=pe("output",t[0].dataType,i,d);return` + @group(0) @binding(0) var input : array<${E.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${C}>; + @group(0) @binding(2) var output : array<${T.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${$.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], ${b}(scale[0]), ${b}(scale[1])); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:y},{inputs:[t[0],f]})},wd=(e,t)=>{t.format==="NHWC"?qs(e,e.inputs,t):e.compute(Gs(e.inputs,t))}}),js,Ks,$d,$c=H(()=>{De(),xe(),be(),js=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Ks=(e,t,r)=>{let a=e[0].dims,i=e[1],n=e[2],s=a,u=F.normalizeAxis(t.axis,a.length),d=F.sizeToDimension(a,u),c=F.sizeFromDimension(a,u),m=F.size(i.dims),l=n?F.size(n.dims):0;if(m!==c||n&&l!==c)throw new Error(`Size of X.shape()[axis:] == ${c}. + Size of scale and bias (if provided) must match this. + Got scale size of ${m} and bias size of ${l}`);let f=[];for(let S=0;S1,b=r>2,E=S=>{let B=tt(e[0].dataType),D=[L("x",e[0].dataType,e[0].dims,y),L("scale",i.dataType,i.dims,y)];n&&D.push(L("bias",n.dataType,n.dims,y)),D.push(pe("output",e[0].dataType,s,y)),C&&D.push(pe("mean_data_output",1,f)),b&&D.push(pe("inv_std_output",1,f));let U=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${S.registerUniforms(U).declareVariables(...D)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var meanVector = ${Ze("f32",y)}; + var meanSquareVector = ${Ze("f32",y)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${bt(B,y,"x[h + offset]")}; + meanVector += value; + meanSquareVector += value * value; + } + let mean = ${yt("meanVector",y)} / uniforms.norm_size; + let invStdDev = + inverseSqrt(${yt("meanSquareVector",y)} / uniforms.norm_size - mean * mean + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${bt(B,y,"x[j + offset]")}; + let f32scale = ${bt(B,y,"scale[j]")}; + output[j + offset] = ${D[0].type.value}((f32input - mean) * invStdDev * f32scale + ${n?`+ ${bt(B,y,"bias[j]")}`:""} + ); + } + + ${C?"mean_data_output[global_idx] = mean":""}; + ${b?"inv_std_output[global_idx] = invStdDev":""}; + }`},T=[{dims:s,dataType:e[0].dataType}];return C&&T.push({dims:f,dataType:1}),b&&T.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${y};${r}`,inputDependencies:$},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/64)},programUniforms:x}),getShaderSource:E}},$d=(e,t)=>{js(e.inputs),e.compute(Ks(e.inputs,t,e.outputCount))}}),Ys,vd,Un,Zs,Jr,bd,vc=H(()=>{xe(),qe(),xa(),il(),be(),Or(),Ys=(e,t)=>{let r=e[0],a=e[1],i=e[2],n=e[3],s=e[4],u=e[5],d=e[6],c=e[7];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=!1,l=r.dims[0],f=r.dims[1],y=r.dims.length===3?m?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],$=f,x=0,C=0,b=Math.floor(y/t.numHeads);if(d&&c){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');x=d.dims[2],C=d.dims[2]}else if(d||c)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let E;if(a){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(a.dims.length<3||a.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==a.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(a.dims.length===3){if(a.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');E=2,$=a.dims[1]}else if(a.dims.length===5){if(a.dims[2]!==t.numHeads||a.dims[3]!==2||a.dims[4]!==b)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.');E=5,$=a.dims[1]}else{if(a.dims[1]!==t.numHeads||a.dims[3]!==b)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');E=0,$=a.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');E=3}if(n){if(n.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 T=0;if(s){T=8;let P=s.dims;throw P.length===1?P[0]===l?T=1:P[0]===3*l+2&&(T=3):P.length===2&&P[0]===l&&P[1]===$&&(T=5),T===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let S=!1,B=y;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($!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');B=i.dims[2]}else{if($!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');B=i.dims[1]*i.dims[3],S=!0}}let D=x+$,U=!1;if(s)throw new Error("Key padding mask is not supported");if(u)throw new Error("extraAddQk is not supported");if(d)throw new Error("pastKey is not supported");if(c)throw new Error("pastValue is not supported");return{batchSize:l,sequenceLength:f,pastSequenceLength:x,kvSequenceLength:$,totalSequenceLength:D,maxSequenceLength:C,inputHiddenSize:0,hiddenSize:y,vHiddenSize:B,headSize:b,vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:T,scale:t.scale,broadcastResPosBias:U,passPastInKv:S,qkvFormat:E}},vd=e=>Be({...e}),Un=Be({perm:[0,2,1,3]}),Zs=(e,t,r,a,i,n,s)=>{let u=[a,i,n],d=F.size(u),c=[{type:"uint32",data:d},{type:"uint32",data:s},{type:"uint32",data:n}],m=l=>{let f=pe("qkv_with_bias",t.dataType,u),y=L("qkv",t.dataType,u),$=L("bias",r.dataType,u),x=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${l.registerUniforms(x).declareVariables(y,$,f)} + ${l.mainStart()} + ${l.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 e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},Jr=(e,t,r,a,i,n,s,u)=>{let d=n;if(s){if(a===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Zs(e,n,s,t,a,r*i,u),d=d.reshape([t,a,r,i]),e.compute(Tt(d,Un.perm),{inputs:[d],outputs:[-1]})[0]}else return n.dims.length===3&&(d=n.reshape([t,a,r,i])),e.compute(Tt(d,Un.perm),{inputs:[d],outputs:[-1]})[0]},bd=(e,t)=>{let r=Ys(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let a=e.inputs[1]&&e.inputs[2]&&e.inputs[1].dims.length===4&&e.inputs[2].dims.length===4,i=Jr(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],e.inputs[3],0);if(a)return fn(e,i,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t);let n=Jr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,e.inputs[1],e.inputs[3],r.hiddenSize),s=Jr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,e.inputs[2],e.inputs[3],2*r.hiddenSize);fn(e,i,n,s,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],r,t)}}),Xs,Qs,Js,eo,to,ro,no,ao,_d,bc=H(()=>{De(),xe(),be(),Xs=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1)throw new Error("Input type must be float.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Qs=(e,t,r)=>{let a="";for(let i=t-1;i>=0;--i)a+=` + k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)}; + if (k < 0) { + break; + } + if (k >= i32(${fe("uniforms.x_shape",i,t)})) { + break; + } + offset += k * i32(${fe("uniforms.x_strides",i,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + } + `},Js=(e,t,r)=>{let a="";for(let i=t-1;i>=0;--i)a+=` + k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${fe("uniforms.x_shape",i,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${fe("uniforms.x_shape",i,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${fe("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},eo=(e,t,r)=>{let a="";for(let i=t-1;i>=0;--i)a+=` + k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${fe("uniforms.x_shape",i,t)})) { + k = i32(${fe("uniforms.x_shape",i,t)}) - 1; + } + offset += k * i32(${fe("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},to=(e,t,r)=>{let a="";for(let i=t-1;i>=0;--i)a+=` + k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)}; + if (k < 0) { + k += i32(${fe("uniforms.x_shape",i,t)}]); + } + if (k >= i32(${fe("uniforms.x_shape",i,t)})) { + k -= i32(${fe("uniforms.x_shape",i,t)}); + } + offset += k * i32(${fe("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},ro=(e,t,r)=>{switch(r.mode){case 0:return Qs(e,t,r.pads.length);case 1:return Js(e,t,r.pads.length);case 2:return eo(e,t,r.pads.length);case 3:return to(e,t,r.pads.length);default:throw new Error("Invalid mode")}},no=(e,t)=>{let r=F.padShape(e[0].dims.slice(),t.pads),a=e[0].dims,i=[{type:"uint32",data:F.size(r)},{type:"uint32",data:t.pads}];if(t.mode===0){let u=ft(e[0].dataType);i.push({type:u,data:t.value})}i.push(...Y(e[0].dims),...Y(r));let n=["rank"],s=u=>{let d=pe("output",e[0].dataType,r.length),c=L("x",e[0].dataType,a.length),m=c.type.value,l=ro(d,a.length,t),f=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&f.push({name:"constant_value",type:m}),` + ${u.registerUniforms(f).declareVariables(c,d)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + + var value = ${m}(0); + ${l} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(F.size(r)/64)},programUniforms:i}),getShaderSource:s}},ao=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),a=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,i=e[0].dims.length,n=new Int32Array(2*i).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;dn[Number(d)]=Number(u));let s=[];return n.forEach(u=>s.push(u)),{mode:t.mode,value:a,pads:s}}else return t},_d=(e,t)=>{Xs(e.inputs);let r=ao(e.inputs,t);e.compute(no(e.inputs,r),{inputs:[0]})}}),vr,Vn,Hn,Ln,Gn,io,so,Fn,qn,xd,Sd,jn,Ed,Id,Kn,Cd,Td,Ad,Od,_c=H(()=>{lt(),xe(),be(),vr=e=>{if(Oe.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Vn=(e,t,r)=>{let a=t.format==="NHWC",i=e.dims.slice();a&&i.splice(1,0,i.pop());let n=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),u=t.strides.slice(),d=n?t.dilations.slice():[],c=t.pads.slice();cn.adjustPoolAttributes(r,i,s,u,d,c);let m=cn.computePoolOutputShape(r,i,u,d,s,c,t.autoPad),l=Object.assign({},t);n?Object.assign(l,{kernelShape:s,strides:u,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(l,{kernelShape:s,strides:u,pads:c,cacheKey:t.cacheKey});let f=m.slice();return f.push(f.splice(1,1)[0]),[l,a?f:m]},Hn=(e,t)=>{let r=t.format==="NHWC",a=F.size(e),i=F.size(t.kernelShape),n=[{type:"uint32",data:a},{type:"uint32",data:i}],s=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],l=!!(c+m);n.push({type:"uint32",data:u},{type:"uint32",data:d},{type:"uint32",data:c},{type:"uint32",data:m}),s.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let f=!1;if(t.kernelShape.length===2){let y=t.kernelShape[t.kernelShape.length-2],$=t.strides[t.strides.length-2],x=t.pads[t.pads.length/2-2],C=t.pads[t.pads.length-2];f=!!(x+C),n.push({type:"uint32",data:y},{type:"uint32",data:$},{type:"uint32",data:x},{type:"uint32",data:C}),s.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,s,!0,l,f]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=F.computeStrides(t.kernelShape);n.push({type:"uint32",data:u},{type:"uint32",data:t.pads},{type:"uint32",data:t.strides}),s.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((c,m)=>c+m);return[n,s,!!d,!1,!1]}},Ln=(e,t,r,a,i,n,s,u,d,c,m,l)=>{let f=i.format==="NHWC",y=t.type.value,$=pe("output",t.type.tensor,a);if(i.kernelShape.length<=2){let x="",C="",b="",E=r-(f?2:1);if(m?x=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${E}] = indices[${E}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${E}] < 0 || xIndices[${E}] + >= uniforms.x_shape[${E}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${n} + }`:x=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${E}] = indices[${E}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${n} + }`,i.kernelShape.length===2){let T=r-(f?3:2);l?C=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) { + pad += i32(uniforms.kw); + continue; + } + `:C=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j; + `,b=` + } + `}return` + ${e.registerUniforms(d).declareVariables(t,$)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${$.offsetToIndices("global_idx")}; + var xIndices = ${$.offsetToIndices("global_idx")}; + + var value = ${y}(${u}); + var pad = 0; + ${C} + ${x} + ${b} + ${s} + + output[global_idx] = value; + }`}else{if(f)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let x=i.kernelShape.length,C=i.pads.length,b="";return c?b=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${n} + }`:b=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(d).declareVariables(t,$)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${$.offsetToIndices("global_idx")}; + var xIndices = ${$.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${y}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${x-1}u; j++) { + offsets[j] = offset / ${fe("uniforms.kernelStrides","j",x)}; + offset -= offsets[j] * ${fe("uniforms.kernelStrides","j",x)}; + } + offsets[${x-1}] = offset; + + isPad = false; + for (var j = ${r-x}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${fe("uniforms.strides",`j - ${r-x}u`,x)} + + offsets[j - ${r-x}u] - ${fe("uniforms.pads","j - 2u",C)}; + ${b} + } + ${s} + + output[global_idx] = value; + }`}},Gn=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,io=e=>`${Gn(e)};${e.countIncludePad}`,so=e=>`${Gn(e)};${e.storageOrder};${e.dilations}`,Fn=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}),qn=(e,t,r,a)=>{let[i,n]=Vn(t,a,r),s=L("x",t.dataType,t.dims.length),u=s.type.value,d="value += x_val;",c="";i.countIncludePad?c+=`value /= ${u}(uniforms.kernelSize);`:c+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[m,l,f,y,$]=Hn(n,i);m.push(...Y(t.dims),...Y(n));let x=["rank"];return{name:e,shaderCache:{hint:`${a.cacheKey};${f};${y};${$}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:n,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(F.size(n)/64)},programUniforms:m}),getShaderSource:C=>Ln(C,s,t.dims.length,n.length,i,d,c,0,l,f,y,$)}},xd=e=>{let t=e.count_include_pad!==0,r=Fn(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let a={countIncludePad:t,...r,cacheKey:""};return{...a,cacheKey:io(a)}},Sd=(e,t)=>{vr(e.inputs),e.compute(qn("AveragePool",e.inputs[0],!1,t))},jn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Ed=e=>{let t=e.format;return{format:t,...jn,cacheKey:t}},Id=(e,t)=>{vr(e.inputs),e.compute(qn("GlobalAveragePool",e.inputs[0],!0,t))},Kn=(e,t,r,a)=>{let[i,n]=Vn(t,a,r),s=` + value = max(x_val, value); + `,u="",d=L("x",t.dataType,t.dims.length),c=["rank"],[m,l,f,y,$]=Hn(n,i);return m.push(...Y(t.dims),...Y(n)),{name:e,shaderCache:{hint:`${a.cacheKey};${f};${y};${$}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(F.size(n)/64)},programUniforms:m}),getShaderSource:x=>Ln(x,d,t.dims.length,n.length,i,s,u,-1e5,l,f,y,$)}},Cd=(e,t)=>{vr(e.inputs),e.compute(Kn("MaxPool",e.inputs[0],!1,t))},Td=e=>{let t=e.storage_order,r=e.dilations,a=Fn(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(a.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:r,...a,cacheKey:""};return{...i,cacheKey:so(i)}},Ad=e=>{let t=e.format;return{format:t,...jn,cacheKey:t}},Od=(e,t)=>{vr(e.inputs),e.compute(Kn("GlobalMaxPool",e.inputs[0],!0,t))}}),oo,uo,kd,xc=H(()=>{lt(),De(),be(),oo=(e,t,r)=>{let a=e===t,i=et&&r>0;if(a||i||n)throw new Error("Range these inputs' contents are invalid.")},uo=(e,t,r,a)=>{let i=Math.abs(Math.ceil((t-e)/r)),n=[i],s=i,u=ft(a),d=[{type:"uint32",data:s},{type:u,data:e},{type:u,data:r},...Y(n)],c=m=>{let l=pe("output",a,n.length),f=l.type.value,y=[{name:"outputSize",type:"u32"},{name:"start",type:f},{name:"delta",type:f}];return` + ${m.registerUniforms(y).declareVariables(l)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${f}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${a}`},getShaderSource:c,getRunData:()=>({outputs:[{dims:n,dataType:a}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d})}},kd=e=>{let t=0,r=0,a=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],a=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],a=e.inputs[2].getFloat32Array()[0]),Oe.webgpu.validateInputContent&&oo(t,r,a),e.compute(uo(t,r,a,e.inputs[0].dataType),{inputs:[]})}}),lo,po,co,ho,fo,mo,go,yo,wo,$o,vo,Yn,bo,_o,xo,So,Eo,Rd,zd,Sc=H(()=>{xe(),qe(),be(),lo=(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 + 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")}},po=(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 a=new Array(r).fill(1);return t.forEach((i,n)=>a[i]=e[n]),a},co=(e,t,r,a,i,n)=>{let[s,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(s>0&&e.length>s&&e[s].dims.length>0)e[s].getFloat32Array().forEach(m=>n.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length>0){if(e[u].getFloat32Array().forEach(m=>a.push(m)),a.length!==0&&a.length!==c&&r>=18&&a.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");lo(a,t),t.axes.length>0&&po(a,t.axes,c).forEach((m,l)=>a[l]=m)}if(d>0&&e.length>d&&(e[d].getBigInt64Array().forEach(m=>i.push(Number(m))),i.length!==c||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(a.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 a<"u"&&typeof i<"u"&&a.length>0&&i.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},ho=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + 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) { + return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(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 = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); + let fract = + ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); + return whole + fract; + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${t}(roiStart) * ${t}(lengthOriginal - 1) + + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / + ${t}(lengthResized - 1); + } else { + return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); + const adjustment = ${t}(lengthResized) / outputWidth; + const center = ${t}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + 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`)}})()+"}",fo=(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`)}})()+"}",mo=(e,t,r)=>{let a=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?a:e.slice();return t.length>0?(t.forEach((n,s)=>{a[n]=i[s],a[s+r]=i[t.length+s]}),a):i},go=(e,t,r,a)=>{let i=[];if(r.length>0)if(a.length>0){if(e.forEach(n=>i.push(n)),Math.max(...a)>e.length)throw new Error("axes is out of bound");a.forEach((n,s)=>i[n]=r[s])}else r.forEach(n=>i.push(n));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((n,s)=>Math.round(n*t[s]))}return i},yo=(e,t,r)=>{let a=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(n=>t[n]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(n=>t[n]),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(n=>t[n]=a),r.axes.forEach(n=>i[n]=Math.round(e[n]*t[n]))):(t.fill(a,0,t.length),i.forEach((n,s)=>i[s]=Math.round(n*t[s]))),i},wo=(e,t,r,a,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { + var original_indices: array<${e.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${fe("uniforms.scales","i",a)}; + var roi_low = ${fe("uniforms.roi","i",i)}; + var roi_hi = ${fe("uniforms.roi",`i + ${t.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${fe("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${fe("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; + }`,$o=(e,t,r,a,i,n,s)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${a.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${fe("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${fe("uniforms.roi","i",n)}; + var roi_hi = ${fe("uniforms.roi",`i + ${r.length}`,n)}; + var input_shape_i = ${fe("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${fe("uniforms.output_shape","i",a.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${s} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.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); + } + } + ${e.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,vo=(e,t)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${t.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${fe("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,Yn=(e,t,r,a)=>e.rank>a?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",bo=(e,t,r,a,i)=>{let[n,s,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",s,`max(0, min(row, ${r[s]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; + ${Yn(e,d,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${c} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${c} = originalIndices[${s}]; + var col:${c} = originalIndices[${u}]; + ${a?`if (row < 0 || row > (${r[s]} - 1) || col < 0 || col > (${r[u]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${r[s]} - 1)); + col = max(0, min(col, ${r[u]} - 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[${d}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${c} = getInputValue(batch, channel, row1, col1); + var x12: ${c} = getInputValue(batch, channel, row1, col2); + var x21: ${c} = getInputValue(batch, channel, row2, col1); + var x22: ${c} = getInputValue(batch, channel, row2, col2); + var dx1: ${c} = abs(row - ${c}(row1)); + var dx2: ${c} = abs(${c}(row2) - row); + var dy1: ${c} = abs(col - ${c}(col1)); + var dy2: ${c} = abs(${c}(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); + }`},_o=(e,t,r,a,i,n,s,u,d,c)=>{let m=r.length===2,[l,f]=m?[0,1]:[2,3],y=e.type.value,$=x=>{let C=x===l?"row":"col";return` + fn ${C}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} { + var output_index = ${t.indicesGet("output_indices",x)}; + var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[x]}, + ${a[x]}, ${r[x]}, ${n[x]}, ${n[x]} + ${r.length}); + var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) { + return ${d}; + } + var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${C}: ${y} = originalIdx + ${y}(i); + if (${C} < 0 || ${C} >= ${r[x]}) { + ${c?`coefs[i + 1] = 0.0; + continue;`:u?`return ${d};`:`${C} = max(0, min(${C}, ${r[x]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",x,`u32(${C})`)}; + data[i + 1] = ${x===l?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${$(l)}; + ${$(f)}; + fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> { + var absS = abs(s); + var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${y} = 1.0 - absS; + var twoMinusAbsS: ${y} = 2.0 - absS; + var onePlusAbsS: ${y} = 1.0 + absS; + coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s}; + coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1; + coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} { + var coefsSum: ${y} = 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: ${t.type.indices}) -> ${y} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},xo=(e,t,r,a,i)=>{let[n,s,u,d,c]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],m=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${m} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",s,`max(0, min(depth, ${r[s]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; + ${Yn(e,c,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${m} = originalIndices[${s}]; + var height:${m} = originalIndices[${u}]; + var width:${m} = originalIndices[${d}]; + ${a?`if (depth < 0 || depth > (${r[s]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${r[s]} - 1)); + height = max(0, min(height, ${r[u]} - 1)); + width = max(0, min(width, ${r[d]} - 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[${c}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${m} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${m} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${m} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${m} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${m} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${m} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${m} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${m} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${m} = abs(depth - ${m}(depth1)); + var dx2: ${m} = abs(${m}(depth2) - depth); + var dy1: ${m} = abs(height - ${m}(height1)); + var dy2: ${m} = abs(${m}(height2) - height); + var dz1: ${m} = abs(width - ${m}(width1)); + var dz2: ${m} = abs(${m}(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); + }`},So=(e,t,r,a,i,n)=>{let s=e.dims,u=mo(n,t.axes,s.length),d=go(s,a,i,t.axes),c=a.slice();a.length===0&&(c=s.map((E,T)=>E===0?1:d[T]/E),t.keepAspectRatioPolicy!=="stretch"&&(d=yo(s,c,t)));let m=pe("output",e.dataType,d.length),l=L("input",e.dataType,s.length),f=F.size(d),y=s.length===d.length&&s.every((E,T)=>E===d[T]),$=t.coordinateTransformMode==="tf_crop_and_resize",x=t.extrapolationValue,C=l.type.value,b=E=>` + ${y?"":` + ${ho(t.coordinateTransformMode,C)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${vo(l,s)}; + ${fo(t.nearestMode,r,C)}; + ${$o(l,m,s,d,c.length,u.length,$)}; + `;case"linear":return` + ${wo(m,s,d,c.length,u.length)}; + ${(()=>{if(s.length===2||s.length===4)return`${bo(l,m,s,$,x)}`;if(s.length===3||s.length===5)return`${xo(l,m,s,$,x)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(s.length===2||s.length===4)return`${_o(l,m,s,d,c,u,t.cubicCoeffA,$,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${E.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",u.length).declareVariables(l,m)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${y?"output[global_idx] = input[global_idx];":` + let output_indices = ${m.offsetToIndices("global_idx")}; + var input_indices: ${l.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${l.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${s.length===2||s.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${c.length>0?c:""}|${i.length>0?i:""}|${u.length>0?u:""}|${y}|${s}`,inputDependencies:["rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:"uint32",data:f},{type:"float32",data:c},{type:"float32",data:u},...Y(s),...Y(d)]})}},Eo=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Rd=(e,t)=>{let r=[],a=[],i=[],n=Eo(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");co(e.inputs,t,n,r,a,i),e.compute(So(e.inputs[0],t,n,r,a,i),{inputs:[0]})},zd=e=>{let t=e.antialias,r=e.axes,a=e.coordinateTransformMode,i=e.cubicCoeffA,n=e.excludeOutside!==0,s=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return Be({antialias:t,axes:r,coordinateTransformMode:a,cubicCoeffA:i,excludeOutside:n,extrapolationValue:s,keepAspectRatioPolicy:u,mode:d,nearestMode:c})}}),Io,Co,Bd,Md,Ec=H(()=>{De(),xe(),qe(),be(),Io=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],a=e[2];if(t.dataType!==r.dataType||t.dataType!==a.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],n=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]!==n)throw new Error("Skip must have the same sequence length as input");if(a.dims.length!==1)throw new Error("Gamma must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let s=e[3];if(s.dims.length!==1)throw new Error("Beta must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let s=e[4];if(s.dims.length!==1)throw new Error("Bias must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Co=(e,t,r,a)=>{let i=e[0].dims,n=F.size(i),s=i,u=n,d=i.slice(-1)[0],c=a?i.slice(0,-1).concat(1):[],m=e.length>3,l=e.length>4,f=a&&r>1,y=a&&r>2,$=r>3,x=Xe(d),C=[L("x",e[0].dataType,e[0].dims,x),L("skip",e[1].dataType,e[1].dims,x),L("gamma",e[2].dataType,e[2].dims,x)];m&&C.push(L("beta",e[3].dataType,e[3].dims,x)),l&&C.push(L("bias",e[4].dataType,e[4].dims,x)),C.push(pe("output",e[0].dataType,s,x)),f&&C.push(pe("meanOutput",1,c)),y&&C.push(pe("invStdOutput",1,c)),$&&C.push(pe("inputSkipBiasSum",e[0].dataType,s,x));let b=tt(e[0].dataType),E=S=>` + const hiddenSize: f32 = ${d}; + const hiddenSizeVectorized: u32 = ${d/x}; + const epsilon: f32 = ${t.epsilon}; + + ${S.declareVariables(...C)} + + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes(u/d)} + let offset = global_idx * hiddenSizeVectorized; + var sum = ${Ze("f32",x)}; + var squareSum = ${Ze("f32",x)}; + for (var i: u32 = 0; i < hiddenSizeVectorized; i++) { + let skipValue = skip[offset + i]; + let biasValue = ${l?"bias[i]":"0.0"}; + let inputValue = x[offset + i]; + let value = inputValue + skipValue + biasValue; + ${$?"inputSkipBiasSum[offset + i] = value;":""} + output[offset + i] = value; + let f32Value = ${bt(b,x,"value")}; + sum += f32Value; + squareSum += f32Value * f32Value; + } + let mean = ${yt("sum",x)} / hiddenSize; + let invStdDev = inverseSqrt(${yt("squareSum",x)} / hiddenSize - mean * mean + epsilon); + ${f?"meanOutput[global_idx] = mean;":""} + ${y?"invStdOutput[global_idx] = invStdDev;":""} + for (var i: u32 = 0; i < hiddenSizeVectorized; i++) { + output[offset + i] = (output[offset + i] - ${b}(mean)) * ${b}(invStdDev) * gamma[i] + + ${m?"beta[i]":"0.0"}; + } + }`,T=[{dims:s,dataType:e[0].dataType}];return r>1&&T.push({dims:c,dataType:1}),r>2&&T.push({dims:c,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:t.cacheKey},getShaderSource:E,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(u/d/64)}})}},Bd=(e,t)=>{Io(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(Co(e.inputs,t,e.outputCount,!1),{outputs:r})},Md=e=>{let t=e.epsilon;return Be({epsilon:t})}}),To,br,Ao,Zn,Oo,ko,Dd,Pd,Ic=H(()=>{De(),xe(),qe(),be(),To=(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,a)=>{if(e[a+1].dataType!==6&&e[a+1].dataType!==7)throw new Error(`Input ${a} must be an array of int32 or int64`)})},br=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(a=>r.push(Number(a)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(a=>r.push(Number(a)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Ao=(e,t)=>{if(e.length>1){let r=br(e,1),a=br(e,2),i=br(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Be({starts:r,ends:a,axes:i})}else return t},Zn=(e,t,r,a,i)=>{let n=e;return e<0&&(n+=r[a[t]]),i[t]<0?Math.max(0,Math.min(n,r[a[t]]-1)):Math.max(0,Math.min(n,r[a[t]]))},Oo=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${fe("uniforms.input_shape","i",r.length)}; + let steps_i = ${fe("uniforms.steps","i",r.length)}; + let signs_i = ${fe("uniforms.signs","i",r.length)}; + let starts_i = ${fe("uniforms.starts","i",r.length)}; + var output_index = ${t.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; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,ko=(e,t)=>{let r=e[0].dims,a=F.size(r),i=t.axes.length>0?F.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],n=br(e,4);n.forEach(b=>b!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(i.length).fill(1));let s=t.starts.map((b,E)=>Zn(b,E,r,i,n)),u=t.ends.map((b,E)=>Zn(b,E,r,i,n));if(i.length!==s.length||i.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let b=0;bMath.sign(b));n.forEach((b,E,T)=>{if(b<0){let S=(u[E]-s[E])/b,B=s[E],D=B+S*n[E];s[E]=D,u[E]=B,T[E]=-b}});let c=r.slice(0);i.forEach((b,E)=>{c[b]=Math.ceil((u[b]-s[b])/n[b])});let m={dims:c,dataType:e[0].dataType},l=pe("output",e[0].dataType,c.length),f=L("input",e[0].dataType,e[0].dims.length),y=F.size(c),$=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:n.length}],x=[{type:"uint32",data:y},{type:"uint32",data:s},{type:"int32",data:d},{type:"uint32",data:n},...Y(e[0].dims),...Y(c)],C=b=>` + ${b.registerUniforms($).declareVariables(f,l)} + ${Oo(f,l,r)} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${l.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${l.setByOffset("global_idx",f.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${s.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:C,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:x})}},Dd=(e,t)=>{To(e.inputs,t);let r=Ao(e.inputs,t);e.compute(ko(e.inputs,r),{inputs:[0]})},Pd=e=>{let t=e.starts,r=e.ends,a=e.axes;return Be({starts:t,ends:r,axes:a})}}),Ro,zo,Nd,Wd,Cc=H(()=>{xe(),qe(),be(),Ro=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},zo=(e,t)=>{let r=e.dims,a=F.size(r),i=64,n=t.axis;if(n<0&&(n=r.length+n),nb===4?`max(max(${C}.x, ${C}.y), max(${C}.z, ${C}.w))`:b===2?`max(${C}.x, ${C}.y)`:b===3?`max(max(${C}.x, ${C}.y), ${C}.z)`:C,l=L("x",e.dataType,e.dims,d),f=pe("result",e.dataType,e.dims,d),y=l.type.value,$=tt(e.dataType)==="f32"?`var threadMax = ${y}(-3.402823e+38f);`:`var threadMax = ${y}(-65504.0h);`,x=C=>` + var rowMaxShared : ${y}; + var rowSumShared : ${y}; + var threadShared : array<${y}, ${i}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${y} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${y}) { + let index = row * row_stride + col; + result[index] = value; + } + ${C.registerUniform("packedCols","i32").declareVariables(l,f)} + ${C.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${i}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${$} + 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 = ${y}(${m("threadShared[0]",d)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${y}(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 = ${y}(${yt("threadShared[0]",d)}); + } + 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:`${d}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:u},programUniforms:[{type:"uint32",data:c}]}),getShaderSource:x}},Nd=(e,t)=>{Ro(e.inputs),e.compute(zo(e.inputs[0],t))},Wd=e=>Be({axis:e.axis})}),Bo,Mo,Do,Po,No,Ud,Vd,Tc=H(()=>{xe(),qe(),be(),Bo=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Mo=(e,t)=>{let r=[],a=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),a=r.length),Be({numOutputs:a,axis:t.axis,splitSizes:r})},Do=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${fe("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Po=e=>{let t=e.length,r=[];for(let a=0;a{let r=e[0].dims,a=F.size(r),i=e[0].dataType,n=F.normalizeAxis(t.axis,r.length),s=new Array(t.numOutputs),u=L("input",i,r),d=new Array(t.numOutputs),c=[],m=[],l=0,f=[{type:"uint32",data:a}];for(let $=0;$f.push(...Y($)));let y=$=>` + ${$.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...s)} + ${Do(d.length)} + ${Po(s)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${fe("uniforms.size_in_split_axis","output_number - 1u",d.length)}; + ${u.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:y,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:f})}},Ud=(e,t)=>{Bo(e.inputs);let r=e.inputs.length===1?t:Mo(e.inputs,t);e.compute(No(e.inputs,r),{inputs:[0]})},Vd=e=>{let t=e.axis,r=e.splitSizes,a=e.numOutputs<0?r.length:e.numOutputs;if(a!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Be({axis:t,numOutputs:a,splitSizes:r})}}),Xn,Wo,Uo,Vo,Hd,Ac=H(()=>{De(),xe(),be(),Xn=e=>Array.from(e.getBigInt64Array(),Number),Wo=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(Xn(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")},Uo=(e,t)=>{let r=[];for(let a=0;a{let t=e[0].dims,r=Xn(e[1]),a=Uo(t,r),i=F.size(a),n=e[0].dataType,s=L("input",n,t.length),u=pe("output",n,a.length),d=c=>` + const inputShape = ${s.indices(...t)}; + ${c.registerUniform("output_size","u32").declareVariables(s,u)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${u.offsetToIndices("global_idx")}; + var input_indices: ${s.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${s.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${u.indicesGet("output_indices","i")} % input_dim_i; + + ${s.indicesSet("input_indices","i","input_dim_value")} + } + ${u.setByOffset("global_idx",s.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:"uint32",data:i},...Y(e[0].dims),...Y(a)]}),getShaderSource:d}},Hd=e=>{Wo(e.inputs),e.compute(Vo(e.inputs),{inputs:[0]})}}),Ho,Lo,Ld,Oc=H(()=>{De(),xe(),be(),Ho=(e,t,r,a,i)=>{let n=pe("output_data",i,r.length,4),s=L("a_data",t[1].dataType,t[1].dims.length,4),u=L("b_data",t[2].dataType,t[2].dims.length,4),d=L("c_data",t[0].dataType,t[0].dims.length,4),c,m=(l,f,y)=>`select(${f}, ${l}, ${y})`;if(!a)c=n.setByOffset("global_idx",m(s.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let l=(f,y,$="")=>{let x=`a_data[index_a${y}][component_a${y}]`,C=`b_data[index_b${y}][component_b${y}]`,b=`bool(c_data[index_c${y}] & ${4278190080>>>(3-y)*8}u)`;return` + let output_indices${y} = ${n.offsetToIndices(`global_idx * 4u + ${y}u`)}; + let offset_a${y} = ${s.broadcastedIndicesToOffset(`output_indices${y}`,n)}; + let offset_b${y} = ${u.broadcastedIndicesToOffset(`output_indices${y}`,n)}; + let offset_c${y} = ${d.broadcastedIndicesToOffset(`output_indices${y}`,n)}; + let index_a${y} = offset_a${y} / 4u; + let index_b${y} = offset_b${y} / 4u; + let index_c${y} = offset_c${y} / 4u; + let component_a${y} = offset_a${y} % 4u; + let component_b${y} = offset_b${y} % 4u; + ${f}[${y}] = ${$}(${m(x,C,b)}); + `};i===9?c=` + var data = vec4(0); + ${l("data",0,"u32")} + ${l("data",1,"u32")} + ${l("data",2,"u32")} + ${l("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` + ${l("output_data[global_idx]",0)} + ${l("output_data[global_idx]",1)} + ${l("output_data[global_idx]",2)} + ${l("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(d,s,u,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${c} + }`},Lo=e=>{let t=e[1].dims,r=e[2].dims,a=e[0].dims,i=e[1].dataType,n=!(F.areEqual(t,r)&&F.areEqual(r,a)),s=t,u=F.size(t);if(n){let c=Zt.calcShape(Zt.calcShape(t,r,!1),a,!1);if(!c)throw new Error("Can't perform where op on the given tensors");s=c,u=F.size(s)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Ho(c,e,s,n,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:"uint32",data:d},...Y(a),...Y(t),...Y(r),...Y(s)]})}},Ld=e=>{e.compute(Lo(e.inputs))}}),Gd,kc=H(()=>{tc(),il(),rc(),nc(),ac(),ic(),sc(),nd(),pc(),cc(),hc(),fc(),mc(),gc(),yc(),wc(),$c(),rd(),vc(),bc(),_c(),xc(),Ca(),Sc(),Ec(),Ic(),Cc(),Tc(),Ac(),Or(),Wl(),Oc(),Gd=new Map([["Abs",[ul]],["Acos",[ll]],["Acosh",[dl]],["Add",[Vl]],["ArgMax",[nl,ia]],["ArgMin",[rl,ia]],["Asin",[pl]],["Asinh",[cl]],["Atan",[hl]],["Atanh",[fl]],["Attention",[al]],["AveragePool",[Sd,xd]],["BatchNormalization",[sl]],["BiasAdd",[ol]],["BiasSplitGelu",[Ul]],["Cast",[gl,ml]],["Ceil",[wl]],["Clip",[yl]],["Concat",[Xl,Ql]],["Conv",[da,la]],["ConvTranspose",[sd,id]],["Cos",[$l]],["Cosh",[vl]],["CumSum",[od,ud]],["Div",[Hl]],["Einsum",[ld,dd]],["Elu",[bl,an]],["Equal",[Ll]],["Erf",[_l]],["Exp",[xl]],["Expand",[pd]],["Floor",[Sl]],["FusedConv",[da,la]],["Gather",[hd,cd]],["GatherElements",[md,fd]],["Gelu",[El]],["Gemm",[yd,gd]],["GlobalAveragePool",[Id,Ed]],["GlobalMaxPool",[Od,Ad]],["Greater",[jl]],["GreaterOrEqual",[Yl]],["InstanceNormalization",[wd]],["LayerNormalization",[$d]],["LeakyRelu",[Il,an]],["Less",[Kl]],["LessOrEqual",[Zl]],["Log",[Nl]],["MatMul",[td]],["MaxPool",[Cd,Td]],["Mul",[Gl]],["MultiHeadAttention",[bd,vd]],["Neg",[Tl]],["Not",[Cl]],["Pad",[_d]],["Pow",[Fl]],["Range",[kd]],["Reciprocal",[Al]],["ReduceMin",[Xu]],["ReduceMean",[qu]],["ReduceMax",[Zu]],["ReduceSum",[Ju]],["ReduceProd",[Qu]],["ReduceL1",[ju]],["ReduceL2",[Ku]],["ReduceLogSum",[tl]],["ReduceLogSumExp",[Yu]],["ReduceSumSquare",[el]],["Relu",[Ol]],["Resize",[Rd,zd]],["Sigmoid",[kl]],["Sin",[Rl]],["Sinh",[zl]],["Slice",[Dd,Pd]],["SkipLayerNormalization",[Bd,Md]],["Split",[Ud,Vd]],["Sqrt",[Bl]],["Softmax",[Nd,Wd]],["Sub",[ql]],["Tan",[Ml]],["Tanh",[Dl]],["ThresholdedRelu",[Pl,an]],["Tile",[Hd]],["Transpose",[Bu,Mu]],["Where",[Ld]]])}),Fd,Rc=H(()=>{lt(),Nt(),be(),Fd=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,a,i){mt(e.programInfo.name);let n=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2),s.setPipeline(e.computePipeline);let u=[];for(let c of t)u.push({binding:u.length,resource:{buffer:c.buffer}});for(let c of r)u.push({binding:u.length,resource:{buffer:c.buffer}});i&&u.push({binding:u.length,resource:i});let d=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});s.setBindGroup(0,d),s.dispatchWorkgroups(...a),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(),gt(e.programInfo.name)}dispose(){}build(e,t){mt(e.name);let r=this.backend.device,a=[];r.features.has("shader-f16")&&a.push("enable f16;");let i=zu(t),n=e.getShaderSource(i),s=`${a.join(` +`)} +${i.additionalImplementations} +${n}`,u=r.createShaderModule({code:s,label:e.name});Ge("verbose",()=>`[WebGPU] ${e.name} shader code: ${s}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return gt(e.name),{programInfo:e,computePipeline:d}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,a=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&r<=i&&a<=i)return[t,r,a];let n=t*r*a,s=Math.ceil(Math.sqrt(n));if(s>i){if(s=Math.ceil(Math.cbrt(n)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}else return[s,s,1]}}}),Go,Fo,qd,zc=H(()=>{lt(),De(),Nt(),Qp(),Jp(),kc(),Rc(),Go=(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 a=0;a{let a=e.name;return e.shaderCache?.hint&&(a+="["+e.shaderCache.hint+"]"),a+=":"+r+`:${Go(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,a},qd=class{constructor(){this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],a={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(a),this.gpuDataManager=ku(this),this.programManager=new Fd(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Au(e.logLevel,!!e.debug),this.device.onuncapturederror=i=>{i.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${i.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder(),this.setQueryType(),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE}))),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=this.getCommandEncoder().beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;mt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let a=0;a"u"&&(this.queryTimeBase=f);let $=Number(f-this.queryTimeBase),x=Number(y-this.queryTimeBase);if(!Number.isSafeInteger($)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(C=>({dims:C.dims,dataType:ft(C.dataType)})),outputsMetadata:l.map(C=>({dims:C.dims,dataType:ft(C.dataType)})),kernelId:n,kernelType:u,kernelName:d,programName:c,startTime:$,endTime:x});else{let C="";m.forEach((E,T)=>{C+=`input[${T}]: [${E.dims}] | ${ft(E.dataType)}, `});let b="";l.forEach((E,T)=>{b+=`output[${T}]: [${E.dims}] | ${ft(E.dataType)}, `}),console.log(`[profiling] kernel "${n}|${u}|${d}|${c}" ${C}${b}execution time: ${x-$} ns`)}on("GPU",`${c}::${f}::${y}`)}e.unmap(),this.pendingQueries.delete(e)}),gt()}run(e,t,r,a,i){mt(e.name);let n=[];for(let b=0;bE):r;if(c.length!==s.length)throw new Error(`Output size ${c.length} must be equal to ${s.length}.`);let m=[],l=[];for(let b=0;b=s.length)throw new Error(`Invalid output index: ${c[b]}`);if(c[b]===-3)continue;let E=c[b]===-1,T=c[b]===-2,S=E||T?i(s[b].dataType,s[b].dims):a(c[b],s[b].dataType,s[b].dims),B=this.gpuDataManager.get(S.data);if(!B)throw new Error(`no GPU data for output: ${S.data}`);if(E&&this.temporaryData.push(B),T){let D=this.kernelPersistentData.get(this.currentKernelId);D||(D=[],this.kernelPersistentData.set(this.currentKernelId,D)),D.push(B)}m.push(S),l.push(B)}let f;if(d){let b=0,E=[];d.forEach(D=>{let U=typeof D.data=="number"?[D.data]:D.data;if(U.length===0)return;let P=U.length<=2?U.length*4:16;b=Math.ceil(b/P)*P,E.push(b),b+=U.length>4?Math.ceil(U.length/4)*16:U.length*4});let T=16;b=Math.ceil(b/T)*T;let S=new ArrayBuffer(b);d.forEach((D,U)=>{let P=E[U],G=typeof D.data=="number"?[D.data]:D.data;D.type==="int32"?new Int32Array(S,P,G.length).set(G):D.type==="uint32"?new Uint32Array(S,P,G.length).set(G):new Float32Array(S,P,G.length).set(G)});let B=this.gpuDataManager.create(b,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(B.buffer,0,S,0,b),this.gpuDataManager.release(B.id),f={offset:0,size:b,buffer:B.buffer}}let y=this.programManager.normalizeDispatchGroupSize(u),$=y[1]===1&&y[2]===1,x=Fo(e,t,$),C=this.programManager.getArtifact(x);if(C||(C=this.programManager.build(e,y),this.programManager.setArtifact(x,C),Ge("info",()=>`[artifact] key: ${x}, programName: ${e.name}`)),Ge("info",()=>`[ProgramManager] run "${e.name}" (key=${x}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"){let b={kernelId:this.currentKernelId,programName:C.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(b)}return this.programManager.run(C,n,l,y,f),gt(e.name),m}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,a){let i=Gd.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:a,kernelEntry:i[0],attributes:[i[1],r]};this.kernels.set(t,n)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let a=this.kernels.get(e);if(!a)throw new Error(`kernel not created: ${e}`);let i=a.kernelType,n=a.kernelName,s=a.kernelEntry,u=a.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),Ge("info",()=>`[WebGPU] Start to run kernel "[${i}] ${n}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),s(t,u[1]),0}catch(c){return r.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${n}" failed. ${c}`)),1}finally{d&&r.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${n}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,a){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let n=i.get(t),s=this.gpuDataManager.registerExternalBuffer(r,a,n?.[1]);return i.set(t,[s,r]),s}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let a=await na(this,e,t);return Ou(a.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||this.env.wasm.trace)&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"))}}}),jd={};Qt(jd,{init:()=>Kd});var en,qo,Kd,Bc=H(()=>{De(),zc(),Nt(),xe(),en=class Yd{constructor(t,r,a,i){this.module=t,this.dataType=r,this.data=a,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=F.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=F.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=F.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(F.size(t)!==F.size(this.dims))throw new Error("Invalid new shape");return new Yd(this.module,this.dataType,this.data,t)}},qo=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0;let a=e.HEAPU32,i=r>>>2;this.opKernelContext=a[i++];let n=a[i++];this.outputCount=a[i++],this.customDataOffset=a[i++],this.customDataSize=a[i++];let s=[];for(let u=0;utypeof s=="number"?this.inputs[s]:s)??this.inputs,a=t?.outputs??[],i=(s,u,d)=>new en(this.module,u,this.output(s,d),d),n=(s,u)=>{let d=ln(s);if(!d)throw new Error(`Unsupported data type: ${s}`);let c=d*F.size(u);return new en(this.module,s,this.backend.gpuDataManager.create(c).id,u)};return this.backend.run(e,r,a,i,n)}output(e,t){let r=this.module.stackSave();try{let a=this.module.stackAlloc((1+t.length)*4),i=a>>2;this.module.HEAPU32[i++]=t.length;for(let n=0;n{let a=e.jsepInit;if(!a)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");let i=new qd;await i.initialize(t,r),a(i,n=>i.alloc(n),n=>i.free(n),(n,s,u,d=!1)=>{if(d)Ge("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${n}, dst=${s}, size=${u}`),i.memcpy(n,s);else{Ge("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${n}, gpuDataId=${s}, size=${u}`);let c=e.HEAPU8.subarray(n>>>0,(n>>>0)+u);i.upload(s,c)}},async(n,s,u)=>{Ge("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${n}, dataOffset=${s}, size=${u}`),await i.download(n,()=>e.HEAPU8.subarray(s>>>0,(s>>>0)+u))},(n,s,u)=>i.createKernel(n,s,u,e.UTF8ToString(e._JsepGetNodeName(s))),n=>i.releaseKernel(n),(n,s,u,d)=>{Ge("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${n}, contextDataOffset=${s}`);let c=new qo(e,i,s);return i.computeKernel(n,c,d)})}}),jo,Zd,Xd,jt,Ko,ca,Qd,Jd,Qn,ep,tp,rp,Mc=H(()=>{Zp(),Xp(),De(),Ar(),va(),Tu(),jo=(e,t)=>{He()._OrtInit(e,t)!==0&&ze("Can't initialize onnxruntime.")},Zd=async e=>{jo(e.wasm.numThreads,dn(e.logLevel))},Xd=async(e,t)=>{if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let r=await navigator.gpu.requestAdapter();if(!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.');if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");let a=(Bc(),Pt(jd)).init;await a(He(),e,r)}},jt=new Map,Ko=e=>{let t=He(),r=t.stackSave();try{let a=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,a,a+4)!==0&&ze("Can't get session input/output count."),[t.HEAP32[a/4],t.HEAP32[a/4+1]]}finally{t.stackRestore(r)}},ca=e=>{let t=He(),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,a,i=He();Array.isArray(e)?[r,a]=e:e.buffer===i.HEAPU8.buffer?[r,a]=[e.byteOffset,e.byteLength]:[r,a]=ca(e);let n=0,s=0,u=0,d=[],c=[],m=[];try{if([s,d]=Cu(t),t?.externalData&&i.mountExternalData){let b=[];for(let E of t.externalData){let T=typeof E=="string"?E:E.path;b.push(pn(typeof E=="string"?E:E.data).then(S=>{i.mountExternalData(T,S)}))}await Promise.all(b)}n=i._OrtCreateSession(r,a,s),n===0&&ze("Can't create a session.");let[l,f]=Ko(n),y=[],$=[],x=[];for(let b=0;bb==="gpu-buffer")&&(u=i._OrtCreateBinding(n),u===0&&ze("Can't create IO binding."),C={handle:u,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(b=>ra(b))}),jt.set(n,[n,c,m,C]),[n,y,$]}catch(l){throw c.forEach(f=>i._OrtFree(f)),m.forEach(f=>i._OrtFree(f)),u!==0&&i._OrtReleaseBinding(u),n!==0&&i._OrtReleaseSession(n),l}finally{i._free(r),s!==0&&i._OrtReleaseSessionOptions(s),d.forEach(l=>i._free(l)),i.unmountExternalData?.()}},Jd=e=>{let t=He(),r=jt.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[a,i,n,s]=r;s&&t._OrtReleaseBinding(s.handle),t.jsepUnregisterBuffers?.(e),i.forEach(u=>t._OrtFree(u)),n.forEach(u=>t._OrtFree(u)),t._OrtReleaseSession(a),jt.delete(e)},Qn=(e,t,r,a,i)=>{if(!e){t.push(0);return}let n=He(),s=e[0],u=e[1],d=e[3],c,m;if(s==="string"&&d==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(d==="gpu-buffer"){let y=e[2].gpuBuffer,$=ln(ta(s));m=u.reduce((x,C)=>x*C,1)*$,c=n.jsepRegisterBuffer(a,i,y,m)}else{let y=e[2];if(Array.isArray(y)){m=4*y.length,c=n._malloc(m),r.push(c);let $=c/4;for(let x=0;xn.HEAP32[y++]=x);let $=n._OrtCreateTensor(ta(s),c,m,f,u.length,ra(d));$===0&&ze(`Can't create tensor for input/output. session=${a}, index=${i}.`),t.push($)}finally{n.stackRestore(l)}},ep=async(e,t,r,a,i,n)=>{let s=He(),u=jt.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let[d,c,m,l]=u,f=t.length,y=a.length,$=0,x=[],C=[],b=[],E=[],T=s.stackSave(),S=s.stackAlloc(f*4),B=s.stackAlloc(f*4),D=s.stackAlloc(y*4),U=s.stackAlloc(y*4);try{[$,x]=Iu(n);for(let Q=0;QNe*Ue,1);he=ft(re);let At=l?.outputPreferredLocations[a[Q]];if(he==="string"){if(At==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ne=[],Ue=ge/4;for(let Qe=0;Qe0){let Ne=s.jsepGetBuffer(ge),Ue=ln(re);if(Ue===void 0||!_a(he))throw new Error(`Unsupported data type: ${he}`);ce=!0,me.push([he,Re,{gpuBuffer:Ne,download:s.jsepCreateDownloader(Ne,We*Ue,he),dispose:()=>{s._OrtReleaseTensor(Ce)}},"gpu-buffer"])}else{let Ne=ba(he),Ue=new Ne(We);new Uint8Array(Ue.buffer,Ue.byteOffset,Ue.byteLength).set(s.HEAPU8.subarray(ge,ge+Ue.byteLength)),me.push([he,Re,Ue,"cpu"])}}finally{s.stackRestore(ve),he==="string"&&ge&&s._free(ge),ce||s._OrtReleaseTensor(Ce)}}return l&&s._OrtClearBoundOutputs(l.handle),me}finally{s.stackRestore(T),C.forEach(P=>s._OrtReleaseTensor(P)),b.forEach(P=>s._OrtReleaseTensor(P)),E.forEach(P=>s._free(P)),$!==0&&s._OrtReleaseRunOptions($),x.forEach(P=>s._free(P))}},tp=e=>{let t=He(),r=jt.get(e);if(!r)throw new Error("invalid session id");let a=r[0],i=t._OrtEndProfiling(a);i===0&&ze("Can't get an profile file name."),t._OrtFree(i)},rp=e=>{let t=[];for(let r of e){let a=r[2];!Array.isArray(a)&&"buffer"in a&&t.push(a.buffer)}return t}}),Dc=Xt((e,t)=>{t.exports='/*!\n * ONNX Runtime Web v1.17.1\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var hn=Object.defineProperty;var Lu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var ju=Object.prototype.hasOwnProperty;var j=(e,t)=>()=>(e&&(t=e(e=0)),t);var dr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Br=(e,t)=>{for(var r in t)hn(e,r,{get:t[r],enumerable:!0})},qu=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fu(t))!ju.call(e,n)&&n!==r&&hn(e,n,{get:()=>t[n],enumerable:!(o=Lu(t,n))||o.enumerable});return e};var Ht=e=>qu(hn({},"__esModule",{value:!0}),e);var gn={};Br(gn,{createReadStream:()=>xo,readFile:()=>Ku,readFileSync:()=>Yu});var Ku,Yu,xo,yn=j(()=>{Ku=void 0,Yu=void 0,xo=void 0});var bn={};Br(bn,{join:()=>Zu});var Zu,wn=j(()=>{Zu=void 0});var Io=dr((Co,vn)=>{"use strict";var _o=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){var r=t,o,n;r.ready=new Promise((d,m)=>{o=d,n=m}),r.mountExternalData=(d,m)=>{(r.Fa||(r.Fa=new Map)).set(d,m)},r.unmountExternalData=()=>{delete r.Fa},r.jsepInit=(d,m,v,C,B,H,q,le)=>{r.ab=d,r.Qa=m,r.Sa=v,r.La=C,r.Ra=B,r.sa=H,r.Ta=q,r.Ua=le,m=(J,re,se)=>(...we)=>{let _e=tt,P=re?.();we=J(...we);let ue=re?.();return P!==ue&&(J=ue,se(P),re=se=null),tt!=_e?xr():we},v=J=>async(...re)=>{try{if(r.Ea)throw Error("Session already started");let se=r.Ea={Va:re[0],errors:[]},we=await J(...re);if(r.Ea!==se)throw Error("Session mismatch");d.flush();let _e=se.errors;if(0<_e.length){let P=await Promise.all(_e);if(P=P.filter(ue=>ue),0r._OrtRun,J=>r._OrtRun=J)),r._OrtRunWithBinding=v(m(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,J=>r._OrtRunWithBinding=J)),r._OrtBindInput=m(r._OrtBindInput,()=>r._OrtBindInput,J=>r._OrtBindInput=J),r.jsepRegisterBuffer=(J,re,se,we)=>d.registerBuffer(J,re,se,we),r.jsepUnregisterBuffers=J=>{d.unregisterBuffers(J)},r.jsepGetBuffer=J=>d.getBuffer(J),r.jsepCreateDownloader=(J,re,se)=>d.createDownloader(J,re,se)};var s=Object.assign({},r),u="./this.program",l=(d,m)=>{throw m},a=typeof window=="object",p=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="",b,w,y;if(h){var _=(yn(),Ht(gn)),I=(wn(),Ht(bn));g=p?I.dirname(g)+"/":__dirname+"/",b=(d,m)=>(d=We(d)?new URL(d):I.normalize(d),_.readFileSync(d,m?void 0:"utf8")),y=d=>(d=b(d,!0),d.buffer||(d=new Uint8Array(d)),d),w=(d,m,v,C=!0)=>{d=We(d)?new URL(d):I.normalize(d),_.readFile(d,C?void 0:"utf8",(B,H)=>{B?v(B):m(C?H.buffer:H)})},!r.thisProgram&&1{throw process.exitCode=d,m},r.inspect=()=>"[Emscripten Module object]"}else(a||p)&&(p?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),e&&(g=e),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",b=d=>{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.send(null),m.responseText},p&&(y=d=>{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),w=(d,m,v)=>{var C=new XMLHttpRequest;C.open("GET",d,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?m(C.response):v()},C.onerror=v,C.send(null)});var $=console.log.bind(console),x=console.error.bind(console);Object.assign(r,s),s=null,typeof WebAssembly!="object"&&he("no native wasm support detected");var E,A=!1,z,R,V,T,N,te,Y;function K(){var d=E.buffer;r.HEAP8=R=new Int8Array(d),r.HEAP16=new Int16Array(d),r.HEAPU8=V=new Uint8Array(d),r.HEAPU16=new Uint16Array(d),r.HEAP32=T=new Int32Array(d),r.HEAPU32=N=new Uint32Array(d),r.HEAPF32=te=new Float32Array(d),r.HEAPF64=Y=new Float64Array(d)}var Q=[],Z=[],Ee=[],Pe=0,fe=null,Ie=null;function he(d){throw d="Aborted("+d+")",x(d),A=!0,z=1,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),n(d),d}var ye=d=>d.startsWith("data:application/octet-stream;base64,"),We=d=>d.startsWith("file://"),De;if(De="ort-wasm-simd.wasm",!ye(De)){var Ge=De;De=r.locateFile?r.locateFile(Ge,g):g+Ge}function G(d){if(y)return y(d);throw"both async and sync fetching of the wasm failed"}function ee(d){if(a||p){if(typeof fetch=="function"&&!We(d))return fetch(d,{credentials:"same-origin"}).then(m=>{if(!m.ok)throw"failed to load wasm binary file at \'"+d+"\'";return m.arrayBuffer()}).catch(()=>G(d));if(w)return new Promise((m,v)=>{w(d,C=>m(new Uint8Array(C)),v)})}return Promise.resolve().then(()=>G(d))}function be(d,m,v){return ee(d).then(C=>WebAssembly.instantiate(C,m)).then(C=>C).then(v,C=>{x(`failed to asynchronously prepare wasm: ${C}`),he(C)})}function et(d,m){var v=De;return typeof WebAssembly.instantiateStreaming!="function"||ye(v)||We(v)||h||typeof fetch!="function"?be(v,d,m):fetch(v,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,d).then(m,function(B){return x(`wasm streaming compile failed: ${B}`),x("falling back to ArrayBuffer instantiation"),be(v,d,m)}))}var ze,Ue={931056:(d,m,v,C)=>{if(typeof r>"u"||!r.Fa)return 1;if(d=qe(d>>>0),d.startsWith("./")&&(d=d.substring(2)),d=r.Fa.get(d),!d)return 2;if(m>>>=0,v>>>=0,m+v>d.byteLength)return 3;try{return V.set(d.subarray(m,m+v),C>>>0>>>0),0}catch{return 4}},931557:d=>r.Qa(d),931590:d=>r.Sa(d),931622:(d,m,v)=>{r.La(d,m,v,!0)},931661:(d,m,v)=>{r.La(d,m,v)},931694:d=>{r.sa("Abs",d,void 0)},931745:d=>{r.sa("Neg",d,void 0)},931796:d=>{r.sa("Floor",d,void 0)},931849:d=>{r.sa("Ceil",d,void 0)},931901:d=>{r.sa("Reciprocal",d,void 0)},931959:d=>{r.sa("Sqrt",d,void 0)},932011:d=>{r.sa("Exp",d,void 0)},932062:d=>{r.sa("Erf",d,void 0)},932113:d=>{r.sa("Sigmoid",d,void 0)},932168:d=>{r.sa("Log",d,void 0)},932219:d=>{r.sa("Sin",d,void 0)},932270:d=>{r.sa("Cos",d,void 0)},932321:d=>{r.sa("Tan",d,void 0)},932372:d=>{r.sa("Asin",d,void 0)},932424:d=>{r.sa("Acos",d,void 0)},932476:d=>{r.sa("Atan",d,void 0)},932528:d=>{r.sa("Sinh",d,void 0)},932580:d=>{r.sa("Cosh",d,void 0)},932632:d=>{r.sa("Asinh",d,void 0)},932685:d=>{r.sa("Acosh",d,void 0)},932738:d=>{r.sa("Atanh",d,void 0)},932791:d=>{r.sa("Tanh",d,void 0)},932843:d=>{r.sa("Not",d,void 0)},932894:(d,m,v)=>{r.sa("Clip",d,{min:m,max:v})},932963:d=>{r.sa("Clip",d,void 0)},933015:(d,m)=>{r.sa("Elu",d,{alpha:m})},933073:d=>{r.sa("Relu",d,void 0)},933125:(d,m)=>{r.sa("LeakyRelu",d,{alpha:m})},933189:(d,m)=>{r.sa("ThresholdedRelu",d,{alpha:m})},933259:(d,m)=>{r.sa("Cast",d,{to:m})},933317:d=>{r.sa("Add",d,void 0)},933368:d=>{r.sa("Sub",d,void 0)},933419:d=>{r.sa("Mul",d,void 0)},933470:d=>{r.sa("Div",d,void 0)},933521:d=>{r.sa("Pow",d,void 0)},933572:d=>{r.sa("Equal",d,void 0)},933625:d=>{r.sa("Greater",d,void 0)},933680:d=>{r.sa("GreaterOrEqual",d,void 0)},933742:d=>{r.sa("Less",d,void 0)},933794:d=>{r.sa("LessOrEqual",d,void 0)},933853:(d,m,v,C,B)=>{r.sa("ReduceMean",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934012:(d,m,v,C,B)=>{r.sa("ReduceMax",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934170:(d,m,v,C,B)=>{r.sa("ReduceMin",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934328:(d,m,v,C,B)=>{r.sa("ReduceProd",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934487:(d,m,v,C,B)=>{r.sa("ReduceSum",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934645:(d,m,v,C,B)=>{r.sa("ReduceL1",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934802:(d,m,v,C,B)=>{r.sa("ReduceL2",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934959:(d,m,v,C,B)=>{r.sa("ReduceLogSum",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935120:(d,m,v,C,B)=>{r.sa("ReduceSumSquare",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935284:(d,m,v,C,B)=>{r.sa("ReduceLogSumExp",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935448:d=>{r.sa("Where",d,void 0)},935501:(d,m,v)=>{r.sa("Transpose",d,{perm:m?Array.from(T.subarray(m>>>0,v>>>0)):[]})},935609:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue)=>{r.sa("ConvTranspose",d,{format:J?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernel_shape:[B],pads:[H,q],strides:[le],wIsConst:()=>!!R[re>>>0],outputPadding:se?Array.from(T.subarray(se>>>0,we>>>0)):[],outputShape:_e?Array.from(T.subarray(_e>>>0,P>>>0)):[],activation:qe(ue)})},936011:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P)=>{r.sa("ConvTranspose",d,{format:le?"NHWC":"NCHW",autoPad:m,dilations:Array.from(T.subarray(v>>>0,(v>>>0)+2>>>0)),group:C,kernelShape:Array.from(T.subarray(B>>>0,(B>>>0)+2>>>0)),pads:Array.from(T.subarray(H>>>0,(H>>>0)+4>>>0)),strides:Array.from(T.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!R[J>>>0],outputPadding:re?Array.from(T.subarray(re>>>0,se>>>0)):[],outputShape:we?Array.from(T.subarray(we>>>0,_e>>>0)):[],activation:qe(P)})},936576:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue)=>{r.sa("ConvTranspose",d,{format:J?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernel_shape:[B],pads:[H,q],strides:[le],wIsConst:()=>!!R[re>>>0],outputPadding:se?Array.from(T.subarray(se>>>0,we>>>0)):[],outputShape:_e?Array.from(T.subarray(_e>>>0,P>>>0)):[],activation:qe(ue)})},936978:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P)=>{r.sa("ConvTranspose",d,{format:le?"NHWC":"NCHW",autoPad:m,dilations:Array.from(T.subarray(v>>>0,(v>>>0)+2>>>0)),group:C,kernelShape:Array.from(T.subarray(B>>>0,(B>>>0)+2>>>0)),pads:Array.from(T.subarray(H>>>0,(H>>>0)+4>>>0)),strides:Array.from(T.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!R[J>>>0],outputPadding:re?Array.from(T.subarray(re>>>0,se>>>0)):[],outputShape:we?Array.from(T.subarray(we>>>0,_e>>>0)):[],activation:qe(P)})},937543:(d,m)=>{r.sa("GlobalAveragePool",d,{format:m?"NHWC":"NCHW"})},937634:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("AveragePool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},937918:(d,m)=>{r.sa("GlobalAveragePool",d,{format:m?"NHWC":"NCHW"})},938009:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("AveragePool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},938293:(d,m)=>{r.sa("GlobalMaxPool",d,{format:m?"NHWC":"NCHW"})},938380:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("MaxPool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},938660:(d,m)=>{r.sa("GlobalMaxPool",d,{format:m?"NHWC":"NCHW"})},938747:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("MaxPool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},939027:(d,m,v,C,B)=>{r.sa("Gemm",d,{alpha:m,beta:v,transA:C,transB:B})},939131:d=>{r.sa("MatMul",d,void 0)},939185:(d,m,v,C)=>{r.sa("ArgMax",d,{keepDims:!!m,selectLastIndex:!!v,axis:C})},939293:(d,m,v,C)=>{r.sa("ArgMin",d,{keepDims:!!m,selectLastIndex:!!v,axis:C})},939401:(d,m)=>{r.sa("Softmax",d,{axis:m})},939464:(d,m)=>{r.sa("Concat",d,{axis:m})},939524:(d,m,v,C,B)=>{r.sa("Split",d,{axis:m,numOutputs:v,splitSizes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},939664:d=>{r.sa("Expand",d,void 0)},939718:(d,m)=>{r.sa("Gather",d,{axis:Number(m)})},939789:(d,m)=>{r.sa("GatherElements",d,{axis:Number(m)})},939868:(d,m,v,C,B,H,q,le,J,re,se)=>{r.sa("Resize",d,{antialias:m,axes:v?Array.from(T.subarray(v>>>0,C>>>0)):[],coordinateTransformMode:qe(B),cubicCoeffA:H,excludeOutside:q,extrapolationValue:le,keepAspectRatioPolicy:qe(J),mode:qe(re),nearestMode:qe(se)})},940214:(d,m,v,C,B,H,q)=>{r.sa("Slice",d,{starts:m?Array.from(T.subarray(m>>>0,v>>>0)):[],ends:C?Array.from(T.subarray(C>>>0,B>>>0)):[],axes:H?Array.from(T.subarray(H>>>0,q>>>0)):[]})},940430:d=>{r.sa("Tile",d,void 0)},940482:(d,m,v)=>{r.sa("LayerNormalization",d,{axis:Number(m),epsilon:Number(v)})},940589:(d,m,v)=>{r.sa("InstanceNormalization",d,{epsilon:m,format:v?"NHWC":"NCHW"})},940703:(d,m,v)=>{r.sa("InstanceNormalization",d,{epsilon:m,format:v?"NHWC":"NCHW"})},940817:d=>{r.sa("Range",d,void 0)},940870:(d,m)=>{r.sa("Einsum",d,{equation:qe(m)})},940951:(d,m,v,C,B)=>{r.sa("Pad",d,{mode:m,value:v,pads:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},941078:(d,m,v,C,B,H)=>{r.sa("BatchNormalization",d,{epsilon:m,momentum:v,spatial:!!B,trainingMode:!!C,format:H?"NHWC":"NCHW"})},941247:(d,m,v,C,B,H)=>{r.sa("BatchNormalization",d,{epsilon:m,momentum:v,spatial:!!B,trainingMode:!!C,format:H?"NHWC":"NCHW"})},941416:(d,m,v)=>{r.sa("CumSum",d,{exclusive:Number(m),reverse:Number(v)})},941513:(d,m,v,C,B,H,q,le,J)=>{r.sa("Attention",d,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:B,doRotary:H,qkvHiddenSizes:q?Array.from(T.subarray(Number(le)>>>0,Number(le)+q>>>0)):[],pastPresentShareBuffer:!!J})},941785:d=>{r.sa("Gelu",d,void 0)},941837:(d,m,v,C,B,H)=>{r.sa("MultiHeadAttention",d,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:B,doRotary:H})},941996:d=>{r.sa("BiasAdd",d,void 0)},942051:d=>{r.sa("BiasSplitGelu",d,void 0)},942112:(d,m)=>{r.sa("SkipLayerNormalization",d,{epsilon:m})},942193:(d,m,v,C,B,H,q,le,J,re,se,we,_e)=>{r.sa("Conv",d,{format:J?"NHWC":"NCHW",auto_pad:m,dilations:[v],group:C,kernel_shape:[B],pads:H?Array.from(T.subarray(H>>>0,q>>>0)):[],strides:[le],w_is_const:()=>!!R[re>>>0],activation:qe(se),activation_params:we?Array.from(te.subarray(we>>>0,_e>>>0)):[]})},942563:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("Conv",d,{format:we?"NHWC":"NCHW",auto_pad:m,dilations:[v,C],group:B,kernel_shape:[H,q],pads:le?Array.from(T.subarray(le>>>0,J>>>0)):[],strides:[re,se],w_is_const:()=>!!R[_e>>>0],activation:qe(P),activation_params:ue?Array.from(te.subarray(ue>>>0,Se>>>0)):[]})},942954:d=>{r.Ta(d)},942988:(d,m)=>r.Ua(d,m,r.Ea.Va,r.Ea.errors)};function Me(d){this.name="ExitStatus",this.message=`Program terminated with exit(${d})`,this.status=d}function wt(d){this.Ja=d-24,this.Oa=function(m){N[this.Ja+4>>>2>>>0]=m},this.Na=function(m){N[this.Ja+8>>>2>>>0]=m},this.$a=function(m,v){this.Ma(),this.Oa(m),this.Na(v)},this.Ma=function(){N[this.Ja+16>>>2>>>0]=0}}var rt=0,Dt=0,At=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,vt=(d,m,v)=>{m>>>=0;var C=m+v;for(v=m;d[v]&&!(v>=C);)++v;if(16B?C+=String.fromCharCode(B):(B-=65536,C+=String.fromCharCode(55296|B>>10,56320|B&1023))}}else C+=String.fromCharCode(B)}return C},qe=(d,m)=>(d>>>=0)?vt(V,d,m):"",qt=d=>{for(var m=0,v=0;v=C?m++:2047>=C?m+=2:55296<=C&&57343>=C?(m+=4,++v):m+=3}return m},Mt=(d,m,v,C)=>{if(v>>>=0,!(0=q){var le=d.charCodeAt(++H);q=65536+((q&1023)<<10)|le&1023}if(127>=q){if(v>=C)break;m[v++>>>0]=q}else{if(2047>=q){if(v+1>=C)break;m[v++>>>0]=192|q>>6}else{if(65535>=q){if(v+2>=C)break;m[v++>>>0]=224|q>>12}else{if(v+3>=C)break;m[v++>>>0]=240|q>>18,m[v++>>>0]=128|q>>12&63}m[v++>>>0]=128|q>>6&63}m[v++>>>0]=128|q&63}}return m[v>>>0]=0,v-B},$t=d=>d%4===0&&(d%100!==0||d%400===0),yt=[0,31,60,91,121,152,182,213,244,274,305,335],zt=[0,31,59,90,120,151,181,212,243,273,304,334],Ut=d=>{var m=qt(d)+1,v=Wt(m);return v&&Mt(d,V,v,m),v},Tt=[],Kt=(d,m)=>{Tt.length=0;for(var v;v=V[d++>>>0];){var C=v!=105;C&=v!=112,m+=C&&m%8?4:0,Tt.push(v==112?N[m>>>2>>>0]:v==105?T[m>>>2>>>0]:Y[m>>>3>>>0]),m+=C?8:4}return Tt},nt={},Yt=()=>{if(!Vt){var d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:u||"./this.program"},m;for(m in nt)nt[m]===void 0?delete d[m]:d[m]=nt[m];var v=[];for(m in d)v.push(`${m}=${d[m]}`);Vt=v}return Vt},Vt,Ye=[null,[],[]],br=[31,29,31,30,31,30,31,31,30,31,30,31],Oe=[31,28,31,30,31,30,31,31,30,31,30,31];function wr(d){var m=Array(qt(d)+1);return Mt(d,m,0,m.length),m}function Nt(d,m,v,C){function B(P,ue,Se){for(P=typeof P=="number"?P.toString():P||"";P.lengthTr?-1:0st-P.getDate())ue-=st-P.getDate()+1,P.setDate(1),11>Se?P.setMonth(Se+1):(P.setMonth(0),P.setFullYear(P.getFullYear()+1));else{P.setDate(P.getDate()+ue);break}}return Se=new Date(P.getFullYear()+1,0,4),ue=le(new Date(P.getFullYear(),0,4)),Se=le(Se),0>=q(ue,P)?0>=q(Se,P)?P.getFullYear()+1:P.getFullYear():P.getFullYear()-1}d>>>=0,m>>>=0,v>>>=0,C>>>=0;var re=N[C+40>>>2>>>0];C={Ya:T[C>>>2>>>0],Xa:T[C+4>>>2>>>0],Ga:T[C+8>>>2>>>0],Ka:T[C+12>>>2>>>0],Ha:T[C+16>>>2>>>0],Da:T[C+20>>>2>>>0],xa:T[C+24>>>2>>>0],Ca:T[C+28>>>2>>>0],bb:T[C+32>>>2>>>0],Wa:T[C+36>>>2>>>0],Za:re?qe(re):""},v=qe(v),re={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var se in re)v=v.replace(new RegExp(se,"g"),re[se]);var we="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),_e="January February March April May June July August September October November December".split(" ");re={"%a":P=>we[P.xa].substring(0,3),"%A":P=>we[P.xa],"%b":P=>_e[P.Ha].substring(0,3),"%B":P=>_e[P.Ha],"%C":P=>H((P.Da+1900)/100|0,2),"%d":P=>H(P.Ka,2),"%e":P=>B(P.Ka,2," "),"%g":P=>J(P).toString().substring(2),"%G":P=>J(P),"%H":P=>H(P.Ga,2),"%I":P=>(P=P.Ga,P==0?P=12:12{for(var ue=0,Se=0;Se<=P.Ha-1;ue+=($t(P.Da+1900)?br:Oe)[Se++]);return H(P.Ka+ue,3)},"%m":P=>H(P.Ha+1,2),"%M":P=>H(P.Xa,2),"%n":()=>`\n`,"%p":P=>0<=P.Ga&&12>P.Ga?"AM":"PM","%S":P=>H(P.Ya,2),"%t":()=>" ","%u":P=>P.xa||7,"%U":P=>H(Math.floor((P.Ca+7-P.xa)/7),2),"%V":P=>{var ue=Math.floor((P.Ca+7-(P.xa+6)%7)/7);if(2>=(P.xa+371-P.Ca-2)%7&&ue++,ue)ue==53&&(Se=(P.xa+371-P.Ca)%7,Se==4||Se==3&&$t(P.Da)||(ue=1));else{ue=52;var Se=(P.xa+7-P.Ca-1)%7;(Se==4||Se==5&&$t(P.Da%400-1))&&ue++}return H(ue,2)},"%w":P=>P.xa,"%W":P=>H(Math.floor((P.Ca+7-(P.xa+6)%7)/7),2),"%y":P=>(P.Da+1900).toString().substring(2),"%Y":P=>P.Da+1900,"%z":P=>{P=P.Wa;var ue=0<=P;return P=Math.abs(P)/60,(ue?"+":"-")+("0000"+(P/60*100+P%60)).slice(-4)},"%Z":P=>P.Za,"%%":()=>"%"},v=v.replace(/%%/g,"\\0\\0");for(se in re)v.includes(se)&&(v=v.replace(new RegExp(se,"g"),re[se](C)));return v=v.replace(/\\0\\0/g,"%"),se=wr(v),se.length>m?0:(R.set(se,d>>>0),se.length-1)}var St=d=>{try{d()}catch(m){he(m)}};function un(){var d=ae,m={};for(let[v,C]of Object.entries(d))m[v]=typeof C=="function"?function(){bt.push(v);try{return C.apply(null,arguments)}finally{A||(bt.pop(),tt&&ot===1&&bt.length===0&&(ot=0,St(ir),typeof Fibers<"u"&&Fibers.cb()))}}:C;return m}var ot=0,tt=null,de=0,bt=[],Zt={},vr={},$r=0,Qt=null,Sr=[];function xr(){return new Promise((d,m)=>{Qt={resolve:d,reject:m}})}function _r(){var d=Wt(65548),m=d+12;N[d>>>2>>>0]=m,N[d+4>>>2>>>0]=m+65536,m=bt[0];var v=Zt[m];return v===void 0&&(v=$r++,Zt[m]=v,vr[v]=m),T[d+8>>>2>>>0]=v,d}function Cr(d){if(!A){if(ot===0){var m=!1,v=!1;d((C=0)=>{if(!A&&(de=C,m=!0,v)){ot=2,St(()=>sr(tt)),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.resume(),C=!1;try{var B=(0,ae[vr[T[tt+8>>>2>>>0]]])()}catch(le){B=le,C=!0}var H=!1;if(!tt){var q=Qt;q&&(Qt=null,(C?q.reject:q.resolve)(B),H=!0)}if(C&&!H)throw B}}),v=!0,m||(ot=1,tt=_r(),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.pause(),St(()=>ar(tt)))}else ot===2?(ot=0,St(ur),er(tt),tt=null,Sr.forEach(C=>{if(!A)try{C();try{z=z=C=z,r.onExit?.(C),A=!0,l(C,new Me(C))}catch(B){B instanceof Me||B=="unwind"||l(1,B)}}catch(B){B instanceof Me||B=="unwind"||l(1,B)}})):he(`invalid state: ${ot}`);return de}}function Xt(d){return Cr(m=>{d().then(m)})}var Ir={n:function(d,m,v){return Xt(async()=>{await r.Ra(d,m,v)})},a:function(d,m,v){throw d>>>=0,new wt(d).$a(m>>>0,v>>>0),rt=d,Dt++,rt},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(d,m,v){d=m+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*m:NaN,v>>>=0,d=new Date(1e3*d),T[v>>>2>>>0]=d.getUTCSeconds(),T[v+4>>>2>>>0]=d.getUTCMinutes(),T[v+8>>>2>>>0]=d.getUTCHours(),T[v+12>>>2>>>0]=d.getUTCDate(),T[v+16>>>2>>>0]=d.getUTCMonth(),T[v+20>>>2>>>0]=d.getUTCFullYear()-1900,T[v+24>>>2>>>0]=d.getUTCDay(),T[v+28>>>2>>>0]=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(d,m,v){d=m+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*m:NaN,v>>>=0,d=new Date(1e3*d),T[v>>>2>>>0]=d.getSeconds(),T[v+4>>>2>>>0]=d.getMinutes(),T[v+8>>>2>>>0]=d.getHours(),T[v+12>>>2>>>0]=d.getDate(),T[v+16>>>2>>>0]=d.getMonth(),T[v+20>>>2>>>0]=d.getFullYear()-1900,T[v+24>>>2>>>0]=d.getDay(),T[v+28>>>2>>>0]=($t(d.getFullYear())?yt:zt)[d.getMonth()]+d.getDate()-1|0,T[v+36>>>2>>>0]=-(60*d.getTimezoneOffset()),m=new Date(d.getFullYear(),6,1).getTimezoneOffset();var C=new Date(d.getFullYear(),0,1).getTimezoneOffset();T[v+32>>>2>>>0]=(m!=C&&d.getTimezoneOffset()==Math.min(C,m))|0},s:function(d){d>>>=0;var m=new Date(T[d+20>>>2>>>0]+1900,T[d+16>>>2>>>0],T[d+12>>>2>>>0],T[d+8>>>2>>>0],T[d+4>>>2>>>0],T[d>>>2>>>0],0),v=T[d+32>>>2>>>0],C=m.getTimezoneOffset(),B=new Date(m.getFullYear(),6,1).getTimezoneOffset(),H=new Date(m.getFullYear(),0,1).getTimezoneOffset(),q=Math.min(H,B);return 0>v?T[d+32>>>2>>>0]=+(B!=H&&q==C):0>>2>>>0]=m.getDay(),T[d+28>>>2>>>0]=($t(m.getFullYear())?yt:zt)[m.getMonth()]+m.getDate()-1|0,T[d>>>2>>>0]=m.getSeconds(),T[d+4>>>2>>>0]=m.getMinutes(),T[d+8>>>2>>>0]=m.getHours(),T[d+12>>>2>>>0]=m.getDate(),T[d+16>>>2>>>0]=m.getMonth(),T[d+20>>>2>>>0]=m.getYear(),d=m.getTime(),isNaN(d)?(T[Jt()>>>2>>>0]=61,d=-1):d/=1e3,tr((ze=d,1<=+Math.abs(ze)?0>>0:~~+Math.ceil((ze-+(~~ze>>>0))/4294967296)>>>0:0)),d>>>0},o:function(){return-52},p:function(){},w:function(d,m,v){function C(J){return(J=J.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?J[1]:"GMT"}v>>>=0;var B=new Date().getFullYear(),H=new Date(B,0,1),q=new Date(B,6,1);B=H.getTimezoneOffset();var le=q.getTimezoneOffset();N[d>>>0>>>2>>>0]=60*Math.max(B,le),T[m>>>0>>>2>>>0]=+(B!=le),d=C(H),m=C(q),d=Ut(d),m=Ut(m),le>>2>>>0]=d,N[v+4>>>2>>>0]=m):(N[v>>>2>>>0]=m,N[v+4>>>2>>>0]=d)},e:()=>{he("")},b:function(d,m,v){return d>>>=0,m=Kt(m>>>0,v>>>0),Ue[d].apply(null,m)},i:function(d,m,v){return d>>>=0,m=Kt(m>>>0,v>>>0),Ue[d].apply(null,m)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(d,m,v){return m>>>=0,V.copyWithin(d>>>0>>>0,m>>>0,m+(v>>>0)>>>0)},u:function(d){d>>>=0;var m=V.length;if(4294901760=v;v*=2){var C=m*(1+.2/v);C=Math.min(C,d+100663296);var B=Math;C=Math.max(d,C);e:{B=(B.min.call(B,4294901760,C+(65536-C%65536)%65536)-E.buffer.byteLength+65535)/65536;try{E.grow(B),K();var H=1;break e}catch{}H=void 0}if(H)return!0}return!1},E:function(d,m){d>>>=0,m>>>=0;var v=0;return Yt().forEach((C,B)=>{var H=m+v;for(B=N[d+4*B>>>2>>>0]=H,H=0;H>>0>>>0]=C.charCodeAt(H);R[B>>>0>>>0]=0,v+=C.length+1}),0},F:function(d,m){d>>>=0,m>>>=0;var v=Yt();N[d>>>2>>>0]=v.length;var C=0;return v.forEach(B=>C+=B.length+1),N[m>>>2>>>0]=C,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(d,m,v,C){m>>>=0,v>>>=0,C>>>=0;for(var B=0,H=0;H>>2>>>0],le=N[m+4>>>2>>>0];m+=8;for(var J=0;J>>0],se=Ye[d];re===0||re===10?((d===1?$:x)(vt(se,0)),se.length=0):se.push(re)}B+=le}return N[C>>>2>>>0]=B,0},v:Nt,d:function(d,m,v,C){return Nt(d>>>0,m>>>0,v>>>0,C>>>0)}},ae=function(){function d(v){return ae=v.exports,ae=un(),ae=Ar(),E=ae.M,K(),Z.unshift(ae.N),Pe--,Pe==0&&(fe!==null&&(clearInterval(fe),fe=null),Ie&&(v=Ie,Ie=null,v())),ae}var m={a:Ir};if(Pe++,r.instantiateWasm)try{return r.instantiateWasm(m,d)}catch(v){x(`Module.instantiateWasm callback failed with error: ${v}`),n(v)}return et(m,function(v){d(v.instance)}).catch(n),{}}();r._OrtInit=(d,m)=>(r._OrtInit=ae.O)(d,m),r._OrtGetLastError=(d,m)=>(r._OrtGetLastError=ae.P)(d,m),r._OrtCreateSessionOptions=(d,m,v,C,B,H,q,le,J,re)=>(r._OrtCreateSessionOptions=ae.Q)(d,m,v,C,B,H,q,le,J,re),r._OrtAppendExecutionProvider=(d,m)=>(r._OrtAppendExecutionProvider=ae.R)(d,m),r._OrtAddFreeDimensionOverride=(d,m,v)=>(r._OrtAddFreeDimensionOverride=ae.S)(d,m,v),r._OrtAddSessionConfigEntry=(d,m,v)=>(r._OrtAddSessionConfigEntry=ae.T)(d,m,v),r._OrtReleaseSessionOptions=d=>(r._OrtReleaseSessionOptions=ae.U)(d),r._OrtCreateSession=(d,m,v)=>(r._OrtCreateSession=ae.V)(d,m,v),r._OrtReleaseSession=d=>(r._OrtReleaseSession=ae.W)(d),r._OrtGetInputOutputCount=(d,m,v)=>(r._OrtGetInputOutputCount=ae.X)(d,m,v),r._OrtGetInputName=(d,m)=>(r._OrtGetInputName=ae.Y)(d,m),r._OrtGetOutputName=(d,m)=>(r._OrtGetOutputName=ae.Z)(d,m),r._OrtFree=d=>(r._OrtFree=ae._)(d),r._OrtCreateTensor=(d,m,v,C,B,H)=>(r._OrtCreateTensor=ae.$)(d,m,v,C,B,H),r._OrtGetTensorData=(d,m,v,C,B)=>(r._OrtGetTensorData=ae.aa)(d,m,v,C,B),r._OrtReleaseTensor=d=>(r._OrtReleaseTensor=ae.ba)(d),r._OrtCreateRunOptions=(d,m,v,C)=>(r._OrtCreateRunOptions=ae.ca)(d,m,v,C),r._OrtAddRunConfigEntry=(d,m,v)=>(r._OrtAddRunConfigEntry=ae.da)(d,m,v),r._OrtReleaseRunOptions=d=>(r._OrtReleaseRunOptions=ae.ea)(d),r._OrtCreateBinding=d=>(r._OrtCreateBinding=ae.fa)(d),r._OrtBindInput=(d,m,v)=>(r._OrtBindInput=ae.ga)(d,m,v),r._OrtBindOutput=(d,m,v,C)=>(r._OrtBindOutput=ae.ha)(d,m,v,C),r._OrtClearBoundOutputs=d=>(r._OrtClearBoundOutputs=ae.ia)(d),r._OrtReleaseBinding=d=>(r._OrtReleaseBinding=ae.ja)(d),r._OrtRunWithBinding=(d,m,v,C,B)=>(r._OrtRunWithBinding=ae.ka)(d,m,v,C,B),r._OrtRun=(d,m,v,C,B,H,q,le)=>(r._OrtRun=ae.la)(d,m,v,C,B,H,q,le),r._OrtEndProfiling=d=>(r._OrtEndProfiling=ae.ma)(d),r._JsepOutput=(d,m,v)=>(r._JsepOutput=ae.na)(d,m,v),r._JsepGetNodeName=d=>(r._JsepGetNodeName=ae.oa)(d);var Jt=()=>(Jt=ae.pa)(),Wt=r._malloc=d=>(Wt=r._malloc=ae.qa)(d),er=r._free=d=>(er=r._free=ae.ra)(d),tr=d=>(tr=ae.ta)(d),rr=()=>(rr=ae.ua)(),nr=d=>(nr=ae.va)(d),or=d=>(or=ae.wa)(d),ar=d=>(ar=ae.ya)(d),ir=()=>(ir=ae.za)(),sr=d=>(sr=ae.Aa)(d),ur=()=>(ur=ae.Ba)();r.___start_em_js=943100,r.___stop_em_js=943261;function Ar(){var d=ae;d=Object.assign({},d);var m=C=>()=>C()>>>0,v=C=>B=>C(B)>>>0;return d.pa=m(d.pa),d.qa=v(d.qa),d.ua=m(d.ua),d.wa=v(d.wa),d}r.stackAlloc=or,r.stackSave=rr,r.stackRestore=nr,r.UTF8ToString=qe,r.stringToUTF8=(d,m,v)=>Mt(d,V,m,v),r.lengthBytesUTF8=qt;var xt;Ie=function d(){xt||Et(),xt||(Ie=d)};function Et(){if(!(0_o)});var Ao=dr(()=>{});var To=dr(()=>{});var Eo={};Br(Eo,{cpus:()=>Qu});var Qu,Oo=j(()=>{Qu=void 0});var Ro=dr((ko,$n)=>{"use strict";var Po=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){function r(){return Q.buffer!=fe.buffer&&Ge(),fe}function o(){return Q.buffer!=fe.buffer&&Ge(),Ie}function n(){return Q.buffer!=fe.buffer&&Ge(),he}function s(){return Q.buffer!=fe.buffer&&Ge(),ye}function u(){return Q.buffer!=fe.buffer&&Ge(),We}function l(){return Q.buffer!=fe.buffer&&Ge(),De}var a=t,p,h;a.ready=new Promise((i,c)=>{p=i,h=c}),a.mountExternalData=(i,c)=>{(a.cb||(a.cb=new Map)).set(i,c)},a.unmountExternalData=()=>{delete a.cb},a.jsepInit=(i,c,f,S,O,D,W,ie)=>{a.Mb=i,a.wb=c,a.yb=f,a.kb=S,a.xb=O,a.Ea=D,a.zb=W,a.Ab=ie,c=(ne,oe,pe)=>(...xe)=>{let Te=ut,k=oe?.();xe=ne(...xe);let me=oe?.();return k!==me&&(ne=me,pe(k),oe=pe=null),ut!=Te?Mu():xe},f=ne=>async(...oe)=>{try{if(a.bb)throw Error("Session already started");let pe=a.bb={Cb:oe[0],errors:[]},xe=await ne(...oe);if(a.bb!==pe)throw Error("Session mismatch");i.flush();let Te=pe.errors;if(0me),0a._OrtRun,ne=>a._OrtRun=ne)),a._OrtRunWithBinding=f(c(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,ne=>a._OrtRunWithBinding=ne)),a._OrtBindInput=c(a._OrtBindInput,()=>a._OrtBindInput,ne=>a._OrtBindInput=ne),a.jsepRegisterBuffer=(ne,oe,pe,xe)=>i.registerBuffer(ne,oe,pe,xe),a.jsepUnregisterBuffers=ne=>{i.unregisterBuffers(ne)},a.jsepGetBuffer=ne=>i.getBuffer(ne),a.jsepCreateDownloader=(ne,oe,pe)=>i.createDownloader(ne,oe,pe)};var g=Object.assign({},a),b="./this.program",w=(i,c)=>{throw c},y=typeof window=="object",_=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",$=a.ENVIRONMENT_IS_PTHREAD||!1,x="";function E(i){return a.locateFile?a.locateFile(i,x):x+i}var A,z,R;if(I){var V=(yn(),Ht(gn)),T=(wn(),Ht(bn));x=_?T.dirname(x)+"/":__dirname+"/",A=(c,f)=>(c=At(c)?new URL(c):T.normalize(c),V.readFileSync(c,f?void 0:"utf8")),R=c=>(c=A(c,!0),c.buffer||(c=new Uint8Array(c)),c),z=(c,f,S,O=!0)=>{c=At(c)?new URL(c):T.normalize(c),V.readFile(c,O?void 0:"utf8",(D,W)=>{D?S(D):f(O?W.buffer:W)})},!a.thisProgram&&1{throw process.exitCode=c,f},a.inspect=()=>"[Emscripten Module object]";let i;try{i=Ao()}catch(c){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),c}global.Worker=i.Worker}else(y||_)&&(_?x=self.location.href:typeof document<"u"&&document.currentScript&&(x=document.currentScript.src),typeof e<"u"&&e&&(x=e),x.indexOf("blob:")!==0?x=x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):x="",I||(A=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.send(null),c.responseText},_&&(R=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),z=(i,c,f)=>{var S=new XMLHttpRequest;S.open("GET",i,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?c(S.response):f()},S.onerror=f,S.send(null)}));I&&typeof performance>"u"&&(global.performance=To().performance);var N=console.log.bind(console),te=console.error.bind(console);I&&(N=(...i)=>V.writeSync(1,i.join(" ")+`\n`),te=(...i)=>V.writeSync(2,i.join(" ")+`\n`));var Y=N,K=te;Object.assign(a,g),g=null,typeof WebAssembly!="object"&&rt("no native wasm support detected");var Q,Z,Ee=!1,Pe,fe,Ie,he,ye,We,De;function Ge(){var i=Q.buffer;a.HEAP8=fe=new Int8Array(i),a.HEAP16=new Int16Array(i),a.HEAPU8=Ie=new Uint8Array(i),a.HEAPU16=new Uint16Array(i),a.HEAP32=he=new Int32Array(i),a.HEAPU32=ye=new Uint32Array(i),a.HEAPF32=We=new Float32Array(i),a.HEAPF64=De=new Float64Array(i)}var G=16777216;if($)Q=a.wasmMemory;else if(a.wasmMemory)Q=a.wasmMemory;else if(Q=new WebAssembly.Memory({initial:G/65536,maximum:65536,shared:!0}),!(Q.buffer instanceof SharedArrayBuffer))throw K("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),I&&K("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ge(),G=Q.buffer.byteLength;var ee=[],be=[],et=[],ze=0,Ue=null,Me=null;function wt(){if(ze--,ze==0&&(Ue!==null&&(clearInterval(Ue),Ue=null),Me)){var i=Me;Me=null,i()}}function rt(i){throw i="Aborted("+i+")",K(i),Ee=!0,Pe=1,i=new WebAssembly.RuntimeError(i+". Build with -sASSERTIONS for more info."),h(i),i}var Dt=i=>i.startsWith("data:application/octet-stream;base64,"),At=i=>i.startsWith("file://"),vt;vt="ort-wasm-simd-threaded.wasm",Dt(vt)||(vt=E(vt));function qe(i){if(R)return R(i);throw"both async and sync fetching of the wasm failed"}function qt(i){if(y||_){if(typeof fetch=="function"&&!At(i))return fetch(i,{credentials:"same-origin"}).then(c=>{if(!c.ok)throw"failed to load wasm binary file at \'"+i+"\'";return c.arrayBuffer()}).catch(()=>qe(i));if(z)return new Promise((c,f)=>{z(i,S=>c(new Uint8Array(S)),f)})}return Promise.resolve().then(()=>qe(i))}function Mt(i,c,f){return qt(i).then(S=>WebAssembly.instantiate(S,c)).then(S=>S).then(f,S=>{K(`failed to asynchronously prepare wasm: ${S}`),rt(S)})}function $t(i,c){var f=vt;return typeof WebAssembly.instantiateStreaming!="function"||Dt(f)||At(f)||I||typeof fetch!="function"?Mt(f,i,c):fetch(f,{credentials:"same-origin"}).then(S=>WebAssembly.instantiateStreaming(S,i).then(c,function(O){return K(`wasm streaming compile failed: ${O}`),K("falling back to ArrayBuffer instantiation"),Mt(f,i,c)}))}var yt,zt={932428:(i,c,f,S)=>{if(typeof a>"u"||!a.cb)return 1;if(i=Ye(i>>>0),i.startsWith("./")&&(i=i.substring(2)),i=a.cb.get(i),!i)return 2;if(c>>>=0,f>>>=0,S>>>=0,c+f>i.byteLength)return 3;try{return o().set(i.subarray(c,c+f),S>>>0),0}catch{return 4}},932929:i=>a.wb(i),932962:i=>a.yb(i),932994:(i,c,f)=>{a.kb(i,c,f,!0)},933033:(i,c,f)=>{a.kb(i,c,f)},933066:i=>{a.Ea("Abs",i,void 0)},933117:i=>{a.Ea("Neg",i,void 0)},933168:i=>{a.Ea("Floor",i,void 0)},933221:i=>{a.Ea("Ceil",i,void 0)},933273:i=>{a.Ea("Reciprocal",i,void 0)},933331:i=>{a.Ea("Sqrt",i,void 0)},933383:i=>{a.Ea("Exp",i,void 0)},933434:i=>{a.Ea("Erf",i,void 0)},933485:i=>{a.Ea("Sigmoid",i,void 0)},933540:i=>{a.Ea("Log",i,void 0)},933591:i=>{a.Ea("Sin",i,void 0)},933642:i=>{a.Ea("Cos",i,void 0)},933693:i=>{a.Ea("Tan",i,void 0)},933744:i=>{a.Ea("Asin",i,void 0)},933796:i=>{a.Ea("Acos",i,void 0)},933848:i=>{a.Ea("Atan",i,void 0)},933900:i=>{a.Ea("Sinh",i,void 0)},933952:i=>{a.Ea("Cosh",i,void 0)},934004:i=>{a.Ea("Asinh",i,void 0)},934057:i=>{a.Ea("Acosh",i,void 0)},934110:i=>{a.Ea("Atanh",i,void 0)},934163:i=>{a.Ea("Tanh",i,void 0)},934215:i=>{a.Ea("Not",i,void 0)},934266:(i,c,f)=>{a.Ea("Clip",i,{min:c,max:f})},934335:i=>{a.Ea("Clip",i,void 0)},934387:(i,c)=>{a.Ea("Elu",i,{alpha:c})},934445:i=>{a.Ea("Relu",i,void 0)},934497:(i,c)=>{a.Ea("LeakyRelu",i,{alpha:c})},934561:(i,c)=>{a.Ea("ThresholdedRelu",i,{alpha:c})},934631:(i,c)=>{a.Ea("Cast",i,{to:c})},934689:i=>{a.Ea("Add",i,void 0)},934740:i=>{a.Ea("Sub",i,void 0)},934791:i=>{a.Ea("Mul",i,void 0)},934842:i=>{a.Ea("Div",i,void 0)},934893:i=>{a.Ea("Pow",i,void 0)},934944:i=>{a.Ea("Equal",i,void 0)},934997:i=>{a.Ea("Greater",i,void 0)},935052:i=>{a.Ea("GreaterOrEqual",i,void 0)},935114:i=>{a.Ea("Less",i,void 0)},935166:i=>{a.Ea("LessOrEqual",i,void 0)},935225:(i,c,f,S,O)=>{a.Ea("ReduceMean",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935384:(i,c,f,S,O)=>{a.Ea("ReduceMax",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935542:(i,c,f,S,O)=>{a.Ea("ReduceMin",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935700:(i,c,f,S,O)=>{a.Ea("ReduceProd",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935859:(i,c,f,S,O)=>{a.Ea("ReduceSum",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936017:(i,c,f,S,O)=>{a.Ea("ReduceL1",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936174:(i,c,f,S,O)=>{a.Ea("ReduceL2",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936331:(i,c,f,S,O)=>{a.Ea("ReduceLogSum",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936492:(i,c,f,S,O)=>{a.Ea("ReduceSumSquare",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936656:(i,c,f,S,O)=>{a.Ea("ReduceLogSumExp",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936820:i=>{a.Ea("Where",i,void 0)},936873:(i,c,f)=>{a.Ea("Transpose",i,{perm:c?Array.from(n().subarray(c>>>0,f>>>0)):[]})},936981:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me)=>{a.Ea("ConvTranspose",i,{format:ne?"NHWC":"NCHW",autoPad:c,dilations:[f],group:S,kernel_shape:[O],pads:[D,W],strides:[ie],wIsConst:()=>!!r()[oe>>>0],outputPadding:pe?Array.from(n().subarray(pe>>>0,xe>>>0)):[],outputShape:Te?Array.from(n().subarray(Te>>>0,k>>>0)):[],activation:Ye(me)})},937383:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k)=>{a.Ea("ConvTranspose",i,{format:ie?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(f>>>0,(f>>>0)+2>>>0)),group:S,kernelShape:Array.from(n().subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(n().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ne>>>0],outputPadding:oe?Array.from(n().subarray(oe>>>0,pe>>>0)):[],outputShape:xe?Array.from(n().subarray(xe>>>0,Te>>>0)):[],activation:Ye(k)})},937948:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me)=>{a.Ea("ConvTranspose",i,{format:ne?"NHWC":"NCHW",autoPad:c,dilations:[f],group:S,kernel_shape:[O],pads:[D,W],strides:[ie],wIsConst:()=>!!r()[oe>>>0],outputPadding:pe?Array.from(n().subarray(pe>>>0,xe>>>0)):[],outputShape:Te?Array.from(n().subarray(Te>>>0,k>>>0)):[],activation:Ye(me)})},938350:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k)=>{a.Ea("ConvTranspose",i,{format:ie?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(f>>>0,(f>>>0)+2>>>0)),group:S,kernelShape:Array.from(n().subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(n().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ne>>>0],outputPadding:oe?Array.from(n().subarray(oe>>>0,pe>>>0)):[],outputShape:xe?Array.from(n().subarray(xe>>>0,Te>>>0)):[],activation:Ye(k)})},938915:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939006:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("AveragePool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},939290:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939381:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("AveragePool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},939665:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},939752:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("MaxPool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},940032:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},940119:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("MaxPool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},940399:(i,c,f,S,O)=>{a.Ea("Gemm",i,{alpha:c,beta:f,transA:S,transB:O})},940503:i=>{a.Ea("MatMul",i,void 0)},940557:(i,c,f,S)=>{a.Ea("ArgMax",i,{keepDims:!!c,selectLastIndex:!!f,axis:S})},940665:(i,c,f,S)=>{a.Ea("ArgMin",i,{keepDims:!!c,selectLastIndex:!!f,axis:S})},940773:(i,c)=>{a.Ea("Softmax",i,{axis:c})},940836:(i,c)=>{a.Ea("Concat",i,{axis:c})},940896:(i,c,f,S,O)=>{a.Ea("Split",i,{axis:c,numOutputs:f,splitSizes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},941036:i=>{a.Ea("Expand",i,void 0)},941090:(i,c)=>{a.Ea("Gather",i,{axis:Number(c)})},941161:(i,c)=>{a.Ea("GatherElements",i,{axis:Number(c)})},941240:(i,c,f,S,O,D,W,ie,ne,oe,pe)=>{a.Ea("Resize",i,{antialias:c,axes:f?Array.from(n().subarray(f>>>0,S>>>0)):[],coordinateTransformMode:Ye(O),cubicCoeffA:D,excludeOutside:W,extrapolationValue:ie,keepAspectRatioPolicy:Ye(ne),mode:Ye(oe),nearestMode:Ye(pe)})},941586:(i,c,f,S,O,D,W)=>{a.Ea("Slice",i,{starts:c?Array.from(n().subarray(c>>>0,f>>>0)):[],ends:S?Array.from(n().subarray(S>>>0,O>>>0)):[],axes:D?Array.from(n().subarray(D>>>0,W>>>0)):[]})},941802:i=>{a.Ea("Tile",i,void 0)},941854:(i,c,f)=>{a.Ea("LayerNormalization",i,{axis:Number(c),epsilon:Number(f)})},941961:(i,c,f)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:f?"NHWC":"NCHW"})},942075:(i,c,f)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:f?"NHWC":"NCHW"})},942189:i=>{a.Ea("Range",i,void 0)},942242:(i,c)=>{a.Ea("Einsum",i,{equation:Ye(c)})},942323:(i,c,f,S,O)=>{a.Ea("Pad",i,{mode:c,value:f,pads:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},942450:(i,c,f,S,O,D)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:f,spatial:!!O,trainingMode:!!S,format:D?"NHWC":"NCHW"})},942619:(i,c,f,S,O,D)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:f,spatial:!!O,trainingMode:!!S,format:D?"NHWC":"NCHW"})},942788:(i,c,f)=>{a.Ea("CumSum",i,{exclusive:Number(c),reverse:Number(f)})},942885:(i,c,f,S,O,D,W,ie,ne)=>{a.Ea("Attention",i,{numHeads:c,isUnidirectional:f,maskFilterValue:S,scale:O,doRotary:D,qkvHiddenSizes:W?Array.from(n().subarray(Number(ie)>>>0,Number(ie)+W>>>0)):[],pastPresentShareBuffer:!!ne})},943157:i=>{a.Ea("Gelu",i,void 0)},943209:(i,c,f,S,O,D)=>{a.Ea("MultiHeadAttention",i,{numHeads:c,isUnidirectional:f,maskFilterValue:S,scale:O,doRotary:D})},943368:i=>{a.Ea("BiasAdd",i,void 0)},943423:i=>{a.Ea("BiasSplitGelu",i,void 0)},943484:(i,c)=>{a.Ea("SkipLayerNormalization",i,{epsilon:c})},943565:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te)=>{a.Ea("Conv",i,{format:ne?"NHWC":"NCHW",auto_pad:c,dilations:[f],group:S,kernel_shape:[O],pads:D?Array.from(n().subarray(D>>>0,W>>>0)):[],strides:[ie],w_is_const:()=>!!r()[oe>>>0],activation:Ye(pe),activation_params:xe?Array.from(u().subarray(xe>>>0,Te>>>0)):[]})},943935:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("Conv",i,{format:xe?"NHWC":"NCHW",auto_pad:c,dilations:[f,S],group:O,kernel_shape:[D,W],pads:ie?Array.from(n().subarray(ie>>>0,ne>>>0)):[],strides:[oe,pe],w_is_const:()=>!!r()[Te>>>0],activation:Ye(k),activation_params:me?Array.from(u().subarray(me>>>0,Ce>>>0)):[]})},944326:i=>{a.zb(i)},944360:(i,c)=>a.Ab(i,c,a.bb.Cb,a.bb.errors)};function Ut(i){this.name="ExitStatus",this.message=`Program terminated with exit(${i})`,this.status=i}var Tt=i=>{i.terminate(),i.onmessage=()=>{}},Kt=i=>{de.Ya.length==0&&(ot(),de.lb(de.Ya[0]));var c=de.Ya.pop();if(!c)return 6;de.Za.push(c),de.Qa[i.Xa]=c,c.Xa=i.Xa;var f={cmd:"run",start_routine:i.Db,arg:i.tb,pthread_ptr:i.Xa};return I&&c.unref(),c.postMessage(f,i.Jb),0},nt=0,Yt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Vt=(i,c,f)=>{c>>>=0;var S=c+f;for(f=c;i[f]&&!(f>=S);)++f;if(16O?S+=String.fromCharCode(O):(O-=65536,S+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else S+=String.fromCharCode(O)}return S},Ye=(i,c)=>(i>>>=0)?Vt(o(),i,c):"",br=i=>{var c=mn();return i=i(),kr(c),i};function Oe(i,c){var f=arguments.length-2,S=arguments;return br(()=>{for(var O=fn(8*f),D=O>>>3,W=0;W>>0]=ie}return po(i,f,O,c)})}function wr(i){if($)return Oe(0,1,i);Pe=i,0{if(Pe=i,$)throw Zt(i),"unwind";wr(i)},St=i=>{i instanceof Ut||i=="unwind"||w(1,i)};function un(){for(var i=a.numThreads;i--;)ot();ee.unshift(()=>{ze++,tt(()=>wt())})}function ot(){var i=E("ort-wasm-simd-threaded.worker.js");i=new Worker(i),de.Ya.push(i)}function tt(i){$?i():Promise.all(de.Ya.map(de.lb)).then(i)}var de={Ya:[],Za:[],pb:[],Qa:{},hb(){$?(de.receiveObjectTransfer=de.Bb,de.threadInitTLS=de.ob,de.setExitStatus=de.nb):un()},nb:i=>Pe=i,Nb:["$terminateWorker"],Eb:()=>{for(var i of de.Za)Tt(i);for(i of de.Ya)Tt(i);de.Ya=[],de.Za=[],de.Qa=[]},mb:i=>{var c=i.Xa;delete de.Qa[c],de.Ya.push(i),de.Za.splice(de.Za.indexOf(i),1),i.Xa=0,cn(c)},Bb(){},ob(){de.pb.forEach(i=>i())},lb:i=>new Promise(c=>{i.onmessage=D=>{D=D.data;var W=D.cmd;if(D.targetThread&&D.targetThread!=Pr()){var ie=de.Qa[D.targetThread];ie?ie.postMessage(D,D.transferList):K(`Internal error! Worker sent a message "${W}" to target pthread ${D.targetThread}, but that thread no longer exists!`)}else W==="checkMailbox"?Et():W==="spawnThread"?Kt(D):W==="cleanupThread"?de.mb(de.Qa[D.thread]):W==="killThread"?(D=D.thread,W=de.Qa[D],delete de.Qa[D],Tt(W),cn(D),de.Za.splice(de.Za.indexOf(W),1),W.Xa=0):W==="cancelThread"?de.Qa[D.thread].postMessage({cmd:"cancel"}):W==="loaded"?(i.loaded=!0,I&&!i.Xa&&i.unref(),c(i)):W==="alert"?alert(`Thread ${D.threadId}: ${D.text}`):D.target==="setimmediate"?i.postMessage(D):W==="callHandler"?a[D.handler](...D.args):W&&K(`worker sent an unknown command ${W}`)},i.onerror=D=>{throw K(`worker sent an error! ${D.filename}:${D.lineno}: ${D.message}`),D},I&&(i.on("message",D=>i.onmessage({data:D})),i.on("error",D=>i.onerror(D)));var f=[],S=["onExit"],O;for(O of S)a.hasOwnProperty(O)&&f.push(O);i.postMessage({cmd:"load",handlers:f,urlOrBlob:a.mainScriptUrlOrBlob||e,wasmMemory:Q,wasmModule:Z})})};a.PThread=de;var bt=i=>{for(;0{var i=Pr(),c=s()[i+52>>>2>>>0];i=s()[i+56>>>2>>>0],ho(c,c-i),kr(c)};function Zt(i){if($)return Oe(1,0,i);Nt(i)}a.invokeEntryPoint=(i,c)=>{i=go.apply(null,[i,c]),0>>2>>>0]=c},this.rb=function(c){s()[this.gb+8>>>2>>>0]=c},this.hb=function(c,f){this.qb(),this.sb(c),this.rb(f)},this.qb=function(){s()[this.gb+16>>>2>>>0]=0}}var $r=0,Qt=0;function Sr(i,c,f,S){return $?Oe(2,1,i,c,f,S):xr(i,c,f,S)}function xr(i,c,f,S){if(i>>>=0,c>>>=0,f>>>=0,S>>>=0,typeof SharedArrayBuffer>"u")return K("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var O=[];return $&&O.length===0?Sr(i,c,f,S):(i={Db:f,Xa:i,tb:S,Jb:O},$?(i.Lb="spawnThread",postMessage(i,O),0):Kt(i))}function _r(i,c,f){return $?Oe(3,1,i,c,f):0}function Cr(i,c){if($)return Oe(4,1,i,c)}var Xt=i=>{for(var c=0,f=0;f=S?c++:2047>=S?c+=2:55296<=S&&57343>=S?(c+=4,++f):c+=3}return c},Ir=(i,c,f,S)=>{if(f>>>=0,!(0=W){var ie=i.charCodeAt(++D);W=65536+((W&1023)<<10)|ie&1023}if(127>=W){if(f>=S)break;c[f++>>>0]=W}else{if(2047>=W){if(f+1>=S)break;c[f++>>>0]=192|W>>6}else{if(65535>=W){if(f+2>=S)break;c[f++>>>0]=224|W>>12}else{if(f+3>=S)break;c[f++>>>0]=240|W>>18,c[f++>>>0]=128|W>>12&63}c[f++>>>0]=128|W>>6&63}c[f++>>>0]=128|W&63}}return c[f>>>0]=0,f-O},ae=(i,c,f)=>Ir(i,o(),c,f);function Jt(i,c){if($)return Oe(5,1,i,c)}function Wt(i,c,f){if($)return Oe(6,1,i,c,f)}function er(i,c,f){return $?Oe(7,1,i,c,f):0}function tr(i,c){if($)return Oe(8,1,i,c)}function rr(i,c,f){if($)return Oe(9,1,i,c,f)}function nr(i,c,f,S){if($)return Oe(10,1,i,c,f,S)}function or(i,c,f,S){if($)return Oe(11,1,i,c,f,S)}function ar(i,c,f,S){if($)return Oe(12,1,i,c,f,S)}function ir(i){if($)return Oe(13,1,i)}function sr(i,c){if($)return Oe(14,1,i,c)}function ur(i,c,f){if($)return Oe(15,1,i,c,f)}var Ar=()=>{if(!(0>>=0,typeof Atomics.Kb=="function"&&(Atomics.Kb(n(),i>>>2,i).value.then(Et),i+=128,Atomics.store(n(),i>>>2,1))}a.__emscripten_thread_mailbox_await=xt;var Et=()=>{var i=Pr();if(i&&(xt(i),!Ee))try{mo(),Ar()}catch(c){St(c)}};a.checkMailbox=Et;var d=[],m=i=>i%4===0&&(i%100!==0||i%400===0),v=[0,31,60,91,121,152,182,213,244,274,305,335],C=[0,31,59,90,120,151,181,212,243,273,304,334];function B(i,c,f,S,O,D,W,ie){return $?Oe(16,1,i,c,f,S,O,D,W,ie):-52}function H(i,c,f,S,O,D,W){if($)return Oe(17,1,i,c,f,S,O,D,W)}var q=i=>{var c=Xt(i)+1,f=ln(c);return f&&ae(i,f,c),f},le=[],J=(i,c)=>{le.length=0;for(var f;f=o()[i++>>>0];){var S=f!=105;S&=f!=112,c+=S&&c%8?4:0,le.push(f==112?s()[c>>>2>>>0]:f==105?n()[c>>>2>>>0]:l()[c>>>3>>>0]),c+=S?8:4}return le},re={},se=()=>{if(!we){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:b||"./this.program"},c;for(c in re)re[c]===void 0?delete i[c]:i[c]=re[c];var f=[];for(c in i)f.push(`${c}=${i[c]}`);we=f}return we},we;function _e(i,c){if($)return Oe(18,1,i,c);i>>>=0,c>>>=0;var f=0;return se().forEach((S,O)=>{var D=c+f;for(O=s()[i+4*O>>>2>>>0]=D,D=0;D>>0>>>0]=S.charCodeAt(D);r()[O>>>0>>>0]=0,f+=S.length+1}),0}function P(i,c){if($)return Oe(19,1,i,c);i>>>=0,c>>>=0;var f=se();s()[i>>>2>>>0]=f.length;var S=0;return f.forEach(O=>S+=O.length+1),s()[c>>>2>>>0]=S,0}function ue(i){return $?Oe(20,1,i):52}function Se(i,c,f,S){return $?Oe(21,1,i,c,f,S):52}function st(i,c,f,S,O){return $?Oe(22,1,i,c,f,S,O):70}var Tr=[null,[],[]];function to(i,c,f,S){if($)return Oe(23,1,i,c,f,S);c>>>=0,f>>>=0,S>>>=0;for(var O=0,D=0;D>>2>>>0],ie=s()[c+4>>>2>>>0];c+=8;for(var ne=0;ne>>0],pe=Tr[i];oe===0||oe===10?((i===1?Y:K)(Vt(pe,0)),pe.length=0):pe.push(oe)}O+=ie}return s()[S>>>2>>>0]=O,0}var ro=[31,29,31,30,31,30,31,31,30,31,30,31],no=[31,28,31,30,31,30,31,31,30,31,30,31];function Pu(i){var c=Array(Xt(i)+1);return Ir(i,c,0,c.length),c}var ku=(i,c)=>{r().set(i,c>>>0)};function oo(i,c,f,S){function O(k,me,Ce){for(k=typeof k=="number"?k.toString():k||"";k.lengthSo?-1:0Ot-k.getDate())me-=Ot-k.getDate()+1,k.setDate(1),11>Ce?k.setMonth(Ce+1):(k.setMonth(0),k.setFullYear(k.getFullYear()+1));else{k.setDate(k.getDate()+me);break}}return Ce=new Date(k.getFullYear()+1,0,4),me=ie(new Date(k.getFullYear(),0,4)),Ce=ie(Ce),0>=W(me,k)?0>=W(Ce,k)?k.getFullYear()+1:k.getFullYear():k.getFullYear()-1}i>>>=0,c>>>=0,f>>>=0,S>>>=0;var oe=s()[S+40>>>2>>>0];S={Hb:n()[S>>>2>>>0],Gb:n()[S+4>>>2>>>0],eb:n()[S+8>>>2>>>0],jb:n()[S+12>>>2>>>0],fb:n()[S+16>>>2>>>0],ab:n()[S+20>>>2>>>0],Wa:n()[S+24>>>2>>>0],$a:n()[S+28>>>2>>>0],Ob:n()[S+32>>>2>>>0],Fb:n()[S+36>>>2>>>0],Ib:oe?Ye(oe):""},f=Ye(f),oe={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var pe in oe)f=f.replace(new RegExp(pe,"g"),oe[pe]);var xe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Te="January February March April May June July August September October November December".split(" ");oe={"%a":k=>xe[k.Wa].substring(0,3),"%A":k=>xe[k.Wa],"%b":k=>Te[k.fb].substring(0,3),"%B":k=>Te[k.fb],"%C":k=>D((k.ab+1900)/100|0,2),"%d":k=>D(k.jb,2),"%e":k=>O(k.jb,2," "),"%g":k=>ne(k).toString().substring(2),"%G":k=>ne(k),"%H":k=>D(k.eb,2),"%I":k=>(k=k.eb,k==0?k=12:12{for(var me=0,Ce=0;Ce<=k.fb-1;me+=(m(k.ab+1900)?ro:no)[Ce++]);return D(k.jb+me,3)},"%m":k=>D(k.fb+1,2),"%M":k=>D(k.Gb,2),"%n":()=>`\n`,"%p":k=>0<=k.eb&&12>k.eb?"AM":"PM","%S":k=>D(k.Hb,2),"%t":()=>" ","%u":k=>k.Wa||7,"%U":k=>D(Math.floor((k.$a+7-k.Wa)/7),2),"%V":k=>{var me=Math.floor((k.$a+7-(k.Wa+6)%7)/7);if(2>=(k.Wa+371-k.$a-2)%7&&me++,me)me==53&&(Ce=(k.Wa+371-k.$a)%7,Ce==4||Ce==3&&m(k.ab)||(me=1));else{me=52;var Ce=(k.Wa+7-k.$a-1)%7;(Ce==4||Ce==5&&m(k.ab%400-1))&&me++}return D(me,2)},"%w":k=>k.Wa,"%W":k=>D(Math.floor((k.$a+7-(k.Wa+6)%7)/7),2),"%y":k=>(k.ab+1900).toString().substring(2),"%Y":k=>k.ab+1900,"%z":k=>{k=k.Fb;var me=0<=k;return k=Math.abs(k)/60,(me?"+":"-")+("0000"+(k/60*100+k%60)).slice(-4)},"%Z":k=>k.Ib,"%%":()=>"%"},f=f.replace(/%%/g,"\\0\\0");for(pe in oe)f.includes(pe)&&(f=f.replace(new RegExp(pe,"g"),oe[pe](S)));return f=f.replace(/\\0\\0/g,"%"),pe=Pu(f),pe.length>c?0:(ku(pe,i),pe.length-1)}var Er=i=>{try{i()}catch(c){rt(c)}};function Ru(){var i=X,c={};for(let[f,S]of Object.entries(i))c[f]=typeof S=="function"?function(){Or.push(f);try{return S.apply(null,arguments)}finally{Ee||(Or.pop(),ut&&_t===1&&Or.length===0&&(_t=0,nt+=1,Er(bo),typeof Fibers<"u"&&Fibers.Pb()))}}:S;return c}var _t=0,ut=null,ao=0,Or=[],io={},so={},Bu=0,dn=null,Du=[];function Mu(){return new Promise((i,c)=>{dn={resolve:i,reject:c}})}function zu(){var i=ln(65548),c=i+12;s()[i>>>2>>>0]=c,s()[i+4>>>2>>>0]=c+65536,c=Or[0];var f=io[c];return f===void 0&&(f=Bu++,io[c]=f,so[f]=c),c=f,n()[i+8>>>2>>>0]=c,i}function Uu(){var i=n()[ut+8>>>2>>>0];return i=X[so[i]],--nt,i()}function Vu(i){if(!Ee){if(_t===0){var c=!1,f=!1;i((S=0)=>{if(!Ee&&(ao=S,c=!0,f)){_t=2,Er(()=>wo(ut)),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.resume(),S=!1;try{var O=Uu()}catch(ie){O=ie,S=!0}var D=!1;if(!ut){var W=dn;W&&(dn=null,(S?W.reject:W.resolve)(O),D=!0)}if(S&&!D)throw O}}),f=!0,c||(_t=1,ut=zu(),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.pause(),Er(()=>yo(ut)))}else _t===2?(_t=0,Er(vo),lo(ut),ut=null,Du.forEach(S=>{if(!Ee)try{S(),Ar()}catch(O){St(O)}})):rt(`invalid state: ${_t}`);return ao}}function Nu(i){return Vu(c=>{i().then(c)})}de.hb();var Wu=[wr,Zt,Sr,_r,Cr,Jt,Wt,er,tr,rr,nr,or,ar,ir,sr,ur,B,H,_e,P,ue,Se,st,to],Hu={r:function(i,c,f){return Nu(async()=>{await a.xb(i,c,f)})},b:function(i,c,f){throw i>>>=0,new vr(i).hb(c>>>0,f>>>0),$r=i,Qt++,$r},N:function(i){co(i>>>0,!_,1,!y,131072,!1),de.ob()},l:function(i){i>>>=0,$?postMessage({cmd:"cleanupThread",thread:i}):de.mb(de.Qa[i])},J:xr,i:_r,T:Cr,F:Jt,H:Wt,U:er,R:tr,L:rr,Q:nr,p:or,G:ar,D:ir,S:sr,E:ur,q:()=>1,B:function(i,c){i>>>=0,i==c>>>0?setTimeout(()=>Et()):$?postMessage({targetThread:i,cmd:"checkMailbox"}):(i=de.Qa[i])&&i.postMessage({cmd:"checkMailbox"})},K:function(i,c,f,S){c>>>=0,d.length=f,S=S>>>0>>>3;for(var O=0;O>>0];return i=0>i?zt[-i-1]:Wu[i],de.ub=c,c=i.apply(null,d),de.ub=0,c},M:xt,W:function(i){I&&de.Qa[i>>>0].ref()},u:function(i,c,f){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,f>>>=0,i=new Date(1e3*i),n()[f>>>2>>>0]=i.getUTCSeconds(),n()[f+4>>>2>>>0]=i.getUTCMinutes(),n()[f+8>>>2>>>0]=i.getUTCHours(),n()[f+12>>>2>>>0]=i.getUTCDate(),n()[f+16>>>2>>>0]=i.getUTCMonth(),n()[f+20>>>2>>>0]=i.getUTCFullYear()-1900,n()[f+24>>>2>>>0]=i.getUTCDay(),i=(i.getTime()-Date.UTC(i.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,n()[f+28>>>2>>>0]=i},v:function(i,c,f){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,f>>>=0,i=new Date(1e3*i),n()[f>>>2>>>0]=i.getSeconds(),n()[f+4>>>2>>>0]=i.getMinutes(),n()[f+8>>>2>>>0]=i.getHours(),n()[f+12>>>2>>>0]=i.getDate(),n()[f+16>>>2>>>0]=i.getMonth(),n()[f+20>>>2>>>0]=i.getFullYear()-1900,n()[f+24>>>2>>>0]=i.getDay(),c=(m(i.getFullYear())?v:C)[i.getMonth()]+i.getDate()-1|0,n()[f+28>>>2>>>0]=c,n()[f+36>>>2>>>0]=-(60*i.getTimezoneOffset()),c=new Date(i.getFullYear(),6,1).getTimezoneOffset();var S=new Date(i.getFullYear(),0,1).getTimezoneOffset();i=(c!=S&&i.getTimezoneOffset()==Math.min(S,c))|0,n()[f+32>>>2>>>0]=i},w:function(i){i>>>=0;var c=new Date(n()[i+20>>>2>>>0]+1900,n()[i+16>>>2>>>0],n()[i+12>>>2>>>0],n()[i+8>>>2>>>0],n()[i+4>>>2>>>0],n()[i>>>2>>>0],0),f=n()[i+32>>>2>>>0],S=c.getTimezoneOffset(),O=new Date(c.getFullYear(),6,1).getTimezoneOffset(),D=new Date(c.getFullYear(),0,1).getTimezoneOffset(),W=Math.min(D,O);return 0>f?n()[i+32>>>2>>>0]=+(O!=D&&W==S):0>>2>>>0]=c.getDay(),f=(m(c.getFullYear())?v:C)[c.getMonth()]+c.getDate()-1|0,n()[i+28>>>2>>>0]=f,n()[i>>>2>>>0]=c.getSeconds(),n()[i+4>>>2>>>0]=c.getMinutes(),n()[i+8>>>2>>>0]=c.getHours(),n()[i+12>>>2>>>0]=c.getDate(),n()[i+16>>>2>>>0]=c.getMonth(),n()[i+20>>>2>>>0]=c.getYear(),i=c.getTime(),isNaN(i)?(n()[uo()>>>2>>>0]=61,i=-1):i/=1e3,fo((yt=i,1<=+Math.abs(yt)?0>>0:~~+Math.ceil((yt-+(~~yt>>>0))/4294967296)>>>0:0)),i>>>0},s:B,t:H,A:function(i,c,f){function S(oe){return(oe=oe.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?oe[1]:"GMT"}i>>>=0,c>>>=0,f>>>=0;var O=new Date().getFullYear(),D=new Date(O,0,1),W=new Date(O,6,1);O=D.getTimezoneOffset();var ie=W.getTimezoneOffset(),ne=Math.max(O,ie);s()[i>>>2>>>0]=60*ne,n()[c>>>2>>>0]=+(O!=ie),i=S(D),c=S(W),i=q(i),c=q(c),ie>>2>>>0]=i,s()[f+4>>>2>>>0]=c):(s()[f>>>2>>>0]=c,s()[f+4>>>2>>>0]=i)},d:()=>{rt("")},c:function(i,c,f){return i>>>=0,c=J(c>>>0,f>>>0),zt[i].apply(null,c)},k:function(i,c,f){return i>>>=0,c=J(c>>>0,f>>>0),zt[i].apply(null,c)},m:()=>{},j:()=>Date.now(),V:()=>{throw nt+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>I?(Oo(),Ht(Eo)).cpus().length:navigator.hardwareConcurrency,y:function(i){i>>>=0;var c=o().length;if(i<=c||4294901760=f;f*=2){var S=c*(1+.2/f);S=Math.min(S,i+100663296);var O=Math;S=Math.max(i,S);e:{O=(O.min.call(O,4294901760,S+(65536-S%65536)%65536)-Q.buffer.byteLength+65535)/65536;try{Q.grow(O),Ge();var D=1;break e}catch{}D=void 0}if(D)return!0}return!1},O:_e,P,I:Nt,h:ue,o:Se,x:st,n:to,a:Q||a.wasmMemory,z:oo,e:function(i,c,f,S){return oo(i>>>0,c>>>0,f>>>0,S>>>0)}},X=function(){function i(f,S){return X=f.exports,X=Ru(),X=Gu(),de.pb.push(X.Da),be.unshift(X.X),Z=S,wt(),X}var c={a:Hu};if(ze++,a.instantiateWasm)try{return a.instantiateWasm(c,i)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),h(f)}return $t(c,function(f){i(f.instance,f.module)}).catch(h),{}}();a._OrtInit=(i,c)=>(a._OrtInit=X.Y)(i,c),a._OrtGetLastError=(i,c)=>(a._OrtGetLastError=X.Z)(i,c),a._OrtCreateSessionOptions=(i,c,f,S,O,D,W,ie,ne,oe)=>(a._OrtCreateSessionOptions=X._)(i,c,f,S,O,D,W,ie,ne,oe),a._OrtAppendExecutionProvider=(i,c)=>(a._OrtAppendExecutionProvider=X.$)(i,c),a._OrtAddFreeDimensionOverride=(i,c,f)=>(a._OrtAddFreeDimensionOverride=X.aa)(i,c,f),a._OrtAddSessionConfigEntry=(i,c,f)=>(a._OrtAddSessionConfigEntry=X.ba)(i,c,f),a._OrtReleaseSessionOptions=i=>(a._OrtReleaseSessionOptions=X.ca)(i),a._OrtCreateSession=(i,c,f)=>(a._OrtCreateSession=X.da)(i,c,f),a._OrtReleaseSession=i=>(a._OrtReleaseSession=X.ea)(i),a._OrtGetInputOutputCount=(i,c,f)=>(a._OrtGetInputOutputCount=X.fa)(i,c,f),a._OrtGetInputName=(i,c)=>(a._OrtGetInputName=X.ga)(i,c),a._OrtGetOutputName=(i,c)=>(a._OrtGetOutputName=X.ha)(i,c),a._OrtFree=i=>(a._OrtFree=X.ia)(i),a._OrtCreateTensor=(i,c,f,S,O,D)=>(a._OrtCreateTensor=X.ja)(i,c,f,S,O,D),a._OrtGetTensorData=(i,c,f,S,O)=>(a._OrtGetTensorData=X.ka)(i,c,f,S,O),a._OrtReleaseTensor=i=>(a._OrtReleaseTensor=X.la)(i),a._OrtCreateRunOptions=(i,c,f,S)=>(a._OrtCreateRunOptions=X.ma)(i,c,f,S),a._OrtAddRunConfigEntry=(i,c,f)=>(a._OrtAddRunConfigEntry=X.na)(i,c,f),a._OrtReleaseRunOptions=i=>(a._OrtReleaseRunOptions=X.oa)(i),a._OrtCreateBinding=i=>(a._OrtCreateBinding=X.pa)(i),a._OrtBindInput=(i,c,f)=>(a._OrtBindInput=X.qa)(i,c,f),a._OrtBindOutput=(i,c,f,S)=>(a._OrtBindOutput=X.ra)(i,c,f,S),a._OrtClearBoundOutputs=i=>(a._OrtClearBoundOutputs=X.sa)(i),a._OrtReleaseBinding=i=>(a._OrtReleaseBinding=X.ta)(i),a._OrtRunWithBinding=(i,c,f,S,O)=>(a._OrtRunWithBinding=X.ua)(i,c,f,S,O),a._OrtRun=(i,c,f,S,O,D,W,ie)=>(a._OrtRun=X.va)(i,c,f,S,O,D,W,ie),a._OrtEndProfiling=i=>(a._OrtEndProfiling=X.wa)(i),a._JsepOutput=(i,c,f)=>(a._JsepOutput=X.xa)(i,c,f),a._JsepGetNodeName=i=>(a._JsepGetNodeName=X.ya)(i);var uo=()=>(uo=X.za)(),Pr=a._pthread_self=()=>(Pr=a._pthread_self=X.Aa)(),ln=a._malloc=i=>(ln=a._malloc=X.Ba)(i),lo=a._free=i=>(lo=a._free=X.Ca)(i);a.__emscripten_tls_init=()=>(a.__emscripten_tls_init=X.Da)();var co=a.__emscripten_thread_init=(i,c,f,S,O,D)=>(co=a.__emscripten_thread_init=X.Fa)(i,c,f,S,O,D);a.__emscripten_thread_crashed=()=>(a.__emscripten_thread_crashed=X.Ga)();var po=(i,c,f,S)=>(po=X.Ha)(i,c,f,S),cn=i=>(cn=X.Ia)(i),pn=a.__emscripten_thread_exit=i=>(pn=a.__emscripten_thread_exit=X.Ja)(i),mo=()=>(mo=X.Ka)(),fo=i=>(fo=X.La)(i),ho=(i,c)=>(ho=X.Ma)(i,c),mn=()=>(mn=X.Na)(),kr=i=>(kr=X.Oa)(i),fn=i=>(fn=X.Pa)(i),go=a.dynCall_ii=(i,c)=>(go=a.dynCall_ii=X.Ra)(i,c),yo=i=>(yo=X.Sa)(i),bo=()=>(bo=X.Ta)(),wo=i=>(wo=X.Ua)(i),vo=()=>(vo=X.Va)();a.___start_em_js=944472,a.___stop_em_js=944633;function Gu(){var i=X;i=Object.assign({},i);var c=S=>()=>S()>>>0,f=S=>O=>S(O)>>>0;return i.za=c(i.za),i.Aa=c(i.Aa),i.Ba=f(i.Ba),i.emscripten_main_runtime_thread_id=c(i.emscripten_main_runtime_thread_id),i.Na=c(i.Na),i.Pa=f(i.Pa),i}a.wasmMemory=Q,a.stackAlloc=fn,a.stackSave=mn,a.stackRestore=kr,a.keepRuntimeAlive=()=>0Po)});var Bo=dr((qc,Xu)=>{Xu.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\\n\'});var _n,Xe,cr,Mr,pr,No,Cn,Ne=j(()=>{"use strict";_n=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},Xe=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},cr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Mr=e=>{switch(e){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},pr=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},No=e=>e==="float32"||e==="int32"||e==="int64"||e==="bool"||e==="float16"||e==="uint32",Cn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}});var zr=j(()=>{"use strict"});var Ho=j(()=>{"use strict";zr()});var Go,Lo=j(()=>{"use strict";Go="1.17.1"});var Fo,Pt,In=j(()=>{"use strict";Lo();Fo="warning",Pt={wasm:{},webgl:{},webgpu:{},versions:{common:Go},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Fo=e}},get logLevel(){return Fo}};Object.defineProperty(Pt,"logLevel",{enumerable:!0})});var Gt,jo=j(()=>{"use strict";In();Gt=Pt});var qo=j(()=>{"use strict"});var Ko=j(()=>{"use strict";Ur()});var Zo=j(()=>{"use strict"});var Qo=j(()=>{"use strict";Ur()});var Ur=j(()=>{"use strict";qo();Ko();Zo();Qo()});var Vr=j(()=>{"use strict";Ur()});var An,Xo,kt,Rt,Tn=j(()=>{"use strict";In();An=(e,t)=>{Pt.wasm.trace&&console.timeStamp(`${e}::ORT::${t}`)},Xo=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let n=0;n{Pt.wasm.trace&&Xo("BEGIN",e)},Rt=e=>{Pt.wasm.trace&&Xo("END",e)}});var Jo=j(()=>{"use strict";zr();Vr();Tn()});var ea=j(()=>{"use strict";Jo()});var ta=j(()=>{"use strict"});var ra=j(()=>{"use strict";zr();Vr()});var na=j(()=>{"use strict";ra()});var Lt=j(()=>{"use strict";Ho();jo();ea();Vr();Tn();ta();na()});var dd,ld,oa,aa,ia,cd,Be,Ct=j(()=>{"use strict";Ne();dd=["V","I","W","E","F"],ld=(e,t)=>{console.log(`[${dd[e]},${new Date().toISOString()}]${t}`)},ia=(e,t)=>{oa=e,aa=t},cd=(e,t)=>{let r=pr(e),o=pr(oa);r>=o&&ld(r,typeof t=="function"?t():t)},Be=(...e)=>{aa&&cd(...e)}});var sa,ua=j(()=>{"use strict";Ne();sa=(e,t)=>new(Mr(t))(e)});var Nr=j(()=>{"use strict"});var Wr,pd,da,On,En,ca,pa=j(()=>{"use strict";Ct();Nr();Wr=e=>Math.ceil(e/16)*16,pd=1,da=()=>pd++,On=async(e,t,r,o)=>{let n=Wr(r),s=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,s,0,n),e.flush(),await s.mapAsync(GPUMapMode.READ);let l=s.getMappedRange();if(o){let a=o();return a.set(new Uint8Array(l,0,r)),a}else return new Uint8Array(l.slice(0,r))}finally{s.destroy()}},En=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map}upload(t,r){let o=r.buffer,n=r.byteOffset,s=r.byteLength,u=Wr(s),l=this.storageCache.get(t);if(!l)throw new Error("gpu data for uploading does not exist");if(l.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${s}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:u,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=a.getMappedRange();new Uint8Array(p).set(new Uint8Array(o,n,s)),a.unmap();let h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.copyBufferToBuffer(a,0,l.gpuData.buffer,0,u),Be("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(a)}memcpy(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(r);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(o.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=Wr(o.originalSize),u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(t,r,o){let n;if(o){if(n=this.externalBuffers.get(o),n===void 0)throw new Error("previous buffer is not registered");if(t===o)return Be("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, buffer is the same, skip.`),n;this.externalBuffers.delete(o)}else n=da();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,n),Be("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, registered.`),n}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),Be("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Wr(t),n,s=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,u=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||u){let a=s?this.freeBuffers:this.freeUniformBuffers,p=a.get(o);p||(p=[],a.set(o,p)),p.length>0?n=p.pop():n=this.backend.device.createBuffer({size:o,usage:r})}else n=this.backend.device.createBuffer({size:o,usage:r});let l={id:da(),type:0,buffer:n};return this.storageCache.set(l.id,{gpuData:l,originalSize:t}),Be("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=this.storageCache.get(t);if(!r)throw new Error("releasing data does not exist");return Be("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("data does not exist");await On(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();this.buffersForUploadingPending=[];for(let t of this.buffersPending)(t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(t.size).push(t):(t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(t.size).push(t):t.destroy();this.buffersPending=[]}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map}},ca=(...e)=>new En(...e)});var Pn,ge,je=j(()=>{"use strict";Pn=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},ge=e=>new Pn(e)});var kn,dt,U,Bt,Hr,Gr,Lr,$e=j(()=>{"use strict";kn=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},dt=class{static calcShape(t,r,o=!1){let n=t.length,s=r.length;if(n===0)return r;if(s===0)return t;let u=Math.max(t.length,r.length),l=new Array(u);if(o){if(n<2||s<2)return;let a=kn.calcMatMulShape([t[n-2],t[n-1]],[r[s-2],r[s-1]]);if(a===void 0)return;[l[u-2],l[u-1]]=a}for(let a=o?3:1;a<=u;a++){let p=n-a<0?1:t[n-a],h=s-a<0?1:r[s-a];if(p!==h&&p>1&&h>1)return;l[u-a]=Math.max(p,h)}return l}static isValidBroadcast(t,r){let o=t.length,n=r.length;if(o>n)return!1;for(let s=1;s<=o;s++)if(t[o-s]!==1&&t[o-s]!==r[n-s])return!1;return!0}},U=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,o){let n=1;for(let s=r;s=0;--n)o[n]=o[n+1]*t[n+1];return o}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(o=>this.normalizeAxis(o,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(o=>t[o]):t.slice().reverse()}static padShape(t,r){let o=t.length;return t.map((n,s)=>n+r[s]+r[s+o])}static areEqual(t,r){return t.length!==r.length?!1:t.every((o,n)=>o===r[n])}},Bt=class e{static adjustPoolAttributes(t,r,o,n,s,u){if(!t&&o.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let l=0;l=o.length?o.push(r[l+2]):o[l]=r[l+2];for(let l=0;l=o[l]||u[l+o.length]>=o[l])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,o,n,s,u,l){if(l){if(s.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let a=0;a{"use strict";Ne();$e();md=64,Bn=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},Le=(e,t=1)=>{let r=Bn(e,t);return typeof r=="string"?r:r[0]},lt=(e,t=1)=>{let r=Bn(e,t);return typeof r=="string"?r:r[1]},L=e=>e.length===0?[]:[{type:"uint32",data:e},{type:"uint32",data:U.computeStrides(e)}],Fe=e=>e%4===0?4:e%2===0?2:1,Ze=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,at=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}f(${r})`,Je=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,ce=(e,t,r)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?`${e}[(${t}) / 4][(${t}) % 4]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Dn=(e,t,r,o,n)=>{let s=typeof r=="number",u=s?r:r.length,l=[...new Array(u).keys()],a=u<2?"u32":u<=4?`vec${u}`:`array`,p=Bn(t,n),h=typeof p=="string"?p:p[1],g=typeof p=="string"?p:p[0],b={indices:a,value:h,storage:g,tensor:t},w=G=>typeof G=="string"?G:`${G}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},_=s?"uniforms.":"",I=`${_}${e}_shape`,$=`${_}${e}_strides`,x="";for(let G=0;G ${b.indices} {\n var indices: ${b.indices};\n var current = offset;\n ${x}\n return indices;\n }`,A=G=>(y.offsetToIndices=!0,u<2?G:`o2i_${e}(${G})`),z=[];if(u>=2)for(let G=u-1;G>=0;G--)z.push(`${ce($,G,u)} * (indices[${G}])`);let R=u<2?"":`\n fn i2o_${e}(indices: ${b.indices}) -> u32 {\n return ${z.join("+")};\n }`,V=G=>(y.indicesToOffset=!0,u<2?G:`i2o_${e}(${G})`),T=(...G)=>u===0?"0u":`${b.indices}(${G.map(w).join(",")})`,N=(G,ee)=>u<2?`${G}`:`${ce(G,ee,u)}`,te=(G,ee,be)=>u<2?`${G}=${be};`:`${ce(G,ee,u)}=${be};`,Y={},K=(G,ee)=>{y.broadcastedIndicesToOffset=!0;let be=`${ee.name}broadcastedIndicesTo${e}Offset`;if(be in Y)return`${be}(${G})`;let et=[];for(let ze=u-1;ze>=0;ze--){let Ue=ee.indicesGet("outputIndices",ze+ee.rank-u);et.push(`${N($,ze)} * (${Ue} % ${N(I,ze)})`)}return Y[be]=`fn ${be}(outputIndices: ${ee.type.indices}) -> u32 {\n return ${et.length>0?et.join("+"):"0u"};\n }`,`${be}(${G})`},Q=(G,ee)=>(()=>{if(b.storage===b.value)return`${e}[${G}]=${ee};`;if(b.storage==="vec2"&&b.value==="i32")return`${e}[${G}]=vec2(u32(${ee}), select(0u, 0xFFFFFFFFu, ${ee} < 0));`;if(b.storage==="vec2"&&b.value==="u32")return`${e}[${G}]=vec2(u32(${ee}), 0u);`;if(b.storage==="u32"&&b.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ee}));`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),Z=G=>(()=>{if(b.storage===b.value)return`${e}[${G}]`;if(b.storage==="vec2"&&b.value==="i32")return`i32(${e}[${G}].x)`;if(b.storage==="vec2"&&b.value==="u32")return`u32(${e}[${G}].x)`;if(b.storage==="u32"&&b.value==="vec4")return`vec4(bool(${e}[${G}] & 0xFFu), bool(${e}[${G}] & 0xFF00u), bool(${e}[${G}] & 0xFF0000u), bool(${e}[${G}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),Ee=u<2?"":`\n fn get_${e}ByIndices(indices: ${b.indices}) -> ${h} {\n return ${Z(`i2o_${e}(indices)`)};\n }`,Pe=u<2?"":(()=>{let G=l.map(be=>`d${be}: u32`).join(", "),ee=l.map(be=>`d${be}`).join(", ");return`\n fn get_${e}(${G}) -> ${h} {\n return get_${e}ByIndices(${T(ee)});\n }`})(),fe=(...G)=>{if(G.length!==u)throw new Error(`indices length must be ${u}`);let ee=G.map(w).join(",");return u===0?Z("0u"):u===1?Z(ee[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${ee})`)},Ie=G=>u<2?Z(G):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${G})`),he=u<2?"":`\n fn set_${e}ByIndices(indices: ${b.indices}, value: ${h}) {\n ${Q(`i2o_${e}(indices)`,"value")}\n }`,ye=u<2?"":(()=>{let G=l.map(be=>`d${be}: u32`).join(", "),ee=l.map(be=>`d${be}`).join(", ");return`\n fn set_${e}(${G}, value: ${h}) {\n set_${e}ByIndices(${T(ee)}, value);\n }`})();return{impl:()=>{let G=[],ee=!1;return y.offsetToIndices&&(G.push(E),ee=!0),y.indicesToOffset&&(G.push(R),ee=!0),y.broadcastedIndicesToOffset&&(Object.values(Y).forEach(be=>G.push(be)),ee=!0),y.set&&(G.push(ye),ee=!0),y.setByIndices&&(G.push(he),ee=!0),y.get&&(G.push(Pe),ee=!0),y.getByIndices&&(G.push(Ee),ee=!0),!s&&ee&&G.unshift(`const ${I} = ${b.indices}(${r.join(",")});`,`const ${$} = ${b.indices}(${U.computeStrides(r).join(",")});`),G.join(`\n`)},type:b,offsetToIndices:A,indicesToOffset:V,broadcastedIndicesToOffset:K,indices:T,indicesGet:N,indicesSet:te,set:(...G)=>{if(G.length!==u+1)throw new Error(`indices length must be ${u}`);let ee=G[u];if(typeof ee!="string")throw new Error("value must be string");let be=G.slice(0,u).map(w).join(",");return u===0?Q("0u",ee):u===1?Q(be[0],ee):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${be}, ${ee})`)},setByOffset:Q,setByIndices:(G,ee)=>u<2?Q(G,ee):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${ee});`),get:fe,getByOffset:Z,getByIndices:Ie,usage:o,name:e,strides:$,shape:I,rank:u}},M=(e,t,r,o=1)=>Dn(e,t,r,"input",o),F=(e,t,r,o=1)=>Dn(e,t,r,"output",o),Fr=(e,t,r,o=1)=>Dn(e,t,r,"internal",o),Rn=class{constructor(t){this.normalizedDispatchGroup=t;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=md){let r=typeof t=="number"?t:t[0],o=typeof t=="number"?1:t[1],n=typeof t=="number"?1:t[2],s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,u=s?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=s?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r*o*n}u + local_idx;`;return`@compute @workgroup_size(${r}, ${o}, ${n})\n fn main(${u}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let o=t.usage==="input"?"read":"read_write",n=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${n}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,o=1){return this.uniforms.push({name:t,type:r,length:o}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:o,length:n}of this.uniforms)if(n&&n>4)t.push(`${r}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?o:`vec${n}<${o}>`;t.push(`${r}:${s}`)}return`\n struct Uniforms { ${t.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}},ma=e=>new Rn(e),Ft=(e,t)=>{let r=e.length,o=[];for(let n=0;n1&&u===1&&o.unshift(s)}return o},Re=e=>!0});var fd,fa,hd,gd,it,ha,ga,jt=j(()=>{"use strict";$e();je();ve();fd=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},fa=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,hd=(e,t)=>U.sortBasedOnPerm(e,fa(e.length,t)),gd=(e,t,r,o)=>{let n=[];n.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let s=0;s{let r=e.dataType,o=e.dims.length,n=fa(o,t),s=Re(o),u=hd(e.dims,n),l=s?u.length:u,a=s?o:e.dims,p=F("output",r,l),h=M("a",r,a),g=b=>`\n ${b.registerUniform("output_size","u32").declareVariables(h,p)}\n\n ${gd(n,o,h,p)}\n\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${p.setByOffset("global_idx",h.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:s?["rank"]:["dims"]},getRunData:b=>{let w=U.size(u);return{outputs:[{dims:u,dataType:b[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:s?[{type:"uint32",data:w},...L(b[0].dims),...L(u)]:[{type:"uint32",data:w}]}},getShaderSource:g}},ha=(e,t)=>{fd(e.inputs),e.compute(it(e.inputs[0],t.perm))},ga=e=>ge({perm:e.perm})});var yd,bd,wd,vd,$d,Sd,xd,_d,Cd,Id,ct,ya,ba,wa,va,$a,Sa,xa,_a,Ca,Ia,Aa=j(()=>{"use strict";$e();ve();jr();jt();yd={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},bd={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},wd={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},vd={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},$d=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let s=0;se[s]);return[r,n]},xd=(e,t)=>{let r=e.length+t.length,o=[],n=0;for(let s=0;s{for(let r=0;r{let r=[];if(!_d(e,t)){for(let o=0;or.push(o))}return r},Id=(e,t,r,o,n,s,u)=>{let l=r[0].dims,a=U.size(s),p=U.size(u),h=M("_A",r[0].dataType,l),g=F("output",n,s),b=32,w=`\n var aBestValues : array<${g.type.storage}, ${b}>;\n `;return{name:e,shaderCache:t,getShaderSource:_=>`\n ${_.registerUniform("reduceSize","u32").declareVariables(h,g)}\n ${w}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${_.mainStart(b)}\n\n let outputIndex = global_idx / ${b};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = ${g.type.storage}(${wd[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${b}) {\n let candidate = ${g.type.storage}(${h.getByOffset("offset + k")});\n bestValue = ${yd[o]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${b}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${bd[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${g.setByOffset("outputIndex",`${o==="mean"?`bestValue / ${g.type.storage}(uniforms.reduceSize)`:`${vd[o]}`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:a},programUniforms:[{type:"uint32",data:p}]})}},ct=(e,t,r,o)=>{let n=e.inputs.length===1?r:Mn(e.inputs,r),s=n.axes;s.length===0&&!n.noopWithEmptyAxes&&(s=e.inputs[0].dims.map((w,y)=>y));let u=U.normalizeAxes(s,e.inputs[0].dims.length),l=u,a=e.inputs[0],p=Cd(l,e.inputs[0].dims.length);p.length>0&&(a=e.compute(it(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=$d(l.length,a.dims.length));let[h,g]=Sd(a.dims,l),b=h;n.keepDims&&(b=xd(h,u)),e.compute(Id(t,{hint:n.cacheKey,inputDependencies:["type"]},[a],o,e.inputs[0].dataType,b,g),{inputs:[a]})},ya=(e,t)=>{ct(e,"ReduceMeanShared",t,"mean")},ba=(e,t)=>{ct(e,"ReduceL1Shared",t,"l1")},wa=(e,t)=>{ct(e,"ReduceL2Shared",t,"l2")},va=(e,t)=>{ct(e,"ReduceLogSumExpShared",t,"logSumExp")},$a=(e,t)=>{ct(e,"ReduceMaxShared",t,"max")},Sa=(e,t)=>{ct(e,"ReduceMinShared",t,"min")},xa=(e,t)=>{ct(e,"ReduceProdShared",t,"prod")},_a=(e,t)=>{ct(e,"ReduceSumShared",t,"sum")},Ca=(e,t)=>{ct(e,"ReduceSumSquareShared",t,"sumSquare")},Ia=(e,t)=>{ct(e,"ReduceLogSumShared",t,"logSum")}});var pt,Ad,qr,Mn,mt,Td,Ed,Od,Pd,kd,Rd,Bd,Dd,Md,zd,ft,Ta,Ea,Oa,Pa,ka,Ra,Ba,Da,Ma,za,jr=j(()=>{"use strict";$e();je();ve();Aa();pt=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Ad=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],qr=(e,t,r,o,n,s,u=!1,l=!1)=>{let a=[],p=r[0].dims,h=p.length,g=U.normalizeAxes(n,h),b=!l&&g.length===0;p.forEach((I,$)=>{b||g.indexOf($)>=0?u&&a.push(1):a.push(I)});let w=a.length,y=U.size(a);return{name:e,shaderCache:t,getShaderSource:I=>{let $=[],x=M("_A",r[0].dataType,h),E=F("output",s,w),A=o(x,E,g),z=A[2];for(let R=0,V=0;R=0?(u&&V++,z=`for(var j${R}: u32 = 0; j${R} < ${p[R]}; j${R}++) {\n ${A[2].includes("last_index")?`let last_index = j${R};`:""}\n ${x.indicesSet("input_indices",R,`j${R}`)}\n ${z}\n }`):($.push(`${x.indicesSet("input_indices",R,E.indicesGet("output_indices",V))};`),V++);return`\n\n ${I.registerUniform("output_size","u32").declareVariables(x,E)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${x.type.indices};\n let output_indices = ${E.offsetToIndices("global_idx")};\n\n ${$.join(`\n`)}\n ${A[0]} // init ops for reduce max/min\n ${A[1]}\n ${z}\n ${A[3]}\n ${A.length===4?E.setByOffset("global_idx","value"):A.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:"uint32",data:y},...L(p),...L(a)]})}},Mn=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),ge({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},mt=(e,t,r,o)=>{let n=e.inputs,s=n.length===1?r:Mn(n,r);e.compute(qr(t,{hint:s.cacheKey,inputDependencies:["rank"]},[n[0]],s.noopWithEmptyAxes&&s.axes.length===0?Ad:o,s.axes,n[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},Td=(e,t)=>{pt(e.inputs),mt(e,"ReduceLogSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Ed=(e,t)=>{pt(e.inputs),mt(e,"ReduceL1",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},Od=(e,t)=>{pt(e.inputs),mt(e,"ReduceL2",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Pd=(e,t)=>{pt(e.inputs),mt(e,"ReduceLogSumExp",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},kd=(e,t)=>{pt(e.inputs),mt(e,"ReduceMax",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(o.indicesSet("input_indices",l,0));return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = max(value, ${o.getByIndices("input_indices")});`,""]})},Rd=(e,t)=>{pt(e.inputs),mt(e,"ReduceMean",t,(o,n,s)=>{let u=1;for(let l=0;l=0||s.length===0)&&(u*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${o.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${u});`]})},Bd=(e,t)=>{pt(e.inputs),mt(e,"ReduceMin",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = min(value, ${o.getByIndices("input_indices")});`,""]})},Dd=(e,t)=>{pt(e.inputs),mt(e,"ReduceProd",t,(o,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},Md=(e,t)=>{pt(e.inputs),mt(e,"ReduceSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},zd=(e,t)=>{pt(e.inputs),mt(e,"ReduceSumSquare",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += t * t;`,""])},ft=(e,t,r)=>{if(t.length===0)return r;let o=1,n=1;for(let s=0;s1024},Ta=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Rd(e,t):ya(e,t)},Ea=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ed(e,t):ba(e,t)},Oa=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Od(e,t):wa(e,t)},Pa=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pd(e,t):va(e,t)},ka=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?kd(e,t):$a(e,t)},Ra=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bd(e,t):Sa(e,t)},Ba=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Dd(e,t):xa(e,t)},Da=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Md(e,t):_a(e,t)},Ma=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zd(e,t):Ca(e,t)},za=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Td(e,t):Ia(e,t)}});var Ua,Va,Na,zn,Wa=j(()=>{"use strict";Ne();je();jr();Ua=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Va=(e,t)=>{Ua(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(qr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Na=(e,t)=>{Ua(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(qr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},zn=e=>ge(e)});var Ud,Vd,Nd,Wd,Kr,Hd,Ha,Un=j(()=>{"use strict";Ne();Nr();ve();Ud=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5];if(u&&l)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error(\'Input "input" must have 3 dimensions\');let a=r.dims[0],p=r.dims[1],h=r.dims[2];if(n.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimensions\');if(o.dims.length!==2)throw new Error(\'Input "weights" is expected to have 2 dimensions\');if(o.dims[0]!==h)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==o.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let g=n.dims[0]/3,b=g,w=b;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let E of t.qkvHiddenSizes)if(E%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],b=t.qkvHiddenSizes[1],w=t.qkvHiddenSizes[2]}let y=p;if(g!==b)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==g+b+w)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let _=0;if(u){if(b!==w)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(u.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(u.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(u.dims[1]!==a)throw new Error(\'Input "past" second dimension must be batch_size\');if(u.dims[2]!==t.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(u.dims[4]!==b/t.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');t.pastPresentShareBuffer||(_=u.dims[3])}let I=y+_,$=-1,x=0;if(s)throw new Error("Mask not supported");if(u)throw new Error("past is not supported");if(l)throw new Error("relativePositionBias is not supported");return{batchSize:a,sequenceLength:p,pastSequenceLength:_,kvSequenceLength:y,totalSequenceLength:I,maxSequenceLength:$,inputHiddenSize:h,hiddenSize:g,vHiddenSize:w,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(w/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Vd=(e,t,r,o)=>{let n=Fe(o),s=64,u=o/n;u{let w=F("x",t.dataType,t.dims,n),y="thread_max_vector";n===2?y="max(thread_max_vector.x, thread_max_vector.y)":n===4&&(y="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let _=lt(t.dataType),I=[{name:"d_inv",type:_},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return`\n var wgMax: array;\n var wgSum: array;\n ${b.registerUniforms(I).declareVariables(w)}\n ${b.mainStart([s,1,1])}\n let localOffset = local_idx * uniforms.elements_per_wg;\n let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset;\n\n var thread_max_vector = ${Ze("f32",n,"-3.402823e+38f")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n thread_max_vector = max(${at(_,n,"x[offset + i]")}, thread_max_vector);\n }\n wgMax[local_idx] = ${y};\n workgroupBarrier();\n\n var maxValue = -3.402823e+38f;\n for (var i = 0u; i < ${s}; i++) {\n maxValue = max(wgMax[i], maxValue);\n }\n\n var sumVector = ${Ze("f32",n,"0")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n sumVector += exp(${at(_,n,"x[offset + i]")} - maxValue);\n }\n wgSum[local_idx] = ${Je("sumVector",n)};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${s}; i++) {\n sum += wgSum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n x[offset + i] = ${Ze("f32",n,"uniforms.d_inv")};\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n let f32input = ${at(_,n,"x[offset + i]")};\n x[offset + i] = ${w.type.value}(exp(f32input - maxValue) / sum);\n }\n }\n }`};e.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${h};${n}`},getShaderSource:g,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:p})},{inputs:[t],outputs:[]})},Nd=(e,t,r,o,n,s)=>{let u=[n.batchSize,n.numHeads,n.sequenceLength,n.kvSequenceLength+n.pastSequenceLength],l=s.scale===0?1/Math.sqrt(n.headSize):s.scale,a=Fe(n.headSize),p=n.headSize/a,h=12,g={x:Math.ceil(n.totalSequenceLength/h),y:Math.ceil(n.sequenceLength/h),z:n.batchSize*n.numHeads},b=Xe(t.dataType),w=[{type:"uint32",data:n.sequenceLength},{type:"uint32",data:p},{type:"uint32",data:n.totalSequenceLength},{type:"uint32",data:n.kvSequenceLength},{type:b,data:l}],y=[t,r],_=$=>{let x=M("q",t.dataType,t.dims,a),E=M("key",r.dataType,r.dims,a),A=F("output",t.dataType,u),z=Le(t.dataType),R=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:z}];return`\n const beta: ${z} = 1.0;\n const TILE_SIZE = ${h}u;\n\n var tileQ: array<${x.type.storage}, ${h*h}>;\n var tileK: array<${x.type.storage}, ${h*h}>;\n ${$.registerUniforms(R).declareVariables(x,E,A)}\n ${$.mainStart([h,h,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let lm = m + local_id.y;\n let ln = n + local_id.x;\n\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${Ze(z,a)};\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m + local_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:g,programUniforms:w}),getShaderSource:_},{inputs:y,outputs:[-1]})[0];return Vd(e,I,n.batchSize*n.numHeads*n.sequenceLength,n.totalSequenceLength),I},Wd=(e,t,r,o)=>{let n=[o.batchSize,o.sequenceLength,o.vHiddenSize],s=12,u={x:Math.ceil(o.vHeadSize/s),y:Math.ceil(o.sequenceLength/s),z:o.batchSize*o.numHeads},l=[{type:"uint32",data:o.sequenceLength},{type:"uint32",data:o.totalSequenceLength},{type:"uint32",data:o.vHeadSize},{type:"uint32",data:o.numHeads},{type:"uint32",data:o.vHiddenSize}],a=p=>{let h=M("probs",t.dataType,t.dims),g=M("v",r.dataType,r.dims),b=F("output",t.dataType,n),w=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return`\n const TILE_SIZE = ${s}u;\n var tileQ: array<${h.type.value}, ${s*s}>;\n var tileK: array<${h.type.value}, ${s*s}>;\n ${p.registerUniforms(w).declareVariables(h,g,b)}\n ${p.mainStart([s,s,1])}\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${h.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:n,dataType:t.dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:l}),getShaderSource:a},{inputs:[t,r],outputs:[0]})[0]},Kr=(e,t,r,o,n,s,u,l,a,p,h)=>{let g=Nd(e,t,r,a,p,h);Wd(e,g,o,p)},Hd=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],o=t.sequenceLength,n=t.inputHiddenSize,s=t.headSize,u=12,l={x:Math.ceil(t.headSize/u),y:Math.ceil(t.sequenceLength/u),z:t.batchSize*t.numHeads},a=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:"uint32",data:o},{type:"uint32",data:n},{type:"uint32",data:s},{type:"uint32",data:t.numHeads},{type:"uint32",data:t.headSize},{type:"uint32",data:t.hiddenSize},{type:"uint32",data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],h=g=>{let b=F("output_q",a[0].dataType,r),w=F("output_k",a[0].dataType,r),y=F("output_v",a[0].dataType,r),_=M("input",a[0].dataType,a[0].dims),I=M("weight",a[1].dataType,a[1].dims),$=M("bias",a[2].dataType,a[2].dims),x=_.type.storage,E=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`\n const TILE_SIZE = ${u}u;\n var tileInput: array<${x}, ${u*u}>;\n var tileWeightQ: array<${x}, ${u*u}>;\n var tileWeightK: array<${x}, ${u*u}>;\n var tileWeightV: array<${x}, ${u*u}>;\n ${g.registerUniforms(E).declareVariables(_,I,$,b,w,y)}\n ${g.mainStart([u,u,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${x}(0);\n var valueK = ${x}(0);\n var valueV = ${x}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:p}),getShaderSource:h},{inputs:a,outputs:[-1,-1,-1]})},Ha=(e,t)=>{let r=Ud(e.inputs,t),[o,n,s]=Hd(e,r);return Kr(e,o,n,s,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var Gd,Ld,Fd,Ga,La=j(()=>{"use strict";Lt();$e();je();ve();Gd=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(o,n,s)=>{let u=n.length;if(u!==o.length)throw new Error(`${s}: num dimensions != ${u}`);n.forEach((l,a)=>{if(l!==o[a])throw new Error(`${s}: dim[${a}] do not match`)})};if(e[0].dims.length>1){let o=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,o,"Invalid input scale"),r(e[2].dims,o,"Invalid input B"),r(e[3].dims,o,"Invalid input mean"),r(e[4].dims,o,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Ld=(e,t)=>{let{epsilon:r,spatial:o,format:n}=t,s=e[0].dims,u=o?Fe(s[s.length-1]):1,l=n==="NHWC"&&s.length>1?u:1,a=U.size(s)/u,p=Re(s.length)&&o,h=p?s.length:s,g=M("x",e[0].dataType,e[0].dims,u),b=M("scale",e[1].dataType,e[1].dims,l),w=M("bias",e[2].dataType,e[2].dims,l),y=M("inputMean",e[3].dataType,e[3].dims,l),_=M("inputVar",e[4].dataType,e[4].dims,l),I=F("y",e[0].dataType,h,u),$=()=>{let E="";if(o)E=`let cOffset = ${s.length===1?"0u":n==="NHWC"?`outputIndices[${s.length-1}] / ${u}`:"outputIndices[1]"};`;else if(n==="NCHW")E=`\n ${I.indicesSet("outputIndices","0","0")}\n let cOffset = ${I.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${b.type.indices}(0);\n cIndices[0] = outputIndices[${s.length-1}];`;for(let A=1;A`\n const epsilon = ${r};\n ${E.registerUniform("outputSize","u32").declareVariables(g,b,w,y,_,I)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${I.offsetToIndices(`global_idx * ${u}`)};\n ${$()}\n let scale = ${b.getByOffset("cOffset")};\n let bias = ${w.getByOffset("cOffset")};\n let inputMean = ${y.getByOffset("cOffset")};\n let inputVar = ${_.getByOffset("cOffset")};\n let x = ${g.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${I.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${o}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p?[{type:"uint32",data:a},...L(s)]:[{type:"uint32",data:a}]})}},Fd=e=>ge(e),Ga=(e,t)=>{let{inputs:r,outputCount:o}=e,n=Fd({...t,outputCount:o});if(Gt.webgpu.validateInputContent&&Gd(r,n),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ld(r,n))}});var jd,qd,Fa,ja=j(()=>{"use strict";$e();ve();jd=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},qd=e=>{let t=e[0].dims,r=e[0].dims[2],o=U.size(t)/4,n=e[0].dataType,s=M("input",n,t,4),u=M("bias",n,[r],4),l=M("residual",n,t,4),a=F("output",n,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:h=>`\n const channels = ${r}u / 4;\n ${h.declareVariables(s,u,l,a)}\n\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes(o)}\n let value = ${s.getByOffset("global_idx")}\n + ${u.getByOffset("global_idx % channels")} + ${l.getByOffset("global_idx")};\n ${a.setByOffset("global_idx","value")}\n }`}},Fa=e=>{jd(e.inputs),e.compute(qd(e.inputs))}});var Kd,Ae,qa,Ka,Ya,Za,Qa,Xa,Ja,ei,ti,Yd,ri,ni,oi,ai,Yr,ii,Zr,si,ui,di,li,ci,pi,mi,fi,hi,gi,yi,bi,wi,vi,$i,Si,xi,Vn=j(()=>{"use strict";Ne();$e();je();ve();Kd=(e,t,r,o,n,s)=>{let u=Math.ceil(t/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let a=M("inputData",r,[u],4),p=F("outputData",o,[u],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,p)}\n\n ${s??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${a.getByOffset("global_idx")};\n ${p.setByOffset("global_idx",l)}\n }`},Ae=(e,t,r,o,n,s=e.dataType)=>({name:t,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:u=>Kd(u,U.size(e.dims),e.dataType,s,r,o),getRunData:u=>({outputs:[{dims:e.dims,dataType:s}],dispatchGroup:{x:Math.ceil(U.size(u[0].dims)/64/4)},programUniforms:[{type:"uint32",data:Math.ceil(U.size(e.dims)/4)}]})}),qa=e=>{e.compute(Ae(e.inputs[0],"Abs","abs"))},Ka=e=>{e.compute(Ae(e.inputs[0],"Acos","acos"))},Ya=e=>{e.compute(Ae(e.inputs[0],"Acosh","acosh"))},Za=e=>{e.compute(Ae(e.inputs[0],"Asin","asin"))},Qa=e=>{e.compute(Ae(e.inputs[0],"Asinh","asinh"))},Xa=e=>{e.compute(Ae(e.inputs[0],"Atan","atan"))},Ja=e=>{e.compute(Ae(e.inputs[0],"Atanh","atanh"))},ei=e=>ge(e),ti=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute \'to\' from \'Cast\' operator): ${t.to}`)}e.compute(Ae(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Yd=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Gr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:Lr;return ge({min:t,max:r})},ri=(e,t)=>{let r=e.inputs.length===1?t:Yd(e.inputs),o=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Clip",n=>`clamp(${n}, clip_min_, clip_max_)`,`\n const clip_min_: vec4<${o}> = vec4(${o}(${r.min}));\n const clip_max_: vec4<${o}> = vec4(${o}(${r.max}));\n`,r.cacheKey),{inputs:[0]})},ni=e=>{e.compute(Ae(e.inputs[0],"Ceil","ceil"))},oi=e=>{e.compute(Ae(e.inputs[0],"Cos","cos"))},ai=e=>{e.compute(Ae(e.inputs[0],"Cosh","cosh"))},Yr=e=>ge(e),ii=(e,t)=>{let r=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Elu",o=>`elu_vf32(${o})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Zr=(e,t="f32")=>`\nconst r0: ${t} = 0.3275911;\nconst r1: ${t} = 0.254829592;\nconst r2: ${t} = -0.284496736;\nconst r3: ${t} = 1.421413741;\nconst r4: ${t} = -1.453152027;\nconst r5: ${t} = 1.061405429;\n\nfn erf_vf32(v: ${e}) -> ${e} {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,si=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Zr(`vec4<${t}>`,t)))},ui=e=>{e.compute(Ae(e.inputs[0],"Exp","exp"))},di=e=>{e.compute(Ae(e.inputs[0],"Floor","floor"))},li=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Zr(`vec4<${t}>`,t)))},ci=(e,t)=>{let r=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"LeakyRelu",o=>`select(leaky_relu_alpha_ * ${o}, ${o}, ${o} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},pi=e=>{e.compute(Ae(e.inputs[0],"Not",t=>`!${t}`))},mi=e=>{e.compute(Ae(e.inputs[0],"Neg",t=>`-${t}`))},fi=e=>{e.compute(Ae(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},hi=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},gi=e=>{e.compute(Ae(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},yi=e=>{e.compute(Ae(e.inputs[0],"Sin","sin"))},bi=e=>{e.compute(Ae(e.inputs[0],"Sinh","sinh"))},wi=e=>{e.compute(Ae(e.inputs[0],"Sqrt","sqrt"))},vi=e=>{e.compute(Ae(e.inputs[0],"Tan","tan"))},$i=e=>{e.compute(Ae(e.inputs[0],"Tanh","tanh"))},Si=(e,t)=>{let r=lt(e.inputs[0].dataType);return e.compute(Ae(e.inputs[0],"ThresholdedRelu",o=>`select(vec4<${r}>(0.0), ${o}, ${o} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},xi=e=>{e.compute(Ae(e.inputs[0],"Log","log"))}});var Qd,Xd,_i,Ci=j(()=>{"use strict";$e();ve();Vn();Qd=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Xd=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=M("input",e[0].dataType,e[0].dims,4),o=M("bias",e[0].dataType,[e[0].dims[2]],4),n=F("output",e[0].dataType,t,4),s=U.size(t)/4,u=Le(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:a=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${a.declareVariables(r,o,n)}\n\n ${Zr(`vec4<${u}>`,u)}\n\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(s)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${n.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},_i=e=>{Qd(e.inputs),e.compute(Xd(e.inputs))}});var Jd,el,ht,Ii,Ai,Ti,Ei,Oi,Pi,ki,Ri,Bi,Di,Mi=j(()=>{"use strict";Ne();$e();ve();Jd=(e,t,r,o,n,s,u,l,a,p,h,g,b)=>{let w,y;typeof l=="string"?w=y=(R,V)=>`${l}((${R}),(${V}))`:typeof l=="function"?w=y=l:(w=l.scalar,y=l.vector);let _=g?t.length:t,I=g?r.length:r,$=g?o.length:o,x=F("outputData",h,$,4),E=M("aData",a,_,4),A=M("bData",p,I,4),z;if(n)if(s){let R=U.size(t)===1,V=U.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,N=r.length>0&&r[r.length-1]%4===0;R||V?z=x.setByOffset("global_idx",y(R?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),V?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):z=`\n let outputIndices = ${x.offsetToIndices("global_idx * 4u")};\n let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",x)};\n let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",x)};\n ${x.setByOffset("global_idx",y(u||T?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||N?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else z=x.setByOffset("global_idx",y(E.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let R=(V,T,N="")=>{let te=`aData[indexA${T}][componentA${T}]`,Y=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${x.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${E.broadcastedIndicesToOffset(`outputIndices${T}`,x)};\n let offsetB${T} = ${A.broadcastedIndicesToOffset(`outputIndices${T}`,x)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${V}[${T}] = ${N}(${w(te,Y)});\n `};h===9?z=`\n var data = vec4(0);\n ${R("data",0,"u32")}\n ${R("data",1,"u32")}\n ${R("data",2,"u32")}\n ${R("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:z=`\n ${R("outputData[global_idx]",0)}\n ${R("outputData[global_idx]",1)}\n ${R("outputData[global_idx]",2)}\n ${R("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(E,A,x)}\n\n ${b??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${z}\n }`},el=(e,t,r,o,n,s,u=r.dataType)=>{let l=!U.areEqual(r.dims,o.dims),a=r.dims,p=U.size(r.dims),h=!1,g=!1,b=[l];if(l){let y=dt.calcShape(r.dims,o.dims,!1);if(!y)throw new Error("Can\'t perform binary op on the given tensors");a=y,p=U.size(a);let _=U.size(r.dims)===1,I=U.size(o.dims)===1,$=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,x=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;b.push(_),b.push(I),b.push($),b.push(x);let E=1;for(let A=1;Ay.toString()).join("_"),inputDependencies:w?["rank","rank"]:["dims","dims"]},getShaderSource:y=>Jd(y,r.dims,o.dims,a,h,l,g,n,r.dataType,o.dataType,u,w,s),getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:w?[{type:"uint32",data:Math.ceil(U.size(a)/4)},...L(r.dims),...L(o.dims),...L(a)]:[{type:"uint32",data:Math.ceil(U.size(a)/4)}]})}},ht=(e,t,r,o,n,s)=>{e.compute(el(t,n??"",e.inputs[0],e.inputs[1],r,o,s))},Ii=e=>{ht(e,"Add",(t,r)=>`${t}+${r}`)},Ai=e=>{ht(e,"Div",(t,r)=>`${t}/${r}`)},Ti=e=>{ht(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Ei=e=>{ht(e,"Mul",(t,r)=>`${t}*${r}`)},Oi=e=>{let t=M("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ht(e,"Pow",{scalar:(o,n)=>`pow_custom(${o},${n})`,vector:(o,n)=>`pow_vector_custom(${o},${n})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Pi=e=>{ht(e,"Sub",(t,r)=>`${t}-${r}`)},ki=e=>{ht(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Ri=e=>{ht(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Bi=e=>{ht(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Di=e=>{ht(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var rl,nl,ol,al,zi,Ui,Vi=j(()=>{"use strict";$e();je();ve();rl=e=>{if(!e||e.length<1)throw new Error("too few inputs");let t=e[0].dataType,r=e[0].dims.length;for(let o of e){if(o.dataType!==t)throw new Error("input tensors should be one type");if(o.dims.length!==r)throw new Error("input tensors should have the same shape")}},nl=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,ol=(e,t)=>{let r=e.length,o=[];for(let n=0;n{let r=e[0].dims.slice();if(t>=r.length||t<-1*r.length)throw new Error("axis specified for concat doesn\'t match input dimensionality");let o=t<0?r.length+t:t,n=r.slice(0);for(let A=1;A`uniforms.sizeInConcatAxis${A}`).join(","),E=A=>`\n\n ${(()=>{A.registerUniform("outputSize","u32");for(let z=0;z(${x});\n ${$} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${ol(l,I)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:w}),getShaderSource:E}},zi=(e,t)=>{rl(e.inputs),e.compute(al(e.inputs,t.axis))},Ui=e=>ge({axis:e.axis})});var gt,Qr,It=j(()=>{"use strict";$e();gt=(e,t)=>{switch(e.activation){case"Relu":return{activationFunction:"",applyActivation:`value = max(value, ${t}(0.0));`};case"Sigmoid":return{activationFunction:"",applyActivation:`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`};case"Clip":return{activationFunction:`const clip_min_=${t}(${e.clipMin});const clip_max_=${t}(${e.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},Qr=e=>{let t=e?.activation||"";if(t==="Clip"){let[r,o]=e?.activation_params||[Gr,Lr];return{activation:t,clipMax:o,clipMin:r,activationCacheKey:`${t}:${r},${o}`}}return{activation:t,activationCacheKey:t}}});var Ke,Xr,Jr=j(()=>{"use strict";Ke=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Xr=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var en,Nn=j(()=>{"use strict";en=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var il,sl,mr,Ni,ul,fr,dl,tn,hr=j(()=>{"use strict";$e();ve();It();Jr();il=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,sl=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,mr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32)=>{let a=t[1]*e[1],p=t[0]*e[0],h=n?a:s,g=n?s:a,b=h/t[0],w=s/t[1];if(!((n&&b===4&&e[1]===4||!n&&(b===3||b===4))&&h%t[0]===0&&s%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${b} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${b} must be 3 or 4.\n tileAWidth ${h} must be divisible by workgroupSize[0]${t[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${h/b}>, ${g}>;\nvar mm_Bsub: array, ${p/e[0]}>, ${s}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${b};\nconst tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${a};\n\n let numTiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dimInner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${w};\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${il(n,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${o?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${b===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${sl(n,b)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Ni=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,ul=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",fr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32,a=!1)=>{let p=e[1]*t[1],h=e[0]*t[0],g=n?p:s,b=n?s:p;if(!(b%t[1]===0&&g%t[0]===0&&s%t[1]===0))throw new Error(`tileAHight ${b} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${s} must be divisible by workgroupSize[1]${t[1]}`);let w=b/t[1],y=g/t[0],_=s/t[1],I=a?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${p};\n let globalColStart = i32(workgroupId.x) * ${h};\n\n // Loop over shared dimension.\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${b}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) {\n ${Ni(n,o)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${h}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${n?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${p};\n\nlet tileRowA = i32(localId.y) * ${w};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${_};\n// Loop over shared dimension.\nfor (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Ni(n,o)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${ul(n)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${b}>;\n var mm_Bsub : array, ${s}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let numTiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dimInner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc : array, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${I}\n }\n`},dl=(e,t,r,o,n,s=!1)=>{let[u,l,a]=n,[p,h,g,b]=o,w=Ft(u,a),y=Ft(l,a),_=Le(o[0].type.tensor),I=()=>{let E=h.rank,A=p.rank,z=`var aIndices: ${h.type.indices};`;for(let R=E-2-1,V=A-1;R>=0;R--,V--)z+=`\naIndices[${R}] = ${A>1?`batchIndices[${V}]`:"batchIndices"};`;return w.forEach(R=>{z+=`\naIndices[${R}] = 0;`}),z+=`\naIndices[${E-2}] = u32(row);\n aIndices[${E-1}] = u32(colIn);`,z},$=()=>{let E=g.rank,A=p.rank,z=`var bIndices: ${g.type.indices};`;for(let R=E-2-1,V=A-1;R>=0;R--,V--)z+=`\nbIndices[${R}] = ${A>1?`batchIndices[${V}]`:"batchIndices"};`;return y.forEach(R=>{z+=`\nbIndices[${R}] = 0;`}),z+=`\nbIndices[${E-2}] = u32(row);\n bIndices[${E-1}] = u32(colIn);`,z};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ke(e,_)} {\n var value = ${Ke(e,_)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dimAOuter && col < uniforms.dimInner)\n {\n ${I()}\n value = ${h.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ke(e,_)} {\n var value = ${Ke(e,_)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dimInner && col < uniforms.dimBOuter)\n {\n ${$()}\n value = ${g.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ke(e,_)}) {\n let col = colIn * ${e};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${s?"bias[colIn]":`${Ke(e,_)}(bias[row])`};`:""}\n ${r}\n ${b.setByIndices("vec3(coords)","value")}\n }\n }\n `},tn=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s.slice(0,-2),a=u.slice(0,-2),p=o?o.slice(0,-2):r.slice(0,-2),h=Re(p.length),g=h?p.length:p,b=Fr("batchDims",e[0].dataType,g,1),w=U.size(p),y=s[s.length-2],_=s[s.length-1],I=u[u.length-1],$=_%4===0&&I%4===0,x=y<=8?[4,1,1]:[4,4,1],E=[8,8,1],A=[Math.ceil(I/E[0]/x[0]),Math.ceil(y/E[1]/x[1]),Math.ceil(w/E[2]/x[2])],z=Le(e[0].dataType),R=$?4:1,V=[...l,y,_/R],T=Re(V.length),N=T?V.length:V,te=[...a,_,I/R],Y=Re(te.length),K=Y?te.length:te,Q=[w,y,I/R],Z=M("a",e[0].dataType,N,R),Ee=M("b",e[1].dataType,K,R),Pe=F("result",e[0].dataType,Q.length,R),fe=[Z,Ee],Ie=[{type:"int32",data:y},{type:"int32",data:I},{type:"int32",data:_}];h&&Ie.push(...L(p)),T&&Ie.push(...L(V)),Y&&Ie.push(...L(te));let he=[];he.push(T?"rank":"dims"),he.push(Y?"rank":"dims");let ye=e.length>2,{activationFunction:We,applyActivation:De}=gt(t,Pe.type.value),Ge=dl(R,ye,De,[b,Z,Ee,Pe],[l,a,p],n);if(ye){let ee=n?R:1;fe.push(M("bias",e[2].dataType,e[2].dims.length,ee)),Ie.push(...L(e[2].dims)),he.push("rank")}Ie.push(...L(Q));let G=ee=>`\n ${ee.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").registerInternalVariables(b).declareVariables(...fe,Pe)}\n ${We}\n ${Ge}\n ${$?mr(x,E,z,b):fr(x,E,z,b)}\n `;return{name:"MatMul",shaderCache:{hint:t.activationCacheKey+`${x}${$}${n}`,inputDependencies:he},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:Ie}),getShaderSource:G}}});var ll,Wi,Hi=j(()=>{"use strict";Ct();ve();It();Jr();Nn();hr();ll=(e,t,r,o,n=!1,s,u=4,l=4,a=4,p="f32")=>{let h=Y=>{switch(Y){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Y} is not supported.`)}},g=Y=>{switch(Y){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Y} is not supported.`)}},b=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,w=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",_=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",I=e?"row":"col",$=e?"col":"row",x=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${I} / outWidth;\n let outCol = ${I} % outWidth;\n\n let WRow = ${$} / (filterDims[1] * inChannels);\n let WCol = ${$} / inChannels % filterDims[1];\n let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0];\n let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1];\n let xCh = ${$} % inChannels;\n var resData = ${Ke(u,p)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the \'same\' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${_}) {\n ${b}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${h(u)}\n }\n return resData;`,E=e?t&&o?`\n let col = colIn * ${u};\n ${x}`:`\n let col = colIn * ${u};\n if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n ${x}\n }\n return ${Ke(u,p)}(0.0);`:o&&r?`\n let col = colIn * ${u};\n ${x}`:`\n let col = colIn * ${u};\n if (row < uniforms.dimInner && col < uniforms.dimBOuter) {\n ${x}\n }\n return ${Ke(u,p)}(0.0);`,A=`${g(l)}`,z=Ke(a,p),R=e?Ke(u,p):Ke(l,p),V=e?Ke(l,p):Ke(u,p),{activationFunction:T,applyActivation:N}=gt(s,z);return`\n ${T}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${R} {\n ${e?E:A}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${V} {\n ${e?A:E}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${z}) {\n let col = colIn * ${a};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${w}\n ${Xr(n)}\n ${N}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Wi=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],h=r[0],g=a?r[2]:r[3],b=a?r[1]:r[2],w=a?r[3]:r[1],y=a&&(p%4===0||p%3===0)&&w%4===0,_=a?w:g*b,I=a?g*b:w,$=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(_/$[0]/x[0]),Math.ceil(I/$[1]/x[1]),Math.ceil(h/$[2]/x[2])];Be("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let A=y?a&&p%4!==0?3:4:1,z=$[1]*x[1],R=$[0]*x[0],V=Math.max($[0]*A,$[1]),T=o%z===0,N=n%R===0,te=s%V===0,Y=y?[A,4,4]:[1,1,1],K=Le(e[0].dataType),Q=y?4:1,Z=[{type:"int32",data:o},{type:"int32",data:n},{type:"int32",data:s}],Ee=M("x",e[0].dataType,e[0].dims.length,A===3?1:A),Pe=M("w",e[1].dataType,e[1].dims.length,Q),fe=[Ee,Pe];Z.push(...L(e[0].dims)),Z.push(...L(e[1].dims));let Ie=`\n fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${K}>`:K}) {\n result[flatIndex] = ${y?`vec4<${K}>`:K}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${y?`vec4<${K}>`:K}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${y?"/ 4":""}, value);\n }`;if(u){let ye=M("bias",e[2].dataType,e[2].dims.length,Q);fe.push(ye),Z.push(...L(e[2].dims)),Ie+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${K}>`:K} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}let he=F("result",e[0].dataType,r.length,Q);return Z.push(...L(r)),{name:"Conv2DMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:Z}),getShaderSource:ye=>`\n ${en("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${ye.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...fe,he)}\n const filterDims : vec2 = vec2(${t.kernelShape[0]}, ${t.kernelShape[1]});\n const pad : vec2 = vec2(${t.pads[0]}, ${t.pads[1]});\n const stride : vec2 = vec2(${t.strides[0]}, ${t.strides[1]});\n const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]});\n ${Ie}\n ${ll(a,T,N,te,u,t,Y[0],Y[1],Y[2],K)}\n ${y?mr(x,$,K,void 0,!a,V):fr(x,$,K,void 0,!a,V,!1,void 0,l)}`}}});var Wn,Gi=j(()=>{"use strict";$e();ve();Gn();It();Wn=(e,t,r)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",s=e[0].dims,u=e[1].dims,l=u[0]/t.group,a=t.format==="NHWC",p=Hn(s,u,t.dilations,t.pads,t.strides,a),h=U.size(p),g=F("output",e[0].dataType,p),{activationFunction:b,applyActivation:w}=gt(t,g.type.value),y=M("x",e[0].dataType,s),_=M("w",e[1].dataType,u),I=[y,_];o&&I.push(M("b",e[2].dataType,e[2].dims));let $=x=>`\n const strides: vec2 = vec2(${t.strides[0]}u, ${t.strides[1]}u);\n const pads: vec2 = vec2(${t.pads[0]}u, ${t.pads[1]}u);\n\n ${x.declareVariables(...I,g)}\n\n ${b}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(h)}\n\n let outputIndices = ${g.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${a?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${a?1:2}], outputIndices[${a?2:3}]) * strides - pads;\n let group_id: u32 = output_channel / ${l}u;\n\n var value: ${g.type.value} = ${g.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < ${u[1]}u; wInChannel++) {\n let input_channel = group_id * ${u[1]}u + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < ${u[2]}u; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}u;\n\n if (xHeight < 0u || xHeight >= ${s[a?1:2]}u) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < ${u[3]}u; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}u;\n if (xWidth < 0u || xWidth >= ${s[a?2:3]}u) {\n continue;\n }\n\n let xVal = ${a?y.get("batch","xHeight","xWidth","input_channel"):y.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${_.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${n}\n ${w}\n ${g.setByOffset("global_idx","value")}\n }`;return{name:"GroupedConv",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r?r(p):p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)}}),getShaderSource:$}}});var Ln,cl,Li,Fn=j(()=>{"use strict";$e();hr();ve();It();Ln=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s[s.length-2],a=u[u.length-1],p=s[s.length-1],h=Fe(a),g=Fe(p),b=Fe(l),w=U.size(r)/h/b,y=e.length>2,_=o?o.slice(0,-2):r.slice(0,-2),$=[U.size(_),l,a],x=[{type:"uint32",data:w},{type:"uint32",data:l},{type:"uint32",data:a},{type:"uint32",data:p},...L(_),...L(s),...L(u)];y&&x.push(...L(e[2].dims)),x.push(...L($));let E=A=>{let z=Fr("batch_dims",e[0].dataType,_.length),R=M("a",e[0].dataType,s.length,g),V=M("b",e[1].dataType,u.length,h),T=F("output",e[0].dataType,$.length,h),{activationFunction:N,applyActivation:te}=gt(t,T.type.value),Y=[R,V],K="";if(y){let he=n?h:1;Y.push(M("bias",e[2].dataType,e[2].dims.length,he)),K=`${n?`value += bias[col / ${he}];`:`value += ${T.type.value}(bias[row + i]);`}`}let Q=s.slice(0,-2),Z=u.slice(0,-2),Ee=Ft(Q,_),Pe=Ft(Z,_),fe=(he,ye)=>{let We=he.rank,De=he.name;if(We===2)return`var ${De}_indices = ${he.type.indices}(0u, 0u);`;let Ge=z.rank,G=`var ${De}_indices: ${he.type.indices};`;for(let ee=We-2-1,be=Ge-1;ee>=0;ee--,be--)G+=`\n${De}_indices[${ee}] = ${Ge>1?`batch_indices[${be}]`:"batch_indices"};`;return ye.forEach(ee=>{G+=`\n${De}_indices[${ee}] = 0;`}),G+=`${De}_indices[${We-2}] = 0u;\n ${De}_indices[${We-1}] = 0u;`,G},Ie=()=>{let he=`var a_data: ${R.type.value};`;for(let ye=0;ye;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${g}) {\n ${Ie()}\n }\n for (var i = 0u; i < ${b}u; i++) {\n var value = values[i];\n ${K}\n ${te}\n let cur_indices = ${T.type.indices}(batch, row + i, col);\n let offset = ${T.indicesToOffset("cur_indices")};\n ${T.setByOffset(`offset / ${h}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activationCacheKey}_${h}_${g}_${b}_${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:x}),getShaderSource:E}},cl=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Li=e=>{cl(e.inputs);let t=dt.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can\'t use matmul on the given tensors");let r=t[t.length-1],o=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&o<8?e.compute(Ln(e.inputs,{activation:"",activationCacheKey:""},t)):e.compute(tn(e.inputs,{activation:"",activationCacheKey:""},t))}});var Hn,Fi,pl,ji,jn,ml,fl,qn,Gn=j(()=>{"use strict";$e();je();Hi();hr();Gi();It();Fn();jt();Hn=(e,t,r,o,n,s)=>{let u=e[0],l=e.slice(s?1:2,s?3:4),a=l.length,p=t[0],g=t.slice(2).map((y,_)=>y+(y-1)*(r[_]-1)),w=l.map((y,_)=>y+o[_]+o[_+a]).map((y,_)=>Math.floor((y-g[_]+n[_])/n[_]));return w.splice(0,0,u),w.splice(s?3:1,0,p),w},Fi=[2,3,1,0],pl=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[1]*t.group;if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ji=(e,t)=>{let r=e.kernelShape.slice();for(let s=2;s{let t=Qr(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,s=e.group,u=e.kernel_shape,l=e.pads,a=e.strides,p=e.w_is_const();return ge({autoPad:o,format:r,dilations:n,group:s,kernelShape:u,pads:l,strides:a,wIsConst:p,...t})},ml=(e,t,r)=>{let o=ji(r,t),n=r.format==="NHWC";if(r.group!==1){e.compute(Wn(t,o));return}let s=t.length===3,u=t[0].dims[n?1:2],l=t[0].dims[n?2:3],a=t[0].dims[n?3:1],p=t[1].dims[2],h=t[1].dims[3],g=Hn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,n),b=g[n?1:2],w=g[n?2:3],y=g[n?3:1],_=n&&p===u&&h===l&&r.pads[0]===0&&r.pads[1]===0;if(_||p===1&&h===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let R=g[0],V,T,N,te=[];if(n){let Q=e.kernelCustomData.wT??e.compute(it(t[1],Fi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Q),_){let Z=u*l*a;V=t[0].reshape([1,R,Z]),T=Q.reshape([1,Z,y]),N=[1,R,y]}else V=t[0].reshape([R,u*l,a]),T=Q.reshape([1,a,y]),N=[R,b*w,y];te.push(V),te.push(T)}else V=t[0].reshape([R,a,u*l]),T=t[1].reshape([1,y,a]),N=[R,y,b*w],te.push(T),te.push(V);s&&te.push(t[2]);let Y=N[2],K=te[0].dims[te[0].dims.length-1];Y<8&&K<8?e.compute(Ln(te,o,g,N,n),{inputs:te}):e.compute(tn(te,o,g,N,n),{inputs:te});return}let I=!0,$=e.kernelCustomData.wT??e.compute(it(t[1],Fi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let x=[t[0],$];s&&x.push(t[2]);let E=n?b*w:y,A=n?y:b*w,z=p*h*a;e.compute(Wi(x,o,g,E,A,z,s,I),{inputs:x})},fl=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&o.push(e.inputs[2]);let n=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),u=[1].concat(t.dilations),l=[1].concat(t.kernelShape),a=ji({...t,pads:n,strides:s,dilations:u,kernelShape:l},o);e.compute(Wn(o,a,p=>r?[p[0],p[2],p[3]]:[]))},qn=(e,t)=>{pl(e.inputs,t),e.inputs[0].dims.length===3?fl(e,t):ml(e,e.inputs,t)}});var hl,qi,Ki=j(()=>{"use strict";Ct();ve();It();Jr();Nn();hr();hl=(e,t=!1,r,o=4)=>{let n=Ke(o,"f32"),s=x=>{switch(x){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return vec4(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${x} is not supported.`)}},u=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,l=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,a=e?"outBackprop[1]":"outBackprop[2]",p=e?"outBackprop[2]":"outBackprop[3]",h=e?"row":"col",g=e?"col":"row",b=`\n let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${h} / outWidth;\n let outCol = ${h} % outWidth;\n\n let WRow = ${g} / (filterDims[1] * inChannels);\n let WCol = ${g} / inChannels % filterDims[1];\n let xR = f32(outRow - pads[0] + dilation[0] * WRow) / f32(strides[0]);\n let xC = f32(outCol - pads[1] + dilation[1] * WCol) / f32(strides[1]);\n if (xR < 0.0 || xR >= f32(${a}) || fract(xR) > 0.0) {\n return ${n}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) {\n return ${n}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${g} % inChannels;\n ${u}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`,w=e?`\n let col = colIn * ${o};\n if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n ${b}\n }\n return ${n}(0.0);`:`\n let col = colIn * ${o};\n if (row < uniforms.dimInner && col < uniforms.dimBOuter) {\n ${b}\n }\n return ${n}(0.0);`,y=`\n let col = colIn * ${o};\n let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"};\n let coordX = filterDims.x - 1 - row / (filterDims[1] * inChannels);\n let coordY = filterDims.y - 1 - (row / inChannels) % filterDims[1];\n if (${e?"row < uniforms.dimInner && col < uniforms.dimBOuter":"row < uniforms.dimInner && col < uniforms.dimAOuter"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${s(o)}\n }\n return ${n}(0.0);\n `,{activationFunction:_,applyActivation:I}=gt(r,n);return`\n ${_}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?w:y}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?y:w}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) {\n let col = colIn * ${o};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${l}\n ${Xr(t)}\n ${I}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value;\n }\n }`},qi=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],h=r[0],g=a?r[2]:r[3],b=a?r[1]:r[2],w=a?r[3]:r[1],y=a?p%4===0&&w%4===0:g%4===0&&w%4===0,_=a?w:g*b,I=a?g*b:w,$=y?[8,8,1]:[_<=4||I<=4?4:16,_>4&&I<=4?4:16,1],x=y?[4,4,1]:[_<=4?1:4,_>4&&I<=4?1:4,1],E=[Math.ceil(_/$[0]/x[0]),Math.ceil(I/$[1]/x[1]),Math.ceil(h/$[2]/x[2])];Be("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let A=y?4:1,z=Math.max($[0]*A,$[1]),R=y?4:1,V=[{type:"int32",data:o},{type:"int32",data:n},{type:"int32",data:s}],T=M("x",e[0].dataType,e[0].dims.length,R),N=M("w",e[1].dataType,e[1].dims.length,1),te=F("result",e[0].dataType,r.length,R),Y=[T,N];V.push(...L(e[0].dims)),V.push(...L(e[1].dims));let K="";if(u){let Q=M("bias",e[2].dataType,e[2].dims.length,R);Y.push(Q),V.push(...L(e[2].dims)),K+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?"vec4":"f32"} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}return V.push(...L(r)),{name:"Conv2DTransposeMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:V}),getShaderSource:Q=>`\n ${en("uniforms.result_strides")}\n ${Q.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...Y,te)};\n const outBackprop : vec4 = vec4(${e[0].dims.join(",")});\n const filterDims : vec2 = vec2(${t.kernelShape[a?1:2]}, ${t.kernelShape[a?2:3]});\n const effectiveFilterDims : vec2 = filterDims + vec2(\n ${t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)},\n ${t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1)});\n const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${t.pads[0]+t.pads[2]})/2,\n i32(effectiveFilterDims[1]) - 1 - (${t.pads[1]+t.pads[3]})/2);\n const strides : vec2 = vec2(${t.strides[0]}, ${t.strides[1]});\n const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]});\n const dimAOuter : i32 = ${o};\n const dimBOuter : i32 = ${n};\n const dimInner : i32 = ${s};\n ${K}\n ${hl(a,u,t,A)}\n ${y?mr(x,$,"f32",void 0,!a,z):fr(x,$,"f32",void 0,!a,z,!1,void 0,l)}`}}});var gl,Kn,Yi=j(()=>{"use strict";Ct();$e();ve();gl=(e,t,r,o,n,s,u=!1,l)=>{let a=r.format==="NHWC",p=a?1:2,h=a?2:3,g=a?3:1,b=U.size(o),w=u?2:1,y=r.group,_=t[1].dims,I=_[0]/y,$=_[1],x=`\n fn setOutputAtIndex(flatIndex : u32, value : ${u?`vec4<${l}>`:l}) {\n result[flatIndex] = ${u?`vec4<${l}>`:l}(value);\n }`;n&&(x+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${u?`vec4<${l}>`:l} {\n return bias[coords.${a?"w":"y"}${u?"/ 4":""}];\n }`);let E=u?4:1,A=M("W",t[1].dataType,t[1].dims,E),z=M("Dy",t[0].dataType,t[0].dims,E),R=[z,A];n&&R.push(M("bias",t[2].dataType,[o[g]],E));let V=F("result",t[0].dataType,o,E),T=`{\n let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / outShape[1];\n let r = ${s?"global_id.z":"workgroup_id.z"} % outShape[1];\n let c = ${s?"global_id.y":"workgroup_id.y"} * ${w};\n let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${w}>;\n for (var i = 0; i < ${w}; i++) {\n dotProd[i] = vec4<${l}>(0.0);\n }\n for (var wR: u32 = 0; wR < filterDims[0]; wR = wR + 1) {\n var dyR = (${l}(dyCorner.x) + ${l}(wR)) / ${l}(strides.x);\n let wRPerm = filterDims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${l}(outBackprop[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < filterDims[1]; wC = wC + 1) {\n let dyC = (${l}(dyCorner.y) + ${l}(wC)) / ${l}(strides.y);\n let dyC2 = (${l}(dyCorner.y) + 1.0 + ${l}(wC)) / ${l}(strides.y);\n let wCPerm = filterDims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${l}(outBackprop[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${l}(outBackprop[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = outBackprop[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${z.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = outBackprop[${g}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = outBackprop[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${w}; i = i + 1) {\n let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${l}>(0.0)`};\n ${V.set("batch","r","c + i","d1","value")};\n }\n }`,N=`\n let outputIndices = ${V.offsetToIndices("global_idx")};\n let batch = ${V.indicesGet("outputIndices",0)};\n let d1 = ${V.indicesGet("outputIndices",g)};\n let r = ${V.indicesGet("outputIndices",p)};\n let c = ${V.indicesGet("outputIndices",h)};\n let dyCorner = vec2(i32(r), i32(c)) - pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / ${$};\n let wOutChannel = d1 - groupId * ${$};\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${l}(0.0);\n for (var wR: u32 = 0; wR < effectiveFilterDims.x; wR = wR + 1) {\n if (wR % dilations.x != 0) {\n continue;\n }\n let dyR = (${l}(dyRCorner) + ${l}(wR)) / ${l}(strides[0]);\n let wRPerm = filterDims.x - 1 - wR / dilations.x;\n if (dyR < 0.0 || dyR >= ${l}(outBackprop[${p}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < effectiveFilterDims.y; wC = wC + 1) {\n if (wC % dilations.y != 0) {\n continue;\n }\n let dyC = (${l}(dyCCorner) + ${l}(wC)) / ${l}(strides.y);\n let wCPerm = filterDims.y - 1 - wC / dilations.y;\n if (dyC < 0.0 || dyC >= ${l}(outBackprop[${h}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * ${I};\n for (var d2: u32 = 0; d2 < ${I}; d2 = d2 + 1) {\n let xValue = ${a?z.get("batch","idyR","idyC","inputChannel"):z.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${A.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${n?"bias[d1]":`${l}(0.0)`};\n ${V.setByOffset("global_idx","value")};\n `;return`\n ${e.declareVariables(...R,V)}\n ${x}\n const outShape : vec4 = vec4(${o.join(",")});\n const outBackprop : vec4 = vec4(${t[0].dims.join(",")});\n const strides : vec2 = vec2(${r.strides[0]}, ${r.strides[1]});\n const filterDims : vec2 = vec2(${r.kernelShape[a?1:2]}, ${r.kernelShape[a?2:3]});\n const dilations : vec2 = vec2(${r.dilations[0]}, ${r.dilations[1]});\n const effectiveFilterDims : vec2 = filterDims + vec2(\n ${r.dilations[0]<=1?0:(r.kernelShape[a?1:2]-1)*(r.dilations[0]-1)},\n ${r.dilations[1]<=1?0:(r.kernelShape[a?2:3]-1)*(r.dilations[1]-1)});\n const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${r.pads[0]+r.pads[2]})/2,\n i32(effectiveFilterDims[1]) - 1 - (${r.pads[1]+r.pads[3]})/2);\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(b)};\n ${u?T:N}}`},Kn=(e,t,r)=>{let o=e.length>2,n=t.outputShape,s=U.size(n),u=[Math.ceil(s/64),1,1];Be("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let l=Le(e[0].dataType);return{name:"ConvTranspose2D",shaderCache:{hint:t.cacheKey},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:r?r(n):n,dataType:e[0].dataType}]}),getShaderSource:a=>gl(a,e,t,n,o,u[1]===1&&u[2]===1,!1,l)}}});var yl,bl,wl,Zi,Qi,vl,$l,Sl,xl,Xi,Ji=j(()=>{"use strict";je();Ki();Yi();It();jt();yl=(e,t,r,o,n,s)=>(e-1)*t+r+(o-1)*n+1-s,bl=(e,t,r,o,n)=>{let s=Math.floor(e/2);t==="SAME_UPPER"?(r[o]=s,r[n]=e-s):t==="SAME_LOWER"&&(r[o]=e-s,r[n]=s)},wl=(e,t,r,o,n,s,u,l,a,p)=>{let h=e.length-2,g=p.length===0;if(a.length===0)for(let y=0;y{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((b,w)=>b*w,1)===0){r.length=0;for(let b=2;bb+w,0)===0){let b=t[0].dims.length-2;a=new Array(b).fill(1)}let p=e.strides.slice();if(p.reduce((b,w)=>b+w,0)===0){let b=t[0].dims.length-2;p=new Array(b).fill(1)}wl(l,r,a,e.autoPad,e.group,n,p,o,u,s);let h=Object.assign({},e),g=e.cacheKey+[r.join("n,"),n.join(","),p.join(","),u.join(","),s.join(","),a.join(",")].join("_");return Object.assign(h,{kernelShape:r,pads:n,outputPadding:u,outputShape:s,dilations:a,strides:p,cacheKey:g}),h},Qi=e=>{let t=Qr(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,s=e.group,u=e.kernelShape,l=e.pads,a=e.strides,p=e.wIsConst(),h=e.outputPadding,g=e.outputShape;return ge({autoPad:o,format:r,dilations:n,group:s,kernelShape:u,outputPadding:h,outputShape:g,pads:l,strides:a,wIsConst:p,...t})},vl=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[0];if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.reduce((h,g)=>h+g,0)>0&&t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.reduce((h,g)=>h+g,0)>0&&t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.reduce((h,g)=>h+g,0)>0&&t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.outputPadding.length!==s&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${s}D`);if(t.kernelShape.reduce((h,g)=>h+g,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},$l=[2,3,1,0],Sl=(e,t,r)=>{let o=Zi(r,t),n=r.format==="NHWC",s=o.outputShape,u=s[n?3:1],l=t[0].dims[n?3:1];if(o.group!==1||u===1&&l===1){e.compute(Kn(t,o));return}let a=s[n?1:2],p=s[n?2:3],h=t[1].dims[2],g=t[1].dims[3],b=n?a*p:u,w=n?u:a*p,y=h*g*l,_=!0,I=e.kernelCustomData.wT??e.compute(it(t[1],$l),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let $=[t[0],I],x=t.length===3;x&&(!n&&t[2].dims.length===1?$.push(t[2].reshape([t[2].dims[0],1,1])):$.push(t[2])),e.compute(qi($,o,s,b,w,y,x,_),{inputs:$})},xl=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];o.length===3&&o.push(e.inputs[2]);let n=t.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let s=t.dilations;(s.length===0||s[0]===0)&&(s=[1]);let u=t.strides;(u.length===0||u[0]===0)&&(u=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],u=[1].concat(u),s=[1].concat(s),n=[1].concat(n);let a=Zi({...t,pads:l,strides:u,dilations:s,kernelShape:n},o);e.compute(Kn(o,a,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},Xi=(e,t)=>{vl(e.inputs,t),e.inputs[0].dims.length===3?xl(e,t):Sl(e,e.inputs,t)}});var _l,es,ts,rs=j(()=>{"use strict";Ne();$e();je();ve();_l=(e,t,r,o)=>{let n=U.size(t),s=t.length,u=M("input",e,s),l=F("output",e,s),a=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=U.normalizeAxis(a,s),h=g=>{let b=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,w=ce("uniforms.input_shape","uniforms.axis",s),y=o.reverse?b+(o.exclusive?" + 1":""):"0",_=o.reverse?w:b+(o.exclusive?"":" + 1");return`\n ${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,l)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${l.offsetToIndices("global_idx")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${_};\n for (var i : i32 = first; i < last; i++) {\n ${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${u.getByIndices("inputIndices")};\n }\n ${l.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:o.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:"uint32",data:n},{type:"int32",data:p},...L(t),...L(t)]}),getShaderSource:h}},es=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,n=e.inputs[1];e.compute(_l(o,r,n,t),{inputs:[0]})},ts=e=>{let t=e.exclusive===1,r=e.reverse===1;return ge({exclusive:t,reverse:r})}});var Yn,rn,ns,Cl,Il,Zn,Qn,os,Al,as,is,ss=j(()=>{"use strict";$e();je();ve();Yn="[a-zA-Z]|\\\\.\\\\.\\\\.",rn="("+Yn+")+",ns="^"+rn+"$",Cl="("+rn+",)*"+rn,Il="^"+Cl+"$",Zn=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let o=this.symbolToIndices.get(t);o===void 0?o=[r]:o.push(r),this.symbolToIndices.set(t,o)}},Qn=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[o,n]=r.includes("->")?r.split("->",2):[r,""];if(!o.match(RegExp(Il)))throw new Error("Invalid LHS term");if(o.split(",").forEach((l,a)=>{let p=t[a].dims.slice();if(!l.match(RegExp(ns)))throw new Error("Invalid LHS term");let h=this.processTerm(l,!0,p,a);this.lhs.push(h)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([l,a])=>a.count===1||l==="...").map(([l])=>l).join("");else if(!n.match(RegExp(rn)))throw new Error("Invalid RHS");n.match(RegExp(Yn,"g"))?.forEach(l=>{if(l==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(l);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(t,r,o){let n=this.symbolToInfo.get(t);if(n!==void 0){if(n.dimValue!==r&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(o)}else n={count:1,dimValue:r,inputIndices:[o]};this.symbolToInfo.set(t,n)}processTerm(t,r,o,n=-1){let s=o.length,u=!1,l=[],a=0;if(!t.match(RegExp(ns))&&!r&&t!=="")throw new Error("Invalid LHS term");let p=t.match(RegExp(Yn,"g")),h=new Zn(n);return p?.forEach((g,b)=>{if(g==="..."){if(u)throw new Error("Only one ellipsis is allowed per input term");u=!0;let w=s-p.length+1;if(w<0)throw new Error("Ellipsis out of bounds");if(l=o.slice(a,a+w),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let y=0;ye+"_max",Al=(e,t,r,o,n)=>{let u=t.map((w,y)=>e[y]?w.length:w).map((w,y)=>M(`input${y}`,r,w)),l=U.size(n),a=Re(n.length),p=a?n.length:n,h=F("output",r,p),g=[...o.symbolToInfo.keys()].filter(w=>!o.rhs.symbolToIndices.has(w)),b=w=>{let y=[],_="var prod = 1.0;",I="var sum = 0.0;",$="sum += prod;",x=[],E=[],A=[],z=[],R=o.symbolToInfo.size===o.rhs.symbolToIndices.size;o.symbolToInfo.forEach((T,N)=>{if(o.rhs.symbolToIndices.has(N)){let te=o.rhs.symbolToIndices.get(N)?.[0];te!==void 0&&o.lhs.forEach((Y,K)=>{if(T.inputIndices.includes(K)){let Q=Y.symbolToIndices.get(N);if(Q===void 0)throw new Error("Invalid symbol error");Q.forEach(Z=>{y.push(`${u[K].indicesSet(`input${K}Indices`,Z,h.indicesGet("outputIndices",te))}`)})}})}else o.lhs.forEach((te,Y)=>{if(T.inputIndices.includes(Y)){let K=te.symbolToIndices.get(N);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(Q=>{x.push(`${u[Y].indicesSet(`input${Y}Indices`,Q,`${N}`)}`)}),z.push(`prod *= ${u[Y].getByIndices(`input${Y}Indices`)};`)}}),E.push(`for(var ${N}: u32 = 0; ${N} < uniforms.${os(N)}; ${N}++) {`),A.push("}")});let V=R?[...y,`let sum = ${u.map((T,N)=>T.getByIndices(`input${N}Indices`)).join(" * ")};`]:[...y,I,...E,...x,_,...z,$,...A];return`\n ${w.registerUniforms(g.map(T=>({name:`${os(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,h)}\n\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${h.offsetToIndices("global_idx")};\n ${u.map((T,N)=>`var input${N}Indices: ${u[N].type.indices};`).join(`\n`)}\n ${V.join(`\n`)};\n ${h.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:o.equation,inputDependencies:e.map(w=>w?"rank":"dims")},getRunData:()=>{let w=g.filter(_=>o.symbolToInfo.has(_)).map(_=>({type:"uint32",data:o.symbolToInfo.get(_)?.dimValue||0}));w.push({type:"uint32",data:l});let y=t.filter((_,I)=>e[I]).map((_,I)=>[...L(_)]).reduce((_,I)=>_.concat(I),w);return a&&y.push(...L(n)),{outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:y}},getShaderSource:b}},as=(e,t)=>{let r=new Qn(e.inputs,t.equation),o=e.inputs.map((u,l)=>Re(u.dims.length)),n=r.outputDims,s=e.inputs.map((u,l)=>u.dims);e.compute(Al(o,s,e.inputs[0].dataType,r,n))},is=e=>{let t=e.equation.replace(/\\s+/g,"");return ge({equation:t})}});var Tl,us,El,Ol,ds,ls=j(()=>{"use strict";Ne();$e();ve();Tl=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=r.length{let r=e.length-t.length,o=[];for(let n=0;ne.length>t.length?us(e,t):us(t,e),Ol=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=El(t,r),n=e[0].dataType,s=n===9?4:1,u=Math.ceil(U.size(o)/s),l=Re(t.length),a=Re(o.length),p=g=>{let b=l?t.length:t,w=a?o.length:o,y=M("input",n,b,s),_=F("output",n,w,s),I;if(n===9){let $=(x,E,A="")=>`\n let outputIndices${E} = ${_.offsetToIndices(`outputOffset + ${E}u`)};\n let offset${E} = ${y.broadcastedIndicesToOffset(`outputIndices${E}`,_)};\n let index${E} = offset${E} / 4u;\n let component${E} = offset${E} % 4u;\n ${x}[${E}] = ${A}(${y.getByOffset(`index${E}`)}[component${E}]);\n `;I=`\n let outputOffset = global_idx * ${s};\n var data = vec4(0);\n ${$("data",0,"u32")}\n ${$("data",1,"u32")}\n ${$("data",2,"u32")}\n ${$("data",3,"u32")}\n ${_.setByOffset("global_idx","data")}\n }`}else I=`\n let outputIndices = ${_.offsetToIndices("global_idx")};\n let inputOffset = ${y.broadcastedIndicesToOffset("outputIndices",_)};\n ${_.setByOffset("global_idx",y.getByOffset("inputOffset"))}\n }`;return`\n ${g.registerUniform("vec_size","u32").declareVariables(y,_)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${I}`},h=[{type:"uint32",data:u}];return l&&h.push(...L(t)),a&&h.push(...L(o)),{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:[l?"rank":"dims"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h})}},ds=e=>{Tl(e.inputs),e.compute(Ol(e.inputs),{inputs:[0]})}});var Pl,kl,cs,ps,ms=j(()=>{"use strict";Ne();$e();je();ve();Pl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},kl=(e,t)=>{let r=e[0].dims,o=e[1].dims,n=r.length,s=U.normalizeAxis(t.axis,n),u=r.slice(0);u.splice(s,1,...o);let l=r[s],a=e[0].dataType===9?4:1,p=Math.ceil(U.size(u)/a),h=Re(e[0].dims.length),g=h?e[0].dims.length:e[0].dims,b=Re(e[1].dims.length),w=b?e[1].dims.length:e[1].dims,y=Re(u.length),_=y?u.length:u,I=[{type:"uint32",data:p},{type:"int32",data:l},{type:"uint32",data:s}];h&&I.push(...L(e[0].dims)),b&&I.push(...L(e[1].dims)),y&&I.push(...L(u));let $=[];$.push(h?"rank":"dims"),$.push(b?"rank":"dims");let x=E=>{let A=M("data",e[0].dataType,g,a),z=M("inputIndices",e[1].dataType,w),R=F("output",e[0].dataType,_,a),V=N=>{let te=o.length,Y=`var indicesIndices${N} = ${z.type.indices}(0);`;for(let K=0;K1?`indicesIndices${N}[${K}]`:`indicesIndices${N}`} = ${u.length>1?`outputIndices${N}[uniforms.axis + ${K}]`:`outputIndices${N}`};`;Y+=`\n var idx${N} = ${z.getByIndices(`indicesIndices${N}`)};\n if (idx${N} < 0) {\n idx${N} = idx${N} + uniforms.axisDimLimit;\n }\n var dataIndices${N} = ${A.type.indices}(0);\n `;for(let K=0,Q=0;K1?`dataIndices${N}[${K}]`:`dataIndices${N}`} = u32(idx${N});`,Q+=te):(Y+=`${n>1?`dataIndices${N}[${K}]`:`dataIndices${N}`} = ${u.length>1?`outputIndices${N}[${Q}]`:`outputIndices${N}`};`,Q++);return Y},T;if(e[0].dataType===9){let N=(te,Y,K="")=>`\n let outputIndices${Y} = ${R.offsetToIndices(`outputOffset + ${Y}u`)};\n ${V(Y)};\n let offset${Y} = ${A.indicesToOffset(`dataIndices${Y}`)};\n let index${Y} = offset${Y} / 4u;\n let component${Y} = offset${Y} % 4u;\n ${te}[${Y}] = ${K}(${A.getByOffset(`index${Y}`)}[component${Y}]);\n `;T=`\n let outputOffset = global_idx * ${a};\n var value = vec4(0);\n ${N("value",0,"u32")}\n ${N("value",1,"u32")}\n ${N("value",2,"u32")}\n ${N("value",3,"u32")}\n ${R.setByOffset("global_idx","value")}\n `}else T=`\n let outputIndices = ${R.offsetToIndices("global_idx")};\n ${V("")};\n let value = ${A.getByIndices("dataIndices")};\n ${R.setByOffset("global_idx","value")};\n `;return`\n ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(A,z,R)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${T}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:$},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:I}),getShaderSource:x}},cs=e=>ge({axis:e.axis}),ps=(e,t)=>{let r=e.inputs;Pl(r),e.compute(kl(e.inputs,t))}});var Rl,Bl,fs,hs,gs=j(()=>{"use strict";$e();je();ve();Rl=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Bl=(e,t)=>{let r=e[0].dims,o=e[0].dataType,n=r.length,s=e[1].dims,u=e[1].dataType,l=U.normalizeAxis(t.axis,n),a=r[l],p=s.slice(0),h=U.size(p),g=M("input",o,n),b=M("indicesInput",u,s.length),w=F("output",o,p.length),y=[{type:"uint32",data:h},{type:"int32",data:a},{type:"uint32",data:l}];return y.push(...L(r)),y.push(...L(s)),y.push(...L(p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:y}),getShaderSource:$=>`\n ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,b,w)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${w.offsetToIndices("global_idx")};\n\n var idx = ${b.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${g.type.indices}(outputIndices);\n ${g.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${g.getByIndices("inputIndices")};\n\n ${w.setByOffset("global_idx","value")};\n }`}},fs=e=>ge({axis:e.axis}),hs=(e,t)=>{let r=e.inputs;Rl(r),e.compute(Bl(e.inputs,t))}});var Dl,Ml,ys,bs,ws=j(()=>{"use strict";$e();ve();Dl=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Ml=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[n,s,u]=Hr.getShapeOfGemmResult(r,t.transA,o,t.transB,e.length===3?e[2].dims:void 0),l=[n,s];if(!l)throw new Error("Can\'t use gemm on the given tensors");let a=U.size(l),p=[{type:"uint32",data:a},{type:"uint32",data:n},{type:"uint32",data:s},{type:"uint32",data:u},{type:"float32",data:t.alpha},{type:"float32",data:t.beta}],h=["type","type"];e.length===3&&(p.push(...L(e[2].dims)),h.push("rank")),p.push(...L(l));let g=b=>{let w="";t.transA&&t.transB?w="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?w="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?w="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(w="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let y=t.alpha===1?"":"value *= uniforms.alpha;",_=M("a",e[0].dataType,e[0].dims),I=M("b",e[1].dataType,e[1].dims),$=_.type.value,x=null,E=[_,I];e.length===3&&(x=M("c",e[2].dataType,e[2].dims.length),E.push(x));let A=F("output",e[0].dataType,l.length);E.push(A);let z=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`\n ${b.registerUniforms(z).declareVariables(...E)}\n\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${$}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${w}\n }\n\n ${y}\n ${(()=>x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${$}(uniforms.beta) * ${x.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:g}},ys=e=>{let t=e.transA,r=e.transB,o=e.alpha,n=e.beta;return{transA:t,transB:r,alpha:o,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},bs=(e,t)=>{Dl(e.inputs),e.compute(Ml(e.inputs,t))}});var zl,Ul,Vl,vs,$s=j(()=>{"use strict";Ne();$e();ve();zl=(e,t)=>{let r=e[0].dims,o=r,n=2,s=U.sizeToDimension(r,n),u=U.sizeFromDimension(r,n),l=Fe(u),a=u/l,p=[r[0],r[1],a],h=["rank","type","type"],g=[{type:"uint32",data:u},{type:"uint32",data:a}];g.push(...L(p),...L(p));let b=w=>{let y=M("x",e[0].dataType,p.length,l),_=M("scale",e[1].dataType,e[1].dims),I=M("bias",e[2].dataType,e[2].dims),$=F("output",e[0].dataType,p.length,l),x=[y,_,I,$],E=y.type.value,A=l===1?"f32":`vec${l}`,z=64,R=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${A}, ${z}>;\n const workgroupSize = ${z}u;\n ${w.registerUniforms(R).declareVariables(...x)}\n ${w.mainStart(z)}\n let norm = global_idx / workgroupSize;\n let batch = norm / uniforms.x_shape[1];\n let channel = norm % uniforms.x_shape[1];\n let localIndex = local_id.x;\n\n // initialize workgroup memory\n var initial = ${A}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${A}(${y.get("batch","channel","h")});\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the mean of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n meanShared = ${Je("workgroupShared[0]",l)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${A}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${A}(${y.get("batch","channel","h")}) - ${A}(meanShared);\n initial = initial + deviation * deviation;\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the sum of square of deviation of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n squaredNormShared = ${Je("workgroupShared[0]",l)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${_.getByOffset("channel")});\n let channelShift = f32(${I.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${y.get("batch","channel","h")} * ${E}(${A}(channelScale)) + ${E}(${A}(channelShift));\n ${$.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${l}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:s},programUniforms:g}),getShaderSource:b}},Ul=(e,t,r,o,n,s,u,l)=>{let a=Fe(u),p=64,h=a===1?"vec2f":`mat2x${a}f`,g=a===1?"f32":`vec${a}f`,b=(R,V)=>`${h}(${R}, ${V})`,w=n*u/a,y=Math.ceil(s/p),_=["type"],I=[{type:"uint32",data:y},{type:"uint32",data:s},{type:"uint32",data:Math.floor(u/a)},{type:"uint32",data:Math.floor(s*u/a)}],$=R=>{let V=M("input",t.dataType,t.dims,a);return`\n ${R.declareVariables(V)}\n @group(0) @binding(1) var output : array<${h}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${R.mainStart(p)}\n let currentImageNumber = global_idx / ${p} / uniforms.C;\n let currentChannelNumber = (global_idx / ${p}) % uniforms.C;\n let wgId = global_idx % ${p};\n let wgOffset = wgId * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${Ze("f32",a)};\n var squaredSum = ${Ze("f32",a)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${g}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${b("sum","squaredSum")};\n }`},x=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${a}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:[n,u,p,2],dataType:1}],dispatchGroup:{x:n*u/a},programUniforms:I}),getShaderSource:$},{inputs:[t],outputs:[-1]})[0],E=[{type:"uint32",data:w},{type:"uint32",data:s},{type:"uint32",data:Math.floor(u/a)},{type:"uint32",data:Math.floor(p*u/a)}],A=["type","type","type"],z=R=>{let V=M("scale",r.dataType,r.dims,a),T=M("bias",o.dataType,o.dims,a);return`\n @group(0) @binding(0) var input : array<${h}>;\n @group(0) @binding(1) var scale : array<${V.type.storage}>;\n @group(0) @binding(2) var bias : array<${T.type.storage}>;\n @group(0) @binding(3) var output : array<${h}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${R.mainStart()}\n ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")}\n let currentImageNumber = global_idx / uniforms.C;\n let currentChannelNumber = global_idx % uniforms.C;\n\n let offset = currentImageNumber * uniforms.image_size;\n var sum = ${Ze("f32",a)};\n var squaredSum = ${Ze("f32",a)};\n for (var i: u32 = 0; i < ${p}; i++) {\n let value = input[offset + i + currentChannelNumber * ${p}];\n sum += value[0];\n squaredSum += value[1];\n }\n sum = sum / f32(uniforms.H);\n squaredSum = squaredSum / f32(uniforms.H);\n let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${l}));\n let channelScale = invStdDev * ${g}(scale[currentChannelNumber]);\n let channelShift = ${g}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${b("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${a};${l}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:[n,u,2],dataType:1}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:E}),getShaderSource:z},{inputs:[x,r,o],outputs:[-1]})[0]},Vl=(e,t,r)=>{let o=t[0].dims,n=o,s=o[0],u=o[o.length-1],l=U.sizeFromDimension(o,1)/u,a=Fe(u),p=U.size(n)/a,h=[{type:"uint32",data:l},{type:"uint32",data:Math.floor(u/a)}],g=["type","type"],b=Ul(e,t[0],t[1],t[2],s,l,u,r.epsilon),w=y=>{let _=Le(t[0].dataType),I=a===1?"vec2f":`mat2x${a}f`,$=a===1?_:`vec${a}<${_}>`,x=M("input",t[0].dataType,t[0].dims,a),E=F("output",t[0].dataType,n,a);return`\n @group(0) @binding(0) var input : array<${x.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${I}>;\n @group(0) @binding(2) var output : array<${E.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${y.mainStart()}\n let currentImageNumber = global_idx / (uniforms.C * uniforms.H);\n let currentChannelNumber = global_idx % uniforms.C;\n\n let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber;\n let scale = scaleInput[scaleOffset];\n output[global_idx] = fma(input[global_idx], ${$}(scale[0]), ${$}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${a}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:w},{inputs:[t[0],b]})},vs=(e,t)=>{t.format==="NHWC"?Vl(e,e.inputs,t):e.compute(zl(e.inputs,t))}});var Nl,Wl,Ss,xs=j(()=>{"use strict";Ne();$e();ve();Nl=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Wl=(e,t,r)=>{let o=e[0].dims,n=e[1],s=e[2],u=o,l=U.normalizeAxis(t.axis,o.length),a=U.sizeToDimension(o,l),p=U.sizeFromDimension(o,l),h=U.size(n.dims),g=s?U.size(s.dims):0;if(h!==p||s&&g!==p)throw new Error(`Size of X.shape()[axis:] == ${p}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${h} and bias size of ${g}`);let b=[];for(let A=0;A1,$=r>2,x=A=>{let z=Le(e[0].dataType),R=[M("x",e[0].dataType,e[0].dims,w),M("scale",n.dataType,n.dims,w)];s&&R.push(M("bias",s.dataType,s.dims,w)),R.push(F("output",e[0].dataType,u,w)),I&&R.push(F("mean_data_output",1,b)),$&&R.push(F("inv_std_output",1,b));let V=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${A.registerUniforms(V).declareVariables(...R)}\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var meanVector = ${Ze("f32",w)};\n var meanSquareVector = ${Ze("f32",w)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${at(z,w,"x[h + offset]")};\n meanVector += value;\n meanSquareVector += value * value;\n }\n let mean = ${Je("meanVector",w)} / uniforms.norm_size;\n let invStdDev =\n inverseSqrt(${Je("meanSquareVector",w)} / uniforms.norm_size - mean * mean + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${at(z,w,"x[j + offset]")};\n let f32scale = ${at(z,w,"scale[j]")};\n output[j + offset] = ${R[0].type.value}((f32input - mean) * invStdDev * f32scale\n ${s?`+ ${at(z,w,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${$?"inv_std_output[global_idx] = invStdDev":""};\n }`},E=[{dims:u,dataType:e[0].dataType}];return I&&E.push({dims:b,dataType:1}),$&&E.push({dims:b,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${w};${r}`,inputDependencies:y},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:_}),getShaderSource:x}},Ss=(e,t)=>{Nl(e.inputs),e.compute(Wl(e.inputs,t,e.outputCount))}});var Hl,Cs,_s,Gl,Xn,Is,As=j(()=>{"use strict";$e();je();Nr();Un();ve();jt();Hl=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5],a=e[6],p=e[7];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let h=!1,g=r.dims[0],b=r.dims[1],w=r.dims.length===3?h?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=b,_=0,I=0,$=Math.floor(w/t.numHeads);if(a&&p){if(a.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(p.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');_=a.dims[2],I=a.dims[2]}else if(a||p)throw new Error(\'Input "past_key" and "past_value" shall be both present or both absent\');let x;if(o){if(r.dims.length!==3)throw new Error(\'Input "query" is expected to have 3 dimensions when key is given\');if(o.dims.length<3||o.dims.length>5)throw new Error(\'Input "key" is expected to have 3, 4, or 5 dimensions\');if(r.dims[0]!==o.dims[0])throw new Error(\'Input "query" and "key" shall have same dim 0 (batch size)\');if(o.dims.length===3){if(o.dims[2]!==r.dims[2])throw new Error(\'Input "query" and "key" shall have same dim 2 (hidden_size)\');x=2,y=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==$)throw new Error(\'Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv\');if(n)throw new Error(\'Expect "value" be none when "key" has packed kv format.\');x=5,y=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==$)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');x=0,y=o.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\'Input "query" is expected to have 3 or 5 dimensions when key is empty\');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error(\'Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv\');x=3}if(s){if(s.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(n&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let E=0;if(u){E=8;let T=u.dims;throw T.length===1?T[0]===g?E=1:T[0]===3*g+2&&(E=3):T.length===2&&T[0]===g&&T[1]===y&&(E=5),E===8?new Error(\'Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)\'):new Error("Mask not supported")}let A=!1,z=w;if(n){if(n.dims.length!==3&&n.dims.length!==4)throw new Error(\'Input "value" is expected to have 3 or 4 dimensions\');if(r.dims[0]!==n.dims[0])throw new Error(\'Input "query" and "value" shall have same dim 0 (batch_size)\');if(n.dims.length===3){if(y!==n.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');z=n.dims[2]}else{if(y!==n.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');z=n.dims[1]*n.dims[3],A=!0}}let R=_+y,V=!1;if(u)throw new Error("Key padding mask is not supported");if(l)throw new Error("extraAddQk is not supported");if(a)throw new Error("pastKey is not supported");if(p)throw new Error("pastValue is not supported");return{batchSize:g,sequenceLength:b,pastSequenceLength:_,kvSequenceLength:y,totalSequenceLength:R,maxSequenceLength:I,inputHiddenSize:0,hiddenSize:w,vHiddenSize:z,headSize:$,vHeadSize:Math.floor(z/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:E,scale:t.scale,broadcastResPosBias:V,passPastInKv:A,qkvFormat:x}},Cs=e=>ge({...e}),_s=ge({perm:[0,2,1,3]}),Gl=(e,t,r,o,n,s,u)=>{let l=[o,n,s],a=U.size(l),p=[{type:"uint32",data:a},{type:"uint32",data:u},{type:"uint32",data:s}],h=g=>{let b=F("qkv_with_bias",t.dataType,l),w=M("qkv",t.dataType,l),y=M("bias",r.dataType,l),_=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${g.registerUniforms(_).declareVariables(w,y,b)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:h},{inputs:[t,r],outputs:[-1]})[0]},Xn=(e,t,r,o,n,s,u,l)=>{let a=s;if(u){if(o===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return a=Gl(e,s,u,t,o,r*n,l),a=a.reshape([t,o,r,n]),e.compute(it(a,_s.perm),{inputs:[a],outputs:[-1]})[0]}else return s.dims.length===3&&(a=s.reshape([t,o,r,n])),e.compute(it(a,_s.perm),{inputs:[a],outputs:[-1]})[0]},Is=(e,t)=>{let r=Hl(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let o=e.inputs[1]&&e.inputs[2]&&e.inputs[1].dims.length===4&&e.inputs[2].dims.length===4,n=Xn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],e.inputs[3],0);if(o)return Kr(e,n,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t);let s=Xn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,e.inputs[1],e.inputs[3],r.hiddenSize),u=Xn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,e.inputs[2],e.inputs[3],2*r.hiddenSize);Kr(e,n,s,u,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],r,t)}});var Ll,Fl,jl,ql,Kl,Yl,Zl,Ql,Ts,Es=j(()=>{"use strict";Ne();$e();ve();Ll=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1)throw new Error("Input type must be float.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Fl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n break;\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n }\n `},jl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${ce("uniforms.x_shape",n,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},ql=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k = i32(${ce("uniforms.x_shape",n,t)}) - 1;\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},Kl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k += i32(${ce("uniforms.x_shape",n,t)}]);\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k -= i32(${ce("uniforms.x_shape",n,t)});\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},Yl=(e,t,r)=>{switch(r.mode){case 0:return Fl(e,t,r.pads.length);case 1:return jl(e,t,r.pads.length);case 2:return ql(e,t,r.pads.length);case 3:return Kl(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Zl=(e,t)=>{let r=U.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,s=[{type:"uint32",data:U.size(r)},{type:"uint32",data:t.pads}];if(t.mode===0){let a=Xe(e[0].dataType);s.push({type:a,data:t.value})}s.push(...L(e[0].dims),...L(r));let u=["rank"],l=a=>{let p=F("output",e[0].dataType,r.length),h=M("x",e[0].dataType,o.length),g=h.type.value,b=Yl(p,o.length,t),w=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&w.push({name:"constant_value",type:g}),`\n ${a.registerUniforms(w).declareVariables(h,p)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n\n var value = ${g}(0);\n ${b}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(U.size(r)/64)},programUniforms:s}),getShaderSource:l}},Ql=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),o=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,n=e[0].dims.length,s=new Int32Array(2*n).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let a=0;as[Number(a)]=Number(l));let u=[];return s.forEach(l=>u.push(l)),{mode:t.mode,value:o,pads:u}}else return t},Ts=(e,t)=>{Ll(e.inputs);let r=Ql(e.inputs,t);e.compute(Zl(e.inputs,r),{inputs:[0]})}});var nn,Os,Ps,ks,Rs,Xl,Jl,Bs,Ds,Ms,zs,Us,Vs,Ns,Ws,Hs,Gs,Ls,Fs,js=j(()=>{"use strict";Lt();$e();ve();nn=e=>{if(Gt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Os=(e,t,r)=>{let o=t.format==="NHWC",n=e.dims.slice();o&&n.splice(1,0,n.pop());let s=Object.hasOwnProperty.call(t,"dilations"),u=t.kernelShape.slice(),l=t.strides.slice(),a=s?t.dilations.slice():[],p=t.pads.slice();Bt.adjustPoolAttributes(r,n,u,l,a,p);let h=Bt.computePoolOutputShape(r,n,l,a,u,p,t.autoPad),g=Object.assign({},t);s?Object.assign(g,{kernelShape:u,strides:l,pads:p,dilations:a,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:u,strides:l,pads:p,cacheKey:t.cacheKey});let b=h.slice();return b.push(b.splice(1,1)[0]),[g,o?b:h]},Ps=(e,t)=>{let r=t.format==="NHWC",o=U.size(e),n=U.size(t.kernelShape),s=[{type:"uint32",data:o},{type:"uint32",data:n}],u=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],a=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],h=t.pads[t.pads.length-1],g=!!(p+h);s.push({type:"uint32",data:l},{type:"uint32",data:a},{type:"uint32",data:p},{type:"uint32",data:h}),u.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let b=!1;if(t.kernelShape.length===2){let w=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],_=t.pads[t.pads.length/2-2],I=t.pads[t.pads.length-2];b=!!(_+I),s.push({type:"uint32",data:w},{type:"uint32",data:y},{type:"uint32",data:_},{type:"uint32",data:I}),u.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[s,u,!0,g,b]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=U.computeStrides(t.kernelShape);s.push({type:"uint32",data:l},{type:"uint32",data:t.pads},{type:"uint32",data:t.strides}),u.push({name:"kernelStrides",type:"u32",length:l.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let a=t.pads.reduce((p,h)=>p+h);return[s,u,!!a,!1,!1]}},ks=(e,t,r,o,n,s,u,l,a,p,h,g)=>{let b=n.format==="NHWC",w=t.type.value,y=F("output",t.type.tensor,o);if(n.kernelShape.length<=2){let _="",I="",$="",x=r-(b?2:1);if(h?_=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${x}] < 0 || xIndices[${x}]\n >= uniforms.x_shape[${x}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:_=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`,n.kernelShape.length===2){let A=r-(b?3:2);g?I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${A}] = indices[${A}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${A}] < 0 || xIndices[${A}] >= uniforms.x_shape[${A}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${A}] = indices[${A}] * uniforms.sh - uniforms.phStart + j;\n `,$=`\n }\n `}return`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var value = ${w}(${l});\n var pad = 0;\n ${I}\n ${_}\n ${$}\n ${u}\n\n output[global_idx] = value;\n }`}else{if(b)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let _=n.kernelShape.length,I=n.pads.length,$="";return p?$=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:$=`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n `,`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${w}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${_-1}u; j++) {\n offsets[j] = offset / ${ce("uniforms.kernelStrides","j",_)};\n offset -= offsets[j] * ${ce("uniforms.kernelStrides","j",_)};\n }\n offsets[${_-1}] = offset;\n\n isPad = false;\n for (var j = ${r-_}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${ce("uniforms.strides",`j - ${r-_}u`,_)}\n + offsets[j - ${r-_}u] - ${ce("uniforms.pads","j - 2u",I)};\n ${$}\n }\n ${u}\n\n output[global_idx] = value;\n }`}},Rs=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Xl=e=>`${Rs(e)};${e.countIncludePad}`,Jl=e=>`${Rs(e)};${e.storageOrder};${e.dilations}`,Bs=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Ds=(e,t,r,o)=>{let[n,s]=Os(t,o,r),u=M("x",t.dataType,t.dims.length),l=u.type.value,a="value += x_val;",p="";n.countIncludePad?p+=`value /= ${l}(uniforms.kernelSize);`:p+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[h,g,b,w,y]=Ps(s,n);h.push(...L(t.dims),...L(s));let _=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${b};${w};${y}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(U.size(s)/64)},programUniforms:h}),getShaderSource:I=>ks(I,u,t.dims.length,s.length,n,a,p,0,g,b,w,y)}},Ms=e=>{let t=e.count_include_pad!==0,r=Bs(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let o={countIncludePad:t,...r,cacheKey:""};return{...o,cacheKey:Xl(o)}},zs=(e,t)=>{nn(e.inputs),e.compute(Ds("AveragePool",e.inputs[0],!1,t))},Us={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Vs=e=>{let t=e.format;return{format:t,...Us,cacheKey:t}},Ns=(e,t)=>{nn(e.inputs),e.compute(Ds("GlobalAveragePool",e.inputs[0],!0,t))},Ws=(e,t,r,o)=>{let[n,s]=Os(t,o,r),u=`\n value = max(x_val, value);\n `,l="",a=M("x",t.dataType,t.dims.length),p=["rank"],[h,g,b,w,y]=Ps(s,n);return h.push(...L(t.dims),...L(s)),{name:e,shaderCache:{hint:`${o.cacheKey};${b};${w};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(U.size(s)/64)},programUniforms:h}),getShaderSource:_=>ks(_,a,t.dims.length,s.length,n,u,l,-1e5,g,b,w,y)}},Hs=(e,t)=>{nn(e.inputs),e.compute(Ws("MaxPool",e.inputs[0],!1,t))},Gs=e=>{let t=e.storage_order,r=e.dilations,o=Bs(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(o.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:t,dilations:r,...o,cacheKey:""};return{...n,cacheKey:Jl(n)}},Ls=e=>{let t=e.format;return{format:t,...Us,cacheKey:t}},Fs=(e,t)=>{nn(e.inputs),e.compute(Ws("GlobalMaxPool",e.inputs[0],!0,t))}});var tc,rc,qs,Ks=j(()=>{"use strict";Lt();Ne();ve();tc=(e,t,r)=>{let o=e===t,n=et&&r>0;if(o||n||s)throw new Error("Range these inputs\' contents are invalid.")},rc=(e,t,r,o)=>{let n=Math.abs(Math.ceil((t-e)/r)),s=[n],u=n,l=Xe(o),a=[{type:"uint32",data:u},{type:l,data:e},{type:l,data:r},...L(s)],p=h=>{let g=F("output",o,s.length),b=g.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:b},{name:"delta",type:b}];return`\n ${h.registerUniforms(w).declareVariables(g)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${b}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:s,dataType:o}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:a})}},qs=e=>{let t=0,r=0,o=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],o=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],o=e.inputs[2].getFloat32Array()[0]),Gt.webgpu.validateInputContent&&tc(t,r,o),e.compute(rc(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var nc,oc,ac,ic,sc,uc,dc,lc,cc,pc,mc,Ys,fc,hc,gc,yc,bc,Zs,Qs,Xs=j(()=>{"use strict";$e();je();ve();nc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},oc=(e,t,r)=>{t.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let o=new Array(r).fill(1);return t.forEach((n,s)=>o[n]=e[s]),o},ac=(e,t,r,o,n,s)=>{let[u,l,a]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(u>0&&e.length>u&&e[u].dims.length>0)e[u].getFloat32Array().forEach(h=>s.push(h));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(l>0&&e.length>l&&e[l].dims.length>0){if(e[l].getFloat32Array().forEach(h=>o.push(h)),o.length!==0&&o.length!==p&&r>=18&&o.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");nc(o,t),t.axes.length>0&&oc(o,t.axes,p).forEach((h,g)=>o[g]=h)}if(a>0&&e.length>a&&(e[a].getBigInt64Array().forEach(h=>n.push(Number(h))),n.length!==p||r>=18&&n.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(o.length!==t.axes.length)throw new Error(\'Resize requires "scales" input size to be of axes rank when axes attributes is specified\');if(n.length!==t.axes.length)throw new Error(\'Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified\')}if(typeof o<"u"&&typeof n<"u"&&o.length>0&&n.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},ic=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",sc=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",uc=(e,t,r)=>{let o=new Array(r).fill(0).concat(new Array(r).fill(1)),n=e.length===0?o:e.slice();return t.length>0?(t.forEach((s,u)=>{o[s]=n[u],o[u+r]=n[t.length+u]}),o):n},dc=(e,t,r,o)=>{let n=[];if(r.length>0)if(o.length>0){if(e.forEach(s=>n.push(s)),Math.max(...o)>e.length)throw new Error("axes is out of bound");o.forEach((s,u)=>n[s]=r[u])}else r.forEach(s=>n.push(s));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((s,u)=>Math.round(s*t[u]))}return n},lc=(e,t,r)=>{let o=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(s=>t[s]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(s=>t[s]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let n=e.slice();return r.axes.length>0?(r.axes.forEach(s=>t[s]=o),r.axes.forEach(s=>n[s]=Math.round(e[s]*t[s]))):(t.fill(o,0,t.length),n.forEach((s,u)=>n[u]=Math.round(s*t[u]))),n},cc=(e,t,r,o,n)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${ce("uniforms.scales","i",o)};\n var roi_low = ${ce("uniforms.roi","i",n)};\n var roi_hi = ${ce("uniforms.roi",`i + ${t.length}`,n)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${ce("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${ce("uniforms.output_shape","i",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,pc=(e,t,r,o,n,s,u)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${o.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${ce("uniforms.scales","i",n)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${ce("uniforms.roi","i",s)};\n var roi_hi = ${ce("uniforms.roi",`i + ${r.length}`,s)};\n var input_shape_i = ${ce("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${ce("uniforms.output_shape","i",o.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${u} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,mc=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${ce("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Ys=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",fc=(e,t,r,o,n)=>{let[u,l,a,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(col, ${r[a]} - 1))`)};\n ${Ys(e,p,u,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${h} = originalIndices[${l}];\n var col:${h} = originalIndices[${a}];\n ${o?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[a]} - 1)) {\n return ${n};\n }`:""};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[a]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${u}])`:"0"};\n var x11: ${h} = getInputValue(batch, channel, row1, col1);\n var x12: ${h} = getInputValue(batch, channel, row1, col2);\n var x21: ${h} = getInputValue(batch, channel, row2, col1);\n var x22: ${h} = getInputValue(batch, channel, row2, col2);\n var dx1: ${h} = abs(row - ${h}(row1));\n var dx2: ${h} = abs(${h}(row2) - row);\n var dy1: ${h} = abs(col - ${h}(col1));\n var dy2: ${h} = abs(${h}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},hc=(e,t,r,o,n,s,u,l,a,p)=>{let h=r.length===2,g=!0,[b,w]=h?[0,1]:g?[2,3]:[1,2],y=e.type.value,_=I=>{let $=I===b?"row":"col";return`\n fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet("output_indices",I)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[I]},\n ${o[I]}, ${r[I]}, ${s[I]}, ${s[I]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[I]} - 1))) {\n return ${a};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${$}: ${y} = originalIdx + ${y}(i);\n if (${$} < 0 || ${$} >= ${r[I]}) {\n ${(()=>p?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${a};`:`${$} = max(0, min(${$}, ${r[I]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",I,`u32(${$})`)};\n data[i + 1] = ${I===b?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${_(b)};\n ${_(w)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};\n coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;\n coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${u} * twoMinusAbsS - 5 * ${u}) * twoMinusAbsS + 8 * ${u}) * twoMinusAbsS - 4 * ${u};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},gc=(e,t,r,o,n)=>{let[u,l,a,p,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(height, ${r[a]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)};\n ${Ys(e,h,u,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${g} = originalIndices[${l}];\n var height:${g} = originalIndices[${a}];\n var width:${g} = originalIndices[${p}];\n ${o?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[a]} - 1) || width < 0 || (width > ${r[p]} - 1)) {\n return ${n};\n }`:""};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[a]} - 1));\n width = max(0, min(width, ${r[p]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${h}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${u}])`:"0"};\n\n var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${g} = abs(depth - ${g}(depth1));\n var dx2: ${g} = abs(${g}(depth2) - depth);\n var dy1: ${g} = abs(height - ${g}(height1));\n var dy2: ${g} = abs(${g}(height2) - height);\n var dz1: ${g} = abs(width - ${g}(width1));\n var dz2: ${g} = abs(${g}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},yc=(e,t,r,o,n,s)=>{let u=e.dims,l=uc(s,t.axes,u.length),a=dc(u,o,n,t.axes),p=o.slice();o.length===0&&(p=u.map((x,E)=>x===0?1:a[E]/x),t.keepAspectRatioPolicy!=="stretch"&&(a=lc(u,p,t)));let h=F("output",e.dataType,a.length),g=M("input",e.dataType,u.length),b=U.size(a),w=u.length===a.length&&u.every((x,E)=>x===a[E]),y=t.coordinateTransformMode==="tf_crop_and_resize",_=t.extrapolationValue,I=g.type.value,$=x=>`\n ${w?"":`\n ${ic(t.coordinateTransformMode,I)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${mc(g,u)};\n ${sc(t.nearestMode,r,I)};\n ${pc(g,h,u,a,p.length,l.length,y)};\n `;case"linear":return`\n ${cc(h,u,a,p.length,l.length)};\n ${(()=>{if(u.length===2||u.length===4)return`${fc(g,h,u,y,_)}`;if(u.length===3||u.length===5)return`${gc(g,h,u,y,_)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(u.length===2||u.length===4)return`${hc(g,h,u,a,p,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${x.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",l.length).declareVariables(g,h)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${w?"output[global_idx] = input[global_idx];":`\n let output_indices = ${h.offsetToIndices("global_idx")};\n var input_indices: ${g.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${g.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${u.length===2||u.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${n.length>0?n:""}|${l.length>0?l:""}|${w}|${u}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:"uint32",data:b},{type:"float32",data:p},{type:"float32",data:l},...L(u),...L(a)]})}},bc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Zs=(e,t)=>{let r=[],o=[],n=[],s=bc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");ac(e.inputs,t,s,r,o,n),e.compute(yc(e.inputs[0],t,s,r,o,n),{inputs:[0]})},Qs=e=>{let t=e.antialias,r=e.axes,o=e.coordinateTransformMode,n=e.cubicCoeffA,s=e.excludeOutside!==0,u=e.extrapolationValue,l=e.keepAspectRatioPolicy,a=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return ge({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:n,excludeOutside:s,extrapolationValue:u,keepAspectRatioPolicy:l,mode:a,nearestMode:p})}});var wc,vc,Js,eu,tu=j(()=>{"use strict";Ne();$e();je();ve();wc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],o=e[2];if(t.dataType!==r.dataType||t.dataType!==o.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let n=t.dims[t.dims.length-1],s=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==s)throw new Error("Skip must have the same sequence length as input");if(o.dims.length!==1)throw new Error("Gamma must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let u=e[3];if(u.dims.length!==1)throw new Error("Beta must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let u=e[4];if(u.dims.length!==1)throw new Error("Bias must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},vc=(e,t,r,o)=>{let n=e[0].dims,s=U.size(n),u=n,l=s,a=n.slice(-1)[0],p=o?n.slice(0,-1).concat(1):[],h=e.length>3,g=e.length>4,b=o&&r>1,w=o&&r>2,y=r>3,_=Fe(a),I=[M("x",e[0].dataType,e[0].dims,_),M("skip",e[1].dataType,e[1].dims,_),M("gamma",e[2].dataType,e[2].dims,_)];h&&I.push(M("beta",e[3].dataType,e[3].dims,_)),g&&I.push(M("bias",e[4].dataType,e[4].dims,_)),I.push(F("output",e[0].dataType,u,_)),b&&I.push(F("meanOutput",1,p)),w&&I.push(F("invStdOutput",1,p)),y&&I.push(F("inputSkipBiasSum",e[0].dataType,u,_));let $=Le(e[0].dataType),x=A=>`\n const hiddenSize: f32 = ${a};\n const hiddenSizeVectorized: u32 = ${a/_};\n const epsilon: f32 = ${t.epsilon};\n\n ${A.declareVariables(...I)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes(l/a)}\n let offset = global_idx * hiddenSizeVectorized;\n var sum = ${Ze("f32",_)};\n var squareSum = ${Ze("f32",_)};\n for (var i: u32 = 0; i < hiddenSizeVectorized; i++) {\n let skipValue = skip[offset + i];\n let biasValue = ${g?"bias[i]":"0.0"};\n let inputValue = x[offset + i];\n let value = inputValue + skipValue + biasValue;\n ${y?"inputSkipBiasSum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32Value = ${at($,_,"value")};\n sum += f32Value;\n squareSum += f32Value * f32Value;\n }\n let mean = ${Je("sum",_)} / hiddenSize;\n let invStdDev = inverseSqrt(${Je("squareSum",_)} / hiddenSize - mean * mean + epsilon);\n ${b?"meanOutput[global_idx] = mean;":""}\n ${w?"invStdOutput[global_idx] = invStdDev;":""}\n for (var i: u32 = 0; i < hiddenSizeVectorized; i++) {\n output[offset + i] = (output[offset + i] - ${$}(mean)) * ${$}(invStdDev) * gamma[i]\n + ${h?"beta[i]":"0.0"};\n }\n }`,E=[{dims:u,dataType:e[0].dataType}];return r>1&&E.push({dims:p,dataType:1}),r>2&&E.push({dims:p,dataType:1}),r>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:t.cacheKey},getShaderSource:x,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/a/64)}})}},Js=(e,t)=>{wc(e.inputs);let o=[0];e.outputCount>1&&o.push(-3),e.outputCount>2&&o.push(-3),e.outputCount>3&&o.push(3),e.compute(vc(e.inputs,t,e.outputCount,!1),{outputs:o})},eu=e=>{let t=e.epsilon;return ge({epsilon:t})}});var $c,on,Sc,ru,xc,_c,nu,ou,au=j(()=>{"use strict";Ne();$e();je();ve();$c=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,o)=>{if(e[o+1].dataType!==6&&e[o+1].dataType!==7)throw new Error(`Input ${o} must be an array of int32 or int64`)})},on=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(o=>r.push(Number(o)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(o=>r.push(Number(o)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Sc=(e,t)=>{if(e.length>1){let r=on(e,1),o=on(e,2),n=on(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),ge({starts:r,ends:o,axes:n})}else return t},ru=(e,t,r,o,n)=>{let s=e;return e<0&&(s+=r[o[t]]),n[t]<0?Math.max(0,Math.min(s,r[o[t]]-1)):Math.max(0,Math.min(s,r[o[t]]))},xc=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${ce("uniforms.input_shape","i",r.length)};\n let steps_i = ${ce("uniforms.steps","i",r.length)};\n let signs_i = ${ce("uniforms.signs","i",r.length)};\n let starts_i = ${ce("uniforms.starts","i",r.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,_c=(e,t)=>{let r=e[0].dims,o=U.size(r),n=t.axes.length>0?U.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],s=on(e,4);s.forEach($=>$!==0||(()=>{throw new Error("step cannot be 0")})),s.length===0&&(s=Array(n.length).fill(1));let u=t.starts.map(($,x)=>ru($,x,r,n,s)),l=t.ends.map(($,x)=>ru($,x,r,n,s));if(n.length!==u.length||n.length!==l.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==r.length)for(let $=0;$Math.sign($));s.forEach(($,x,E)=>{if($<0){let A=(l[x]-u[x])/$,z=u[x],R=z+A*s[x];u[x]=R,l[x]=z,E[x]=-$}});let p=r.slice(0);n.forEach(($,x)=>{p[$]=Math.ceil((l[$]-u[$])/s[$])});let h={dims:p,dataType:e[0].dataType},g=F("output",e[0].dataType,p.length),b=M("input",e[0].dataType,e[0].dims.length),w=U.size(p),y=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:u.length},{name:"signs",type:"i32",length:a.length},{name:"steps",type:"u32",length:s.length}],_=[{type:"uint32",data:w},{type:"uint32",data:u},{type:"int32",data:a},{type:"uint32",data:s},...L(e[0].dims),...L(p)],I=$=>`\n ${$.registerUniforms(y).declareVariables(b,g)}\n ${xc(b,g,r)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${g.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${g.setByOffset("global_idx",b.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${a.length}_${u.length}_${s.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[h],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:_})}},nu=(e,t)=>{$c(e.inputs,t);let r=Sc(e.inputs,t);e.compute(_c(e.inputs,r),{inputs:[0]})},ou=e=>{let t=e.starts,r=e.ends,o=e.axes;return ge({starts:t,ends:r,axes:o})}});var Cc,Ic,iu,su,uu=j(()=>{"use strict";$e();je();ve();Cc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Ic=(e,t)=>{let r=e.dims,o=U.size(r),n=64,s=t.axis;if(s<0&&(s=r.length+s),s$===4?`max(max(${I}.x, ${I}.y), max(${I}.z, ${I}.w))`:$===2?`max(${I}.x, ${I}.y)`:$===3?`max(max(${I}.x, ${I}.y), ${I}.z)`:I,g=M("x",e.dataType,e.dims,a),b=F("result",e.dataType,e.dims,a),w=g.type.value,y=Le(e.dataType)==="f32"?`var threadMax = ${w}(-3.402823e+38f);`:`var threadMax = ${w}(-65504.0h);`,_=I=>`\n var rowMaxShared : ${w};\n var rowSumShared : ${w};\n var threadShared : array<${w}, ${n}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${w} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${w}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${I.registerUniform("packedCols","i32").declareVariables(g,b)}\n ${I.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${n};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${y}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${w}(${h("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${w}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${w}(${Je("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`;return{name:"Softmax",shaderCache:{hint:`${a}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:l},programUniforms:[{type:"uint32",data:p}]}),getShaderSource:_}},iu=(e,t)=>{Cc(e.inputs),e.compute(Ic(e.inputs[0],t))},su=e=>ge({axis:e.axis})});var Ac,Tc,Ec,Oc,Pc,du,lu,cu=j(()=>{"use strict";$e();je();ve();Ac=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Tc=(e,t)=>{let r=[],o=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),o=r.length),ge({numOutputs:o,axis:t.axis,splitSizes:r})},Ec=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${ce("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Oc=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=U.size(r),n=e[0].dataType,s=U.normalizeAxis(t.axis,r.length),u=new Array(t.numOutputs),l=M("input",n,r),a=new Array(t.numOutputs),p=[],h=[],g=0,b=[{type:"uint32",data:o}];for(let y=0;yb.push(...L(y)));let w=y=>`\n ${y.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",a.length).declareVariables(l,...u)}\n ${Ec(a.length)}\n ${Oc(u)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${l.offsetToIndices("global_idx")};\n var index = ${l.indicesGet("indices",s)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${ce("uniforms.size_in_split_axis","output_number - 1u",a.length)};\n ${l.indicesSet("indices",s,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:b})}},du=(e,t)=>{Ac(e.inputs);let r=e.inputs.length===1?t:Tc(e.inputs,t);e.compute(Pc(e.inputs,r),{inputs:[0]})},lu=e=>{let t=e.axis,r=e.splitSizes,o=e.numOutputs<0?r.length:e.numOutputs;if(o!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ge({axis:t,numOutputs:o,splitSizes:r})}});var pu,kc,Rc,Bc,mu,fu=j(()=>{"use strict";Ne();$e();ve();pu=e=>Array.from(e.getBigInt64Array(),Number),kc=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(pu(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Rc=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=pu(e[1]),o=Rc(t,r),n=U.size(o),s=e[0].dataType,u=M("input",s,t.length),l=F("output",s,o.length),a=p=>`\n const inputShape = ${u.indices(...t)};\n ${p.registerUniform("output_size","u32").declareVariables(u,l)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${l.offsetToIndices("global_idx")};\n var input_indices: ${u.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i;\n\n ${u.indicesSet("input_indices","i","input_dim_value")}\n }\n ${l.setByOffset("global_idx",u.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:"uint32",data:n},...L(e[0].dims),...L(o)]}),getShaderSource:a}},mu=e=>{kc(e.inputs),e.compute(Bc(e.inputs),{inputs:[0]})}});var Dc,Mc,hu,gu=j(()=>{"use strict";Ne();$e();ve();Dc=(e,t,r,o,n)=>{let s=F("output_data",n,r.length,4),u=M("a_data",t[1].dataType,t[1].dims.length,4),l=M("b_data",t[2].dataType,t[2].dims.length,4),a=M("c_data",t[0].dataType,t[0].dims.length,4),p,h=(g,b,w)=>`select(${b}, ${g}, ${w})`;if(!o)p=s.setByOffset("global_idx",h(u.getByOffset("global_idx"),l.getByOffset("global_idx"),a.getByOffset("global_idx")));else{let g=(b,w,y="")=>{let _=`a_data[index_a${w}][component_a${w}]`,I=`b_data[index_b${w}][component_b${w}]`,$=`bool(c_data[index_c${w}] & ${4278190080>>>(3-w)*8}u)`;return`\n let output_indices${w} = ${s.offsetToIndices(`global_idx * 4u + ${w}u`)};\n let offset_a${w} = ${u.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let offset_b${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let offset_c${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let index_a${w} = offset_a${w} / 4u;\n let index_b${w} = offset_b${w} / 4u;\n let index_c${w} = offset_c${w} / 4u;\n let component_a${w} = offset_a${w} % 4u;\n let component_b${w} = offset_b${w} % 4u;\n ${b}[${w}] = ${y}(${h(_,I,$)});\n `};n===9?p=`\n var data = vec4(0);\n ${g("data",0,"u32")}\n ${g("data",1,"u32")}\n ${g("data",2,"u32")}\n ${g("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=`\n ${g("output_data[global_idx]",0)}\n ${g("output_data[global_idx]",1)}\n ${g("output_data[global_idx]",2)}\n ${g("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,u,l,s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${p}\n }`},Mc=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,n=e[1].dataType,s=!(U.areEqual(t,r)&&U.areEqual(r,o)),u=t,l=U.size(t);if(s){let p=dt.calcShape(dt.calcShape(t,r,!1),o,!1);if(!p)throw new Error("Can\'t perform where op on the given tensors");u=p,l=U.size(u)}let a=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Dc(p,e,u,s,n),getRunData:()=>({outputs:[{dims:u,dataType:n}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:"uint32",data:a},...L(o),...L(t),...L(r),...L(u)]})}},hu=e=>{e.compute(Mc(e.inputs))}});var yu,bu=j(()=>{"use strict";Wa();Un();La();ja();Ci();Mi();Vi();Gn();Ji();rs();ss();ls();ms();gs();ws();$s();xs();Fn();As();Es();js();Ks();jr();Xs();tu();au();uu();cu();fu();jt();Vn();gu();yu=new Map([["Abs",[qa]],["Acos",[Ka]],["Acosh",[Ya]],["Add",[Ii]],["ArgMax",[Na,zn]],["ArgMin",[Va,zn]],["Asin",[Za]],["Asinh",[Qa]],["Atan",[Xa]],["Atanh",[Ja]],["Attention",[Ha]],["AveragePool",[zs,Ms]],["BatchNormalization",[Ga]],["BiasAdd",[Fa]],["BiasSplitGelu",[_i]],["Cast",[ti,ei]],["Ceil",[ni]],["Clip",[ri]],["Concat",[zi,Ui]],["Conv",[qn,jn]],["ConvTranspose",[Xi,Qi]],["Cos",[oi]],["Cosh",[ai]],["CumSum",[es,ts]],["Div",[Ai]],["Einsum",[as,is]],["Elu",[ii,Yr]],["Equal",[Ti]],["Erf",[si]],["Exp",[ui]],["Expand",[ds]],["Floor",[di]],["FusedConv",[qn,jn]],["Gather",[ps,cs]],["GatherElements",[hs,fs]],["Gelu",[li]],["Gemm",[bs,ys]],["GlobalAveragePool",[Ns,Vs]],["GlobalMaxPool",[Fs,Ls]],["Greater",[ki]],["GreaterOrEqual",[Bi]],["InstanceNormalization",[vs]],["LayerNormalization",[Ss]],["LeakyRelu",[ci,Yr]],["Less",[Ri]],["LessOrEqual",[Di]],["Log",[xi]],["MatMul",[Li]],["MaxPool",[Hs,Gs]],["Mul",[Ei]],["MultiHeadAttention",[Is,Cs]],["Neg",[mi]],["Not",[pi]],["Pad",[Ts]],["Pow",[Oi]],["Range",[qs]],["Reciprocal",[fi]],["ReduceMin",[Ra]],["ReduceMean",[Ta]],["ReduceMax",[ka]],["ReduceSum",[Da]],["ReduceProd",[Ba]],["ReduceL1",[Ea]],["ReduceL2",[Oa]],["ReduceLogSum",[za]],["ReduceLogSumExp",[Pa]],["ReduceSumSquare",[Ma]],["Relu",[hi]],["Resize",[Zs,Qs]],["Sigmoid",[gi]],["Sin",[yi]],["Sinh",[bi]],["Slice",[nu,ou]],["SkipLayerNormalization",[Js,eu]],["Split",[du,lu]],["Sqrt",[wi]],["Softmax",[iu,su]],["Sub",[Pi]],["Tan",[vi]],["Tanh",[$i]],["ThresholdedRelu",[Si,Yr]],["Tile",[mu]],["Transpose",[ha,ga]],["Where",[hu]]])});var an,wu=j(()=>{"use strict";Lt();Ct();ve();an=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,o,n,s){kt(t.programInfo.name);let u=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2),l.setPipeline(t.computePipeline);let a=[];for(let h of r)a.push({binding:a.length,resource:{buffer:h.buffer}});for(let h of o)a.push({binding:a.length,resource:{buffer:h.buffer}});s&&a.push({binding:a.length,resource:s});let p=u.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:a,label:t.programInfo.name});l.setBindGroup(0,p),l.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Rt(t.programInfo.name)}dispose(){}build(t,r){kt(t.name);let o=this.backend.device,n=[];o.features.has("shader-f16")&&n.push("enable f16;");let s=ma(r),u=t.getShaderSource(s),l=`${n.join(`\n`)}\n${s.additionalImplementations}\n${u}`,a=o.createShaderModule({code:l,label:t.name});Be("verbose",()=>`[WebGPU] ${t.name} shader code: ${l}`);let p=o.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:t.name});return Rt(t.name),{programInfo:t,computePipeline:p}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,o=typeof t=="number"?1:t.y||1,n=typeof t=="number"?1:t.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=s&&o<=s&&n<=s)return[r,o,n];let u=r*o*n,l=Math.ceil(Math.sqrt(u));if(l>s){if(l=Math.ceil(Math.cbrt(u)),l>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}});var zc,Uc,sn,vu=j(()=>{"use strict";Lt();Ne();Ct();ua();pa();bu();wu();zc=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let o=0;o{let o=e.name;return e.shaderCache?.hint&&(o+="["+e.shaderCache.hint+"]"),o+=":"+r+`:${zc(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},sn=class{constructor(){this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let o=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:o};r.features.has("chromium-experimental-timestamp-query-inside-passes")?o.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&o.push("timestamp-query"),r.features.has("shader-f16")&&o.push("shader-f16"),this.device=await r.requestDevice(n),this.gpuDataManager=ca(this),this.programManager=new an(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ia(t.logLevel,!!t.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder(),this.setQueryType(),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE}))),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=this.getCommandEncoder().beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;kt(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),o=this.pendingQueries.get(t);for(let n=0;n"u"&&(this.queryTimeBase=w);let _=Number(w-this.queryTimeBase),I=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(I))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map($=>({dims:$.dims,dataType:Xe($.dataType)})),outputsMetadata:b.map($=>({dims:$.dims,dataType:Xe($.dataType)})),kernelId:u,kernelType:a,kernelName:p,programName:h,startTime:_,endTime:I});else{let $="";g.forEach((E,A)=>{$+=`input[${A}]: [${E.dims}] | ${Xe(E.dataType)}, `});let x="";b.forEach((E,A)=>{x+=`output[${A}]: [${E.dims}] | ${Xe(E.dataType)}, `}),console.log(`[profiling] kernel "${u}|${a}|${p}|${h}" ${$}${x}execution time: ${I-_} ns`)}An("GPU",`${h}::${w}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Rt()}run(t,r,o,n,s){kt(t.name);let u=[];for(let x=0;xE):o;if(h.length!==l.length)throw new Error(`Output size ${h.length} must be equal to ${l.length}.`);let g=[],b=[];for(let x=0;x=l.length)throw new Error(`Invalid output index: ${h[x]}`);if(h[x]===-3)continue;let E=h[x]===-1,A=h[x]===-2,z=E||A?s(l[x].dataType,l[x].dims):n(h[x],l[x].dataType,l[x].dims),R=this.gpuDataManager.get(z.data);if(!R)throw new Error(`no GPU data for output: ${z.data}`);if(E&&this.temporaryData.push(R),A){let V=this.kernelPersistentData.get(this.currentKernelId);V||(V=[],this.kernelPersistentData.set(this.currentKernelId,V)),V.push(R)}g.push(z),b.push(R)}let w;if(p){let x=0,E=[];p.forEach(V=>{let T=typeof V.data=="number"?[V.data]:V.data;if(T.length===0)return;let N=T.length<=2?T.length*4:16;x=Math.ceil(x/N)*N,E.push(x),x+=T.length>4?Math.ceil(T.length/4)*16:T.length*4});let A=16;x=Math.ceil(x/A)*A;let z=new ArrayBuffer(x);p.forEach((V,T)=>{let N=E[T],te=typeof V.data=="number"?[V.data]:V.data;V.type==="int32"?new Int32Array(z,N,te.length).set(te):V.type==="uint32"?new Uint32Array(z,N,te.length).set(te):new Float32Array(z,N,te.length).set(te)});let R=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(R.buffer,0,z,0,x),this.gpuDataManager.release(R.id),w={offset:0,size:x,buffer:R.buffer}}let y=this.programManager.normalizeDispatchGroupSize(a),_=y[1]===1&&y[2]===1,I=Uc(t,r,_),$=this.programManager.getArtifact(I);if($||($=this.programManager.build(t,y),this.programManager.setArtifact(I,$),Be("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),Be("info",()=>`[ProgramManager] run "${t.name}" (key=${I}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"){let x={kernelId:this.currentKernelId,programName:$.programInfo.name,inputTensorViews:r,outputTensorViews:g};this.pendingKernels.push(x)}return this.programManager.run($,u,b,y,w),Rt(t.name),g}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,o,n){let s=yu.get(t);if(!s)throw new Error(`kernel not implemented: ${t}`);let u={kernelType:t,kernelName:n,kernelEntry:s[0],attributes:[s[1],o]};this.kernels.set(r,u)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let o of r)this.gpuDataManager.release(o.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,o){let n=this.kernels.get(t);if(!n)throw new Error(`kernel not created: ${t}`);let s=n.kernelType,u=n.kernelName,l=n.kernelEntry,a=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${u}" is not allowed to be called recursively`);this.currentKernelId=t,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Be("info",()=>`[WebGPU] Start to run kernel "[${s}] ${u}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),l(r,a[1]),0}catch(h){return o.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${u}" failed. ${h}`)),1}finally{p&&o.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${s}] ${u}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,o,n){let s=this.sessionExternalDataMapping.get(t);s||(s=new Map,this.sessionExternalDataMapping.set(t,s));let u=s.get(r),l=this.gpuDataManager.registerExternalBuffer(o,n,u?.[1]);return s.set(r,[l,o]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(o=>this.gpuDataManager.unregisterExternalBuffer(o[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,o){return async()=>{let n=await On(this,t,r);return sa(n.buffer,o)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||this.env.wasm.trace)&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"))}}});var $u={};Br($u,{init:()=>Vc});var gr,Jn,Vc,Su=j(()=>{"use strict";Ne();vu();Ct();$e();gr=class e{constructor(t,r,o,n){this.module=t;this.dataType=r;this.data=o;this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=U.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=U.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=U.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(U.size(t)!==U.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Jn=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;let n=t.HEAPU32,s=o>>>2;this.opKernelContext=n[s++];let u=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let l=[];for(let a=0;atypeof l=="number"?this.inputs[l]:l)??this.inputs,n=r?.outputs??[],s=(l,a,p)=>new gr(this.module,a,this.output(l,p),p),u=(l,a)=>{let p=cr(l);if(!p)throw new Error(`Unsupported data type: ${l}`);let h=p*U.size(a);return new gr(this.module,l,this.backend.gpuDataManager.create(h).id,a)};return this.backend.run(t,o,n,s,u)}output(t,r){let o=this.module.stackSave();try{let n=this.module.stackAlloc((1+r.length)*4),s=n>>2;this.module.HEAPU32[s++]=r.length;for(let u=0;u{let o=e.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");let n=new sn;await n.initialize(t,r),o(n,s=>n.alloc(s),s=>n.free(s),(s,u,l,a=!1)=>{if(a)Be("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${u}, size=${l}`),n.memcpy(s,u);else{Be("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${u}, size=${l}`);let p=e.HEAPU8.subarray(s>>>0,(s>>>0)+l);n.upload(u,p)}},async(s,u,l)=>{Be("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${u}, size=${l}`),await n.download(s,()=>e.HEAPU8.subarray(u>>>0,(u>>>0)+l))},(s,u,l)=>n.createKernel(s,u,l,e.UTF8ToString(e._JsepGetNodeName(u))),s=>n.releaseKernel(s),(s,u,l,a)=>{Be("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${s}, contextDataOffset=${u}`);let p=new Jn(e,n,u);return n.computeKernel(s,p,a)})}});var Mo;Mo=Io();var Ju=Ro(),Sn,xn=!1,Dr=!1,Do=!1,ed=e=>{if(e===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},td=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},rd=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",zo=async e=>{if(xn)return Promise.resolve();if(Dr)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Do)throw new Error("previous call to \'initializeWebAssembly()\' failed.");Dr=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,n=ed(r),s=o&&td(),u=e.wasmPaths,l=typeof u=="string"?u:void 0,a=rd(s,n),p=typeof u=="object"?u[a]:void 0,h=!1,g=[];if(t>0&&g.push(new Promise(b=>{setTimeout(()=>{h=!0,b()},t)})),g.push(new Promise((b,w)=>{let y=n?Ju:Mo,_={locateFile:(I,$)=>{if(n&&I.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Bo()],{type:"text/javascript"}));if(I.endsWith(".wasm")){if(p)return p;let x=l??$;return a==="ort-wasm-simd.wasm"?x+"ort-wasm-simd.jsep.wasm":a==="ort-wasm-simd-threaded.wasm"?x+"ort-wasm-simd-threaded.jsep.wasm":x+a}return $+I}};if(n)if(_.numThreads=r,typeof Blob>"u")_.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let I=`var ortWasmThreaded=${y.toString()};`;_.mainScriptUrlOrBlob=new Blob([I],{type:"text/javascript"})}y(_).then(I=>{Dr=!1,xn=!0,Sn=I,b()},I=>{Dr=!1,Do=!0,w(I)})})),await Promise.race(g),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ve=()=>{if(xn&&Sn)return Sn;throw new Error("WebAssembly is not initialized yet.")};var He=(e,t)=>{let r=Ve(),o=r.lengthBytesUTF8(e)+1,n=r._malloc(o);return r.stringToUTF8(e,n,o),t.push(n),n},lr=(e,t,r,o)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,s])=>{let u=t?t+n:n;if(typeof s=="object")lr(s,u+".",r,o);else if(typeof s=="string"||typeof s=="number")o(u,s.toString());else if(typeof s=="boolean")o(u,s?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof s}`)})},ke=e=>{let t=Ve(),r=t.stackSave();try{let o=t.stackAlloc(8);t._OrtGetLastError(o,o+4);let n=t.HEAP32[o/4],s=t.HEAPU32[o/4+1],u=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}};var Uo=e=>{let t=Ve(),r=0,o=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let s=0;return e?.tag!==void 0&&(s=He(e.tag,o)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&ke("Can\'t create run options."),e?.extra!==void 0&&lr(e.extra,"",new WeakSet,(u,l)=>{let a=He(u,o),p=He(l,o);t._OrtAddRunConfigEntry(r,a,p)!==0&&ke(`Can\'t set a run config entry: ${u} - ${l}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(u=>t._free(u)),s}};var nd=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},od=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ad=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},id=(e,t,r)=>{for(let o of t){let n=typeof o=="string"?o:o.name;switch(n){case"webnn":if(n="WEBNN",typeof o!="string"){let u=o;if(u?.deviceType){let l=He("deviceType",r),a=He(u.deviceType,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`Can\'t set a session config entry: \'deviceType\' - ${u.deviceType}.`)}if(u?.numThreads){let l=u.numThreads;(typeof l!="number"||!Number.isInteger(l)||l<0)&&(l=0);let a=He("numThreads",r),p=He(l.toString(),r);Ve()._OrtAddSessionConfigEntry(e,a,p)!==0&&ke(`Can\'t set a session config entry: \'numThreads\' - ${u.numThreads}.`)}if(u?.powerPreference){let l=He("powerPreference",r),a=He(u.powerPreference,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`Can\'t set a session config entry: \'powerPreference\' - ${u.powerPreference}.`)}}break;case"webgpu":if(n="JS",typeof o!="string"){let u=o;if(u?.preferredLayout){if(u.preferredLayout!=="NCHW"&&u.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${u.preferredLayout}`);let l=He("preferredLayout",r),a=He(u.preferredLayout,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`Can\'t set a session config entry: \'preferredLayout\' - ${u.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let s=He(n,r);Ve()._OrtAppendExecutionProvider(e,s)!==0&&ke(`Can\'t append execution provider: ${n}.`)}},Vo=e=>{let t=Ve(),r=0,o=[],n=e||{};ad(n);try{let s=nd(n.graphOptimizationLevel??"all"),u=od(n.executionMode??"sequential"),l=typeof n.logId=="string"?He(n.logId,o):0,a=n.logSeverityLevel??2;if(!Number.isInteger(a)||a<0||a>4)throw new Error(`log serverity level is not valid: ${a}`);let p=n.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let h=typeof n.optimizedModelFilePath=="string"?He(n.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,u,!!n.enableProfiling,0,l,a,p,h),r===0&&ke("Can\'t create session options."),n.executionProviders&&id(r,n.executionProviders,o),n.freeDimensionOverrides)for(let[g,b]of Object.entries(n.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof b!="number"||!Number.isInteger(b)||b<0)throw new Error(`free dimension override value must be a non-negative integer: ${b}`);let w=He(g,o);t._OrtAddFreeDimensionOverride(r,w,b)!==0&&ke(`Can\'t set a free dimension override: ${g} - ${b}.`)}return n.extra!==void 0&&lr(n.extra,"",new WeakSet,(g,b)=>{let w=He(g,o),y=He(b,o);t._OrtAddSessionConfigEntry(r,w,y)!==0&&ke(`Can\'t set a session config entry: ${g} - ${b}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(u=>t._free(u)),s}};Ne();var Wo=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(e),o=[];for await(let n of r)o.push(n);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),o=r?parseInt(r,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),s;try{s=new ArrayBuffer(o)}catch(l){if(l instanceof RangeError){let a=Math.ceil(o/65536);s=new WebAssembly.Memory({initial:a,maximum:a}).buffer}else throw l}let u=0;for(;;){let{done:l,value:a}=await n.read();if(l)break;let p=a.byteLength;new Uint8Array(s,u,p).set(a),u+=p}return new Uint8Array(s,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var Nc=(e,t)=>{Ve()._OrtInit(e,t)!==0&&ke("Can\'t initialize onnxruntime.")},_u=async e=>{Nc(e.wasm.numThreads,pr(e.logLevel))},Cu=async(e,t)=>{if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let r=await navigator.gpu.requestAdapter();if(!r)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\');if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");let o=(Su(),Ht($u)).init;await o(Ve(),e,r)}},yr=new Map,Wc=e=>{let t=Ve(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&ke("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},eo=e=>{let t=Ve(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Iu=async(e,t)=>{let r,o,n=Ve();Array.isArray(e)?[r,o]=e:e.buffer===n.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=eo(e);let s=0,u=0,l=0,a=[],p=[],h=[];try{if([u,a]=Vo(t),t?.externalData&&n.mountExternalData){let $=[];for(let x of t.externalData){let E=typeof x=="string"?x:x.path;$.push(Wo(typeof x=="string"?x:x.data).then(A=>{n.mountExternalData(E,A)}))}await Promise.all($)}s=n._OrtCreateSession(r,o,u),s===0&&ke("Can\'t create a session.");let[g,b]=Wc(s),w=[],y=[],_=[];for(let $=0;$$==="gpu-buffer")&&(l=n._OrtCreateBinding(s),l===0&&ke("Can\'t create IO binding."),I={handle:l,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map($=>Cn($))}),yr.set(s,[s,p,h,I]),[s,w,y]}catch(g){throw p.forEach(b=>n._OrtFree(b)),h.forEach(b=>n._OrtFree(b)),l!==0&&n._OrtReleaseBinding(l),s!==0&&n._OrtReleaseSession(s),g}finally{n._free(r),u!==0&&n._OrtReleaseSessionOptions(u),a.forEach(g=>n._free(g)),n.unmountExternalData?.()}},Au=e=>{let t=Ve(),r=yr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,n,s,u]=r;u&&t._OrtReleaseBinding(u.handle),t.jsepUnregisterBuffers?.(e),n.forEach(l=>t._OrtFree(l)),s.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(o),yr.delete(e)},xu=(e,t,r,o,n)=>{if(!e){t.push(0);return}let s=Ve(),u=e[0],l=e[1],a=e[3],p,h;if(u==="string"&&a==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a==="gpu-buffer"){let w=e[2].gpuBuffer,y=cr(_n(u));h=l.reduce((_,I)=>_*I,1)*y,p=s.jsepRegisterBuffer(o,n,w,h)}else{let w=e[2];if(Array.isArray(w)){h=4*w.length,p=s._malloc(h),r.push(p);let y=p/4;for(let _=0;_s.HEAP32[w++]=_);let y=s._OrtCreateTensor(_n(u),p,h,b,l.length,Cn(a));y===0&&ke(`Can\'t create tensor for input/output. session=${o}, index=${n}.`),t.push(y)}finally{s.stackRestore(g)}},Tu=async(e,t,r,o,n,s)=>{let u=Ve(),l=yr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let[a,p,h,g]=l,b=t.length,w=o.length,y=0,_=[],I=[],$=[],x=[],E=u.stackSave(),A=u.stackAlloc(b*4),z=u.stackAlloc(b*4),R=u.stackAlloc(w*4),V=u.stackAlloc(w*4);try{[y,_]=Uo(s);for(let Z=0;ZUe*Me,1);he=Xe(Ge);let ze=g?.outputPreferredLocations[o[Z]];if(he==="string"){if(ze==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ue=[],Me=ye/4;for(let wt=0;wt0){let Ue=u.jsepGetBuffer(ye),Me=cr(Ge);if(Me===void 0||!No(he))throw new Error(`Unsupported data type: ${he}`);Ie=!0,Q.push([he,be,{gpuBuffer:Ue,download:u.jsepCreateDownloader(Ue,et*Me,he),dispose:()=>{u._OrtReleaseTensor(Ee)}},"gpu-buffer"])}else{let Ue=Mr(he),Me=new Ue(et);new Uint8Array(Me.buffer,Me.byteOffset,Me.byteLength).set(u.HEAPU8.subarray(ye,ye+Me.byteLength)),Q.push([he,be,Me,"cpu"])}}finally{u.stackRestore(Pe),he==="string"&&ye&&u._free(ye),Ie||u._OrtReleaseTensor(Ee)}}return g&&u._OrtClearBoundOutputs(g.handle),Q}finally{u.stackRestore(E),I.forEach(T=>u._OrtReleaseTensor(T)),$.forEach(T=>u._OrtReleaseTensor(T)),x.forEach(T=>u._free(T)),y!==0&&u._OrtReleaseRunOptions(y),_.forEach(T=>u._free(T))}},Eu=e=>{let t=Ve(),r=yr.get(e);if(!r)throw new Error("invalid session id");let o=r[0],n=t._OrtEndProfiling(o);n===0&&ke("Can\'t get an profile file name."),t._OrtFree(n)},Ou=e=>{let t=[];for(let r of e){let o=r[2];!Array.isArray(o)&&"buffer"in o&&t.push(o.buffer)}return t};self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":zo(r.wasm).then(()=>{_u(r).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=r;Cu(n,o).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})});break}case"copy-from":{let{buffer:o}=r,n=eo(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=r;Iu(o,n).then(s=>{postMessage({type:t,out:s})},s=>{postMessage({type:t,err:s})});break}case"release":Au(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:s,outputIndices:u,options:l}=r;Tu(o,n,s,u,new Array(u.length).fill(null),l).then(a=>{a.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:a},Ou(a))},a=>{postMessage({type:t,err:a})});break}case"end-profiling":Eu(r),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}};})();\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n'}),Ct,et,Kt,_r,xr,Jn,tn,Mt,Dt,Yo,Sr,np,ap,ip,sp,op,up,lp,dp=H(()=>{lt(),Mc(),Ar(),Ct=()=>!!Oe.wasm.proxy&&typeof document<"u",Kt=!1,_r=!1,xr=!1,tn=new Map,Mt=(e,t)=>{let r=tn.get(e);r?r.push(t):tn.set(e,[t])},Dt=()=>{if(Kt||!_r||xr||!et)throw new Error("worker not ready")},Yo=e=>{switch(e.data.type){case"init-wasm":Kt=!1,e.data.err?(xr=!0,Jn[1](e.data.err)):(_r=!0,Jn[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=tn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Sr=typeof document<"u"?document?.currentScript?.src:void 0,np=async()=>{if(!_r){if(Kt)throw new Error("multiple calls to 'initWasm()' detected.");if(xr)throw new Error("previous call to 'initWasm()' failed.");if(Kt=!0,Ct())return Oe.wasm.wasmPaths===void 0&&Sr&&Sr.indexOf("blob:")!==0&&(Oe.wasm.wasmPaths=Sr.substr(0,+Sr.lastIndexOf("/")+1)),new Promise((e,t)=>{et?.terminate();let r=URL.createObjectURL(new Blob([Dc()],{type:"text/javascript"}));et=new Worker(r,{name:"ort-wasm-proxy-worker"}),et.onerror=i=>t(i),et.onmessage=Yo,URL.revokeObjectURL(r),Jn=[e,t];let a={type:"init-wasm",in:Oe};et.postMessage(a)});try{await Eu(Oe.wasm),await Zd(Oe),_r=!0}catch(e){throw xr=!0,e}finally{Kt=!1}}},ap=async e=>{if(Ct())return Dt(),new Promise((t,r)=>{Mt("init-ep",[t,r]);let a={type:"init-ep",in:{epName:e,env:Oe}};et.postMessage(a)});await Xd(Oe,e)},ip=async e=>Ct()?(Dt(),new Promise((t,r)=>{Mt("copy-from",[t,r]);let a={type:"copy-from",in:{buffer:e}};et.postMessage(a,[e.buffer])})):ca(e),sp=async(e,t)=>{if(Ct()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Dt(),new Promise((r,a)=>{Mt("create",[r,a]);let i={type:"create",in:{model:e,options:t}},n=[];e instanceof Uint8Array&&n.push(e.buffer),et.postMessage(i,n)})}else return Qd(e,t)},op=async e=>{if(Ct())return Dt(),new Promise((t,r)=>{Mt("release",[t,r]);let a={type:"release",in:e};et.postMessage(a)});Jd(e)},up=async(e,t,r,a,i,n)=>{if(Ct()){if(r.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return Dt(),new Promise((s,u)=>{Mt("run",[s,u]);let d=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:a,options:n}};et.postMessage(c,rp(d))})}else return ep(e,t,r,a,i,n)},lp=async e=>{if(Ct())return Dt(),new Promise((t,r)=>{Mt("end-profiling",[t,r]);let a={type:"end-profiling",in:e};et.postMessage(a)});tp(e)}}),ea,Zo,pp,Pc=H(()=>{lt(),dp(),De(),Tu(),ea=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Zo=e=>{switch(e[3]){case"cpu":return new Ke(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!_a(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:a,dispose:i}=e[2];return Ke.fromGpuBuffer(r,{dataType:t,dims:e[1],download:a,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},pp=class{async fetchModelAndCopyToWasmMemory(e){return ip(await pn(e))}async loadModel(e,t){mt();let r;typeof e=="string"?typeof process<"u"&&process.versions&&process.versions.node?r=await pn(e):r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await sp(r,t),gt()}async dispose(){return op(this.sessionId)}async run(e,t,r){mt();let a=[],i=[];Object.entries(e).forEach(l=>{let f=l[0],y=l[1],$=this.inputNames.indexOf(f);if($===-1)throw new Error(`invalid input '${f}'`);a.push(y),i.push($)});let n=[],s=[];Object.entries(t).forEach(l=>{let f=l[0],y=l[1],$=this.outputNames.indexOf(f);if($===-1)throw new Error(`invalid output '${f}'`);n.push(y),s.push($)});let u=a.map((l,f)=>ea(l,()=>`input "${this.inputNames[i[f]]}"`)),d=n.map((l,f)=>l?ea(l,()=>`output "${this.outputNames[s[f]]}"`):null),c=await up(this.sessionId,i,u,s,d,r),m={};for(let l=0;l{lt(),dp(),Pc(),Xo=()=>{if((typeof Oe.wasm.initTimeout!="number"||Oe.wasm.initTimeout<0)&&(Oe.wasm.initTimeout=0),typeof Oe.wasm.simd!="boolean"&&(Oe.wasm.simd=!0),typeof Oe.wasm.proxy!="boolean"&&(Oe.wasm.proxy=!1),typeof Oe.wasm.trace!="boolean"&&(Oe.wasm.trace=!1),typeof Oe.wasm.numThreads!="number"||!Number.isInteger(Oe.wasm.numThreads)||Oe.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Oe.wasm.numThreads=1);let e=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Oe.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},cp=class{async init(e){Xo(),await np(),await ap(e)}async createInferenceSessionHandler(e,t){let r=new pp;return await r.loadModel(e,t),Promise.resolve(r)}}}),hp={};Qt(hp,{wasmBackend:()=>fp});var fp,Wc=H(()=>{Nc(),fp=new cp});lt();lt();lt();var Uc="1.17.1",Vc=gu;{let e=(Wc(),Pt(hp)).wasmBackend;Ir("webgpu",e,5),Ir("cpu",e,10),Ir("wasm",e,10)}Object.defineProperty(Oe.versions,"web",{value:Uc,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. + * ============================================================================= + */export{cu as InferenceSession,on as TRACE,mt as TRACE_FUNC_BEGIN,gt as TRACE_FUNC_END,Ke as Tensor,mu as TrainingSession,Vc as default,Oe as env,Ir as registerBackend}; diff --git a/index.html b/index.html index b0c4b3666032a737f3903db53e6a8a9272483e28..84306acb078b5fa8a7966a48c2adeee0f27795bb 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,53 @@ - - - - - - My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- - + + + + + + + Transformers.js | WebGPU Benchmark + + + + + +

+ 🤗 Transformers.js WebGPU Benchmark +

+

+ This benchmark measures the execution time of Xenova/all-MiniLM-L6-v2 (bert-based embedding model) + using the WASM and WebGPU execution providers across different batch sizes. +

+
+ +
+
+ + +
+ +
+ + Options + +
+ + +
+
+ + +
+
+ + + + + +
+
+ + + + + \ No newline at end of file diff --git a/ort-training-wasm-simd.wasm b/ort-training-wasm-simd.wasm new file mode 100644 index 0000000000000000000000000000000000000000..840559fa1b06eb8a21f3f8f4c138d53519c63a67 --- /dev/null +++ b/ort-training-wasm-simd.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17a47dfb0e0c62a92ceaea1d538ecc5d5bdca2e29fc79a1a4523cd52d639c953 +size 11270629 diff --git a/ort-wasm-simd-threaded.jsep.wasm b/ort-wasm-simd-threaded.jsep.wasm new file mode 100644 index 0000000000000000000000000000000000000000..bcdc47c5ca6c68f02d5a246b6bcc4196aca1bd4f --- /dev/null +++ b/ort-wasm-simd-threaded.jsep.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b081048a1c9973a0e054d9966a23c1925be414235b0507b2ac612136b67b6c8d +size 19514999 diff --git a/ort-wasm-simd-threaded.wasm b/ort-wasm-simd-threaded.wasm new file mode 100644 index 0000000000000000000000000000000000000000..e9e813d404c1fa7961db86f56f0dc9f612f1120a --- /dev/null +++ b/ort-wasm-simd-threaded.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:785344bd598d3cd8abe3c7fa018b26e736601bc5c4c145f91a371470bcd001c3 +size 10646922 diff --git a/ort-wasm-simd.jsep.wasm b/ort-wasm-simd.jsep.wasm new file mode 100644 index 0000000000000000000000000000000000000000..32e5fa88d896fb74735df4fdbb540c319267682d --- /dev/null +++ b/ort-wasm-simd.jsep.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:adf595aa5fab7390d413dd259ceb28711b0591a52059f1ea9e5efe6040479681 +size 17411110 diff --git a/ort-wasm-simd.wasm b/ort-wasm-simd.wasm new file mode 100644 index 0000000000000000000000000000000000000000..d4dfbd3df11b188411bbcce144111306d3fa4b53 --- /dev/null +++ b/ort-wasm-simd.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0855759fb0ef86d4c64df1ccaaabead0ec402a68a658ad107cf2e3616b5fd48f +size 10550433 diff --git a/ort-wasm-threaded.wasm b/ort-wasm-threaded.wasm new file mode 100644 index 0000000000000000000000000000000000000000..e5ec8f6df41b52f2baa03b8d8fc4378e390d014c --- /dev/null +++ b/ort-wasm-threaded.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:024ccaec1f9925493e760e76f41e61864233be941465218e0c6287ff603f180f +size 9817579 diff --git a/ort-wasm.wasm b/ort-wasm.wasm new file mode 100644 index 0000000000000000000000000000000000000000..f06bd02692aabf0130c94c52d1c08c285274745d --- /dev/null +++ b/ort-wasm.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc387b876b7ea68d30be94a619d7d6f0edfe99df06edbb1dd0461465a870919a +size 9725745