var d3=Object.defineProperty;var c3=(Ye,fr,jr)=>fr in Ye?d3(Ye,fr,{enumerable:!0,configurable:!0,writable:!0,value:jr}):Ye[fr]=jr;var te=(Ye,fr,jr)=>(c3(Ye,typeof fr!="symbol"?fr+"":fr,jr),jr);(function(){"use strict";var jg;var Ye={},fr=Object.freeze({__proto__:null,default:Ye});const jr="3.0.0-alpha.0",Ji=typeof self<"u",g0=Ji&&self.constructor.name==="DedicatedWorkerGlobalScope",pl=Ji&&"caches"in self,y0=typeof navigator<"u"&&"gpu"in navigator,hl=typeof process<"u",_0=hl&&((jg=process==null?void 0:process.release)==null?void 0:jg.name)==="node",ea=!yl(Ye),fl=!yl(Ye),Rr=Object.freeze({IS_BROWSER_ENV:Ji,IS_WEBWORKER_ENV:g0,IS_WEB_CACHE_AVAILABLE:pl,IS_WEBGPU_AVAILABLE:y0,IS_PROCESS_AVAILABLE:hl,IS_NODE_ENV:_0,IS_FS_AVAILABLE:ea,IS_PATH_AVAILABLE:fl}),$s=ea&&fl,ml=$s?Ye.dirname(Ye.dirname(Ye.fileURLToPath(self.location.href))):"./",w0=$s?Ye.join(ml,"/.cache/"):null,gl="/models/",v0=$s?Ye.join(ml,gl):gl,Et={version:jr,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ji,localModelPath:v0,useFS:ea,useBrowserCache:pl,useFSCache:ea,cacheDir:w0,useCustomCache:!1,customCache:null};function yl(t){return Object.keys(t).length===0}const Ot=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 Dn(t,e){t&&t(e)}function b0(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e]))}function _l(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $0(t){return Number.isInteger(t)||typeof t=="bigint"}function ht(...t){return Array.prototype.concat.apply([],t)}function dn(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}var mr={};class ta{constructor(e){te(this,"_CONTENT_TYPE_MAP",{txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});if(this.filePath=e,this.headers=new Headers,this.exists=Ye.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Ye.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let n=this;this.body=new ReadableStream({start(a){n.arrayBuffer().then(o=>{a.enqueue(new Uint8Array(o)),a.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new ta(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 Ye.promises.readFile(this.filePath)).buffer}async blob(){const e=await Ye.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Ye.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function xs(t,e=null){let r;try{r=new URL(t)}catch{return!1}return e&&!e.includes(r.hostname)?!1:r.protocol==="http:"||r.protocol==="https:"}async function wl(t){var e;if(Et.useFS&&!xs(t))return new ta(t);if(typeof process<"u"&&((e=process==null?void 0:process.release)==null?void 0:e.name)==="node"){const r=!!(mr!=null&&mr.TESTING_REMOTELY),n=Et.version,a=new Headers;if(a.set("User-Agent",`transformers.js/${n}; is_ci/${r};`),xs(t,["huggingface.co","hf.co"])){const i=(mr==null?void 0:mr.HF_TOKEN)??(mr==null?void 0:mr.HF_ACCESS_TOKEN);i&&a.set("Authorization",`Bearer ${i}`)}return fetch(t,{headers:a})}else return fetch(t)}const x0={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 C0(t,e,r){if(!r)return null;const n=x0[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${n}: "${e}".`)}class vl{constructor(e){this.path=e}async match(e){let r=Ye.join(this.path,e),n=new ta(r);if(n.exists)return n}async put(e,r){const n=Buffer.from(await r.arrayBuffer());let a=Ye.join(this.path,e);try{await Ye.promises.mkdir(Ye.dirname(a),{recursive:!0}),await Ye.promises.writeFile(a,n)}catch(o){console.warn("An error occurred while writing the file to cache:",o)}}}async function S0(t,...e){for(let r of e)try{let n=await t.match(r);if(n)return n}catch{continue}}async function ra(t,e,r=!0,n={}){if(!Et.allowLocalModels&&n.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");Dn(n.progress_callback,{status:"initiate",name:t,file:e});let a;if(!a&&Et.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{a=await caches.open("transformers-cache")}catch(z){console.warn("An error occurred while opening the browser cache:",z)}}if(!a&&Et.useFSCache&&(a=new vl(n.cache_dir??Et.cacheDir)),!a&&Et.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const o=n.revision??"main";let i=na(t,e),d=na(Et.localModelPath,i),h=na(Et.remoteHost,Et.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(o)),e),m=o==="main"?i:na(t,o,e),c,_=a instanceof vl?m:h,v=!1,$;a&&($=await S0(a,d,_));const C=$!==void 0;if($===void 0){if(Et.allowLocalModels)if(xs(i)){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`)}else try{$=await wl(d),c=d}catch(I){console.warn(`Unable to load from local path "${d}": "${I}"`)}if($===void 0||$.status===404){if(n.local_files_only||!Et.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${d}".`);return null}if($=await wl(h),$.status!==200)return C0($.status,h,r);c=_}v=a&&typeof Response<"u"&&$ instanceof Response&&$.status===200}Dn(n.progress_callback,{status:"download",name:t,file:e});const k={status:"progress",name:t,file:e};let M;return n.progress_callback?C&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(M=new Uint8Array(await $.arrayBuffer()),Dn(n.progress_callback,{...k,progress:100,loaded:M.length,total:M.length})):M=await E0($,z=>{Dn(n.progress_callback,{...k,...z})}):M=new Uint8Array(await $.arrayBuffer()),v&&c&&await a.match(c)===void 0&&await a.put(c,new Response(M,{headers:$.headers})).catch(z=>{console.warn(`Unable to add response to browser cache: ${z}.`)}),Dn(n.progress_callback,{status:"done",name:t,file:e}),M}async function Br(t,e,r=!0,n={}){let a=await ra(t,e,r,n);if(a===null)return{};let i=new TextDecoder("utf-8").decode(a);return JSON.parse(i)}async function E0(t,e){const r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let n=parseInt(r??"0"),a=new Uint8Array(n),o=0;const i=t.body.getReader();async function d(){const{done:h,value:m}=await i.read();if(h)return;let c=o+m.length;if(c>n){n=c;let v=new Uint8Array(n);v.set(a),a=v}a.set(m,o),o=c;const _=o/n*100;return e({progress:_,loaded:o,total:n}),d()}return await d(),a}function na(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function k0(t,e,r){const n=new Array(r.length),a=new Array(r.length);for(let d=r.length-1,h=1;d>=0;--d)a[d]=h,n[d]=e[r[d]],h*=n[d];const o=r.map((d,h)=>a[r.indexOf(h)]),i=new t.constructor(t.length);for(let d=0;d=0;--m)h+=c%e[m]*o[m],c=Math.floor(c/e[m]);i[h]=t[d]}return[i,n]}function bl(t){const e=Cs(t)[0],r=t.map(o=>Math.exp(o-e)),n=r.reduce((o,i)=>o+i,0);return r.map(o=>o/n)}function $l(t,e=0){return t=Array.from(t).map((r,n)=>[n,r]).sort((r,n)=>n[1]-r[1]),e!==null&&e>0&&(t=t.slice(0,e)),t}function T0(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let n=1;ne&&(e=t[n],r=n);return[Number(e),r]}function I0(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");const r=new t.constructor(t.length),n=new t.constructor(e),a=Math.floor(e/2);for(let o=0;o=t.length&&(h=2*(t.length-1)-h),n[i++]=t[h]}n.sort(),r[o]=n[a]}return r}function ia(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}/*! * ONNX Runtime Web v1.18.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var Ss=Object.defineProperty,A0=Object.getOwnPropertyDescriptor,M0=Object.getOwnPropertyNames,O0=Object.prototype.hasOwnProperty,le=(t,e)=>()=>(t&&(e=t(t=0)),e),cn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),pn=(t,e)=>{for(var r in e)Ss(t,r,{get:e[r],enumerable:!0})},z0=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of M0(e))!O0.call(t,a)&&a!==r&&Ss(t,a,{get:()=>e[a],enumerable:!(n=A0(e,a))||n.enumerable});return t},Sr=t=>z0(Ss({},"__esModule",{value:!0}),t),Nn,Er,Dr,xl,Es,ks=le(()=>{Nn=new Map,Er=[],Dr=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let n=Nn.get(t);if(n===void 0)Nn.set(t,{backend:e,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let a=Er.indexOf(t);a!==-1&&Er.splice(a,1);for(let o=0;o{let e=Nn.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(n){return r||(e.error=`${n}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Es=async t=>{let e=t.executionProviders||[],r=e.map(h=>typeof h=="string"?h:h.name),n=r.length===0?Er:r,a,o=[],i=new Set;for(let h of n){let m=await xl(h);typeof m=="string"?o.push({name:h,err:m}):(a||(a=m),a===m&&i.add(h))}if(!a)throw new Error(`no available backend found. ERR: ${o.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:m}of o)r.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${m}`);let d=e.filter(h=>i.has(typeof h=="string"?h:h.name));return[a,new Proxy(t,{get:(h,m)=>m==="executionProviders"?d:Reflect.get(h,m)})]}}),P0=le(()=>{ks()}),Cl,j0=le(()=>{Cl="1.18.0"}),Ts,Lt,Sl=le(()=>{j0(),Ts="warning",Lt={wasm:{},webgl:{},webgpu:{},versions:{common:Cl},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}`);Ts=t}},get logLevel(){return Ts}},Object.defineProperty(Lt,"logLevel",{enumerable:!0})}),He,R0=le(()=>{Sl(),He=Lt}),El,kl,B0=le(()=>{El=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let n=r.getContext("2d");if(n!=null){let a,o;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],o=t.dims[3]):(a=t.dims[3],o=t.dims[2]);let i=(e==null?void 0:e.format)!==void 0?e.format:"RGB",d=e==null?void 0:e.norm,h,m;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[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 c=o*a,_=0,v=c,$=c*2,C=-1;i==="RGBA"?(_=0,v=c,$=c*2,C=c*3):i==="RGB"?(_=0,v=c,$=c*2):i==="RBG"&&(_=0,$=c,v=c*2);for(let k=0;k{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let a,o,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],o=t.dims[1],i=t.dims[3]):(a=t.dims[3],o=t.dims[2],i=t.dims[1]);let d=e!==void 0&&e.format!==void 0?e.format:"RGB",h=e==null?void 0:e.norm,m,c;h===void 0||h.mean===void 0?m=[255,255,255,255]:typeof h.mean=="number"?m=[h.mean,h.mean,h.mean,h.mean]:(m=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(m[3]=h.mean[3])),h===void 0||h.bias===void 0?c=[0,0,0,0]:typeof h.bias=="number"?c=[h.bias,h.bias,h.bias,h.bias]:(c=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(c[3]=h.bias[3]));let _=o*a;if(e!==void 0&&(e.format!==void 0&&i===4&&e.format!=="RGBA"||i===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let v=4,$=0,C=1,k=2,M=3,z=0,I=_,j=_*2,R=-1;d==="RGBA"?(z=0,I=_,j=_*2,R=_*3):d==="RGB"?(z=0,I=_,j=_*2):d==="RBG"&&(z=0,j=_,I=_*2),n=r.createImageData(a,o);for(let L=0;L{As(),aa=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=e,a=e.norm??{mean:255,bias:0},o,i;typeof a.mean=="number"?o=[a.mean,a.mean,a.mean,a.mean]:o=[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],typeof a.bias=="number"?i=[a.bias,a.bias,a.bias,a.bias]:i=[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];let d=e.format!==void 0?e.format:"RGBA",h=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",m=r*n,c=h==="RGBA"?new Float32Array(m*4):new Float32Array(m*3),_=4,v=0,$=1,C=2,k=3,M=0,z=m,I=m*2,j=-1;d==="RGB"&&(_=3,v=0,$=1,C=2,k=-1),h==="RGBA"?j=m*3:h==="RBG"?(M=0,I=m,z=m*2):h==="BGR"&&(I=0,z=m,M=m*2);for(let R=0;R{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,n=typeof ImageData<"u"&&t instanceof ImageData,a=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",i,d=e??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},m=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(r){let c=h();c.width=t.width,c.height=t.height;let _=m(c);if(_!=null){let v=t.height,$=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(v=e.resizedHeight,$=e.resizedWidth),e!==void 0){if(d=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=v,d.width=$}else d.tensorFormat="RGBA",d.height=v,d.width=$;_.drawImage(t,0,0),i=_.getImageData(0,0,$,v).data}else throw new Error("Can not access image data")}else if(n){let c,_;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,_=e.resizedWidth):(c=t.height,_=t.width),e!==void 0&&(d=e),d.format="RGBA",d.height=c,d.width=_,e!==void 0){let v=h();v.width=_,v.height=c;let $=m(v);if($!=null)$.putImageData(t,0,0),i=$.getImageData(0,0,_,c).data;else throw new Error("Can not access image data")}else i=t.data}else if(a){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let c=h();c.width=t.width,c.height=t.height;let _=m(c);if(_!=null){let v=t.height,$=t.width;return _.drawImage(t,0,0,$,v),i=_.getImageData(0,0,$,v).data,d.height=v,d.width=$,aa(i,d)}else throw new Error("Can not access image data")}else{if(o)return new Promise((c,_)=>{let v=h(),$=m(v);if(!t||!$)return _();let C=new Image;C.crossOrigin="Anonymous",C.src=t,C.onload=()=>{v.width=C.width,v.height=C.height,$.drawImage(C,0,0,v.width,v.height);let k=$.getImageData(0,0,v.width,v.height);d.height=v.height,d.width=v.width,c(aa(k.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return aa(i,d);throw new Error("Input data provided is not supported - aborted tensor creation")},Il=(t,e)=>{let{width:r,height:n,download:a,dispose:o}=e,i=[1,n,r,4];return new qt({location:"texture",type:"float32",texture:t,dims:i,download:a,dispose:o})},Al=(t,e)=>{let{dataType:r,dims:n,download:a,dispose:o}=e;return new qt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:o})},Ml=(t,e,r)=>new qt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Nr,Ln,Is,Ol,N0=le(()=>{Nr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Ln=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Is=!1,Ol=()=>{if(!Is){Is=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;t&&(Nr.set("int64",BigInt64Array),Ln.set(BigInt64Array,"int64")),e&&(Nr.set("uint64",BigUint64Array),Ln.set(BigUint64Array,"uint64")),r?(Nr.set("float16",Float16Array),Ln.set(Float16Array,"float16")):Nr.set("float16",Uint16Array)}}}),zl,Pl,L0=le(()=>{As(),zl=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new qt(t.type,t.data,e);case"cpu-pinned":return new qt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new qt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new qt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),qt,As=le(()=>{B0(),D0(),N0(),L0(),qt=class{constructor(t,e,r){Ol();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case"cpu-pinned":{let i=Nr.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,d;if(typeof t=="string")if(n=t,d=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");i=e}else{let h=Nr.get(t);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&h===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");t==="uint64"||t==="int64"?i=h.from(e,BigInt):i=h.from(e)}else if(e instanceof h)i=e;else throw new TypeError(`A ${n} tensor's data must be type of ${h}`)}else if(d=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof t[0];if(h==="string")n="string",i=t;else if(h==="boolean")n="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else{let h=Ln.get(t.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=h,i=t}if(d===void 0)d=[i.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");a=d,this.cpuData=i,this.dataLocation="cpu"}let o=zl(a);if(this.cpuData&&o!==this.cpuData.length)throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=o}static async fromImage(t,e){return Tl(t,e)}static fromTexture(t,e){return Il(t,e)}static fromGpuBuffer(t,e){return Al(t,e)}static fromPinnedBuffer(t,e,r){return Ml(t,e,r)}toDataURL(t){return El(this,t)}toImageData(t){return kl(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 Pl(this,t)}}}),bt,Ms=le(()=>{As(),bt=qt}),Un,Os,Kt,Ut,jl=le(()=>{Sl(),Un=(t,e)=>{(typeof Lt.trace>"u"?!Lt.wasm.trace:!Lt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Os=(t,e)=>{var a;let r=((a=new Error().stack)==null?void 0:a.split(/\r\n|\r|\n/g))||[],n=!1;for(let o=0;o{(typeof Lt.trace>"u"?!Lt.wasm.trace:!Lt.trace)||Os("BEGIN",t)},Ut=t=>{(typeof Lt.trace>"u"?!Lt.wasm.trace:!Lt.trace)||Os("END",t)}}),Rl,U0=le(()=>{ks(),Ms(),jl(),Rl=class h0{constructor(e){this.handler=e}async run(e,r,n){Kt();let a={},o={};if(typeof e!="object"||e===null||e instanceof bt||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof bt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let m of r){if(typeof m!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(m)===-1)throw new RangeError(`'fetches' contains invalid output name: ${m}.`);a[m]=null}if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let m=!1,c=Object.getOwnPropertyNames(r);for(let _ of this.outputNames)if(c.indexOf(_)!==-1){let v=r[_];(v===null||v instanceof bt)&&(m=!0,i=!1,a[_]=v)}if(m){if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let m of this.inputNames)if(typeof e[m]>"u")throw new Error(`input '${m}' is missing in 'feeds'.`);if(i)for(let m of this.outputNames)a[m]=null;let d=await this.handler.run(e,a,o),h={};for(let m in d)if(Object.hasOwnProperty.call(d,m)){let c=d[m];c instanceof bt?h[m]=c:h[m]=new bt(c.type,c.data,c.dims)}return Ut(),h}async release(){return this.handler.dispose()}static async create(e,r,n,a){Kt();let o,i={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let c=e,_=0,v=e.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(_=r,!Number.isSafeInteger(_))throw new RangeError("'byteOffset' must be an integer.");if(_<0||_>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.byteLength}).`);if(v=e.byteLength-_,typeof n=="number"){if(v=n,!Number.isSafeInteger(v))throw new RangeError("'byteLength' must be an integer.");if(v<=0||_+v>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.byteLength-_}].`);if(typeof a=="object"&&a!==null)i=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(c,_,v)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,h]=await Es(i),m=await d.createInferenceSessionHandler(o,h);return Ut(),new h0(m)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),zs,F0=le(()=>{U0(),zs=Rl}),W0=le(()=>{}),G0=le(()=>{}),V0=le(()=>{}),H0=le(()=>{}),Bl,Dl,q0=le(()=>{ks(),Ms(),Bl="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Dl=class f0{constructor(e,r,n){this.handler=e,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(e,r){let n=e.evalModel||"",a=e.optimizerModel||"",o=r||{},[i,d]=await Es(o);if(i.createTrainingSessionHandler){let h=await i.createTrainingSessionHandler(e.checkpointState,e.trainModel,n,a,d);return new f0(h,!!e.optimizerModel,!!e.evalModel)}else throw new Error(Bl)}typeNarrowingForRunStep(e,r,n,a,o){let i={},d={};if(typeof n!="object"||n===null||n instanceof bt||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let h=!0;if(typeof a=="object"){if(a===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(a instanceof bt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(a)){if(a.length===0)throw new TypeError("'fetches' cannot be an empty array.");h=!1;for(let m of a){if(typeof m!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(m)===-1)throw new RangeError(`'fetches' contains invalid output name: ${m}.`);i[m]=null}if(typeof o=="object"&&o!==null)d=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else{let m=!1,c=Object.getOwnPropertyNames(a);for(let _ of r)if(c.indexOf(_)!==-1){let v=a[_];(v===null||v instanceof bt)&&(m=!0,h=!1,i[_]=v)}if(m){if(typeof o=="object"&&o!==null)d=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else d=a}}else if(typeof a<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let m of e)if(typeof n[m]>"u")throw new Error(`input '${m}' is missing in 'feeds'.`);if(h)for(let m of r)i[m]=null;return[i,d]}convertHandlerReturnTypeToMapOfTensors(e){let r={};for(let n in e)if(Object.hasOwnProperty.call(e,n)){let a=e[n];a instanceof bt?r[n]=a:r[n]=new bt(a.type,a.data,a.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,r,n){let[a,o]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,r,n),i=await this.handler.runTrainStep(e,a,o);return this.convertHandlerReturnTypeToMapOfTensors(i)}async runOptimizerStep(e){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(e||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(e,r,n){if(this.hasEvalModel){let[a,o]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,r,n),i=await this.handler.runEvalStep(e,a,o);return this.convertHandlerReturnTypeToMapOfTensors(i)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,r=!0){let n=await this.getParametersSize(r);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,r)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}}),Ps,K0=le(()=>{q0(),Ps=Dl}),Nl={};pn(Nl,{InferenceSession:()=>zs,TRACE:()=>Un,TRACE_FUNC_BEGIN:()=>Kt,TRACE_FUNC_END:()=>Ut,Tensor:()=>bt,TrainingSession:()=>Ps,env:()=>He,registerBackend:()=>Dr});var Yt=le(()=>{P0(),R0(),F0(),Ms(),W0(),G0(),jl(),V0(),H0(),K0()}),sa={};pn(sa,{createReadStream:()=>Fl,readFile:()=>Ll,readFileSync:()=>Ul});var Ll,Ul,Fl,js=le(()=>{Ll=void 0,Ul=void 0,Fl=void 0}),Rs={};pn(Rs,{join:()=>Wl});var Wl,Gl=le(()=>{Wl=void 0}),Y0=cn((t,e)=>{var r=(()=>{var a;var n=typeof document<"u"?(a=document.currentScript)==null?void 0:a.src:void 0;return typeof __filename<"u"&&(n||(n=__filename)),function(o={}){var i=o,d,h,m=new Promise((s,l)=>{d=s,h=l});i.mountExternalData=(s,l)=>{(i.Ph||(i.Ph=new Map)).set(s,l)},i.unmountExternalData=()=>{delete i.Ph};let c=()=>{let s=(u,p,f)=>(...g)=>{let w=Dt,b=p==null?void 0:p();g=u(...g);let x=p==null?void 0:p();return b!==x&&(u=x,f(b),p=f=null),Dt!=w?cs():g},l=u=>async(...p)=>{var f;try{if(i.Oh)throw Error("Session already started");let g=i.Oh={gi:p[0],errors:[]},w=await u(...p);if(i.Oh!==g)throw Error("Session mismatch");(f=i.Uh)==null||f.flush();let b=g.errors;if(0E),0i._OrtCreateSession,u=>i._OrtCreateSession=u),i._OrtRun=l(s(i._OrtRun,()=>i._OrtRun,u=>i._OrtRun=u)),i._OrtRunWithBinding=l(s(i._OrtRunWithBinding,()=>i._OrtRunWithBinding,u=>i._OrtRunWithBinding=u)),i._OrtBindInput=s(i._OrtBindInput,()=>i._OrtBindInput,u=>i._OrtBindInput=u),c=void 0};i.jsepInit=(s,l)=>{if(c==null||c(),s==="webgpu"){[i.Uh,i.Zh,i.ci,i.Vh,i.bi,i.je,i.di,i.fi,i.$h,i.ai,i.ei]=l;let u=i.Uh;i.jsepRegisterBuffer=(p,f,g,w)=>u.registerBuffer(p,f,g,w),i.jsepGetBuffer=p=>u.getBuffer(p),i.jsepCreateDownloader=(p,f,g)=>u.createDownloader(p,f,g),i.jsepOnReleaseSession=p=>{u.onReleaseSession(p)},i.jsepOnRunStart=p=>u.onRunStart(p)}};var _=Object.assign({},i),v="./this.program",$=(s,l)=>{throw l},C=typeof window=="object",k=typeof importScripts=="function",M=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",z="",I,j,R;if(M){var L=(js(),Sr(sa)),Y=(Gl(),Sr(Rs));z=k?Y.dirname(z)+"/":__dirname+"/",I=(s,l)=>(s=It(s)?new URL(s):Y.normalize(s),L.readFileSync(s,l?void 0:"utf8")),R=s=>(s=I(s,!0),s.buffer||(s=new Uint8Array(s)),s),j=(s,l,u,p=!0)=>{s=It(s)?new URL(s):Y.normalize(s),L.readFile(s,p?void 0:"utf8",(f,g)=>{f?u(f):l(p?g.buffer:g)})},!i.thisProgram&&1{throw process.exitCode=s,l}}else(C||k)&&(k?z=self.location.href:typeof document<"u"&&document.currentScript&&(z=document.currentScript.src),n&&(z=n),z.startsWith("blob:")?z="":z=z.substr(0,z.replace(/[?#].*/,"").lastIndexOf("/")+1),I=s=>{var l=new XMLHttpRequest;return l.open("GET",s,!1),l.send(null),l.responseText},k&&(R=s=>{var l=new XMLHttpRequest;return l.open("GET",s,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)}),j=(s,l,u)=>{var p=new XMLHttpRequest;p.open("GET",s,!0),p.responseType="arraybuffer",p.onload=()=>{p.status==200||p.status==0&&p.response?l(p.response):u()},p.onerror=u,p.send(null)});var Q=console.log.bind(console),ie=console.error.bind(console);Object.assign(i,_),_=null;var pe,ce=!1,Se,fe,me,ge,X,U,ne,ee,Ee,Te,K;function he(){var s=pe.buffer;i.HEAP8=fe=new Int8Array(s),i.HEAP16=ge=new Int16Array(s),i.HEAPU8=me=new Uint8Array(s),i.HEAPU16=X=new Uint16Array(s),i.HEAP32=U=new Int32Array(s),i.HEAPU32=ne=new Uint32Array(s),i.HEAPF32=ee=new Float32Array(s),i.HEAPF64=K=new Float64Array(s),i.HEAP64=Ee=new BigInt64Array(s),i.HEAPU64=Te=new BigUint64Array(s)}var ve=[],Le=[],Ke=[],ct=0,pt=null;function rt(s){throw s="Aborted("+s+")",ie(s),ce=!0,Se=1,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),h(s),s}var Gt=s=>s.startsWith("data:application/octet-stream;base64,"),It=s=>s.startsWith("file://"),ir;if(ir="ort-wasm-simd.wasm",!Gt(ir)){var st=ir;ir=i.locateFile?i.locateFile(st,z):z+st}function ot(s){if(R)return R(s);throw"both async and sync fetching of the wasm failed"}function vt(s){if(C||k){if(typeof fetch=="function"&&!It(s))return fetch(s,{credentials:"same-origin"}).then(l=>{if(!l.ok)throw`failed to load wasm binary file at '${s}'`;return l.arrayBuffer()}).catch(()=>ot(s));if(j)return new Promise((l,u)=>{j(s,p=>l(new Uint8Array(p)),u)})}return Promise.resolve().then(()=>ot(s))}function ar(s,l,u){return vt(s).then(p=>WebAssembly.instantiate(p,l)).then(u,p=>{ie(`failed to asynchronously prepare wasm: ${p}`),rt(p)})}function bn(s,l){var u=ir;return typeof WebAssembly.instantiateStreaming!="function"||Gt(u)||It(u)||M||typeof fetch!="function"?ar(u,s,l):fetch(u,{credentials:"same-origin"}).then(p=>WebAssembly.instantiateStreaming(p,s).then(l,function(f){return ie(`wasm streaming compile failed: ${f}`),ie("falling back to ArrayBuffer instantiation"),ar(u,s,l)}))}var bi={1261504:(s,l,u,p)=>{if(typeof i>"u"||!i.Ph)return 1;if(s=et(s>>>0),s.startsWith("./")&&(s=s.substring(2)),s=i.Ph.get(s),!s)return 2;if(l>>>=0,u>>>=0,l+u>s.byteLength)return 3;try{return me.set(s.subarray(l,l+u),p>>>0>>>0),0}catch{return 4}},1262005:(s,l,u)=>{u=et(u);let p=new Uint8Array(l);p.set(me.subarray(s>>>0,s+l>>>0)),typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"?(js(),Sr(sa)).writeFileSync(u,p):(s=new File([p],u,{type:"application/octet-stream"}),s=URL.createObjectURL(s),window.open(s,"_blank"))},1262513:()=>{i.$h()},1262544:()=>{i.ai()},1262573:()=>{i.ei()},1262598:s=>i.Zh(s),1262631:s=>i.ci(s),1262663:(s,l,u)=>{i.Vh(s,l,u,!0)},1262702:(s,l,u)=>{i.Vh(s,l,u)},1262735:s=>{i.je("Abs",s,void 0)},1262786:s=>{i.je("Neg",s,void 0)},1262837:s=>{i.je("Floor",s,void 0)},1262890:s=>{i.je("Ceil",s,void 0)},1262942:s=>{i.je("Reciprocal",s,void 0)},1263e3:s=>{i.je("Sqrt",s,void 0)},1263052:s=>{i.je("Exp",s,void 0)},1263103:s=>{i.je("Erf",s,void 0)},1263154:s=>{i.je("Sigmoid",s,void 0)},1263209:(s,l,u)=>{i.je("HardSigmoid",s,{alpha:l,beta:u})},1263288:s=>{i.je("Log",s,void 0)},1263339:s=>{i.je("Sin",s,void 0)},1263390:s=>{i.je("Cos",s,void 0)},1263441:s=>{i.je("Tan",s,void 0)},1263492:s=>{i.je("Asin",s,void 0)},1263544:s=>{i.je("Acos",s,void 0)},1263596:s=>{i.je("Atan",s,void 0)},1263648:s=>{i.je("Sinh",s,void 0)},1263700:s=>{i.je("Cosh",s,void 0)},1263752:s=>{i.je("Asinh",s,void 0)},1263805:s=>{i.je("Acosh",s,void 0)},1263858:s=>{i.je("Atanh",s,void 0)},1263911:s=>{i.je("Tanh",s,void 0)},1263963:s=>{i.je("Not",s,void 0)},1264014:(s,l,u)=>{i.je("Clip",s,{min:l,max:u})},1264083:s=>{i.je("Clip",s,void 0)},1264135:(s,l)=>{i.je("Elu",s,{alpha:l})},1264193:s=>{i.je("Relu",s,void 0)},1264245:(s,l)=>{i.je("LeakyRelu",s,{alpha:l})},1264309:(s,l)=>{i.je("ThresholdedRelu",s,{alpha:l})},1264379:(s,l)=>{i.je("Cast",s,{to:l})},1264437:s=>{i.je("Add",s,void 0)},1264488:s=>{i.je("Sub",s,void 0)},1264539:s=>{i.je("Mul",s,void 0)},1264590:s=>{i.je("Div",s,void 0)},1264641:s=>{i.je("Pow",s,void 0)},1264692:s=>{i.je("Equal",s,void 0)},1264745:s=>{i.je("Greater",s,void 0)},1264800:s=>{i.je("GreaterOrEqual",s,void 0)},1264862:s=>{i.je("Less",s,void 0)},1264914:s=>{i.je("LessOrEqual",s,void 0)},1264973:(s,l,u,p,f)=>{i.je("ReduceMean",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1265132:(s,l,u,p,f)=>{i.je("ReduceMax",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1265290:(s,l,u,p,f)=>{i.je("ReduceMin",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1265448:(s,l,u,p,f)=>{i.je("ReduceProd",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1265607:(s,l,u,p,f)=>{i.je("ReduceSum",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1265765:(s,l,u,p,f)=>{i.je("ReduceL1",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1265922:(s,l,u,p,f)=>{i.je("ReduceL2",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1266079:(s,l,u,p,f)=>{i.je("ReduceLogSum",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1266240:(s,l,u,p,f)=>{i.je("ReduceSumSquare",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1266404:(s,l,u,p,f)=>{i.je("ReduceLogSumExp",s,{keepDims:!!l,noopWithEmptyAxes:!!u,axes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1266568:s=>{i.je("Where",s,void 0)},1266621:(s,l,u)=>{i.je("Transpose",s,{perm:l?Array.from(U.subarray(l>>>0,u>>>0)):[]})},1266729:(s,l,u,p)=>{i.je("DepthToSpace",s,{blocksize:l,mode:et(u),format:p?"NHWC":"NCHW"})},1266862:(s,l,u,p)=>{i.je("DepthToSpace",s,{blocksize:l,mode:et(u),format:p?"NHWC":"NCHW"})},1266995:(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)=>{i.je("ConvTranspose",s,{format:x?"NHWC":"NCHW",autoPad:l,dilations:[u],group:p,kernelShape:[f],pads:[g,w],strides:[b],wIsConst:()=>!!fe[E>>>0],outputPadding:T?Array.from(U.subarray(T>>>0,P>>>0)):[],outputShape:D?Array.from(U.subarray(D>>>0,O>>>0)):[],activation:et(F)})},1267396:(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>{i.je("ConvTranspose",s,{format:b?"NHWC":"NCHW",autoPad:l,dilations:Array.from(U.subarray(u>>>0,(u>>>0)+2>>>0)),group:p,kernelShape:Array.from(U.subarray(f>>>0,(f>>>0)+2>>>0)),pads:Array.from(U.subarray(g>>>0,(g>>>0)+4>>>0)),strides:Array.from(U.subarray(w>>>0,(w>>>0)+2>>>0)),wIsConst:()=>!!fe[x>>>0],outputPadding:E?Array.from(U.subarray(E>>>0,T>>>0)):[],outputShape:P?Array.from(U.subarray(P>>>0,D>>>0)):[],activation:et(O)})},1267961:(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)=>{i.je("ConvTranspose",s,{format:x?"NHWC":"NCHW",autoPad:l,dilations:[u],group:p,kernelShape:[f],pads:[g,w],strides:[b],wIsConst:()=>!!fe[E>>>0],outputPadding:T?Array.from(U.subarray(T>>>0,P>>>0)):[],outputShape:D?Array.from(U.subarray(D>>>0,O>>>0)):[],activation:et(F)})},1268362:(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>{i.je("ConvTranspose",s,{format:b?"NHWC":"NCHW",autoPad:l,dilations:Array.from(U.subarray(u>>>0,(u>>>0)+2>>>0)),group:p,kernelShape:Array.from(U.subarray(f>>>0,(f>>>0)+2>>>0)),pads:Array.from(U.subarray(g>>>0,(g>>>0)+4>>>0)),strides:Array.from(U.subarray(w>>>0,(w>>>0)+2>>>0)),wIsConst:()=>!!fe[x>>>0],outputPadding:E?Array.from(U.subarray(E>>>0,T>>>0)):[],outputShape:P?Array.from(U.subarray(P>>>0,D>>>0)):[],activation:et(O)})},1268927:(s,l)=>{i.je("GlobalAveragePool",s,{format:l?"NHWC":"NCHW"})},1269018:(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>{i.je("AveragePool",s,{format:J?"NHWC":"NCHW",auto_pad:l,ceil_mode:u,count_include_pad:p,storage_order:f,dilations:[g,w],kernel_shape:[b,x],pads:[E,T,P,D],strides:[O,F]})},1269302:(s,l)=>{i.je("GlobalAveragePool",s,{format:l?"NHWC":"NCHW"})},1269393:(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>{i.je("AveragePool",s,{format:J?"NHWC":"NCHW",auto_pad:l,ceil_mode:u,count_include_pad:p,storage_order:f,dilations:[g,w],kernel_shape:[b,x],pads:[E,T,P,D],strides:[O,F]})},1269677:(s,l)=>{i.je("GlobalMaxPool",s,{format:l?"NHWC":"NCHW"})},1269764:(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>{i.je("MaxPool",s,{format:J?"NHWC":"NCHW",auto_pad:l,ceil_mode:u,count_include_pad:p,storage_order:f,dilations:[g,w],kernel_shape:[b,x],pads:[E,T,P,D],strides:[O,F]})},1270044:(s,l)=>{i.je("GlobalMaxPool",s,{format:l?"NHWC":"NCHW"})},1270131:(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>{i.je("MaxPool",s,{format:J?"NHWC":"NCHW",auto_pad:l,ceil_mode:u,count_include_pad:p,storage_order:f,dilations:[g,w],kernel_shape:[b,x],pads:[E,T,P,D],strides:[O,F]})},1270411:(s,l,u,p,f)=>{i.je("Gemm",s,{alpha:l,beta:u,transA:p,transB:f})},1270515:s=>{i.je("MatMul",s,void 0)},1270569:(s,l,u,p)=>{i.je("ArgMax",s,{keepDims:!!l,selectLastIndex:!!u,axis:p})},1270677:(s,l,u,p)=>{i.je("ArgMin",s,{keepDims:!!l,selectLastIndex:!!u,axis:p})},1270785:(s,l)=>{i.je("Softmax",s,{axis:l})},1270848:(s,l)=>{i.je("Concat",s,{axis:l})},1270908:(s,l,u,p,f)=>{i.je("Split",s,{axis:l,numOutputs:u,splitSizes:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1271048:s=>{i.je("Expand",s,void 0)},1271102:(s,l)=>{i.je("Gather",s,{axis:Number(l)})},1271173:(s,l)=>{i.je("GatherElements",s,{axis:Number(l)})},1271252:(s,l,u,p,f,g,w,b,x,E,T)=>{i.je("Resize",s,{antialias:l,axes:u?Array.from(U.subarray(u>>>0,p>>>0)):[],coordinateTransformMode:et(f),cubicCoeffA:g,excludeOutside:w,extrapolationValue:b,keepAspectRatioPolicy:et(x),mode:et(E),nearestMode:et(T)})},1271598:(s,l,u,p,f,g,w)=>{i.je("Slice",s,{starts:l?Array.from(U.subarray(l>>>0,u>>>0)):[],ends:p?Array.from(U.subarray(p>>>0,f>>>0)):[],axes:g?Array.from(U.subarray(g>>>0,w>>>0)):[]})},1271814:s=>{i.je("Tile",s,void 0)},1271866:(s,l,u,p)=>{i.je("LayerNormalization",s,{axis:l,epsilon:u,simplified:!!p})},1271977:(s,l,u)=>{i.je("InstanceNormalization",s,{epsilon:l,format:u?"NHWC":"NCHW"})},1272091:(s,l,u)=>{i.je("InstanceNormalization",s,{epsilon:l,format:u?"NHWC":"NCHW"})},1272205:s=>{i.je("Range",s,void 0)},1272258:(s,l)=>{i.je("Einsum",s,{equation:et(l)})},1272339:(s,l,u,p,f)=>{i.je("Pad",s,{mode:l,value:u,pads:p?Array.from(U.subarray(p>>>0,f>>>0)):[]})},1272466:(s,l,u,p,f,g)=>{i.je("BatchNormalization",s,{epsilon:l,momentum:u,spatial:!!f,trainingMode:!!p,format:g?"NHWC":"NCHW"})},1272635:(s,l,u,p,f,g)=>{i.je("BatchNormalization",s,{epsilon:l,momentum:u,spatial:!!f,trainingMode:!!p,format:g?"NHWC":"NCHW"})},1272804:(s,l,u)=>{i.je("CumSum",s,{exclusive:Number(l),reverse:Number(u)})},1272901:(s,l,u,p,f,g,w,b,x)=>{i.je("Attention",s,{numHeads:l,isUnidirectional:u,maskFilterValue:p,scale:f,doRotary:g,qkvHiddenSizes:w?Array.from(U.subarray(Number(b)>>>0,Number(b)+w>>>0)):[],pastPresentShareBuffer:!!x})},1273173:s=>{i.je("BiasAdd",s,void 0)},1273228:s=>{i.je("BiasSplitGelu",s,void 0)},1273289:s=>{i.je("FastGelu",s,void 0)},1273345:(s,l,u,p,f,g,w,b,x,E,T,P,D)=>{i.je("Conv",s,{format:x?"NHWC":"NCHW",auto_pad:l,dilations:[u],group:p,kernel_shape:[f],pads:g?Array.from(U.subarray(g>>>0,w>>>0)):[],strides:[b],w_is_const:()=>!!fe[E>>>0],activation:et(T),activation_params:P?Array.from(ee.subarray(P>>>0,D>>>0)):[]})},1273715:(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>{i.je("Conv",s,{format:P?"NHWC":"NCHW",auto_pad:l,dilations:[u,p],group:f,kernel_shape:[g,w],pads:b?Array.from(U.subarray(b>>>0,x>>>0)):[],strides:[E,T],w_is_const:()=>!!fe[D>>>0],activation:et(O),activation_params:F?Array.from(ee.subarray(F>>>0,J>>>0)):[]})},1274106:s=>{i.je("Gelu",s,void 0)},1274158:(s,l,u,p,f,g)=>{i.je("MatMulNBits",s,{k:l,n:u,accuracyLevel:p,bits:f,blockSize:g})},1274285:(s,l,u,p,f,g)=>{i.je("MultiHeadAttention",s,{numHeads:l,isUnidirectional:u,maskFilterValue:p,scale:f,doRotary:g})},1274444:(s,l,u,p,f)=>{i.je("RotaryEmbedding",s,{interleaved:!!l,numHeads:u,rotaryEmbeddingDim:p,scale:f})},1274583:(s,l,u)=>{i.je("SkipLayerNormalization",s,{epsilon:l,simplified:!!u})},1274685:(s,l,u)=>{i.je("SkipLayerNormalization",s,{epsilon:l,simplified:!!u})},1274787:(s,l,u,p)=>{i.je("LayerNormalization",s,{axis:l,epsilon:u,simplified:!!p})},1274898:s=>{i.di(s)},1274932:(s,l)=>i.fi(s,l,i.Oh.gi,i.Oh.errors)};function Vt(s){this.name="ExitStatus",this.message=`Program terminated with exit(${s})`,this.status=s}var Zr=[],sr=0,or=0;class $i{constructor(l){this.Nh=l,this.Ih=l-24}}var Jr=s=>{var l=or;if(!l)return sn(0),0;var u=new $i(l);ne[u.Ih+16>>>2>>>0]=l;var p=ne[u.Ih+4>>>2>>>0];if(!p)return sn(0),l;for(var f in s){var g=s[f];if(g===0||g===p)break;if(_s(g,p,u.Ih+16))return sn(g),l}return sn(p),l},Xa=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,$r=(s,l,u)=>{l>>>=0;var p=l+u;for(u=l;s[u]&&!(u>=p);)++u;if(16f?p+=String.fromCharCode(f):(f-=65536,p+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else p+=String.fromCharCode(f)}return p},et=(s,l)=>(s>>>=0)?$r(me,s,l):"",Or=s=>{for(var l=0,u=0;u=p?l++:2047>=p?l+=2:55296<=p&&57343>=p?(l+=4,++u):l+=3}return l},lr=(s,l,u,p)=>{if(u>>>=0,!(0=w){var b=s.charCodeAt(++g);w=65536+((w&1023)<<10)|b&1023}if(127>=w){if(u>=p)break;l[u++>>>0]=w}else{if(2047>=w){if(u+1>=p)break;l[u++>>>0]=192|w>>6}else{if(65535>=w){if(u+2>=p)break;l[u++>>>0]=224|w>>12}else{if(u+3>=p)break;l[u++>>>0]=240|w>>18,l[u++>>>0]=128|w>>12&63}l[u++>>>0]=128|w>>6&63}l[u++>>>0]=128|w&63}}return l[u>>>0]=0,u-f},xi,Rt=s=>{for(var l="";me[s>>>0];)l+=xi[me[s++>>>0]];return l},$n={},xn={},gt;function Za(s,l,u={}){var p=l.name;if(!s)throw new gt(`type "${p}" must have a positive integer typeid pointer`);if(xn.hasOwnProperty(s)){if(u.Xh)return;throw new gt(`Cannot register type '${p}' twice`)}xn[s]=l,$n.hasOwnProperty(s)&&(l=$n[s],delete $n[s],l.forEach(f=>f()))}function Bt(s,l,u={}){if(!("argPackAdvance"in l))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Za(s,l,u)}var Ie=(s,l,u)=>{switch(l){case 1:return u?p=>fe[p>>>0]:p=>me[p>>>0];case 2:return u?p=>ge[p>>>1>>>0]:p=>X[p>>>1>>>0];case 4:return u?p=>U[p>>>2>>>0]:p=>ne[p>>>2>>>0];case 8:return u?p=>Ee[p>>>3]:p=>Te[p>>>3];default:throw new TypeError(`invalid integer width (${l}): ${s}`)}},zr=[],Ht=[];function Ci(s){s>>>=0,9{if(!s)throw new gt("Cannot use deleted val. handle = "+s);return Ht[s]},At=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let l=zr.pop()||Ht.length;return Ht[l]=s,Ht[l+1]=1,l}};function Cn(s){return this.fromWireType(ne[s>>>2>>>0])}var Ja={name:"emscripten::val",fromWireType:s=>{var l=yt(s);return Ci(s),l},toWireType:(s,l)=>At(l),argPackAdvance:8,readValueFromPointer:Cn,Mh:null},es=(s,l)=>{switch(l){case 4:return function(u){return this.fromWireType(ee[u>>>2>>>0])};case 8:return function(u){return this.fromWireType(K[u>>>3>>>0])};default:throw new TypeError(`invalid float width (${l}): ${s}`)}},Sn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ts=(s,l)=>{for(var u=s>>1,p=u+l/2;!(u>=p)&&X[u>>>0];)++u;if(u<<=1,32>>0,u>>>0));for(u="",p=0;!(p>=l/2);++p){var f=ge[s+2*p>>>1>>>0];if(f==0)break;u+=String.fromCharCode(f)}return u},rs=(s,l,u)=>{if(u??(u=2147483647),2>u)return 0;u-=2;var p=l;u=u<2*s.length?u/2:s.length;for(var f=0;f>>1>>>0]=s.charCodeAt(f),l+=2;return ge[l>>>1>>>0]=0,l-p},ns=s=>2*s.length,is=(s,l)=>{for(var u=0,p="";!(u>=l/4);){var f=U[s+4*u>>>2>>>0];if(f==0)break;++u,65536<=f?(f-=65536,p+=String.fromCharCode(55296|f>>10,56320|f&1023)):p+=String.fromCharCode(f)}return p},as=(s,l,u)=>{if(l>>>=0,u??(u=2147483647),4>u)return 0;var p=l;u=p+u-4;for(var f=0;f=g){var w=s.charCodeAt(++f);g=65536+((g&1023)<<10)|w&1023}if(U[l>>>2>>>0]=g,l+=4,l+4>u)break}return U[l>>>2>>>0]=0,l-p},ss=s=>{for(var l=0,u=0;u=p&&++u,l+=4}return l},En=(s,l)=>{var u=xn[s];if(u===void 0)throw s=Di(s),u=Rt(s),Mt(s),new gt(`${l} has unknown type ${u}`);return u},Si=(s,l,u)=>{var p=[];return s=s.toWireType(p,u),p.length&&(ne[l>>>2>>>0]=At(p)),s},en=s=>{try{s()}catch(l){rt(l)}},os=s=>{var l;if(!ce)try{s();try{Se=Se=s=Se,(l=i.onExit)==null||l.call(i,s),ce=!0,$(s,new Vt(s))}catch(u){u instanceof Vt||u=="unwind"||$(1,u)}}catch(u){u instanceof Vt||u=="unwind"||$(1,u)}};function ls(){var s=N,l={};for(let[u,p]of Object.entries(s))l[u]=typeof p=="function"?(...f)=>{Pr.push(u);try{return p(...f)}finally{ce||(Pr.pop(),Dt&&ur===1&&Pr.length===0&&(ur=0,en(u0),typeof Fibers<"u"&&Fibers.mi()))}}:p;return l}var ur=0,Dt=null,Ei=0,Pr=[],tn={},xr={},us=0,kn=null,ds=[];function cs(){return new Promise((s,l)=>{kn={resolve:s,reject:l}})}function ps(){var s=On(65548),l=s+12;ne[s>>>2>>>0]=l,ne[s+4>>>2>>>0]=l+65536,l=Pr[0];var u=tn[l];return u===void 0&&(u=us++,tn[l]=u,xr[u]=l),U[s+8>>>2>>>0]=u,s}function ki(s){if(!ce){if(ur===0){var l=!1,u=!1;s((p=0)=>{if(!ce&&(Ei=p,l=!0,u)){ur=2,en(()=>d0(Dt)),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.resume(),p=!1;try{var f=(0,N[xr[U[Dt+8>>>2>>>0]]])()}catch(b){f=b,p=!0}var g=!1;if(!Dt){var w=kn;w&&(kn=null,(p?w.reject:w.resolve)(f),g=!0)}if(p&&!g)throw f}}),u=!0,l||(ur=1,Dt=ps(),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.pause(),en(()=>l0(Dt)))}else ur===2?(ur=0,en(c0),Mt(Dt),Dt=null,ds.forEach(os)):rt(`invalid state: ${ur}`);return Ei}}function Ti(s){return ki(l=>{s().then(l)})}var Tn=[],Qe={},rn=s=>{var l=Qe[s];return l===void 0?Rt(s):l},In=()=>typeof globalThis=="object"?globalThis:Function("return this")(),hs=s=>{var l=Tn.length;return Tn.push(s),l},Ii=(s,l)=>{for(var u=Array(s),p=0;p>>2>>>0],"parameter "+p);return u},Ai=(s,l)=>Object.defineProperty(l,"name",{value:s});function fs(s){var l=Function;if(!(l instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof l} which is not a function`);var u=Ai(l.name||"unknownFunctionName",function(){});return u.prototype=l.prototype,u=new u,s=l.apply(u,s),s instanceof Object?s:u}var Cr=s=>s%4===0&&(s%100!==0||s%400===0),Mi=[0,31,60,91,121,152,182,213,244,274,305,335],Oi=[0,31,59,90,120,151,181,212,243,273,304,334],zi=[],Pi=(s,l)=>{zi.length=0;for(var u;u=me[s++>>>0];){var p=u!=105;p&=u!=112,l+=p&&l%8?4:0,zi.push(u==112?ne[l>>>2>>>0]:u==106?Ee[l>>>3]:u==105?U[l>>>2>>>0]:K[l>>>3>>>0]),l+=p?8:4}return zi},An={},ji=()=>{if(!Ri){var s={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:v||"./this.program"},l;for(l in An)An[l]===void 0?delete s[l]:s[l]=An[l];var u=[];for(l in s)u.push(`${l}=${s[l]}`);Ri=u}return Ri},Ri,sl=[null,[],[]],Bi=[31,29,31,30,31,30,31,31,30,31,30,31],nn=[31,28,31,30,31,30,31,31,30,31,30,31];function ol(s){var l=Array(Or(s)+1);return lr(s,l,0,l.length),l}function dr(s,l,u,p){function f(O,F,J){for(O=typeof O=="number"?O.toString():O||"";O.length_e?-1:0<_e?1:0}var de;return(de=J(O.getFullYear()-F.getFullYear()))===0&&(de=J(O.getMonth()-F.getMonth()))===0&&(de=J(O.getDate()-F.getDate())),de}function b(O){switch(O.getDay()){case 0:return new Date(O.getFullYear()-1,11,29);case 1:return O;case 2:return new Date(O.getFullYear(),0,3);case 3:return new Date(O.getFullYear(),0,2);case 4:return new Date(O.getFullYear(),0,1);case 5:return new Date(O.getFullYear()-1,11,31);case 6:return new Date(O.getFullYear()-1,11,30)}}function x(O){var F=O.Kh;for(O=new Date(new Date(O.Lh+1900,0,1).getTime());0de-O.getDate())F-=de-O.getDate()+1,O.setDate(1),11>J?O.setMonth(J+1):(O.setMonth(0),O.setFullYear(O.getFullYear()+1));else{O.setDate(O.getDate()+F);break}}return J=new Date(O.getFullYear()+1,0,4),F=b(new Date(O.getFullYear(),0,4)),J=b(J),0>=w(F,O)?0>=w(J,O)?O.getFullYear()+1:O.getFullYear():O.getFullYear()-1}s>>>=0,l>>>=0,u>>>=0,p>>>=0;var E=ne[p+40>>>2>>>0];p={ji:U[p>>>2>>>0],ii:U[p+4>>>2>>>0],Qh:U[p+8>>>2>>>0],Th:U[p+12>>>2>>>0],Rh:U[p+16>>>2>>>0],Lh:U[p+20>>>2>>>0],Jh:U[p+24>>>2>>>0],Kh:U[p+28>>>2>>>0],li:U[p+32>>>2>>>0],hi:U[p+36>>>2>>>0],ki:E?et(E):""},u=et(u),E={"%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 T in E)u=u.replace(new RegExp(T,"g"),E[T]);var P="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),D="January February March April May June July August September October November December".split(" ");E={"%a":O=>P[O.Jh].substring(0,3),"%A":O=>P[O.Jh],"%b":O=>D[O.Rh].substring(0,3),"%B":O=>D[O.Rh],"%C":O=>g((O.Lh+1900)/100|0,2),"%d":O=>g(O.Th,2),"%e":O=>f(O.Th,2," "),"%g":O=>x(O).toString().substring(2),"%G":x,"%H":O=>g(O.Qh,2),"%I":O=>(O=O.Qh,O==0?O=12:12{for(var F=0,J=0;J<=O.Rh-1;F+=(Cr(O.Lh+1900)?Bi:nn)[J++]);return g(O.Th+F,3)},"%m":O=>g(O.Rh+1,2),"%M":O=>g(O.ii,2),"%n":()=>` `,"%p":O=>0<=O.Qh&&12>O.Qh?"AM":"PM","%S":O=>g(O.ji,2),"%t":()=>" ","%u":O=>O.Jh||7,"%U":O=>g(Math.floor((O.Kh+7-O.Jh)/7),2),"%V":O=>{var F=Math.floor((O.Kh+7-(O.Jh+6)%7)/7);if(2>=(O.Jh+371-O.Kh-2)%7&&F++,F)F==53&&(J=(O.Jh+371-O.Kh)%7,J==4||J==3&&Cr(O.Lh)||(F=1));else{F=52;var J=(O.Jh+7-O.Kh-1)%7;(J==4||J==5&&Cr(O.Lh%400-1))&&F++}return g(F,2)},"%w":O=>O.Jh,"%W":O=>g(Math.floor((O.Kh+7-(O.Jh+6)%7)/7),2),"%y":O=>(O.Lh+1900).toString().substring(2),"%Y":O=>O.Lh+1900,"%z":O=>{O=O.hi;var F=0<=O;return O=Math.abs(O)/60,(F?"+":"-")+("0000"+(O/60*100+O%60)).slice(-4)},"%Z":O=>O.ki,"%%":()=>"%"},u=u.replace(/%%/g,"\0\0");for(T in E)u.includes(T)&&(u=u.replace(new RegExp(T,"g"),E[T](p)));return u=u.replace(/\0\0/g,"%"),T=ol(u),T.length>l?0:(fe.set(T,s>>>0),T.length-1)}for(var Nt=Array(256),an=0;256>an;++an)Nt[an]=String.fromCharCode(an);xi=Nt,gt=i.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},i.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},Ht.push(0,1,void 0,1,null,1,!0,1,!1,1),i.count_emval_handles=()=>Ht.length/2-5-zr.length;var Mn={bd:function(s,l,u){return Ti(async()=>{await i.bi(s,l,u)})},v:function(s){if(s=new $i(s>>>0),fe[s.Ih+12>>>0]==0&&(fe[s.Ih+12>>>0]=1,sr--),fe[s.Ih+13>>>0]=0,Zr.push(s),ys(s.Nh),on(ne[s.Ih+4>>>2>>>0]))s=ne[s.Nh>>>2>>>0];else{var l=ne[s.Ih+16>>>2>>>0];s=l!==0?l:s.Nh}return s},N:()=>{W(0,0);var s=Zr.pop();gs(s.Nh),or=0},a:function(){return Jr([])},m:function(s){return Jr([s>>>0])},x:function(s,l){return Jr([s>>>0,l>>>0])},q:function(s,l,u){return Jr([s>>>0,l>>>0,u>>>0])},Bb:()=>{var s=Zr.pop();s||rt("no exception to throw");var l=s.Nh;throw fe[s.Ih+13>>>0]==0&&(Zr.push(s),fe[s.Ih+13>>>0]=1,fe[s.Ih+12>>>0]=0,sr++),or=l,or},s:function(s,l,u){s>>>=0;var p=new $i(s);throw ne[p.Ih+16>>>2>>>0]=0,ne[p.Ih+4>>>2>>>0]=l>>>0,ne[p.Ih+8>>>2>>>0]=u>>>0,or=s,sr++,or},fb:()=>sr,g:function(s){throw or||(or=s>>>0),or},Cb:function(){return 0},$c:function(){},Mc:function(){},Oc:function(){},Gc:function(){return 0},Zc:function(){},Uc:function(){},Yc:function(){},_b:function(){},Nc:function(){},Kc:function(){},_c:function(){},Lc:function(){},Wb:function(s,l,u){l=Rt(l>>>0),Bt(s>>>0,{name:l,fromWireType:p=>p,toWireType:function(p,f){if(typeof f!="bigint"&&typeof f!="number")throw f===null?f="null":(p=typeof f,f=p==="object"||p==="array"||p==="function"?f.toString():""+f),new TypeError(`Cannot convert "${f}" to ${this.name}`);return typeof f=="number"&&(f=BigInt(f)),f},argPackAdvance:8,readValueFromPointer:Ie(l,u>>>0,l.indexOf("u")==-1),Mh:null})},Ec:function(s,l,u,p){l=Rt(l>>>0),Bt(s>>>0,{name:l,fromWireType:function(f){return!!f},toWireType:function(f,g){return g?u:p},argPackAdvance:8,readValueFromPointer:function(f){return this.fromWireType(me[f>>>0])},Mh:null})},Cc:function(s){return Bt(s>>>0,Ja)},Vb:function(s,l,u){l=Rt(l>>>0),Bt(s>>>0,{name:l,fromWireType:p=>p,toWireType:(p,f)=>f,argPackAdvance:8,readValueFromPointer:es(l,u>>>0),Mh:null})},Aa:function(s,l,u,p,f){if(s>>>=0,u>>>=0,l=Rt(l>>>0),f===-1&&(f=4294967295),f=b=>b,p===0){var g=32-8*u;f=b=>b<>>g}var w=l.includes("unsigned")?function(b,x){return x>>>0}:function(b,x){return x};Bt(s,{name:l,fromWireType:f,toWireType:w,argPackAdvance:8,readValueFromPointer:Ie(l,u,p!==0),Mh:null})},_:function(s,l,u){function p(g){return new f(fe.buffer,ne[g+4>>>2>>>0],ne[g>>>2>>>0])}var f=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][l];u=Rt(u>>>0),Bt(s>>>0,{name:u,fromWireType:p,argPackAdvance:8,readValueFromPointer:p},{Xh:!0})},Xb:function(s,l){l=Rt(l>>>0);var u=l==="std::string";Bt(s>>>0,{name:l,fromWireType:function(p){var f=ne[p>>>2>>>0],g=p+4;if(u)for(var w=g,b=0;b<=f;++b){var x=g+b;if(b==f||me[x>>>0]==0){if(w=et(w,x-w),E===void 0)var E=w;else E+="\0",E+=w;w=x+1}}else{for(E=Array(f),b=0;b>>0]);E=E.join("")}return Mt(p),E},toWireType:function(p,f){f instanceof ArrayBuffer&&(f=new Uint8Array(f));var g=typeof f=="string";if(!(g||f instanceof Uint8Array||f instanceof Uint8ClampedArray||f instanceof Int8Array))throw new gt("Cannot pass non-string to std::string");var w=u&&g?Or(f):f.length,b=On(4+w+1),x=b+4;if(ne[b>>>2>>>0]=w,u&&g)lr(f,me,x,w+1);else if(g)for(g=0;g>>0]=E}else for(g=0;g>>0]=f[g];return p!==null&&p.push(Mt,b),b},argPackAdvance:8,readValueFromPointer:Cn,Mh(p){Mt(p)}})},Ab:function(s,l,u){if(l>>>=0,u>>>=0,u=Rt(u),l===2)var p=ts,f=rs,g=ns,w=b=>X[b>>>1>>>0];else l===4&&(p=is,f=as,g=ss,w=b=>ne[b>>>2>>>0]);Bt(s>>>0,{name:u,fromWireType:b=>{for(var x=ne[b>>>2>>>0],E,T=b+4,P=0;P<=x;++P){var D=b+4+P*l;(P==x||w(D)==0)&&(T=p(T,D-T),E===void 0?E=T:(E+="\0",E+=T),T=D+l)}return Mt(b),E},toWireType:(b,x)=>{if(typeof x!="string")throw new gt(`Cannot pass non-string to C++ string type ${u}`);var E=g(x),T=On(4+E+l);return ne[T>>>2>>>0]=E/l,f(x,T+4,E+l),b!==null&&b.push(Mt,T),T},argPackAdvance:8,readValueFromPointer:Cn,Mh(b){Mt(b)}})},Fc:function(s,l){l=Rt(l>>>0),Bt(s>>>0,{Yh:!0,name:l,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ad:()=>1,kd:function(s,l,u){return l>>>=0,u>>>=0,s=yt(s>>>0),l=En(l,"emval::as"),Si(l,u,s)},Cd:function(s){return s>>>=0,Ti(()=>(s=yt(s),s.then(At)))},ud:function(s,l,u,p){return u>>>=0,p>>>=0,s=Tn[s>>>0],l=yt(l>>>0),s(null,l,u,p)},ia:function(s,l,u,p,f){return u>>>=0,p>>>=0,f>>>=0,s=Tn[s>>>0],l=yt(l>>>0),u=rn(u),s(l,l[u],p,f)},Bc:Ci,qd:function(s,l){return l>>>=0,s=yt(s>>>0),l=yt(l),s==l},zd:function(s){return s>>>=0,s===0?At(In()):(s=rn(s),At(In()[s]))},ha:function(s,l,u){l=Ii(s,l>>>0);var p=l.shift();s--;var f=`return function (obj, func, destructorsRef, args) { `,g=0,w=[];u===0&&w.push("obj");for(var b=["retType"],x=[p],E=0;ET.name).join(", ")}) => ${p.name}>`,hs(Ai(u,s))},yd:function(s,l){return l>>>=0,s=yt(s>>>0),l=yt(l),At(s[l])},ba:function(s){s>>>=0,9>>0);for(var l=Array(s.length),u=0;u>>0))},Xa:function(){return At({})},vd:function(s){s>>>=0;for(var l=yt(s);l.length;){var u=l.pop();l.pop()(u)}Ci(s)},sd:function(s,l,u){l>>>=0,u>>>=0,s=yt(s>>>0),l=yt(l),u=yt(u),s[l]=u},zb:function(s,l){return l>>>=0,s=En(s>>>0,"_emval_take_value"),s=s.readValueFromPointer(l),At(s)},Rc:function(s,l){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),U[l>>>2>>>0]=s.getUTCSeconds(),U[l+4>>>2>>>0]=s.getUTCMinutes(),U[l+8>>>2>>>0]=s.getUTCHours(),U[l+12>>>2>>>0]=s.getUTCDate(),U[l+16>>>2>>>0]=s.getUTCMonth(),U[l+20>>>2>>>0]=s.getUTCFullYear()-1900,U[l+24>>>2>>>0]=s.getUTCDay(),U[l+28>>>2>>>0]=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Sc:function(s,l){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),U[l>>>2>>>0]=s.getSeconds(),U[l+4>>>2>>>0]=s.getMinutes(),U[l+8>>>2>>>0]=s.getHours(),U[l+12>>>2>>>0]=s.getDate(),U[l+16>>>2>>>0]=s.getMonth(),U[l+20>>>2>>>0]=s.getFullYear()-1900,U[l+24>>>2>>>0]=s.getDay(),U[l+28>>>2>>>0]=(Cr(s.getFullYear())?Mi:Oi)[s.getMonth()]+s.getDate()-1|0,U[l+36>>>2>>>0]=-(60*s.getTimezoneOffset());var u=new Date(s.getFullYear(),6,1).getTimezoneOffset(),p=new Date(s.getFullYear(),0,1).getTimezoneOffset();U[l+32>>>2>>>0]=(u!=p&&s.getTimezoneOffset()==Math.min(p,u))|0},Tc:function(s){s>>>=0;var l=new Date(U[s+20>>>2>>>0]+1900,U[s+16>>>2>>>0],U[s+12>>>2>>>0],U[s+8>>>2>>>0],U[s+4>>>2>>>0],U[s>>>2>>>0],0),u=U[s+32>>>2>>>0],p=l.getTimezoneOffset(),f=new Date(l.getFullYear(),6,1).getTimezoneOffset(),g=new Date(l.getFullYear(),0,1).getTimezoneOffset(),w=Math.min(g,f);return 0>u?U[s+32>>>2>>>0]=+(f!=g&&w==p):0>>2>>>0]=l.getDay(),U[s+28>>>2>>>0]=(Cr(l.getFullYear())?Mi:Oi)[l.getMonth()]+l.getDate()-1|0,U[s>>>2>>>0]=l.getSeconds(),U[s+4>>>2>>>0]=l.getMinutes(),U[s+8>>>2>>>0]=l.getHours(),U[s+12>>>2>>>0]=l.getDate(),U[s+16>>>2>>>0]=l.getMonth(),U[s+20>>>2>>>0]=l.getYear(),s=l.getTime(),BigInt(isNaN(s)?-1:s/1e3)},Pc:function(){return-52},Qc:function(){},Ic:function(s,l,u,p){u>>>=0,p>>>=0;var f=new Date().getFullYear(),g=new Date(f,0,1),w=new Date(f,6,1);f=g.getTimezoneOffset();var b=w.getTimezoneOffset();ne[s>>>0>>>2>>>0]=60*Math.max(f,b),U[l>>>0>>>2>>>0]=+(f!=b),s=x=>x.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],g=s(g),w=s(w),b{rt("")},A:function(s,l,u){return s>>>=0,l=Pi(l>>>0,u>>>0),bi[s](...l)},bc:function(s,l,u){return s>>>=0,l=Pi(l>>>0,u>>>0),bi[s](...l)},$b:()=>Date.now(),Jc:function(){return 4294901760},ga:()=>performance.now(),Hc:function(s){s>>>=0;var l=me.length;if(4294901760=u;u*=2){var p=l*(1+.2/u);p=Math.min(p,s+100663296);var f=Math;p=Math.max(s,p);e:{f=(f.min.call(f,4294901760,p+(65536-p%65536)%65536)-pe.buffer.byteLength+65535)/65536;try{pe.grow(f),he();var g=1;break e}catch{}g=void 0}if(g)return!0}return!1},Wc:function(s,l){s>>>=0,l>>>=0;var u=0;return ji().forEach((p,f)=>{var g=l+u;for(f=ne[s+4*f>>>2>>>0]=g,g=0;g>>0]=p.charCodeAt(g);fe[f>>>0]=0,u+=p.length+1}),0},Xc:function(s,l){s>>>=0,l>>>=0;var u=ji();ne[s>>>2>>>0]=u.length;var p=0;return u.forEach(f=>p+=f.length+1),ne[l>>>2>>>0]=p,0},Db:()=>52,Zb:function(){return 52},Vc:function(){return 70},Yb:function(s,l,u,p){l>>>=0,u>>>=0,p>>>=0;for(var f=0,g=0;g>>2>>>0],b=ne[l+4>>>2>>>0];l+=8;for(var x=0;x>>0],T=sl[s];E===0||E===10?((s===1?Q:ie)($r(T,0)),T.length=0):T.push(E)}f+=b}return ne[p>>>2>>>0]=f,0},xb:jE,cd:o3,ua:oT,W:QT,$:XT,ra:Rk,ta:zE,dd:s3,ob:sT,P:fk,z:_E,b:tE,Ub:hE,ya:fE,e:JS,kb:KT,h:ZS,X:RT,i:oE,ed:i3,j:sE,t:aE,r:CE,o:AE,Wa:NE,Ca:bT,ma:EE,Qb:ck,db:mk,Ib:$T,mb:cT,kc:DT,xc:FE,hc:FT,ic:LT,ac:n3,oa:Uk,yb:IE,Ba:jT,Eb:t3,ea:Fk,jc:NT,Ta:yk,F:nE,G:ek,Gb:BT,jd:UT,qa:tT,O:ik,V:tk,T:wk,y:mE,Fb:HT,gc:WT,D:TT,Hb:MT,id:GT,Ua:hk,wa:Kk,lc:OT,cc:r3,Nb:Dk,aa:PE,I:gE,C:qE,_a:IT,fc:VT,Q:nk,d:iE,ab:sk,n:rE,Ya:qT,va:aT,wb:WE,f:eE,yc:UE,da:PT,gb:lk,Da:Bk,lb:pT,hb:VE,c:lE,vc:YE,od:xT,k:uE,tc:ok,l:dE,wc:HE,sc:uk,rd:fT,p:cE,Ra:Ck,tb:xk,Qa:Sk,Kb:lT,B:SE,K:yE,S:kE,$a:CT,pc:eT,ub:ak,za:_k,ka:pE,xa:pk,Sb:TE,La:rT,jb:a3,Ga:yT,nc:_T,Ha:gT,Ia:hT,fd:e3,xd:dk,Z:Ok,pa:iT,pd:vT,wd:bk,Mb:Nk,Ma:Zk,Ka:nT,Tb:bE,rc:Wk,Ja:uT,Na:Xk,pb:Lk,la:Yk,Ea:vk,mc:AT,qc:Hk,Jb:wT,Fa:ET,ja:ZE,Ad:BE,nd:ST,R:Vk,eb:xE,Za:zT,ec:ZT,ib:GE,E:OE,M:vE,Va:LE,ld:kT,ca:DE,nb:dT,na:qk,dc:JT,Ac:$E,u:wE,L:QE,td:Jk,Pb:Ak,oc:mT,Bd:RE,Ob:Mk,Lb:Gk,cb:gk,zc:ME,Rb:JE,Oa:Qk,Y:zk,uc:XE,J:rk,gd:YT,vb:KE,sa:jk,H:Pk,rb:Tk,Pa:kk,Sa:$k,sb:Ek,qb:Ik,w:function(s){return s>>>0},Dc:dr,fa:function(s,l,u,p){return dr(s>>>0,l>>>0,u>>>0,p>>>0)}},N=function(){function s(u){return N=u.exports,N=ls(),N=l3(),pe=N.Dd,he(),Le.unshift(N.Ed),ct--,ct==0&&pt&&(u=pt,pt=null,u()),N}var l={a:Mn};if(ct++,i.instantiateWasm)try{return i.instantiateWasm(l,s)}catch(u){ie(`Module.instantiateWasm callback failed with error: ${u}`),h(u)}return bn(l,function(u){s(u.instance)}).catch(h),{}}(),Di=s=>(Di=N.Fd)(s);i._OrtInit=(s,l)=>(i._OrtInit=N.Gd)(s,l),i._OrtGetLastError=(s,l)=>(i._OrtGetLastError=N.Hd)(s,l),i._OrtCreateSessionOptions=(s,l,u,p,f,g,w,b,x,E)=>(i._OrtCreateSessionOptions=N.Id)(s,l,u,p,f,g,w,b,x,E),i._OrtAppendExecutionProvider=(s,l)=>(i._OrtAppendExecutionProvider=N.Jd)(s,l),i._OrtAddFreeDimensionOverride=(s,l,u)=>(i._OrtAddFreeDimensionOverride=N.Kd)(s,l,u),i._OrtAddSessionConfigEntry=(s,l,u)=>(i._OrtAddSessionConfigEntry=N.Ld)(s,l,u),i._OrtReleaseSessionOptions=s=>(i._OrtReleaseSessionOptions=N.Md)(s),i._OrtCreateSession=(s,l,u)=>(i._OrtCreateSession=N.Nd)(s,l,u),i._OrtReleaseSession=s=>(i._OrtReleaseSession=N.Od)(s),i._OrtGetInputOutputCount=(s,l,u)=>(i._OrtGetInputOutputCount=N.Pd)(s,l,u),i._OrtGetInputName=(s,l)=>(i._OrtGetInputName=N.Qd)(s,l),i._OrtGetOutputName=(s,l)=>(i._OrtGetOutputName=N.Rd)(s,l),i._OrtFree=s=>(i._OrtFree=N.Sd)(s),i._OrtCreateTensor=(s,l,u,p,f,g)=>(i._OrtCreateTensor=N.Td)(s,l,u,p,f,g),i._OrtGetTensorData=(s,l,u,p,f)=>(i._OrtGetTensorData=N.Ud)(s,l,u,p,f),i._OrtReleaseTensor=s=>(i._OrtReleaseTensor=N.Vd)(s),i._OrtCreateRunOptions=(s,l,u,p)=>(i._OrtCreateRunOptions=N.Wd)(s,l,u,p),i._OrtAddRunConfigEntry=(s,l,u)=>(i._OrtAddRunConfigEntry=N.Xd)(s,l,u),i._OrtReleaseRunOptions=s=>(i._OrtReleaseRunOptions=N.Yd)(s),i._OrtCreateBinding=s=>(i._OrtCreateBinding=N.Zd)(s),i._OrtBindInput=(s,l,u)=>(i._OrtBindInput=N._d)(s,l,u),i._OrtBindOutput=(s,l,u,p)=>(i._OrtBindOutput=N.$d)(s,l,u,p),i._OrtClearBoundOutputs=s=>(i._OrtClearBoundOutputs=N.ae)(s),i._OrtReleaseBinding=s=>(i._OrtReleaseBinding=N.be)(s),i._OrtRunWithBinding=(s,l,u,p,f)=>(i._OrtRunWithBinding=N.ce)(s,l,u,p,f),i._OrtRun=(s,l,u,p,f,g,w,b)=>(i._OrtRun=N.de)(s,l,u,p,f,g,w,b),i._OrtEndProfiling=s=>(i._OrtEndProfiling=N.ee)(s),i._JsepOutput=(s,l,u)=>(i._JsepOutput=N.fe)(s,l,u),i._JsepGetNodeName=s=>(i._JsepGetNodeName=N.ge)(s);var On=i._malloc=s=>(On=i._malloc=N.he)(s),Mt=i._free=s=>(Mt=i._free=N.ie)(s),W=(s,l)=>(W=N.ke)(s,l),sn=s=>(sn=N.le)(s),G=s=>(G=N.me)(s),ms=s=>(ms=N.ne)(s),V=()=>(V=N.oe)(),gs=s=>(gs=N.pe)(s),ys=s=>(ys=N.qe)(s),_s=(s,l,u)=>(_s=N.re)(s,l,u),on=s=>(on=N.se)(s),zn=i.dynCall_vii=(s,l,u)=>(zn=i.dynCall_vii=N.te)(s,l,u),Ni=i.dynCall_iiii=(s,l,u,p)=>(Ni=i.dynCall_iiii=N.ue)(s,l,u,p),Li=i.dynCall_iii=(s,l,u)=>(Li=i.dynCall_iii=N.ve)(s,l,u),Ui=i.dynCall_ii=(s,l)=>(Ui=i.dynCall_ii=N.we)(s,l),Pn=i.dynCall_iiiiiii=(s,l,u,p,f,g,w)=>(Pn=i.dynCall_iiiiiii=N.xe)(s,l,u,p,f,g,w),jn=i.dynCall_vi=(s,l)=>(jn=i.dynCall_vi=N.ye)(s,l),Fi=i.dynCall_v=s=>(Fi=i.dynCall_v=N.ze)(s),Wi=i.dynCall_iiiiii=(s,l,u,p,f,g)=>(Wi=i.dynCall_iiiiii=N.Ae)(s,l,u,p,f,g),Gi=i.dynCall_iiij=(s,l,u,p)=>(Gi=i.dynCall_iiij=N.Be)(s,l,u,p),Rn=i.dynCall_iiiii=(s,l,u,p,f)=>(Rn=i.dynCall_iiiii=N.Ce)(s,l,u,p,f),ln=i.dynCall_viii=(s,l,u,p)=>(ln=i.dynCall_viii=N.De)(s,l,u,p),Bn=i.dynCall_viiiii=(s,l,u,p,f,g)=>(Bn=i.dynCall_viiiii=N.Ee)(s,l,u,p,f,g),Vi=i.dynCall_viiii=(s,l,u,p,f)=>(Vi=i.dynCall_viiii=N.Fe)(s,l,u,p,f),Hi=i.dynCall_viiiiii=(s,l,u,p,f,g,w)=>(Hi=i.dynCall_viiiiii=N.Ge)(s,l,u,p,f,g,w),qi=i.dynCall_viiji=(s,l,u,p,f)=>(qi=i.dynCall_viiji=N.He)(s,l,u,p,f),Ki=i.dynCall_viiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P)=>(Ki=i.dynCall_viiiiiiiiiii=N.Ie)(s,l,u,p,f,g,w,b,x,E,T,P),Yi=i.dynCall_viiijjjii=(s,l,u,p,f,g,w,b,x)=>(Yi=i.dynCall_viiijjjii=N.Je)(s,l,u,p,f,g,w,b,x),ws=i.dynCall_iid=(s,l,u)=>(ws=i.dynCall_iid=N.Ke)(s,l,u),un=i.dynCall_iif=(s,l,u)=>(un=i.dynCall_iif=N.Le)(s,l,u),Qi=i.dynCall_iij=(s,l,u)=>(Qi=i.dynCall_iij=N.Me)(s,l,u),y=i.dynCall_jii=(s,l,u)=>(y=i.dynCall_jii=N.Ne)(s,l,u),S=i.dynCall_i=s=>(S=i.dynCall_i=N.Oe)(s),A=i.dynCall_viiiiiiii=(s,l,u,p,f,g,w,b,x)=>(A=i.dynCall_viiiiiiii=N.Pe)(s,l,u,p,f,g,w,b,x),B=i.dynCall_viiiiij=(s,l,u,p,f,g,w)=>(B=i.dynCall_viiiiij=N.Qe)(s,l,u,p,f,g,w),H=i.dynCall_ji=(s,l)=>(H=i.dynCall_ji=N.Re)(s,l),re=i.dynCall_viij=(s,l,u,p)=>(re=i.dynCall_viij=N.Se)(s,l,u,p),ae=i.dynCall_iiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P)=>(ae=i.dynCall_iiiiiiiiiiii=N.Te)(s,l,u,p,f,g,w,b,x,E,T,P),be=i.dynCall_viiiiiiiii=(s,l,u,p,f,g,w,b,x,E)=>(be=i.dynCall_viiiiiiiii=N.Ue)(s,l,u,p,f,g,w,b,x,E),we=i.dynCall_ij=(s,l)=>(we=i.dynCall_ij=N.Ve)(s,l),ye=i.dynCall_iiiiij=(s,l,u,p,f,g)=>(ye=i.dynCall_iiiiij=N.We)(s,l,u,p,f,g),xe=i.dynCall_j=s=>(xe=i.dynCall_j=N.Xe)(s),Ne=i.dynCall_vij=(s,l,u)=>(Ne=i.dynCall_vij=N.Ye)(s,l,u),We=i.dynCall_viijjjiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P)=>(We=i.dynCall_viijjjiiiiii=N.Ze)(s,l,u,p,f,g,w,b,x,E,T,P),q=i.dynCall_viiijiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P)=>(q=i.dynCall_viiijiiiiiii=N._e)(s,l,u,p,f,g,w,b,x,E,T,P),Me=i.dynCall_iiiiiiii=(s,l,u,p,f,g,w,b)=>(Me=i.dynCall_iiiiiiii=N.$e)(s,l,u,p,f,g,w,b),Ve=i.dynCall_viiiiiii=(s,l,u,p,f,g,w,b)=>(Ve=i.dynCall_viiiiiii=N.af)(s,l,u,p,f,g,w,b),hr=i.dynCall_iiiiiiiij=(s,l,u,p,f,g,w,b,x)=>(hr=i.dynCall_iiiiiiiij=N.bf)(s,l,u,p,f,g,w,b,x),Xi=i.dynCall_viiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>(Xi=i.dynCall_viiiiiiiiiiiii=N.cf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O),Rg=i.dynCall_iiiiiiiii=(s,l,u,p,f,g,w,b,x)=>(Rg=i.dynCall_iiiiiiiii=N.df)(s,l,u,p,f,g,w,b,x),Bg=i.dynCall_iiiiijiiiii=(s,l,u,p,f,g,w,b,x,E,T)=>(Bg=i.dynCall_iiiiijiiiii=N.ef)(s,l,u,p,f,g,w,b,x,E,T),Dg=i.dynCall_vijjjiiij=(s,l,u,p,f,g,w,b,x)=>(Dg=i.dynCall_vijjjiiij=N.ff)(s,l,u,p,f,g,w,b,x),Ng=i.dynCall_fi=(s,l)=>(Ng=i.dynCall_fi=N.gf)(s,l),Lg=i.dynCall_fii=(s,l,u)=>(Lg=i.dynCall_fii=N.hf)(s,l,u),Ug=i.dynCall_di=(s,l)=>(Ug=i.dynCall_di=N.jf)(s,l),Fg=i.dynCall_dii=(s,l,u)=>(Fg=i.dynCall_dii=N.kf)(s,l,u),Wg=i.dynCall_vijj=(s,l,u,p)=>(Wg=i.dynCall_vijj=N.lf)(s,l,u,p),Gg=i.dynCall_iiiiiiiiii=(s,l,u,p,f,g,w,b,x,E)=>(Gg=i.dynCall_iiiiiiiiii=N.mf)(s,l,u,p,f,g,w,b,x,E),Vg=i.dynCall_viijiii=(s,l,u,p,f,g,w)=>(Vg=i.dynCall_viijiii=N.nf)(s,l,u,p,f,g,w),Hg=i.dynCall_viid=(s,l,u,p)=>(Hg=i.dynCall_viid=N.of)(s,l,u,p),qg=i.dynCall_viffiii=(s,l,u,p,f,g,w)=>(qg=i.dynCall_viffiii=N.pf)(s,l,u,p,f,g,w),Kg=i.dynCall_viifiii=(s,l,u,p,f,g,w)=>(Kg=i.dynCall_viifiii=N.qf)(s,l,u,p,f,g,w),Yg=i.dynCall_viiiiidiidi=(s,l,u,p,f,g,w,b,x,E,T)=>(Yg=i.dynCall_viiiiidiidi=N.rf)(s,l,u,p,f,g,w,b,x,E,T),Qg=i.dynCall_viiiiiiiiidi=(s,l,u,p,f,g,w,b,x,E,T,P)=>(Qg=i.dynCall_viiiiiiiiidi=N.sf)(s,l,u,p,f,g,w,b,x,E,T,P),Xg=i.dynCall_jiii=(s,l,u,p)=>(Xg=i.dynCall_jiii=N.tf)(s,l,u,p),Zg=i.dynCall_vjiiiiii=(s,l,u,p,f,g,w,b)=>(Zg=i.dynCall_vjiiiiii=N.uf)(s,l,u,p,f,g,w,b),Jg=i.dynCall_viiid=(s,l,u,p,f)=>(Jg=i.dynCall_viiid=N.vf)(s,l,u,p,f),ey=i.dynCall_viiiiiiiiiji=(s,l,u,p,f,g,w,b,x,E,T,P)=>(ey=i.dynCall_viiiiiiiiiji=N.wf)(s,l,u,p,f,g,w,b,x,E,T,P),ty=i.dynCall_viji=(s,l,u,p)=>(ty=i.dynCall_viji=N.xf)(s,l,u,p),ry=i.dynCall_vijjjjjjjjjjjjji=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>(ry=i.dynCall_vijjjjjjjjjjjjji=N.yf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J),ny=i.dynCall_viiiji=(s,l,u,p,f,g)=>(ny=i.dynCall_viiiji=N.zf)(s,l,u,p,f,g),iy=i.dynCall_vijjjiiji=(s,l,u,p,f,g,w,b,x)=>(iy=i.dynCall_vijjjiiji=N.Af)(s,l,u,p,f,g,w,b,x),ay=i.dynCall_iiiji=(s,l,u,p,f)=>(ay=i.dynCall_iiiji=N.Bf)(s,l,u,p,f),sy=i.dynCall_iiijiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>(sy=i.dynCall_iiijiiiiiiiiii=N.Cf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O),oy=i.dynCall_vj=(s,l)=>(oy=i.dynCall_vj=N.Df)(s,l),ly=i.dynCall_jjj=(s,l,u)=>(ly=i.dynCall_jjj=N.Ef)(s,l,u),uy=i.dynCall_iiijiiiiii=(s,l,u,p,f,g,w,b,x,E)=>(uy=i.dynCall_iiijiiiiii=N.Ff)(s,l,u,p,f,g,w,b,x,E),dy=i.dynCall_vfiii=(s,l,u,p,f)=>(dy=i.dynCall_vfiii=N.Gf)(s,l,u,p,f),cy=i.dynCall_viiiiff=(s,l,u,p,f,g,w)=>(cy=i.dynCall_viiiiff=N.Hf)(s,l,u,p,f,g,w),py=i.dynCall_viiiiiff=(s,l,u,p,f,g,w,b)=>(py=i.dynCall_viiiiiff=N.If)(s,l,u,p,f,g,w,b),hy=i.dynCall_viiff=(s,l,u,p,f)=>(hy=i.dynCall_viiff=N.Jf)(s,l,u,p,f),fy=i.dynCall_viiiiiiiiifiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>(fy=i.dynCall_viiiiiiiiifiii=N.Kf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O),my=i.dynCall_viiiiiiiijj=(s,l,u,p,f,g,w,b,x,E,T)=>(my=i.dynCall_viiiiiiiijj=N.Lf)(s,l,u,p,f,g,w,b,x,E,T),gy=i.dynCall_iiiiiiiiiiiiiifii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de)=>(gy=i.dynCall_iiiiiiiiiiiiiifii=N.Mf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de),yy=i.dynCall_viiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(yy=i.dynCall_viiiiiiiiiiii=N.Nf)(s,l,u,p,f,g,w,b,x,E,T,P,D),_y=i.dynCall_iiiiiiiiiiiiiiiiifii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De)=>(_y=i.dynCall_iiiiiiiiiiiiiiiiifii=N.Of)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De),wy=i.dynCall_vijjiiiiii=(s,l,u,p,f,g,w,b,x,E)=>(wy=i.dynCall_vijjiiiiii=N.Pf)(s,l,u,p,f,g,w,b,x,E),vy=i.dynCall_iiiijjj=(s,l,u,p,f,g,w)=>(vy=i.dynCall_iiiijjj=N.Qf)(s,l,u,p,f,g,w),by=i.dynCall_viiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T)=>(by=i.dynCall_viiiiiiiiii=N.Rf)(s,l,u,p,f,g,w,b,x,E,T),$y=i.dynCall_iiijjj=(s,l,u,p,f,g)=>($y=i.dynCall_iiijjj=N.Sf)(s,l,u,p,f,g),xy=i.dynCall_fffffff=(s,l,u,p,f,g,w)=>(xy=i.dynCall_fffffff=N.Tf)(s,l,u,p,f,g,w),Cy=i.dynCall_viiiij=(s,l,u,p,f,g)=>(Cy=i.dynCall_viiiij=N.Uf)(s,l,u,p,f,g),Sy=i.dynCall_viiiiiijiifiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>(Sy=i.dynCall_viiiiiijiifiii=N.Vf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O),Ey=i.dynCall_vjjjjjjffjifiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e)=>(Ey=i.dynCall_vjjjjjjffjifiiiiii=N.Wf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e),ky=i.dynCall_viiiiiiffjifiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de)=>(ky=i.dynCall_viiiiiiffjifiiiii=N.Xf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de),Ty=i.dynCall_viiiiiiffjfiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>(Ty=i.dynCall_viiiiiiffjfiiiii=N.Yf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J),Iy=i.dynCall_viiiiiiffjiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)=>(Iy=i.dynCall_viiiiiiffjiiiii=N.Zf)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F),Ay=i.dynCall_vjjjjjjjjfffiiifiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe)=>(Ay=i.dynCall_vjjjjjjjjfffiiifiiiii=N._f)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe),My=i.dynCall_vjjjjjjfffifijiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke)=>(My=i.dynCall_vjjjjjjfffifijiiiii=N.$f)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke),Oy=i.dynCall_vjjjjjjfffifiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e)=>(Oy=i.dynCall_vjjjjjjfffifiiiiii=N.ag)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e),zy=i.dynCall_vjjjjjjjjfffjifiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe)=>(zy=i.dynCall_vjjjjjjjjfffjifiiiiii=N.bg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe),Py=i.dynCall_vijiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(Py=i.dynCall_vijiiiiiiiiii=N.cg)(s,l,u,p,f,g,w,b,x,E,T,P,D),jy=i.dynCall_vijjfffiii=(s,l,u,p,f,g,w,b,x,E)=>(jy=i.dynCall_vijjfffiii=N.dg)(s,l,u,p,f,g,w,b,x,E),Ry=i.dynCall_viiiiiiijiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(Ry=i.dynCall_viiiiiiijiiii=N.eg)(s,l,u,p,f,g,w,b,x,E,T,P,D),By=i.dynCall_vijjjjjjifiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)=>(By=i.dynCall_vijjjjjjifiiiii=N.fg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F),Dy=i.dynCall_viifi=(s,l,u,p,f)=>(Dy=i.dynCall_viifi=N.gg)(s,l,u,p,f),Ny=i.dynCall_vjjjjjiiii=(s,l,u,p,f,g,w,b,x,E)=>(Ny=i.dynCall_vjjjjjiiii=N.hg)(s,l,u,p,f,g,w,b,x,E),Ly=i.dynCall_vjjjjfiii=(s,l,u,p,f,g,w,b,x)=>(Ly=i.dynCall_vjjjjfiii=N.ig)(s,l,u,p,f,g,w,b,x),Uy=i.dynCall_viiiiiijiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>(Uy=i.dynCall_viiiiiijiiiiii=N.jg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O),Fy=i.dynCall_vijjii=(s,l,u,p,f,g)=>(Fy=i.dynCall_vijjii=N.kg)(s,l,u,p,f,g),Wy=i.dynCall_viiiiijjiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(Wy=i.dynCall_viiiiijjiiiii=N.lg)(s,l,u,p,f,g,w,b,x,E,T,P,D),Gy=i.dynCall_iiiiiji=(s,l,u,p,f,g,w)=>(Gy=i.dynCall_iiiiiji=N.mg)(s,l,u,p,f,g,w),Vy=i.dynCall_iiiiji=(s,l,u,p,f,g)=>(Vy=i.dynCall_iiiiji=N.ng)(s,l,u,p,f,g),Hy=i.dynCall_viiiiijiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(Hy=i.dynCall_viiiiijiiiiii=N.og)(s,l,u,p,f,g,w,b,x,E,T,P,D),qy=i.dynCall_viiijiiiiii=(s,l,u,p,f,g,w,b,x,E,T)=>(qy=i.dynCall_viiijiiiiii=N.pg)(s,l,u,p,f,g,w,b,x,E,T),Ky=i.dynCall_viijj=(s,l,u,p,f)=>(Ky=i.dynCall_viijj=N.qg)(s,l,u,p,f),Yy=i.dynCall_viiiijii=(s,l,u,p,f,g,w,b)=>(Yy=i.dynCall_viiiijii=N.rg)(s,l,u,p,f,g,w,b),Qy=i.dynCall_viijjiii=(s,l,u,p,f,g,w,b)=>(Qy=i.dynCall_viijjiii=N.sg)(s,l,u,p,f,g,w,b),Xy=i.dynCall_ijii=(s,l,u,p)=>(Xy=i.dynCall_ijii=N.tg)(s,l,u,p),Zy=i.dynCall_viiiiijjji=(s,l,u,p,f,g,w,b,x,E)=>(Zy=i.dynCall_viiiiijjji=N.ug)(s,l,u,p,f,g,w,b,x,E),Jy=i.dynCall_vijjjjiij=(s,l,u,p,f,g,w,b,x)=>(Jy=i.dynCall_vijjjjiij=N.vg)(s,l,u,p,f,g,w,b,x),e_=i.dynCall_viiiiijij=(s,l,u,p,f,g,w,b,x)=>(e_=i.dynCall_viiiiijij=N.wg)(s,l,u,p,f,g,w,b,x),t_=i.dynCall_viiiiiijij=(s,l,u,p,f,g,w,b,x,E)=>(t_=i.dynCall_viiiiiijij=N.xg)(s,l,u,p,f,g,w,b,x,E),r_=i.dynCall_vijiii=(s,l,u,p,f,g)=>(r_=i.dynCall_vijiii=N.yg)(s,l,u,p,f,g),n_=i.dynCall_viiiiiiiiifi=(s,l,u,p,f,g,w,b,x,E,T,P)=>(n_=i.dynCall_viiiiiiiiifi=N.zg)(s,l,u,p,f,g,w,b,x,E,T,P),i_=i.dynCall_iiijiiii=(s,l,u,p,f,g,w,b)=>(i_=i.dynCall_iiijiiii=N.Ag)(s,l,u,p,f,g,w,b),a_=i.dynCall_viiiiiijjiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>(a_=i.dynCall_viiiiiijjiiiii=N.Bg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O),s_=i.dynCall_viiiiiiijiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)=>(s_=i.dynCall_viiiiiiijiiiiii=N.Cg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F),o_=i.dynCall_vif=(s,l,u)=>(o_=i.dynCall_vif=N.Dg)(s,l,u),l_=i.dynCall_viif=(s,l,u,p)=>(l_=i.dynCall_viif=N.Eg)(s,l,u,p),u_=i.dynCall_fiii=(s,l,u,p)=>(u_=i.dynCall_fiii=N.Fg)(s,l,u,p),d_=i.dynCall_diii=(s,l,u,p)=>(d_=i.dynCall_diii=N.Gg)(s,l,u,p),c_=i.dynCall_viiiiiifii=(s,l,u,p,f,g,w,b,x,E)=>(c_=i.dynCall_viiiiiifii=N.Hg)(s,l,u,p,f,g,w,b,x,E),p_=i.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe,lt,St,ll,ul,dl)=>(p_=i.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=N.Ig)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe,lt,St,ll,ul,dl),h_=i.dynCall_viijji=(s,l,u,p,f,g)=>(h_=i.dynCall_viijji=N.Jg)(s,l,u,p,f,g),f_=i.dynCall_iiiiiiiiiiiji=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(f_=i.dynCall_iiiiiiiiiiiji=N.Kg)(s,l,u,p,f,g,w,b,x,E,T,P,D),m_=i.dynCall_viifiifijjjii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(m_=i.dynCall_viifiifijjjii=N.Lg)(s,l,u,p,f,g,w,b,x,E,T,P,D),g_=i.dynCall_viiiiiiiiiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe)=>(g_=i.dynCall_viiiiiiiiiiiiiiiiiiii=N.Mg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe),y_=i.dynCall_viiiiifiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(y_=i.dynCall_viiiiifiiiiii=N.Ng)(s,l,u,p,f,g,w,b,x,E,T,P,D),__=i.dynCall_vijiiiiiiijjii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O)=>(__=i.dynCall_vijiiiiiiijjii=N.Og)(s,l,u,p,f,g,w,b,x,E,T,P,D,O),w_=i.dynCall_viiiiiiiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke)=>(w_=i.dynCall_viiiiiiiiiiiiiiiiii=N.Pg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke),v_=i.dynCall_viiiiiiiiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De)=>(v_=i.dynCall_viiiiiiiiiiiiiiiiiii=N.Qg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De),b_=i.dynCall_viiiiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)=>(b_=i.dynCall_viiiiiiiiiiiiiii=N.Rg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J),$_=i.dynCall_viiiiiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de)=>($_=i.dynCall_viiiiiiiiiiiiiiii=N.Sg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de),x_=i.dynCall_viiiijjj=(s,l,u,p,f,g,w,b)=>(x_=i.dynCall_viiiijjj=N.Tg)(s,l,u,p,f,g,w,b),C_=i.dynCall_iiiiid=(s,l,u,p,f,g)=>(C_=i.dynCall_iiiiid=N.Ug)(s,l,u,p,f,g),S_=i.dynCall_viiiiiiijjj=(s,l,u,p,f,g,w,b,x,E,T)=>(S_=i.dynCall_viiiiiiijjj=N.Vg)(s,l,u,p,f,g,w,b,x,E,T),E_=i.dynCall_iiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T)=>(E_=i.dynCall_iiiiiiiiiii=N.Wg)(s,l,u,p,f,g,w,b,x,E,T),k_=i.dynCall_iiiiiiiiiiiiiiiiiifi=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De)=>(k_=i.dynCall_iiiiiiiiiiiiiiiiiifi=N.Xg)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De),T_=i.dynCall_viiif=(s,l,u,p,f)=>(T_=i.dynCall_viiif=N.Yg)(s,l,u,p,f),I_=i.dynCall_viiijiiiii=(s,l,u,p,f,g,w,b,x,E)=>(I_=i.dynCall_viiijiiiii=N.Zg)(s,l,u,p,f,g,w,b,x,E),A_=i.dynCall_viiij=(s,l,u,p,f)=>(A_=i.dynCall_viiij=N._g)(s,l,u,p,f),M_=i.dynCall_iijjj=(s,l,u,p,f)=>(M_=i.dynCall_iijjj=N.$g)(s,l,u,p,f),O_=i.dynCall_viiiiji=(s,l,u,p,f,g,w)=>(O_=i.dynCall_viiiiji=N.ah)(s,l,u,p,f,g,w),z_=i.dynCall_iijjji=(s,l,u,p,f,g)=>(z_=i.dynCall_iijjji=N.bh)(s,l,u,p,f,g),P_=i.dynCall_ijijji=(s,l,u,p,f,g)=>(P_=i.dynCall_ijijji=N.ch)(s,l,u,p,f,g),j_=i.dynCall_viiijjiii=(s,l,u,p,f,g,w,b,x)=>(j_=i.dynCall_viiijjiii=N.dh)(s,l,u,p,f,g,w,b,x),R_=i.dynCall_iiiiijji=(s,l,u,p,f,g,w,b)=>(R_=i.dynCall_iiiiijji=N.eh)(s,l,u,p,f,g,w,b),B_=i.dynCall_iiiifi=(s,l,u,p,f,g)=>(B_=i.dynCall_iiiifi=N.fh)(s,l,u,p,f,g),D_=i.dynCall_iiijii=(s,l,u,p,f,g)=>(D_=i.dynCall_iiijii=N.gh)(s,l,u,p,f,g),N_=i.dynCall_iiiiiiiiijii=(s,l,u,p,f,g,w,b,x,E,T,P)=>(N_=i.dynCall_iiiiiiiiijii=N.hh)(s,l,u,p,f,g,w,b,x,E,T,P),L_=i.dynCall_iiiijjii=(s,l,u,p,f,g,w,b)=>(L_=i.dynCall_iiiijjii=N.ih)(s,l,u,p,f,g,w,b),U_=i.dynCall_iiiiiijjjii=(s,l,u,p,f,g,w,b,x,E,T)=>(U_=i.dynCall_iiiiiijjjii=N.jh)(s,l,u,p,f,g,w,b,x,E,T),F_=i.dynCall_iiijiii=(s,l,u,p,f,g,w)=>(F_=i.dynCall_iiijiii=N.kh)(s,l,u,p,f,g,w),W_=i.dynCall_iiiiiiiijjjfi=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(W_=i.dynCall_iiiiiiiijjjfi=N.lh)(s,l,u,p,f,g,w,b,x,E,T,P,D),G_=i.dynCall_iijiiii=(s,l,u,p,f,g,w)=>(G_=i.dynCall_iijiiii=N.mh)(s,l,u,p,f,g,w),V_=i.dynCall_iijjjii=(s,l,u,p,f,g,w)=>(V_=i.dynCall_iijjjii=N.nh)(s,l,u,p,f,g,w),H_=i.dynCall_jij=(s,l,u)=>(H_=i.dynCall_jij=N.oh)(s,l,u),q_=i.dynCall_iiji=(s,l,u,p)=>(q_=i.dynCall_iiji=N.ph)(s,l,u,p),K_=i.dynCall_iiif=(s,l,u,p)=>(K_=i.dynCall_iiif=N.qh)(s,l,u,p),Y_=i.dynCall_vidi=(s,l,u,p)=>(Y_=i.dynCall_vidi=N.rh)(s,l,u,p),Q_=i.dynCall_vjiii=(s,l,u,p,f)=>(Q_=i.dynCall_vjiii=N.sh)(s,l,u,p,f),X_=i.dynCall_diiii=(s,l,u,p,f)=>(X_=i.dynCall_diiii=N.th)(s,l,u,p,f),Z_=i.dynCall_diiiii=(s,l,u,p,f,g)=>(Z_=i.dynCall_diiiii=N.uh)(s,l,u,p,f,g),J_=i.dynCall_viiijjiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P)=>(J_=i.dynCall_viiijjiiiiii=N.vh)(s,l,u,p,f,g,w,b,x,E,T,P),e0=i.dynCall_viijjijjjjiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(e0=i.dynCall_viijjijjjjiii=N.wh)(s,l,u,p,f,g,w,b,x,E,T,P,D),t0=i.dynCall_iiiij=(s,l,u,p,f)=>(t0=i.dynCall_iiiij=N.xh)(s,l,u,p,f),r0=i.dynCall_viiijii=(s,l,u,p,f,g,w)=>(r0=i.dynCall_viiijii=N.yh)(s,l,u,p,f,g,w),n0=i.dynCall_viijiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D)=>(n0=i.dynCall_viijiiiiiiiii=N.zh)(s,l,u,p,f,g,w,b,x,E,T,P,D),i0=i.dynCall_fiiii=(s,l,u,p,f)=>(i0=i.dynCall_fiiii=N.Ah)(s,l,u,p,f),a0=i.dynCall_jfi=(s,l,u)=>(a0=i.dynCall_jfi=N.Bh)(s,l,u),s0=i.dynCall_viiiiiiiiiiiiii=(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)=>(s0=i.dynCall_viiiiiiiiiiiiii=N.Ch)(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F),o0=i.dynCall_jiij=(s,l,u,p)=>(o0=i.dynCall_jiij=N.Dh)(s,l,u,p),l0=s=>(l0=N.Eh)(s),u0=()=>(u0=N.Fh)(),d0=s=>(d0=N.Gh)(s),c0=()=>(c0=N.Hh)();i.___start_em_js=1275044,i.___stop_em_js=1275205;function ZS(s,l,u,p){var f=V();try{return Ni(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function JS(s,l,u){var p=V();try{return Li(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function eE(s,l,u){var p=V();try{zn(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function tE(s,l){var u=V();try{return Ui(s,l)}catch(p){if(G(u),p!==p+0)throw p;W(1,0)}}function rE(s,l){var u=V();try{jn(s,l)}catch(p){if(G(u),p!==p+0)throw p;W(1,0)}}function nE(s,l,u,p){var f=V();try{return Gi(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function iE(s){var l=V();try{Fi(s)}catch(u){if(G(l),u!==u+0)throw u;W(1,0)}}function aE(s,l,u,p,f,g,w){var b=V();try{return Pn(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function sE(s,l,u,p,f,g){var w=V();try{return Wi(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function oE(s,l,u,p,f){var g=V();try{return Rn(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function lE(s,l,u,p){var f=V();try{ln(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function uE(s,l,u,p,f){var g=V();try{Vi(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function dE(s,l,u,p,f,g){var w=V();try{Bn(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function cE(s,l,u,p,f,g,w){var b=V();try{Hi(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function pE(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{Ki(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function hE(s,l,u){var p=V();try{return ws(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function fE(s,l,u){var p=V();try{return un(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function mE(s,l,u){var p=V();try{return Qi(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function gE(s,l,u){var p=V();try{return y(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;return W(1,0),0n}}function yE(s,l,u,p,f,g,w,b,x){var E=V();try{A(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function _E(s){var l=V();try{return S(s)}catch(u){if(G(l),u!==u+0)throw u;W(1,0)}}function wE(s,l,u){var p=V();try{Ne(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function vE(s,l,u,p,f){var g=V();try{qi(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function bE(s,l,u,p,f,g,w){var b=V();try{B(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function $E(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{We(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function xE(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{q(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function CE(s,l,u,p,f,g,w,b){var x=V();try{return Me(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function SE(s,l,u,p,f,g,w,b){var x=V();try{Ve(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function EE(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{return ae(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function kE(s,l,u,p,f,g,w,b,x,E){var T=V();try{be(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function TE(s,l,u,p,f,g,w,b,x,E,T,P,D,O){var F=V();try{Xi(s,l,u,p,f,g,w,b,x,E,T,P,D,O)}catch(J){if(G(F),J!==J+0)throw J;W(1,0)}}function IE(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{return Bg(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function AE(s,l,u,p,f,g,w,b,x){var E=V();try{return Rg(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function ME(s,l,u,p,f,g,w,b,x){var E=V();try{Dg(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function OE(s,l,u,p){var f=V();try{re(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function zE(s,l){var u=V();try{return Ng(s,l)}catch(p){if(G(u),p!==p+0)throw p;W(1,0)}}function PE(s,l){var u=V();try{return H(s,l)}catch(p){if(G(u),p!==p+0)throw p;return W(1,0),0n}}function jE(s,l){var u=V();try{return Ug(s,l)}catch(p){if(G(u),p!==p+0)throw p;W(1,0)}}function RE(s,l,u,p){var f=V();try{Wg(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function BE(s,l,u,p,f,g,w){var b=V();try{r0(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function DE(s,l,u,p,f){var g=V();try{Ky(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function NE(s,l,u,p,f,g,w,b,x,E){var T=V();try{return Gg(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function LE(s,l,u,p,f,g,w){var b=V();try{Vg(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function UE(s,l,u,p){var f=V();try{Hg(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function FE(s,l,u,p,f,g,w,b,x){var E=V();try{return hr(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function WE(s,l,u,p,f,g,w){var b=V();try{qg(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function GE(s,l,u,p,f,g,w,b,x){var E=V();try{Yi(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function VE(s,l,u,p,f,g,w){var b=V();try{Kg(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function HE(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{Yg(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function qE(s,l,u,p){var f=V();try{return Xg(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;return W(1,0),0n}}function KE(s,l,u,p,f,g,w,b){var x=V();try{Zg(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function YE(s,l,u,p,f){var g=V();try{Jg(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function QE(s,l,u,p){var f=V();try{ty(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function XE(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J){var de=V();try{ry(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)}catch(_e){if(G(de),_e!==_e+0)throw _e;W(1,0)}}function ZE(s,l,u,p,f,g){var w=V();try{ny(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function JE(s,l,u,p,f,g,w,b,x){var E=V();try{iy(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function ek(s,l,u,p,f){var g=V();try{return ay(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function tk(s,l,u,p,f,g,w,b,x,E,T,P,D,O){var F=V();try{return sy(s,l,u,p,f,g,w,b,x,E,T,P,D,O)}catch(J){if(G(F),J!==J+0)throw J;W(1,0)}}function rk(s,l){var u=V();try{oy(s,l)}catch(p){if(G(u),p!==p+0)throw p;W(1,0)}}function nk(s,l,u){var p=V();try{return ly(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;return W(1,0),0n}}function ik(s,l,u,p,f,g,w,b,x,E){var T=V();try{return uy(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function ak(s,l,u,p,f,g,w,b,x,E,T,P,D,O){var F=V();try{fy(s,l,u,p,f,g,w,b,x,E,T,P,D,O)}catch(J){if(G(F),J!==J+0)throw J;W(1,0)}}function sk(s,l,u,p,f){var g=V();try{dy(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function ok(s,l,u,p,f,g,w){var b=V();try{cy(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function lk(s,l,u,p,f){var g=V();try{hy(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function uk(s,l,u,p,f,g,w,b){var x=V();try{py(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function dk(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{my(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function ck(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de){var _e=V();try{return gy(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de)}catch(ke){if(G(_e),ke!==ke+0)throw ke;W(1,0)}}function pk(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{yy(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function hk(s,l){var u=V();try{return we(s,l)}catch(p){if(G(u),p!==p+0)throw p;W(1,0)}}function fk(s,l,u,p,f){var g=V();try{return i0(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function mk(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De){var qe=V();try{return _y(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De)}catch(lt){if(G(qe),lt!==lt+0)throw lt;W(1,0)}}function gk(s,l,u,p,f,g,w,b,x,E){var T=V();try{wy(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function yk(s,l,u,p,f,g,w){var b=V();try{return vy(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function _k(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{by(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function wk(s,l,u,p,f,g){var w=V();try{return $y(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function vk(s,l,u,p,f,g){var w=V();try{Cy(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function bk(s,l,u,p,f,g,w,b,x,E,T,P,D,O){var F=V();try{Sy(s,l,u,p,f,g,w,b,x,E,T,P,D,O)}catch(J){if(G(F),J!==J+0)throw J;W(1,0)}}function $k(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e){var ke=V();try{Ey(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e)}catch(De){if(G(ke),De!==De+0)throw De;W(1,0)}}function xk(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de){var _e=V();try{ky(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de)}catch(ke){if(G(_e),ke!==ke+0)throw ke;W(1,0)}}function Ck(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J){var de=V();try{Ty(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)}catch(_e){if(G(de),_e!==_e+0)throw _e;W(1,0)}}function Sk(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F){var J=V();try{Iy(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)}catch(de){if(G(J),de!==de+0)throw de;W(1,0)}}function Ek(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe){var lt=V();try{Ay(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe)}catch(St){if(G(lt),St!==St+0)throw St;W(1,0)}}function kk(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke){var De=V();try{My(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke)}catch(qe){if(G(De),qe!==qe+0)throw qe;W(1,0)}}function Tk(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e){var ke=V();try{Oy(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e)}catch(De){if(G(ke),De!==De+0)throw De;W(1,0)}}function Ik(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe){var lt=V();try{zy(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe)}catch(St){if(G(lt),St!==St+0)throw St;W(1,0)}}function Ak(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{Py(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function Mk(s,l,u,p,f,g,w,b,x,E){var T=V();try{jy(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function Ok(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{Ry(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function zk(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F){var J=V();try{By(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)}catch(de){if(G(J),de!==de+0)throw de;W(1,0)}}function Pk(s,l,u,p,f,g,w,b,x,E){var T=V();try{Ny(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function jk(s,l,u,p,f,g,w,b,x){var E=V();try{Ly(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function Rk(s,l,u,p,f,g,w){var b=V();try{return xy(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function Bk(s,l,u,p,f){var g=V();try{Dy(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function Dk(s,l,u){var p=V();try{return a0(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;return W(1,0),0n}}function Nk(s,l,u,p,f,g,w,b,x,E,T,P,D,O){var F=V();try{Uy(s,l,u,p,f,g,w,b,x,E,T,P,D,O)}catch(J){if(G(F),J!==J+0)throw J;W(1,0)}}function Lk(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{Wy(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function Uk(s,l,u,p,f,g,w){var b=V();try{return Gy(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function Fk(s,l,u,p,f,g){var w=V();try{return Vy(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function Wk(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{Hy(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function Gk(s,l,u,p,f,g){var w=V();try{Fy(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function Vk(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{qy(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function Hk(s,l,u,p,f,g,w,b){var x=V();try{Yy(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function qk(s,l,u,p,f,g,w,b){var x=V();try{Qy(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function Kk(s,l,u,p){var f=V();try{return Xy(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function Yk(s,l,u,p,f,g,w,b,x,E){var T=V();try{Zy(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function Qk(s,l,u,p,f,g,w,b,x){var E=V();try{Jy(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function Xk(s,l,u,p,f,g,w,b,x){var E=V();try{e_(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function Zk(s,l,u,p,f,g,w,b,x,E){var T=V();try{t_(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function Jk(s,l,u,p,f,g){var w=V();try{r_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function eT(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{n_(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function tT(s,l,u,p,f,g,w,b){var x=V();try{return i_(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function rT(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F){var J=V();try{s0(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)}catch(de){if(G(J),de!==de+0)throw de;W(1,0)}}function nT(s,l,u,p,f,g,w,b,x,E,T,P,D,O){var F=V();try{a_(s,l,u,p,f,g,w,b,x,E,T,P,D,O)}catch(J){if(G(F),J!==J+0)throw J;W(1,0)}}function iT(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F){var J=V();try{s_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F)}catch(de){if(G(J),de!==de+0)throw de;W(1,0)}}function aT(s,l,u){var p=V();try{o_(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function sT(s,l,u,p){var f=V();try{return u_(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function oT(s,l,u,p){var f=V();try{return d_(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function lT(s,l,u,p,f,g,w,b,x,E){var T=V();try{c_(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function uT(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe,lt,St,ll,ul,dl){var u3=V();try{p_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe,lt,St,ll,ul,dl)}catch(cl){if(G(u3),cl!==cl+0)throw cl;W(1,0)}}function dT(s,l,u,p,f,g){var w=V();try{h_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function cT(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{return f_(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function pT(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{m_(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function hT(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe){var lt=V();try{g_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De,qe)}catch(St){if(G(lt),St!==St+0)throw St;W(1,0)}}function fT(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{y_(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function mT(s,l,u,p,f,g,w,b,x,E,T,P,D,O){var F=V();try{__(s,l,u,p,f,g,w,b,x,E,T,P,D,O)}catch(J){if(G(F),J!==J+0)throw J;W(1,0)}}function gT(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De){var qe=V();try{v_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De)}catch(lt){if(G(qe),lt!==lt+0)throw lt;W(1,0)}}function yT(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de){var _e=V();try{$_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de)}catch(ke){if(G(_e),ke!==ke+0)throw ke;W(1,0)}}function _T(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke){var De=V();try{w_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke)}catch(qe){if(G(De),qe!==qe+0)throw qe;W(1,0)}}function wT(s,l,u,p,f,g,w,b){var x=V();try{x_(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function vT(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{S_(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function bT(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{return E_(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function $T(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De){var qe=V();try{return k_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J,de,_e,ke,De)}catch(lt){if(G(qe),lt!==lt+0)throw lt;W(1,0)}}function xT(s,l,u,p,f){var g=V();try{T_(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function CT(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{Qg(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function ST(s,l,u,p,f,g,w,b,x,E){var T=V();try{I_(s,l,u,p,f,g,w,b,x,E)}catch(P){if(G(T),P!==P+0)throw P;W(1,0)}}function ET(s,l,u,p,f){var g=V();try{A_(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function kT(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{n0(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function TT(s,l,u,p,f){var g=V();try{return M_(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function IT(s,l,u,p){var f=V();try{return o0(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;return W(1,0),0n}}function AT(s,l,u,p,f,g,w){var b=V();try{O_(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function MT(s,l,u,p,f,g){var w=V();try{return z_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function OT(s,l,u,p,f,g){var w=V();try{return P_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function zT(s,l,u,p,f,g,w,b,x){var E=V();try{j_(s,l,u,p,f,g,w,b,x)}catch(T){if(G(E),T!==T+0)throw T;W(1,0)}}function PT(s,l,u,p){var f=V();try{l_(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function jT(s,l,u,p,f,g,w,b){var x=V();try{return R_(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function RT(s,l,u,p,f,g){var w=V();try{return B_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function BT(s,l,u,p,f,g){var w=V();try{return D_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function DT(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{return N_(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function NT(s,l,u,p,f,g,w,b){var x=V();try{return L_(s,l,u,p,f,g,w,b)}catch(E){if(G(x),E!==E+0)throw E;W(1,0)}}function LT(s,l,u,p,f,g,w,b,x,E,T){var P=V();try{return U_(s,l,u,p,f,g,w,b,x,E,T)}catch(D){if(G(P),D!==D+0)throw D;W(1,0)}}function UT(s,l,u,p,f,g,w){var b=V();try{return F_(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function FT(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{return W_(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function WT(s,l,u,p,f,g,w){var b=V();try{return G_(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function GT(s,l,u,p,f,g,w){var b=V();try{return V_(s,l,u,p,f,g,w)}catch(x){if(G(b),x!==x+0)throw x;W(1,0)}}function VT(s,l,u){var p=V();try{return H_(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;return W(1,0),0n}}function HT(s,l,u,p){var f=V();try{return q_(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function qT(s,l,u,p){var f=V();try{Y_(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function KT(s,l,u,p){var f=V();try{return K_(s,l,u,p)}catch(g){if(G(f),g!==g+0)throw g;W(1,0)}}function YT(s,l,u,p,f){var g=V();try{Q_(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function QT(s,l,u,p,f){var g=V();try{return X_(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function XT(s,l,u,p,f,g){var w=V();try{return Z_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function ZT(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{J_(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function JT(s,l,u,p,f,g,w,b,x,E,T,P,D){var O=V();try{e0(s,l,u,p,f,g,w,b,x,E,T,P,D)}catch(F){if(G(O),F!==F+0)throw F;W(1,0)}}function e3(s,l,u,p,f,g,w,b,x,E,T,P){var D=V();try{ey(s,l,u,p,f,g,w,b,x,E,T,P)}catch(O){if(G(D),O!==O+0)throw O;W(1,0)}}function t3(s,l,u,p,f){var g=V();try{return t0(s,l,u,p,f)}catch(w){if(G(g),w!==w+0)throw w;W(1,0)}}function r3(s){var l=V();try{return xe(s)}catch(u){if(G(l),u!==u+0)throw u;return W(1,0),0n}}function n3(s,l,u,p,f,g){var w=V();try{return ye(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function i3(s,l,u,p,f,g){var w=V();try{return C_(s,l,u,p,f,g)}catch(b){if(G(w),b!==b+0)throw b;W(1,0)}}function a3(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J){var de=V();try{b_(s,l,u,p,f,g,w,b,x,E,T,P,D,O,F,J)}catch(_e){if(G(de),_e!==_e+0)throw _e;W(1,0)}}function s3(s,l,u){var p=V();try{return Lg(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function o3(s,l,u){var p=V();try{return Fg(s,l,u)}catch(f){if(G(p),f!==f+0)throw f;W(1,0)}}function l3(){var s=N;s=Object.assign({},s);var l=u=>p=>u(p)>>>0;return s.Fd=l(s.Fd),s.he=l(s.he),s.ne=l(s.ne),s.oe=(u=>()=>u()>>>0)(s.oe),s}i.stackSave=()=>V(),i.stackRestore=s=>G(s),i.stackAlloc=s=>ms(s),i.UTF8ToString=et,i.stringToUTF8=(s,l,u)=>lr(s,me,l,u),i.lengthBytesUTF8=Or;var vs;pt=function s(){vs||p0(),vs||(pt=s)};function p0(){if(!(0r)}),Q0=cn(()=>{}),X0=cn(()=>{}),Vl={};pn(Vl,{cpus:()=>Hl});var Hl,Z0=le(()=>{Hl=void 0}),J0=cn((t,e)=>{var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(a={}){function o(){return ne.buffer!=he.buffer&&pt(),he}function i(){return ne.buffer!=he.buffer&&pt(),ve}function d(){return ne.buffer!=he.buffer&&pt(),Le}function h(){return ne.buffer!=he.buffer&&pt(),Ke}function m(){return ne.buffer!=he.buffer&&pt(),ct}var c=a,_,v;c.ready=new Promise((y,S)=>{_=y,v=S}),c.jsepInit=(y,S,A,B,H,re,ae,be)=>{c.Qb=y,c.wb=S,c.yb=A,c.jb=B,c.xb=H,c.Ea=re,c.zb=ae,c.Ab=be,S=(we,ye,xe)=>(...Ne)=>{let We=Nt,q=ye==null?void 0:ye();Ne=we(...Ne);let Me=ye==null?void 0:ye();return q!==Me&&(we=Me,xe(q),ye=xe=null),Nt!=We?sn():Ne},A=we=>async(...ye)=>{try{if(c.bb)throw Error("Session already started");let xe=c.bb={Fb:ye[0],errors:[]},Ne=await we(...ye);if(c.bb!==xe)throw Error("Session mismatch");y.flush();let We=xe.errors;if(0Me),0c._OrtRun,we=>c._OrtRun=we)),c._OrtRunWithBinding=A(S(c._OrtRunWithBinding,()=>c._OrtRunWithBinding,we=>c._OrtRunWithBinding=we)),c._OrtBindInput=S(c._OrtBindInput,()=>c._OrtBindInput,we=>c._OrtBindInput=we),c.jsepRegisterBuffer=(we,ye,xe,Ne)=>y.registerBuffer(we,ye,xe,Ne),c.jsepUnregisterBuffers=we=>{y.unregisterBuffers(we)},c.jsepGetBuffer=we=>y.getBuffer(we),c.jsepCreateDownloader=(we,ye,xe)=>y.createDownloader(we,ye,xe)};var $=Object.assign({},c),C="./this.program",k=(y,S)=>{throw S},M=typeof window=="object",z=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",j=c.ENVIRONMENT_IS_PTHREAD||!1,R="";function L(y){return c.locateFile?c.locateFile(y,R):R+y}var Y,Q,ie;if(I){var pe=(js(),Sr(sa)),ce=(Gl(),Sr(Rs));R=z?ce.dirname(R)+"/":__dirname+"/",Y=(S,A)=>(S=S.startsWith("file://")?new URL(S):ce.normalize(S),pe.readFileSync(S,A?void 0:"utf8")),ie=S=>(S=Y(S,!0),S.buffer||(S=new Uint8Array(S)),S),Q=(S,A,B,H=!0)=>{S=S.startsWith("file://")?new URL(S):ce.normalize(S),pe.readFile(S,H?void 0:"utf8",(re,ae)=>{re?B(re):A(H?ae.buffer:ae)})},!c.thisProgram&&1{throw process.exitCode=S,A},c.inspect=()=>"[Emscripten Module object]";let y;try{y=Q0()}catch(S){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),S}global.Worker=y.Worker}else(M||z)&&(z?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),typeof n<"u"&&n&&(R=n),R.indexOf("blob:")!==0?R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):R="",I||(Y=y=>{var S=new XMLHttpRequest;return S.open("GET",y,!1),S.send(null),S.responseText},z&&(ie=y=>{var S=new XMLHttpRequest;return S.open("GET",y,!1),S.responseType="arraybuffer",S.send(null),new Uint8Array(S.response)}),Q=(y,S,A)=>{var B=new XMLHttpRequest;B.open("GET",y,!0),B.responseType="arraybuffer",B.onload=()=>{B.status==200||B.status==0&&B.response?S(B.response):A()},B.onerror=A,B.send(null)}));I&&typeof performance>"u"&&(global.performance=X0().performance);var Se=console.log.bind(console),fe=console.error.bind(console);I&&(Se=(...y)=>pe.writeSync(1,y.join(" ")+` `),fe=(...y)=>pe.writeSync(2,y.join(" ")+` `));var me=c.print||Se,ge=c.printErr||fe;Object.assign(c,$),$=null,c.thisProgram&&(C=c.thisProgram),c.quit&&(k=c.quit);var X;c.wasmBinary&&(X=c.wasmBinary);var U=c.noExitRuntime||!0;typeof WebAssembly!="object"&&Vt("no native wasm support detected");var ne,ee,Ee,Te=!1,K,he,ve,Le,Ke,ct;function pt(){var y=ne.buffer;c.HEAP8=he=new Int8Array(y),c.HEAP16=new Int16Array(y),c.HEAP32=Le=new Int32Array(y),c.HEAPU8=ve=new Uint8Array(y),c.HEAPU16=new Uint16Array(y),c.HEAPU32=Ke=new Uint32Array(y),c.HEAPF32=new Float32Array(y),c.HEAPF64=ct=new Float64Array(y)}var rt=c.INITIAL_MEMORY||16777216;if(5242880<=rt||Vt("INITIAL_MEMORY should be larger than STACK_SIZE, was "+rt+"! (STACK_SIZE=5242880)"),j)ne=c.wasmMemory;else if(c.wasmMemory)ne=c.wasmMemory;else if(ne=new WebAssembly.Memory({initial:rt/65536,maximum:65536,shared:!0}),!(ne.buffer instanceof SharedArrayBuffer))throw ge("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&&ge("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");pt(),rt=ne.buffer.byteLength;var Gt=[],It=[],ir=[],st=0;function ot(){return U||0{if(!S.ok)throw"failed to load wasm binary file at '"+y+"'";return S.arrayBuffer()}).catch(()=>or(y));if(Q)return new Promise((S,A)=>{Q(y,B=>S(new Uint8Array(B)),A)})}return Promise.resolve().then(()=>or(y))}function Jr(y,S,A){return $i(y).then(B=>WebAssembly.instantiate(B,S)).then(B=>B).then(A,B=>{ge("failed to asynchronously prepare wasm: "+B),Vt(B)})}function Xa(y,S){var A=sr;return X||typeof WebAssembly.instantiateStreaming!="function"||Zr(A)||A.startsWith("file://")||I||typeof fetch!="function"?Jr(A,y,S):fetch(A,{credentials:"same-origin"}).then(B=>WebAssembly.instantiateStreaming(B,y).then(S,function(H){return ge("wasm streaming compile failed: "+H),ge("falling back to ArrayBuffer instantiation"),Jr(A,y,S)}))}var $r,et={906828:y=>{c.Ea("Abs",y,void 0)},906879:y=>{c.Ea("Neg",y,void 0)},906930:y=>{c.Ea("Floor",y,void 0)},906983:y=>{c.Ea("Ceil",y,void 0)},907035:y=>{c.Ea("Reciprocal",y,void 0)},907093:y=>{c.Ea("Sqrt",y,void 0)},907145:y=>{c.Ea("Exp",y,void 0)},907196:y=>{c.Ea("Erf",y,void 0)},907247:y=>{c.Ea("Sigmoid",y,void 0)},907302:y=>{c.Ea("Log",y,void 0)},907353:y=>{c.Ea("Sin",y,void 0)},907404:y=>{c.Ea("Cos",y,void 0)},907455:y=>{c.Ea("Tan",y,void 0)},907506:y=>{c.Ea("Asin",y,void 0)},907558:y=>{c.Ea("Acos",y,void 0)},907610:y=>{c.Ea("Atan",y,void 0)},907662:y=>{c.Ea("Sinh",y,void 0)},907714:y=>{c.Ea("Cosh",y,void 0)},907766:y=>{c.Ea("Asinh",y,void 0)},907819:y=>{c.Ea("Acosh",y,void 0)},907872:y=>{c.Ea("Atanh",y,void 0)},907925:y=>{c.Ea("Tanh",y,void 0)},907977:y=>{c.Ea("Not",y,void 0)},908028:(y,S,A)=>{c.Ea("ClipV10",y,{min:S,max:A})},908100:y=>{c.Ea("Clip",y,void 0)},908152:(y,S)=>{c.Ea("Elu",y,{alpha:S})},908210:y=>{c.Ea("Relu",y,void 0)},908262:(y,S)=>{c.Ea("LeakyRelu",y,{alpha:S})},908326:(y,S)=>{c.Ea("ThresholdedRelu",y,{alpha:S})},908396:(y,S)=>{c.Ea("Cast",y,{to:S})},908454:y=>{c.Ea("Add",y,void 0)},908505:y=>{c.Ea("Sub",y,void 0)},908556:y=>{c.Ea("Mul",y,void 0)},908607:y=>{c.Ea("Div",y,void 0)},908658:y=>{c.Ea("Pow",y,void 0)},908709:y=>{c.Ea("Equal",y,void 0)},908762:y=>{c.Ea("Greater",y,void 0)},908817:y=>{c.Ea("GreaterOrEqual",y,void 0)},908879:y=>{c.Ea("Less",y,void 0)},908931:y=>{c.Ea("LessOrEqual",y,void 0)},908990:(y,S,A,B,H)=>{c.Ea("ReduceMean",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},909154:(y,S,A,B,H)=>{c.Ea("ReduceMax",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},909317:(y,S,A,B,H)=>{c.Ea("ReduceMin",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},909480:(y,S,A,B,H)=>{c.Ea("ReduceProd",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},909644:(y,S,A,B,H)=>{c.Ea("ReduceSum",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},909807:(y,S,A,B,H)=>{c.Ea("ReduceL1",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},909969:(y,S,A,B,H)=>{c.Ea("ReduceL2",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},910131:(y,S,A,B,H)=>{c.Ea("ReduceLogSum",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},910297:(y,S,A,B,H)=>{c.Ea("ReduceSumSquare",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},910466:(y,S,A,B,H)=>{c.Ea("ReduceLogSumExp",y,{keepDims:!!S,noopWithEmptyAxes:!!A,axes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},910635:y=>{c.Ea("Where",y,void 0)},910688:(y,S,A)=>{c.Ea("Transpose",y,{perm:S?Array.from(d().subarray(A>>>0,A+S>>>0)):[]})},910801:(y,S,A,B,H,re,ae,be,we,ye)=>{c.Ea("Conv",y,{format:we?"NHWC":"NCHW",auto_pad:S,dilations:[A],group:B,kernel_shape:[H],pads:[re,ae],strides:[be],w_is_const:()=>!!o()[ye>>>0]})},911029:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q,Me)=>{c.Ea("Conv",y,{format:q?"NHWC":"NCHW",auto_pad:S,dilations:[A,B],group:H,kernel_shape:[re,ae],pads:[be,we,ye,xe],strides:[Ne,We],w_is_const:()=>!!o()[Me>>>0]})},911288:(y,S,A,B,H,re,ae,be,we,ye)=>{c.Ea("Conv",y,{format:we?"NHWC":"NCHW",auto_pad:S,dilations:[A],group:B,kernel_shape:[H],pads:[re,ae],strides:[be],w_is_const:()=>!!o()[ye>>>0]})},911516:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q,Me)=>{c.Ea("Conv",y,{format:q?"NHWC":"NCHW",auto_pad:S,dilations:[A,B],group:H,kernel_shape:[re,ae],pads:[be,we,ye,xe],strides:[Ne,We],w_is_const:()=>!!o()[Me>>>0]})},911775:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q)=>{c.Ea("ConvTranspose",y,{format:we?"NHWC":"NCHW",autoPad:S,dilations:[A],group:B,kernel_shape:[H],pads:[re,ae],strides:[be],wIsConst:()=>!!o()[ye>>>0],outputPadding:xe?Array.from(d().subarray(Ne>>>0,Ne+xe>>>0)):[],outputShape:We?Array.from(d().subarray(q>>>0,q+We>>>0)):[]})},912155:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We)=>{c.Ea("ConvTranspose",y,{format:be?"NHWC":"NCHW",autoPad:S,dilations:Array.from(d().subarray(A>>>0,A+2>>>0)),group:B,kernelShape:Array.from(d().subarray(H>>>0,H+2>>>0)),pads:Array.from(d().subarray(re>>>0,re+4>>>0)),strides:Array.from(d().subarray(ae>>>0,ae+2>>>0)),wIsConst:()=>!!o()[we>>>0],outputPadding:0>>0,xe+ye>>>0)):[],outputShape:0>>0,We+Ne>>>0)):[]})},912678:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q)=>{c.Ea("ConvTranspose",y,{format:we?"NHWC":"NCHW",autoPad:S,dilations:[A],group:B,kernel_shape:[H],pads:[re,ae],strides:[be],wIsConst:()=>!!o()[ye>>>0],outputPadding:xe?Array.from(d().subarray(Ne>>>0,Ne+xe>>>0)):[],outputShape:We?Array.from(d().subarray(q>>>0,q+We>>>0)):[]})},913058:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We)=>{c.Ea("ConvTranspose",y,{format:be?"NHWC":"NCHW",autoPad:S,dilations:Array.from(d().subarray(A>>>0,A+2>>>0)),group:B,kernelShape:Array.from(d().subarray(H>>>0,H+2>>>0)),pads:Array.from(d().subarray(re>>>0,re+4>>>0)),strides:Array.from(d().subarray(ae>>>0,ae+2>>>0)),wIsConst:()=>!!o()[we>>>0],outputPadding:0>>0,xe+ye>>>0)):[],outputShape:0>>0,We+Ne>>>0)):[]})},913581:(y,S)=>{c.Ea("GlobalAveragePool",y,{format:S?"NHWC":"NCHW"})},913672:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q,Me,Ve)=>{c.Ea("AveragePool",y,{format:Ve?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:B,storage_order:H,dilations:[re,ae],kernel_shape:[be,we],pads:[ye,xe,Ne,We],strides:[q,Me]})},913956:(y,S)=>{c.Ea("GlobalAveragePool",y,{format:S?"NHWC":"NCHW"})},914047:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q,Me,Ve)=>{c.Ea("AveragePool",y,{format:Ve?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:B,storage_order:H,dilations:[re,ae],kernel_shape:[be,we],pads:[ye,xe,Ne,We],strides:[q,Me]})},914331:(y,S)=>{c.Ea("GlobalMaxPool",y,{format:S?"NHWC":"NCHW"})},914418:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q,Me,Ve)=>{c.Ea("MaxPool",y,{format:Ve?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:B,storage_order:H,dilations:[re,ae],kernel_shape:[be,we],pads:[ye,xe,Ne,We],strides:[q,Me]})},914698:(y,S)=>{c.Ea("GlobalMaxPool",y,{format:S?"NHWC":"NCHW"})},914785:(y,S,A,B,H,re,ae,be,we,ye,xe,Ne,We,q,Me,Ve)=>{c.Ea("MaxPool",y,{format:Ve?"NHWC":"NCHW",auto_pad:S,ceil_mode:A,count_include_pad:B,storage_order:H,dilations:[re,ae],kernel_shape:[be,we],pads:[ye,xe,Ne,We],strides:[q,Me]})},915065:(y,S,A,B,H)=>{c.Ea("Gemm",y,{alpha:S,beta:A,transA:B,transB:H})},915169:y=>{c.Ea("MatMul",y,void 0)},915223:(y,S,A,B)=>{c.Ea("ArgMax",y,{keepDims:!!S,selectLastIndex:!!A,axis:B})},915331:(y,S,A,B)=>{c.Ea("ArgMin",y,{keepDims:!!S,selectLastIndex:!!A,axis:B})},915439:(y,S)=>{c.Ea("Softmax",y,{axis:S})},915502:(y,S)=>{c.Ea("Concat",y,{axis:S})},915562:(y,S,A,B,H)=>{c.Ea("Split",y,{axis:S,numOutputs:A,splitSizes:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},915707:y=>{c.Ea("Expand",y,void 0)},915761:(y,S)=>{c.Ea("Gather",y,{axis:Number(S)})},915832:(y,S)=>{c.Ea("GatherElements",y,{axis:Number(S)})},915911:(y,S,A,B,H,re,ae,be,we,ye,xe)=>{c.Ea("Resize",y,{antialias:S,axes:A?Array.from(d().subarray(B>>>0,B+A>>>0)):[],coordinateTransformMode:gt(H),cubicCoeffA:re,excludeOutside:ae,extrapolationValue:be,keepAspectRatioPolicy:gt(we),mode:gt(ye),nearestMode:gt(xe)})},916262:(y,S,A,B,H,re,ae)=>{c.Ea("Slice",y,{starts:S?Array.from(d().subarray(A>>>0,A+S>>>0)):[],ends:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[],axes:re?Array.from(d().subarray(ae>>>0,ae+re>>>0)):[]})},916493:y=>{c.Ea("Tile",y,void 0)},916545:(y,S,A)=>{c.Ea("LayerNormalization",y,{axis:Number(S),epsilon:Number(A)})},916652:(y,S,A)=>{c.Ea("InstanceNormalization",y,{epsilon:S,format:A?"NHWC":"NCHW"})},916766:(y,S,A)=>{c.Ea("InstanceNormalization",y,{epsilon:S,format:A?"NHWC":"NCHW"})},916880:y=>{c.Ea("Range",y,void 0)},916933:(y,S)=>{c.Ea("Einsum",y,{equation:gt(S)})},917014:(y,S,A,B,H)=>{c.Ea("Pad",y,{mode:S,value:A,pads:B?Array.from(d().subarray(H>>>0,H+B>>>0)):[]})},917146:y=>{c.Ea("Gelu",y,void 0)},917198:y=>{c.Ea("BiasAdd",y,void 0)},917253:y=>{c.Ea("BiasSplitGelu",y,void 0)},917314:(y,S)=>{c.Ea("SkipLayerNormalization",y,{epsilon:S})},917395:y=>{c.zb(y)},917429:(y,S)=>c.Ab(y,S,c.bb.Fb,c.bb.errors),917541:y=>c.wb(y),917574:y=>c.yb(y),917606:(y,S,A)=>{c.jb(y,S,A,!0)},917645:(y,S,A)=>{c.jb(y,S,A)}};function Or(y){this.name="ExitStatus",this.message=`Program terminated with exit(${y})`,this.status=y}function lr(y){y.terminate(),y.onmessage=()=>{}}function xi(y){(y=Ie.Qa[y])||Vt(),Ie.Eb(y)}function Rt(y){var S=Ie.tb();if(!S)return 6;Ie.Ya.push(S),Ie.Qa[y.Xa]=S,S.Xa=y.Xa;var A={cmd:"run",start_routine:y.Gb,arg:y.rb,pthread_ptr:y.Xa};return I&&S.unref(),S.postMessage(A,y.Mb),0}var $n=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,xn=(y,S,A)=>{S>>>=0;var B=S+A;for(A=S;y[A]&&!(A>=B);)++A;if(16H?B+=String.fromCharCode(H):(H-=65536,B+=String.fromCharCode(55296|H>>10,56320|H&1023))}}else B+=String.fromCharCode(H)}return B},gt=(y,S)=>(y>>>=0)?xn(i(),y,S):"";function Za(y){if(j)return Qe(1,1,y);K=y,ot()||(Ie.Hb(),c.onExit&&c.onExit(y),Te=!0),k(y,new Or(y))}var Bt=y=>{if(K=y,j)throw Ht(y),"unwind";Za(y)},Ie={ab:[],Ya:[],mb:[],Qa:{},gb:function(){j?Ie.vb():Ie.ub()},ub:function(){Gt.unshift(()=>{bn(),Ie.Bb(()=>bi())})},vb:function(){Ie.receiveObjectTransfer=Ie.Db,Ie.threadInitTLS=Ie.lb,Ie.setExitStatus=Ie.kb,U=!1},kb:function(y){K=y},Sb:["$terminateWorker"],Hb:function(){for(var y of Ie.Ya)lr(y);for(y of Ie.ab)lr(y);Ie.ab=[],Ie.Ya=[],Ie.Qa=[]},Eb:function(y){var S=y.Xa;delete Ie.Qa[S],Ie.ab.push(y),Ie.Ya.splice(Ie.Ya.indexOf(y),1),y.Xa=0,Pn(S)},Db:function(){},lb:function(){Ie.mb.forEach(y=>y())},Cb:y=>new Promise(S=>{y.onmessage=re=>{re=re.data;var ae=re.cmd;if(re.targetThread&&re.targetThread!=on()){var be=Ie.Qa[re.Rb];be?be.postMessage(re,re.transferList):ge('Internal error! Worker sent a message "'+ae+'" to target pthread '+re.targetThread+", but that thread no longer exists!")}else ae==="checkMailbox"?tn():ae==="spawnThread"?Rt(re):ae==="cleanupThread"?xi(re.thread):ae==="killThread"?(re=re.thread,ae=Ie.Qa[re],delete Ie.Qa[re],lr(ae),Pn(re),Ie.Ya.splice(Ie.Ya.indexOf(ae),1),ae.Xa=0):ae==="cancelThread"?Ie.Qa[re.thread].postMessage({cmd:"cancel"}):ae==="loaded"?(y.loaded=!0,S(y)):ae==="alert"?alert("Thread "+re.threadId+": "+re.text):re.target==="setimmediate"?y.postMessage(re):ae==="callHandler"?c[re.handler](...re.args):ae&&ge("worker sent an unknown command "+ae)},y.onerror=re=>{throw ge("worker sent an error! "+re.filename+":"+re.lineno+": "+re.message),re},I&&(y.on("message",function(re){y.onmessage({data:re})}),y.on("error",function(re){y.onerror(re)}));var A=[],B=["onExit","onAbort","print","printErr"],H;for(H of B)c.hasOwnProperty(H)&&A.push(H);y.postMessage({cmd:"load",handlers:A,urlOrBlob:c.mainScriptUrlOrBlob||n,wasmMemory:ne,wasmModule:Ee})}),Bb:function(y){y()},qb:function(){var y=L("ort-wasm-simd-threaded.worker.js");y=new Worker(y),Ie.ab.push(y)},tb:function(){return Ie.ab.length==0&&(Ie.qb(),Ie.Cb(Ie.ab[0])),Ie.ab.pop()}};c.PThread=Ie;var zr=y=>{for(;0>2>>>0];y=d()[y+56>>2>>>0],Gi(S,S-y),ln(S)};function Ht(y){if(j)return Qe(2,0,y);Bt(y)}c.invokeEntryPoint=function(y,S){y=Vi.apply(null,[y,S]),ot()?Ie.kb(y):jn(y)};function Ci(y){this.fb=y-24,this.pb=function(S){h()[this.fb+4>>2>>>0]=S},this.ob=function(S){h()[this.fb+8>>2>>>0]=S},this.gb=function(S,A){this.nb(),this.pb(S),this.ob(A)},this.nb=function(){h()[this.fb+16>>2>>>0]=0}}var yt=0;function At(y,S,A,B){return j?Qe(3,1,y,S,A,B):Cn(y,S,A,B)}function Cn(y,S,A,B){if(y>>>=0,S>>>=0,A>>>=0,B>>>=0,typeof SharedArrayBuffer>"u")return ge("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var H=[];return j&&H.length===0?At(y,S,A,B):(y={Gb:A,Xa:y,rb:B,Mb:H},j?(y.Ob="spawnThread",postMessage(y,H),0):Rt(y))}function Ja(y,S,A){return j?Qe(4,1,y,S,A):0}function es(y,S){if(j)return Qe(5,1,y,S)}var Sn=y=>{for(var S=0,A=0;A=B?S++:2047>=B?S+=2:55296<=B&&57343>=B?(S+=4,++A):S+=3}return S},ts=(y,S,A,B)=>{if(A>>>=0,!(0=ae){var be=y.charCodeAt(++re);ae=65536+((ae&1023)<<10)|be&1023}if(127>=ae){if(A>=B)break;S[A++>>>0]=ae}else{if(2047>=ae){if(A+1>=B)break;S[A++>>>0]=192|ae>>6}else{if(65535>=ae){if(A+2>=B)break;S[A++>>>0]=224|ae>>12}else{if(A+3>=B)break;S[A++>>>0]=240|ae>>18,S[A++>>>0]=128|ae>>12&63}S[A++>>>0]=128|ae>>6&63}S[A++>>>0]=128|ae&63}}return S[A>>>0]=0,A-H},rs=(y,S,A)=>ts(y,i(),S,A);function ns(y,S){if(j)return Qe(6,1,y,S)}function is(y,S,A){if(j)return Qe(7,1,y,S,A)}function as(y,S,A){return j?Qe(8,1,y,S,A):0}function ss(y,S){if(j)return Qe(9,1,y,S)}function En(y,S,A){if(j)return Qe(10,1,y,S,A)}function Si(y,S,A,B){if(j)return Qe(11,1,y,S,A,B)}function en(y,S,A,B){if(j)return Qe(12,1,y,S,A,B)}function os(y,S,A,B){if(j)return Qe(13,1,y,S,A,B)}function ls(y){if(j)return Qe(14,1,y)}function ur(y,S){if(j)return Qe(15,1,y,S)}function Dt(y,S,A){if(j)return Qe(16,1,y,S,A)}var Ei=y=>{if(!Te)try{if(y(),!ot())try{j?jn(K):Bt(K)}catch(S){S instanceof Or||S=="unwind"||k(1,S)}}catch(S){S instanceof Or||S=="unwind"||k(1,S)}};function Pr(y){y>>>=0,typeof Atomics.Nb=="function"&&(Atomics.Nb(d(),y>>2,y).value.then(tn),y+=128,Atomics.store(d(),y>>2,1))}c.__emscripten_thread_mailbox_await=Pr;function tn(){var y=on();y&&(Pr(y),Ei(()=>Fi()))}c.checkMailbox=tn;var xr=y=>y%4===0&&(y%100!==0||y%400===0),us=[0,31,60,91,121,152,182,213,244,274,305,335],kn=[0,31,59,90,120,151,181,212,243,273,304,334];function ds(y,S,A,B,H,re,ae,be){return j?Qe(17,1,y,S,A,B,H,re,ae,be):-52}function cs(y,S,A,B,H,re,ae){if(j)return Qe(18,1,y,S,A,B,H,re,ae)}var ps=y=>{var S=Sn(y)+1,A=zn(S);return A&&rs(y,A,S),A},ki=[],Ti=(y,S)=>{ki.length=0;var A;for(S>>=2;A=i()[y++>>>0];)S+=A!=105&S,ki.push(A==105?d()[S>>>0]:m()[S++>>>1]),++S;return ki},Tn=y=>{var S=Rn();return y=y(),ln(S),y};function Qe(y,S){var A=arguments.length-2,B=arguments;return Tn(()=>{for(var H=Bn(8*A),re=H>>3,ae=0;ae>>0]=be}return Ui(y,A,H,S)})}var rn=[],In={},hs=()=>{if(!Ii){var y={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"},S;for(S in In)In[S]===void 0?delete y[S]:y[S]=In[S];var A=[];for(S in y)A.push(`${S}=${y[S]}`);Ii=A}return Ii},Ii;function Ai(y,S){if(j)return Qe(19,1,y,S);y>>>=0,S>>>=0;var A=0;return hs().forEach(function(B,H){var re=S+A;for(H=h()[y+4*H>>2>>>0]=re,re=0;re>0>>>0]=B.charCodeAt(re);o()[H>>0>>>0]=0,A+=B.length+1}),0}function fs(y,S){if(j)return Qe(20,1,y,S);y>>>=0,S>>>=0;var A=hs();h()[y>>2>>>0]=A.length;var B=0;return A.forEach(function(H){B+=H.length+1}),h()[S>>2>>>0]=B,0}function Cr(y){return j?Qe(21,1,y):52}function Mi(y,S,A,B){return j?Qe(22,1,y,S,A,B):52}function Oi(y,S,A,B,H){return j?Qe(23,1,y,S,A,B,H):70}var zi=[null,[],[]];function Pi(y,S,A,B){if(j)return Qe(24,1,y,S,A,B);S>>>=0,A>>>=0,B>>>=0;for(var H=0,re=0;re>2>>>0],be=h()[S+4>>2>>>0];S+=8;for(var we=0;we>>0],xe=zi[y];ye===0||ye===10?((y===1?me:ge)(xn(xe,0)),xe.length=0):xe.push(ye)}H+=be}return h()[B>>2>>>0]=H,0}var An=[31,29,31,30,31,30,31,31,30,31,30,31],ji=[31,28,31,30,31,30,31,31,30,31,30,31];function Ri(y){var S=Array(Sn(y)+1);return ts(y,S,0,S.length),S}var sl=(y,S)=>{o().set(y,S>>>0)};function Bi(y,S,A,B){function H(q,Me,Ve){for(q=typeof q=="number"?q.toString():q||"";q.lengthXi?-1:0hr-q.getDate())Me-=hr-q.getDate()+1,q.setDate(1),11>Ve?q.setMonth(Ve+1):(q.setMonth(0),q.setFullYear(q.getFullYear()+1));else{q.setDate(q.getDate()+Me);break}}return Ve=new Date(q.getFullYear()+1,0,4),Me=be(new Date(q.getFullYear(),0,4)),Ve=be(Ve),0>=ae(Me,q)?0>=ae(Ve,q)?q.getFullYear()+1:q.getFullYear():q.getFullYear()-1}y>>>=0,S>>>=0,A>>>=0,B>>>=0;var ye=d()[B+40>>2>>>0];B={Kb:d()[B>>2>>>0],Jb:d()[B+4>>2>>>0],cb:d()[B+8>>2>>>0],ib:d()[B+12>>2>>>0],eb:d()[B+16>>2>>>0],$a:d()[B+20>>2>>>0],Wa:d()[B+24>>2>>>0],Za:d()[B+28>>2>>>0],Tb:d()[B+32>>2>>>0],Ib:d()[B+36>>2>>>0],Lb:ye?gt(ye):""},A=gt(A),ye={"%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 xe in ye)A=A.replace(new RegExp(xe,"g"),ye[xe]);var Ne="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),We="January February March April May June July August September October November December".split(" ");ye={"%a":q=>Ne[q.Wa].substring(0,3),"%A":q=>Ne[q.Wa],"%b":q=>We[q.eb].substring(0,3),"%B":q=>We[q.eb],"%C":q=>re((q.$a+1900)/100|0,2),"%d":q=>re(q.ib,2),"%e":q=>H(q.ib,2," "),"%g":q=>we(q).toString().substring(2),"%G":q=>we(q),"%H":q=>re(q.cb,2),"%I":q=>(q=q.cb,q==0?q=12:12{for(var Me=0,Ve=0;Ve<=q.eb-1;Me+=(xr(q.$a+1900)?An:ji)[Ve++]);return re(q.ib+Me,3)},"%m":q=>re(q.eb+1,2),"%M":q=>re(q.Jb,2),"%n":()=>` `,"%p":q=>0<=q.cb&&12>q.cb?"AM":"PM","%S":q=>re(q.Kb,2),"%t":()=>" ","%u":q=>q.Wa||7,"%U":q=>re(Math.floor((q.Za+7-q.Wa)/7),2),"%V":q=>{var Me=Math.floor((q.Za+7-(q.Wa+6)%7)/7);if(2>=(q.Wa+371-q.Za-2)%7&&Me++,Me)Me==53&&(Ve=(q.Wa+371-q.Za)%7,Ve==4||Ve==3&&xr(q.$a)||(Me=1));else{Me=52;var Ve=(q.Wa+7-q.Za-1)%7;(Ve==4||Ve==5&&xr(q.$a%400-1))&&Me++}return re(Me,2)},"%w":q=>q.Wa,"%W":q=>re(Math.floor((q.Za+7-(q.Wa+6)%7)/7),2),"%y":q=>(q.$a+1900).toString().substring(2),"%Y":q=>q.$a+1900,"%z":q=>{q=q.Ib;var Me=0<=q;return q=Math.abs(q)/60,(Me?"+":"-")+("0000"+(q/60*100+q%60)).slice(-4)},"%Z":q=>q.Lb,"%%":()=>"%"},A=A.replace(/%%/g,"\0\0");for(xe in ye)A.includes(xe)&&(A=A.replace(new RegExp(xe,"g"),ye[xe](B)));return A=A.replace(/\0\0/g,"%"),xe=Ri(A),xe.length>S?0:(sl(xe,y),xe.length-1)}function nn(y){try{y()}catch(S){Vt(S)}}function ol(y){var S={},A;for(A in y)(function(B){var H=y[B];S[B]=typeof H=="function"?function(){Mn.push(B);try{return H.apply(null,arguments)}finally{Te||(Mn.pop()===B||Vt(),Nt&&dr===1&&Mn.length===0&&(dr=0,st+=1,nn(qi),typeof Fibers<"u"&&Fibers.Ub()))}}:H})(A);return S}var dr=0,Nt=null,an=0,Mn=[],N={},Di={},On=0,Mt=null,W=[];function sn(){return new Promise((y,S)=>{Mt={resolve:y,reject:S}})}function G(){var y=zn(65548),S=y+12;h()[y>>2>>>0]=S,h()[y+4>>2>>>0]=S+65536,S=Mn[0];var A=N[S];return A===void 0&&(A=On++,N[S]=A,Di[A]=S),S=A,d()[y+8>>2>>>0]=S,y}function ms(){var y=d()[Nt+8>>2>>>0];return y=ee[Di[y]],--st,y()}function V(y){if(!Te){if(dr===0){var S=!1,A=!1;y((B=0)=>{if(!Te&&(an=B,S=!0,A)){dr=2,nn(()=>Ki(Nt)),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.resume(),B=!1;try{var H=ms()}catch(be){H=be,B=!0}var re=!1;if(!Nt){var ae=Mt;ae&&(Mt=null,(B?ae.reject:ae.resolve)(H),re=!0)}if(B&&!re)throw H}}),A=!0,S||(dr=1,Nt=G(),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.pause(),nn(()=>Hi(Nt)))}else dr===2?(dr=0,nn(Yi),Ni(Nt),Nt=null,W.forEach(B=>Ei(B))):Vt(`invalid state: ${dr}`);return an}}function gs(y){return V(S=>{y().then(S)})}Ie.gb();var ys=[null,Za,Ht,At,Ja,es,ns,is,as,ss,En,Si,en,os,ls,ur,Dt,ds,cs,Ai,fs,Cr,Mi,Oi,Pi],_s={r:function(y,S,A){return gs(async()=>{await c.xb(y,S,A)})},b:function(y,S,A){throw y>>>=0,new Ci(y).gb(S>>>0,A>>>0),yt=y,yt},O:function(y){Li(y>>>0,!z,1,!M,131072,!1),Ie.lb()},l:function(y){y>>>=0,j?postMessage({cmd:"cleanupThread",thread:y}):xi(y)},I:Cn,i:Ja,U:es,E:ns,G:is,V:as,S:ss,K:En,R:Si,p:en,F:os,C:ls,T:ur,D:Dt,q:()=>!0,A:function(y,S){y>>>=0,y==S>>>0?setTimeout(()=>tn()):j?postMessage({targetThread:y,cmd:"checkMailbox"}):(y=Ie.Qa[y])&&y.postMessage({cmd:"checkMailbox"})},M:function(){return-1},N:Pr,X:function(y){I&&Ie.Qa[y>>>0].ref()},u:function(y,S,A){y=S+2097152>>>0<4194305-!!y?(y>>>0)+4294967296*S:NaN,A>>>=0,y=new Date(1e3*y),d()[A>>2>>>0]=y.getUTCSeconds(),d()[A+4>>2>>>0]=y.getUTCMinutes(),d()[A+8>>2>>>0]=y.getUTCHours(),d()[A+12>>2>>>0]=y.getUTCDate(),d()[A+16>>2>>>0]=y.getUTCMonth(),d()[A+20>>2>>>0]=y.getUTCFullYear()-1900,d()[A+24>>2>>>0]=y.getUTCDay(),y=(y.getTime()-Date.UTC(y.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,d()[A+28>>2>>>0]=y},v:function(y,S,A){y=S+2097152>>>0<4194305-!!y?(y>>>0)+4294967296*S:NaN,A>>>=0,y=new Date(1e3*y),d()[A>>2>>>0]=y.getSeconds(),d()[A+4>>2>>>0]=y.getMinutes(),d()[A+8>>2>>>0]=y.getHours(),d()[A+12>>2>>>0]=y.getDate(),d()[A+16>>2>>>0]=y.getMonth(),d()[A+20>>2>>>0]=y.getFullYear()-1900,d()[A+24>>2>>>0]=y.getDay(),S=(xr(y.getFullYear())?us:kn)[y.getMonth()]+y.getDate()-1|0,d()[A+28>>2>>>0]=S,d()[A+36>>2>>>0]=-(60*y.getTimezoneOffset()),S=new Date(y.getFullYear(),6,1).getTimezoneOffset();var B=new Date(y.getFullYear(),0,1).getTimezoneOffset();y=(S!=B&&y.getTimezoneOffset()==Math.min(B,S))|0,d()[A+32>>2>>>0]=y},w:function(y){y>>>=0;var S=new Date(d()[y+20>>2>>>0]+1900,d()[y+16>>2>>>0],d()[y+12>>2>>>0],d()[y+8>>2>>>0],d()[y+4>>2>>>0],d()[y>>2>>>0],0),A=d()[y+32>>2>>>0],B=S.getTimezoneOffset(),H=new Date(S.getFullYear(),6,1).getTimezoneOffset(),re=new Date(S.getFullYear(),0,1).getTimezoneOffset(),ae=Math.min(re,H);return 0>A?d()[y+32>>2>>>0]=+(H!=re&&ae==B):0>2>>>0]=S.getDay(),A=(xr(S.getFullYear())?us:kn)[S.getMonth()]+S.getDate()-1|0,d()[y+28>>2>>>0]=A,d()[y>>2>>>0]=S.getSeconds(),d()[y+4>>2>>>0]=S.getMinutes(),d()[y+8>>2>>>0]=S.getHours(),d()[y+12>>2>>>0]=S.getDate(),d()[y+16>>2>>>0]=S.getMonth(),d()[y+20>>2>>>0]=S.getYear(),y=S.getTime()/1e3,Wi(($r=y,1<=+Math.abs($r)?0<$r?+Math.floor($r/4294967296)>>>0:~~+Math.ceil(($r-+(~~$r>>>0))/4294967296)>>>0:0)),y>>>0},s:ds,t:cs,z:function(y,S,A){function B(ye){return(ye=ye.toTimeString().match(/\(([A-Za-z ]+)\)$/))?ye[1]:"GMT"}y>>>=0,S>>>=0,A>>>=0;var H=new Date().getFullYear(),re=new Date(H,0,1),ae=new Date(H,6,1);H=re.getTimezoneOffset();var be=ae.getTimezoneOffset(),we=Math.max(H,be);h()[y>>2>>>0]=60*we,d()[S>>2>>>0]=+(H!=be),y=B(re),S=B(ae),y=ps(y),S=ps(S),be>2>>>0]=y,h()[A+4>>2>>>0]=S):(h()[A>>2>>>0]=S,h()[A+4>>2>>>0]=y)},d:()=>{Vt("")},c:function(y,S,A){return y>>>=0,S=Ti(S>>>0,A>>>0),et[y].apply(null,S)},k:function(y,S,A){return y>>>=0,S=Ti(S>>>0,A>>>0),et[y].apply(null,S)},m:function(){},j:function(){return Date.now()},W:()=>{throw st+=1,"unwind"},B:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:function(){return I?(Z0(),Sr(Vl)).cpus().length:navigator.hardwareConcurrency},L:function(y,S,A,B){for(Ie.Pb=S>>>0,rn.length=A,S=B>>>0>>3,B=0;B>>0];return(0>y?et[-y-1]:ys[y]).apply(null,rn)},y:function(y){y>>>=0;var S=i().length;if(y<=S||4294901760=A;A*=2){var B=S*(1+.2/A);B=Math.min(B,y+100663296);var H=Math;B=Math.max(y,B);e:{H=H.min.call(H,4294901760,B+(65536-B%65536)%65536)-ne.buffer.byteLength+65535>>>16;try{ne.grow(H),pt();var re=1;break e}catch{}re=void 0}if(re)return!0}return!1},P:Ai,Q:fs,H:Bt,h:Cr,o:Mi,x:Oi,n:Pi,a:ne||c.wasmMemory,J:Bi,e:function(y,S,A,B){return Bi(y>>>0,S>>>0,A>>>0,B>>>0)}};(function(){function y(A,B){return A=A.exports,A=ol(A),ee=A=ws(A),Ie.mb.push(ee.Da),It.unshift(ee.Y),Ee=B,bi(),A}var S={a:_s};if(bn(),c.instantiateWasm)try{return c.instantiateWasm(S,y)}catch(A){ge("Module.instantiateWasm callback failed with error: "+A),v(A)}return Xa(S,function(A){y(A.instance,A.module)}).catch(v),{}})(),c._OrtInit=(y,S)=>(c._OrtInit=ee.Z)(y,S),c._OrtGetLastError=(y,S)=>(c._OrtGetLastError=ee._)(y,S),c._OrtCreateSessionOptions=(y,S,A,B,H,re,ae,be,we,ye)=>(c._OrtCreateSessionOptions=ee.$)(y,S,A,B,H,re,ae,be,we,ye),c._OrtAppendExecutionProvider=(y,S)=>(c._OrtAppendExecutionProvider=ee.aa)(y,S),c._OrtAddFreeDimensionOverride=(y,S,A)=>(c._OrtAddFreeDimensionOverride=ee.ba)(y,S,A),c._OrtAddSessionConfigEntry=(y,S,A)=>(c._OrtAddSessionConfigEntry=ee.ca)(y,S,A),c._OrtReleaseSessionOptions=y=>(c._OrtReleaseSessionOptions=ee.da)(y),c._OrtCreateSession=(y,S,A)=>(c._OrtCreateSession=ee.ea)(y,S,A),c._OrtReleaseSession=y=>(c._OrtReleaseSession=ee.fa)(y),c._OrtGetInputOutputCount=(y,S,A)=>(c._OrtGetInputOutputCount=ee.ga)(y,S,A),c._OrtGetInputName=(y,S)=>(c._OrtGetInputName=ee.ha)(y,S),c._OrtGetOutputName=(y,S)=>(c._OrtGetOutputName=ee.ia)(y,S),c._OrtFree=y=>(c._OrtFree=ee.ja)(y),c._OrtCreateTensor=(y,S,A,B,H,re)=>(c._OrtCreateTensor=ee.ka)(y,S,A,B,H,re),c._OrtGetTensorData=(y,S,A,B,H)=>(c._OrtGetTensorData=ee.la)(y,S,A,B,H),c._OrtReleaseTensor=y=>(c._OrtReleaseTensor=ee.ma)(y),c._OrtCreateRunOptions=(y,S,A,B)=>(c._OrtCreateRunOptions=ee.na)(y,S,A,B),c._OrtAddRunConfigEntry=(y,S,A)=>(c._OrtAddRunConfigEntry=ee.oa)(y,S,A),c._OrtReleaseRunOptions=y=>(c._OrtReleaseRunOptions=ee.pa)(y),c._OrtCreateBinding=y=>(c._OrtCreateBinding=ee.qa)(y),c._OrtBindInput=(y,S,A)=>(c._OrtBindInput=ee.ra)(y,S,A),c._OrtBindOutput=(y,S,A,B)=>(c._OrtBindOutput=ee.sa)(y,S,A,B),c._OrtClearBoundOutputs=y=>(c._OrtClearBoundOutputs=ee.ta)(y),c._OrtReleaseBinding=y=>(c._OrtReleaseBinding=ee.ua)(y),c._OrtRunWithBinding=(y,S,A,B,H)=>(c._OrtRunWithBinding=ee.va)(y,S,A,B,H),c._OrtRun=(y,S,A,B,H,re,ae,be)=>(c._OrtRun=ee.wa)(y,S,A,B,H,re,ae,be),c._OrtEndProfiling=y=>(c._OrtEndProfiling=ee.xa)(y),c._JsepOutput=(y,S,A)=>(c._JsepOutput=ee.ya)(y,S,A),c._JsepGetNodeName=y=>(c._JsepGetNodeName=ee.za)(y);var on=c._pthread_self=()=>(on=c._pthread_self=ee.Aa)(),zn=c._malloc=y=>(zn=c._malloc=ee.Ba)(y),Ni=c._free=y=>(Ni=c._free=ee.Ca)(y);c.__emscripten_tls_init=()=>(c.__emscripten_tls_init=ee.Da)();var Li=c.__emscripten_thread_init=(y,S,A,B,H,re)=>(Li=c.__emscripten_thread_init=ee.Fa)(y,S,A,B,H,re);c.__emscripten_thread_crashed=()=>(c.__emscripten_thread_crashed=ee.Ga)();var Ui=(y,S,A,B)=>(Ui=ee.Ha)(y,S,A,B),Pn=y=>(Pn=ee.Ia)(y),jn=c.__emscripten_thread_exit=y=>(jn=c.__emscripten_thread_exit=ee.Ja)(y),Fi=c.__emscripten_check_mailbox=()=>(Fi=c.__emscripten_check_mailbox=ee.Ka)(),Wi=y=>(Wi=ee.La)(y),Gi=(y,S)=>(Gi=ee.Ma)(y,S),Rn=()=>(Rn=ee.Na)(),ln=y=>(ln=ee.Oa)(y),Bn=y=>(Bn=ee.Pa)(y),Vi=c.dynCall_ii=(y,S)=>(Vi=c.dynCall_ii=ee.Ra)(y,S),Hi=y=>(Hi=ee.Sa)(y),qi=()=>(qi=ee.Ta)(),Ki=y=>(Ki=ee.Ua)(y),Yi=()=>(Yi=ee.Va)();c.___start_em_js=917678,c.___stop_em_js=917839;function ws(y){y=Object.assign({},y);var S=B=>()=>B()>>>0,A=B=>H=>B(H)>>>0;return y.__errno_location=S(y.__errno_location),y.pthread_self=S(y.pthread_self),y.malloc=A(y.malloc),y.stackSave=S(y.stackSave),y.stackAlloc=A(y.stackAlloc),y}c.keepRuntimeAlive=ot,c.wasmMemory=ne,c.stackAlloc=Bn,c.stackSave=Rn,c.stackRestore=ln,c.UTF8ToString=gt,c.stringToUTF8=rs,c.lengthBytesUTF8=Sn,c.ExitStatus=Or,c.PThread=Ie;var un;ar=function y(){un||Qi(),un||(ar=y)};function Qi(){function y(){if(!un&&(un=!0,c.calledRun=!0,!Te)&&(j||zr(It),_(c),c.onRuntimeInitialized&&c.onRuntimeInitialized(),!j)){if(c.postRun)for(typeof c.postRun=="function"&&(c.postRun=[c.postRun]);c.postRun.length;){var S=c.postRun.shift();ir.unshift(S)}zr(ir)}}if(!(0r)}),ew=cn((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");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>(0,eval)(fs.readFileSync(e,"utf8")+"//# sourceURL="+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&&Module.__emscripten_thread_crashed(),a}}self.onmessage=handleMessage;\n'}),ql,Kl,Bs,oa,Fn,Ds,Yl,Ql,Xl,Zl,ut,Wn=le(()=>{ql=Y0(),Kl=J0(),oa=!1,Fn=!1,Ds=!1,Yl=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}},Ql=()=>{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}},Xl=(t,e)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Zl=async t=>{if(oa)return Promise.resolve();if(Fn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ds)throw new Error("previous call to 'initializeWebAssembly()' failed.");Fn=!0;let e=t.initTimeout,r=t.numThreads,n=t.simd,a=Yl(r),o=n&&Ql(),i=t.wasmPaths,d=typeof i=="string"?i:void 0,h=Xl(o,a),m=typeof i=="object"?i[h]:void 0,c=!1,_=[];if(e>0&&_.push(new Promise(v=>{setTimeout(()=>{c=!0,v()},e)})),_.push(new Promise((v,$)=>{let C=a?Kl:ql,k={locateFile:(M,z)=>{if(a&&M.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([ew()],{type:"text/javascript"}));if(M.endsWith(".wasm")){if(m)return m;let I=d??z;return h==="ort-wasm-simd.wasm"?I+"ort-wasm-simd.jsep.wasm":h==="ort-wasm-simd-threaded.wasm"?I+"ort-wasm-simd-threaded.jsep.wasm":I+h}return z+M}};if(a)if(k.numThreads=r,typeof Blob>"u")k.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let M=`var ortWasmThreaded=${C.toString()};`;k.mainScriptUrlOrBlob=new Blob([M],{type:"text/javascript"})}C(k).then(M=>{Fn=!1,oa=!0,Bs=M,v()},M=>{Fn=!1,Ds=!0,$(M)})})),await Promise.race(_),c)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},ut=()=>{if(oa&&Bs)return Bs;throw new Error("WebAssembly is not initialized yet.")}}),nt,la,Xe,Ns=le(()=>{Wn(),nt=(t,e)=>{let r=ut(),n=r.lengthBytesUTF8(t)+1,a=r._malloc(n);return r.stringToUTF8(t,a,n),e.push(a),a},la=(t,e,r,n)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([a,o])=>{let i=e?e+a:a;if(typeof o=="object")la(o,i+".",r,n);else if(typeof o=="string"||typeof o=="number")n(i,o.toString());else if(typeof o=="boolean")n(i,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Xe=t=>{let e=ut(),r=e.stackSave();try{let n=e.stackAlloc(8);e._OrtGetLastError(n,n+4);let a=e.HEAP32[n/4],o=e.HEAPU32[n/4+1],i=o?e.UTF8ToString(o):"";throw new Error(`${t} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),Jl,tw=le(()=>{Wn(),Ns(),Jl=t=>{let e=ut(),r=0,n=[],a=t||{};try{if((t==null?void 0:t.logSeverityLevel)===void 0)a.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if((t==null?void 0:t.logVerbosityLevel)===void 0)a.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);(t==null?void 0:t.terminate)===void 0&&(a.terminate=!1);let o=0;return(t==null?void 0:t.tag)!==void 0&&(o=nt(t.tag,n)),r=e._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),r===0&&Xe("Can't create run options."),(t==null?void 0:t.extra)!==void 0&&la(t.extra,"",new WeakSet,(i,d)=>{let h=nt(i,n),m=nt(d,n);e._OrtAddRunConfigEntry(r,h,m)!==0&&Xe(`Can't set a run config entry: ${i} - ${d}.`)}),[r,n]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),n.forEach(i=>e._free(i)),o}}}),eu,tu,ru,nu,iu,rw=le(()=>{Wn(),Ns(),eu=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}`)}},tu=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},ru=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},nu=(t,e,r)=>{for(let n of e){let a=typeof n=="string"?n:n.name;switch(a){case"webnn":if(a="WEBNN",typeof n!="string"){let i=n;if(i!=null&&i.deviceType){let d=nt("deviceType",r),h=nt(i.deviceType,r);ut()._OrtAddSessionConfigEntry(t,d,h)!==0&&Xe(`Can't set a session config entry: 'deviceType' - ${i.deviceType}.`)}if(i!=null&&i.numThreads){let d=i.numThreads;(typeof d!="number"||!Number.isInteger(d)||d<0)&&(d=0);let h=nt("numThreads",r),m=nt(d.toString(),r);ut()._OrtAddSessionConfigEntry(t,h,m)!==0&&Xe(`Can't set a session config entry: 'numThreads' - ${i.numThreads}.`)}if(i!=null&&i.powerPreference){let d=nt("powerPreference",r),h=nt(i.powerPreference,r);ut()._OrtAddSessionConfigEntry(t,d,h)!==0&&Xe(`Can't set a session config entry: 'powerPreference' - ${i.powerPreference}.`)}}break;case"webgpu":if(a="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let d=nt("preferredLayout",r),h=nt(i.preferredLayout,r);ut()._OrtAddSessionConfigEntry(t,d,h)!==0&&Xe(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let o=nt(a,r);ut()._OrtAppendExecutionProvider(t,o)!==0&&Xe(`Can't append execution provider: ${a}.`)}},iu=t=>{let e=ut(),r=0,n=[],a=t||{};ru(a);try{let o=eu(a.graphOptimizationLevel??"all"),i=tu(a.executionMode??"sequential"),d=typeof a.logId=="string"?nt(a.logId,n):0,h=a.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log serverity level is not valid: ${h}`);let m=a.logVerbosityLevel??0;if(!Number.isInteger(m)||m<0||m>4)throw new Error(`log verbosity level is not valid: ${m}`);let c=typeof a.optimizedModelFilePath=="string"?nt(a.optimizedModelFilePath,n):0;if(r=e._OrtCreateSessionOptions(o,!!a.enableCpuMemArena,!!a.enableMemPattern,i,!!a.enableProfiling,0,d,h,m,c),r===0&&Xe("Can't create session options."),a.executionProviders&&nu(r,a.executionProviders,n),a.enableGraphCapture!==void 0){if(typeof a.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${a.enableGraphCapture}`);let _=nt("enableGraphCapture",n),v=nt(a.enableGraphCapture.toString(),n);e._OrtAddSessionConfigEntry(r,_,v)!==0&&Xe(`Can't set a session config entry: 'enableGraphCapture' - ${a.enableGraphCapture}.`)}if(a.freeDimensionOverrides)for(let[_,v]of Object.entries(a.freeDimensionOverrides)){if(typeof _!="string")throw new Error(`free dimension override name must be a string: ${_}`);if(typeof v!="number"||!Number.isInteger(v)||v<0)throw new Error(`free dimension override value must be a non-negative integer: ${v}`);let $=nt(_,n);e._OrtAddFreeDimensionOverride(r,$,v)!==0&&Xe(`Can't set a free dimension override: ${_} - ${v}.`)}return a.extra!==void 0&&la(a.extra,"",new WeakSet,(_,v)=>{let $=nt(_,n),C=nt(v,n);e._OrtAddSessionConfigEntry(r,$,C)!==0&&Xe(`Can't set a session config entry: ${_} - ${v}.`)}),[r,n]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r),n.forEach(i=>e._free(i)),o}}}),Ls,Lr,Gn,Us,ua,Fs,Ws,Oe=le(()=>{Ls=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}`)}},Lr=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}`)}},Gn=t=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][t],Us=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},ua=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}`)}},Fs=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool",Ws=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}`)}}}),da,au=le(()=>{da=async t=>{if(typeof t=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(t),n=[];for await(let a of r)n.push(a);return new Uint8Array(Buffer.concat(n))}throw e}else{let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let a=e.body.getReader(),o;try{o=new ArrayBuffer(n)}catch(d){if(d instanceof RangeError){let h=Math.ceil(n/65536);o=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw d}let i=0;for(;;){let{done:d,value:h}=await a.read();if(d)break;let m=h.byteLength;new Uint8Array(o,i,m).set(h),i+=m}return new Uint8Array(o,0,n)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),su,ou,lu,uu,du,cu,it,Ur=le(()=>{Oe(),su=["V","I","W","E","F"],ou=(t,e)=>{console.log(`[${su[t]},${new Date().toISOString()}]${e}`)},du=(t,e)=>{lu=t,uu=e},cu=(t,e)=>{let r=ua(t),n=ua(lu);r>=n&&ou(r,typeof e=="function"?e():e)},it=(...t)=>{uu&&cu(...t)}}),pu,nw=le(()=>{Oe(),pu=(t,e)=>new(Us(e))(t)}),Gs=le(()=>{}),Vs,ca,pa,hu,fu,Hs,qs,mu,gu,iw=le(()=>{Ur(),Gs(),Vs=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),ca=[],pa=t=>Math.ceil(t/16)*16,hu=t=>{for(let e=0;efu++,qs=async(t,e,r,n)=>{let a=pa(r),o=t.device.createBuffer({size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=t.getCommandEncoder();t.endComputePass(),i.copyBufferToBuffer(e,0,o,0,a),t.flush(),await o.mapAsync(GPUMapMode.READ);let d=o.getMappedRange();if(n){let h=n();return h.set(new Uint8Array(d,0,r)),h}else return new Uint8Array(d.slice(0,r))}finally{o.destroy()}},mu=class{constructor(t){this.backend=t,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[e]of Vs)ca.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[])}upload(t,e){let r=e.buffer,n=e.byteOffset,a=e.byteLength,o=pa(a),i=this.storageCache.get(t);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==a)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${a}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=d.getMappedRange();new Uint8Array(h).set(new Uint8Array(r,n,a)),d.unmap();let m=this.backend.getCommandEncoder();this.backend.endComputePass(),m.copyBufferToBuffer(d,0,i.gpuData.buffer,0,o),it("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(d)}memcpy(t,e){let r=this.storageCache.get(t);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(e);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let a=pa(r.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,a)}registerExternalBuffer(t,e,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(t===r)return it("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`);this.externalBuffers.delete(r)}else n=Hs();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:e}),this.externalBuffers.set(t,n),it("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${n}, registered.`),n}unregisterExternalBuffer(t){let e=this.externalBuffers.get(t);e!==void 0&&(this.storageCache.delete(e),this.externalBuffers.delete(t),it("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(t,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=hu(t),n,a=(e&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(e&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(a||o){let d=(a?this.freeBuffers:this.freeUniformBuffers).get(r);d?d.length>0?n=d.pop():n=this.backend.device.createBuffer({size:r,usage:e}):n=this.backend.device.createBuffer({size:r,usage:e})}else n=this.backend.device.createBuffer({size:r,usage:e});let i={id:Hs(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:t}),it("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${i.id}`),i}get(t){var e;return(e=this.storageCache.get(t))==null?void 0:e.gpuData}release(t){let e=this.storageCache.get(t);if(!e)throw new Error("releasing data does not exist");return it("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${e.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(e.gpuData.buffer),e.originalSize}async download(t,e){let r=this.storageCache.get(t);if(!r)throw new Error("data does not exist");await qs(this.backend,r.gpuData.buffer,r.originalSize,e)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let e=Vs.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(t.size)||[];e===void 0||r.length>=e?t.destroy():r.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(t.size)||[];e===void 0||r.length>=e?t.destroy():r.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let e of this.buffersPending)t.push(e);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let e=this.capturedPendingBuffers.get(t);e&&(e.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(t))}},gu=(...t)=>new mu(...t)}),yu,Ze,ft=le(()=>{yu=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}},Ze=t=>new yu(t)}),_u,hn,se,ha,wu,Ks,Ys,Be=le(()=>{_u=class{static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}},hn=class{static calcShape(t,e,r=!1){let n=t.length,a=e.length;if(n===0)return e;if(a===0)return t;let o=Math.max(t.length,e.length),i=new Array(o);if(r){if(n<2||a<2)return;let d=_u.calcMatMulShape([t[n-2],t[n-1]],[e[a-2],e[a-1]]);if(d===void 0)return;[i[o-2],i[o-1]]=d}for(let d=r?3:1;d<=o;d++){let h=n-d<0?1:t[n-d],m=a-d<0?1:e[a-d];if(h!==m&&h>1&&m>1)return;let c=Math.max(h,m);if(h&&m)i[o-d]=Math.max(h,m);else{if(c>1)return;i[o-d]=0}}return i}static isValidBroadcast(t,e){let r=t.length,n=e.length;if(r>n)return!1;for(let a=1;a<=r;a++)if(t[r-a]!==1&&t[r-a]!==e[n-a])return!1;return!0}},se=class bs{static size(e){return bs.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,r=4){let n=e.length;if(n===0)return[];let a=new Array(n),o=n-1;for(;o>=0;){if(e[o]%r===0){a[o]=e[o]/r;break}if(r%e[o]!==0)throw new Error("cannot convert shape");a[o]=1,r/=e[o],o--}for(o--;o>=0;o--)a[o]=e[o];return a}static sizeFromDimension(e,r){if(r<0||r>e.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return bs.getSizeFromDimensionRange(e,r,e.length)}static sizeToDimension(e,r){if(r<0||r>e.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${e.length} dimensions.`);return bs.getSizeFromDimensionRange(e,0,r)}static getSizeFromDimensionRange(e,r,n){let a=1;for(let o=r;o=0;--a)n[a]=n[a+1]*e[a+1];return n}static normalizeAxis(e,r){if(e<-r&&e>=r)throw new Error("unsupported axis for this operation.");return e<0?e+r:e}static normalizeAxes(e,r){return e.map(n=>this.normalizeAxis(n,r??e.length))}static sortBasedOnPerm(e,r){return r?r.map(n=>e[n]):e.slice().reverse()}static padShape(e,r){let n=e.length;return e.map((a,o)=>a+r[o]+r[o+n])}static areEqual(e,r){return e.length!==r.length?!1:e.every((n,a)=>n===r[a])}},ha=class Zi{static adjustPoolAttributes(e,r,n,a,o,i){if(!e&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let d=0;d=n.length?n.push(r[d+2]):n[d]=r[d+2];for(let d=0;d=n[d]||i[d+n.length]>=n[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,r,n,a,o,i,d){if(d){if(o.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(a.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let h=0;h{Oe(),Be(),fn=64,fa=(t,e)=>{if(e===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(t){case 10:return e>1?`vec${e}`:"f16";case 1:return e>1?`vec${e}`:"f32";case 6:return e>1?`vec${e}`:"i32";case 12:return e>1?`vec${e}`:"u32";case 7:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(e!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${t}`)}},mt=(t,e=1)=>{let r=fa(t,e);return typeof r=="string"?r:r[0]},kt=(t,e=1)=>{let r=fa(t,e);return typeof r=="string"?r:r[1]},Ce=(...t)=>{let e=[];return t.forEach(r=>{r.length!==0&&e.push({type:12,data:r},{type:12,data:se.computeStrides(r)})}),e},dt=t=>t%4===0?4:t%2===0?2:1,gr=(t="f32",e,r="0")=>!e||e===1?`${t}(${r})`:`vec${e}<${t}>(${r})`,mn=(t,e,r)=>t==="f32"?r:e===1?`f32(${r})`:`vec${e}(${r})`,kr=(t,e)=>e===4?`(${t}.x + ${t}.y + ${t}.z + ${t}.w)`:e===2?`(${t}.x + ${t}.y)`:e===3?`(${t}.x + ${t}.y + ${t}.z)`:t,ze=(t,e,r,n)=>t.startsWith("uniforms.")&&r>4?typeof e=="string"?n==="f16"?`${t}[(${e}) / 8][(${e}) % 8 / 4][(${e}) % 8 % 4]`:`${t}[(${e}) / 4][(${e}) % 4]`:n==="f16"?`${t}[${Math.floor(e/8)}][${Math.floor(e%8/4)}][${e%8%4}]`:`${t}[${Math.floor(e/4)}][${e%4}]`:r>1?`${t}[${e}]`:t,ma=(t,e,r,n,a)=>{let o=typeof r=="number",i=o?r:r.length,d=[...new Array(i).keys()],h=i<2?"u32":i<=4?`vec${i}`:`array`,m=fa(e,a),c=typeof m=="string"?m:m[1],_=typeof m=="string"?m:m[0],v={indices:h,value:c,storage:_,tensor:e},$=K=>typeof K=="string"?K:`${K}u`,C={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},k=o?"uniforms.":"",M=`${k}${t}_shape`,z=`${k}${t}_strides`,I="";for(let K=0;K ${v.indices} { var indices: ${v.indices}; var current = offset; ${I} return indices; }`,R=K=>(C.offsetToIndices=!0,i<2?K:`o2i_${t}(${K})`),L=[];if(i>=2)for(let K=i-1;K>=0;K--)L.push(`${ze(z,K,i)} * (indices[${K}])`);let Y=i<2?"":` fn i2o_${t}(indices: ${v.indices}) -> u32 { return ${L.join("+")}; }`,Q=K=>(C.indicesToOffset=!0,i<2?K:`i2o_${t}(${K})`),ie=(...K)=>i===0?"0u":`${v.indices}(${K.map($).join(",")})`,pe=(K,he)=>i<2?`${K}`:`${ze(K,he,i)}`,ce=(K,he,ve)=>i<2?`${K}=${ve};`:`${ze(K,he,i)}=${ve};`,Se={},fe=(K,he)=>{C.broadcastedIndicesToOffset=!0;let ve=`${he.name}broadcastedIndicesTo${t}Offset`;if(ve in Se)return`${ve}(${K})`;let Le=[];for(let Ke=i-1;Ke>=0;Ke--){let ct=he.indicesGet("outputIndices",Ke+he.rank-i);Le.push(`${pe(z,Ke)} * (${ct} % ${pe(M,Ke)})`)}return Se[ve]=`fn ${ve}(outputIndices: ${he.type.indices}) -> u32 { return ${Le.length>0?Le.join("+"):"0u"}; }`,`${ve}(${K})`},me=(K,he)=>(()=>{if(v.storage===v.value)return`${t}[${K}]=${he};`;if(v.storage==="vec2"&&v.value==="i32")return`${t}[${K}]=vec2(u32(${he}), select(0u, 0xFFFFFFFFu, ${he} < 0));`;if(v.storage==="vec2"&&v.value==="u32")return`${t}[${K}]=vec2(u32(${he}), 0u);`;if(v.storage==="u32"&&v.value==="vec4")return`${t}[${K}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${he}));`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),ge=K=>(()=>{if(v.storage===v.value)return`${t}[${K}]`;if(v.storage==="vec2"&&v.value==="i32")return`i32(${t}[${K}].x)`;if(v.storage==="vec2"&&v.value==="u32")return`u32(${t}[${K}].x)`;if(v.storage==="u32"&&v.value==="vec4")return`vec4(bool(${t}[${K}] & 0xFFu), bool(${t}[${K}] & 0xFF00u), bool(${t}[${K}] & 0xFF0000u), bool(${t}[${K}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),X=i<2?"":` fn get_${t}ByIndices(indices: ${v.indices}) -> ${c} { return ${ge(`i2o_${t}(indices)`)}; }`,U=i<2?"":(()=>{let K=d.map(ve=>`d${ve}: u32`).join(", "),he=d.map(ve=>`d${ve}`).join(", ");return` fn get_${t}(${K}) -> ${c} { return get_${t}ByIndices(${ie(he)}); }`})(),ne=(...K)=>{if(K.length!==i)throw new Error(`indices length must be ${i}`);let he=K.map($).join(",");return i===0?ge("0u"):i===1?ge(he[0]):(C.get=!0,C.getByIndices=!0,C.indicesToOffset=!0,`get_${t}(${he})`)},ee=K=>i<2?ge(K):(C.getByIndices=!0,C.indicesToOffset=!0,`get_${t}ByIndices(${K})`),Ee=i<2?"":` fn set_${t}ByIndices(indices: ${v.indices}, value: ${c}) { ${me(`i2o_${t}(indices)`,"value")} }`,Te=i<2?"":(()=>{let K=d.map(ve=>`d${ve}: u32`).join(", "),he=d.map(ve=>`d${ve}`).join(", ");return` fn set_${t}(${K}, value: ${c}) { set_${t}ByIndices(${ie(he)}, value); }`})();return{impl:()=>{let K=[],he=!1;return C.offsetToIndices&&(K.push(j),he=!0),C.indicesToOffset&&(K.push(Y),he=!0),C.broadcastedIndicesToOffset&&(Object.values(Se).forEach(ve=>K.push(ve)),he=!0),C.set&&(K.push(Te),he=!0),C.setByIndices&&(K.push(Ee),he=!0),C.get&&(K.push(U),he=!0),C.getByIndices&&(K.push(X),he=!0),!o&&he&&K.unshift(`const ${M} = ${v.indices}(${r.join(",")});`,`const ${z} = ${v.indices}(${se.computeStrides(r).join(",")});`),K.join(` `)},type:v,offsetToIndices:R,indicesToOffset:Q,broadcastedIndicesToOffset:fe,indices:ie,indicesGet:pe,indicesSet:ce,set:(...K)=>{if(K.length!==i+1)throw new Error(`indices length must be ${i}`);let he=K[i];if(typeof he!="string")throw new Error("value must be string");let ve=K.slice(0,i).map($).join(",");return i===0?me("0u",he):i===1?me(ve[0],he):(C.set=!0,C.setByIndices=!0,C.indicesToOffset=!0,`set_${t}(${ve}, ${he})`)},setByOffset:me,setByIndices:(K,he)=>i<2?me(K,he):(C.setByIndices=!0,C.indicesToOffset=!0,`set_${t}ByIndices(${K}, ${he});`),get:ne,getByOffset:ge,getByIndices:ee,usage:n,name:t,strides:z,shape:M,rank:i}},oe=(t,e,r,n=1)=>ma(t,e,r,"input",n),$e=(t,e,r,n=1)=>ma(t,e,r,"output",n),Qs=(t,e,r,n=1)=>ma(t,e,r,"internal",n),vu=class{constructor(t,e){this.normalizedDispatchGroup=t,this.limits=e,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=fn){let e=typeof t=="number"?t:t[0],r=typeof t=="number"?1:t[1],n=typeof t=="number"?1:t[2];if(e>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${e}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(e*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${e}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let a=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=a?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,i=a?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${e*r*n}u + local_idx;`;return`@compute @workgroup_size(${e}, ${r}, ${n}) fn main(${o}) { ${i} `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,e){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let r=t.usage==="input"?"read":"read_write",n=t.type.storage;return`@group(0) @binding(${e}) var ${t.name}: array<${n}>;`}declareVariables(...t){return t.map(e=>this.declareVariable(e,this.variableIndex++)).join(` `)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(e=>this.registerInternalVariable(e)),this}registerUniform(t,e,r=1){return this.uniforms.push({name:t,type:e,length:r}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:e,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?t.push(`@align(16) ${e}:array, ${Math.ceil(n/8)}>`):t.push(`${e}:array, ${Math.ceil(n/4)}>`);else{let a=n==null||n===1?r:`vec${n}<${r}>`;t.push(`${e}:${a}`)}return` struct Uniforms { ${t.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(` `)+this.internalVariables.map(t=>t.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let t=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map(e=>[t(e.type),e.length??1])}},bu=(t,e)=>new vu(t,e),Vn=(t,e)=>{let r=t.length,n=[];for(let a=0;a1&&i===1&&n.unshift(o)}return n}}),$u,Xs,xu,Cu,yr,Su,Eu,Hn=le(()=>{Oe(),Be(),ft(),Re(),$u=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},Xs=(t,e)=>e&&e.length!==t?[...new Array(t).keys()].reverse():e,xu=(t,e)=>se.sortBasedOnPerm(t,Xs(t.length,e)),Cu=(t,e,r,n)=>{let a=[];a.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let o=0;o{let r=t.dataType,n=t.dims.length,a=Xs(n,e),o=xu(t.dims,a),i=$e("output",r,o.length),d=oe("a",r,n),h=m=>` ${m.registerUniform("output_size","u32").declareVariables(d,i)} ${Cu(a,n,d,i)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${i.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${i.setByOffset("global_idx",d.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:["rank"]},getRunData:m=>{let c=se.size(o);return{outputs:[{dims:o,dataType:m[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},...Ce(m[0].dims,o)]}},getShaderSource:h}},Su=(t,e)=>{$u(t.inputs),t.compute(yr(t.inputs[0],e.perm))},Eu=t=>Ze({perm:t.perm})}),ku,Tu,Iu,Au,Mu,Ou,zu,Pu,ju,Ru,Qt,Bu,Du,Nu,Lu,Uu,Fu,Wu,Gu,Vu,Hu,aw=le(()=>{Oe(),Be(),Re(),Js(),Hn(),ku={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Tu={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},Iu={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Au={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Mu=(t,e)=>{let r=[];for(let n=e-t;n{let r=[],n=t.length;for(let o=0;ot[o]);return[r,a]},zu=(t,e)=>{let r=t.length+e.length,n=[],a=0;for(let o=0;o{for(let r=0;r{let r=[];if(!Pu(t,e)){for(let n=0;nr.push(n))}return r},Ru=(t,e,r,n,a,o,i)=>{let d=r[0].dims,h=se.size(o),m=se.size(i),c=oe("_A",r[0].dataType,d),_=$e("output",a,o),v=32,$=` var aBestValues : array; `;return{name:t,shaderCache:e,getShaderSource:C=>` ${C.registerUniform("reduceSize","u32").declareVariables(c,_)} ${$} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${C.mainStart(v)} let outputIndex = global_idx / ${v}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Iu[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${v}) { let candidate = f32(${c.getByOffset("offset + k")}); bestValue = ${ku[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${v}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${Tu[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${_.setByOffset("outputIndex",`${n==="mean"?`${_.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${_.type.storage}(${Au[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:o,dataType:a}],dispatchGroup:{x:h},programUniforms:[{type:12,data:m}]})}},Qt=(t,e,r,n)=>{let a=t.inputs.length===1?r:Zs(t.inputs,r),o=a.axes;o.length===0&&!a.noopWithEmptyAxes&&(o=t.inputs[0].dims.map(($,C)=>C));let i=se.normalizeAxes(o,t.inputs[0].dims.length),d=i,h=t.inputs[0],m=ju(d,t.inputs[0].dims.length);m.length>0&&(h=t.compute(yr(t.inputs[0],m),{inputs:[0],outputs:[-1]})[0],d=Mu(d.length,h.dims.length));let[c,_]=Ou(h.dims,d),v=c;a.keepDims&&(v=zu(c,i)),t.compute(Ru(e,{hint:a.cacheKey,inputDependencies:["type"]},[h],n,t.inputs[0].dataType,v,_),{inputs:[h]})},Bu=(t,e)=>{Qt(t,"ReduceMeanShared",e,"mean")},Du=(t,e)=>{Qt(t,"ReduceL1Shared",e,"l1")},Nu=(t,e)=>{Qt(t,"ReduceL2Shared",e,"l2")},Lu=(t,e)=>{Qt(t,"ReduceLogSumExpShared",e,"logSumExp")},Uu=(t,e)=>{Qt(t,"ReduceMaxShared",e,"max")},Fu=(t,e)=>{Qt(t,"ReduceMinShared",e,"min")},Wu=(t,e)=>{Qt(t,"ReduceProdShared",e,"prod")},Gu=(t,e)=>{Qt(t,"ReduceSumShared",e,"sum")},Vu=(t,e)=>{Qt(t,"ReduceSumSquareShared",e,"sumSquare")},Hu=(t,e)=>{Qt(t,"ReduceLogSumShared",e,"logSum")}}),Xt,qu,ga,Zs,Zt,Ku,Yu,Qu,Xu,Zu,Ju,ed,td,rd,nd,Jt,id,ad,sd,od,ld,ud,dd,cd,pd,hd,Js=le(()=>{Oe(),Be(),ft(),Re(),aw(),Xt=t=>{if(!t||t.length===0||t.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(t.length===2&&t[1].dims.length!==1)throw new Error("Invalid axes input dims.")},qu=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],ga=(t,e,r,n,a,o,i=!1,d=!1)=>{let h=[],m=r[0].dims,c=m.length,_=se.normalizeAxes(a,c),v=!d&&_.length===0;m.forEach((k,M)=>{v||_.indexOf(M)>=0?i&&h.push(1):h.push(k)});let $=h.length,C=se.size(h);return{name:t,shaderCache:e,getShaderSource:k=>{let M=[],z=oe("_A",r[0].dataType,c),I=$e("output",o,$),j=n(z,I,_),R=j[2];for(let L=0,Y=0;L=0?(i&&Y++,R=`for(var j${L}: u32 = 0; j${L} < ${m[L]}; j${L}++) { ${j[2].includes("last_index")?`let last_index = j${L};`:""} ${z.indicesSet("input_indices",L,`j${L}`)} ${R} }`):(M.push(`${z.indicesSet("input_indices",L,I.indicesGet("output_indices",Y))};`),Y++);return` ${k.registerUniform("output_size","u32").declareVariables(z,I)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${z.type.indices}; let output_indices = ${I.offsetToIndices("global_idx")}; ${M.join(` `)} ${j[0]} // init ops for reduce max/min ${j[1]} ${R} ${j[3]} ${j.length===4?I.setByOffset("global_idx","value"):j.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:h,dataType:o}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...Ce(m,h)]})}},Zs=(t,e)=>{let r=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(n=>r.push(Number(n))),Ze({axes:r,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},Zt=(t,e,r,n)=>{let a=t.inputs,o=a.length===1?r:Zs(a,r);t.compute(ga(e,{hint:o.cacheKey,inputDependencies:["rank"]},[a[0]],o.noopWithEmptyAxes&&o.axes.length===0?qu:n,o.axes,a[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Ku=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceLogSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Yu=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceL1",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Qu=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceL2",e,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Xu=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceLogSumExp",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Zu=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceMax",e,(r,n,a)=>{let o=[];for(let i=0;i=0||a.length===0)&&o.push(r.indicesSet("input_indices",i,0));return[`${o.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},Ju=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceMean",e,(r,n,a)=>{let o=1;for(let i=0;i=0||a.length===0)&&(o*=t.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${o});`]})},ed=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceMin",e,(r,n,a)=>{let o=[];for(let i=0;i=0||a.length===0)&&o.push(`input_indices[${i}] = 0;`);return[`${o.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},td=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceProd",e,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},rd=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceSum",e,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},nd=(t,e)=>{Xt(t.inputs),Zt(t,"ReduceSumSquare",e,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},Jt=(t,e,r)=>{if(e.length===0)return r;let n=1,a=1;for(let o=0;o1024},id=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ju(t,e):Bu(t,e)},ad=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Yu(t,e):Du(t,e)},sd=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Qu(t,e):Nu(t,e)},od=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Xu(t,e):Lu(t,e)},ld=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Zu(t,e):Uu(t,e)},ud=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?ed(t,e):Fu(t,e)},dd=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?td(t,e):Wu(t,e)},cd=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?rd(t,e):Gu(t,e)},pd=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?nd(t,e):Vu(t,e)},hd=(t,e)=>{Jt(t.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ku(t,e):Hu(t,e)}}),eo,fd,md,to,sw=le(()=>{Oe(),ft(),Js(),eo=t=>{if(!t||t.length===0||t.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(t[0].dataType!==1)throw new Error("Invalid input type.")},fd=(t,e)=>{eo(t.inputs);let r=(n,a,o)=>{let i=[];for(let d=0;d=0||o.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${e.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",a.setByOffset("global_idx","best_index")]};t.compute(ga("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},md=(t,e)=>{eo(t.inputs);let r=(n,a,o)=>{let i=[];for(let d=0;d=0||o.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${e.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",a.setByOffset("global_idx","best_index")]};t.compute(ga("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},to=t=>Ze(t)}),gd,yd,_d,ya,wd,vd,bd=le(()=>{Oe(),Be(),ft(),Re(),gd=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");let r=0,n=t[r],a=n.dataType,o=n.dims.length;t.forEach((i,d)=>{if(d!==r){if(i.dataType!==a)throw new Error("input tensors should be one type");if(i.dims.length!==o)throw new Error("input tensors should have the same shape");i.dims.forEach((h,m)=>{if(m!==e&&h!==n.dims[m])throw new Error("non concat dimensions must match")})}})},yd=(t,e)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${e}); for (var i: u32 = 0u; i < ${t}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${t}u; }`,_d=(t,e)=>{let r=t.length,n=[];for(let a=0;a{let a=se.size(r),o=new Array(t.length),i=new Array(t.length),d=0,h=[],m=[],c=[{type:12,data:a}];for(let k=0;k`uniforms.sizeInConcatAxis${k}`).join(","),C=k=>` ${(()=>{k.registerUniform("outputSize","u32");for(let M=0;M(${$}); ${v} -= sizeInConcatAxis[inputIndex - 1u]; } ${_d(i,_)} }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:C}},wd=(t,e)=>{let r=t.inputs,n=r[0].dims,a=se.normalizeAxis(e.axis,n.length);gd(r,a);let o=n.slice();o[a]=r.reduce((d,h)=>d+(h.dims.length>a?h.dims[a]:0),0);let i=r.filter(d=>se.size(d.dims)>0);t.compute(ya(i,a,o,r[0].dataType),{inputs:i})},vd=t=>Ze({axis:t.axis})}),$d,xd,Cd,Sd,_a,Ed,kd,Td=le(()=>{Oe(),Gs(),Re(),bd(),$d=(t,e)=>{let r=t[0],n=t[1],a=t[2],o=t[3],i=t[4],d=t[5];if(i&&d)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 h=r.dims[0],m=r.dims[1],c=r.dims[2];if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==c)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(a.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let _=a.dims[0]/3,v=_,$=v;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let j of e.qkvHiddenSizes)if(j%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");_=e.qkvHiddenSizes[0],v=e.qkvHiddenSizes[1],$=e.qkvHiddenSizes[2]}let C=m;if(_!==v)throw new Error("qkv_hidden_sizes first element should be same as the second");if(a.dims[0]!==_+v+$)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let k=0;if(i){if(v!==$)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==h)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==e.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==v/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(k=i.dims[3])}let M=C+k,z=-1,I=0;if(o)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");return{batchSize:h,sequenceLength:m,pastSequenceLength:k,kvSequenceLength:C,totalSequenceLength:M,maxSequenceLength:z,inputHiddenSize:c,hiddenSize:_,vHiddenSize:$,headSize:Math.floor(_/e.numHeads),vHeadSize:Math.floor($/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:I,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},xd=(t,e,r,n)=>{let a=dt(n),o=64,i=n/a;i{let $=$e("x",e.dataType,e.dims,a),C=[{name:"d_inv",type:kt(e.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${v.registerUniforms(C).declareVariables($)} ${v.mainStart([o,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = workgroup_id.x * uniforms.d_comp + local_offset; var thread_max_vector = ${c}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${c}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(a){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${a}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${o}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${c}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${c}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(a){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${a}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${o}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${$.type.value}(uniforms.d_inv); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${c}(x[offset + i]); x[offset + i] = ${$.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${o};${m};${a}`},getShaderSource:_,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:h})}},Cd=(t,e,r,n,a,o,i)=>{let d=i+a.kvSequenceLength,h=[a.batchSize,a.numHeads,a.sequenceLength,d],m=o.scale===0?1/Math.sqrt(a.headSize):o.scale,c=dt(a.headSize),_=a.headSize/c,v=12,$={x:Math.ceil(d/v),y:Math.ceil(a.sequenceLength/v),z:a.batchSize*a.numHeads},C=[{type:12,data:a.sequenceLength},{type:12,data:_},{type:12,data:d},{type:12,data:a.numHeads},{type:1,data:m}],k=["type","type"];n&&(k.push("rank"),C.push(...Ce(n.dims)));let M=z=>{let I=oe("q",e.dataType,e.dims,c),j=oe("key",r.dataType,r.dims,c),R=[I,j],L=n?oe("relative_position_bias",n.dataType,n.dims.length):void 0;L&&R.push(L);let Y=$e("output",e.dataType,h),Q=kt(1,c),ie=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return` const TILE_SIZE = ${v}u; var tileQ: array<${I.type.storage}, ${v*v}>; var tileK: array<${I.type.storage}, ${v*v}>; ${z.registerUniforms(ie).declareVariables(...R,Y)} ${z.mainStart([v,v,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K; var value = ${Q}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x]; } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${Q}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(c){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${c}`)}})()}; ${L?` let batch = workgroup_id.z / uniforms.num_heads; let head = workgroup_id.z % uniforms.num_heads; var indices = ${L.type.indices}(batch, head, global_id.y, global_id.x); output[outputIdx] = ${Y.type.value}(sum * uniforms.alpha) + ${L.getByIndices("indices")};`:`output[outputIdx] = ${Y.type.value} (sum * uniforms.alpha);`} } }`};return{name:"AttentionProbs",shaderCache:{hint:`${c}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:h,dataType:e.dataType,gpuDataType:0}],dispatchGroup:$,programUniforms:C}),getShaderSource:M}},Sd=(t,e,r,n,a)=>{let o=a+n.kvSequenceLength,i=[n.batchSize,n.sequenceLength,n.vHiddenSize],d=12,h={x:Math.ceil(n.vHeadSize/d),y:Math.ceil(n.sequenceLength/d),z:n.batchSize*n.numHeads},m=[{type:12,data:n.sequenceLength},{type:12,data:o},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType,gpuDataType:0}],dispatchGroup:h,programUniforms:m}),getShaderSource:c=>{let _=oe("probs",e.dataType,e.dims),v=oe("v",r.dataType,r.dims),$=$e("output",e.dataType,i),C=[{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 = ${d}u; var tileQ: array<${_.type.value}, ${d*d}>; var tileK: array<${_.type.value}, ${d*d}>; ${c.registerUniforms(C).declareVariables(_,v,$)} ${c.mainStart([d,d,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; let offsetB = headIdx * (uniforms.N * uniforms.K) + n; var value = ${_.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N]; } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`}}},_a=(t,e,r,n,a,o,i,d,h,m,c)=>{let _=t.outputCount>1,v=t.outputCount>2,$=_&&v?m.pastSequenceLength:0,C=$+m.kvSequenceLength,k=[m.batchSize,m.numHeads,C,m.headSize],M=i?[i,r]:[r],z=_?t.compute(ya(M,2,k,r.dataType),{inputs:M,outputs:[1]})[0]:r,I=[m.batchSize,m.numHeads,C,m.headSize],j=d?[d,n]:[n],R=v?t.compute(ya(j,2,I,n.dataType),{inputs:j,outputs:[2]})[0]:n,L=[e,z];h&&L.push(h);let Y=t.compute(Cd(t,e,z,h,m,c,$),{inputs:L,outputs:[-1]})[0];t.compute(xd(t,Y,m.batchSize*m.numHeads*m.sequenceLength,C),{inputs:[Y],outputs:[]});let Q=[Y,R];t.compute(Sd(t,Y,R,m,$),{inputs:Q,outputs:[0]})},Ed=(t,e)=>{let r=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],n=e.sequenceLength,a=e.inputHiddenSize,o=e.headSize,i=12,d={x:Math.ceil(e.headSize/i),y:Math.ceil(e.sequenceLength/i),z:e.batchSize*e.numHeads},h=[t.inputs[0],t.inputs[1],t.inputs[2]],m=[{type:12,data:n},{type:12,data:a},{type:12,data:o},{type:12,data:e.numHeads},{type:12,data:e.headSize},{type:12,data:e.hiddenSize},{type:12,data:e.hiddenSize+e.hiddenSize+e.vHiddenSize}],c=_=>{let v=$e("output_q",h[0].dataType,r),$=$e("output_k",h[0].dataType,r),C=$e("output_v",h[0].dataType,r),k=oe("input",h[0].dataType,h[0].dims),M=oe("weight",h[1].dataType,h[1].dims),z=oe("bias",h[2].dataType,h[2].dims),I=k.type.storage,j=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${i}u; var tileInput: array<${I}, ${i*i}>; var tileWeightQ: array<${I}, ${i*i}>; var tileWeightK: array<${I}, ${i*i}>; var tileWeightV: array<${I}, ${i*i}>; ${_.registerUniforms(j).declareVariables(k,M,z,v,$,C)} ${_.mainStart([i,i,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${I}(0); var valueK = ${I}(0); var valueV = ${I}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:t.inputs[0].dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:m}),getShaderSource:c},{inputs:h,outputs:[-1,-1,-1]})},kd=(t,e)=>{let r=$d(t.inputs,e),[n,a,o]=Ed(t,r);return _a(t,n,a,o,t.inputs[4],void 0,void 0,void 0,t.inputs[5],r,e)}}),Id,Ad,Md,Od,ow=le(()=>{Yt(),Oe(),Be(),ft(),Re(),Id=(t,e)=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,a,o)=>{let i=a.length;if(i!==n.length)throw new Error(`${o}: num dimensions != ${i}`);a.forEach((d,h)=>{if(d!==n[h])throw new Error(`${o}: dim[${h}] do not match`)})};if(t[0].dims.length>1){let n=e.format==="NHWC"?e.spatial?t[0].dims.slice(-1):t[0].dims.slice(-1).concat(t[0].dims.slice(1,t[0].dims.length-1)):t[0].dims.slice(1,e.spatial?2:void 0);r(t[1].dims,n,"Invalid input scale"),r(t[2].dims,n,"Invalid input B"),r(t[3].dims,n,"Invalid input mean"),r(t[4].dims,n,"Invalid input var")}else r(t[1].dims,[1],"Invalid input scale"),r(t[2].dims,[1],"Invalid input B"),r(t[3].dims,[1],"Invalid input mean"),r(t[4].dims,[1],"Invalid input var")},Ad=(t,e)=>{let{epsilon:r,spatial:n,format:a}=e,o=t[0].dims,i=n?dt(o[o.length-1]):1,d=a==="NHWC"&&o.length>1?i:1,h=se.size(o)/i,m=n,c=m?o.length:o,_=oe("x",t[0].dataType,t[0].dims,i),v=oe("scale",t[1].dataType,t[1].dims,d),$=oe("bias",t[2].dataType,t[2].dims,d),C=oe("inputMean",t[3].dataType,t[3].dims,d),k=oe("inputVar",t[4].dataType,t[4].dims,d),M=$e("y",t[0].dataType,c,i),z=()=>{let j="";if(n)j=`let cOffset = ${o.length===1?"0u":a==="NHWC"?`outputIndices[${o.length-1}] / ${i}`:"outputIndices[1]"};`;else if(a==="NCHW")j=` ${M.indicesSet("outputIndices","0","0")} let cOffset = ${M.indicesToOffset("outputIndices")};`;else{j=`var cIndices = ${v.type.indices}(0); cIndices[0] = outputIndices[${o.length-1}];`;for(let R=1;R` const epsilon = ${r}; ${j.registerUniform("outputSize","u32").declareVariables(_,v,$,C,k,M)} ${j.mainStart()} ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${M.offsetToIndices(`global_idx * ${i}`)}; ${z()} let scale = ${v.getByOffset("cOffset")}; let bias = ${$.getByOffset("cOffset")}; let inputMean = ${C.getByOffset("cOffset")}; let inputVar = ${k.getByOffset("cOffset")}; let x = ${_.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${M.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${e.epsilon}_${e.format}_${n}_${i}`,inputDependencies:m?["rank","type","type","type","type"]:void 0},getShaderSource:I,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m?[{type:12,data:h},...Ce(o)]:[{type:12,data:h}]})}},Md=t=>Ze(t),Od=(t,e)=>{let{inputs:r,outputCount:n}=t,a=Md({...e,outputCount:n});if(He.webgpu.validateInputContent&&Id(r,a),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(Ad(r,a))}}),zd,Pd,jd,lw=le(()=>{Be(),Re(),zd=t=>{if(t[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(t[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(t[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(t[0].dims[2]!==t[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Pd=t=>{let e=t[0].dims,r=t[0].dims[2],n=se.size(e)/4,a=t[0].dataType,o=oe("input",a,e,4),i=oe("bias",a,[r],4),d=oe("residual",a,e,4),h=$e("output",a,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:m=>` const channels = ${r}u / 4; ${m.declareVariables(o,i,d,h)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${o.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; ${h.setByOffset("global_idx","value")} }`}},jd=t=>{zd(t.inputs),t.compute(Pd(t.inputs))}}),Rd,Ge,Bd,Dd,Nd,Ld,Ud,Fd,Wd,Gd,Vd,Hd,qd,Kd,Yd,Qd,wa,Xd,va,Zd,Jd,ec,tc,rc,nc,ic,ac,sc,oc,lc,uc,dc,cc,pc,hc,ro,fc,no,io,mc,gc,yc,ao=le(()=>{Oe(),Be(),ft(),Re(),Rd=(t,e,r,n,a,o)=>{let i=Math.ceil(e/4),d="";typeof a=="string"?d=`${a}(a)`:d=a("a");let h=oe("inputData",r,[i],4),m=$e("outputData",n,[i],4);return` ${t.registerUniform("vec_size","u32").declareVariables(h,m)} ${o??""} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${m.setByOffset("global_idx",d)} }`},Ge=(t,e,r,n,a,o=t.dataType)=>({name:e,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:i=>Rd(i,se.size(t.dims),t.dataType,o,r,n),getRunData:i=>({outputs:[{dims:t.dims,dataType:o}],dispatchGroup:{x:Math.ceil(se.size(i[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(se.size(t.dims)/4)}]})}),Bd=t=>{t.compute(Ge(t.inputs[0],"Abs","abs"))},Dd=t=>{t.compute(Ge(t.inputs[0],"Acos","acos"))},Nd=t=>{t.compute(Ge(t.inputs[0],"Acosh","acosh"))},Ld=t=>{t.compute(Ge(t.inputs[0],"Asin","asin"))},Ud=t=>{t.compute(Ge(t.inputs[0],"Asinh","asinh"))},Fd=t=>{t.compute(Ge(t.inputs[0],"Atan","atan"))},Wd=t=>{t.compute(Ge(t.inputs[0],"Atanh","atanh"))},Gd=t=>Ze(t),Vd=(t,e)=>{let r;switch(e.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${e.to}`)}t.compute(Ge(t.inputs[0],"Cast",r,void 0,e.cacheKey,e.to))},Hd=t=>{let e=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:Ks,r=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:Ys;return Ze({min:e,max:r})},qd=(t,e)=>{let r=t.inputs.length===1?e:Hd(t.inputs),n=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"Clip",a=>`clamp(${a}, clip_min_, clip_max_)`,` const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); `,r.cacheKey),{inputs:[0]})},Kd=t=>{t.compute(Ge(t.inputs[0],"Ceil","ceil"))},Yd=t=>{t.compute(Ge(t.inputs[0],"Cos","cos"))},Qd=t=>{t.compute(Ge(t.inputs[0],"Cosh","cosh"))},wa=t=>Ze(t),Xd=(t,e)=>{let r=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${r}(${e.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,e.cacheKey))},va=(t="f32")=>` const r0: ${t} = 0.3275911; const r1: ${t} = 0.254829592; const r2: ${t} = -0.284496736; const r3: ${t} = 1.421413741; const r4: ${t} = -1.453152027; const r5: ${t} = 1.061405429; fn erf_vf32(v: vec4<${t}>) -> vec4<${t}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,Zd=t=>{let e=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"Erf",r=>`erf_vf32(${r})`,va(e)))},Jd=t=>{t.compute(Ge(t.inputs[0],"Exp","exp"))},ec=t=>{t.compute(Ge(t.inputs[0],"Floor","floor"))},tc=t=>{let e=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,va(e)))},rc=(t,e)=>{let r=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${e.alpha});`,e.cacheKey))},nc=t=>{t.compute(Ge(t.inputs[0],"Not",e=>`!${e}`))},ic=t=>{t.compute(Ge(t.inputs[0],"Neg",e=>`-${e}`))},ac=t=>{t.compute(Ge(t.inputs[0],"Reciprocal",e=>`1.0/${e}`))},sc=t=>{let e=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"Relu",r=>`select(vec4<${e}>(0.0), ${r}, ${r} > vec4<${e}>(0.0))`))},oc=t=>{t.compute(Ge(t.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},lc=t=>Ze(t),uc=(t,e)=>{let r=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${e.alpha} * ${n} + vec4<${r}>(${e.beta})))`,void 0,e.cacheKey))},dc=t=>{t.compute(Ge(t.inputs[0],"Sin","sin"))},cc=t=>{t.compute(Ge(t.inputs[0],"Sinh","sinh"))},pc=t=>{t.compute(Ge(t.inputs[0],"Sqrt","sqrt"))},hc=t=>{t.compute(Ge(t.inputs[0],"Tan","tan"))},ro=t=>`sign(${t}) * (1 - exp(-2 * abs(${t}))) / (1 + exp(-2 * abs(${t})))`,fc=t=>{t.compute(Ge(t.inputs[0],"Tanh",ro))},no=(t="f32")=>` const fast_gelu_a: ${t} = 0.5; const fast_gelu_b: ${t} = 0.7978845608028654; const fast_gelu_c: ${t} = 0.035677408136300125; fn tanh_v(v: vec4<${t}>) -> vec4<${t}> { return ${ro("v")}; } `,io=t=>`(fast_gelu_a + fast_gelu_a * tanh_v(${t} * (fast_gelu_c * ${t} * ${t} + fast_gelu_b))) * ${t}`,mc=t=>{let e=kt(t.inputs[0].dataType);t.compute(Ge(t.inputs[0],"FastGelu",io,no(e),void 0,t.inputs[0].dataType))},gc=(t,e)=>{let r=kt(t.inputs[0].dataType);return t.compute(Ge(t.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${e.alpha});`,e.cacheKey)),0},yc=t=>{t.compute(Ge(t.inputs[0],"Log","log"))}}),_c,wc,vc,uw=le(()=>{Be(),Re(),ao(),_c=t=>{if(t[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(t[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(t[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(t[0].dims[2]!==t[1].dims[0])throw new Error("last dimension of input and bias are not the same")},wc=t=>{let e=t[0].dims.slice();e[2]=e[2]/2;let r=oe("input",t[0].dataType,t[0].dims,4),n=oe("bias",t[0].dataType,[t[0].dims[2]],4),a=$e("output",t[0].dataType,e,4),o=se.size(e)/4,i=mt(t[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:e,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:d=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${t[0].dims[2]/4/2}u; ${d.declareVariables(r,n,a)} ${va(i)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(o)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${a.setByOffset("global_idx","valueLeft * geluRight")} }`}},vc=t=>{_c(t.inputs),t.compute(wc(t.inputs))}}),bc,$c,er,xc,Cc,Sc,Ec,kc,Tc,Ic,Ac,Mc,Oc,dw=le(()=>{Oe(),Be(),Re(),bc=(t,e,r,n,a,o,i,d,h,m,c,_)=>{let v,$;typeof d=="string"?v=$=(I,j)=>`${d}((${I}),(${j}))`:typeof d=="function"?v=$=d:(v=d.scalar,$=d.vector);let C=$e("outputData",c,n.length,4),k=oe("aData",h,e.length,4),M=oe("bData",m,r.length,4),z;if(a)if(o){let I=se.size(e)===1,j=se.size(r)===1,R=e.length>0&&e[e.length-1]%4===0,L=r.length>0&&r[r.length-1]%4===0;I||j?z=C.setByOffset("global_idx",$(I?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"),j?`${M.type.value}(${M.getByOffset("0")}.x)`:M.getByOffset("global_idx"))):z=` let outputIndices = ${C.offsetToIndices("global_idx * 4u")}; let offsetA = ${k.broadcastedIndicesToOffset("outputIndices",C)}; let offsetB = ${M.broadcastedIndicesToOffset("outputIndices",C)}; ${C.setByOffset("global_idx",$(i||R?k.getByOffset("offsetA / 4u"):`${k.type.value}(${k.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||L?M.getByOffset("offsetB / 4u"):`${M.type.value}(${M.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else z=C.setByOffset("global_idx",$(k.getByOffset("global_idx"),M.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let I=(j,R,L="")=>{let Y=`aData[indexA${R}][componentA${R}]`,Q=`bData[indexB${R}][componentB${R}]`;return` let outputIndices${R} = ${C.offsetToIndices(`global_idx * 4u + ${R}u`)}; let offsetA${R} = ${k.broadcastedIndicesToOffset(`outputIndices${R}`,C)}; let offsetB${R} = ${M.broadcastedIndicesToOffset(`outputIndices${R}`,C)}; let indexA${R} = offsetA${R} / 4u; let indexB${R} = offsetB${R} / 4u; let componentA${R} = offsetA${R} % 4u; let componentB${R} = offsetB${R} % 4u; ${j}[${R}] = ${L}(${v(Y,Q)}); `};c===9?z=` var data = vec4(0); ${I("data",0,"u32")} ${I("data",1,"u32")} ${I("data",2,"u32")} ${I("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:z=` ${I("outputData[global_idx]",0)} ${I("outputData[global_idx]",1)} ${I("outputData[global_idx]",2)} ${I("outputData[global_idx]",3)} `}return` ${t.registerUniform("vec_size","u32").declareVariables(k,M,C)} ${_??""} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${z} }`},$c=(t,e,r,n,a,o,i=r.dataType)=>{let d=!se.areEqual(r.dims,n.dims),h=r.dims,m=se.size(r.dims),c=!1,_=!1,v=[d];if(d){let $=hn.calcShape(r.dims,n.dims,!1);if(!$)throw new Error("Can't perform binary op on the given tensors");h=$,m=se.size(h);let C=se.size(r.dims)===1,k=se.size(n.dims)===1,M=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,z=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;v.push(C),v.push(k),v.push(M),v.push(z);let I=1;for(let j=1;j$.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:$=>bc($,r.dims,n.dims,h,c,d,_,a,r.dataType,n.dataType,i,o),getRunData:()=>({outputs:[{dims:h,dataType:i}],dispatchGroup:{x:Math.ceil(m/64/4)},programUniforms:[{type:12,data:Math.ceil(se.size(h)/4)},...Ce(r.dims,n.dims,h)]})}},er=(t,e,r,n,a,o)=>{t.compute($c(e,a??"",t.inputs[0],t.inputs[1],r,n,o))},xc=t=>{er(t,"Add",(e,r)=>`${e}+${r}`)},Cc=t=>{er(t,"Div",(e,r)=>`${e}/${r}`)},Sc=t=>{er(t,"Equal",{scalar:(e,r)=>`u32(${e}==${r})`,vector:(e,r)=>`vec4(${e}==${r})`},void 0,void 0,9)},Ec=t=>{er(t,"Mul",(e,r)=>`${e}*${r}`)},kc=t=>{let e=oe("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;er(t,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` fn pow_custom(a : ${e}, b : ${e}) -> ${e} { if (b == ${e}(0.0)) { return ${e}(1.0); } else if (a < ${e}(0.0) && f32(b) != floor(f32(b))) { return ${e}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${e}(1.0), round(f32(abs(b) % ${e}(2.0))) != 1.0) * ${e}(${e==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${e}>, b : vec4<${e}>) -> vec4<${e}> { // TODO: implement vectorized pow return vec4<${e}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},Tc=t=>{er(t,"Sub",(e,r)=>`${e}-${r}`)},Ic=t=>{er(t,"Greater",{scalar:(e,r)=>`u32(${e}>${r})`,vector:(e,r)=>`vec4(${e}>${r})`},void 0,void 0,9)},Ac=t=>{er(t,"Less",{scalar:(e,r)=>`u32(${e}<${r})`,vector:(e,r)=>`vec4(${e}<${r})`},void 0,void 0,9)},Mc=t=>{er(t,"GreaterOrEqual",{scalar:(e,r)=>`u32(${e}>=${r})`,vector:(e,r)=>`vec4(${e}>=${r})`},void 0,void 0,9)},Oc=t=>{er(t,"LessOrEqual",{scalar:(e,r)=>`u32(${e}<=${r})`,vector:(e,r)=>`vec4(${e}<=${r})`},void 0,void 0,9)}}),Fr,Wr,Gr,so,Vr=le(()=>{Oe(),Be(),Fr=(t,e,r="f32")=>{switch(t.activation){case"Relu":return`value = max(value, ${e}(0.0));`;case"Sigmoid":return`value = (${e}(1.0) / (${e}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${e}(${r}(uniforms.clip_min)), ${e}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${e}(0.0), min(${e}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${e}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${t.activation}`)}},Wr=(t,e)=>{t.activation==="Clip"?e.push({type:1,data:t.clipMax},{type:1,data:t.clipMin}):t.activation==="HardSigmoid"?e.push({type:1,data:t.alpha},{type:1,data:t.beta}):t.activation==="LeakyRelu"&&e.push({type:1,data:t.alpha})},Gr=(t,e)=>{t.activation==="Clip"?e.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):t.activation==="HardSigmoid"?e.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):t.activation==="LeakyRelu"&&e.push({name:"alpha",type:"f32"})},so=t=>{let e=(t==null?void 0:t.activation)||"";if(e==="HardSigmoid"){let[r,n]=(t==null?void 0:t.activation_params)||[.2,.5];return{activation:e,alpha:r,beta:n}}else if(e==="Clip"){let[r,n]=(t==null?void 0:t.activation_params)||[Ks,Ys];return{activation:e,clipMax:n,clipMin:r}}else if(e==="LeakyRelu"){let[r]=(t==null?void 0:t.activation_params)||[.01];return{activation:e,alpha:r}}return{activation:e}}}),$t,oo,lo=le(()=>{$t=(t,e)=>{switch(t){case 1:return e;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${t}-component is not supported.`)}},oo=t=>` ${t?"value = value + getBiasByOutputCoords(coords);":""} `}),uo,zc=le(()=>{uo=t=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${t}.x), i32(${t}.y), i32(${t}.z), 1)); } `}),Pc,jc,ba,co,Rc,$a,Bc,po,xa=le(()=>{Oe(),Be(),Re(),Vr(),lo(),Pc=(t,e)=>t?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${e?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${e?", batchIndices":""}); `,jc=(t,e)=>t?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${e===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${e===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${e===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,ba=(t,e,r="f32",n,a=!1,o=32,i=!1,d=32)=>{let h=e[1]*t[1],m=e[0]*t[0],c=a?h:o,_=a?o:h,v=c/e[0],$=o/e[1];if(!((a&&v===4&&t[1]===4||!a&&(v===3||v===4))&&c%e[0]===0&&o%e[1]===0&&t[0]===4))throw new Error(`If transposeA ${a} is true, innerElementSize ${v} and workPerThread[1] ${t[1]} must be 4. Otherwise, innerElementSize ${v} must be 3 or 4. tileAWidth ${c} must be divisible by workgroupSize[0]${e[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${t[0]} must be 4.`);return` var mm_Asub: array, ${c/v}>, ${_}>; var mm_Bsub: array, ${m/t[0]}>, ${o}>; const rowPerThread = ${t[1]}; const colPerThread = ${t[0]}; const innerElementSize = ${v}; const tileInner = ${o}; @compute @workgroup_size(${e[0]}, ${e[1]}, ${e[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${h}; let num_tiles = ${i?`${Math.ceil(d/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${$}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${Pc(a,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${$}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${v===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${jc(a,v)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},co=(t,e)=>t?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${e?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${e?", batchIndices":""}); `,Rc=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",$a=(t,e,r="f32",n,a=!1,o=32,i=!1,d=32,h=!1)=>{let m=t[1]*e[1],c=t[0]*e[0],_=a?m:o,v=a?o:m;if(!(v%e[1]===0&&_%e[0]===0&&o%e[1]===0))throw new Error(`tileAHight ${v} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${_} must be divisible by workgroupSize[0]${e[0]}, tileInner ${o} must be divisible by workgroupSize[1]${e[1]}`);let $=v/e[1],C=_/e[0],k=o/e[1],M=h?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${m}; let globalColStart = i32(workgroupId.x) * ${c}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${v}; inputRow = inputRow + ${e[1]}) { for (var inputCol = localCol; inputCol < ${_}; inputCol = inputCol + ${e[0]}) { ${co(a,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${e[1]}) { for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${e[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${a?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${e[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${e[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${m}; let tileRowA = i32(localId.y) * ${$}; let tileColA = i32(localId.x) * ${C}; let tileRowB = i32(localId.y) * ${k}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${$}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${C}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${co(a,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${k}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Rc(a)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${v}>; var mm_Bsub : array, ${o}>; const rowPerThread = ${t[1]}; const colPerThread = ${t[0]}; const tileInner = ${o}; @compute @workgroup_size(${e[0]}, ${e[1]}, ${e[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${i?`${Math.ceil(d/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${d}`:"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; } } ${M} } `},Bc=(t,e,r,n,a,o=!1)=>{let[i,d,h]=a,[m,c,_,v]=n,$=Vn(i,h),C=Vn(d,h),k=mt(n[0].type.tensor),M=()=>{let I=c.rank,j=m.rank,R=`var aIndices: ${c.type.indices};`;for(let L=I-2-1,Y=j-1;L>=0;L--,Y--)R+=` aIndices[${L}] = ${j>1?`batchIndices[${Y}]`:"batchIndices"};`;return $.forEach(L=>{R+=` aIndices[${L}] = 0;`}),R+=` aIndices[${I-2}] = u32(row); aIndices[${I-1}] = u32(colIn);`,R},z=()=>{let I=_.rank,j=m.rank,R=`var bIndices: ${_.type.indices};`;for(let L=I-2-1,Y=j-1;L>=0;L--,Y--)R+=` bIndices[${L}] = ${j>1?`batchIndices[${Y}]`:"batchIndices"};`;return C.forEach(L=>{R+=` bIndices[${L}] = 0;`}),R+=` bIndices[${I-2}] = u32(row); bIndices[${I-1}] = u32(colIn);`,R};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${m.type.indices}) -> ${$t(t,k)} { var value = ${$t(t,k)}(0.0); let col = colIn * ${t}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${M()} value = ${c.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${m.type.indices}) -> ${$t(t,k)} { var value = ${$t(t,k)}(0.0); let col = colIn * ${t}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${z()} value = ${_.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${$t(t,k)}) { let col = colIn * ${t}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${e?`value = value + ${o?"bias[colIn]":`${$t(t,k)}(bias[row])`};`:""} ${r} ${v.setByIndices("vec3(coords)","value")} } } `},po=(t,e,r,n,a=!1)=>{let o=t[0].dims,i=t[1].dims,d=o.slice(0,-2),h=i.slice(0,-2),m=n?n.slice(0,-2):r.slice(0,-2),c=se.size(m),_=o[o.length-2],v=o[o.length-1],$=i[i.length-1],C=v%4===0&&$%4===0,k=_<=8?[4,1,1]:[4,4,1],M=[8,8,1],z=[Math.ceil($/M[0]/k[0]),Math.ceil(_/M[1]/k[1]),Math.ceil(c/M[2]/k[2])],I=C?4:1,j=[...d,_,v/I],R=j.length,L=[...h,v,$/I],Y=L.length,Q=[c,_,$/I],ie=[{type:6,data:_},{type:6,data:$},{type:6,data:v}];Wr(e,ie),ie.push(...Ce(m,j,L));let pe=["rank","rank"],ce=t.length>2;ce&&(ie.push(...Ce(t[2].dims)),pe.push("rank")),ie.push(...Ce(Q));let Se=fe=>{let me=m.length,ge=Qs("batchDims",t[0].dataType,me,1),X=mt(t[0].dataType),U=oe("a",t[0].dataType,R,I),ne=oe("b",t[1].dataType,Y,I),ee=$e("result",t[0].dataType,Q.length,I),Ee=[U,ne];if(ce){let Le=a?I:1;Ee.push(oe("bias",t[2].dataType,t[2].dims.length,Le))}let Te=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Gr(e,Te);let K=mt(ee.type.tensor),he=Fr(e,ee.type.value,K),ve=Bc(I,ce,he,[ge,U,ne,ee],[d,h,m],a);return` ${fe.registerUniforms(Te).registerInternalVariables(ge).declareVariables(...Ee,ee)} ${ve} ${C?ba(k,M,X,ge):$a(k,M,X,ge)} `};return{name:"MatMul",shaderCache:{hint:`${k};${e.activation};${C};${a}`,inputDependencies:pe},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:z[0],y:z[1],z:z[2]},programUniforms:ie}),getShaderSource:Se}}}),Dc,Nc,cw=le(()=>{Oe(),Ur(),Re(),Vr(),lo(),zc(),xa(),Dc=(t,e,r,n,a=!1,o,i=4,d=4,h=4,m="f32")=>{let c=pe=>{switch(pe){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${m}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${pe} is not supported.`)}},_=pe=>{switch(pe){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 ${pe} is not supported.`)}},v=t?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,$=t?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,C=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",k=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",M=t?"row":"col",z=t?"col":"row",I=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${M} / outWidth; let outCol = ${M} % outWidth; let WRow = ${z} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${z} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${z} % inChannels; var resData = ${$t(i,m)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${C} && xCol >= 0 && xCol < ${k}) { ${v} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${c(i)} } return resData;`,j=t?e&&n?` let col = colIn * ${i}; ${I}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${I} } return ${$t(i,m)}(0.0);`:n&&r?` let col = colIn * ${i}; ${I}`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${I} } return ${$t(i,m)}(0.0);`,R=`${_(d)}`,L=$t(h,m),Y=$t(t?i:d,m),Q=$t(t?d:i,m),ie=Fr(o,L,m);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Y} { ${t?j:R} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Q} { ${t?R:j} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${L}) { let col = colIn * ${h}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${$} ${oo(a)} ${ie} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Nc=(t,e,r,n,a,o,i,d)=>{let h=e.format==="NHWC",m=h?t[0].dims[3]:t[0].dims[1],c=r[0],_=h?r[2]:r[3],v=h?r[1]:r[2],$=h?r[3]:r[1],C=h&&(m%4===0||m%3===0)&&$%4===0,k=h?$:_*v,M=h?_*v:$,z=[8,8,1],I=n<=8?[4,1,1]:[4,4,1],j=[Math.ceil(k/z[0]/I[0]),Math.ceil(M/z[1]/I[1]),Math.ceil(c/z[2]/I[2])];it("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${j}`);let R=C?h&&m%4!==0?3:4:1,L=z[1]*I[1],Y=z[0]*I[0],Q=Math.max(z[0]*R,z[1]),ie=n%L===0,pe=a%Y===0,ce=o%Q===0,Se=C?[R,4,4]:[1,1,1],fe=[{type:6,data:n},{type:6,data:a},{type:6,data:o},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];Wr(e,fe),fe.push(...Ce(t[0].dims,t[1].dims));let me=["rank","rank"];i&&(fe.push(...Ce(t[2].dims)),me.push("rank")),fe.push(...Ce(r));let ge=X=>{let U=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Gr(e,U);let ne=C?4:1,ee=mt(t[0].dataType),Ee=` fn setOutputAtIndex(flatIndex : i32, value : ${C?`vec4<${ee}>`:ee}) { result[flatIndex] = ${C?`vec4<${ee}>`:ee}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${C?`vec4<${ee}>`:ee}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${C?"/ 4":""}, value); }`,Te=oe("x",t[0].dataType,t[0].dims.length,R===3?1:R),K=oe("w",t[1].dataType,t[1].dims.length,ne),he=[Te,K],ve=$e("result",t[0].dataType,r.length,ne);if(i){let Le=oe("bias",t[2].dataType,t[2].dims.length,ne);he.push(Le),Ee+=` fn getBiasByOutputCoords(coords : vec4) -> ${C?`vec4<${ee}>`:ee} { return bias[coords.${h?"w":"y"}${C?"/ 4":""}]; }`}return` ${uo("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 }; ${X.registerUniforms(U).declareVariables(...he,ve)} ${Ee} ${Dc(h,ie,pe,ce,i,e,Se[0],Se[1],Se[2],ee)} ${C?ba(I,z,ee,void 0,!h,Q):$a(I,z,ee,void 0,!h,Q,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${R};${C};${ie};${pe};${ce};${L};${Y};${Q}`,inputDependencies:me},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:j[0],y:j[1],z:j[2]},programUniforms:fe}),getShaderSource:ge}}}),ho,Lc,pw=le(()=>{Oe(),Be(),Re(),qc(),Vr(),ho=(t,e,r)=>{let n=t.length>2,a=n?"value += b[output_channel];":"",o=t[0].dims,i=t[1].dims,d=i[0]/e.group,h=e.format==="NHWC",m=Ca(o,i,e.dilations,e.pads,e.strides,h),c=se.size(m),_=[{type:12,data:c},{type:12,data:e.dilations},{type:12,data:[e.strides[0],e.strides[1]]},{type:12,data:[e.pads[0],e.pads[1]]},{type:12,data:d}];Wr(e,_),_.push(...Ce(o,i));let v=["rank","rank"];n&&(_.push(...Ce(t[2].dims)),v.push("rank")),_.push(...Ce(m));let $=C=>{let k=$e("output",t[0].dataType,m.length),M=mt(k.type.tensor),z=Fr(e,k.type.value,M),I=oe("x",t[0].dataType,o.length),j=oe("w",t[1].dataType,i.length),R=[I,j];n&&R.push(oe("b",t[2].dataType,t[2].dims.length));let L=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:e.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Gr(e,L),` ${C.registerUniforms(L).declareVariables(...R,k)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${k.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${h?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${h?1:2}], outputIndices[${h?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${k.type.value} = ${k.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = group_id * uniforms.w_shape[1] + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[${h?1:2}]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[${h?2:3}]) { continue; } let xVal = ${h?I.get("batch","xHeight","xWidth","input_channel"):I.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${j.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${a} ${z} ${k.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:e.cacheKey,inputDependencies:v},getRunData:()=>({outputs:[{dims:r?r(m):m,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:_}),getShaderSource:$}},Lc=(t,e,r)=>{let n=t.length>2,a=dt(r[3]),o=dt(r[2]),i=se.size(r)/a/o,d=[t[0].dims[0],t[0].dims[1],t[0].dims[2],t[0].dims[3]/a],h=[t[1].dims[0],t[1].dims[1],t[1].dims[2],t[1].dims[3]/a],m=[r[0],r[1],r[2],r[3]/a],c=[{type:12,data:i},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];Wr(e,c),c.push(...Ce(d,h,m));let _=(o-1)*e.strides[1]+h[1],v=$=>{let C=$e("output",t[0].dataType,m.length,a),k=mt(C.type.tensor),M=Fr(e,C.type.value,k),z=oe("x",t[0].dataType,d.length,a),I=oe("w",t[1].dataType,h.length,a),j=[z,I];n&&j.push(oe("b",t[2].dataType,t[2].dims,a));let R=n?"value += b[output_channel];":"",L=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Gr(e,L),` ${$.registerUniforms(L).declareVariables(...j,C)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${o}u; let col = (index1 % width1) * ${o}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${z.type.value}, ${_}>; var values: array<${C.type.value}, ${o}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${_}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${z.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${z.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${I.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${o}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${o}u; i++) { var value = values[i]; ${R} ${M} ${C.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${a};${o};${_};${h[0]};${h[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c}),getShaderSource:v}}}),fo,Uc,Fc,Wc=le(()=>{Oe(),Be(),xa(),Re(),Vr(),fo=(t,e,r,n,a=!1)=>{let o=t[0].dims,i=t[1].dims,d=o[o.length-2],h=i[i.length-1],m=o[o.length-1],c=dt(h),_=dt(m),v=dt(d),$=se.size(r)/c/v,C=t.length>2,k=n?n.slice(0,-2):r.slice(0,-2),M=[se.size(k),d,h],z=[{type:12,data:$},{type:12,data:d},{type:12,data:h},{type:12,data:m}];Wr(e,z),z.push(...Ce(k,o,i)),C&&z.push(...Ce(t[2].dims)),z.push(...Ce(M));let I=j=>{let R=Qs("batch_dims",t[0].dataType,k.length),L=oe("a",t[0].dataType,o.length,_),Y=oe("b",t[1].dataType,i.length,c),Q=$e("output",t[0].dataType,M.length,c),ie=mt(Q.type.tensor),pe=Fr(e,Q.type.value,ie),ce=[L,Y],Se="";if(C){let Ee=a?c:1;ce.push(oe("bias",t[2].dataType,t[2].dims.length,Ee)),Se=`${a?`value += bias[col / ${Ee}];`:`value += ${Q.type.value}(bias[row + i]);`}`}let fe=o.slice(0,-2),me=i.slice(0,-2),ge=Vn(fe,k),X=Vn(me,k),U=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Gr(e,U);let ne=(Ee,Te)=>{let K=Ee.rank,he=Ee.name;if(K===2)return`var ${he}_indices = ${Ee.type.indices}(0u, 0u);`;let ve=R.rank,Le=`var ${he}_indices: ${Ee.type.indices};`;for(let Ke=K-2-1,ct=ve-1;Ke>=0;Ke--,ct--)Le+=` ${he}_indices[${Ke}] = ${ve>1?`batch_indices[${ct}]`:"batch_indices"};`;return Te.forEach(Ke=>{Le+=` ${he}_indices[${Ke}] = 0;`}),Le+=`${he}_indices[${K-2}] = 0u; ${he}_indices[${K-1}] = 0u;`,Le},ee=()=>{let Ee=`var a_data: ${L.type.value};`;for(let Te=0;Te<_;Te++)Ee+=` let b_data${Te} = b[(b_offset + (k + ${Te}) * uniforms.N + col) / ${c}];`;for(let Te=0;Te; for (var k: u32 = 0u; k < uniforms.K; k = k + ${_}) { ${ee()} } for (var i = 0u; i < ${v}u; i++) { var value = values[i]; ${Se} ${pe} let cur_indices = ${Q.type.indices}(batch, row + i, col); let offset = ${Q.indicesToOffset("cur_indices")}; ${Q.setByOffset(`offset / ${c}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${c};${_};${v};${a}`,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:z}),getShaderSource:I}},Uc=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.")},Fc=t=>{Uc(t.inputs);let e=hn.calcShape(t.inputs[0].dims,t.inputs[1].dims,!0);if(!e)throw new Error("Can't use matmul on the given tensors");let r=e[e.length-1],n=t.inputs[0].dims[t.inputs[0].dims.length-1];r<8&&n<8?t.compute(fo(t.inputs,{activation:""},e)):t.compute(po(t.inputs,{activation:""},e))}}),Ca,Sa,Gc,mo,go,Vc,Hc,yo,qc=le(()=>{Be(),cw(),xa(),pw(),Vr(),Wc(),Hn(),Ca=(t,e,r,n,a,o)=>{let i=t[0],d=t.slice(o?1:2,o?3:4),h=d.length,m=e[0],c=e.slice(2).map((v,$)=>v+(v-1)*(r[$]-1)),_=d.map((v,$)=>v+n[$]+n[$+h]).map((v,$)=>Math.floor((v-c[$]+a[$])/a[$]));return _.splice(0,0,i),_.splice(o?3:1,0,m),_},Sa=[2,3,1,0],Gc=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4&&t[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let r=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],n=t[1].dims[1]*e.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(t.length===3&&(t[2].dims.length!==1||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");let a=t[0].dims.length-2;if(e.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(e.strides.length!==a)throw new Error(`strides should be ${a}D`);if(e.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape")},mo=(t,e)=>{let r=t.kernelShape.slice();for(let o=2;o{let e=so(t),r=t.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],a=t.dilations,o=t.group,i=t.kernel_shape,d=t.pads,h=t.strides,m=t.w_is_const();return{autoPad:n,format:r,dilations:a,group:o,kernelShape:i,pads:d,strides:h,wIsConst:m,...e,cacheKey:`${t.format};${e.activation};`}},Vc=(t,e,r)=>{let n=mo(r,e),a=r.format==="NHWC";if(r.group!==1){if(!t.adapterInfo.isArchitecture("ampere")&&a&&e[1].dims[0]===r.group&&e[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let Y=Ca(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),Q=t.kernelCustomData.wT??t.compute(yr(e[1],Sa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=Q);let ie=[e[0],Q];e.length===3&&ie.push(e[2]),t.compute(Lc(ie,n,Y),{inputs:ie})}else t.compute(ho(e,n));return}let o=e.length===3,i=e[0].dims[a?1:2],d=e[0].dims[a?2:3],h=e[0].dims[a?3:1],m=e[1].dims[2],c=e[1].dims[3],_=Ca(e[0].dims,e[1].dims,r.dilations,n.pads,r.strides,a),v=_[a?1:2],$=_[a?2:3],C=_[a?3:1],k=a&&m===i&&c===d&&r.pads[0]===0&&r.pads[1]===0;if(k||m===1&&c===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 Y=_[0],Q,ie,pe,ce=[];if(a){let me=t.kernelCustomData.wT??t.compute(yr(e[1],Sa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=me),k){let ge=i*d*h;Q=e[0].reshape([1,Y,ge]),ie=me.reshape([1,ge,C]),pe=[1,Y,C]}else Q=e[0].reshape([Y,i*d,h]),ie=me.reshape([1,h,C]),pe=[Y,v*$,C];ce.push(Q),ce.push(ie)}else Q=e[0].reshape([Y,h,i*d]),ie=e[1].reshape([1,C,h]),pe=[Y,C,v*$],ce.push(ie),ce.push(Q);o&&ce.push(e[2]);let Se=pe[2],fe=ce[0].dims[ce[0].dims.length-1];Se<8&&fe<8?t.compute(fo(ce,n,_,pe,a),{inputs:ce}):t.compute(po(ce,n,_,pe,a),{inputs:ce});return}let M=!0,z=t.kernelCustomData.wT??t.compute(yr(e[1],Sa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=z);let I=[e[0],z];o&&I.push(e[2]);let j=a?v*$:C,R=a?C:v*$,L=m*c*h;t.compute(Nc(I,n,_,j,R,L,o,M),{inputs:I})},Hc=(t,e)=>{let r=e.format==="NHWC",n=[t.inputs[0].reshape(r?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];t.inputs.length===3&&n.push(t.inputs[2]);let a=[0,e.pads[0],0,e.pads[1]],o=[1].concat(e.strides),i=[1].concat(e.dilations),d=[1].concat(e.kernelShape),h=mo({...e,pads:a,strides:o,dilations:i,kernelShape:d},n);t.compute(ho(n,h,m=>r?[m[0],m[2],m[3]]:[]))},yo=(t,e)=>{Gc(t.inputs,e),t.inputs[0].dims.length===3?Hc(t,e):Vc(t,t.inputs,e)}}),Kc,Yc,hw=le(()=>{Oe(),Ur(),Re(),Vr(),lo(),zc(),xa(),Kc=(t,e=!1,r,n,a=4)=>{let o=M=>{switch(M){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${n}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${M} is not supported.`)}},i=t?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,d=t?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,h=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",m=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",c=t?"row":"col",_=t?"col":"row",v=` let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${c} / outWidth; let outCol = ${c} % outWidth; let WRow = ${_} / (uniforms.filter_dims[1] * inChannels); let WCol = ${_} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${h}) || fract(xR) > 0.0) { return ${n}(0.0); } if (xC < 0.0 || xC >= f32(${m}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${_} % inChannels; ${i} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${a}];`,$=t?` let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${v} } return ${n}(0.0);`:` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${v} } return ${n}(0.0);`,C=` let col = colIn * ${a}; let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${t?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${o(a)} } return ${n}(0.0); `,k=Fr(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${t?$:C} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${t?C:$} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${d} ${oo(e)} ${k} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${a}] = value; } }`},Yc=(t,e,r,n,a,o,i,d)=>{let h=e.format==="NHWC",m=h?t[0].dims[3]:t[0].dims[1],c=r[0],_=h?r[2]:r[3],v=h?r[1]:r[2],$=h?r[3]:r[1],C=h&&m%4===0&&m%3&&$%4===0,k=h?$:_*v,M=h?_*v:$,z=[8,8,1],I=n<=8?[4,1,1]:[4,4,1],j=[Math.ceil(k/z[0]/I[0]),Math.ceil(M/z[1]/I[1]),Math.ceil(c/z[2]/I[2])];it("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${j}`);let R=C?4:1,L=Math.max(z[0]*R,z[1]),Y=C?4:1,Q=[e.kernelShape[h?1:2],e.kernelShape[h?2:3]],ie=[Q[0]+(e.dilations[0]<=1?0:(Q[0]-1)*(e.dilations[0]-1)),Q[1]+(e.dilations[1]<=1?0:(Q[1]-1)*(e.dilations[1]-1))],pe=[ie[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),ie[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],ce=[{type:6,data:n},{type:6,data:a},{type:6,data:o},{type:6,data:e.strides},{type:6,data:e.dilations},{type:6,data:Q},{type:6,data:pe}];Wr(e,ce),ce.push(...Ce(t[0].dims,t[1].dims));let Se=["rank","rank"];i&&(ce.push(...Ce(t[2].dims)),Se.push("rank")),ce.push(...Ce(r));let fe=me=>{let ge=oe("x",t[0].dataType,t[0].dims.length,Y),X=oe("w",t[1].dataType,t[1].dims.length,1),U=$e("result",t[0].dataType,r.length,Y),ne=[ge,X],ee="";if(i){let K=oe("bias",t[2].dataType,t[2].dims.length,Y);ne.push(K),ee+=` fn getBiasByOutputCoords(coords : vec4) -> ${K.type.value} { return bias[coords.${h?"w":"y"}${C?"/ 4":""}]; }`}let Ee=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:Q.length},{name:"pads",type:"i32",length:pe.length}];Gr(e,Ee);let Te=mt(t[0].dataType,1);if(Te!=="f16"&&Te!=="f32")throw new Error(`elemType ${Te} is not supported.`);return` ${uo("uniforms.result_strides")} ${me.registerUniforms(Ee).declareVariables(...ne,U)}; ${ee} ${Kc(h,i,e,ge.type.value,R)} ${C?ba(I,z,Te,void 0,!h,L):$a(I,z,Te,void 0,!h,L,!1,void 0,d)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${e.cacheKey};${I};${z};${C}`,inputDependencies:Se},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:j[0],y:j[1],z:j[2]},programUniforms:ce}),getShaderSource:fe}}}),Qc,_o,fw=le(()=>{Oe(),Ur(),Be(),Re(),Qc=(t,e,r,n,a,o=!1,i,d,h=!1)=>{let m=h?1:2,c=h?2:3,_=h?3:1,v=o?2:1,$=` fn setOutputAtIndex(flatIndex : u32, value : ${o?`vec4<${i}>`:i}) { result[flatIndex] = ${o?`vec4<${i}>`:i}(value); }`;n&&($+=` fn getBiasByOutputCoords(coords : vec4) -> ${o?`vec4<${i}>`:i} { return bias[coords.${h?"w":"y"}${o?"/ 4":""}]; }`);let C=o?4:1,k=oe("W",e[1].dataType,e[1].dims.length,C),M=oe("Dy",e[0].dataType,e[0].dims.length,C),z=[M,k];n&&z.push(oe("bias",e[2].dataType,[r[_]].length,C));let I=$e("result",e[0].dataType,r.length,C),j=`{ let batch: u32 = ${a?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${a?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${a?"global_id.y":"workgroup_id.y"} * ${v}; let d1: u32 = ${a?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${v}>; for (var i = 0; i < ${v}; i++) { dotProd[i] = vec4<${i}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${i}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${M.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${M.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${_}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${M.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${k.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${M.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${i}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${v}; i = i + 1) { let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; ${I.set("batch","r","c + i","d1","value")}; } }`,R=` let outputIndices = ${I.offsetToIndices("global_idx")}; let batch = ${I.indicesGet("outputIndices",0)}; let d1 = ${I.indicesGet("outputIndices",_)}; let r = ${I.indicesGet("outputIndices",m)}; let c = ${I.indicesGet("outputIndices",c)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${i}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[${m}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${c}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${h?M.get("batch","idyR","idyC","inputChannel"):M.get("batch","inputChannel","idyR","idyC")}; let wValue = ${k.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; ${I.setByOffset("global_idx","value")}; `;return` ${t.registerUniforms(d).declareVariables(...z,I)} ${$} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${o?j:R}}`},_o=(t,e,r)=>{let n=t.length>2,a=e.outputShape,o=se.size(a),i=[Math.ceil(o/64),1,1];it("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let d=e.format==="NHWC",h=["rank","rank"],m=[e.strides[0],e.strides[1]],c=[e.kernelShape[d?1:2],e.kernelShape[d?2:3]],_=[e.dilations[0],e.dilations[1]],v=[c[0]+(e.dilations[0]<=1?0:(e.kernelShape[d?1:2]-1)*(e.dilations[0]-1)),c[1]+(e.dilations[1]<=1?0:(e.kernelShape[d?2:3]-1)*(e.dilations[1]-1))],$=[v[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),v[1]-1-Math.floor(e.pads[1]+e.pads[3])/2],C=!1,k=e.group,M=t[1].dims,z=M[0]/k,I=M[1],j=[{type:12,data:o},{type:12,data:m},{type:12,data:c},{type:12,data:_},{type:12,data:v},{type:6,data:$},{type:12,data:z},{type:12,data:I},...Ce(t[0].dims,t[1].dims)];n&&(j.push(...Ce(t[2].dims)),h.push("rank")),j.push(...Ce(a));let R=i[1]===1&&i[2]===1,L=Y=>{let Q=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:m.length},{name:"filter_dims",type:"u32",length:c.length},{name:"dilations",type:"u32",length:c.length},{name:"effective_filter_dims",type:"u32",length:v.length},{name:"pads",type:"i32",length:$.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],ie=mt(t[0].dataType);return`${Qc(Y,t,a,n,R,C,ie,Q,d)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};`,inputDependencies:h},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(a):a,dataType:t[0].dataType}],programUniforms:j}),getShaderSource:L}}}),Xc,Zc,Jc,wo,ep,tp,rp,np,ip,ap,mw=le(()=>{hw(),fw(),Vr(),Hn(),Xc=(t,e,r,n,a,o)=>(t-1)*e+r+(n-1)*a+1-o,Zc=(t,e,r,n,a)=>{let o=Math.floor(t/2);e==="SAME_UPPER"?(r[n]=o,r[a]=t-o):e==="SAME_LOWER"&&(r[n]=t-o,r[a]=o)},Jc=(t,e,r,n,a,o,i,d,h,m)=>{let c=t.length-2,_=m.length===0;if(h.length===0)for(let C=0;C{let r=t.kernelShape.slice();if(t.kernelShape.length===0||t.kernelShape.reduce((_,v)=>_*v,1)===0){r.length=0;for(let _=2;__+v,0)===0){let _=e[0].dims.length-2;h=new Array(_).fill(1)}let m=t.strides.slice();if(m.reduce((_,v)=>_+v,0)===0){let _=e[0].dims.length-2;m=new Array(_).fill(1)}Jc(d,r,h,t.autoPad,t.group,a,m,n,i,o);let c=Object.assign({},t);return Object.assign(c,{kernelShape:r,pads:a,outputPadding:i,outputShape:o,dilations:h,strides:m}),c},ep=t=>{let e=so(t),r=t.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof t.autoPad>"u"?0:t.autoPad],a=t.dilations,o=t.group,i=t.kernelShape,d=t.pads,h=t.strides,m=t.wIsConst(),c=t.outputPadding,_=t.outputShape;return{autoPad:n,format:r,dilations:a,group:o,kernelShape:i,outputPadding:c,outputShape:_,pads:d,strides:h,wIsConst:m,...e,cacheKey:`${t.format};${e.activation};`}},tp=(t,e)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4&&t[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let r=t[0].dims[e.format==="NHWC"?t[0].dims.length-1:1],n=t[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let a=t[1].dims[1]*e.group;if(t.length===3&&(t[2].dims.length!==1||t[2].dims[0]!==a))throw new Error("invalid bias");let o=t[0].dims.length-2;if(e.dilations.reduce((i,d)=>i+d,0)>0&&e.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(e.strides.reduce((i,d)=>i+d,0)>0&&e.strides.length!==o)throw new Error(`strides should be ${o}D`);if(e.pads.reduce((i,d)=>i+d,0)>0&&e.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(e.outputPadding.length!==o&&e.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(e.kernelShape.reduce((i,d)=>i+d,0)>0&&e.kernelShape.length!==0&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(e.outputShape.length!==0&&e.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape")},rp=[2,3,1,0],np=(t,e,r)=>{let n=wo(r,e),a=r.format==="NHWC",o=n.outputShape,i=o[a?3:1],d=e[0].dims[a?3:1];if(n.group!==1||i===1&&d===1){t.compute(_o(e,n));return}let h=o[a?1:2],m=o[a?2:3],c=e[1].dims[2],_=e[1].dims[3],v=a?h*m:i,$=a?i:h*m,C=c*_*d,k=!0,M=t.kernelCustomData.wT??t.compute(yr(e[1],rp),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=M);let z=[e[0],M],I=e.length===3;I&&(!a&&e[2].dims.length===1?z.push(e[2].reshape([e[2].dims[0],1,1])):z.push(e[2])),t.compute(Yc(z,n,o,v,$,C,I,k),{inputs:z})},ip=(t,e)=>{let r=e.format==="NHWC",n=[t.inputs[0].reshape(r?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];t.inputs.length===3&&n.push(t.inputs[2]);let a=e.kernelShape;(a.length===0||a[0]===0)&&(a=[t.inputs[1].dims[2]]);let o=e.dilations;(o.length===0||o[0]===0)&&(o=[1]);let i=e.strides;(i.length===0||i[0]===0)&&(i=[1]);let d=e.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],i=[1].concat(i),o=[1].concat(o),a=[1].concat(a);let h=wo({...e,pads:d,strides:i,dilations:o,kernelShape:a},n);t.compute(_o(n,h,m=>r?[m[0],m[2],m[3]]:[m[0],m[1],m[3]]))},ap=(t,e)=>{tp(t.inputs,e),t.inputs[0].dims.length===3?ip(t,e):np(t,t.inputs,e)}}),sp,op,lp,gw=le(()=>{Oe(),Be(),ft(),Re(),sp=(t,e,r,n)=>{let a=se.size(e),o=e.length,i=oe("input",t,o),d=$e("output",t,o),h=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),m=se.normalizeAxis(h,o),c=_=>{let v=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,$=ze("uniforms.input_shape","uniforms.axis",o),C=n.reverse?v+(n.exclusive?" + 1":""):"0",k=n.reverse?$:v+(n.exclusive?"":" + 1");return` ${_.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,d)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${d.offsetToIndices("global_idx")}; var sum = ${d.type.value}(0); let first : i32 = ${C}; let last : i32 = ${k}; for (var i : i32 = first; i < last; i++) { ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${i.getByIndices("inputIndices")}; } ${d.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:e,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},{type:12,data:m},...Ce(e,e)]}),getShaderSource:c}},op=(t,e)=>{let r=t.inputs[0].dims,n=t.inputs[0].dataType,a=t.inputs[1];t.compute(sp(n,r,a,e),{inputs:[0]})},lp=t=>{let e=t.exclusive===1,r=t.reverse===1;return Ze({exclusive:e,reverse:r})}}),up,dp,cp,pp,hp,yw=le(()=>{Oe(),Be(),ft(),Re(),up=t=>{if(!t||t.length!==1)throw new Error("DepthToSpace requires 1 input.");if(t[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},dp=(t,e,r,n)=>{let a=[];a.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let o=0;o{let r,n,a,o,i,d,h=e.format==="NHWC",m=e.blocksize,c=e.mode==="DCR";h?([r,n,a,o]=t.dims,i=c?[r,n,a,m,m,o/m**2]:[r,n,a,o/m**2,m,m],d=c?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,a,o]=[t.dims[0],t.dims[2],t.dims[3],t.dims[1]],i=c?[r,m,m,o/m**2,n,a]:[r,o/m**2,m,m,n,a],d=c?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let _=t.reshape(i),v=_.dims.length,$=t.dataType,C=oe("a",$,v),k=$e("output",$,v),M=z=>` ${z.registerUniform("output_size","u32").declareVariables(C,k)} ${dp(d,v,C,k)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${k.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${k.setByOffset("global_idx",C.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${t.dims};${e.blocksize};${e.mode}`,inputDependencies:["rank"]},getRunData:z=>{let I=h?[r,n*m,a*m,o/m**2]:[r,o/m**2,n*m,a*m],j=se.size(I),R=_.dims,L=se.sortBasedOnPerm(R,d);return{outputs:[{dims:I,dataType:z[0].dataType}],dispatchGroup:{x:Math.ceil(j/64)},programUniforms:[{type:12,data:j},...Ce(R,L)]}},getShaderSource:M}},pp=(t,e)=>{up(t.inputs),t.compute(cp(t.inputs[0],e))},hp=t=>Ze({blocksize:t.blocksize,mode:t.mode,format:t.format})}),Ea,qn,vo,fp,mp,gp,yp,bo,_p,wp,vp,_w=le(()=>{Oe(),Be(),ft(),Re(),Ea="[a-zA-Z]|\\.\\.\\.",qn="("+Ea+")+",vo="^"+qn+"$",fp="("+qn+",)*"+qn,mp="^"+fp+"$",gp=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,e){let r=this.symbolToIndices.get(t);r===void 0?r=[e]:r.push(e),this.symbolToIndices.set(t,r)}},yp=class{constructor(t,e){var a;this.equation=e,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=e.includes("->")?e.split("->",2):[e,""];if(!r.match(RegExp(mp)))throw new Error("Invalid LHS term");if(r.split(",").forEach((o,i)=>{let d=t[i].dims.slice();if(!o.match(RegExp(vo)))throw new Error("Invalid LHS term");let h=this.processTerm(o,!0,d,i);this.lhs.push(h)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([o,i])=>i.count===1||o==="...").map(([o])=>o).join("");else if(!n.match(RegExp(qn)))throw new Error("Invalid RHS");(a=n.match(RegExp(Ea,"g")))==null||a.forEach(o=>{if(o==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(o);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(t,e,r){let n=this.symbolToInfo.get(t);if(n!==void 0){if(n.dimValue!==e&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:e,inputIndices:[r]};this.symbolToInfo.set(t,n)}processTerm(t,e,r,n=-1){let a=r.length,o=!1,i=[],d=0;if(!t.match(RegExp(vo))&&!e&&t!=="")throw new Error("Invalid LHS term");let h=t.match(RegExp(Ea,"g")),m=new gp(n);return h==null||h.forEach((c,_)=>{if(c==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let v=a-h.length+1;if(v<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(d,d+v),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(e)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let $=0;$t+"_max",_p=(t,e,r,n)=>{let a=t.map(m=>m.length).map((m,c)=>oe(`input${c}`,e,m)),o=se.size(n),i=$e("output",e,n.length),d=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),h=m=>{let c=[],_="var prod = 1.0;",v="var sum = 0.0;",$="sum += prod;",C=[],k=[],M=[],z=[],I=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((R,L)=>{var Y;if(r.rhs.symbolToIndices.has(L)){let Q=(Y=r.rhs.symbolToIndices.get(L))==null?void 0:Y[0];Q!==void 0&&r.lhs.forEach((ie,pe)=>{if(R.inputIndices.includes(pe)){let ce=ie.symbolToIndices.get(L);if(ce===void 0)throw new Error("Invalid symbol error");ce.forEach(Se=>{c.push(`${a[pe].indicesSet(`input${pe}Indices`,Se,i.indicesGet("outputIndices",Q))}`)})}})}else r.lhs.forEach((Q,ie)=>{if(R.inputIndices.includes(ie)){let pe=Q.symbolToIndices.get(L);if(pe===void 0)throw new Error("Invalid symbol error");pe.forEach(ce=>{C.push(`${a[ie].indicesSet(`input${ie}Indices`,ce,`${L}`)}`)}),z.push(`prod *= ${a[ie].getByIndices(`input${ie}Indices`)};`)}}),k.push(`for(var ${L}: u32 = 0; ${L} < uniforms.${bo(L)}; ${L}++) {`),M.push("}")});let j=I?[...c,`let sum = ${a.map((R,L)=>R.getByIndices(`input${L}Indices`)).join(" * ")};`]:[...c,v,...k,...C,_,...z,$,...M];return` ${m.registerUniforms(d.map(R=>({name:`${bo(R)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...a,i)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${a.map((R,L)=>`var input${L}Indices: ${a[L].type.indices};`).join(` `)} ${j.join(` `)}; ${i.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:t.map(()=>"rank")},getRunData:()=>{let m=d.filter(_=>r.symbolToInfo.has(_)).map(_=>{var v;return{type:12,data:((v=r.symbolToInfo.get(_))==null?void 0:v.dimValue)||0}});m.push({type:12,data:o});let c=t.map((_,v)=>[...Ce(_)]).reduce((_,v)=>_.concat(v),m);return c.push(...Ce(n)),{outputs:[{dims:n,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:c}},getShaderSource:h}},wp=(t,e)=>{let r=new yp(t.inputs,e.equation),n=r.outputDims,a=t.inputs.map((o,i)=>o.dims);t.compute(_p(a,t.inputs[0].dataType,r,n))},vp=t=>{let e=t.equation.replace(/\s+/g,"");return Ze({equation:e})}}),bp,$o,$p,xp,Cp,ww=le(()=>{Oe(),Be(),Re(),bp=t=>{if(!t||t.length!==2)throw new Error("Expand requires 2 input.");let e=t[0].dims,r=Array.from(t[1].getBigInt64Array(),Number),n=r.length{let r=t.length-e.length,n=[];for(let a=0;at.length>e.length?$o(t,e):$o(e,t),xp=t=>{let e=t[0].dims,r=Array.from(t[1].getBigInt64Array(),Number),n=$p(e,r),a=t[0].dataType,o=a===9?4:1,i=Math.ceil(se.size(n)/o),d=m=>{let c=oe("input",a,e.length,o),_=$e("output",a,n.length,o),v;if(a===9){let $=(C,k,M="")=>` let outputIndices${k} = ${_.offsetToIndices(`outputOffset + ${k}u`)}; let offset${k} = ${c.broadcastedIndicesToOffset(`outputIndices${k}`,_)}; let index${k} = offset${k} / 4u; let component${k} = offset${k} % 4u; ${C}[${k}] = ${M}(${c.getByOffset(`index${k}`)}[component${k}]); `;v=` let outputOffset = global_idx * ${o}; var data = vec4(0); ${$("data",0,"u32")} ${$("data",1,"u32")} ${$("data",2,"u32")} ${$("data",3,"u32")} ${_.setByOffset("global_idx","data")} }`}else v=` let outputIndices = ${_.offsetToIndices("global_idx")}; let inputOffset = ${c.broadcastedIndicesToOffset("outputIndices",_)}; ${_.setByOffset("global_idx",c.getByOffset("inputOffset"))} }`;return` ${m.registerUniform("vec_size","u32").declareVariables(c,_)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${v}`},h=[{type:12,data:i},...Ce(e,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:h})}},Cp=t=>{bp(t.inputs),t.compute(xp(t.inputs),{inputs:[0]})}}),Sp,Ep,vw=le(()=>{Oe(),Be(),Re(),ao(),Sp=t=>{let e=t[0].dataType,r=se.size(t[0].dims),n=se.size(t[1].dims),a=n%4===0,o=i=>{let d=oe("x",e,[1],4),h=oe("bias",e,[1],4),m=$e("y",e,[1],4),c=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],_=$=>` let bias${$}_offset: u32 = (global_idx * 4 + ${$}) % uniforms.bias_size; let bias${$} = ${h.getByOffset(`bias${$}_offset / 4`)}[bias${$}_offset % 4];`,v=a?` let bias = ${h.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${_(0)}${_(1)}${_(2)}${_(3)} let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(c).declareVariables(d,h,m)} ${no(kt(e))} ${i.mainStart(fn)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${d.getByOffset("global_idx")}; ${v} let x_in = x + bias; ${m.setByOffset("global_idx",io("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${a}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/fn/4)}})}},Ep=t=>{t.inputs.length<2||se.size(t.inputs[1].dims)===0?mc(t):t.compute(Sp(t.inputs))}}),kp,Tp,Ip,Ap,bw=le(()=>{Oe(),Be(),ft(),Re(),kp=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},Tp=(t,e)=>{let r=t[0].dims,n=t[1].dims,a=r.length,o=se.normalizeAxis(e.axis,a),i=r.slice(0);i.splice(o,1,...n);let d=r[o],h=t[0].dataType===9?4:1,m=Math.ceil(se.size(i)/h),c=[{type:12,data:m},{type:6,data:d},{type:12,data:o},...Ce(t[0].dims,t[1].dims,i)],_=v=>{let $=oe("data",t[0].dataType,t[0].dims.length,h),C=oe("inputIndices",t[1].dataType,t[1].dims.length),k=$e("output",t[0].dataType,i.length,h),M=I=>{let j=n.length,R=`var indicesIndices${I} = ${C.type.indices}(0);`;for(let L=0;L1?`indicesIndices${I}[${L}]`:`indicesIndices${I}`} = ${i.length>1?`outputIndices${I}[uniforms.axis + ${L}]`:`outputIndices${I}`};`;R+=` var idx${I} = ${C.getByIndices(`indicesIndices${I}`)}; if (idx${I} < 0) { idx${I} = idx${I} + uniforms.axisDimLimit; } var dataIndices${I} : ${$.type.indices}; `;for(let L=0,Y=0;L1?`dataIndices${I}[${L}]`:`dataIndices${I}`} = u32(idx${I});`,Y+=j):(R+=`${a>1?`dataIndices${I}[${L}]`:`dataIndices${I}`} = ${i.length>1?`outputIndices${I}[${Y}]`:`outputIndices${I}`};`,Y++);return R},z;if(t[0].dataType===9){let I=(j,R,L="")=>` let outputIndices${R} = ${k.offsetToIndices(`outputOffset + ${R}u`)}; ${M(R)}; let offset${R} = ${$.indicesToOffset(`dataIndices${R}`)}; let index${R} = offset${R} / 4u; let component${R} = offset${R} % 4u; ${j}[${R}] = ${L}(${$.getByOffset(`index${R}`)}[component${R}]); `;z=` let outputOffset = global_idx * ${h}; var value = vec4(0); ${I("value",0,"u32")} ${I("value",1,"u32")} ${I("value",2,"u32")} ${I("value",3,"u32")} ${k.setByOffset("global_idx","value")} `}else z=` let outputIndices = ${k.offsetToIndices("global_idx")}; ${M("")}; let value = ${$.getByIndices("dataIndices")}; ${k.setByOffset("global_idx","value")}; `;return` ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables($,C,k)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${z} }`};return{name:"Gather",shaderCache:{hint:e.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:c}),getShaderSource:_}},Ip=t=>Ze({axis:t.axis}),Ap=(t,e)=>{let r=t.inputs;kp(r),t.compute(Tp(t.inputs,e))}}),Mp,Op,zp,Pp,$w=le(()=>{Oe(),Be(),ft(),Re(),Mp=t=>{if(!t||t.length!==2)throw new Error("GatherElements requires 2 inputs.");if(t[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(t[0].dims.length!==t[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},Op=(t,e)=>{let r=t[0].dims,n=t[0].dataType,a=r.length,o=t[1].dims,i=t[1].dataType,d=se.normalizeAxis(e.axis,a),h=r[d],m=o.slice(0),c=se.size(m),_=oe("input",n,a),v=oe("indicesInput",i,o.length),$=$e("output",n,m.length),C=[{type:12,data:c},{type:6,data:h},{type:12,data:d}];return C.push(...Ce(r,o,m)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:m,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:C}),getShaderSource:k=>` ${k.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,v,$)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${$.offsetToIndices("global_idx")}; var idx = ${v.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${_.type.indices}(outputIndices); ${_.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${_.getByIndices("inputIndices")}; ${$.setByOffset("global_idx","value")}; }`}},zp=t=>Ze({axis:t.axis}),Pp=(t,e)=>{let r=t.inputs;Mp(r),t.compute(Op(t.inputs,e))}}),jp,Rp,Bp,Dp,xw=le(()=>{Oe(),Be(),Re(),jp=t=>{if(!t)throw new Error("Input is missing");if(t.length<2||t.length>3)throw new Error("Invaid input number.");if(t.length===3&&t[2].dims.length>2)throw new Error("Invalid input shape of C");if(t[0].dataType!==t[1].dataType||t.length===3&&t[0].dataType!==t[2].dataType)throw new Error("Input types are mismatched")},Rp=(t,e)=>{let r=t[0].dims.slice(),n=t[1].dims.slice(),[a,o,i]=wu.getShapeOfGemmResult(r,e.transA,n,e.transB,t.length===3?t[2].dims:void 0),d=[a,o];if(!d)throw new Error("Can't use gemm on the given tensors");let h=se.size(d),m=[{type:12,data:h},{type:12,data:a},{type:12,data:o},{type:12,data:i},{type:1,data:e.alpha},{type:1,data:e.beta}],c=["type","type"];t.length===3&&(m.push(...Ce(t[2].dims)),c.push("rank")),m.push(...Ce(d));let _=v=>{let $="";e.transA&&e.transB?$="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":e.transA&&!e.transB?$="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!e.transA&&e.transB?$="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!e.transA&&!e.transB&&($="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=e.alpha===1?"":"value *= uniforms.alpha;",k=oe("a",t[0].dataType,t[0].dims),M=oe("b",t[1].dataType,t[1].dims),z=k.type.value,I=null,j=[k,M];t.length===3&&(I=oe("c",t[2].dataType,t[2].dims.length),j.push(I));let R=$e("output",t[0].dataType,d.length);j.push(R);let L=[{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` ${v.registerUniforms(L).declareVariables(...j)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${z}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${$} } ${C} ${I!=null?`let cOffset = ${I.broadcastedIndicesToOffset("vec2(m, n)",R)}; value += ${z}(uniforms.beta) * ${I.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:d,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m}),getShaderSource:_}},Bp=t=>{let e=t.transA,r=t.transB,n=t.alpha,a=t.beta;return{transA:e,transB:r,alpha:n,beta:a,cacheKey:`${t.transA};${t.transB};${t.alpha===1}`}},Dp=(t,e)=>{jp(t.inputs),t.compute(Rp(t.inputs,e))}}),Np,Lp,Up,Fp,Cw=le(()=>{Oe(),Be(),Re(),Np=(t,e)=>{let r=t[0].dims,n=r,a=2,o=se.sizeToDimension(r,a),i=se.sizeFromDimension(r,a),d=dt(i),h=i/d,m=[r[0],r[1],h],c=["rank","type","type"],_=[{type:12,data:i},{type:12,data:h}];_.push(...Ce(m,m));let v=$=>{let C=oe("x",t[0].dataType,m.length,d),k=oe("scale",t[1].dataType,t[1].dims),M=oe("bias",t[2].dataType,t[2].dims),z=$e("output",t[0].dataType,m.length,d),I=[C,k,M,z],j=C.type.value,R=d===1?"f32":`vec${d}`,L=64,Y=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${R}, ${L}>; const workgroupSize = ${L}u; ${$.registerUniforms(Y).declareVariables(...I)} ${$.mainStart(L)} 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 = ${R}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${R}(${C.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 = ${kr("workgroupShared[0]",d)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${R}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${R}(${C.get("batch","channel","h")}) - ${R}(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 = ${kr("workgroupShared[0]",d)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); let channelScale = invStdDev * f32(${k.getByOffset("channel")}); let channelShift = f32(${M.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${C.get("batch","channel","h")} * ${j}(${R}(channelScale)) + ${j}(${R}(channelShift)); ${z.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${e.epsilon};${d}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:o},programUniforms:_}),getShaderSource:v}},Lp=(t,e,r,n,a,o,i,d)=>{let h=dt(i),m=64,c=h===1?"vec2f":`mat2x${h}f`,_=h===1?"f32":`vec${h}f`,v=(Y,Q)=>`${c}(${Y}, ${Q})`,$=a*i/h,C=Math.ceil(o/m),k=["type"],M=[{type:12,data:C},{type:12,data:o},{type:12,data:Math.floor(i/h)},{type:12,data:Math.floor(o*i/h)}],z=Y=>{let Q=oe("input",e.dataType,e.dims,h);return` ${Y.declareVariables(Q)} @group(0) @binding(1) var output : array<${c}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${Y.mainStart(m)} let currentImageNumber = global_idx / ${m} / uniforms.C; let currentChannelNumber = (global_idx / ${m}) % uniforms.C; let wgOffset = local_id.x * uniforms.wg_size; if (wgOffset >= uniforms.H) { return; } let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; var sum = ${gr("f32",h)}; var squaredSum = ${gr("f32",h)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${_}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${v("sum","squaredSum")}; }`},I=t.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${h}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:[a,i,m,2],dataType:1}],dispatchGroup:{x:a*i/h},programUniforms:M}),getShaderSource:z},{inputs:[e],outputs:[-1]})[0],j=[{type:12,data:$},{type:12,data:o},{type:12,data:Math.floor(i/h)},{type:12,data:Math.floor(m*i/h)}],R=["type","type","type"],L=Y=>{let Q=oe("scale",r.dataType,r.dims,h),ie=oe("bias",n.dataType,n.dims,h);return` @group(0) @binding(0) var input : array<${c}>; @group(0) @binding(1) var scale : array<${Q.type.storage}>; @group(0) @binding(2) var bias : array<${ie.type.storage}>; @group(0) @binding(3) var output : array<${c}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${Y.mainStart()} ${Y.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 = ${gr("f32",h)}; var squaredSum = ${gr("f32",h)}; for (var i: u32 = 0; i < min(${m}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${m}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${d})); let channelScale = invStdDev * ${_}(scale[currentChannelNumber]); let channelShift = ${_}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${v("channelScale","channelShift")}; }`};return t.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${d}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:[a,i,2],dataType:1}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:j}),getShaderSource:L},{inputs:[I,r,n],outputs:[-1]})[0]},Up=(t,e,r)=>{let n=e[0].dims,a=n,o=n[0],i=n[n.length-1],d=se.sizeFromDimension(n,1)/i,h=dt(i),m=se.size(a)/h,c=[{type:12,data:d},{type:12,data:Math.floor(i/h)}],_=["type","type"],v=Lp(t,e[0],e[1],e[2],o,d,i,r.epsilon),$=C=>{let k=mt(e[0].dataType),M=h===1?"vec2f":`mat2x${h}f`,z=h===1?k:`vec${h}<${k}>`,I=oe("input",e[0].dataType,e[0].dims,h),j=$e("output",e[0].dataType,a,h);return` @group(0) @binding(0) var input : array<${I.type.storage}>; @group(0) @binding(1) var scaleInput : array<${M}>; @group(0) @binding(2) var output : array<${j.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${C.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], ${z}(scale[0]), ${z}(scale[1])); }`};t.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${h}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:c}),getShaderSource:$},{inputs:[e[0],v]})},Fp=(t,e)=>{e.format==="NHWC"?Up(t,t.inputs,e):t.compute(Np(t.inputs,e))}}),Wp,Gp,Vp,Sw=le(()=>{Oe(),Be(),Re(),Wp=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Gp=(t,e,r)=>{let n=e.simplified,a=t[0].dims,o=t[1],i=!n&&t[2],d=a,h=se.normalizeAxis(e.axis,a.length),m=se.sizeToDimension(a,h),c=se.sizeFromDimension(a,h),_=se.size(o.dims),v=i?se.size(i.dims):0;if(_!==c||i&&v!==c)throw new Error(`Size of X.shape()[axis:] == ${c}. Size of scale and bias (if provided) must match this. Got scale size of ${_} and bias size of ${v}`);let $=[];for(let L=0;L1,I=r>2,j=L=>{let Y=mt(t[0].dataType),Q=[oe("x",t[0].dataType,t[0].dims,C),oe("scale",o.dataType,o.dims,C)];i&&Q.push(oe("bias",i.dataType,i.dims,C)),Q.push($e("output",t[0].dataType,d,C)),z&&Q.push($e("mean_data_output",1,$)),I&&Q.push($e("inv_std_output",1,$));let ie=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${L.registerUniforms(ie).declareVariables(...Q)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${gr("f32",C)}; var mean_square_vector = ${gr("f32",C)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${mn(Y,C,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${kr("mean_vector",C)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${kr("mean_square_vector",C)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${mn(Y,C,"x[j + offset]")}; let f32scale = ${mn(Y,C,"scale[j]")}; output[j + offset] = ${Q[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${mn(Y,C,"bias[j]")}`:""} ); } ${z?"mean_data_output[global_idx] = mean":""}; ${I?"inv_std_output[global_idx] = inv_std_dev":""}; }`},R=[{dims:d,dataType:t[0].dataType}];return z&&R.push({dims:$,dataType:1}),I&&R.push({dims:$,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${C};${r};${n}`,inputDependencies:k},getRunData:()=>({outputs:R,dispatchGroup:{x:Math.ceil(m/64)},programUniforms:M}),getShaderSource:j}},Vp=(t,e)=>{Wp(t.inputs),t.compute(Gp(t.inputs,e,t.outputCount))}}),Hp,qp,Kp,Yp,Ew=le(()=>{Oe(),Be(),ft(),Re(),Hp=(t,e)=>{if(t.length<3||t.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=t[0],n=r.dims.length;if(r.dims[n-1]!==e.k)throw new Error("The last dim of input shape does not match the k value");let a=Math.floor((e.k+e.blockSize-1)/e.blockSize),o=e.blockSize/8*e.bits,i=t[1];if(!se.areEqual(i.dims,[e.n,a,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=t[2].dims;if(se.size(d)!==e.n*a)throw new Error("scales input size error.");if(t.length===4){let h=t[3].dims,m=e.bits>4?e.n*a:e.n*Math.floor((a+1)/2);if(se.size(h)!==m)throw new Error("zeroPoints input size error.")}},qp=(t,e,r,n)=>{let a=t[0].dims,o=a.length,i=Math.floor((e.k+e.blockSize-1)/e.blockSize),d=a[o-2],h=e.k,m=e.n,c=a.slice(0,o-2),_=se.size(c),v=e.blockSize/8*e.bits/4,$=t[0].dataType,C=dt(d),k=dt(e.k),M=dt(v),z=Gn($),I=d*i*z,j=Math.floor(n/I),R=i<=r[0]&&j>0,L=!R||j>=4?dt(m):j>=2&&dt(m)>=2?2:1,Y=c.concat([d,m]),Q=se.size(Y)/L/C,ie=R?[]:[{type:12,data:Q},{type:12,data:e.blockSize}],pe=[_,d,h/k],ce=se.convertShape(t[1].dims).slice();ce.splice(-1,1,v/M),ie.push(...Ce(pe)),ie.push(...Ce(ce)),ie.push(...Ce(t[2].dims)),t.length===4&&ie.push(...Ce(se.convertShape(t[3].dims)));let Se=[_,d,m/L];ie.push(...Ce(Se));let fe=me=>{let ge=pe.length,X=oe("a",t[0].dataType,ge,k),U=oe("b",12,ce.length,M),ne=oe("scales",t[2].dataType,t[2].dims.length),ee=[X,U,ne],Ee=t.length===4?oe("zero_points",12,t[3].dims.length):void 0;Ee&&ee.push(Ee);let Te=Se.length,K=$e("output",t[0].dataType,Te,L),he=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],ve=mt(t[0].dataType),Le=(()=>{switch(k){case 1:return`array<${ve}, 8>`;case 2:return`mat4x2<${ve}>`;case 4:return`mat2x4<${ve}>`;default:throw new Error(`${k}-component is not supported.`)}})(),Ke=` for (var word: u32 = 0; word < ${v}; word += ${M}) { ${U.indicesSet("b_indices","2","word")}; let b_data = ${U.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${M}; i++) { let b_value: u32 = ${M===1?"b_data":"b_data[word + i]"}; let b_mask: u32 = 0x0F0F0F0Fu; let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); let b_quantized_values = ${Le}(${Array.from({length:4},(pt,rt)=>`${ve}(b_value_lower[${rt}]), ${ve}(b_value_upper[${rt}])`).join(", ")}); let b_dequantized_values = ${k===1?`${Le}(${Array.from({length:8},(pt,rt)=>`(b_quantized_values[${rt}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${Le}(${Array(8).fill("zero_point").join(",")})) * scale;`}; // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 for (var m: u32 = 0; m < ${R?d:C}u; m++) { ${X.indicesSet("a_indices",ge-2,R?"m":`row * ${C} + m`)}; ${X.indicesSet("a_indices",ge-1,"word_offset")}; var input_offset = ${X.indicesToOffset("a_indices")}; var a_data: ${Le}; for (var j: u32 = 0; j < ${8/k}; j++) { a_data[j] = ${X.getByOffset("input_offset")}; input_offset++; } ${R?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${L>1?"[c]":""} += ${Array.from({length:8/k},(pt,rt)=>`${k===1?`a_data[${rt}] * b_dequantized_values[${rt}]`:`dot(a_data[${rt}], b_dequantized_values[${rt}])`}`).join(" + ")}; } word_offset += ${8/k}; } }`,ct=Ee?` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${Ee.getByOffset("zero_point_index")}; }`:"";return R?` var workgroup_shared: array<${K.type.value}, ${d*i}>; ${me.declareVariables(...ee,K)} ${me.mainStart([i,1,1])} var a_indices: ${X.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${X.indicesSet("a_indices","0","batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${L}; c++) { let col_times_components_plus_c = col * ${L} + c; ${Ee?` var zero_point_bytes_per_col: u32 = (${i} + 1) / 2; var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; var zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); var zero_point_word: u32 = ${Ee.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} var b_indices: ${U.type.indices}; ${U.indicesSet("b_indices","0","col_times_components_plus_c")}; // The scale and zero points are computed per block. var scales_index = col_times_components_plus_c * ${i} + block; let scale = ${ne.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${ve}(${Ee?"(zero_point_word) & 0xFu":8}); ${U.indicesSet("b_indices","1","block")}; var word_offset: u32 = block * ${e.blockSize/k}; var workgroup_shared_offset: u32 = block * ${d}; ${Ke} } workgroupBarrier(); if (local_id.x == 0u) { var output_indices: ${K.type.indices}; ${K.indicesSet("output_indices","0","batch")}; ${K.indicesSet("output_indices",Te-1,"col")}; ${K.indicesSet("output_indices",Te-2,"0")}; var output_offset = ${K.indicesToOffset("output_indices")}; for (var m: u32 = 0u; m < ${d}u; m++) { var output_value: ${K.type.value} = ${K.type.value}(0); var workgroup_shared_offset: u32 = m; for (var b: u32 = 0u; b < ${i}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${d}; } ${K.setByOffset("output_offset","output_value")}; output_offset += ${m/L}; } } }`:` ${me.registerUniforms(he).declareVariables(...ee,K)} ${me.mainStart()} ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${K.type.value}, ${C}>; var output_indices = ${K.offsetToIndices("global_idx")}; var col = ${K.indicesGet("output_indices",Te-1)}; var row = ${K.indicesGet("output_indices",Te-2)}; var a_indices: ${X.type.indices} = output_indices; // Two zero points are packed into one byte because uniforms.bits <= 4. // zero_point_offset is either 0 or 4. It is bit offset within one byte. // TODO support zero_point_offset for bits > 4 ${Ee?` var zero_point_abs_offset = col * ${L} * ((${i} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${Ee.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} var scale_index = col * ${i*L}; var b_indices: ${U.type.indices}; for (var c: u32 = 0; c < ${L}; c++) { ${U.indicesSet("b_indices","0",`col * ${L} + c`)}; var block_offset: u32 = 0; for (var block: u32 = 0; block < ${i}; block++) { // The scale and zero points are computed per block. let scale = ${ne.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${ve}(${Ee?"extractBits(zero_point_word, zero_point_offset, 4)":8}); ${U.indicesSet("b_indices","1","block")}; var word_offset: u32 = block_offset; ${Ke} scale_index++; ${ct} block_offset += uniforms.block_size / ${k}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${Ee?`if (zero_point_offset % 8 > 0) { ${ct} }`:""} } for (var k: u32 = 0u; k < ${C}u; k++) { ${K.indicesSet("output_indices",Te-2,`${C} * row + k`)}; ${K.setByIndices("output_indices","output_values[k]")} } }`};return{name:R?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${e.cacheKey};${d};${$};${t.length}`,inputDependencies:Array(t.length).fill("rank")},getRunData:()=>({outputs:[{dims:Y,dataType:$}],name:R?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:R?{x:1,y:Math.ceil(m/L),z:_}:{x:Math.ceil(Q/64)},programUniforms:ie}),getShaderSource:fe}},Kp=(t,e)=>{Hp(t.inputs,e);let r=t.getMaxComputeWorkgroupSizes(),n=t.getMaxComputeWorkgroupStoragesize();t.compute(qp(t.inputs,e,r,n))},Yp=t=>Ze(t)}),xt,Qp,Xp,xo,Zp,ka,Jp,kw=le(()=>{Oe(),Be(),ft(),Gs(),Td(),Re(),Hn(),xt=(t,e)=>t.length>e&&t[e].dims.length>0&&se.size(t[e].dims)>0?t[e]:void 0,Qp=(t,e)=>{let r=t[0],n=xt(t,1),a=xt(t,2),o=xt(t,3),i=xt(t,4),d=xt(t,5),h=xt(t,6),m=xt(t,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,_=r.dims[0],v=r.dims[1],$=r.dims.length===3?c?r.dims[2]/3:r.dims[2]:e.numHeads*r.dims[4],C=v,k=0,M=0,z=Math.floor($/e.numHeads);if(h&&m){if(h.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(h.dims[0]!==_||h.dims[1]!==e.numHeads||h.dims[3]!==z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(m.dims[0]!==_||m.dims[1]!==e.numHeads||m.dims[3]!==z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[2]!==m.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(m.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');k=h.dims[2],M=h.dims[2]}else if(h||m)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let I;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');I=2,C=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==e.numHeads||n.dims[3]!==2||n.dims[4]!==z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');I=5,C=n.dims[1]}else{if(n.dims[1]!==e.numHeads||n.dims[3]!==z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');I=0,C=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==e.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');I=3}if(o){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(a&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let j=0;if(i){j=8;let ie=i.dims;throw ie.length===1?ie[0]===_?j=1:ie[0]===3*_+2&&(j=3):ie.length===2&&ie[0]===_&&ie[1]===C&&(j=5),j===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let R=!1,L=$;if(a){if(a.dims.length!==3&&a.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(a.dims.length===3){if(C!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');L=a.dims[2]}else{if(C!==a.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');L=a.dims[1]*a.dims[3],R=!0}}let Y=k+C,Q=!1;if(i)throw new Error("Key padding mask is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(d.dims[0]!==_&&d.dims[0]!==1||d.dims[1]!==e.numHeads||d.dims[2]!==v||d.dims[3]!==Y)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:_,sequenceLength:v,pastSequenceLength:k,kvSequenceLength:C,totalSequenceLength:Y,maxSequenceLength:M,inputHiddenSize:0,hiddenSize:$,vHiddenSize:L,headSize:z,vHeadSize:Math.floor(L/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:j,scale:e.scale,broadcastResPosBias:Q,passPastInKv:R,qkvFormat:I}},Xp=t=>Ze({...t}),xo=Ze({perm:[0,2,1,3]}),Zp=(t,e,r,n,a,o,i)=>{let d=[n,a,o],h=se.size(d),m=[{type:12,data:h},{type:12,data:i},{type:12,data:o}],c=_=>{let v=$e("qkv_with_bias",e.dataType,d),$=oe("qkv",e.dataType,d),C=oe("bias",r.dataType,d),k=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${_.registerUniforms(k).declareVariables($,C,v)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return t.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:d,dataType:e.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:m}),getShaderSource:c},{inputs:[e,r],outputs:[-1]})[0]},ka=(t,e,r,n,a,o,i,d)=>{let h=o;if(i){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return h=Zp(t,o,i,e,n,r*a,d),h=h.reshape([e,n,r,a]),t.compute(yr(h,xo.perm),{inputs:[h],outputs:[-1]})[0]}else return o.dims.length===3&&(h=o.reshape([e,n,r,a])),t.compute(yr(h,xo.perm),{inputs:[h],outputs:[-1]})[0]},Jp=(t,e)=>{let r=Qp(t.inputs,e),n=t.inputs[0],a=xt(t.inputs,1),o=xt(t.inputs,2),i=xt(t.inputs,3),d=xt(t.inputs,4),h=xt(t.inputs,5),m=xt(t.inputs,6),c=xt(t.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((a==null?void 0:a.dims.length)===5)throw new Error("Packed KV is not implemented");let _=a&&o&&a.dims.length===4&&o.dims.length===4,v=ka(t,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(_)return _a(t,v,a,o,d,void 0,m,c,h,r,e);if(!a||!o)throw new Error("key and value must be provided");let $=ka(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,a,i,r.hiddenSize),C=ka(t,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,o,i,2*r.hiddenSize);_a(t,v,$,C,d,void 0,m,c,h,r,e)}}),eh,th,rh,nh,ih,ah,sh,oh,lh,Tw=le(()=>{Oe(),Be(),Re(),eh=t=>{if(!t||t.length<1)throw new Error("Too few inputs");if(t[0].dataType!==1&&t[0].dataType!==10)throw new Error("Input type must be float or float16.");if(t.length>=2){let e=t[0].dims.length*2===t[1].dims[0];if(t.length===4&&(e=t[3].dims[0]*2===t[1].dims[0]),!e)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},th=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ze("uniforms.pads",a,r)}; if (k < 0) { break; } if (k >= i32(${ze("uniforms.x_shape",a,e)})) { break; } offset += k * i32(${ze("uniforms.x_strides",a,e)}); `;return` value = ${t.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},rh=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ze("uniforms.pads",a,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${ze("uniforms.x_shape",a,e)}) - 1); k = k % _2n_1; if(k >= i32(${ze("uniforms.x_shape",a,e)})) { k = _2n_1 - k; } } offset += k * i32(${ze("uniforms.x_strides",a,e)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},nh=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ze("uniforms.pads",a,r)}; if (k < 0) { k = 0; } if (k >= i32(${ze("uniforms.x_shape",a,e)})) { k = i32(${ze("uniforms.x_shape",a,e)}) - 1; } offset += k * i32(${ze("uniforms.x_strides",a,e)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},ih=(t,e,r)=>{let n="";for(let a=e-1;a>=0;--a)n+=` k = i32(${t.indicesGet("indices",a)}) - ${ze("uniforms.pads",a,r)}; if (k < 0) { k += i32(${ze("uniforms.x_shape",a,e)}]); } if (k >= i32(${ze("uniforms.x_shape",a,e)})) { k -= i32(${ze("uniforms.x_shape",a,e)}); } offset += k * i32(${ze("uniforms.x_strides",a,e)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},ah=(t,e,r)=>{switch(r.mode){case 0:return th(t,e,r.pads.length);case 1:return rh(t,e,r.pads.length);case 2:return nh(t,e,r.pads.length);case 3:return ih(t,e,r.pads.length);default:throw new Error("Invalid mode")}},sh=(t,e)=>{let r=se.padShape(t[0].dims.slice(),e.pads),n=t[0].dims,a=se.size(r),o=[{type:12,data:a},{type:6,data:e.pads}];e.mode===0&&o.push({type:t[0].dataType,data:e.value}),o.push(...Ce(t[0].dims,r));let i=["rank"],d=h=>{let m=$e("output",t[0].dataType,r.length),c=oe("x",t[0].dataType,n.length),_=c.type.value,v=ah(m,n.length,e),$=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&$.push({name:"constant_value",type:_}),` ${h.registerUniforms($).declareVariables(c,m)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${m.offsetToIndices("global_idx")}; var value = ${_}(0); ${v} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${e.mode}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(se.size(r)/64)},programUniforms:o}),getShaderSource:d}},oh=(t,e)=>{if(t.length>1){let r=t[1].getBigInt64Array(),n=t.length>=3&&t[2].data?t[2].getFloat32Array()[0]:0,a=t[0].dims.length,o=new Int32Array(2*a).fill(0);if(t.length>=4){let d=t[3].getBigInt64Array();for(let h=0;ho[Number(h)]=Number(d));let i=[];return o.forEach(d=>i.push(d)),{mode:e.mode,value:n,pads:i}}else return e},lh=(t,e)=>{eh(t.inputs);let r=oh(t.inputs,e);t.compute(sh(t.inputs,r),{inputs:[0]})}}),Kn,Co,So,Eo,ko,uh,dh,To,Io,ch,ph,Ao,hh,fh,Mo,mh,gh,yh,_h,Iw=le(()=>{Yt(),Oe(),Be(),Re(),Kn=t=>{if(He.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},Co=(t,e,r)=>{let n=e.format==="NHWC",a=t.dims.slice();n&&a.splice(1,0,a.pop());let o=Object.hasOwnProperty.call(e,"dilations"),i=e.kernelShape.slice(),d=e.strides.slice(),h=o?e.dilations.slice():[],m=e.pads.slice();ha.adjustPoolAttributes(r,a,i,d,h,m);let c=ha.computePoolOutputShape(r,a,d,h,i,m,e.autoPad),_=Object.assign({},e);o?Object.assign(_,{kernelShape:i,strides:d,pads:m,dilations:h,cacheKey:e.cacheKey}):Object.assign(_,{kernelShape:i,strides:d,pads:m,cacheKey:e.cacheKey});let v=c.slice();return v.push(v.splice(1,1)[0]),[_,n?v:c]},So=(t,e)=>{let r=e.format==="NHWC",n=se.size(t),a=se.size(e.kernelShape),o=[{type:12,data:n},{type:12,data:a}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(e.kernelShape.length<=2){let d=e.kernelShape[e.kernelShape.length-1],h=e.strides[e.strides.length-1],m=e.pads[e.pads.length/2-1],c=e.pads[e.pads.length-1],_=!!(m+c);o.push({type:12,data:d},{type:12,data:h},{type:12,data:m},{type:12,data:c}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let v=!1;if(e.kernelShape.length===2){let $=e.kernelShape[e.kernelShape.length-2],C=e.strides[e.strides.length-2],k=e.pads[e.pads.length/2-2],M=e.pads[e.pads.length-2];v=!!(k+M),o.push({type:12,data:$},{type:12,data:C},{type:12,data:k},{type:12,data:M}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,i,!0,_,v]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=se.computeStrides(e.kernelShape);o.push({type:12,data:d},{type:12,data:e.pads},{type:12,data:e.strides}),i.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:e.pads.length},{name:"strides",type:"u32",length:e.strides.length});let h=e.pads.reduce((m,c)=>m+c);return[o,i,!!h,!1,!1]}},Eo=(t,e,r,n,a,o,i,d,h,m,c,_)=>{let v=a.format==="NHWC",$=e.type.value,C=$e("output",e.type.tensor,n);if(a.kernelShape.length<=2){let k="",M="",z="",I=r-(v?2:1);if(c?k=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${I}] = indices[${I}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${I}] < 0 || xIndices[${I}] >= uniforms.x_shape[${I}]) { pad++; continue; } let x_val = x[${e.indicesToOffset("xIndices")}]; ${o} }`:k=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${I}] = indices[${I}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${e.indicesToOffset("xIndices")}]; ${o} }`,a.kernelShape.length===2){let j=r-(v?3:2);_?M=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${j}] = indices[${j}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${j}] < 0 || xIndices[${j}] >= uniforms.x_shape[${j}]) { pad += i32(uniforms.kw); continue; } `:M=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${j}] = indices[${j}] * uniforms.sh - uniforms.phStart + j; `,z=` } `}return` ${t.registerUniforms(h).declareVariables(e,C)} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${C.offsetToIndices("global_idx")}; var xIndices = ${C.offsetToIndices("global_idx")}; var value = ${$}(${d}); var pad = 0; ${M} ${k} ${z} ${i} output[global_idx] = value; }`}else{if(v)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let k=a.kernelShape.length,M=a.pads.length,z="";return m?z=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${e.indicesToOffset("xIndices")}]; ${o} }`:z=` } let x_val = x[${e.indicesToOffset("xIndices")}]; ${o} `,` ${t.registerUniforms(h).declareVariables(e,C)} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${C.offsetToIndices("global_idx")}; var xIndices = ${C.offsetToIndices("global_idx")}; var offsets: array; var value = ${$}(${d}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${k-1}u; j++) { offsets[j] = offset / ${ze("uniforms.kernelStrides","j",k)}; offset -= offsets[j] * ${ze("uniforms.kernelStrides","j",k)}; } offsets[${k-1}] = offset; isPad = false; for (var j = ${r-k}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${ze("uniforms.strides",`j - ${r-k}u`,k)} + offsets[j - ${r-k}u] - ${ze("uniforms.pads","j - 2u",M)}; ${z} } ${i} output[global_idx] = value; }`}},ko=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,uh=t=>`${ko(t)};${t.countIncludePad}`,dh=t=>`${ko(t)};${t.storageOrder};${t.dilations}`,To=t=>({format:t.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],ceilMode:t.ceil_mode,kernelShape:t.kernel_shape,strides:t.strides,pads:t.pads}),Io=(t,e,r,n)=>{let[a,o]=Co(e,n,r),i=oe("x",e.dataType,e.dims.length),d=i.type.value,h="value += x_val;",m="";a.countIncludePad?m+=`value /= ${d}(uniforms.kernelSize);`:m+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[c,_,v,$,C]=So(o,a);c.push(...Ce(e.dims,o));let k=["rank"];return{name:t,shaderCache:{hint:`${n.cacheKey};${v};${$};${C}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(se.size(o)/64)},programUniforms:c}),getShaderSource:M=>Eo(M,i,e.dims.length,o.length,a,h,m,0,_,v,$,C)}},ch=t=>{let e=t.count_include_pad!==0,r=To(t);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:e,...r,cacheKey:""};return{...n,cacheKey:uh(n)}},ph=(t,e)=>{Kn(t.inputs),t.compute(Io("AveragePool",t.inputs[0],!1,e))},Ao={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},hh=t=>{let e=t.format;return{format:e,...Ao,cacheKey:e}},fh=(t,e)=>{Kn(t.inputs),t.compute(Io("GlobalAveragePool",t.inputs[0],!0,e))},Mo=(t,e,r,n)=>{let[a,o]=Co(e,n,r),i=` value = max(x_val, value); `,d="",h=oe("x",e.dataType,e.dims.length),m=["rank"],[c,_,v,$,C]=So(o,a);return c.push(...Ce(e.dims,o)),{name:t,shaderCache:{hint:`${n.cacheKey};${v};${$};${C}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(se.size(o)/64)},programUniforms:c}),getShaderSource:k=>Eo(k,h,e.dims.length,o.length,a,i,d,e.dataType===10?-65504:-1e5,_,v,$,C)}},mh=(t,e)=>{Kn(t.inputs),t.compute(Mo("MaxPool",t.inputs[0],!1,e))},gh=t=>{let e=t.storage_order,r=t.dilations,n=To(t);if(e!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let a={storageOrder:e,dilations:r,...n,cacheKey:""};return{...a,cacheKey:dh(a)}},yh=t=>{let e=t.format;return{format:e,...Ao,cacheKey:e}},_h=(t,e)=>{Kn(t.inputs),t.compute(Mo("GlobalMaxPool",t.inputs[0],!0,e))}}),wh,vh,bh,Aw=le(()=>{Yt(),Oe(),Re(),wh=(t,e,r)=>{let n=t===e,a=te&&r>0;if(n||a||o)throw new Error("Range these inputs' contents are invalid.")},vh=(t,e,r,n)=>{let a=Math.abs(Math.ceil((e-t)/r)),o=[a],i=a,d=[{type:12,data:i},{type:n,data:t},{type:n,data:r},...Ce(o)],h=m=>{let c=$e("output",n,o.length),_=c.type.value,v=[{name:"outputSize",type:"u32"},{name:"start",type:_},{name:"delta",type:_}];return` ${m.registerUniforms(v).declareVariables(c)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${_}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},bh=t=>{let e=0,r=0,n=0;t.inputs[0].dataType===6?(e=t.inputs[0].getInt32Array()[0],r=t.inputs[1].getInt32Array()[0],n=t.inputs[2].getInt32Array()[0]):t.inputs[0].dataType===1&&(e=t.inputs[0].getFloat32Array()[0],r=t.inputs[1].getFloat32Array()[0],n=t.inputs[2].getFloat32Array()[0]),He.webgpu.validateInputContent&&wh(e,r,n),t.compute(vh(e,r,n,t.inputs[0].dataType),{inputs:[]})}}),$h,xh,Ch,Sh,Eh,kh,Th,Ih,Ah,Mh,Oh,Oo,zh,Ph,jh,Rh,Bh,Dh,Nh,Mw=le(()=>{Oe(),Be(),ft(),Re(),$h=(t,e)=>{if(t.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),t.length>0){if(e.mode==="linear"){if(!(t.length===2||t.length===3||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1||t.length===5&&t[0]===1&&t[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(e.mode==="cubic"&&!(t.length===2||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},xh=(t,e,r)=>{e.every(a=>a>=0&&a{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return e.forEach((a,o)=>n[a]=t[o]),n},Ch=(t,e,r,n,a,o)=>{let[i,d,h]=r>10?[1,2,3]:[-1,t.length>1?1:-1,-1],m=t[0].dims.length;if(i>0&&t.length>i&&t[i].dims.length>0)t[i].getFloat32Array().forEach(c=>o.push(c));else if(e.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&t.length>d&&t[d].dims.length>0){if(t[d].getFloat32Array().forEach(c=>n.push(c)),n.length!==0&&n.length!==m&&r>=18&&n.length!==e.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");$h(n,e),e.axes.length>0&&xh(n,e.axes,m).forEach((c,_)=>n[_]=c)}if(h>0&&t.length>h&&(t[h].getBigInt64Array().forEach(c=>a.push(Number(c))),a.length!==m||r>=18&&a.length===e.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(e.axes.length>0){if(n.length!==e.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(a.length!==e.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof a<"u"&&n.length>0&&a.length>m)throw new Error("Resize requires only of scales or sizes to be specified")},Sh=(t,e)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${e} { `+(()=>{switch(t){case"asymmetric":return`return ${e}(xResized) / ${e}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${e}(xResized) + 0.5) / ${e}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${e}(xResized) + 0.5) / ${e}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${e}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${e}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${e}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${e}(roiStart) * ${e}(lengthOriginal - 1) + (${e}(xResized) * ${e}(roiEnd - roiStart) * ${e}(lengthOriginal - 1)) / ${e}(lengthResized - 1); } else { return 0.5 * ${e}(roiStart + roiEnd) * ${e}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${e}xScale * ${e}(lengthResized); const adjustment = ${e}(lengthResized) / outputWidth; const center = ${e}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;case"half_pixel":return`return ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${t} is not supported`)}})()+"}",Eh=(t,e,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(t){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(e<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${t} is not supported`)}})()+"}",kh=(t,e,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),a=t.length===0?n:t.slice();return e.length>0?(e.forEach((o,i)=>{n[o]=a[i],n[i+r]=a[e.length+i]}),n):a},Th=(t,e,r,n)=>{let a=[];if(r.length>0)if(n.length>0){if(t.forEach(o=>a.push(o)),Math.max(...n)>t.length)throw new Error("axes is out of bound");n.forEach((o,i)=>a[o]=r[i])}else r.forEach(o=>a.push(o));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");a=t.map((o,i)=>Math.round(o*e[i]))}return a},Ih=(t,e,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(o=>e[o]),Number.MAX_VALUE):Math.min(...e,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(o=>e[o]),Number.MIN_VALUE):Math.max(...e,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();e.fill(1,0,e.length);let a=t.slice();return r.axes.length>0?(r.axes.forEach(o=>e[o]=n),r.axes.forEach(o=>a[o]=Math.round(t[o]*e[o]))):(e.fill(n,0,e.length),a.forEach((o,i)=>a[i]=Math.round(o*e[i]))),a},Ah=(t,e,r,n,a)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> array<${t.type.value}, ${r.length}> { var original_indices: array<${t.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var scale = ${ze("uniforms.scales","i",n)}; var roi_low = ${ze("uniforms.roi","i",a)}; var roi_hi = ${ze("uniforms.roi",`i + ${e.length}`,a)}; if (scale == 1.0) { original_indices[i] = ${t.type.value}(output_index); } else { var input_shape_i = ${ze("uniforms.input_shape","i",e.length)}; var output_shape_i = ${ze("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; }`,Mh=(t,e,r,n,a,o,i)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> ${t.type.indices} { var input_indices: ${t.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${ze("uniforms.scales","i",a)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${ze("uniforms.roi","i",o)}; var roi_hi = ${ze("uniforms.roi",`i + ${r.length}`,o)}; var input_shape_i = ${ze("uniforms.input_shape","i",r.length)}; var output_shape_i = ${ze("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${i} || (original_idx >= 0 && original_idx < ${e.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${e.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${t.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,Oh=(t,e)=>` fn checkInputIndices(input_indices: ${t.type.indices}) -> bool { for (var i:u32 = 0; i < ${e.length}; i++) { var input_index = ${t.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${ze("uniforms.input_shape","i",e.length)}) { return false; } } return true; }`,Oo=(t,e,r,n)=>t.rank>n?` ${t.indicesSet("input_indices",e,"channel")}; ${t.indicesSet("input_indices",r,"batch")}; `:"",zh=(t,e,r,n,a)=>{let[o,i,d,h]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=t.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} { var input_indices: ${t.type.indices}; ${t.indicesSet("input_indices",i,`max(0, min(row, ${r[i]} - 1))`)}; ${t.indicesSet("input_indices",d,`max(0, min(col, ${r[d]} - 1))`)}; ${Oo(t,h,o,2)} return ${t.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${e.type.indices}) -> ${m} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${m} = originalIndices[${i}]; var col:${m} = originalIndices[${d}]; ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[d]} - 1)) { return ${a}; }`:""}; row = max(0, min(row, ${r[i]} - 1)); col = max(0, min(col, ${r[d]} - 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[${h}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${o}])`:"0"}; var x11: ${m} = getInputValue(batch, channel, row1, col1); var x12: ${m} = getInputValue(batch, channel, row1, col2); var x21: ${m} = getInputValue(batch, channel, row2, col1); var x22: ${m} = getInputValue(batch, channel, row2, col2); var dx1: ${m} = abs(row - ${m}(row1)); var dx2: ${m} = abs(${m}(row2) - row); var dy1: ${m} = abs(col - ${m}(col1)); var dy2: ${m} = abs(${m}(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); }`},Ph=(t,e,r,n,a,o,i,d,h,m)=>{let c=r.length===2,[_,v]=c?[0,1]:[2,3],$=t.type.value,C=k=>{let M=k===_?"row":"col";return` fn ${M}CubicInterpolation(input_indices: ${t.type.indices}, output_indices: ${e.type.indices}) -> ${$} { var output_index = ${e.indicesGet("output_indices",k)}; var originalIdx: ${$} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[k]}, ${n[k]}, ${r[k]}, ${o[k]}, ${o[k]} + ${r.length}); var fractOriginalIdx: ${$} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${d} && (originalIdx < 0 || originalIdx > (${r[k]} - 1))) { return ${h}; } var data: array<${$}, 4> = array<${$}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${M}: ${$} = originalIdx + ${$}(i); if (${M} < 0 || ${M} >= ${r[k]}) { ${m?`coefs[i + 1] = 0.0; continue;`:d?`return ${h};`:`${M} = max(0, min(${M}, ${r[k]} - 1));`}; } var input_indices_copy: ${t.type.indices} = input_indices; ${t.indicesSet("input_indices_copy",k,`u32(${M})`)}; data[i + 1] = ${k===_?t.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${C(_)}; ${C(v)}; fn getCubicInterpolationCoefs(s: ${$}) -> array<${$}, 4> { var absS = abs(s); var coeffs: array<${$}, 4> = array<${$}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${$} = 1.0 - absS; var twoMinusAbsS: ${$} = 2.0 - absS; var onePlusAbsS: ${$} = 1.0 + absS; coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; return coeffs; } fn cubicInterpolation1D(x: array<${$}, 4>, coefs: array<${$}, 4>) -> ${$} { var coefsSum: ${$} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${e.type.indices}) -> ${$} { var input_indices: ${t.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},jh=(t,e,r,n,a)=>{let[o,i,d,h,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],c=t.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${c} { var input_indices: ${t.type.indices}; ${t.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; ${t.indicesSet("input_indices",d,`max(0, min(height, ${r[d]} - 1))`)}; ${t.indicesSet("input_indices",h,`max(0, min(width, ${r[h]} - 1))`)}; ${Oo(t,m,o,3)} return ${t.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${c} = originalIndices[${i}]; var height:${c} = originalIndices[${d}]; var width:${c} = originalIndices[${h}]; ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[h]} - 1)) { return ${a}; }`:""}; depth = max(0, min(depth, ${r[i]} - 1)); height = max(0, min(height, ${r[d]} - 1)); width = max(0, min(width, ${r[h]} - 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[${m}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${o}])`:"0"}; var x111: ${c} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${c} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${c} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${c} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${c} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${c} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${c} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${c} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${c} = abs(depth - ${c}(depth1)); var dx2: ${c} = abs(${c}(depth2) - depth); var dy1: ${c} = abs(height - ${c}(height1)); var dy2: ${c} = abs(${c}(height2) - height); var dz1: ${c} = abs(width - ${c}(width1)); var dz2: ${c} = abs(${c}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},Rh=(t,e,r,n,a,o)=>{let i=t.dims,d=kh(o,e.axes,i.length),h=Th(i,n,a,e.axes),m=n.slice();n.length===0&&(m=i.map((I,j)=>I===0?1:h[j]/I),e.keepAspectRatioPolicy!=="stretch"&&(h=Ih(i,m,e)));let c=$e("output",t.dataType,h.length),_=oe("input",t.dataType,i.length),v=se.size(h),$=i.length===h.length&&i.every((I,j)=>I===h[j]),C=e.coordinateTransformMode==="tf_crop_and_resize",k=e.extrapolationValue,M=_.type.value,z=I=>` ${$?"":` ${Sh(e.coordinateTransformMode,M)}; ${(()=>{switch(e.mode){case"nearest":return` ${Oh(_,i)}; ${Eh(e.nearestMode,r,M)}; ${Mh(_,c,i,h,m.length,d.length,C)}; `;case"linear":return` ${Ah(c,i,h,m.length,d.length)}; ${(()=>{if(i.length===2||i.length===4)return`${zh(_,c,i,C,k)}`;if(i.length===3||i.length===5)return`${jh(_,c,i,C,k)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(i.length===2||i.length===4)return`${Ph(_,c,i,h,m,d,e.cubicCoeffA,C,e.extrapolationValue,e.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${I.registerUniform("output_size","u32").registerUniform("scales","f32",m.length).registerUniform("roi","f32",d.length).declareVariables(_,c)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${$?"output[global_idx] = input[global_idx];":` let output_indices = ${c.offsetToIndices("global_idx")}; var input_indices: ${_.type.indices}; ${(()=>{switch(e.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${_.getByIndices("input_indices")}; } else { output[global_idx] = ${e.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${e.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${e.cacheKey}|${r}|${m.length>0?m:""}|${a.length>0?a:""}|${d.length>0?d:""}|${$}|${i}`,inputDependencies:["rank"]},getShaderSource:z,getRunData:()=>({outputs:[{dims:h,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},{type:1,data:m},{type:1,data:d},...Ce(i,h)]})}},Bh=t=>{let e=t.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},Dh=(t,e)=>{let r=[],n=[],a=[],o=Bh(t);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ch(t.inputs,e,o,r,n,a),t.compute(Rh(t.inputs[0],e,o,r,n,a),{inputs:[0]})},Nh=t=>{let e=t.antialias,r=t.axes,n=t.coordinateTransformMode,a=t.cubicCoeffA,o=t.excludeOutside!==0,i=t.extrapolationValue,d=t.keepAspectRatioPolicy,h=t.mode,m=t.nearestMode===""?"simple":t.nearestMode;return Ze({antialias:e,axes:r,coordinateTransformMode:n,cubicCoeffA:a,excludeOutside:o,extrapolationValue:i,keepAspectRatioPolicy:d,mode:h,nearestMode:m})}}),Lh,Uh,Fh,Ow=le(()=>{Oe(),Be(),ft(),Re(),Lh=(t,e)=>{let[r,n,a,o]=t,{numHeads:i,rotaryEmbeddingDim:d}=e;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!se.areEqual(n.dims,[])&&!se.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!se.areEqual(a.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let h=r.dims[0],m=r.dims[r.dims.length-2],c=a.dims[0],_=se.sizeFromDimension(r.dims,1)/m,v=d===0?a.dims[1]*2:_/i;if(d>v)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(h!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(m!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(v/2!==a.dims[1]&&d/2!==a.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${a.dims[1]}`);if(m>c)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Uh=(t,e)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:a,scale:o}=e,i=t[0].dims[0],d=se.sizeFromDimension(t[0].dims,1),h=t[0].dims[t[0].dims.length-2],m=d/h,c=t[2].dims[1],_=a===0?c*2:m/n,v=new Array(i,h,m/_,_-c),$=se.computeStrides(v),C=[{type:1,data:o},{type:12,data:v},{type:12,data:$},...t[0].dims.length===3?new Array({type:12,data:[d,m,_,1]}):[],...t[0].dims.length===4?new Array({type:12,data:[d,_,h*_,1]}):[],...Ce(t[0].dims,t[1].dims,t[2].dims,t[3].dims,t[0].dims)],k=M=>{let z=oe("input",t[0].dataType,t[0].dims.length),I=oe("position_ids",t[1].dataType,t[1].dims.length),j=oe("cos_cache",t[2].dataType,t[2].dims.length),R=oe("sin_cache",t[3].dataType,t[3].dims.length),L=$e("output",t[0].dataType,t[0].dims.length);return M.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:v.length},{name:"global_strides",type:"u32",length:$.length},{name:"input_output_strides",type:"u32",length:$.length}]),` ${M.declareVariables(z,I,j,R,L)} ${M.mainStart(fn)} let half_rotary_emb_dim = uniforms.${j.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${M.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${I.broadcastedIndicesToOffset("bsnh.xy",$e("",I.type.tensor,2))}; let position_id = u32(${I.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${z.getByOffset("i")} * ${j.get("position_id","bsnh[3]")} - ${z.getByOffset("j")} * ${R.get("position_id","bsnh[3]")}; ${L.setByOffset("i","re")} let im = ${z.getByOffset("i")} * ${R.get("position_id","bsnh[3]")} + ${z.getByOffset("j")} * ${j.get("position_id","bsnh[3]")}; ${L.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${L.setByOffset("k",z.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:Ze({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:k,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(se.size(v)/fn)},programUniforms:C})}},Fh=(t,e)=>{Lh(t.inputs,e),t.compute(Uh(t.inputs,e))}}),Wh,Gh,Vh,zw=le(()=>{Oe(),Be(),Re(),Wh=t=>{if(!t||t.length<3)throw new Error("layerNorm requires at least 3 inputs.");let e=t[0],r=t[1],n=t[2];if(e.dataType!==r.dataType||e.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(e.dims.length!==3&&e.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let a=e.dims[e.dims.length-1],o=e.dims[e.dims.length-2];if(r.dims[r.dims.length-1]!==a)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==a)throw new Error("Gamma must have the same hidden size as input");if(t.length>3){let i=t[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==a)throw new Error("Beta must have the same hidden size as input")}if(t.length>4){let i=t[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==a)throw new Error("Bias must have the same hidden size as input")}},Gh=(t,e,r,n)=>{let a=e.simplified,o=t[0].dims,i=se.size(o),d=o,h=i,m=o.slice(-1)[0],c=n?o.slice(0,-1).concat(1):[],_=!a&&t.length>3,v=t.length>4,$=n&&r>1,C=n&&r>2,k=r>3,M=dt(m),z=[{type:12,data:h},{type:12,data:M},{type:12,data:m},{type:1,data:e.epsilon}],I=R=>{let L=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Y=[oe("x",t[0].dataType,t[0].dims,M),oe("skip",t[1].dataType,t[1].dims,M),oe("gamma",t[2].dataType,t[2].dims,M)];_&&Y.push(oe("beta",t[3].dataType,t[3].dims,M)),v&&Y.push(oe("bias",t[4].dataType,t[4].dims,M)),Y.push($e("output",t[0].dataType,d,M)),$&&Y.push($e("mean_output",1,c)),C&&Y.push($e("inv_std_output",1,c)),k&&Y.push($e("input_skip_bias_sum",t[0].dataType,d,M));let Q=mt(t[0].dataType);return` ${R.registerUniforms(L).declareVariables(...Y)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")} let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; let offset = global_idx * hidden_size_vectorized; var sum = ${gr("f32",M)}; var squareSum = ${gr("f32",M)}; for (var i: u32 = 0; i < hidden_size_vectorized; i++) { let skip_value = skip[offset + i]; let bias_value = ${v?"bias[i]":Q+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${k?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${mn(Q,M,"value")}; sum += f32_value; squareSum += f32_value * f32_value; } let mean = ${kr("sum",M)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${kr("squareSum",M)} / f32(uniforms.hidden_size) ${a?"":"- mean * mean"} + uniforms.epsilon); ${$?"mean_output[global_idx] = mean;":""} ${C?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < hidden_size_vectorized; i++) { output[offset + i] = (output[offset + i] ${a?"":`- ${Q}(mean)`}) * ${Q}(inv_std_dev) * gamma[i] ${_?"+ beta[i]":""}; } }`},j=[{dims:d,dataType:t[0].dataType}];return r>1&&j.push({dims:c,dataType:1}),r>2&&j.push({dims:c,dataType:1}),r>3&&j.push({dims:o,dataType:t[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${M};${$};${C};${k}`,inputDependencies:t.map((R,L)=>"type")},getShaderSource:I,getRunData:()=>({outputs:j,dispatchGroup:{x:Math.ceil(h/m/64)},programUniforms:z})}},Vh=(t,e)=>{Wh(t.inputs);let r=[0];t.outputCount>1&&r.push(-3),t.outputCount>2&&r.push(-3),t.outputCount>3&&r.push(3),t.compute(Gh(t.inputs,e,t.outputCount,!1),{outputs:r})}}),Hh,Yn,qh,zo,Kh,Yh,Qh,Xh,Pw=le(()=>{Oe(),Be(),ft(),Re(),Hh=(t,e)=>{if(!t||t.length<1)throw new Error("too few inputs");if(e.axes.length!==0){if(e.axes.length!==e.starts.length||e.axes.length!==e.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(e.starts.length!==e.ends.length)throw new Error("starts and ends must have the same length");t.slice(1).forEach((r,n)=>{if(t[n+1].dataType!==6&&t[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Yn=(t,e)=>{let r=[];if(t.length>e)if(t[e].dataType===7)t[e].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(t[e].dataType===6)t[e].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${e} must be an array of int32 or int64`);return r},qh=(t,e)=>{if(t.length>1){let r=Yn(t,1),n=Yn(t,2),a=Yn(t,3);return a.length===0&&(a=[...Array(t[0].dims.length).keys()]),Ze({starts:r,ends:n,axes:a})}else return e},zo=(t,e,r,n,a)=>{let o=t;return t<0&&(o+=r[n[e]]),a[e]<0?Math.max(0,Math.min(o,r[n[e]]-1)):Math.max(0,Math.min(o,r[n[e]]))},Kh=(t,e,r)=>`fn calculateInputIndices(output_indices: ${e.type.indices}) -> ${t.type.indices} { var input_indices: ${t.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${ze("uniforms.input_shape","i",r.length)}; let steps_i = ${ze("uniforms.steps","i",r.length)}; let signs_i = ${ze("uniforms.signs","i",r.length)}; let starts_i = ${ze("uniforms.starts","i",r.length)}; var output_index = ${e.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${t.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,Yh=(t,e)=>{let r=t[0].dims,n=se.size(r),a=e.axes.length>0?se.normalizeAxes(e.axes,r.length):[...Array(r.length).keys()],o=Yn(t,4);o.forEach(z=>z!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(a.length).fill(1));let i=e.starts.map((z,I)=>zo(z,I,r,a,o)),d=e.ends.map((z,I)=>zo(z,I,r,a,o));if(a.length!==i.length||a.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(a.length!==r.length)for(let z=0;zMath.sign(z));o.forEach((z,I,j)=>{if(z<0){let R=(d[I]-i[I])/z,L=i[I],Y=L+R*o[I];i[I]=Y,d[I]=L,j[I]=-z}});let m=r.slice(0);a.forEach((z,I)=>{m[z]=Math.ceil((d[z]-i[z])/o[z])});let c={dims:m,dataType:t[0].dataType},_=$e("output",t[0].dataType,m.length),v=oe("input",t[0].dataType,t[0].dims.length),$=se.size(m),C=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:h.length},{name:"steps",type:"u32",length:o.length}],k=[{type:12,data:$},{type:12,data:i},{type:6,data:h},{type:12,data:o},...Ce(t[0].dims,m)],M=z=>` ${z.registerUniforms(C).declareVariables(v,_)} ${Kh(v,_,r)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${_.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${_.setByOffset("global_idx",v.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${h.length}_${i.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:[c],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:k})}},Qh=(t,e)=>{Hh(t.inputs,e);let r=qh(t.inputs,e);t.compute(Yh(t.inputs,r),{inputs:[0]})},Xh=t=>{let e=t.starts,r=t.ends,n=t.axes;return Ze({starts:e,ends:r,axes:n})}}),Zh,Jh,ef,tf,jw=le(()=>{Oe(),Be(),ft(),Re(),Zh=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},Jh=(t,e)=>{let r=t.dims,n=se.size(r),a=64,o=e.axis;if(o<0&&(o=r.length+o),oz===4?`max(max(${M}.x, ${M}.y), max(${M}.z, ${M}.w))`:z===2?`max(${M}.x, ${M}.y)`:z===3?`max(max(${M}.x, ${M}.y), ${M}.z)`:M,_=oe("x",t.dataType,t.dims,h),v=$e("result",t.dataType,t.dims,h),$=_.type.value,C=mt(t.dataType)==="f32"?`var threadMax = ${$}(-3.402823e+38f);`:`var threadMax = ${$}(-65504.0h);`,k=M=>` var rowMaxShared : ${$}; var rowSumShared : ${$}; var threadShared : array<${$}, ${a}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${$} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${$}) { let index = row * row_stride + col; result[index] = value; } ${M.registerUniform("packedCols","i32").declareVariables(_,v)} ${M.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${a}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${C} 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 = ${$}(${c("threadShared[0]",h)}); } workgroupBarrier(); // find the rows sum var threadSum = ${$}(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 = ${$}(${kr("threadShared[0]",h)}); } 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:`${h}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:t.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:m}]}),getShaderSource:k}},ef=(t,e)=>{Zh(t.inputs),t.compute(Jh(t.inputs[0],e))},tf=t=>Ze({axis:t.axis})}),rf,nf,af,sf,of,lf,uf,Rw=le(()=>{Oe(),Be(),ft(),Re(),rf=t=>{if(!t||t.length<1)throw new Error("too few inputs")},nf=(t,e)=>{let r=[],n=e.numOutputs;return t[1].dims[0]>0&&(t[1].getBigInt64Array().forEach(a=>r.push(Number(a))),n=r.length),Ze({numOutputs:n,axis:e.axis,splitSizes:r})},af=t=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${t}u; i += 1u ) { if (index < ${ze("uniforms.size_in_split_axis","i",t)}) { return i; } } return ${t}u; }`,sf=t=>{let e=t.length,r=[];for(let n=0;n{let r=t[0].dims,n=se.size(r),a=t[0].dataType,o=se.normalizeAxis(e.axis,r.length),i=new Array(e.numOutputs),d=oe("input",a,r.length),h=new Array(e.numOutputs),m=[],c=[],_=0,v=[{type:12,data:n}];for(let C=0;C` ${C.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",h.length).declareVariables(d,...i)} ${af(h.length)} ${sf(i)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${d.offsetToIndices("global_idx")}; var index = ${d.indicesGet("indices",o)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${ze("uniforms.size_in_split_axis","output_number - 1u",h.length)}; ${d.indicesSet("indices",o,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:e.cacheKey,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:m,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:v})}},lf=(t,e)=>{rf(t.inputs);let r=t.inputs.length===1?e:nf(t.inputs,e);t.compute(of(t.inputs,r),{inputs:[0]})},uf=t=>{let e=t.axis,r=t.splitSizes,n=t.numOutputs<0?r.length:t.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Ze({axis:e,numOutputs:n,splitSizes:r})}}),Po,df,cf,pf,hf,Bw=le(()=>{Oe(),Be(),Re(),Po=t=>Array.from(t.getBigInt64Array(),Number),df=t=>{if(!t||t.length!==2)throw new Error("Tile requires 2 inputs.");if(t[0].dataType!==1&&t[0].dataType!==6&&t[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(t[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(t[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Po(t[1]).length!==t[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},cf=(t,e)=>{let r=[];for(let n=0;n{let e=t[0].dims,r=Po(t[1]),n=cf(e,r),a=se.size(n),o=t[0].dataType,i=oe("input",o,e.length),d=$e("output",o,n.length),h=m=>` const inputShape = ${i.indices(...e)}; ${m.registerUniform("output_size","u32").declareVariables(i,d)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${d.offsetToIndices("global_idx")}; var input_indices: ${i.type.indices}; for (var i = 0; i < ${e.length}; i++) { let input_dim_i = ${i.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; ${i.indicesSet("input_indices","i","input_dim_value")} } ${d.setByOffset("global_idx",i.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...Ce(t[0].dims,n)]}),getShaderSource:h}},hf=t=>{df(t.inputs),t.compute(pf(t.inputs),{inputs:[0]})}}),ff,mf,gf,Dw=le(()=>{Oe(),Be(),Re(),ff=(t,e,r,n,a)=>{let o=$e("output_data",a,r.length,4),i=oe("a_data",e[1].dataType,e[1].dims.length,4),d=oe("b_data",e[2].dataType,e[2].dims.length,4),h=oe("c_data",e[0].dataType,e[0].dims.length,4),m,c=(_,v,$)=>`select(${v}, ${_}, ${$})`;if(!n)m=o.setByOffset("global_idx",c(i.getByOffset("global_idx"),d.getByOffset("global_idx"),h.getByOffset("global_idx")));else{let _=(v,$,C="")=>{let k=`a_data[index_a${$}][component_a${$}]`,M=`b_data[index_b${$}][component_b${$}]`,z=`bool(c_data[index_c${$}] & (0xffu << (component_c${$} * 8)))`;return` let output_indices${$} = ${o.offsetToIndices(`global_idx * 4u + ${$}u`)}; let offset_a${$} = ${i.broadcastedIndicesToOffset(`output_indices${$}`,o)}; let offset_b${$} = ${d.broadcastedIndicesToOffset(`output_indices${$}`,o)}; let offset_c${$} = ${h.broadcastedIndicesToOffset(`output_indices${$}`,o)}; let index_a${$} = offset_a${$} / 4u; let index_b${$} = offset_b${$} / 4u; let index_c${$} = offset_c${$} / 4u; let component_a${$} = offset_a${$} % 4u; let component_b${$} = offset_b${$} % 4u; let component_c${$} = offset_c${$} % 4u; ${v}[${$}] = ${C}(${c(k,M,z)}); `};a===9?m=` var data = vec4(0); ${_("data",0,"u32")} ${_("data",1,"u32")} ${_("data",2,"u32")} ${_("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:m=` ${_("output_data[global_idx]",0)} ${_("output_data[global_idx]",1)} ${_("output_data[global_idx]",2)} ${_("output_data[global_idx]",3)} `}return` ${t.registerUniform("vec_size","u32").declareVariables(h,i,d,o)} ${t.mainStart()} ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${m} }`},mf=t=>{let e=t[1].dims,r=t[2].dims,n=t[0].dims,a=t[1].dataType,o=!(se.areEqual(e,r)&&se.areEqual(r,n)),i=e,d=se.size(e);if(o){let m=hn.calcShape(hn.calcShape(e,r,!1),n,!1);if(!m)throw new Error("Can't perform where op on the given tensors");i=m,d=se.size(i)}let h=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:m=>ff(m,t,i,o,a),getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:h},...Ce(n,e,r,i)]})}},gf=t=>{t.compute(mf(t.inputs))}}),yf,Nw=le(()=>{sw(),Td(),ow(),lw(),uw(),dw(),bd(),qc(),mw(),gw(),yw(),_w(),ww(),vw(),bw(),$w(),xw(),Cw(),Sw(),Wc(),Ew(),kw(),Tw(),Iw(),Aw(),Js(),Mw(),Ow(),zw(),Pw(),jw(),Rw(),Bw(),Hn(),ao(),Dw(),yf=new Map([["Abs",[Bd]],["Acos",[Dd]],["Acosh",[Nd]],["Add",[xc]],["ArgMax",[md,to]],["ArgMin",[fd,to]],["Asin",[Ld]],["Asinh",[Ud]],["Atan",[Fd]],["Atanh",[Wd]],["Attention",[kd]],["AveragePool",[ph,ch]],["BatchNormalization",[Od]],["BiasAdd",[jd]],["BiasSplitGelu",[vc]],["Cast",[Vd,Gd]],["Ceil",[Kd]],["Clip",[qd]],["Concat",[wd,vd]],["Conv",[yo,go]],["ConvTranspose",[ap,ep]],["Cos",[Yd]],["Cosh",[Qd]],["CumSum",[op,lp]],["DepthToSpace",[pp,hp]],["Div",[Cc]],["Einsum",[wp,vp]],["Elu",[Xd,wa]],["Equal",[Sc]],["Erf",[Zd]],["Exp",[Jd]],["Expand",[Cp]],["FastGelu",[Ep]],["Floor",[ec]],["FusedConv",[yo,go]],["Gather",[Ap,Ip]],["GatherElements",[Pp,zp]],["Gelu",[tc]],["Gemm",[Dp,Bp]],["GlobalAveragePool",[fh,hh]],["GlobalMaxPool",[_h,yh]],["Greater",[Ic]],["GreaterOrEqual",[Mc]],["HardSigmoid",[uc,lc]],["InstanceNormalization",[Fp]],["LayerNormalization",[Vp]],["LeakyRelu",[rc,wa]],["Less",[Ac]],["LessOrEqual",[Oc]],["Log",[yc]],["MatMul",[Fc]],["MatMulNBits",[Kp,Yp]],["MaxPool",[mh,gh]],["Mul",[Ec]],["MultiHeadAttention",[Jp,Xp]],["Neg",[ic]],["Not",[nc]],["Pad",[lh]],["Pow",[kc]],["Range",[bh]],["Reciprocal",[ac]],["ReduceMin",[ud]],["ReduceMean",[id]],["ReduceMax",[ld]],["ReduceSum",[cd]],["ReduceProd",[dd]],["ReduceL1",[ad]],["ReduceL2",[sd]],["ReduceLogSum",[hd]],["ReduceLogSumExp",[od]],["ReduceSumSquare",[pd]],["Relu",[sc]],["Resize",[Dh,Nh]],["RotaryEmbedding",[Fh]],["Sigmoid",[oc]],["Sin",[dc]],["Sinh",[cc]],["Slice",[Qh,Xh]],["SkipLayerNormalization",[Vh]],["Split",[lf,uf]],["Sqrt",[pc]],["Softmax",[ef,tf]],["Sub",[Tc]],["Tan",[hc]],["Tanh",[fc]],["ThresholdedRelu",[gc,wa]],["Tile",[hf]],["Transpose",[Su,Eu]],["Where",[gf]]])}),_f,Lw=le(()=>{Yt(),Ur(),Re(),_f=class{constructor(t){this.backend=t,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,r,n,a){Kt(t.programInfo.name);let o=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let m of e)d.push({binding:d.length,resource:{buffer:m.buffer}});for(let m of r)d.push({binding:d.length,resource:{buffer:m.buffer}});a&&d.push({binding:d.length,resource:a});let h=o.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:h,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}i.setPipeline(t.computePipeline),i.setBindGroup(0,h),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ut(t.programInfo.name)}dispose(){}build(t,e){Kt(t.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let a=bu(e,this.backend.device.limits),o=t.getShaderSource(a),i=`${n.join(` `)} ${a.additionalImplementations} ${o}`,d=r.createShaderModule({code:i,label:t.name});it("verbose",()=>`[WebGPU] ${t.name} shader code: ${i}`);let h=r.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:t.name});return Ut(t.name),{programInfo:t,computePipeline:h,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let e=typeof t=="number"?t:t.x,r=typeof t=="number"?1:t.y||1,n=typeof t=="number"?1:t.z||1,a=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=a&&r<=a&&n<=a)return[e,r,n];let o=e*r*n,i=Math.ceil(Math.sqrt(o));if(i>a){if(i=Math.ceil(Math.cbrt(o)),i>a)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),wf,vf,bf,$f,Uw=le(()=>{Yt(),Oe(),Ur(),nw(),iw(),Nw(),Lw(),wf=(t,e)=>{if(e.length!==t.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${t.length}.`);let r=[];for(let n=0;n{var a,o;let n=t.name;return(a=t.shaderCache)!=null&&a.hint&&(n+="["+t.shaderCache.hint+"]"),n+=":"+r+`:${wf(e,((o=t.shaderCache)==null?void 0:o.inputDependencies)??new Array(e.length).fill("dims"))}`,n},bf=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},$f=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,e){this.env=t;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};e.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):e.features.has("timestamp-query")&&r.push("timestamp-query"),e.features.has("shader-f16")&&r.push("shader-f16"),this.device=await e.requestDevice(n),this.adapterInfo=new bf(await e.requestAdapterInfo()),this.gpuDataManager=gu(this),this.programManager=new _f(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,du(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;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(()=>{var n;let e=new BigUint64Array(t.getMappedRange()),r=this.pendingQueries.get(t);for(let a=0;a"u"&&(this.queryTimeBase=$);let k=Number($-this.queryTimeBase),M=Number(C-this.queryTimeBase);if(!Number.isSafeInteger(k)||!Number.isSafeInteger(M))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:_.map(z=>({dims:z.dims,dataType:Lr(z.dataType)})),outputsMetadata:v.map(z=>({dims:z.dims,dataType:Lr(z.dataType)})),kernelId:i,kernelType:h,kernelName:m,programName:c,startTime:k,endTime:M});else{let z="";_.forEach((j,R)=>{z+=`input[${R}]: [${j.dims}] | ${Lr(j.dataType)}, `});let I="";v.forEach((j,R)=>{I+=`output[${R}]: [${j.dims}] | ${Lr(j.dataType)}, `}),console.log(`[profiling] kernel "${i}|${h}|${m}|${c}" ${z}${I}execution time: ${M-k} ns`)}Un("GPU",`${c}::${$}::${C}`)}t.unmap(),this.pendingQueries.delete(t)}),Ut()}run(t,e,r,n,a,o){Kt(t.name);let i=[];for(let I=0;Ij):r;if(c.length!==d.length)throw new Error(`Output size ${c.length} must be equal to ${d.length}.`);let _=[],v=[];for(let I=0;I=o)throw new Error(`Invalid output index: ${c[I]}`);if(c[I]===-3)continue;let j=c[I]===-1,R=c[I]===-2,L=j||R?a(d[I].dataType,d[I].dims):n(c[I],d[I].dataType,d[I].dims);if(_.push(L),L.data===0)continue;let Y=this.gpuDataManager.get(L.data);if(!Y)throw new Error(`no GPU data for output: ${L.data}`);if(j&&this.temporaryData.push(Y),R){let Q=this.kernelPersistentData.get(this.currentKernelId);Q||(Q=[],this.kernelPersistentData.set(this.currentKernelId,Q)),Q.push(Y)}v.push(Y)}if(i.length!==e.length||v.length!==_.length){if(v.length===0)return Ut(t.name),_;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let $;if(m){let I=0,j=[];m.forEach(Q=>{let ie=typeof Q.data=="number"?[Q.data]:Q.data;if(ie.length===0)return;let pe=Q.type===10?2:4,ce,Se;Q.type===10?(Se=ie.length>4?16:ie.length>2?8:ie.length*pe,ce=ie.length>4?16:pe*ie.length):(Se=ie.length<=2?ie.length*pe:16,ce=16),I=Math.ceil(I/Se)*Se,j.push(I);let fe=Q.type===10?8:4;I+=ie.length>4?Math.ceil(ie.length/fe)*ce:ie.length*pe});let R=16;I=Math.ceil(I/R)*R;let L=new ArrayBuffer(I);m.forEach((Q,ie)=>{let pe=j[ie],ce=typeof Q.data=="number"?[Q.data]:Q.data;if(Q.type===6)new Int32Array(L,pe,ce.length).set(ce);else if(Q.type===12)new Uint32Array(L,pe,ce.length).set(ce);else if(Q.type===10)new Uint16Array(L,pe,ce.length).set(ce);else if(Q.type===1)new Float32Array(L,pe,ce.length).set(ce);else throw new Error(`Unsupported uniform type: ${Lr(Q.type)}`)});let Y=this.gpuDataManager.create(I,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Y.buffer,0,L,0,I),this.gpuDataManager.release(Y.id),$={offset:0,size:I,buffer:Y.buffer}}let C=this.programManager.normalizeDispatchGroupSize(h),k=C[1]===1&&C[2]===1,M=vf(t,e,k),z=this.programManager.getArtifact(M);if(z||(z=this.programManager.build(t,C),this.programManager.setArtifact(M,z),it("info",()=>`[artifact] key: ${M}, programName: ${t.name}`)),m&&z.uniformVariablesInfo){if(m.length!==z.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${z.uniformVariablesInfo.length}, got ${m.length} in program "${z.programInfo.name}".`);for(let I=0;I`[ProgramManager] run "${t.name}" (key=${M}) with ${C[0]}x${C[1]}x${C[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let I={kernelId:this.currentKernelId,programName:z.programInfo.name,inputTensorViews:e,outputTensorViews:_};this.pendingKernels.push(I),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(I)}return this.programManager.run(z,i,v,C,$),Ut(t.name),_}upload(t,e){this.gpuDataManager.upload(t,e)}memcpy(t,e){this.gpuDataManager.memcpy(t,e)}async download(t,e){await this.gpuDataManager.download(t,e)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,e,r,n){let a=yf.get(t);if(!a)throw new Error(`kernel not implemented: ${t}`);let o={kernelType:t,kernelName:n,kernelEntry:a[0],attributes:[a[1],r]};this.kernels.set(e,o)}releaseKernel(t){let e=this.kernelPersistentData.get(t);if(e){for(let r of e)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,e,r){let n=this.kernels.get(t);if(!n)throw new Error(`kernel not created: ${t}`);let a=n.kernelType,o=n.kernelName,i=n.kernelEntry,d=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${a}] ${o}" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),it("info",()=>`[WebGPU] Start to run kernel "[${a}] ${o}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),i(e,d[1]),0}catch(m){return r.push(Promise.resolve(`[WebGPU] Kernel "[${a}] ${o}" failed. ${m}`)),1}finally{h&&r.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel "[${a}] ${o}": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,e,r,n){let a=this.sessionExternalDataMapping.get(t);a||(a=new Map,this.sessionExternalDataMapping.set(t,a));let o=a.get(e),i=this.gpuDataManager.registerExternalBuffer(r,n,o==null?void 0:o[1]);return a.set(e,[i,r]),i}unregisterBuffers(t){let e=this.sessionExternalDataMapping.get(t);e&&(e.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let e=this.gpuDataManager.get(t);if(!e)throw new Error(`no GPU data for buffer: ${t}`);return e.buffer}createDownloader(t,e,r){return async()=>{let n=await qs(this,t,e);return pu(n.buffer,r)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){var t;this.queryType="none",(((t=this.env.webgpu.profiling)==null?void 0:t.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){it("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){it("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){it("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),r=t.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}}),xf={};pn(xf,{init:()=>Sf});var Ta,Cf,Sf,Fw=le(()=>{Oe(),Uw(),Ur(),Be(),Ta=class m0{constructor(e,r,n,a){this.module=e,this.dataType=r,this.data=n,this.dims=a}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=se.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=se.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=se.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(se.size(e)!==se.size(this.dims))throw new Error("Invalid new shape");return new m0(this.module,this.dataType,this.data,e)}},Cf=class{constructor(t,e,r){this.module=t,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let n=t.HEAPU32,a=r>>>2;this.opKernelContext=n[a++];let o=n[a++];this.outputCount=n[a++],this.customDataOffset=n[a++],this.customDataSize=n[a++];let i=[];for(let d=0;dtypeof d=="number"?this.inputs[d]:d))??this.inputs,n=(e==null?void 0:e.outputs)??[],a=(d,h,m)=>new Ta(this.module,h,this.output(d,m),m),o=(d,h)=>{let m=Gn(d);if(!m)throw new Error(`Unsupported data type: ${d}`);let c=m*se.size(h),_=c>0?this.backend.gpuDataManager.create(c).id:0;return new Ta(this.module,d,_,h)};return this.backend.run(t,r,n,a,o,this.outputCount)}output(t,e){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+e.length)*4),a=n>>2;this.module.HEAPU32[a++]=e.length;for(let o=0;o{let a=e.jsepInit;if(!a)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(t==="webgpu"){let o=new $f;await o.initialize(r,n),a("webgpu",[o,i=>o.alloc(i),i=>o.free(i),(i,d,h,m=!1)=>{if(m)it("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${d}, size=${h}`),o.memcpy(i,d);else{it("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${d}, size=${h}`);let c=e.HEAPU8.subarray(i>>>0,(i>>>0)+h);o.upload(d,c)}},async(i,d,h)=>{it("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${d}, size=${h}`),await o.download(i,()=>e.HEAPU8.subarray(d>>>0,(d>>>0)+h))},(i,d,h)=>o.createKernel(i,d,h,e.UTF8ToString(e._JsepGetNodeName(d))),i=>o.releaseKernel(i),(i,d,h,m)=>{it("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${h}, kernel=${i}, contextDataOffset=${d}`);let c=new Cf(e,o,d);return o.computeKernel(i,c,m)},()=>o.captureBegin(),()=>o.captureEnd(),()=>o.replay()])}else a("webnn")}}),Ef,kf,Tf,Tr,If,jo,Af,Mf,Ro,Of,zf,Pf,Ww=le(()=>{tw(),rw(),Oe(),Wn(),Ns(),au(),Ef=(t,e)=>{ut()._OrtInit(t,e)!==0&&Xe("Can't initialize onnxruntime.")},kf=async t=>{Ef(t.wasm.numThreads,ua(t.logLevel))},Tf=async(t,e)=>{{let r=(Fw(),Sr(xf)).init;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=t.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let a=t.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let o=t.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:a,forceFallbackAdapter:o}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}if(!t.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",ut(),t,n)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",ut(),t)}}},Tr=new Map,If=t=>{let e=ut(),r=e.stackSave();try{let n=e.stackAlloc(8);return e._OrtGetInputOutputCount(t,n,n+4)!==0&&Xe("Can't get session input/output count."),[e.HEAP32[n/4],e.HEAP32[n/4+1]]}finally{e.stackRestore(r)}},jo=t=>{let e=ut(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Af=async(t,e)=>{var _,v;let r,n,a=ut();Array.isArray(t)?[r,n]=t:t.buffer===a.HEAPU8.buffer?[r,n]=[t.byteOffset,t.byteLength]:[r,n]=jo(t);let o=0,i=0,d=0,h=[],m=[],c=[];try{if([i,h]=iu(e),(e==null?void 0:e.externalData)&&a.mountExternalData){let R=[];for(let L of e.externalData){let Y=typeof L=="string"?L:L.path;R.push(da(typeof L=="string"?L:L.data).then(Q=>{a.mountExternalData(Y,Q)}))}await Promise.all(R)}o=await a._OrtCreateSession(r,n,i),o===0&&Xe("Can't create a session.");let[$,C]=If(o),k=!!(e!=null&&e.enableGraphCapture),M=[],z=[],I=[];for(let R=0;R<$;R++){let L=a._OrtGetInputName(o,R);L===0&&Xe("Can't get an input name."),m.push(L),M.push(a.UTF8ToString(L))}for(let R=0;RR==="gpu-buffer")&&(d=a._OrtCreateBinding(o),d===0&&Xe("Can't create IO binding."),j={handle:d,outputPreferredLocations:I,outputPreferredLocationsEncoded:I.map(R=>Ws(R))}),Tr.set(o,[o,m,c,j,k,!1]),[o,M,z]}catch($){throw m.forEach(C=>a._OrtFree(C)),c.forEach(C=>a._OrtFree(C)),d!==0&&a._OrtReleaseBinding(d),o!==0&&a._OrtReleaseSession(o),$}finally{a._free(r),i!==0&&a._OrtReleaseSessionOptions(i),h.forEach($=>a._free($)),(v=a.unmountExternalData)==null||v.call(a)}},Mf=t=>{var h;let e=ut(),r=Tr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[n,a,o,i,d]=r;i&&(d&&e._OrtClearBoundOutputs(i.handle),e._OrtReleaseBinding(i.handle)),(h=e.jsepOnReleaseSession)==null||h.call(e,t),a.forEach(m=>e._OrtFree(m)),o.forEach(m=>e._OrtFree(m)),e._OrtReleaseSession(n),Tr.delete(t)},Ro=(t,e,r,n,a,o=!1)=>{if(!t){e.push(0);return}let i=ut(),d=t[0],h=t[1],m=t[3],c,_;if(d==="string"&&m==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(o&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let C=t[2].gpuBuffer,k=Gn(Ls(d));_=h.reduce((z,I)=>z*I,1)*k;let M=i.jsepRegisterBuffer;if(!M)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');c=M(n,a,C,_)}else{let C=t[2];if(Array.isArray(C)){_=4*C.length,c=i._malloc(_),r.push(c);let k=c/4;for(let M=0;Mi.HEAP32[C++]=M);let k=i._OrtCreateTensor(Ls(d),c,_,$,h.length,Ws(m));k===0&&Xe(`Can't create tensor for input/output. session=${n}, index=${a}.`),e.push(k)}finally{i.stackRestore(v)}},Of=async(t,e,r,n,a,o)=>{var ce,Se;let i=ut(),d=Tr.get(t);if(!d)throw new Error(`cannot run inference. invalid session id: ${t}`);let h=d[0],m=d[1],c=d[2],_=d[3],v=d[4],$=d[5],C=e.length,k=n.length,M=0,z=[],I=[],j=[],R=[],L=i.stackSave(),Y=i.stackAlloc(C*4),Q=i.stackAlloc(C*4),ie=i.stackAlloc(k*4),pe=i.stackAlloc(k*4);try{[M,z]=Jl(o);for(let ee=0;eest*ot,1);ve=Lr(ct);let ir=_==null?void 0:_.outputPreferredLocations[n[ee]];if(ve==="string"){if(ir==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let st=[],ot=Le/4;for(let vt=0;vt0){let st=i.jsepGetBuffer;if(!st)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ot=st(Le),vt=Gn(ct);if(vt===void 0||!Fs(ve))throw new Error(`Unsupported data type: ${ve}`);he=!0,ne.push([ve,Gt,{gpuBuffer:ot,download:i.jsepCreateDownloader(ot,It*vt,ve),dispose:()=>{i._OrtReleaseTensor(Ee)}},"gpu-buffer"])}else{let st=Us(ve),ot=new st(It);new Uint8Array(ot.buffer,ot.byteOffset,ot.byteLength).set(i.HEAPU8.subarray(Le,Le+ot.byteLength)),ne.push([ve,Gt,ot,"cpu"])}}finally{i.stackRestore(Te),ve==="string"&&Le&&i._free(Le),he||i._OrtReleaseTensor(Ee)}}return _&&!v&&(i._OrtClearBoundOutputs(_.handle),Tr.set(t,[h,m,c,_,v,!1])),ne}finally{i.stackRestore(L),I.forEach(fe=>i._OrtReleaseTensor(fe)),j.forEach(fe=>i._OrtReleaseTensor(fe)),R.forEach(fe=>i._free(fe)),M!==0&&i._OrtReleaseRunOptions(M),z.forEach(fe=>i._free(fe))}},zf=t=>{let e=ut(),r=Tr.get(t);if(!r)throw new Error("invalid session id");let n=r[0],a=e._OrtEndProfiling(n);a===0&&Xe("Can't get an profile file name."),e._OrtFree(a)},Pf=t=>{let e=[];for(let r of t){let n=r[2];!Array.isArray(n)&&"buffer"in n&&e.push(n.buffer)}return e}}),Gw=cn((t,e)=>{e.exports='/*!\n * ONNX Runtime Web v1.18.0\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var Ai=Object.defineProperty;var kh=Object.getOwnPropertyDescriptor;var Oh=Object.getOwnPropertyNames;var Rh=Object.prototype.hasOwnProperty;var ae=(e,r)=>()=>(e&&(r=e(e=0)),r);var un=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Hn=(e,r)=>{for(var t in r)Ai(e,t,{get:r[t],enumerable:!0})},Bh=(e,r,t,u)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Oh(r))!Rh.call(e,s)&&s!==t&&Ai(e,s,{get:()=>r[s],enumerable:!(u=kh(r,s))||u.enumerable});return e};var ir=e=>Bh(Ai({},"__esModule",{value:!0}),e);var Ln={};Hn(Ln,{createReadStream:()=>qs,readFile:()=>Dh,readFileSync:()=>zh});var Dh,zh,qs,Fn=ae(()=>{Dh=void 0,zh=void 0,qs=void 0});var Ti={};Hn(Ti,{join:()=>Mh});var Mh,Ei=ae(()=>{Mh=void 0});var Zs=un((Ys,Pi)=>{"use strict";var Ks=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(r={}){var t=r,u,s,c=new Promise((n,i)=>{u=n,s=i});t.mountExternalData=(n,i)=>{(t.Ph||(t.Ph=new Map)).set(n,i)},t.unmountExternalData=()=>{delete t.Ph};let f=()=>{let n=(o,a,l)=>(...p)=>{let h=yt,y=a?.();p=o(...p);let b=a?.();return y!==b&&(o=b,l(y),a=l=null),yt!=h?Tn():p},i=o=>async(...a)=>{try{if(t.Oh)throw Error("Session already started");let l=t.Oh={gi:a[0],errors:[]},p=await o(...a);if(t.Oh!==l)throw Error("Session mismatch");t.Uh?.flush();let h=l.errors;if(0b),0t._OrtCreateSession,o=>t._OrtCreateSession=o),t._OrtRun=i(n(t._OrtRun,()=>t._OrtRun,o=>t._OrtRun=o)),t._OrtRunWithBinding=i(n(t._OrtRunWithBinding,()=>t._OrtRunWithBinding,o=>t._OrtRunWithBinding=o)),t._OrtBindInput=n(t._OrtBindInput,()=>t._OrtBindInput,o=>t._OrtBindInput=o),f=void 0};t.jsepInit=(n,i)=>{if(f?.(),n==="webgpu"){[t.Uh,t.Zh,t.ci,t.Vh,t.bi,t.je,t.di,t.fi,t.$h,t.ai,t.ei]=i;let o=t.Uh;t.jsepRegisterBuffer=(a,l,p,h)=>o.registerBuffer(a,l,p,h),t.jsepGetBuffer=a=>o.getBuffer(a),t.jsepCreateDownloader=(a,l,p)=>o.createDownloader(a,l,p),t.jsepOnReleaseSession=a=>{o.onReleaseSession(a)},t.jsepOnRunStart=a=>o.onRunStart(a)}};var d=Object.assign({},t),g="./this.program",w=(n,i)=>{throw i},C=typeof window=="object",$=typeof importScripts=="function",A=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",P="",x,E,O;if(A){var B=(Fn(),ir(Ln)),R=(Ei(),ir(Ti));P=$?R.dirname(P)+"/":__dirname+"/",x=(n,i)=>(n=tt(n)?new URL(n):R.normalize(n),B.readFileSync(n,i?void 0:"utf8")),O=n=>(n=x(n,!0),n.buffer||(n=new Uint8Array(n)),n),E=(n,i,o,a=!0)=>{n=tt(n)?new URL(n):R.normalize(n),B.readFile(n,a?void 0:"utf8",(l,p)=>{l?o(l):i(a?p.buffer:p)})},!t.thisProgram&&1{throw process.exitCode=n,i}}else(C||$)&&($?P=self.location.href:typeof document<"u"&&document.currentScript&&(P=document.currentScript.src),e&&(P=e),P.startsWith("blob:")?P="":P=P.substr(0,P.replace(/[?#].*/,"").lastIndexOf("/")+1),x=n=>{var i=new XMLHttpRequest;return i.open("GET",n,!1),i.send(null),i.responseText},$&&(O=n=>{var i=new XMLHttpRequest;return i.open("GET",n,!1),i.responseType="arraybuffer",i.send(null),new Uint8Array(i.response)}),E=(n,i,o)=>{var a=new XMLHttpRequest;a.open("GET",n,!0),a.responseType="arraybuffer",a.onload=()=>{a.status==200||a.status==0&&a.response?i(a.response):o()},a.onerror=o,a.send(null)});var j=console.log.bind(console),U=console.error.bind(console);Object.assign(t,d),d=null;var L,F=!1,te,J,oe,le,ge,X,pe,we,ue,me,Ee;function Pe(){var n=L.buffer;t.HEAP8=J=new Int8Array(n),t.HEAP16=le=new Int16Array(n),t.HEAPU8=oe=new Uint8Array(n),t.HEAPU16=ge=new Uint16Array(n),t.HEAP32=X=new Int32Array(n),t.HEAPU32=pe=new Uint32Array(n),t.HEAPF32=we=new Float32Array(n),t.HEAPF64=Ee=new Float64Array(n),t.HEAP64=ue=new BigInt64Array(n),t.HEAPU64=me=new BigUint64Array(n)}var Ce=[],be=[],Ae=[],_e=0,Je=null,ee=null;function ce(n){throw n="Aborted("+n+")",U(n),F=!0,te=1,n=new WebAssembly.RuntimeError(n+". Build with -sASSERTIONS for more info."),s(n),n}var Be=n=>n.startsWith("data:application/octet-stream;base64,"),tt=n=>n.startsWith("file://"),Ye;if(Ye="ort-wasm-simd.wasm",!Be(Ye)){var Ke=Ye;Ye=t.locateFile?t.locateFile(Ke,P):P+Ke}function Pt(n){if(O)return O(n);throw"both async and sync fetching of the wasm failed"}function Ze(n){if(C||$){if(typeof fetch=="function"&&!tt(n))return fetch(n,{credentials:"same-origin"}).then(i=>{if(!i.ok)throw`failed to load wasm binary file at \'${n}\'`;return i.arrayBuffer()}).catch(()=>Pt(n));if(E)return new Promise((i,o)=>{E(n,a=>i(new Uint8Array(a)),o)})}return Promise.resolve().then(()=>Pt(n))}function rt(n,i,o){return Ze(n).then(a=>WebAssembly.instantiate(a,i)).then(o,a=>{U(`failed to asynchronously prepare wasm: ${a}`),ce(a)})}function ct(n,i){var o=Ye;return typeof WebAssembly.instantiateStreaming!="function"||Be(o)||tt(o)||A||typeof fetch!="function"?rt(o,n,i):fetch(o,{credentials:"same-origin"}).then(a=>WebAssembly.instantiateStreaming(a,n).then(i,function(l){return U(`wasm streaming compile failed: ${l}`),U("falling back to ArrayBuffer instantiation"),rt(o,n,i)}))}var Ut={1261504:(n,i,o,a)=>{if(typeof t>"u"||!t.Ph)return 1;if(n=qe(n>>>0),n.startsWith("./")&&(n=n.substring(2)),n=t.Ph.get(n),!n)return 2;if(i>>>=0,o>>>=0,i+o>n.byteLength)return 3;try{return oe.set(n.subarray(i,i+o),a>>>0>>>0),0}catch{return 4}},1262005:(n,i,o)=>{o=qe(o);let a=new Uint8Array(i);a.set(oe.subarray(n>>>0,n+i>>>0)),typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"?(Fn(),ir(Ln)).writeFileSync(o,a):(n=new File([a],o,{type:"application/octet-stream"}),n=URL.createObjectURL(n),window.open(n,"_blank"))},1262513:()=>{t.$h()},1262544:()=>{t.ai()},1262573:()=>{t.ei()},1262598:n=>t.Zh(n),1262631:n=>t.ci(n),1262663:(n,i,o)=>{t.Vh(n,i,o,!0)},1262702:(n,i,o)=>{t.Vh(n,i,o)},1262735:n=>{t.je("Abs",n,void 0)},1262786:n=>{t.je("Neg",n,void 0)},1262837:n=>{t.je("Floor",n,void 0)},1262890:n=>{t.je("Ceil",n,void 0)},1262942:n=>{t.je("Reciprocal",n,void 0)},1263e3:n=>{t.je("Sqrt",n,void 0)},1263052:n=>{t.je("Exp",n,void 0)},1263103:n=>{t.je("Erf",n,void 0)},1263154:n=>{t.je("Sigmoid",n,void 0)},1263209:(n,i,o)=>{t.je("HardSigmoid",n,{alpha:i,beta:o})},1263288:n=>{t.je("Log",n,void 0)},1263339:n=>{t.je("Sin",n,void 0)},1263390:n=>{t.je("Cos",n,void 0)},1263441:n=>{t.je("Tan",n,void 0)},1263492:n=>{t.je("Asin",n,void 0)},1263544:n=>{t.je("Acos",n,void 0)},1263596:n=>{t.je("Atan",n,void 0)},1263648:n=>{t.je("Sinh",n,void 0)},1263700:n=>{t.je("Cosh",n,void 0)},1263752:n=>{t.je("Asinh",n,void 0)},1263805:n=>{t.je("Acosh",n,void 0)},1263858:n=>{t.je("Atanh",n,void 0)},1263911:n=>{t.je("Tanh",n,void 0)},1263963:n=>{t.je("Not",n,void 0)},1264014:(n,i,o)=>{t.je("Clip",n,{min:i,max:o})},1264083:n=>{t.je("Clip",n,void 0)},1264135:(n,i)=>{t.je("Elu",n,{alpha:i})},1264193:n=>{t.je("Relu",n,void 0)},1264245:(n,i)=>{t.je("LeakyRelu",n,{alpha:i})},1264309:(n,i)=>{t.je("ThresholdedRelu",n,{alpha:i})},1264379:(n,i)=>{t.je("Cast",n,{to:i})},1264437:n=>{t.je("Add",n,void 0)},1264488:n=>{t.je("Sub",n,void 0)},1264539:n=>{t.je("Mul",n,void 0)},1264590:n=>{t.je("Div",n,void 0)},1264641:n=>{t.je("Pow",n,void 0)},1264692:n=>{t.je("Equal",n,void 0)},1264745:n=>{t.je("Greater",n,void 0)},1264800:n=>{t.je("GreaterOrEqual",n,void 0)},1264862:n=>{t.je("Less",n,void 0)},1264914:n=>{t.je("LessOrEqual",n,void 0)},1264973:(n,i,o,a,l)=>{t.je("ReduceMean",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1265132:(n,i,o,a,l)=>{t.je("ReduceMax",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1265290:(n,i,o,a,l)=>{t.je("ReduceMin",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1265448:(n,i,o,a,l)=>{t.je("ReduceProd",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1265607:(n,i,o,a,l)=>{t.je("ReduceSum",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1265765:(n,i,o,a,l)=>{t.je("ReduceL1",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1265922:(n,i,o,a,l)=>{t.je("ReduceL2",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1266079:(n,i,o,a,l)=>{t.je("ReduceLogSum",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1266240:(n,i,o,a,l)=>{t.je("ReduceSumSquare",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1266404:(n,i,o,a,l)=>{t.je("ReduceLogSumExp",n,{keepDims:!!i,noopWithEmptyAxes:!!o,axes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1266568:n=>{t.je("Where",n,void 0)},1266621:(n,i,o)=>{t.je("Transpose",n,{perm:i?Array.from(X.subarray(i>>>0,o>>>0)):[]})},1266729:(n,i,o,a)=>{t.je("DepthToSpace",n,{blocksize:i,mode:qe(o),format:a?"NHWC":"NCHW"})},1266862:(n,i,o,a)=>{t.je("DepthToSpace",n,{blocksize:i,mode:qe(o),format:a?"NHWC":"NCHW"})},1266995:(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)=>{t.je("ConvTranspose",n,{format:b?"NHWC":"NCHW",autoPad:i,dilations:[o],group:a,kernelShape:[l],pads:[p,h],strides:[y],wIsConst:()=>!!J[_>>>0],outputPadding:S?Array.from(X.subarray(S>>>0,k>>>0)):[],outputShape:z?Array.from(X.subarray(z>>>0,T>>>0)):[],activation:qe(V)})},1267396:(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>{t.je("ConvTranspose",n,{format:y?"NHWC":"NCHW",autoPad:i,dilations:Array.from(X.subarray(o>>>0,(o>>>0)+2>>>0)),group:a,kernelShape:Array.from(X.subarray(l>>>0,(l>>>0)+2>>>0)),pads:Array.from(X.subarray(p>>>0,(p>>>0)+4>>>0)),strides:Array.from(X.subarray(h>>>0,(h>>>0)+2>>>0)),wIsConst:()=>!!J[b>>>0],outputPadding:_?Array.from(X.subarray(_>>>0,S>>>0)):[],outputShape:k?Array.from(X.subarray(k>>>0,z>>>0)):[],activation:qe(T)})},1267961:(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)=>{t.je("ConvTranspose",n,{format:b?"NHWC":"NCHW",autoPad:i,dilations:[o],group:a,kernelShape:[l],pads:[p,h],strides:[y],wIsConst:()=>!!J[_>>>0],outputPadding:S?Array.from(X.subarray(S>>>0,k>>>0)):[],outputShape:z?Array.from(X.subarray(z>>>0,T>>>0)):[],activation:qe(V)})},1268362:(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>{t.je("ConvTranspose",n,{format:y?"NHWC":"NCHW",autoPad:i,dilations:Array.from(X.subarray(o>>>0,(o>>>0)+2>>>0)),group:a,kernelShape:Array.from(X.subarray(l>>>0,(l>>>0)+2>>>0)),pads:Array.from(X.subarray(p>>>0,(p>>>0)+4>>>0)),strides:Array.from(X.subarray(h>>>0,(h>>>0)+2>>>0)),wIsConst:()=>!!J[b>>>0],outputPadding:_?Array.from(X.subarray(_>>>0,S>>>0)):[],outputShape:k?Array.from(X.subarray(k>>>0,z>>>0)):[],activation:qe(T)})},1268927:(n,i)=>{t.je("GlobalAveragePool",n,{format:i?"NHWC":"NCHW"})},1269018:(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>{t.je("AveragePool",n,{format:Y?"NHWC":"NCHW",auto_pad:i,ceil_mode:o,count_include_pad:a,storage_order:l,dilations:[p,h],kernel_shape:[y,b],pads:[_,S,k,z],strides:[T,V]})},1269302:(n,i)=>{t.je("GlobalAveragePool",n,{format:i?"NHWC":"NCHW"})},1269393:(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>{t.je("AveragePool",n,{format:Y?"NHWC":"NCHW",auto_pad:i,ceil_mode:o,count_include_pad:a,storage_order:l,dilations:[p,h],kernel_shape:[y,b],pads:[_,S,k,z],strides:[T,V]})},1269677:(n,i)=>{t.je("GlobalMaxPool",n,{format:i?"NHWC":"NCHW"})},1269764:(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>{t.je("MaxPool",n,{format:Y?"NHWC":"NCHW",auto_pad:i,ceil_mode:o,count_include_pad:a,storage_order:l,dilations:[p,h],kernel_shape:[y,b],pads:[_,S,k,z],strides:[T,V]})},1270044:(n,i)=>{t.je("GlobalMaxPool",n,{format:i?"NHWC":"NCHW"})},1270131:(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>{t.je("MaxPool",n,{format:Y?"NHWC":"NCHW",auto_pad:i,ceil_mode:o,count_include_pad:a,storage_order:l,dilations:[p,h],kernel_shape:[y,b],pads:[_,S,k,z],strides:[T,V]})},1270411:(n,i,o,a,l)=>{t.je("Gemm",n,{alpha:i,beta:o,transA:a,transB:l})},1270515:n=>{t.je("MatMul",n,void 0)},1270569:(n,i,o,a)=>{t.je("ArgMax",n,{keepDims:!!i,selectLastIndex:!!o,axis:a})},1270677:(n,i,o,a)=>{t.je("ArgMin",n,{keepDims:!!i,selectLastIndex:!!o,axis:a})},1270785:(n,i)=>{t.je("Softmax",n,{axis:i})},1270848:(n,i)=>{t.je("Concat",n,{axis:i})},1270908:(n,i,o,a,l)=>{t.je("Split",n,{axis:i,numOutputs:o,splitSizes:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1271048:n=>{t.je("Expand",n,void 0)},1271102:(n,i)=>{t.je("Gather",n,{axis:Number(i)})},1271173:(n,i)=>{t.je("GatherElements",n,{axis:Number(i)})},1271252:(n,i,o,a,l,p,h,y,b,_,S)=>{t.je("Resize",n,{antialias:i,axes:o?Array.from(X.subarray(o>>>0,a>>>0)):[],coordinateTransformMode:qe(l),cubicCoeffA:p,excludeOutside:h,extrapolationValue:y,keepAspectRatioPolicy:qe(b),mode:qe(_),nearestMode:qe(S)})},1271598:(n,i,o,a,l,p,h)=>{t.je("Slice",n,{starts:i?Array.from(X.subarray(i>>>0,o>>>0)):[],ends:a?Array.from(X.subarray(a>>>0,l>>>0)):[],axes:p?Array.from(X.subarray(p>>>0,h>>>0)):[]})},1271814:n=>{t.je("Tile",n,void 0)},1271866:(n,i,o,a)=>{t.je("LayerNormalization",n,{axis:i,epsilon:o,simplified:!!a})},1271977:(n,i,o)=>{t.je("InstanceNormalization",n,{epsilon:i,format:o?"NHWC":"NCHW"})},1272091:(n,i,o)=>{t.je("InstanceNormalization",n,{epsilon:i,format:o?"NHWC":"NCHW"})},1272205:n=>{t.je("Range",n,void 0)},1272258:(n,i)=>{t.je("Einsum",n,{equation:qe(i)})},1272339:(n,i,o,a,l)=>{t.je("Pad",n,{mode:i,value:o,pads:a?Array.from(X.subarray(a>>>0,l>>>0)):[]})},1272466:(n,i,o,a,l,p)=>{t.je("BatchNormalization",n,{epsilon:i,momentum:o,spatial:!!l,trainingMode:!!a,format:p?"NHWC":"NCHW"})},1272635:(n,i,o,a,l,p)=>{t.je("BatchNormalization",n,{epsilon:i,momentum:o,spatial:!!l,trainingMode:!!a,format:p?"NHWC":"NCHW"})},1272804:(n,i,o)=>{t.je("CumSum",n,{exclusive:Number(i),reverse:Number(o)})},1272901:(n,i,o,a,l,p,h,y,b)=>{t.je("Attention",n,{numHeads:i,isUnidirectional:o,maskFilterValue:a,scale:l,doRotary:p,qkvHiddenSizes:h?Array.from(X.subarray(Number(y)>>>0,Number(y)+h>>>0)):[],pastPresentShareBuffer:!!b})},1273173:n=>{t.je("BiasAdd",n,void 0)},1273228:n=>{t.je("BiasSplitGelu",n,void 0)},1273289:n=>{t.je("FastGelu",n,void 0)},1273345:(n,i,o,a,l,p,h,y,b,_,S,k,z)=>{t.je("Conv",n,{format:b?"NHWC":"NCHW",auto_pad:i,dilations:[o],group:a,kernel_shape:[l],pads:p?Array.from(X.subarray(p>>>0,h>>>0)):[],strides:[y],w_is_const:()=>!!J[_>>>0],activation:qe(S),activation_params:k?Array.from(we.subarray(k>>>0,z>>>0)):[]})},1273715:(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>{t.je("Conv",n,{format:k?"NHWC":"NCHW",auto_pad:i,dilations:[o,a],group:l,kernel_shape:[p,h],pads:y?Array.from(X.subarray(y>>>0,b>>>0)):[],strides:[_,S],w_is_const:()=>!!J[z>>>0],activation:qe(T),activation_params:V?Array.from(we.subarray(V>>>0,Y>>>0)):[]})},1274106:n=>{t.je("Gelu",n,void 0)},1274158:(n,i,o,a,l,p)=>{t.je("MatMulNBits",n,{k:i,n:o,accuracyLevel:a,bits:l,blockSize:p})},1274285:(n,i,o,a,l,p)=>{t.je("MultiHeadAttention",n,{numHeads:i,isUnidirectional:o,maskFilterValue:a,scale:l,doRotary:p})},1274444:(n,i,o,a,l)=>{t.je("RotaryEmbedding",n,{interleaved:!!i,numHeads:o,rotaryEmbeddingDim:a,scale:l})},1274583:(n,i,o)=>{t.je("SkipLayerNormalization",n,{epsilon:i,simplified:!!o})},1274685:(n,i,o)=>{t.je("SkipLayerNormalization",n,{epsilon:i,simplified:!!o})},1274787:(n,i,o,a)=>{t.je("LayerNormalization",n,{axis:i,epsilon:o,simplified:!!a})},1274898:n=>{t.di(n)},1274932:(n,i)=>t.fi(n,i,t.Oh.gi,t.Oh.errors)};function Vt(n){this.name="ExitStatus",this.message=`Program terminated with exit(${n})`,this.status=n}var pt=[],qt=0,ut=0;class cr{constructor(i){this.Nh=i,this.Ih=i-24}}var fr=n=>{var i=ut;if(!i)return er(0),0;var o=new cr(i);pe[o.Ih+16>>>2>>>0]=i;var a=pe[o.Ih+4>>>2>>>0];if(!a)return er(0),i;for(var l in n){var p=n[l];if(p===0||p===a)break;if(Vn(p,a,o.Ih+16))return er(p),i}return er(a),i},zr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,hn=(n,i,o)=>{i>>>=0;var a=i+o;for(o=i;n[o]&&!(o>=a);)++o;if(16l?a+=String.fromCharCode(l):(l-=65536,a+=String.fromCharCode(55296|l>>10,56320|l&1023))}}else a+=String.fromCharCode(l)}return a},qe=(n,i)=>(n>>>=0)?hn(oe,n,i):"",Kt=n=>{for(var i=0,o=0;o=a?i++:2047>=a?i+=2:55296<=a&&57343>=a?(i+=4,++o):i+=3}return i},vt=(n,i,o,a)=>{if(o>>>=0,!(0=h){var y=n.charCodeAt(++p);h=65536+((h&1023)<<10)|y&1023}if(127>=h){if(o>=a)break;i[o++>>>0]=h}else{if(2047>=h){if(o+1>=a)break;i[o++>>>0]=192|h>>6}else{if(65535>=h){if(o+2>=a)break;i[o++>>>0]=224|h>>12}else{if(o+3>=a)break;i[o++>>>0]=240|h>>18,i[o++>>>0]=128|h>>12&63}i[o++>>>0]=128|h>>6&63}i[o++>>>0]=128|h&63}}return i[o>>>0]=0,o-l},pr,mt=n=>{for(var i="";oe[n>>>0];)i+=pr[oe[n++>>>0]];return i},mr={},hr={},gn={},it;function yn(n,i,o={}){var a=i.name;if(!n)throw new it(`type "${a}" must have a positive integer typeid pointer`);if(hr.hasOwnProperty(n)){if(o.Xh)return;throw new it(`Cannot register type \'${a}\' twice`)}hr[n]=i,delete gn[n],mr.hasOwnProperty(n)&&(i=mr[n],delete mr[n],i.forEach(l=>l()))}function ht(n,i,o={}){if(!("argPackAdvance"in i))throw new TypeError("registerType registeredInstance requires argPackAdvance");return yn(n,i,o)}var Se=(n,i,o)=>{switch(i){case 1:return o?a=>J[a>>>0]:a=>oe[a>>>0];case 2:return o?a=>le[a>>>1>>>0]:a=>ge[a>>>1>>>0];case 4:return o?a=>X[a>>>2>>>0]:a=>pe[a>>>2>>>0];case 8:return o?a=>ue[a>>>3]:a=>me[a>>>3];default:throw new TypeError(`invalid integer width (${i}): ${n}`)}},Wt=[],wt=[];function Mr(n){n>>>=0,9{if(!n)throw new it("Cannot use deleted val. handle = "+n);return wt[n]},gt=n=>{switch(n){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let i=Wt.pop()||wt.length;return wt[i]=n,wt[i+1]=1,i}};function gr(n){return this.fromWireType(pe[n>>>2>>>0])}var bn={name:"emscripten::val",fromWireType:n=>{var i=ot(n);return Mr(n),i},toWireType:(n,i)=>gt(i),argPackAdvance:8,readValueFromPointer:gr,Mh:null},vn=(n,i)=>{switch(i){case 4:return function(o){return this.fromWireType(we[o>>>2>>>0])};case 8:return function(o){return this.fromWireType(Ee[o>>>3>>>0])};default:throw new TypeError(`invalid float width (${i}): ${n}`)}},jr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ur=(n,i)=>{for(var o=n>>1,a=o+i/2;!(o>=a)&&ge[o>>>0];)++o;if(o<<=1,32>>0,o>>>0));for(o="",a=0;!(a>=i/2);++a){var l=le[n+2*a>>>1>>>0];if(l==0)break;o+=String.fromCharCode(l)}return o},wn=(n,i,o)=>{if(o??=2147483647,2>o)return 0;o-=2;var a=i;o=o<2*n.length?o/2:n.length;for(var l=0;l>>1>>>0]=n.charCodeAt(l),i+=2;return le[i>>>1>>>0]=0,i-a},_n=n=>2*n.length,$n=(n,i)=>{for(var o=0,a="";!(o>=i/4);){var l=X[n+4*o>>>2>>>0];if(l==0)break;++o,65536<=l?(l-=65536,a+=String.fromCharCode(55296|l>>10,56320|l&1023)):a+=String.fromCharCode(l)}return a},Cn=(n,i,o)=>{if(i>>>=0,o??=2147483647,4>o)return 0;var a=i;o=a+o-4;for(var l=0;l=p){var h=n.charCodeAt(++l);p=65536+((p&1023)<<10)|h&1023}if(X[i>>>2>>>0]=p,i+=4,i+4>o)break}return X[i>>>2>>>0]=0,i-a},Sn=n=>{for(var i=0,o=0;o=a&&++o,i+=4}return i},yr=(n,i)=>{var o=hr[n];if(o===void 0)throw n=qr(n),o=mt(n),_t(n),new it(`${i} has unknown type ${o}`);return o},Vr=(n,i,o)=>{var a=[];return n=n.toWireType(a,o),a.length&&(pe[i>>>2>>>0]=gt(a)),n},Yt=n=>{try{n()}catch(i){ce(i)}},xn=n=>{if(!F)try{n();try{te=te=n=te,t.onExit?.(n),F=!0,w(n,new Vt(n))}catch(i){i instanceof Vt||i=="unwind"||w(1,i)}}catch(i){i instanceof Vt||i=="unwind"||w(1,i)}};function In(){var n=M,i={};for(let[o,a]of Object.entries(n))i[o]=typeof a=="function"?(...l)=>{Zt.push(o);try{return a(...l)}finally{F||(Zt.pop(),yt&&Ct===1&&Zt.length===0&&(Ct=0,Yt(Gs),typeof Fibers<"u"&&Fibers.mi()))}}:a;return i}var Ct=0,yt=null,Wr=0,Zt=[],br={},Qt={},Nt=0,vr=null,An=[];function Tn(){return new Promise((n,i)=>{vr={resolve:n,reject:i}})}function En(){var n=Jt(65548),i=n+12;pe[n>>>2>>>0]=i,pe[n+4>>>2>>>0]=i+65536,i=Zt[0];var o=br[i];return o===void 0&&(o=Nt++,br[i]=o,Qt[o]=i),X[n+8>>>2>>>0]=o,n}function Pn(n){if(!F){if(Ct===0){var i=!1,o=!1;n((a=0)=>{if(!F&&(Wr=a,i=!0,o)){Ct=2,Yt(()=>Hs(yt)),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.resume(),a=!1;try{var l=(0,M[Qt[X[yt+8>>>2>>>0]]])()}catch(y){l=y,a=!0}var p=!1;if(!yt){var h=vr;h&&(vr=null,(a?h.reject:h.resolve)(l),p=!0)}if(a&&!p)throw l}}),o=!0,i||(Ct=1,yt=En(),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.pause(),Yt(()=>Ns(yt)))}else Ct===2?(Ct=0,Yt(Ls),_t(yt),yt=null,An.forEach(xn)):ce(`invalid state: ${Ct}`);return Wr}}function wr(n){return Pn(i=>{n().then(i)})}var Xt=[],_i={},Ge=n=>{var i=_i[n];return i===void 0?mt(n):i},_r=()=>typeof globalThis=="object"?globalThis:Function("return this")(),Nr=n=>{var i=Xt.length;return Xt.push(n),i},kn=(n,i)=>{for(var o=Array(n),a=0;a>>2>>>0],"parameter "+a);return o},$r=(n,i)=>Object.defineProperty(i,"name",{value:n});function On(n){var i=Function;if(!(i instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof i} which is not a function`);var o=$r(i.name||"unknownFunctionName",function(){});return o.prototype=i.prototype,o=new o,n=i.apply(o,n),n instanceof Object?n:o}var jt=n=>n%4===0&&(n%100!==0||n%400===0),Gr=[0,31,60,91,121,152,182,213,244,274,305,335],Hr=[0,31,59,90,120,151,181,212,243,273,304,334],Cr=[],Rn=(n,i)=>{Cr.length=0;for(var o;o=oe[n++>>>0];){var a=o!=105;a&=o!=112,i+=a&&i%8?4:0,Cr.push(o==112?pe[i>>>2>>>0]:o==106?ue[i>>>3]:o==105?X[i>>>2>>>0]:Ee[i>>>3>>>0]),i+=a?8:4}return Cr},Sr={},Lr=()=>{if(!xr){var n={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:g||"./this.program"},i;for(i in Sr)Sr[i]===void 0?delete n[i]:n[i]=Sr[i];var o=[];for(i in n)o.push(`${i}=${n[i]}`);xr=o}return xr},xr,$i=[null,[],[]],Bn=[31,29,31,30,31,30,31,31,30,31,30,31],Fr=[31,28,31,30,31,30,31,31,30,31,30,31];function Ir(n){var i=Array(Kt(n)+1);return vt(n,i,0,i.length),i}function Dn(n,i,o,a){function l(T,V,Y){for(T=typeof T=="number"?T.toString():T||"";T.lengthde?-1:0ie-T.getDate())V-=ie-T.getDate()+1,T.setDate(1),11>Y?T.setMonth(Y+1):(T.setMonth(0),T.setFullYear(T.getFullYear()+1));else{T.setDate(T.getDate()+V);break}}return Y=new Date(T.getFullYear()+1,0,4),V=y(new Date(T.getFullYear(),0,4)),Y=y(Y),0>=h(V,T)?0>=h(Y,T)?T.getFullYear()+1:T.getFullYear():T.getFullYear()-1}n>>>=0,i>>>=0,o>>>=0,a>>>=0;var _=pe[a+40>>>2>>>0];a={ji:X[a>>>2>>>0],ii:X[a+4>>>2>>>0],Qh:X[a+8>>>2>>>0],Th:X[a+12>>>2>>>0],Rh:X[a+16>>>2>>>0],Lh:X[a+20>>>2>>>0],Jh:X[a+24>>>2>>>0],Kh:X[a+28>>>2>>>0],li:X[a+32>>>2>>>0],hi:X[a+36>>>2>>>0],ki:_?qe(_):""},o=qe(o),_={"%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 S in _)o=o.replace(new RegExp(S,"g"),_[S]);var k="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),z="January February March April May June July August September October November December".split(" ");_={"%a":T=>k[T.Jh].substring(0,3),"%A":T=>k[T.Jh],"%b":T=>z[T.Rh].substring(0,3),"%B":T=>z[T.Rh],"%C":T=>p((T.Lh+1900)/100|0,2),"%d":T=>p(T.Th,2),"%e":T=>l(T.Th,2," "),"%g":T=>b(T).toString().substring(2),"%G":b,"%H":T=>p(T.Qh,2),"%I":T=>(T=T.Qh,T==0?T=12:12{for(var V=0,Y=0;Y<=T.Rh-1;V+=(jt(T.Lh+1900)?Bn:Fr)[Y++]);return p(T.Th+V,3)},"%m":T=>p(T.Rh+1,2),"%M":T=>p(T.ii,2),"%n":()=>`\n`,"%p":T=>0<=T.Qh&&12>T.Qh?"AM":"PM","%S":T=>p(T.ji,2),"%t":()=>" ","%u":T=>T.Jh||7,"%U":T=>p(Math.floor((T.Kh+7-T.Jh)/7),2),"%V":T=>{var V=Math.floor((T.Kh+7-(T.Jh+6)%7)/7);if(2>=(T.Jh+371-T.Kh-2)%7&&V++,V)V==53&&(Y=(T.Jh+371-T.Kh)%7,Y==4||Y==3&&jt(T.Lh)||(V=1));else{V=52;var Y=(T.Jh+7-T.Kh-1)%7;(Y==4||Y==5&&jt(T.Lh%400-1))&&V++}return p(V,2)},"%w":T=>T.Jh,"%W":T=>p(Math.floor((T.Kh+7-(T.Jh+6)%7)/7),2),"%y":T=>(T.Lh+1900).toString().substring(2),"%Y":T=>T.Lh+1900,"%z":T=>{T=T.hi;var V=0<=T;return T=Math.abs(T)/60,(V?"+":"-")+("0000"+(T/60*100+T%60)).slice(-4)},"%Z":T=>T.ki,"%%":()=>"%"},o=o.replace(/%%/g,"\\0\\0");for(S in _)o.includes(S)&&(o=o.replace(new RegExp(S,"g"),_[S](a)));return o=o.replace(/\\0\\0/g,"%"),S=Ir(o),S.length>i?0:(J.set(S,n>>>0),S.length-1)}for(var St=Array(256),lt=0;256>lt;++lt)St[lt]=String.fromCharCode(lt);pr=St,it=t.BindingError=class extends Error{constructor(n){super(n),this.name="BindingError"}},t.InternalError=class extends Error{constructor(n){super(n),this.name="InternalError"}},wt.push(0,1,void 0,1,null,1,!0,1,!1,1),t.count_emval_handles=()=>wt.length/2-5-Wt.length;var zn={bd:function(n,i,o){return wr(async()=>{await t.bi(n,i,o)})},v:function(n){if(n=new cr(n>>>0),J[n.Ih+12>>>0]==0&&(J[n.Ih+12>>>0]=1,qt--),J[n.Ih+13>>>0]=0,pt.push(n),Un(n.Nh),Wn(pe[n.Ih+4>>>2>>>0]))n=pe[n.Nh>>>2>>>0];else{var i=pe[n.Ih+16>>>2>>>0];n=i!==0?i:n.Nh}return n},N:()=>{W(0,0);var n=pt.pop();jn(n.Nh),ut=0},a:function(){return fr([])},m:function(n){return fr([n>>>0])},x:function(n,i){return fr([n>>>0,i>>>0])},q:function(n,i,o){return fr([n>>>0,i>>>0,o>>>0])},Bb:()=>{var n=pt.pop();n||ce("no exception to throw");var i=n.Nh;throw J[n.Ih+13>>>0]==0&&(pt.push(n),J[n.Ih+13>>>0]=1,J[n.Ih+12>>>0]=0,qt++),ut=i,ut},s:function(n,i,o){n>>>=0;var a=new cr(n);throw pe[a.Ih+16>>>2>>>0]=0,pe[a.Ih+4>>>2>>>0]=i>>>0,pe[a.Ih+8>>>2>>>0]=o>>>0,ut=n,qt++,ut},fb:()=>qt,g:function(n){throw ut||=n>>>0,ut},Cb:function(){return 0},$c:function(){},Mc:function(){},Oc:function(){},Gc:function(){return 0},Zc:function(){},Uc:function(){},Yc:function(){},_b:function(){},Nc:function(){},Kc:function(){},_c:function(){},Lc:function(){},Wb:function(n,i,o){i=mt(i>>>0),ht(n>>>0,{name:i,fromWireType:a=>a,toWireType:function(a,l){if(typeof l!="bigint"&&typeof l!="number")throw l===null?l="null":(a=typeof l,l=a==="object"||a==="array"||a==="function"?l.toString():""+l),new TypeError(`Cannot convert "${l}" to ${this.name}`);return typeof l=="number"&&(l=BigInt(l)),l},argPackAdvance:8,readValueFromPointer:Se(i,o>>>0,i.indexOf("u")==-1),Mh:null})},Ec:function(n,i,o,a){i=mt(i>>>0),ht(n>>>0,{name:i,fromWireType:function(l){return!!l},toWireType:function(l,p){return p?o:a},argPackAdvance:8,readValueFromPointer:function(l){return this.fromWireType(oe[l>>>0])},Mh:null})},Cc:function(n){return ht(n>>>0,bn)},Vb:function(n,i,o){i=mt(i>>>0),ht(n>>>0,{name:i,fromWireType:a=>a,toWireType:(a,l)=>l,argPackAdvance:8,readValueFromPointer:vn(i,o>>>0),Mh:null})},Aa:function(n,i,o,a,l){if(n>>>=0,o>>>=0,i=mt(i>>>0),l===-1&&(l=4294967295),l=y=>y,a===0){var p=32-8*o;l=y=>y<

>>p}var h=i.includes("unsigned")?function(y,b){return b>>>0}:function(y,b){return b};ht(n,{name:i,fromWireType:l,toWireType:h,argPackAdvance:8,readValueFromPointer:Se(i,o,a!==0),Mh:null})},_:function(n,i,o){function a(p){return new l(J.buffer,pe[p+4>>>2>>>0],pe[p>>>2>>>0])}var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][i];o=mt(o>>>0),ht(n>>>0,{name:o,fromWireType:a,argPackAdvance:8,readValueFromPointer:a},{Xh:!0})},Xb:function(n,i){i=mt(i>>>0);var o=i==="std::string";ht(n>>>0,{name:i,fromWireType:function(a){var l=pe[a>>>2>>>0],p=a+4;if(o)for(var h=p,y=0;y<=l;++y){var b=p+y;if(y==l||oe[b>>>0]==0){if(h=qe(h,b-h),_===void 0)var _=h;else _+=String.fromCharCode(0),_+=h;h=b+1}}else{for(_=Array(l),y=0;y>>0]);_=_.join("")}return _t(a),_},toWireType:function(a,l){l instanceof ArrayBuffer&&(l=new Uint8Array(l));var p=typeof l=="string";if(!(p||l instanceof Uint8Array||l instanceof Uint8ClampedArray||l instanceof Int8Array))throw new it("Cannot pass non-string to std::string");var h=o&&p?Kt(l):l.length,y=Jt(4+h+1),b=y+4;if(pe[y>>>2>>>0]=h,o&&p)vt(l,oe,b,h+1);else if(p)for(p=0;p>>0]=_}else for(p=0;p>>0]=l[p];return a!==null&&a.push(_t,y),y},argPackAdvance:8,readValueFromPointer:gr,Mh(a){_t(a)}})},Ab:function(n,i,o){if(i>>>=0,o>>>=0,o=mt(o),i===2)var a=Ur,l=wn,p=_n,h=y=>ge[y>>>1>>>0];else i===4&&(a=$n,l=Cn,p=Sn,h=y=>pe[y>>>2>>>0]);ht(n>>>0,{name:o,fromWireType:y=>{for(var b=pe[y>>>2>>>0],_,S=y+4,k=0;k<=b;++k){var z=y+4+k*i;(k==b||h(z)==0)&&(S=a(S,z-S),_===void 0?_=S:(_+=String.fromCharCode(0),_+=S),S=z+i)}return _t(y),_},toWireType:(y,b)=>{if(typeof b!="string")throw new it(`Cannot pass non-string to C++ string type ${o}`);var _=p(b),S=Jt(4+_+i);return pe[S>>>2>>>0]=_/i,l(b,S+4,_+i),y!==null&&y.push(_t,S),S},argPackAdvance:8,readValueFromPointer:gr,Mh(y){_t(y)}})},Fc:function(n,i){i=mt(i>>>0),ht(n>>>0,{Yh:!0,name:i,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ad:()=>1,kd:function(n,i,o){return i>>>=0,o>>>=0,n=ot(n>>>0),i=yr(i,"emval::as"),Vr(i,o,n)},Cd:function(n){return n>>>=0,wr(()=>(n=ot(n),n.then(gt)))},ud:function(n,i,o,a){return o>>>=0,a>>>=0,n=Xt[n>>>0],i=ot(i>>>0),n(null,i,o,a)},ia:function(n,i,o,a,l){return o>>>=0,a>>>=0,l>>>=0,n=Xt[n>>>0],i=ot(i>>>0),o=Ge(o),n(i,i[o],a,l)},Bc:Mr,qd:function(n,i){return i>>>=0,n=ot(n>>>0),i=ot(i),n==i},zd:function(n){return n>>>=0,n===0?gt(_r()):(n=Ge(n),gt(_r()[n]))},ha:function(n,i,o){i=kn(n,i>>>0);var a=i.shift();n--;var l=`return function (obj, func, destructorsRef, args) {\n`,p=0,h=[];o===0&&h.push("obj");for(var y=["retType"],b=[a],_=0;_S.name).join(", ")}) => ${a.name}>`,Nr($r(o,n))},yd:function(n,i){return i>>>=0,n=ot(n>>>0),i=ot(i),gt(n[i])},ba:function(n){n>>>=0,9>>0);for(var i=Array(n.length),o=0;o>>0))},Xa:function(){return gt({})},vd:function(n){n>>>=0;for(var i=ot(n);i.length;){var o=i.pop();i.pop()(o)}Mr(n)},sd:function(n,i,o){i>>>=0,o>>>=0,n=ot(n>>>0),i=ot(i),o=ot(o),n[i]=o},zb:function(n,i){return i>>>=0,n=yr(n>>>0,"_emval_take_value"),n=n.readValueFromPointer(i),gt(n)},Rc:function(n,i){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),X[i>>>2>>>0]=n.getUTCSeconds(),X[i+4>>>2>>>0]=n.getUTCMinutes(),X[i+8>>>2>>>0]=n.getUTCHours(),X[i+12>>>2>>>0]=n.getUTCDate(),X[i+16>>>2>>>0]=n.getUTCMonth(),X[i+20>>>2>>>0]=n.getUTCFullYear()-1900,X[i+24>>>2>>>0]=n.getUTCDay(),X[i+28>>>2>>>0]=(n.getTime()-Date.UTC(n.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Sc:function(n,i){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),X[i>>>2>>>0]=n.getSeconds(),X[i+4>>>2>>>0]=n.getMinutes(),X[i+8>>>2>>>0]=n.getHours(),X[i+12>>>2>>>0]=n.getDate(),X[i+16>>>2>>>0]=n.getMonth(),X[i+20>>>2>>>0]=n.getFullYear()-1900,X[i+24>>>2>>>0]=n.getDay(),X[i+28>>>2>>>0]=(jt(n.getFullYear())?Gr:Hr)[n.getMonth()]+n.getDate()-1|0,X[i+36>>>2>>>0]=-(60*n.getTimezoneOffset());var o=new Date(n.getFullYear(),6,1).getTimezoneOffset(),a=new Date(n.getFullYear(),0,1).getTimezoneOffset();X[i+32>>>2>>>0]=(o!=a&&n.getTimezoneOffset()==Math.min(a,o))|0},Tc:function(n){n>>>=0;var i=new Date(X[n+20>>>2>>>0]+1900,X[n+16>>>2>>>0],X[n+12>>>2>>>0],X[n+8>>>2>>>0],X[n+4>>>2>>>0],X[n>>>2>>>0],0),o=X[n+32>>>2>>>0],a=i.getTimezoneOffset(),l=new Date(i.getFullYear(),6,1).getTimezoneOffset(),p=new Date(i.getFullYear(),0,1).getTimezoneOffset(),h=Math.min(p,l);return 0>o?X[n+32>>>2>>>0]=+(l!=p&&h==a):0>>2>>>0]=i.getDay(),X[n+28>>>2>>>0]=(jt(i.getFullYear())?Gr:Hr)[i.getMonth()]+i.getDate()-1|0,X[n>>>2>>>0]=i.getSeconds(),X[n+4>>>2>>>0]=i.getMinutes(),X[n+8>>>2>>>0]=i.getHours(),X[n+12>>>2>>>0]=i.getDate(),X[n+16>>>2>>>0]=i.getMonth(),X[n+20>>>2>>>0]=i.getYear(),n=i.getTime(),BigInt(isNaN(n)?-1:n/1e3)},Pc:function(){return-52},Qc:function(){},Ic:function(n,i,o,a){o>>>=0,a>>>=0;var l=new Date().getFullYear(),p=new Date(l,0,1),h=new Date(l,6,1);l=p.getTimezoneOffset();var y=h.getTimezoneOffset();pe[n>>>0>>>2>>>0]=60*Math.max(l,y),X[i>>>0>>>2>>>0]=+(l!=y),n=b=>b.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],p=n(p),h=n(h),y{ce("")},A:function(n,i,o){return n>>>=0,i=Rn(i>>>0,o>>>0),Ut[n](...i)},bc:function(n,i,o){return n>>>=0,i=Rn(i>>>0,o>>>0),Ut[n](...i)},$b:()=>Date.now(),Jc:function(){return 4294901760},ga:()=>performance.now(),Hc:function(n){n>>>=0;var i=oe.length;if(4294901760=o;o*=2){var a=i*(1+.2/o);a=Math.min(a,n+100663296);var l=Math;a=Math.max(n,a);e:{l=(l.min.call(l,4294901760,a+(65536-a%65536)%65536)-L.buffer.byteLength+65535)/65536;try{L.grow(l),Pe();var p=1;break e}catch{}p=void 0}if(p)return!0}return!1},Wc:function(n,i){n>>>=0,i>>>=0;var o=0;return Lr().forEach((a,l)=>{var p=i+o;for(l=pe[n+4*l>>>2>>>0]=p,p=0;p>>0]=a.charCodeAt(p);J[l>>>0]=0,o+=a.length+1}),0},Xc:function(n,i){n>>>=0,i>>>=0;var o=Lr();pe[n>>>2>>>0]=o.length;var a=0;return o.forEach(l=>a+=l.length+1),pe[i>>>2>>>0]=a,0},Db:()=>52,Zb:function(){return 52},Vc:function(){return 70},Yb:function(n,i,o,a){i>>>=0,o>>>=0,a>>>=0;for(var l=0,p=0;p>>2>>>0],y=pe[i+4>>>2>>>0];i+=8;for(var b=0;b>>0],S=$i[n];_===0||_===10?((n===1?j:U)(hn(S,0)),S.length=0):S.push(_)}l+=y}return pe[a>>>2>>>0]=l,0},xb:rp,cd:Th,ua:Tm,W:yh,$:bh,ra:nm,ta:ep,dd:Ah,ob:Am,P:Dp,z:Uf,b:$f,Ub:Bf,ya:Df,e:wf,kb:hh,h:vf,X:nh,i:Tf,ed:xh,j:Af,t:If,r:Lf,o:Qf,Wa:ap,Ca:Nm,ma:qf,Qb:Op,db:zp,Ib:Gm,mb:Om,kc:oh,xc:lp,hc:lh,ic:sh,ac:Sh,oa:um,yb:Zf,Ba:rh,Eb:$h,ea:lm,jc:ah,Ta:jp,F:Sf,G:_p,Gb:ih,jd:uh,qa:$m,O:xp,V:$p,T:Vp,y:zf,Fb:ph,gc:dh,D:Ym,Hb:Xm,id:ch,Ua:Bp,wa:hm,lc:Jm,cc:Ch,Nb:om,aa:tp,I:Mf,C:mp,_a:Zm,fc:fh,Q:Sp,d:xf,ab:Ap,n:Cf,Ya:mh,va:Im,wb:dp,f:_f,yc:up,da:th,gb:Ep,Da:im,lb:Rm,hb:fp,c:Ef,vc:gp,od:Hm,k:Pf,tc:Tp,l:kf,wc:pp,sc:Pp,rd:Dm,p:Of,Ra:Lp,tb:Hp,Qa:Fp,Kb:Em,B:Ff,K:jf,S:Kf,$a:Lm,pc:_m,ub:Ip,za:Up,ka:Rf,xa:Rp,Sb:Yf,La:Cm,jb:Ih,Ga:jm,nc:Um,Ha:Mm,Ia:Bm,fd:_h,xd:kp,Z:Jp,pa:xm,pd:Wm,wd:Np,Mb:am,Ma:vm,Ka:Sm,Tb:Nf,rc:dm,Ja:Pm,Na:bm,pb:sm,la:gm,Ea:Wp,mc:Qm,qc:pm,Jb:Vm,Fa:qm,ja:vp,Ad:ip,nd:Fm,R:fm,eb:Hf,Za:eh,ec:vh,ib:cp,E:Jf,M:Wf,Va:sp,ld:Km,ca:op,nb:km,na:mm,dc:wh,Ac:Gf,u:Vf,L:yp,td:wm,Pb:Qp,oc:zm,Bd:np,Ob:Xp,Lb:cm,cb:Mp,zc:Xf,Rb:wp,Oa:ym,Y:em,uc:bp,J:Cp,gd:gh,vb:hp,sa:rm,H:tm,rb:Yp,Pa:Kp,Sa:Gp,sb:qp,qb:Zp,w:function(n){return n>>>0},Dc:Dn,fa:function(n,i,o,a){return Dn(n>>>0,i>>>0,o>>>0,a>>>0)}},M=function(){function n(o){return M=o.exports,M=In(),M=Eh(),L=M.Dd,Pe(),be.unshift(M.Ed),_e--,_e==0&&(Je!==null&&(clearInterval(Je),Je=null),ee&&(o=ee,ee=null,o())),M}var i={a:zn};if(_e++,t.instantiateWasm)try{return t.instantiateWasm(i,n)}catch(o){U(`Module.instantiateWasm callback failed with error: ${o}`),s(o)}return ct(i,function(o){n(o.instance)}).catch(s),{}}(),qr=n=>(qr=M.Fd)(n);t._OrtInit=(n,i)=>(t._OrtInit=M.Gd)(n,i),t._OrtGetLastError=(n,i)=>(t._OrtGetLastError=M.Hd)(n,i),t._OrtCreateSessionOptions=(n,i,o,a,l,p,h,y,b,_)=>(t._OrtCreateSessionOptions=M.Id)(n,i,o,a,l,p,h,y,b,_),t._OrtAppendExecutionProvider=(n,i)=>(t._OrtAppendExecutionProvider=M.Jd)(n,i),t._OrtAddFreeDimensionOverride=(n,i,o)=>(t._OrtAddFreeDimensionOverride=M.Kd)(n,i,o),t._OrtAddSessionConfigEntry=(n,i,o)=>(t._OrtAddSessionConfigEntry=M.Ld)(n,i,o),t._OrtReleaseSessionOptions=n=>(t._OrtReleaseSessionOptions=M.Md)(n),t._OrtCreateSession=(n,i,o)=>(t._OrtCreateSession=M.Nd)(n,i,o),t._OrtReleaseSession=n=>(t._OrtReleaseSession=M.Od)(n),t._OrtGetInputOutputCount=(n,i,o)=>(t._OrtGetInputOutputCount=M.Pd)(n,i,o),t._OrtGetInputName=(n,i)=>(t._OrtGetInputName=M.Qd)(n,i),t._OrtGetOutputName=(n,i)=>(t._OrtGetOutputName=M.Rd)(n,i),t._OrtFree=n=>(t._OrtFree=M.Sd)(n),t._OrtCreateTensor=(n,i,o,a,l,p)=>(t._OrtCreateTensor=M.Td)(n,i,o,a,l,p),t._OrtGetTensorData=(n,i,o,a,l)=>(t._OrtGetTensorData=M.Ud)(n,i,o,a,l),t._OrtReleaseTensor=n=>(t._OrtReleaseTensor=M.Vd)(n),t._OrtCreateRunOptions=(n,i,o,a)=>(t._OrtCreateRunOptions=M.Wd)(n,i,o,a),t._OrtAddRunConfigEntry=(n,i,o)=>(t._OrtAddRunConfigEntry=M.Xd)(n,i,o),t._OrtReleaseRunOptions=n=>(t._OrtReleaseRunOptions=M.Yd)(n),t._OrtCreateBinding=n=>(t._OrtCreateBinding=M.Zd)(n),t._OrtBindInput=(n,i,o)=>(t._OrtBindInput=M._d)(n,i,o),t._OrtBindOutput=(n,i,o,a)=>(t._OrtBindOutput=M.$d)(n,i,o,a),t._OrtClearBoundOutputs=n=>(t._OrtClearBoundOutputs=M.ae)(n),t._OrtReleaseBinding=n=>(t._OrtReleaseBinding=M.be)(n),t._OrtRunWithBinding=(n,i,o,a,l)=>(t._OrtRunWithBinding=M.ce)(n,i,o,a,l),t._OrtRun=(n,i,o,a,l,p,h,y)=>(t._OrtRun=M.de)(n,i,o,a,l,p,h,y),t._OrtEndProfiling=n=>(t._OrtEndProfiling=M.ee)(n),t._JsepOutput=(n,i,o)=>(t._JsepOutput=M.fe)(n,i,o),t._JsepGetNodeName=n=>(t._JsepGetNodeName=M.ge)(n);var Jt=t._malloc=n=>(Jt=t._malloc=M.he)(n),_t=t._free=n=>(_t=t._free=M.ie)(n),W=(n,i)=>(W=M.ke)(n,i),er=n=>(er=M.le)(n),N=n=>(N=M.me)(n),Mn=n=>(Mn=M.ne)(n),G=()=>(G=M.oe)(),jn=n=>(jn=M.pe)(n),Un=n=>(Un=M.qe)(n),Vn=(n,i,o)=>(Vn=M.re)(n,i,o),Wn=n=>(Wn=M.se)(n),tr=t.dynCall_vii=(n,i,o)=>(tr=t.dynCall_vii=M.te)(n,i,o),Ar=t.dynCall_iiii=(n,i,o,a)=>(Ar=t.dynCall_iiii=M.ue)(n,i,o,a),Kr=t.dynCall_iii=(n,i,o)=>(Kr=t.dynCall_iii=M.ve)(n,i,o),Yr=t.dynCall_ii=(n,i)=>(Yr=t.dynCall_ii=M.we)(n,i),Zr=t.dynCall_iiiiiii=(n,i,o,a,l,p,h)=>(Zr=t.dynCall_iiiiiii=M.xe)(n,i,o,a,l,p,h),Tr=t.dynCall_vi=(n,i)=>(Tr=t.dynCall_vi=M.ye)(n,i),Er=t.dynCall_v=n=>(Er=t.dynCall_v=M.ze)(n),Qr=t.dynCall_iiiiii=(n,i,o,a,l,p)=>(Qr=t.dynCall_iiiiii=M.Ae)(n,i,o,a,l,p),Xr=t.dynCall_iiij=(n,i,o,a)=>(Xr=t.dynCall_iiij=M.Be)(n,i,o,a),Jr=t.dynCall_iiiii=(n,i,o,a,l)=>(Jr=t.dynCall_iiiii=M.Ce)(n,i,o,a,l),Pr=t.dynCall_viii=(n,i,o,a)=>(Pr=t.dynCall_viii=M.De)(n,i,o,a),rr=t.dynCall_viiiii=(n,i,o,a,l,p)=>(rr=t.dynCall_viiiii=M.Ee)(n,i,o,a,l,p),kr=t.dynCall_viiii=(n,i,o,a,l)=>(kr=t.dynCall_viiii=M.Fe)(n,i,o,a,l),en=t.dynCall_viiiiii=(n,i,o,a,l,p,h)=>(en=t.dynCall_viiiiii=M.Ge)(n,i,o,a,l,p,h),tn=t.dynCall_viiji=(n,i,o,a,l)=>(tn=t.dynCall_viiji=M.He)(n,i,o,a,l),rn=t.dynCall_viiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k)=>(rn=t.dynCall_viiiiiiiiiii=M.Ie)(n,i,o,a,l,p,h,y,b,_,S,k),nn=t.dynCall_viiijjjii=(n,i,o,a,l,p,h,y,b)=>(nn=t.dynCall_viiijjjii=M.Je)(n,i,o,a,l,p,h,y,b),on=t.dynCall_iid=(n,i,o)=>(on=t.dynCall_iid=M.Ke)(n,i,o),Nn=t.dynCall_iif=(n,i,o)=>(Nn=t.dynCall_iif=M.Le)(n,i,o),nr=t.dynCall_iij=(n,i,o)=>(nr=t.dynCall_iij=M.Me)(n,i,o),an=t.dynCall_jii=(n,i,o)=>(an=t.dynCall_jii=M.Ne)(n,i,o),m=t.dynCall_i=n=>(m=t.dynCall_i=M.Oe)(n),v=t.dynCall_viiiiiiii=(n,i,o,a,l,p,h,y,b)=>(v=t.dynCall_viiiiiiii=M.Pe)(n,i,o,a,l,p,h,y,b),I=t.dynCall_viiiiij=(n,i,o,a,l,p,h)=>(I=t.dynCall_viiiiij=M.Qe)(n,i,o,a,l,p,h),D=t.dynCall_ji=(n,i)=>(D=t.dynCall_ji=M.Re)(n,i),H=t.dynCall_viij=(n,i,o,a)=>(H=t.dynCall_viij=M.Se)(n,i,o,a),Q=t.dynCall_iiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k)=>(Q=t.dynCall_iiiiiiiiiiii=M.Te)(n,i,o,a,l,p,h,y,b,_,S,k),re=t.dynCall_viiiiiiiii=(n,i,o,a,l,p,h,y,b,_)=>(re=t.dynCall_viiiiiiiii=M.Ue)(n,i,o,a,l,p,h,y,b,_),ye=t.dynCall_ij=(n,i)=>(ye=t.dynCall_ij=M.Ve)(n,i),he=t.dynCall_iiiiij=(n,i,o,a,l,p)=>(he=t.dynCall_iiiiij=M.We)(n,i,o,a,l,p),fe=t.dynCall_j=n=>(fe=t.dynCall_j=M.Xe)(n),ve=t.dynCall_vij=(n,i,o)=>(ve=t.dynCall_vij=M.Ye)(n,i,o),Me=t.dynCall_viijjjiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k)=>(Me=t.dynCall_viijjjiiiiii=M.Ze)(n,i,o,a,l,p,h,y,b,_,S,k),je=t.dynCall_viiijiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k)=>(je=t.dynCall_viiijiiiiiii=M._e)(n,i,o,a,l,p,h,y,b,_,S,k),q=t.dynCall_iiiiiiii=(n,i,o,a,l,p,h,y)=>(q=t.dynCall_iiiiiiii=M.$e)(n,i,o,a,l,p,h,y),Ie=t.dynCall_viiiiiii=(n,i,o,a,l,p,h,y)=>(Ie=t.dynCall_viiiiiii=M.af)(n,i,o,a,l,p,h,y),Ue=t.dynCall_iiiiiiiij=(n,i,o,a,l,p,h,y,b)=>(Ue=t.dynCall_iiiiiiiij=M.bf)(n,i,o,a,l,p,h,y,b),kt=t.dynCall_viiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>(kt=t.dynCall_viiiiiiiiiiiii=M.cf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T),sn=t.dynCall_iiiiiiiii=(n,i,o,a,l,p,h,y,b)=>(sn=t.dynCall_iiiiiiiii=M.df)(n,i,o,a,l,p,h,y,b),yo=t.dynCall_iiiiijiiiii=(n,i,o,a,l,p,h,y,b,_,S)=>(yo=t.dynCall_iiiiijiiiii=M.ef)(n,i,o,a,l,p,h,y,b,_,S),bo=t.dynCall_vijjjiiij=(n,i,o,a,l,p,h,y,b)=>(bo=t.dynCall_vijjjiiij=M.ff)(n,i,o,a,l,p,h,y,b),vo=t.dynCall_fi=(n,i)=>(vo=t.dynCall_fi=M.gf)(n,i),wo=t.dynCall_fii=(n,i,o)=>(wo=t.dynCall_fii=M.hf)(n,i,o),_o=t.dynCall_di=(n,i)=>(_o=t.dynCall_di=M.jf)(n,i),$o=t.dynCall_dii=(n,i,o)=>($o=t.dynCall_dii=M.kf)(n,i,o),Co=t.dynCall_vijj=(n,i,o,a)=>(Co=t.dynCall_vijj=M.lf)(n,i,o,a),So=t.dynCall_iiiiiiiiii=(n,i,o,a,l,p,h,y,b,_)=>(So=t.dynCall_iiiiiiiiii=M.mf)(n,i,o,a,l,p,h,y,b,_),xo=t.dynCall_viijiii=(n,i,o,a,l,p,h)=>(xo=t.dynCall_viijiii=M.nf)(n,i,o,a,l,p,h),Io=t.dynCall_viid=(n,i,o,a)=>(Io=t.dynCall_viid=M.of)(n,i,o,a),Ao=t.dynCall_viffiii=(n,i,o,a,l,p,h)=>(Ao=t.dynCall_viffiii=M.pf)(n,i,o,a,l,p,h),To=t.dynCall_viifiii=(n,i,o,a,l,p,h)=>(To=t.dynCall_viifiii=M.qf)(n,i,o,a,l,p,h),Eo=t.dynCall_viiiiidiidi=(n,i,o,a,l,p,h,y,b,_,S)=>(Eo=t.dynCall_viiiiidiidi=M.rf)(n,i,o,a,l,p,h,y,b,_,S),Po=t.dynCall_viiiiiiiiidi=(n,i,o,a,l,p,h,y,b,_,S,k)=>(Po=t.dynCall_viiiiiiiiidi=M.sf)(n,i,o,a,l,p,h,y,b,_,S,k),ko=t.dynCall_jiii=(n,i,o,a)=>(ko=t.dynCall_jiii=M.tf)(n,i,o,a),Oo=t.dynCall_vjiiiiii=(n,i,o,a,l,p,h,y)=>(Oo=t.dynCall_vjiiiiii=M.uf)(n,i,o,a,l,p,h,y),Ro=t.dynCall_viiid=(n,i,o,a,l)=>(Ro=t.dynCall_viiid=M.vf)(n,i,o,a,l),Bo=t.dynCall_viiiiiiiiiji=(n,i,o,a,l,p,h,y,b,_,S,k)=>(Bo=t.dynCall_viiiiiiiiiji=M.wf)(n,i,o,a,l,p,h,y,b,_,S,k),Do=t.dynCall_viji=(n,i,o,a)=>(Do=t.dynCall_viji=M.xf)(n,i,o,a),zo=t.dynCall_vijjjjjjjjjjjjji=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>(zo=t.dynCall_vijjjjjjjjjjjjji=M.yf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y),Mo=t.dynCall_viiiji=(n,i,o,a,l,p)=>(Mo=t.dynCall_viiiji=M.zf)(n,i,o,a,l,p),jo=t.dynCall_vijjjiiji=(n,i,o,a,l,p,h,y,b)=>(jo=t.dynCall_vijjjiiji=M.Af)(n,i,o,a,l,p,h,y,b),Uo=t.dynCall_iiiji=(n,i,o,a,l)=>(Uo=t.dynCall_iiiji=M.Bf)(n,i,o,a,l),Vo=t.dynCall_iiijiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>(Vo=t.dynCall_iiijiiiiiiiiii=M.Cf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T),Wo=t.dynCall_vj=(n,i)=>(Wo=t.dynCall_vj=M.Df)(n,i),No=t.dynCall_jjj=(n,i,o)=>(No=t.dynCall_jjj=M.Ef)(n,i,o),Go=t.dynCall_iiijiiiiii=(n,i,o,a,l,p,h,y,b,_)=>(Go=t.dynCall_iiijiiiiii=M.Ff)(n,i,o,a,l,p,h,y,b,_),Ho=t.dynCall_vfiii=(n,i,o,a,l)=>(Ho=t.dynCall_vfiii=M.Gf)(n,i,o,a,l),Lo=t.dynCall_viiiiff=(n,i,o,a,l,p,h)=>(Lo=t.dynCall_viiiiff=M.Hf)(n,i,o,a,l,p,h),Fo=t.dynCall_viiiiiff=(n,i,o,a,l,p,h,y)=>(Fo=t.dynCall_viiiiiff=M.If)(n,i,o,a,l,p,h,y),qo=t.dynCall_viiff=(n,i,o,a,l)=>(qo=t.dynCall_viiff=M.Jf)(n,i,o,a,l),Ko=t.dynCall_viiiiiiiiifiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>(Ko=t.dynCall_viiiiiiiiifiii=M.Kf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T),Yo=t.dynCall_viiiiiiiijj=(n,i,o,a,l,p,h,y,b,_,S)=>(Yo=t.dynCall_viiiiiiiijj=M.Lf)(n,i,o,a,l,p,h,y,b,_,S),Zo=t.dynCall_iiiiiiiiiiiiiifii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie)=>(Zo=t.dynCall_iiiiiiiiiiiiiifii=M.Mf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie),Qo=t.dynCall_viiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Qo=t.dynCall_viiiiiiiiiiii=M.Nf)(n,i,o,a,l,p,h,y,b,_,S,k,z),Xo=t.dynCall_iiiiiiiiiiiiiiiiifii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze)=>(Xo=t.dynCall_iiiiiiiiiiiiiiiiifii=M.Of)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze),Jo=t.dynCall_vijjiiiiii=(n,i,o,a,l,p,h,y,b,_)=>(Jo=t.dynCall_vijjiiiiii=M.Pf)(n,i,o,a,l,p,h,y,b,_),ea=t.dynCall_iiiijjj=(n,i,o,a,l,p,h)=>(ea=t.dynCall_iiiijjj=M.Qf)(n,i,o,a,l,p,h),ta=t.dynCall_viiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S)=>(ta=t.dynCall_viiiiiiiiii=M.Rf)(n,i,o,a,l,p,h,y,b,_,S),ra=t.dynCall_iiijjj=(n,i,o,a,l,p)=>(ra=t.dynCall_iiijjj=M.Sf)(n,i,o,a,l,p),na=t.dynCall_fffffff=(n,i,o,a,l,p,h)=>(na=t.dynCall_fffffff=M.Tf)(n,i,o,a,l,p,h),ia=t.dynCall_viiiij=(n,i,o,a,l,p)=>(ia=t.dynCall_viiiij=M.Uf)(n,i,o,a,l,p),oa=t.dynCall_viiiiiijiifiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>(oa=t.dynCall_viiiiiijiifiii=M.Vf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T),aa=t.dynCall_vjjjjjjffjifiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de)=>(aa=t.dynCall_vjjjjjjffjifiiiiii=M.Wf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de),sa=t.dynCall_viiiiiiffjifiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie)=>(sa=t.dynCall_viiiiiiffjifiiiii=M.Xf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie),ua=t.dynCall_viiiiiiffjfiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>(ua=t.dynCall_viiiiiiffjfiiiii=M.Yf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y),la=t.dynCall_viiiiiiffjiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)=>(la=t.dynCall_viiiiiiffjiiiii=M.Zf)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V),da=t.dynCall_vjjjjjjjjfffiiifiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We)=>(da=t.dynCall_vjjjjjjjjfffiiifiiiii=M._f)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We),ca=t.dynCall_vjjjjjjfffifijiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e)=>(ca=t.dynCall_vjjjjjjfffifijiiiii=M.$f)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e),fa=t.dynCall_vjjjjjjfffifiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de)=>(fa=t.dynCall_vjjjjjjfffifiiiiii=M.ag)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de),pa=t.dynCall_vjjjjjjjjfffjifiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We)=>(pa=t.dynCall_vjjjjjjjjfffjifiiiiii=M.bg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We),ma=t.dynCall_vijiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(ma=t.dynCall_vijiiiiiiiiii=M.cg)(n,i,o,a,l,p,h,y,b,_,S,k,z),ha=t.dynCall_vijjfffiii=(n,i,o,a,l,p,h,y,b,_)=>(ha=t.dynCall_vijjfffiii=M.dg)(n,i,o,a,l,p,h,y,b,_),ga=t.dynCall_viiiiiiijiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(ga=t.dynCall_viiiiiiijiiii=M.eg)(n,i,o,a,l,p,h,y,b,_,S,k,z),ya=t.dynCall_vijjjjjjifiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)=>(ya=t.dynCall_vijjjjjjifiiiii=M.fg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V),ba=t.dynCall_viifi=(n,i,o,a,l)=>(ba=t.dynCall_viifi=M.gg)(n,i,o,a,l),va=t.dynCall_vjjjjjiiii=(n,i,o,a,l,p,h,y,b,_)=>(va=t.dynCall_vjjjjjiiii=M.hg)(n,i,o,a,l,p,h,y,b,_),wa=t.dynCall_vjjjjfiii=(n,i,o,a,l,p,h,y,b)=>(wa=t.dynCall_vjjjjfiii=M.ig)(n,i,o,a,l,p,h,y,b),_a=t.dynCall_viiiiiijiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>(_a=t.dynCall_viiiiiijiiiiii=M.jg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T),$a=t.dynCall_vijjii=(n,i,o,a,l,p)=>($a=t.dynCall_vijjii=M.kg)(n,i,o,a,l,p),Ca=t.dynCall_viiiiijjiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Ca=t.dynCall_viiiiijjiiiii=M.lg)(n,i,o,a,l,p,h,y,b,_,S,k,z),Sa=t.dynCall_iiiiiji=(n,i,o,a,l,p,h)=>(Sa=t.dynCall_iiiiiji=M.mg)(n,i,o,a,l,p,h),xa=t.dynCall_iiiiji=(n,i,o,a,l,p)=>(xa=t.dynCall_iiiiji=M.ng)(n,i,o,a,l,p),Ia=t.dynCall_viiiiijiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Ia=t.dynCall_viiiiijiiiiii=M.og)(n,i,o,a,l,p,h,y,b,_,S,k,z),Aa=t.dynCall_viiijiiiiii=(n,i,o,a,l,p,h,y,b,_,S)=>(Aa=t.dynCall_viiijiiiiii=M.pg)(n,i,o,a,l,p,h,y,b,_,S),Ta=t.dynCall_viijj=(n,i,o,a,l)=>(Ta=t.dynCall_viijj=M.qg)(n,i,o,a,l),Ea=t.dynCall_viiiijii=(n,i,o,a,l,p,h,y)=>(Ea=t.dynCall_viiiijii=M.rg)(n,i,o,a,l,p,h,y),Pa=t.dynCall_viijjiii=(n,i,o,a,l,p,h,y)=>(Pa=t.dynCall_viijjiii=M.sg)(n,i,o,a,l,p,h,y),ka=t.dynCall_ijii=(n,i,o,a)=>(ka=t.dynCall_ijii=M.tg)(n,i,o,a),Oa=t.dynCall_viiiiijjji=(n,i,o,a,l,p,h,y,b,_)=>(Oa=t.dynCall_viiiiijjji=M.ug)(n,i,o,a,l,p,h,y,b,_),Ra=t.dynCall_vijjjjiij=(n,i,o,a,l,p,h,y,b)=>(Ra=t.dynCall_vijjjjiij=M.vg)(n,i,o,a,l,p,h,y,b),Ba=t.dynCall_viiiiijij=(n,i,o,a,l,p,h,y,b)=>(Ba=t.dynCall_viiiiijij=M.wg)(n,i,o,a,l,p,h,y,b),Da=t.dynCall_viiiiiijij=(n,i,o,a,l,p,h,y,b,_)=>(Da=t.dynCall_viiiiiijij=M.xg)(n,i,o,a,l,p,h,y,b,_),za=t.dynCall_vijiii=(n,i,o,a,l,p)=>(za=t.dynCall_vijiii=M.yg)(n,i,o,a,l,p),Ma=t.dynCall_viiiiiiiiifi=(n,i,o,a,l,p,h,y,b,_,S,k)=>(Ma=t.dynCall_viiiiiiiiifi=M.zg)(n,i,o,a,l,p,h,y,b,_,S,k),ja=t.dynCall_iiijiiii=(n,i,o,a,l,p,h,y)=>(ja=t.dynCall_iiijiiii=M.Ag)(n,i,o,a,l,p,h,y),Ua=t.dynCall_viiiiiijjiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>(Ua=t.dynCall_viiiiiijjiiiii=M.Bg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T),Va=t.dynCall_viiiiiiijiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)=>(Va=t.dynCall_viiiiiiijiiiiii=M.Cg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V),Wa=t.dynCall_vif=(n,i,o)=>(Wa=t.dynCall_vif=M.Dg)(n,i,o),Na=t.dynCall_viif=(n,i,o,a)=>(Na=t.dynCall_viif=M.Eg)(n,i,o,a),Ga=t.dynCall_fiii=(n,i,o,a)=>(Ga=t.dynCall_fiii=M.Fg)(n,i,o,a),Ha=t.dynCall_diii=(n,i,o,a)=>(Ha=t.dynCall_diii=M.Gg)(n,i,o,a),La=t.dynCall_viiiiiifii=(n,i,o,a,l,p,h,y,b,_)=>(La=t.dynCall_viiiiiifii=M.Hg)(n,i,o,a,l,p,h,y,b,_),Fa=t.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We,et,dt,Ci,Si,xi)=>(Fa=t.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=M.Ig)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We,et,dt,Ci,Si,xi),qa=t.dynCall_viijji=(n,i,o,a,l,p)=>(qa=t.dynCall_viijji=M.Jg)(n,i,o,a,l,p),Ka=t.dynCall_iiiiiiiiiiiji=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Ka=t.dynCall_iiiiiiiiiiiji=M.Kg)(n,i,o,a,l,p,h,y,b,_,S,k,z),Ya=t.dynCall_viifiifijjjii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Ya=t.dynCall_viifiifijjjii=M.Lg)(n,i,o,a,l,p,h,y,b,_,S,k,z),Za=t.dynCall_viiiiiiiiiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We)=>(Za=t.dynCall_viiiiiiiiiiiiiiiiiiii=M.Mg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We),Qa=t.dynCall_viiiiifiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Qa=t.dynCall_viiiiifiiiiii=M.Ng)(n,i,o,a,l,p,h,y,b,_,S,k,z),Xa=t.dynCall_vijiiiiiiijjii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T)=>(Xa=t.dynCall_vijiiiiiiijjii=M.Og)(n,i,o,a,l,p,h,y,b,_,S,k,z,T),Ja=t.dynCall_viiiiiiiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e)=>(Ja=t.dynCall_viiiiiiiiiiiiiiiiii=M.Pg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e),es=t.dynCall_viiiiiiiiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze)=>(es=t.dynCall_viiiiiiiiiiiiiiiiiii=M.Qg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze),ts=t.dynCall_viiiiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)=>(ts=t.dynCall_viiiiiiiiiiiiiii=M.Rg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y),rs=t.dynCall_viiiiiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie)=>(rs=t.dynCall_viiiiiiiiiiiiiiii=M.Sg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie),ns=t.dynCall_viiiijjj=(n,i,o,a,l,p,h,y)=>(ns=t.dynCall_viiiijjj=M.Tg)(n,i,o,a,l,p,h,y),is=t.dynCall_iiiiid=(n,i,o,a,l,p)=>(is=t.dynCall_iiiiid=M.Ug)(n,i,o,a,l,p),os=t.dynCall_viiiiiiijjj=(n,i,o,a,l,p,h,y,b,_,S)=>(os=t.dynCall_viiiiiiijjj=M.Vg)(n,i,o,a,l,p,h,y,b,_,S),as=t.dynCall_iiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S)=>(as=t.dynCall_iiiiiiiiiii=M.Wg)(n,i,o,a,l,p,h,y,b,_,S),ss=t.dynCall_iiiiiiiiiiiiiiiiiifi=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze)=>(ss=t.dynCall_iiiiiiiiiiiiiiiiiifi=M.Xg)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze),us=t.dynCall_viiif=(n,i,o,a,l)=>(us=t.dynCall_viiif=M.Yg)(n,i,o,a,l),ls=t.dynCall_viiijiiiii=(n,i,o,a,l,p,h,y,b,_)=>(ls=t.dynCall_viiijiiiii=M.Zg)(n,i,o,a,l,p,h,y,b,_),ds=t.dynCall_viiij=(n,i,o,a,l)=>(ds=t.dynCall_viiij=M._g)(n,i,o,a,l),cs=t.dynCall_iijjj=(n,i,o,a,l)=>(cs=t.dynCall_iijjj=M.$g)(n,i,o,a,l),fs=t.dynCall_viiiiji=(n,i,o,a,l,p,h)=>(fs=t.dynCall_viiiiji=M.ah)(n,i,o,a,l,p,h),ps=t.dynCall_iijjji=(n,i,o,a,l,p)=>(ps=t.dynCall_iijjji=M.bh)(n,i,o,a,l,p),ms=t.dynCall_ijijji=(n,i,o,a,l,p)=>(ms=t.dynCall_ijijji=M.ch)(n,i,o,a,l,p),hs=t.dynCall_viiijjiii=(n,i,o,a,l,p,h,y,b)=>(hs=t.dynCall_viiijjiii=M.dh)(n,i,o,a,l,p,h,y,b),gs=t.dynCall_iiiiijji=(n,i,o,a,l,p,h,y)=>(gs=t.dynCall_iiiiijji=M.eh)(n,i,o,a,l,p,h,y),ys=t.dynCall_iiiifi=(n,i,o,a,l,p)=>(ys=t.dynCall_iiiifi=M.fh)(n,i,o,a,l,p),bs=t.dynCall_iiijii=(n,i,o,a,l,p)=>(bs=t.dynCall_iiijii=M.gh)(n,i,o,a,l,p),vs=t.dynCall_iiiiiiiiijii=(n,i,o,a,l,p,h,y,b,_,S,k)=>(vs=t.dynCall_iiiiiiiiijii=M.hh)(n,i,o,a,l,p,h,y,b,_,S,k),ws=t.dynCall_iiiijjii=(n,i,o,a,l,p,h,y)=>(ws=t.dynCall_iiiijjii=M.ih)(n,i,o,a,l,p,h,y),_s=t.dynCall_iiiiiijjjii=(n,i,o,a,l,p,h,y,b,_,S)=>(_s=t.dynCall_iiiiiijjjii=M.jh)(n,i,o,a,l,p,h,y,b,_,S),$s=t.dynCall_iiijiii=(n,i,o,a,l,p,h)=>($s=t.dynCall_iiijiii=M.kh)(n,i,o,a,l,p,h),Cs=t.dynCall_iiiiiiiijjjfi=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Cs=t.dynCall_iiiiiiiijjjfi=M.lh)(n,i,o,a,l,p,h,y,b,_,S,k,z),Ss=t.dynCall_iijiiii=(n,i,o,a,l,p,h)=>(Ss=t.dynCall_iijiiii=M.mh)(n,i,o,a,l,p,h),xs=t.dynCall_iijjjii=(n,i,o,a,l,p,h)=>(xs=t.dynCall_iijjjii=M.nh)(n,i,o,a,l,p,h),Is=t.dynCall_jij=(n,i,o)=>(Is=t.dynCall_jij=M.oh)(n,i,o),As=t.dynCall_iiji=(n,i,o,a)=>(As=t.dynCall_iiji=M.ph)(n,i,o,a),Ts=t.dynCall_iiif=(n,i,o,a)=>(Ts=t.dynCall_iiif=M.qh)(n,i,o,a),Es=t.dynCall_vidi=(n,i,o,a)=>(Es=t.dynCall_vidi=M.rh)(n,i,o,a),Ps=t.dynCall_vjiii=(n,i,o,a,l)=>(Ps=t.dynCall_vjiii=M.sh)(n,i,o,a,l),ks=t.dynCall_diiii=(n,i,o,a,l)=>(ks=t.dynCall_diiii=M.th)(n,i,o,a,l),Os=t.dynCall_diiiii=(n,i,o,a,l,p)=>(Os=t.dynCall_diiiii=M.uh)(n,i,o,a,l,p),Rs=t.dynCall_viiijjiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k)=>(Rs=t.dynCall_viiijjiiiiii=M.vh)(n,i,o,a,l,p,h,y,b,_,S,k),Bs=t.dynCall_viijjijjjjiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Bs=t.dynCall_viijjijjjjiii=M.wh)(n,i,o,a,l,p,h,y,b,_,S,k,z),Ds=t.dynCall_iiiij=(n,i,o,a,l)=>(Ds=t.dynCall_iiiij=M.xh)(n,i,o,a,l),zs=t.dynCall_viiijii=(n,i,o,a,l,p,h)=>(zs=t.dynCall_viiijii=M.yh)(n,i,o,a,l,p,h),Ms=t.dynCall_viijiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z)=>(Ms=t.dynCall_viijiiiiiiiii=M.zh)(n,i,o,a,l,p,h,y,b,_,S,k,z),js=t.dynCall_fiiii=(n,i,o,a,l)=>(js=t.dynCall_fiiii=M.Ah)(n,i,o,a,l),Us=t.dynCall_jfi=(n,i,o)=>(Us=t.dynCall_jfi=M.Bh)(n,i,o),Vs=t.dynCall_viiiiiiiiiiiiii=(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)=>(Vs=t.dynCall_viiiiiiiiiiiiii=M.Ch)(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V),Ws=t.dynCall_jiij=(n,i,o,a)=>(Ws=t.dynCall_jiij=M.Dh)(n,i,o,a),Ns=n=>(Ns=M.Eh)(n),Gs=()=>(Gs=M.Fh)(),Hs=n=>(Hs=M.Gh)(n),Ls=()=>(Ls=M.Hh)();t.___start_em_js=1275044,t.___stop_em_js=1275205;function vf(n,i,o,a){var l=G();try{return Ar(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function wf(n,i,o){var a=G();try{return Kr(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function _f(n,i,o){var a=G();try{tr(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function $f(n,i){var o=G();try{return Yr(n,i)}catch(a){if(N(o),a!==a+0)throw a;W(1,0)}}function Cf(n,i){var o=G();try{Tr(n,i)}catch(a){if(N(o),a!==a+0)throw a;W(1,0)}}function Sf(n,i,o,a){var l=G();try{return Xr(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function xf(n){var i=G();try{Er(n)}catch(o){if(N(i),o!==o+0)throw o;W(1,0)}}function If(n,i,o,a,l,p,h){var y=G();try{return Zr(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function Af(n,i,o,a,l,p){var h=G();try{return Qr(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function Tf(n,i,o,a,l){var p=G();try{return Jr(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Ef(n,i,o,a){var l=G();try{Pr(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function Pf(n,i,o,a,l){var p=G();try{kr(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function kf(n,i,o,a,l,p){var h=G();try{rr(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function Of(n,i,o,a,l,p,h){var y=G();try{en(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function Rf(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{rn(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function Bf(n,i,o){var a=G();try{return on(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function Df(n,i,o){var a=G();try{return Nn(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function zf(n,i,o){var a=G();try{return nr(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function Mf(n,i,o){var a=G();try{return an(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;return W(1,0),0n}}function jf(n,i,o,a,l,p,h,y,b){var _=G();try{v(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function Uf(n){var i=G();try{return m(n)}catch(o){if(N(i),o!==o+0)throw o;W(1,0)}}function Vf(n,i,o){var a=G();try{ve(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function Wf(n,i,o,a,l){var p=G();try{tn(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Nf(n,i,o,a,l,p,h){var y=G();try{I(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function Gf(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{Me(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function Hf(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{je(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function Lf(n,i,o,a,l,p,h,y){var b=G();try{return q(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function Ff(n,i,o,a,l,p,h,y){var b=G();try{Ie(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function qf(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{return Q(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function Kf(n,i,o,a,l,p,h,y,b,_){var S=G();try{re(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function Yf(n,i,o,a,l,p,h,y,b,_,S,k,z,T){var V=G();try{kt(n,i,o,a,l,p,h,y,b,_,S,k,z,T)}catch(Y){if(N(V),Y!==Y+0)throw Y;W(1,0)}}function Zf(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{return yo(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function Qf(n,i,o,a,l,p,h,y,b){var _=G();try{return sn(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function Xf(n,i,o,a,l,p,h,y,b){var _=G();try{bo(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function Jf(n,i,o,a){var l=G();try{H(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function ep(n,i){var o=G();try{return vo(n,i)}catch(a){if(N(o),a!==a+0)throw a;W(1,0)}}function tp(n,i){var o=G();try{return D(n,i)}catch(a){if(N(o),a!==a+0)throw a;return W(1,0),0n}}function rp(n,i){var o=G();try{return _o(n,i)}catch(a){if(N(o),a!==a+0)throw a;W(1,0)}}function np(n,i,o,a){var l=G();try{Co(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function ip(n,i,o,a,l,p,h){var y=G();try{zs(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function op(n,i,o,a,l){var p=G();try{Ta(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function ap(n,i,o,a,l,p,h,y,b,_){var S=G();try{return So(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function sp(n,i,o,a,l,p,h){var y=G();try{xo(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function up(n,i,o,a){var l=G();try{Io(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function lp(n,i,o,a,l,p,h,y,b){var _=G();try{return Ue(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function dp(n,i,o,a,l,p,h){var y=G();try{Ao(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function cp(n,i,o,a,l,p,h,y,b){var _=G();try{nn(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function fp(n,i,o,a,l,p,h){var y=G();try{To(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function pp(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{Eo(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function mp(n,i,o,a){var l=G();try{return ko(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;return W(1,0),0n}}function hp(n,i,o,a,l,p,h,y){var b=G();try{Oo(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function gp(n,i,o,a,l){var p=G();try{Ro(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function yp(n,i,o,a){var l=G();try{Do(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function bp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y){var ie=G();try{zo(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)}catch(de){if(N(ie),de!==de+0)throw de;W(1,0)}}function vp(n,i,o,a,l,p){var h=G();try{Mo(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function wp(n,i,o,a,l,p,h,y,b){var _=G();try{jo(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function _p(n,i,o,a,l){var p=G();try{return Uo(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function $p(n,i,o,a,l,p,h,y,b,_,S,k,z,T){var V=G();try{return Vo(n,i,o,a,l,p,h,y,b,_,S,k,z,T)}catch(Y){if(N(V),Y!==Y+0)throw Y;W(1,0)}}function Cp(n,i){var o=G();try{Wo(n,i)}catch(a){if(N(o),a!==a+0)throw a;W(1,0)}}function Sp(n,i,o){var a=G();try{return No(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;return W(1,0),0n}}function xp(n,i,o,a,l,p,h,y,b,_){var S=G();try{return Go(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function Ip(n,i,o,a,l,p,h,y,b,_,S,k,z,T){var V=G();try{Ko(n,i,o,a,l,p,h,y,b,_,S,k,z,T)}catch(Y){if(N(V),Y!==Y+0)throw Y;W(1,0)}}function Ap(n,i,o,a,l){var p=G();try{Ho(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Tp(n,i,o,a,l,p,h){var y=G();try{Lo(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function Ep(n,i,o,a,l){var p=G();try{qo(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Pp(n,i,o,a,l,p,h,y){var b=G();try{Fo(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function kp(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{Yo(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function Op(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie){var de=G();try{return Zo(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie)}catch($e){if(N(de),$e!==$e+0)throw $e;W(1,0)}}function Rp(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{Qo(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function Bp(n,i){var o=G();try{return ye(n,i)}catch(a){if(N(o),a!==a+0)throw a;W(1,0)}}function Dp(n,i,o,a,l){var p=G();try{return js(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function zp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze){var We=G();try{return Xo(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze)}catch(et){if(N(We),et!==et+0)throw et;W(1,0)}}function Mp(n,i,o,a,l,p,h,y,b,_){var S=G();try{Jo(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function jp(n,i,o,a,l,p,h){var y=G();try{return ea(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function Up(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{ta(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function Vp(n,i,o,a,l,p){var h=G();try{return ra(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function Wp(n,i,o,a,l,p){var h=G();try{ia(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function Np(n,i,o,a,l,p,h,y,b,_,S,k,z,T){var V=G();try{oa(n,i,o,a,l,p,h,y,b,_,S,k,z,T)}catch(Y){if(N(V),Y!==Y+0)throw Y;W(1,0)}}function Gp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de){var $e=G();try{aa(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de)}catch(ze){if(N($e),ze!==ze+0)throw ze;W(1,0)}}function Hp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie){var de=G();try{sa(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie)}catch($e){if(N(de),$e!==$e+0)throw $e;W(1,0)}}function Lp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y){var ie=G();try{ua(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)}catch(de){if(N(ie),de!==de+0)throw de;W(1,0)}}function Fp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V){var Y=G();try{la(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)}catch(ie){if(N(Y),ie!==ie+0)throw ie;W(1,0)}}function qp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We){var et=G();try{da(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We)}catch(dt){if(N(et),dt!==dt+0)throw dt;W(1,0)}}function Kp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e){var ze=G();try{ca(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e)}catch(We){if(N(ze),We!==We+0)throw We;W(1,0)}}function Yp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de){var $e=G();try{fa(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de)}catch(ze){if(N($e),ze!==ze+0)throw ze;W(1,0)}}function Zp(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We){var et=G();try{pa(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We)}catch(dt){if(N(et),dt!==dt+0)throw dt;W(1,0)}}function Qp(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{ma(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function Xp(n,i,o,a,l,p,h,y,b,_){var S=G();try{ha(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function Jp(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{ga(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function em(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V){var Y=G();try{ya(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)}catch(ie){if(N(Y),ie!==ie+0)throw ie;W(1,0)}}function tm(n,i,o,a,l,p,h,y,b,_){var S=G();try{va(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function rm(n,i,o,a,l,p,h,y,b){var _=G();try{wa(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function nm(n,i,o,a,l,p,h){var y=G();try{return na(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function im(n,i,o,a,l){var p=G();try{ba(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function om(n,i,o){var a=G();try{return Us(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;return W(1,0),0n}}function am(n,i,o,a,l,p,h,y,b,_,S,k,z,T){var V=G();try{_a(n,i,o,a,l,p,h,y,b,_,S,k,z,T)}catch(Y){if(N(V),Y!==Y+0)throw Y;W(1,0)}}function sm(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{Ca(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function um(n,i,o,a,l,p,h){var y=G();try{return Sa(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function lm(n,i,o,a,l,p){var h=G();try{return xa(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function dm(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{Ia(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function cm(n,i,o,a,l,p){var h=G();try{$a(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function fm(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{Aa(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function pm(n,i,o,a,l,p,h,y){var b=G();try{Ea(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function mm(n,i,o,a,l,p,h,y){var b=G();try{Pa(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function hm(n,i,o,a){var l=G();try{return ka(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function gm(n,i,o,a,l,p,h,y,b,_){var S=G();try{Oa(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function ym(n,i,o,a,l,p,h,y,b){var _=G();try{Ra(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function bm(n,i,o,a,l,p,h,y,b){var _=G();try{Ba(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function vm(n,i,o,a,l,p,h,y,b,_){var S=G();try{Da(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function wm(n,i,o,a,l,p){var h=G();try{za(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function _m(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{Ma(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function $m(n,i,o,a,l,p,h,y){var b=G();try{return ja(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function Cm(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V){var Y=G();try{Vs(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)}catch(ie){if(N(Y),ie!==ie+0)throw ie;W(1,0)}}function Sm(n,i,o,a,l,p,h,y,b,_,S,k,z,T){var V=G();try{Ua(n,i,o,a,l,p,h,y,b,_,S,k,z,T)}catch(Y){if(N(V),Y!==Y+0)throw Y;W(1,0)}}function xm(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V){var Y=G();try{Va(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V)}catch(ie){if(N(Y),ie!==ie+0)throw ie;W(1,0)}}function Im(n,i,o){var a=G();try{Wa(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function Am(n,i,o,a){var l=G();try{return Ga(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function Tm(n,i,o,a){var l=G();try{return Ha(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function Em(n,i,o,a,l,p,h,y,b,_){var S=G();try{La(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function Pm(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We,et,dt,Ci,Si,xi){var Ph=G();try{Fa(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We,et,dt,Ci,Si,xi)}catch(Ii){if(N(Ph),Ii!==Ii+0)throw Ii;W(1,0)}}function km(n,i,o,a,l,p){var h=G();try{qa(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function Om(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{return Ka(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function Rm(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{Ya(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function Bm(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We){var et=G();try{Za(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze,We)}catch(dt){if(N(et),dt!==dt+0)throw dt;W(1,0)}}function Dm(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{Qa(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function zm(n,i,o,a,l,p,h,y,b,_,S,k,z,T){var V=G();try{Xa(n,i,o,a,l,p,h,y,b,_,S,k,z,T)}catch(Y){if(N(V),Y!==Y+0)throw Y;W(1,0)}}function Mm(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze){var We=G();try{es(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze)}catch(et){if(N(We),et!==et+0)throw et;W(1,0)}}function jm(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie){var de=G();try{rs(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie)}catch($e){if(N(de),$e!==$e+0)throw $e;W(1,0)}}function Um(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e){var ze=G();try{Ja(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e)}catch(We){if(N(ze),We!==We+0)throw We;W(1,0)}}function Vm(n,i,o,a,l,p,h,y){var b=G();try{ns(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function Wm(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{os(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function Nm(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{return as(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function Gm(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze){var We=G();try{return ss(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y,ie,de,$e,ze)}catch(et){if(N(We),et!==et+0)throw et;W(1,0)}}function Hm(n,i,o,a,l){var p=G();try{us(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Lm(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{Po(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function Fm(n,i,o,a,l,p,h,y,b,_){var S=G();try{ls(n,i,o,a,l,p,h,y,b,_)}catch(k){if(N(S),k!==k+0)throw k;W(1,0)}}function qm(n,i,o,a,l){var p=G();try{ds(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Km(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{Ms(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function Ym(n,i,o,a,l){var p=G();try{return cs(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Zm(n,i,o,a){var l=G();try{return Ws(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;return W(1,0),0n}}function Qm(n,i,o,a,l,p,h){var y=G();try{fs(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function Xm(n,i,o,a,l,p){var h=G();try{return ps(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function Jm(n,i,o,a,l,p){var h=G();try{return ms(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function eh(n,i,o,a,l,p,h,y,b){var _=G();try{hs(n,i,o,a,l,p,h,y,b)}catch(S){if(N(_),S!==S+0)throw S;W(1,0)}}function th(n,i,o,a){var l=G();try{Na(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function rh(n,i,o,a,l,p,h,y){var b=G();try{return gs(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function nh(n,i,o,a,l,p){var h=G();try{return ys(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function ih(n,i,o,a,l,p){var h=G();try{return bs(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function oh(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{return vs(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function ah(n,i,o,a,l,p,h,y){var b=G();try{return ws(n,i,o,a,l,p,h,y)}catch(_){if(N(b),_!==_+0)throw _;W(1,0)}}function sh(n,i,o,a,l,p,h,y,b,_,S){var k=G();try{return _s(n,i,o,a,l,p,h,y,b,_,S)}catch(z){if(N(k),z!==z+0)throw z;W(1,0)}}function uh(n,i,o,a,l,p,h){var y=G();try{return $s(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function lh(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{return Cs(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function dh(n,i,o,a,l,p,h){var y=G();try{return Ss(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function ch(n,i,o,a,l,p,h){var y=G();try{return xs(n,i,o,a,l,p,h)}catch(b){if(N(y),b!==b+0)throw b;W(1,0)}}function fh(n,i,o){var a=G();try{return Is(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;return W(1,0),0n}}function ph(n,i,o,a){var l=G();try{return As(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function mh(n,i,o,a){var l=G();try{Es(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function hh(n,i,o,a){var l=G();try{return Ts(n,i,o,a)}catch(p){if(N(l),p!==p+0)throw p;W(1,0)}}function gh(n,i,o,a,l){var p=G();try{Ps(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function yh(n,i,o,a,l){var p=G();try{return ks(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function bh(n,i,o,a,l,p){var h=G();try{return Os(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function vh(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{Rs(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function wh(n,i,o,a,l,p,h,y,b,_,S,k,z){var T=G();try{Bs(n,i,o,a,l,p,h,y,b,_,S,k,z)}catch(V){if(N(T),V!==V+0)throw V;W(1,0)}}function _h(n,i,o,a,l,p,h,y,b,_,S,k){var z=G();try{Bo(n,i,o,a,l,p,h,y,b,_,S,k)}catch(T){if(N(z),T!==T+0)throw T;W(1,0)}}function $h(n,i,o,a,l){var p=G();try{return Ds(n,i,o,a,l)}catch(h){if(N(p),h!==h+0)throw h;W(1,0)}}function Ch(n){var i=G();try{return fe(n)}catch(o){if(N(i),o!==o+0)throw o;return W(1,0),0n}}function Sh(n,i,o,a,l,p){var h=G();try{return he(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function xh(n,i,o,a,l,p){var h=G();try{return is(n,i,o,a,l,p)}catch(y){if(N(h),y!==y+0)throw y;W(1,0)}}function Ih(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y){var ie=G();try{ts(n,i,o,a,l,p,h,y,b,_,S,k,z,T,V,Y)}catch(de){if(N(ie),de!==de+0)throw de;W(1,0)}}function Ah(n,i,o){var a=G();try{return wo(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function Th(n,i,o){var a=G();try{return $o(n,i,o)}catch(l){if(N(a),l!==l+0)throw l;W(1,0)}}function Eh(){var n=M;n=Object.assign({},n);var i=o=>a=>o(a)>>>0;return n.Fd=i(n.Fd),n.he=i(n.he),n.ne=i(n.ne),n.oe=(o=>()=>o()>>>0)(n.oe),n}t.stackSave=()=>G(),t.stackRestore=n=>N(n),t.stackAlloc=n=>Mn(n),t.UTF8ToString=qe,t.stringToUTF8=(n,i,o)=>vt(n,oe,i,o),t.lengthBytesUTF8=Kt;var Gn;ee=function n(){Gn||Fs(),Gn||(ee=n)};function Fs(){if(!(0<_e)){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;){var n=t.preRun.shift();Ce.unshift(n)}for(;0Ks)});var Qs=un(()=>{});var Xs=un(()=>{});var Js={};Hn(Js,{cpus:()=>jh});var jh,eu=ae(()=>{jh=void 0});var nu=un((ru,ki)=>{"use strict";var tu=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(r={}){function t(){return we.buffer!=Ce.buffer&&ee(),Ce}function u(){return we.buffer!=Ce.buffer&&ee(),be}function s(){return we.buffer!=Ce.buffer&&ee(),Ae}function c(){return we.buffer!=Ce.buffer&&ee(),_e}function f(){return we.buffer!=Ce.buffer&&ee(),Je}var d=r,g,w;d.ready=new Promise((m,v)=>{g=m,w=v}),d.jsepInit=(m,v,I,D,H,Q,re,ye)=>{d.Qb=m,d.wb=v,d.yb=I,d.jb=D,d.xb=H,d.Ea=Q,d.zb=re,d.Ab=ye,v=(he,fe,ve)=>(...Me)=>{let je=lt,q=fe?.();Me=he(...Me);let Ie=fe?.();return q!==Ie&&(he=Ie,ve(q),fe=ve=null),lt!=je?N():Me},I=he=>async(...fe)=>{try{if(d.bb)throw Error("Session already started");let ve=d.bb={Fb:fe[0],errors:[]},Me=await he(...fe);if(d.bb!==ve)throw Error("Session mismatch");m.flush();let je=ve.errors;if(0Ie),0d._OrtRun,he=>d._OrtRun=he)),d._OrtRunWithBinding=I(v(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,he=>d._OrtRunWithBinding=he)),d._OrtBindInput=v(d._OrtBindInput,()=>d._OrtBindInput,he=>d._OrtBindInput=he),d.jsepRegisterBuffer=(he,fe,ve,Me)=>m.registerBuffer(he,fe,ve,Me),d.jsepUnregisterBuffers=he=>{m.unregisterBuffers(he)},d.jsepGetBuffer=he=>m.getBuffer(he),d.jsepCreateDownloader=(he,fe,ve)=>m.createDownloader(he,fe,ve)};var C=Object.assign({},d),$="./this.program",A=(m,v)=>{throw v},P=typeof window=="object",x=typeof importScripts=="function",E=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",O=d.ENVIRONMENT_IS_PTHREAD||!1,B="";function R(m){return d.locateFile?d.locateFile(m,B):B+m}var j,U,L;if(E){var F=(Fn(),ir(Ln)),te=(Ei(),ir(Ti));B=x?te.dirname(B)+"/":__dirname+"/",j=(v,I)=>(v=v.startsWith("file://")?new URL(v):te.normalize(v),F.readFileSync(v,I?void 0:"utf8")),L=v=>(v=j(v,!0),v.buffer||(v=new Uint8Array(v)),v),U=(v,I,D,H=!0)=>{v=v.startsWith("file://")?new URL(v):te.normalize(v),F.readFile(v,H?void 0:"utf8",(Q,re)=>{Q?D(Q):I(H?re.buffer:re)})},!d.thisProgram&&1{throw process.exitCode=v,I},d.inspect=()=>"[Emscripten Module object]";let m;try{m=Qs()}catch(v){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),v}global.Worker=m.Worker}else(P||x)&&(x?B=self.location.href:typeof document<"u"&&document.currentScript&&(B=document.currentScript.src),typeof e<"u"&&e&&(B=e),B.indexOf("blob:")!==0?B=B.substr(0,B.replace(/[?#].*/,"").lastIndexOf("/")+1):B="",E||(j=m=>{var v=new XMLHttpRequest;return v.open("GET",m,!1),v.send(null),v.responseText},x&&(L=m=>{var v=new XMLHttpRequest;return v.open("GET",m,!1),v.responseType="arraybuffer",v.send(null),new Uint8Array(v.response)}),U=(m,v,I)=>{var D=new XMLHttpRequest;D.open("GET",m,!0),D.responseType="arraybuffer",D.onload=()=>{D.status==200||D.status==0&&D.response?v(D.response):I()},D.onerror=I,D.send(null)}));E&&typeof performance>"u"&&(global.performance=Xs().performance);var J=console.log.bind(console),oe=console.error.bind(console);E&&(J=(...m)=>F.writeSync(1,m.join(" ")+`\n`),oe=(...m)=>F.writeSync(2,m.join(" ")+`\n`));var le=d.print||J,ge=d.printErr||oe;Object.assign(d,C),C=null,d.thisProgram&&($=d.thisProgram),d.quit&&(A=d.quit);var X;d.wasmBinary&&(X=d.wasmBinary);var pe=d.noExitRuntime||!0;typeof WebAssembly!="object"&&pt("no native wasm support detected");var we,ue,me,Ee=!1,Pe,Ce,be,Ae,_e,Je;function ee(){var m=we.buffer;d.HEAP8=Ce=new Int8Array(m),d.HEAP16=new Int16Array(m),d.HEAP32=Ae=new Int32Array(m),d.HEAPU8=be=new Uint8Array(m),d.HEAPU16=new Uint16Array(m),d.HEAPU32=_e=new Uint32Array(m),d.HEAPF32=new Float32Array(m),d.HEAPF64=Je=new Float64Array(m)}var ce=d.INITIAL_MEMORY||16777216;if(5242880<=ce||pt("INITIAL_MEMORY should be larger than STACK_SIZE, was "+ce+"! (STACK_SIZE=5242880)"),O)we=d.wasmMemory;else if(d.wasmMemory)we=d.wasmMemory;else if(we=new WebAssembly.Memory({initial:ce/65536,maximum:65536,shared:!0}),!(we.buffer instanceof SharedArrayBuffer))throw ge("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"),E&&ge("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");ee(),ce=we.buffer.byteLength;var Be=[],tt=[],Ye=[],Ke=0;function Pt(){return pe||0{if(!v.ok)throw"failed to load wasm binary file at \'"+m+"\'";return v.arrayBuffer()}).catch(()=>cr(m));if(U)return new Promise((v,I)=>{U(m,D=>v(new Uint8Array(D)),I)})}return Promise.resolve().then(()=>cr(m))}function zr(m,v,I){return fr(m).then(D=>WebAssembly.instantiate(D,v)).then(D=>D).then(I,D=>{ge("failed to asynchronously prepare wasm: "+D),pt(D)})}function hn(m,v){var I=ut;return X||typeof WebAssembly.instantiateStreaming!="function"||qt(I)||I.startsWith("file://")||E||typeof fetch!="function"?zr(I,m,v):fetch(I,{credentials:"same-origin"}).then(D=>WebAssembly.instantiateStreaming(D,m).then(v,function(H){return ge("wasm streaming compile failed: "+H),ge("falling back to ArrayBuffer instantiation"),zr(I,m,v)}))}var qe,Kt={906828:m=>{d.Ea("Abs",m,void 0)},906879:m=>{d.Ea("Neg",m,void 0)},906930:m=>{d.Ea("Floor",m,void 0)},906983:m=>{d.Ea("Ceil",m,void 0)},907035:m=>{d.Ea("Reciprocal",m,void 0)},907093:m=>{d.Ea("Sqrt",m,void 0)},907145:m=>{d.Ea("Exp",m,void 0)},907196:m=>{d.Ea("Erf",m,void 0)},907247:m=>{d.Ea("Sigmoid",m,void 0)},907302:m=>{d.Ea("Log",m,void 0)},907353:m=>{d.Ea("Sin",m,void 0)},907404:m=>{d.Ea("Cos",m,void 0)},907455:m=>{d.Ea("Tan",m,void 0)},907506:m=>{d.Ea("Asin",m,void 0)},907558:m=>{d.Ea("Acos",m,void 0)},907610:m=>{d.Ea("Atan",m,void 0)},907662:m=>{d.Ea("Sinh",m,void 0)},907714:m=>{d.Ea("Cosh",m,void 0)},907766:m=>{d.Ea("Asinh",m,void 0)},907819:m=>{d.Ea("Acosh",m,void 0)},907872:m=>{d.Ea("Atanh",m,void 0)},907925:m=>{d.Ea("Tanh",m,void 0)},907977:m=>{d.Ea("Not",m,void 0)},908028:(m,v,I)=>{d.Ea("ClipV10",m,{min:v,max:I})},908100:m=>{d.Ea("Clip",m,void 0)},908152:(m,v)=>{d.Ea("Elu",m,{alpha:v})},908210:m=>{d.Ea("Relu",m,void 0)},908262:(m,v)=>{d.Ea("LeakyRelu",m,{alpha:v})},908326:(m,v)=>{d.Ea("ThresholdedRelu",m,{alpha:v})},908396:(m,v)=>{d.Ea("Cast",m,{to:v})},908454:m=>{d.Ea("Add",m,void 0)},908505:m=>{d.Ea("Sub",m,void 0)},908556:m=>{d.Ea("Mul",m,void 0)},908607:m=>{d.Ea("Div",m,void 0)},908658:m=>{d.Ea("Pow",m,void 0)},908709:m=>{d.Ea("Equal",m,void 0)},908762:m=>{d.Ea("Greater",m,void 0)},908817:m=>{d.Ea("GreaterOrEqual",m,void 0)},908879:m=>{d.Ea("Less",m,void 0)},908931:m=>{d.Ea("LessOrEqual",m,void 0)},908990:(m,v,I,D,H)=>{d.Ea("ReduceMean",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},909154:(m,v,I,D,H)=>{d.Ea("ReduceMax",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},909317:(m,v,I,D,H)=>{d.Ea("ReduceMin",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},909480:(m,v,I,D,H)=>{d.Ea("ReduceProd",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},909644:(m,v,I,D,H)=>{d.Ea("ReduceSum",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},909807:(m,v,I,D,H)=>{d.Ea("ReduceL1",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},909969:(m,v,I,D,H)=>{d.Ea("ReduceL2",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},910131:(m,v,I,D,H)=>{d.Ea("ReduceLogSum",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},910297:(m,v,I,D,H)=>{d.Ea("ReduceSumSquare",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},910466:(m,v,I,D,H)=>{d.Ea("ReduceLogSumExp",m,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},910635:m=>{d.Ea("Where",m,void 0)},910688:(m,v,I)=>{d.Ea("Transpose",m,{perm:v?Array.from(s().subarray(I>>>0,I+v>>>0)):[]})},910801:(m,v,I,D,H,Q,re,ye,he,fe)=>{d.Ea("Conv",m,{format:he?"NHWC":"NCHW",auto_pad:v,dilations:[I],group:D,kernel_shape:[H],pads:[Q,re],strides:[ye],w_is_const:()=>!!t()[fe>>>0]})},911029:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q,Ie)=>{d.Ea("Conv",m,{format:q?"NHWC":"NCHW",auto_pad:v,dilations:[I,D],group:H,kernel_shape:[Q,re],pads:[ye,he,fe,ve],strides:[Me,je],w_is_const:()=>!!t()[Ie>>>0]})},911288:(m,v,I,D,H,Q,re,ye,he,fe)=>{d.Ea("Conv",m,{format:he?"NHWC":"NCHW",auto_pad:v,dilations:[I],group:D,kernel_shape:[H],pads:[Q,re],strides:[ye],w_is_const:()=>!!t()[fe>>>0]})},911516:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q,Ie)=>{d.Ea("Conv",m,{format:q?"NHWC":"NCHW",auto_pad:v,dilations:[I,D],group:H,kernel_shape:[Q,re],pads:[ye,he,fe,ve],strides:[Me,je],w_is_const:()=>!!t()[Ie>>>0]})},911775:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q)=>{d.Ea("ConvTranspose",m,{format:he?"NHWC":"NCHW",autoPad:v,dilations:[I],group:D,kernel_shape:[H],pads:[Q,re],strides:[ye],wIsConst:()=>!!t()[fe>>>0],outputPadding:ve?Array.from(s().subarray(Me>>>0,Me+ve>>>0)):[],outputShape:je?Array.from(s().subarray(q>>>0,q+je>>>0)):[]})},912155:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je)=>{d.Ea("ConvTranspose",m,{format:ye?"NHWC":"NCHW",autoPad:v,dilations:Array.from(s().subarray(I>>>0,I+2>>>0)),group:D,kernelShape:Array.from(s().subarray(H>>>0,H+2>>>0)),pads:Array.from(s().subarray(Q>>>0,Q+4>>>0)),strides:Array.from(s().subarray(re>>>0,re+2>>>0)),wIsConst:()=>!!t()[he>>>0],outputPadding:0>>0,ve+fe>>>0)):[],outputShape:0>>0,je+Me>>>0)):[]})},912678:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q)=>{d.Ea("ConvTranspose",m,{format:he?"NHWC":"NCHW",autoPad:v,dilations:[I],group:D,kernel_shape:[H],pads:[Q,re],strides:[ye],wIsConst:()=>!!t()[fe>>>0],outputPadding:ve?Array.from(s().subarray(Me>>>0,Me+ve>>>0)):[],outputShape:je?Array.from(s().subarray(q>>>0,q+je>>>0)):[]})},913058:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je)=>{d.Ea("ConvTranspose",m,{format:ye?"NHWC":"NCHW",autoPad:v,dilations:Array.from(s().subarray(I>>>0,I+2>>>0)),group:D,kernelShape:Array.from(s().subarray(H>>>0,H+2>>>0)),pads:Array.from(s().subarray(Q>>>0,Q+4>>>0)),strides:Array.from(s().subarray(re>>>0,re+2>>>0)),wIsConst:()=>!!t()[he>>>0],outputPadding:0>>0,ve+fe>>>0)):[],outputShape:0>>0,je+Me>>>0)):[]})},913581:(m,v)=>{d.Ea("GlobalAveragePool",m,{format:v?"NHWC":"NCHW"})},913672:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q,Ie,Ue)=>{d.Ea("AveragePool",m,{format:Ue?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:D,storage_order:H,dilations:[Q,re],kernel_shape:[ye,he],pads:[fe,ve,Me,je],strides:[q,Ie]})},913956:(m,v)=>{d.Ea("GlobalAveragePool",m,{format:v?"NHWC":"NCHW"})},914047:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q,Ie,Ue)=>{d.Ea("AveragePool",m,{format:Ue?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:D,storage_order:H,dilations:[Q,re],kernel_shape:[ye,he],pads:[fe,ve,Me,je],strides:[q,Ie]})},914331:(m,v)=>{d.Ea("GlobalMaxPool",m,{format:v?"NHWC":"NCHW"})},914418:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q,Ie,Ue)=>{d.Ea("MaxPool",m,{format:Ue?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:D,storage_order:H,dilations:[Q,re],kernel_shape:[ye,he],pads:[fe,ve,Me,je],strides:[q,Ie]})},914698:(m,v)=>{d.Ea("GlobalMaxPool",m,{format:v?"NHWC":"NCHW"})},914785:(m,v,I,D,H,Q,re,ye,he,fe,ve,Me,je,q,Ie,Ue)=>{d.Ea("MaxPool",m,{format:Ue?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:D,storage_order:H,dilations:[Q,re],kernel_shape:[ye,he],pads:[fe,ve,Me,je],strides:[q,Ie]})},915065:(m,v,I,D,H)=>{d.Ea("Gemm",m,{alpha:v,beta:I,transA:D,transB:H})},915169:m=>{d.Ea("MatMul",m,void 0)},915223:(m,v,I,D)=>{d.Ea("ArgMax",m,{keepDims:!!v,selectLastIndex:!!I,axis:D})},915331:(m,v,I,D)=>{d.Ea("ArgMin",m,{keepDims:!!v,selectLastIndex:!!I,axis:D})},915439:(m,v)=>{d.Ea("Softmax",m,{axis:v})},915502:(m,v)=>{d.Ea("Concat",m,{axis:v})},915562:(m,v,I,D,H)=>{d.Ea("Split",m,{axis:v,numOutputs:I,splitSizes:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},915707:m=>{d.Ea("Expand",m,void 0)},915761:(m,v)=>{d.Ea("Gather",m,{axis:Number(v)})},915832:(m,v)=>{d.Ea("GatherElements",m,{axis:Number(v)})},915911:(m,v,I,D,H,Q,re,ye,he,fe,ve)=>{d.Ea("Resize",m,{antialias:v,axes:I?Array.from(s().subarray(D>>>0,D+I>>>0)):[],coordinateTransformMode:it(H),cubicCoeffA:Q,excludeOutside:re,extrapolationValue:ye,keepAspectRatioPolicy:it(he),mode:it(fe),nearestMode:it(ve)})},916262:(m,v,I,D,H,Q,re)=>{d.Ea("Slice",m,{starts:v?Array.from(s().subarray(I>>>0,I+v>>>0)):[],ends:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[],axes:Q?Array.from(s().subarray(re>>>0,re+Q>>>0)):[]})},916493:m=>{d.Ea("Tile",m,void 0)},916545:(m,v,I)=>{d.Ea("LayerNormalization",m,{axis:Number(v),epsilon:Number(I)})},916652:(m,v,I)=>{d.Ea("InstanceNormalization",m,{epsilon:v,format:I?"NHWC":"NCHW"})},916766:(m,v,I)=>{d.Ea("InstanceNormalization",m,{epsilon:v,format:I?"NHWC":"NCHW"})},916880:m=>{d.Ea("Range",m,void 0)},916933:(m,v)=>{d.Ea("Einsum",m,{equation:it(v)})},917014:(m,v,I,D,H)=>{d.Ea("Pad",m,{mode:v,value:I,pads:D?Array.from(s().subarray(H>>>0,H+D>>>0)):[]})},917146:m=>{d.Ea("Gelu",m,void 0)},917198:m=>{d.Ea("BiasAdd",m,void 0)},917253:m=>{d.Ea("BiasSplitGelu",m,void 0)},917314:(m,v)=>{d.Ea("SkipLayerNormalization",m,{epsilon:v})},917395:m=>{d.zb(m)},917429:(m,v)=>d.Ab(m,v,d.bb.Fb,d.bb.errors),917541:m=>d.wb(m),917574:m=>d.yb(m),917606:(m,v,I)=>{d.jb(m,v,I,!0)},917645:(m,v,I)=>{d.jb(m,v,I)}};function vt(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}function pr(m){m.terminate(),m.onmessage=()=>{}}function mt(m){(m=Se.Qa[m])||pt(),Se.Eb(m)}function mr(m){var v=Se.tb();if(!v)return 6;Se.Ya.push(v),Se.Qa[m.Xa]=v,v.Xa=m.Xa;var I={cmd:"run",start_routine:m.Gb,arg:m.rb,pthread_ptr:m.Xa};return E&&v.unref(),v.postMessage(I,m.Mb),0}var hr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,gn=(m,v,I)=>{v>>>=0;var D=v+I;for(I=v;m[I]&&!(I>=D);)++I;if(16H?D+=String.fromCharCode(H):(H-=65536,D+=String.fromCharCode(55296|H>>10,56320|H&1023))}}else D+=String.fromCharCode(H)}return D},it=(m,v)=>(m>>>=0)?gn(u(),m,v):"";function yn(m){if(O)return Ge(1,1,m);Pe=m,Pt()||(Se.Hb(),d.onExit&&d.onExit(m),Ee=!0),A(m,new vt(m))}var ht=m=>{if(Pe=m,O)throw wt(m),"unwind";yn(m)},Se={ab:[],Ya:[],mb:[],Qa:{},gb:function(){O?Se.vb():Se.ub()},ub:function(){Be.unshift(()=>{Ut(),Se.Bb(()=>Vt())})},vb:function(){Se.receiveObjectTransfer=Se.Db,Se.threadInitTLS=Se.lb,Se.setExitStatus=Se.kb,pe=!1},kb:function(m){Pe=m},Sb:["$terminateWorker"],Hb:function(){for(var m of Se.Ya)pr(m);for(m of Se.ab)pr(m);Se.ab=[],Se.Ya=[],Se.Qa=[]},Eb:function(m){var v=m.Xa;delete Se.Qa[v],Se.ab.push(m),Se.Ya.splice(Se.Ya.indexOf(m),1),m.Xa=0,Tr(v)},Db:function(){},lb:function(){Se.mb.forEach(m=>m())},Cb:m=>new Promise(v=>{m.onmessage=Q=>{Q=Q.data;var re=Q.cmd;if(Q.targetThread&&Q.targetThread!=tr()){var ye=Se.Qa[Q.Rb];ye?ye.postMessage(Q,Q.transferList):ge(\'Internal error! Worker sent a message "\'+re+\'" to target pthread \'+Q.targetThread+", but that thread no longer exists!")}else re==="checkMailbox"?Qt():re==="spawnThread"?mr(Q):re==="cleanupThread"?mt(Q.thread):re==="killThread"?(Q=Q.thread,re=Se.Qa[Q],delete Se.Qa[Q],pr(re),Tr(Q),Se.Ya.splice(Se.Ya.indexOf(re),1),re.Xa=0):re==="cancelThread"?Se.Qa[Q.thread].postMessage({cmd:"cancel"}):re==="loaded"?(m.loaded=!0,v(m)):re==="alert"?alert("Thread "+Q.threadId+": "+Q.text):Q.target==="setimmediate"?m.postMessage(Q):re==="callHandler"?d[Q.handler](...Q.args):re&&ge("worker sent an unknown command "+re)},m.onerror=Q=>{throw ge("worker sent an error! "+Q.filename+":"+Q.lineno+": "+Q.message),Q},E&&(m.on("message",function(Q){m.onmessage({data:Q})}),m.on("error",function(Q){m.onerror(Q)}));var I=[],D=["onExit","onAbort","print","printErr"],H;for(H of D)d.hasOwnProperty(H)&&I.push(H);m.postMessage({cmd:"load",handlers:I,urlOrBlob:d.mainScriptUrlOrBlob||e,wasmMemory:we,wasmModule:me})}),Bb:function(m){m()},qb:function(){var m=R("ort-wasm-simd-threaded.worker.js");m=new Worker(m),Se.ab.push(m)},tb:function(){return Se.ab.length==0&&(Se.qb(),Se.Cb(Se.ab[0])),Se.ab.pop()}};d.PThread=Se;var Wt=m=>{for(;0>2>>>0];m=s()[m+56>>2>>>0],Jr(v,v-m),rr(v)};function wt(m){if(O)return Ge(2,0,m);ht(m)}d.invokeEntryPoint=function(m,v){m=en.apply(null,[m,v]),Pt()?Se.kb(m):Er(m)};function Mr(m){this.fb=m-24,this.pb=function(v){c()[this.fb+4>>2>>>0]=v},this.ob=function(v){c()[this.fb+8>>2>>>0]=v},this.gb=function(v,I){this.nb(),this.pb(v),this.ob(I)},this.nb=function(){c()[this.fb+16>>2>>>0]=0}}var ot=0,gt=0;function gr(m,v,I,D){return O?Ge(3,1,m,v,I,D):bn(m,v,I,D)}function bn(m,v,I,D){if(m>>>=0,v>>>=0,I>>>=0,D>>>=0,typeof SharedArrayBuffer>"u")return ge("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var H=[];return O&&H.length===0?gr(m,v,I,D):(m={Gb:I,Xa:m,rb:D,Mb:H},O?(m.Ob="spawnThread",postMessage(m,H),0):mr(m))}function vn(m,v,I){return O?Ge(4,1,m,v,I):0}function jr(m,v){if(O)return Ge(5,1,m,v)}var Ur=m=>{for(var v=0,I=0;I=D?v++:2047>=D?v+=2:55296<=D&&57343>=D?(v+=4,++I):v+=3}return v},wn=(m,v,I,D)=>{if(I>>>=0,!(0=re){var ye=m.charCodeAt(++Q);re=65536+((re&1023)<<10)|ye&1023}if(127>=re){if(I>=D)break;v[I++>>>0]=re}else{if(2047>=re){if(I+1>=D)break;v[I++>>>0]=192|re>>6}else{if(65535>=re){if(I+2>=D)break;v[I++>>>0]=224|re>>12}else{if(I+3>=D)break;v[I++>>>0]=240|re>>18,v[I++>>>0]=128|re>>12&63}v[I++>>>0]=128|re>>6&63}v[I++>>>0]=128|re&63}}return v[I>>>0]=0,I-H},_n=(m,v,I)=>wn(m,u(),v,I);function $n(m,v){if(O)return Ge(6,1,m,v)}function Cn(m,v,I){if(O)return Ge(7,1,m,v,I)}function Sn(m,v,I){return O?Ge(8,1,m,v,I):0}function yr(m,v){if(O)return Ge(9,1,m,v)}function Vr(m,v,I){if(O)return Ge(10,1,m,v,I)}function Yt(m,v,I,D){if(O)return Ge(11,1,m,v,I,D)}function xn(m,v,I,D){if(O)return Ge(12,1,m,v,I,D)}function In(m,v,I,D){if(O)return Ge(13,1,m,v,I,D)}function Ct(m){if(O)return Ge(14,1,m)}function yt(m,v){if(O)return Ge(15,1,m,v)}function Wr(m,v,I){if(O)return Ge(16,1,m,v,I)}var Zt=m=>{if(!Ee)try{if(m(),!Pt())try{O?Er(Pe):ht(Pe)}catch(v){v instanceof vt||v=="unwind"||A(1,v)}}catch(v){v instanceof vt||v=="unwind"||A(1,v)}};function br(m){m>>>=0,typeof Atomics.Nb=="function"&&(Atomics.Nb(s(),m>>2,m).value.then(Qt),m+=128,Atomics.store(s(),m>>2,1))}d.__emscripten_thread_mailbox_await=br;function Qt(){var m=tr();m&&(br(m),Zt(()=>Qr()))}d.checkMailbox=Qt;var Nt=m=>m%4===0&&(m%100!==0||m%400===0),vr=[0,31,60,91,121,152,182,213,244,274,305,335],An=[0,31,59,90,120,151,181,212,243,273,304,334];function Tn(m,v,I,D,H,Q,re,ye){return O?Ge(17,1,m,v,I,D,H,Q,re,ye):-52}function En(m,v,I,D,H,Q,re){if(O)return Ge(18,1,m,v,I,D,H,Q,re)}var Pn=m=>{var v=Ur(m)+1,I=Ar(v);return I&&_n(m,I,v),I},wr=[],Xt=(m,v)=>{wr.length=0;var I;for(v>>=2;I=u()[m++>>>0];)v+=I!=105&v,wr.push(I==105?s()[v>>>0]:f()[v++>>>1]),++v;return wr},_i=m=>{var v=Pr();return m=m(),rr(v),m};function Ge(m,v){var I=arguments.length-2,D=arguments;return _i(()=>{for(var H=kr(8*I),Q=H>>3,re=0;re>>0]=ye}return Zr(m,I,H,v)})}var _r=[],Nr={},kn=()=>{if(!$r){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",_:$||"./this.program"},v;for(v in Nr)Nr[v]===void 0?delete m[v]:m[v]=Nr[v];var I=[];for(v in m)I.push(`${v}=${m[v]}`);$r=I}return $r},$r;function On(m,v){if(O)return Ge(19,1,m,v);m>>>=0,v>>>=0;var I=0;return kn().forEach(function(D,H){var Q=v+I;for(H=c()[m+4*H>>2>>>0]=Q,Q=0;Q>0>>>0]=D.charCodeAt(Q);t()[H>>0>>>0]=0,I+=D.length+1}),0}function jt(m,v){if(O)return Ge(20,1,m,v);m>>>=0,v>>>=0;var I=kn();c()[m>>2>>>0]=I.length;var D=0;return I.forEach(function(H){D+=H.length+1}),c()[v>>2>>>0]=D,0}function Gr(m){return O?Ge(21,1,m):52}function Hr(m,v,I,D){return O?Ge(22,1,m,v,I,D):52}function Cr(m,v,I,D,H){return O?Ge(23,1,m,v,I,D,H):70}var Rn=[null,[],[]];function Sr(m,v,I,D){if(O)return Ge(24,1,m,v,I,D);v>>>=0,I>>>=0,D>>>=0;for(var H=0,Q=0;Q>2>>>0],ye=c()[v+4>>2>>>0];v+=8;for(var he=0;he>>0],ve=Rn[m];fe===0||fe===10?((m===1?le:ge)(gn(ve,0)),ve.length=0):ve.push(fe)}H+=ye}return c()[D>>2>>>0]=H,0}var Lr=[31,29,31,30,31,30,31,31,30,31,30,31],xr=[31,28,31,30,31,30,31,31,30,31,30,31];function $i(m){var v=Array(Ur(m)+1);return wn(m,v,0,v.length),v}var Bn=(m,v)=>{t().set(m,v>>>0)};function Fr(m,v,I,D){function H(q,Ie,Ue){for(q=typeof q=="number"?q.toString():q||"";q.lengthsn?-1:0kt-q.getDate())Ie-=kt-q.getDate()+1,q.setDate(1),11>Ue?q.setMonth(Ue+1):(q.setMonth(0),q.setFullYear(q.getFullYear()+1));else{q.setDate(q.getDate()+Ie);break}}return Ue=new Date(q.getFullYear()+1,0,4),Ie=ye(new Date(q.getFullYear(),0,4)),Ue=ye(Ue),0>=re(Ie,q)?0>=re(Ue,q)?q.getFullYear()+1:q.getFullYear():q.getFullYear()-1}m>>>=0,v>>>=0,I>>>=0,D>>>=0;var fe=s()[D+40>>2>>>0];D={Kb:s()[D>>2>>>0],Jb:s()[D+4>>2>>>0],cb:s()[D+8>>2>>>0],ib:s()[D+12>>2>>>0],eb:s()[D+16>>2>>>0],$a:s()[D+20>>2>>>0],Wa:s()[D+24>>2>>>0],Za:s()[D+28>>2>>>0],Tb:s()[D+32>>2>>>0],Ib:s()[D+36>>2>>>0],Lb:fe?it(fe):""},I=it(I),fe={"%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 ve in fe)I=I.replace(new RegExp(ve,"g"),fe[ve]);var Me="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),je="January February March April May June July August September October November December".split(" ");fe={"%a":q=>Me[q.Wa].substring(0,3),"%A":q=>Me[q.Wa],"%b":q=>je[q.eb].substring(0,3),"%B":q=>je[q.eb],"%C":q=>Q((q.$a+1900)/100|0,2),"%d":q=>Q(q.ib,2),"%e":q=>H(q.ib,2," "),"%g":q=>he(q).toString().substring(2),"%G":q=>he(q),"%H":q=>Q(q.cb,2),"%I":q=>(q=q.cb,q==0?q=12:12{for(var Ie=0,Ue=0;Ue<=q.eb-1;Ie+=(Nt(q.$a+1900)?Lr:xr)[Ue++]);return Q(q.ib+Ie,3)},"%m":q=>Q(q.eb+1,2),"%M":q=>Q(q.Jb,2),"%n":()=>`\n`,"%p":q=>0<=q.cb&&12>q.cb?"AM":"PM","%S":q=>Q(q.Kb,2),"%t":()=>" ","%u":q=>q.Wa||7,"%U":q=>Q(Math.floor((q.Za+7-q.Wa)/7),2),"%V":q=>{var Ie=Math.floor((q.Za+7-(q.Wa+6)%7)/7);if(2>=(q.Wa+371-q.Za-2)%7&&Ie++,Ie)Ie==53&&(Ue=(q.Wa+371-q.Za)%7,Ue==4||Ue==3&&Nt(q.$a)||(Ie=1));else{Ie=52;var Ue=(q.Wa+7-q.Za-1)%7;(Ue==4||Ue==5&&Nt(q.$a%400-1))&&Ie++}return Q(Ie,2)},"%w":q=>q.Wa,"%W":q=>Q(Math.floor((q.Za+7-(q.Wa+6)%7)/7),2),"%y":q=>(q.$a+1900).toString().substring(2),"%Y":q=>q.$a+1900,"%z":q=>{q=q.Ib;var Ie=0<=q;return q=Math.abs(q)/60,(Ie?"+":"-")+("0000"+(q/60*100+q%60)).slice(-4)},"%Z":q=>q.Lb,"%%":()=>"%"},I=I.replace(/%%/g,"\\0\\0");for(ve in fe)I.includes(ve)&&(I=I.replace(new RegExp(ve,"g"),fe[ve](D)));return I=I.replace(/\\0\\0/g,"%"),ve=$i(I),ve.length>v?0:(Bn(ve,m),ve.length-1)}function Ir(m){try{m()}catch(v){pt(v)}}function Dn(m){var v={},I;for(I in m)(function(D){var H=m[D];v[D]=typeof H=="function"?function(){M.push(D);try{return H.apply(null,arguments)}finally{Ee||(M.pop()===D||pt(),lt&&St===1&&M.length===0&&(St=0,Ke+=1,Ir(rn),typeof Fibers<"u"&&Fibers.Ub()))}}:H})(I);return v}var St=0,lt=null,zn=0,M=[],qr={},Jt={},_t=0,W=null,er=[];function N(){return new Promise((m,v)=>{W={resolve:m,reject:v}})}function Mn(){var m=Ar(65548),v=m+12;c()[m>>2>>>0]=v,c()[m+4>>2>>>0]=v+65536,v=M[0];var I=qr[v];return I===void 0&&(I=_t++,qr[v]=I,Jt[I]=v),v=I,s()[m+8>>2>>>0]=v,m}function G(){var m=s()[lt+8>>2>>>0];return m=ue[Jt[m]],--Ke,m()}function jn(m){if(!Ee){if(St===0){var v=!1,I=!1;m((D=0)=>{if(!Ee&&(zn=D,v=!0,I)){St=2,Ir(()=>nn(lt)),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.resume(),D=!1;try{var H=G()}catch(ye){H=ye,D=!0}var Q=!1;if(!lt){var re=W;re&&(W=null,(D?re.reject:re.resolve)(H),Q=!0)}if(D&&!Q)throw H}}),I=!0,v||(St=1,lt=Mn(),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.pause(),Ir(()=>tn(lt)))}else St===2?(St=0,Ir(on),Kr(lt),lt=null,er.forEach(D=>Zt(D))):pt(`invalid state: ${St}`);return zn}}function Un(m){return jn(v=>{m().then(v)})}Se.gb();var Vn=[null,yn,wt,gr,vn,jr,$n,Cn,Sn,yr,Vr,Yt,xn,In,Ct,yt,Wr,Tn,En,On,jt,Gr,Hr,Cr,Sr],Wn={r:function(m,v,I){return Un(async()=>{await d.xb(m,v,I)})},b:function(m,v,I){throw m>>>=0,new Mr(m).gb(v>>>0,I>>>0),ot=m,gt++,ot},O:function(m){Yr(m>>>0,!x,1,!P,131072,!1),Se.lb()},l:function(m){m>>>=0,O?postMessage({cmd:"cleanupThread",thread:m}):mt(m)},I:bn,i:vn,U:jr,E:$n,G:Cn,V:Sn,S:yr,K:Vr,R:Yt,p:xn,F:In,C:Ct,T:yt,D:Wr,q:()=>!0,A:function(m,v){m>>>=0,m==v>>>0?setTimeout(()=>Qt()):O?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=Se.Qa[m])&&m.postMessage({cmd:"checkMailbox"})},M:function(){return-1},N:br,X:function(m){E&&Se.Qa[m>>>0].ref()},u:function(m,v,I){m=v+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*v:NaN,I>>>=0,m=new Date(1e3*m),s()[I>>2>>>0]=m.getUTCSeconds(),s()[I+4>>2>>>0]=m.getUTCMinutes(),s()[I+8>>2>>>0]=m.getUTCHours(),s()[I+12>>2>>>0]=m.getUTCDate(),s()[I+16>>2>>>0]=m.getUTCMonth(),s()[I+20>>2>>>0]=m.getUTCFullYear()-1900,s()[I+24>>2>>>0]=m.getUTCDay(),m=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,s()[I+28>>2>>>0]=m},v:function(m,v,I){m=v+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*v:NaN,I>>>=0,m=new Date(1e3*m),s()[I>>2>>>0]=m.getSeconds(),s()[I+4>>2>>>0]=m.getMinutes(),s()[I+8>>2>>>0]=m.getHours(),s()[I+12>>2>>>0]=m.getDate(),s()[I+16>>2>>>0]=m.getMonth(),s()[I+20>>2>>>0]=m.getFullYear()-1900,s()[I+24>>2>>>0]=m.getDay(),v=(Nt(m.getFullYear())?vr:An)[m.getMonth()]+m.getDate()-1|0,s()[I+28>>2>>>0]=v,s()[I+36>>2>>>0]=-(60*m.getTimezoneOffset()),v=new Date(m.getFullYear(),6,1).getTimezoneOffset();var D=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=(v!=D&&m.getTimezoneOffset()==Math.min(D,v))|0,s()[I+32>>2>>>0]=m},w:function(m){m>>>=0;var v=new Date(s()[m+20>>2>>>0]+1900,s()[m+16>>2>>>0],s()[m+12>>2>>>0],s()[m+8>>2>>>0],s()[m+4>>2>>>0],s()[m>>2>>>0],0),I=s()[m+32>>2>>>0],D=v.getTimezoneOffset(),H=new Date(v.getFullYear(),6,1).getTimezoneOffset(),Q=new Date(v.getFullYear(),0,1).getTimezoneOffset(),re=Math.min(Q,H);return 0>I?s()[m+32>>2>>>0]=+(H!=Q&&re==D):0>2>>>0]=v.getDay(),I=(Nt(v.getFullYear())?vr:An)[v.getMonth()]+v.getDate()-1|0,s()[m+28>>2>>>0]=I,s()[m>>2>>>0]=v.getSeconds(),s()[m+4>>2>>>0]=v.getMinutes(),s()[m+8>>2>>>0]=v.getHours(),s()[m+12>>2>>>0]=v.getDate(),s()[m+16>>2>>>0]=v.getMonth(),s()[m+20>>2>>>0]=v.getYear(),m=v.getTime()/1e3,Xr((qe=m,1<=+Math.abs(qe)?0>>0:~~+Math.ceil((qe-+(~~qe>>>0))/4294967296)>>>0:0)),m>>>0},s:Tn,t:En,z:function(m,v,I){function D(fe){return(fe=fe.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?fe[1]:"GMT"}m>>>=0,v>>>=0,I>>>=0;var H=new Date().getFullYear(),Q=new Date(H,0,1),re=new Date(H,6,1);H=Q.getTimezoneOffset();var ye=re.getTimezoneOffset(),he=Math.max(H,ye);c()[m>>2>>>0]=60*he,s()[v>>2>>>0]=+(H!=ye),m=D(Q),v=D(re),m=Pn(m),v=Pn(v),ye>2>>>0]=m,c()[I+4>>2>>>0]=v):(c()[I>>2>>>0]=v,c()[I+4>>2>>>0]=m)},d:()=>{pt("")},c:function(m,v,I){return m>>>=0,v=Xt(v>>>0,I>>>0),Kt[m].apply(null,v)},k:function(m,v,I){return m>>>=0,v=Xt(v>>>0,I>>>0),Kt[m].apply(null,v)},m:function(){},j:function(){return Date.now()},W:()=>{throw Ke+=1,"unwind"},B:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:function(){return E?(eu(),ir(Js)).cpus().length:navigator.hardwareConcurrency},L:function(m,v,I,D){for(Se.Pb=v>>>0,_r.length=I,v=D>>>0>>3,D=0;D>>0];return(0>m?Kt[-m-1]:Vn[m]).apply(null,_r)},y:function(m){m>>>=0;var v=u().length;if(m<=v||4294901760=I;I*=2){var D=v*(1+.2/I);D=Math.min(D,m+100663296);var H=Math;D=Math.max(m,D);e:{H=H.min.call(H,4294901760,D+(65536-D%65536)%65536)-we.buffer.byteLength+65535>>>16;try{we.grow(H),ee();var Q=1;break e}catch{}Q=void 0}if(Q)return!0}return!1},P:On,Q:jt,H:ht,h:Gr,o:Hr,x:Cr,n:Sr,a:we||d.wasmMemory,J:Fr,e:function(m,v,I,D){return Fr(m>>>0,v>>>0,I>>>0,D>>>0)}};(function(){function m(I,D){return I=I.exports,I=Dn(I),ue=I=Nn(I),Se.mb.push(ue.Da),tt.unshift(ue.Y),me=D,Vt(),I}var v={a:Wn};if(Ut(),d.instantiateWasm)try{return d.instantiateWasm(v,m)}catch(I){ge("Module.instantiateWasm callback failed with error: "+I),w(I)}return hn(v,function(I){m(I.instance,I.module)}).catch(w),{}})(),d._OrtInit=(m,v)=>(d._OrtInit=ue.Z)(m,v),d._OrtGetLastError=(m,v)=>(d._OrtGetLastError=ue._)(m,v),d._OrtCreateSessionOptions=(m,v,I,D,H,Q,re,ye,he,fe)=>(d._OrtCreateSessionOptions=ue.$)(m,v,I,D,H,Q,re,ye,he,fe),d._OrtAppendExecutionProvider=(m,v)=>(d._OrtAppendExecutionProvider=ue.aa)(m,v),d._OrtAddFreeDimensionOverride=(m,v,I)=>(d._OrtAddFreeDimensionOverride=ue.ba)(m,v,I),d._OrtAddSessionConfigEntry=(m,v,I)=>(d._OrtAddSessionConfigEntry=ue.ca)(m,v,I),d._OrtReleaseSessionOptions=m=>(d._OrtReleaseSessionOptions=ue.da)(m),d._OrtCreateSession=(m,v,I)=>(d._OrtCreateSession=ue.ea)(m,v,I),d._OrtReleaseSession=m=>(d._OrtReleaseSession=ue.fa)(m),d._OrtGetInputOutputCount=(m,v,I)=>(d._OrtGetInputOutputCount=ue.ga)(m,v,I),d._OrtGetInputName=(m,v)=>(d._OrtGetInputName=ue.ha)(m,v),d._OrtGetOutputName=(m,v)=>(d._OrtGetOutputName=ue.ia)(m,v),d._OrtFree=m=>(d._OrtFree=ue.ja)(m),d._OrtCreateTensor=(m,v,I,D,H,Q)=>(d._OrtCreateTensor=ue.ka)(m,v,I,D,H,Q),d._OrtGetTensorData=(m,v,I,D,H)=>(d._OrtGetTensorData=ue.la)(m,v,I,D,H),d._OrtReleaseTensor=m=>(d._OrtReleaseTensor=ue.ma)(m),d._OrtCreateRunOptions=(m,v,I,D)=>(d._OrtCreateRunOptions=ue.na)(m,v,I,D),d._OrtAddRunConfigEntry=(m,v,I)=>(d._OrtAddRunConfigEntry=ue.oa)(m,v,I),d._OrtReleaseRunOptions=m=>(d._OrtReleaseRunOptions=ue.pa)(m),d._OrtCreateBinding=m=>(d._OrtCreateBinding=ue.qa)(m),d._OrtBindInput=(m,v,I)=>(d._OrtBindInput=ue.ra)(m,v,I),d._OrtBindOutput=(m,v,I,D)=>(d._OrtBindOutput=ue.sa)(m,v,I,D),d._OrtClearBoundOutputs=m=>(d._OrtClearBoundOutputs=ue.ta)(m),d._OrtReleaseBinding=m=>(d._OrtReleaseBinding=ue.ua)(m),d._OrtRunWithBinding=(m,v,I,D,H)=>(d._OrtRunWithBinding=ue.va)(m,v,I,D,H),d._OrtRun=(m,v,I,D,H,Q,re,ye)=>(d._OrtRun=ue.wa)(m,v,I,D,H,Q,re,ye),d._OrtEndProfiling=m=>(d._OrtEndProfiling=ue.xa)(m),d._JsepOutput=(m,v,I)=>(d._JsepOutput=ue.ya)(m,v,I),d._JsepGetNodeName=m=>(d._JsepGetNodeName=ue.za)(m);var tr=d._pthread_self=()=>(tr=d._pthread_self=ue.Aa)(),Ar=d._malloc=m=>(Ar=d._malloc=ue.Ba)(m),Kr=d._free=m=>(Kr=d._free=ue.Ca)(m);d.__emscripten_tls_init=()=>(d.__emscripten_tls_init=ue.Da)();var Yr=d.__emscripten_thread_init=(m,v,I,D,H,Q)=>(Yr=d.__emscripten_thread_init=ue.Fa)(m,v,I,D,H,Q);d.__emscripten_thread_crashed=()=>(d.__emscripten_thread_crashed=ue.Ga)();var Zr=(m,v,I,D)=>(Zr=ue.Ha)(m,v,I,D),Tr=m=>(Tr=ue.Ia)(m),Er=d.__emscripten_thread_exit=m=>(Er=d.__emscripten_thread_exit=ue.Ja)(m),Qr=d.__emscripten_check_mailbox=()=>(Qr=d.__emscripten_check_mailbox=ue.Ka)(),Xr=m=>(Xr=ue.La)(m),Jr=(m,v)=>(Jr=ue.Ma)(m,v),Pr=()=>(Pr=ue.Na)(),rr=m=>(rr=ue.Oa)(m),kr=m=>(kr=ue.Pa)(m),en=d.dynCall_ii=(m,v)=>(en=d.dynCall_ii=ue.Ra)(m,v),tn=m=>(tn=ue.Sa)(m),rn=()=>(rn=ue.Ta)(),nn=m=>(nn=ue.Ua)(m),on=()=>(on=ue.Va)();d.___start_em_js=917678,d.___stop_em_js=917839;function Nn(m){m=Object.assign({},m);var v=D=>()=>D()>>>0,I=D=>H=>D(H)>>>0;return m.__errno_location=v(m.__errno_location),m.pthread_self=v(m.pthread_self),m.malloc=I(m.malloc),m.stackSave=v(m.stackSave),m.stackAlloc=I(m.stackAlloc),m}d.keepRuntimeAlive=Pt,d.wasmMemory=we,d.stackAlloc=kr,d.stackSave=Pr,d.stackRestore=rr,d.UTF8ToString=it,d.stringToUTF8=_n,d.lengthBytesUTF8=Ur,d.ExitStatus=vt,d.PThread=Se;var nr;ct=function m(){nr||an(),nr||(ct=m)};function an(){function m(){if(!nr&&(nr=!0,d.calledRun=!0,!Ee)&&(O||Wt(tt),g(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),!O)){if(d.postRun)for(typeof d.postRun=="function"&&(d.postRun=[d.postRun]);d.postRun.length;){var v=d.postRun.shift();Ye.unshift(v)}Wt(Ye)}}if(!(0tu)});var iu=un((N0,Uh)=>{Uh.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");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>(0,eval)(fs.readFileSync(e,"utf8")+"//# sourceURL="+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&&Module.__emscripten_thread_crashed(),a}}self.onmessage=handleMessage;\\n\'});var Bi,Gt,or,Kn,dn,du,Di,Te=ae(()=>{"use strict";Bi=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},Gt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},or=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Kn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},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}`)}},du=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",Di=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 Yn=ae(()=>{"use strict"});var fu=ae(()=>{"use strict";Yn()});var pu,mu=ae(()=>{"use strict";pu="1.18.0"});var hu,bt,zi=ae(()=>{"use strict";mu();hu="warning",bt={wasm:{},webgl:{},webgpu:{},versions:{common:pu},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}`);hu=e}},get logLevel(){return hu}};Object.defineProperty(bt,"logLevel",{enumerable:!0})});var Or,gu=ae(()=>{"use strict";zi();Or=bt});var yu=ae(()=>{"use strict"});var bu=ae(()=>{"use strict";Zn()});var wu=ae(()=>{"use strict"});var _u=ae(()=>{"use strict";Zn()});var Zn=ae(()=>{"use strict";yu();bu();wu();_u()});var Qn=ae(()=>{"use strict";Zn()});var Mi,$u,ar,Ht,ji=ae(()=>{"use strict";zi();Mi=(e,r)=>{(typeof bt.trace>"u"?!bt.wasm.trace:!bt.trace)||console.timeStamp(`${e}::ORT::${r}`)},$u=(e,r)=>{let t=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],u=!1;for(let s=0;s{(typeof bt.trace>"u"?!bt.wasm.trace:!bt.trace)||$u("BEGIN",e)},Ht=e=>{(typeof bt.trace>"u"?!bt.wasm.trace:!bt.trace)||$u("END",e)}});var Cu=ae(()=>{"use strict";Yn();Qn();ji()});var Su=ae(()=>{"use strict";Cu()});var xu=ae(()=>{"use strict"});var Iu=ae(()=>{"use strict"});var Au=ae(()=>{"use strict"});var Tu=ae(()=>{"use strict"});var Eu=ae(()=>{"use strict";Yn();Qn()});var Pu=ae(()=>{"use strict";Eu()});var Rr=ae(()=>{"use strict";fu();gu();Su();Qn();xu();Iu();ji();Au();Tu();Pu()});var Zh,Qh,ku,Ou,Ru,Xh,Fe,Lt=ae(()=>{"use strict";Te();Zh=["V","I","W","E","F"],Qh=(e,r)=>{console.log(`[${Zh[e]},${new Date().toISOString()}]${r}`)},Ru=(e,r)=>{ku=e,Ou=r},Xh=(e,r)=>{let t=dn(e),u=dn(ku);t>=u&&Qh(t,typeof r=="function"?r():r)},Fe=(...e)=>{Ou&&Xh(...e)}});var Bu,Du=ae(()=>{"use strict";Te();Bu=(e,r)=>new(Kn(r))(e)});var Xn=ae(()=>{"use strict"});var zu,Ui,Vi,Jh,eg,Mu,Ni,Wi,Uu,Vu=ae(()=>{"use strict";Lt();Xn();zu=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ui=[],Vi=e=>Math.ceil(e/16)*16,Jh=e=>{for(let r=0;reg++,Ni=async(e,r,t,u)=>{let s=Vi(t),c=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let f=e.getCommandEncoder();e.endComputePass(),f.copyBufferToBuffer(r,0,c,0,s),e.flush(),await c.mapAsync(GPUMapMode.READ);let d=c.getMappedRange();if(u){let g=u();return g.set(new Uint8Array(d,0,t)),g}else return new Uint8Array(d.slice(0,t))}finally{c.destroy()}},Wi=class{constructor(r){this.backend=r;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[t]of zu)Ui.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(r,t){let u=t.buffer,s=t.byteOffset,c=t.byteLength,f=Vi(c),d=this.storageCache.get(r);if(!d)throw new Error("gpu data for uploading does not exist");if(d.originalSize!==c)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${c}`);let g=this.backend.device.createBuffer({mappedAtCreation:!0,size:f,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),w=g.getMappedRange();new Uint8Array(w).set(new Uint8Array(u,s,c)),g.unmap();let C=this.backend.getCommandEncoder();this.backend.endComputePass(),C.copyBufferToBuffer(g,0,d.gpuData.buffer,0,f),Fe("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${r})`),this.buffersForUploadingPending.push(g)}memcpy(r,t){let u=this.storageCache.get(r);if(!u)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(t);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(u.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let c=Vi(u.originalSize),f=this.backend.getCommandEncoder();this.backend.endComputePass(),f.copyBufferToBuffer(u.gpuData.buffer,0,s.gpuData.buffer,0,c)}registerExternalBuffer(r,t,u){let s;if(u){if(s=this.externalBuffers.get(u),s===void 0)throw new Error("previous buffer is not registered");if(r===u)return Fe("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`);this.externalBuffers.delete(u)}else s=Mu();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:r},originalSize:t}),this.externalBuffers.set(r,s),Fe("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${s}, registered.`),s}unregisterExternalBuffer(r){let t=this.externalBuffers.get(r);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(r),Fe("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(r,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let u=Jh(r),s,c=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,f=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(c||f){let w=(c?this.freeBuffers:this.freeUniformBuffers).get(u);w?w.length>0?s=w.pop():s=this.backend.device.createBuffer({size:u,usage:t}):s=this.backend.device.createBuffer({size:u,usage:t})}else s=this.backend.device.createBuffer({size:u,usage:t});let d={id:Mu(),type:0,buffer:s};return this.storageCache.set(d.id,{gpuData:d,originalSize:r}),Fe("verbose",()=>`[WebGPU] GpuDataManager.create(size=${r}) => id=${d.id}`),d}get(r){return this.storageCache.get(r)?.gpuData}release(r){let t=this.storageCache.get(r);if(!t)throw new Error("releasing data does not exist");return Fe("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(r,t){let u=this.storageCache.get(r);if(!u)throw new Error("data does not exist");await Ni(this.backend,u.gpuData.buffer,u.originalSize,t)}refreshPendingBuffers(){for(let r of this.buffersForUploadingPending)r.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let r of this.buffersPending){let t=zu.get(r.size);if((r.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let u=this.freeBuffers.get(r.size)||[];t===void 0||u.length>=t?r.destroy():u.push(r)}else if((r.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let u=this.freeUniformBuffers.get(r.size)||[];t===void 0||u.length>=t?r.destroy():u.push(r)}else r.destroy()}this.buffersPending=[]}else{let r=this.capturedPendingBuffers.get(this.backend.currentSessionId);r||(r=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,r));for(let t of this.buffersPending)r.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(r=>{r.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(r=>{r.forEach(t=>{t.destroy()})}),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(r=>{r.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(r){let t=this.capturedPendingBuffers.get(r);t&&(t.forEach(u=>{u.destroy()}),this.capturedPendingBuffers.delete(r))}},Uu=(...e)=>new Wi(...e)});var Gi,ke,nt=ae(()=>{"use strict";Gi=class{constructor(r){Object.assign(this,r)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(r=>`${this[r]}`).join(";")),this.key}},ke=e=>new Gi(e)});var Hi,Ot,K,sr,Jn,ei,ti,De=ae(()=>{"use strict";Hi=class{static calcMatMulShape(r,t){return r[1]!==t[0]?void 0:[r[0],t[1]]}},Ot=class{static calcShape(r,t,u=!1){let s=r.length,c=t.length;if(s===0)return t;if(c===0)return r;let f=Math.max(r.length,t.length),d=new Array(f);if(u){if(s<2||c<2)return;let g=Hi.calcMatMulShape([r[s-2],r[s-1]],[t[c-2],t[c-1]]);if(g===void 0)return;[d[f-2],d[f-1]]=g}for(let g=u?3:1;g<=f;g++){let w=s-g<0?1:r[s-g],C=c-g<0?1:t[c-g];if(w!==C&&w>1&&C>1)return;let $=Math.max(w,C);if(w&&C)d[f-g]=Math.max(w,C);else{if($>1)return;d[f-g]=0}}return d}static isValidBroadcast(r,t){let u=r.length,s=t.length;if(u>s)return!1;for(let c=1;c<=u;c++)if(r[u-c]!==1&&r[u-c]!==t[s-c])return!1;return!0}},K=class e{static size(r){return e.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let u=r.length;if(u===0)return[];let s=new Array(u),c=u-1;for(;c>=0;){if(r[c]%t===0){s[c]=r[c]/t;break}if(t%r[c]!==0)throw new Error("cannot convert shape");s[c]=1,t/=r[c],c--}for(c--;c>=0;c--)s[c]=r[c];return s}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return e.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return e.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,u){let s=1;for(let c=t;c=0;--s)u[s]=u[s+1]*r[s+1];return u}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(u=>this.normalizeAxis(u,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(u=>r[u]):r.slice().reverse()}static padShape(r,t){let u=r.length;return r.map((s,c)=>s+t[c]+t[c+u])}static areEqual(r,t){return r.length!==t.length?!1:r.every((u,s)=>u===t[s])}},sr=class e{static adjustPoolAttributes(r,t,u,s,c,f){if(!r&&u.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let d=0;d=u.length?u.push(t[d+2]):u[d]=t[d+2];for(let d=0;d=u[d]||f[d+u.length]>=u[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,u,s,c,f,d){if(d){if(c.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let g=0;g{"use strict";Te();De();ur=64,Fi=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},Ne=(e,r=1)=>{let t=Fi(e,r);return typeof t=="string"?t:t[0]},at=(e,r=1)=>{let t=Fi(e,r);return typeof t=="string"?t:t[1]},se=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:K.computeStrides(t)})}),r},He=e=>e%4===0?4:e%2===0?2:1,xt=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,lr=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,It=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,xe=(e,r,t,u)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?u==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:u==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,qi=(e,r,t,u,s)=>{let c=typeof t=="number",f=c?t:t.length,d=[...new Array(f).keys()],g=f<2?"u32":f<=4?`vec${f}`:`array`,w=Fi(r,s),C=typeof w=="string"?w:w[1],$=typeof w=="string"?w:w[0],A={indices:g,value:C,storage:$,tensor:r},P=ee=>typeof ee=="string"?ee:`${ee}u`,x={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=c?"uniforms.":"",O=`${E}${e}_shape`,B=`${E}${e}_strides`,R="";for(let ee=0;ee ${A.indices} {\n var indices: ${A.indices};\n var current = offset;\n ${R}\n return indices;\n }`,U=ee=>(x.offsetToIndices=!0,f<2?ee:`o2i_${e}(${ee})`),L=[];if(f>=2)for(let ee=f-1;ee>=0;ee--)L.push(`${xe(B,ee,f)} * (indices[${ee}])`);let F=f<2?"":`\n fn i2o_${e}(indices: ${A.indices}) -> u32 {\n return ${L.join("+")};\n }`,te=ee=>(x.indicesToOffset=!0,f<2?ee:`i2o_${e}(${ee})`),J=(...ee)=>f===0?"0u":`${A.indices}(${ee.map(P).join(",")})`,oe=(ee,ce)=>f<2?`${ee}`:`${xe(ee,ce,f)}`,le=(ee,ce,Be)=>f<2?`${ee}=${Be};`:`${xe(ee,ce,f)}=${Be};`,ge={},X=(ee,ce)=>{x.broadcastedIndicesToOffset=!0;let Be=`${ce.name}broadcastedIndicesTo${e}Offset`;if(Be in ge)return`${Be}(${ee})`;let tt=[];for(let Ye=f-1;Ye>=0;Ye--){let Ke=ce.indicesGet("outputIndices",Ye+ce.rank-f);tt.push(`${oe(B,Ye)} * (${Ke} % ${oe(O,Ye)})`)}return ge[Be]=`fn ${Be}(outputIndices: ${ce.type.indices}) -> u32 {\n return ${tt.length>0?tt.join("+"):"0u"};\n }`,`${Be}(${ee})`},pe=(ee,ce)=>(()=>{if(A.storage===A.value)return`${e}[${ee}]=${ce};`;if(A.storage==="vec2"&&A.value==="i32")return`${e}[${ee}]=vec2(u32(${ce}), select(0u, 0xFFFFFFFFu, ${ce} < 0));`;if(A.storage==="vec2"&&A.value==="u32")return`${e}[${ee}]=vec2(u32(${ce}), 0u);`;if(A.storage==="u32"&&A.value==="vec4")return`${e}[${ee}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ce}));`;throw new Error(`not supported combination of storage type ${A.storage} and value type ${A.value} yet`)})(),we=ee=>(()=>{if(A.storage===A.value)return`${e}[${ee}]`;if(A.storage==="vec2"&&A.value==="i32")return`i32(${e}[${ee}].x)`;if(A.storage==="vec2"&&A.value==="u32")return`u32(${e}[${ee}].x)`;if(A.storage==="u32"&&A.value==="vec4")return`vec4(bool(${e}[${ee}] & 0xFFu), bool(${e}[${ee}] & 0xFF00u), bool(${e}[${ee}] & 0xFF0000u), bool(${e}[${ee}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${A.storage} and value type ${A.value} yet`)})(),ue=f<2?"":`\n fn get_${e}ByIndices(indices: ${A.indices}) -> ${C} {\n return ${we(`i2o_${e}(indices)`)};\n }`,me=f<2?"":(()=>{let ee=d.map(Be=>`d${Be}: u32`).join(", "),ce=d.map(Be=>`d${Be}`).join(", ");return`\n fn get_${e}(${ee}) -> ${C} {\n return get_${e}ByIndices(${J(ce)});\n }`})(),Ee=(...ee)=>{if(ee.length!==f)throw new Error(`indices length must be ${f}`);let ce=ee.map(P).join(",");return f===0?we("0u"):f===1?we(ce[0]):(x.get=!0,x.getByIndices=!0,x.indicesToOffset=!0,`get_${e}(${ce})`)},Pe=ee=>f<2?we(ee):(x.getByIndices=!0,x.indicesToOffset=!0,`get_${e}ByIndices(${ee})`),Ce=f<2?"":`\n fn set_${e}ByIndices(indices: ${A.indices}, value: ${C}) {\n ${pe(`i2o_${e}(indices)`,"value")}\n }`,be=f<2?"":(()=>{let ee=d.map(Be=>`d${Be}: u32`).join(", "),ce=d.map(Be=>`d${Be}`).join(", ");return`\n fn set_${e}(${ee}, value: ${C}) {\n set_${e}ByIndices(${J(ce)}, value);\n }`})();return{impl:()=>{let ee=[],ce=!1;return x.offsetToIndices&&(ee.push(j),ce=!0),x.indicesToOffset&&(ee.push(F),ce=!0),x.broadcastedIndicesToOffset&&(Object.values(ge).forEach(Be=>ee.push(Be)),ce=!0),x.set&&(ee.push(be),ce=!0),x.setByIndices&&(ee.push(Ce),ce=!0),x.get&&(ee.push(me),ce=!0),x.getByIndices&&(ee.push(ue),ce=!0),!c&&ce&&ee.unshift(`const ${O} = ${A.indices}(${t.join(",")});`,`const ${B} = ${A.indices}(${K.computeStrides(t).join(",")});`),ee.join(`\n`)},type:A,offsetToIndices:U,indicesToOffset:te,broadcastedIndicesToOffset:X,indices:J,indicesGet:oe,indicesSet:le,set:(...ee)=>{if(ee.length!==f+1)throw new Error(`indices length must be ${f}`);let ce=ee[f];if(typeof ce!="string")throw new Error("value must be string");let Be=ee.slice(0,f).map(P).join(",");return f===0?pe("0u",ce):f===1?pe(Be[0],ce):(x.set=!0,x.setByIndices=!0,x.indicesToOffset=!0,`set_${e}(${Be}, ${ce})`)},setByOffset:pe,setByIndices:(ee,ce)=>f<2?pe(ee,ce):(x.setByIndices=!0,x.indicesToOffset=!0,`set_${e}ByIndices(${ee}, ${ce});`),get:Ee,getByOffset:we,getByIndices:Pe,usage:u,name:e,strides:B,shape:O,rank:f}},Z=(e,r,t,u=1)=>qi(e,r,t,"input",u),ne=(e,r,t,u=1)=>qi(e,r,t,"output",u),ri=(e,r,t,u=1)=>qi(e,r,t,"internal",u),Li=class{constructor(r,t){this.normalizedDispatchGroup=r;this.limits=t;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(r){return`if (global_idx >= ${typeof r=="number"?`${r}u`:r}) { return; }`}mainStart(r=ur){let t=typeof r=="number"?r:r[0],u=typeof r=="number"?1:r[1],s=typeof r=="number"?1:r[2];if(t>this.limits.maxComputeWorkgroupSizeX||u>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${u}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*u*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${u}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let c=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,f=c?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,d=c?"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) * ${t*u*s}u + local_idx;`;return`@compute @workgroup_size(${t}, ${u}, ${s})\n fn main(${f}) {\n ${d}\n `}appendVariableUniforms(r){r.rank!==0&&(r.shape.startsWith("uniforms.")&&this.uniforms.push({name:r.shape.replace("uniforms.",""),type:"u32",length:r.rank}),r.strides.startsWith("uniforms.")&&this.uniforms.push({name:r.strides.replace("uniforms.",""),type:"u32",length:r.rank}))}declareVariable(r,t){if(r.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(r),this.appendVariableUniforms(r);let u=r.usage==="input"?"read":"read_write",s=r.type.storage;return`@group(0) @binding(${t}) var ${r.name}: array<${s}>;`}declareVariables(...r){return r.map(t=>this.declareVariable(t,this.variableIndex++)).join(`\n`)}registerInternalVariable(r){if(r.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(r),this.appendVariableUniforms(r)}registerInternalVariables(...r){return r.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(r,t,u=1){return this.uniforms.push({name:r,type:t,length:u}),this}registerUniforms(r){return this.uniforms=this.uniforms.concat(r),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let r=[];for(let{name:t,type:u,length:s}of this.uniforms)if(s&&s>4)u==="f16"?r.push(`@align(16) ${t}:array, ${Math.ceil(s/8)}>`):r.push(`${t}:array, ${Math.ceil(s/4)}>`);else{let c=s==null||s===1?u:`vec${s}<${u}>`;r.push(`${t}:${c}`)}return`\n struct Uniforms { ${r.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(r=>r.impl()).join(`\n`)+this.internalVariables.map(r=>r.impl()).join(`\n`)}get variablesInfo(){if(this.uniforms.length===0)return;let r=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[r(t.type),t.length??1])}},Wu=(e,r)=>new Li(e,r),Br=(e,r)=>{let t=e.length,u=[];for(let s=0;s1&&f===1&&u.unshift(c)}return u}});var tg,Nu,rg,ng,$t,Gu,Hu,Dr=ae(()=>{"use strict";Te();De();nt();Re();tg=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Nu=(e,r)=>r&&r.length!==e?[...new Array(e).keys()].reverse():r,rg=(e,r)=>K.sortBasedOnPerm(e,Nu(e.length,r)),ng=(e,r,t,u)=>{let s=[];s.push(`fn perm(i: ${u.type.indices}) -> ${t.type.indices} {\n var a: ${t.type.indices};`);for(let c=0;c{let t=e.dataType,u=e.dims.length,s=Nu(u,r),c=rg(e.dims,s),f=ne("output",t,c.length),d=Z("a",t,u),g=w=>`\n ${w.registerUniform("output_size","u32").declareVariables(d,f)}\n\n ${ng(s,u,d,f)}\n\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${f.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${f.setByOffset("global_idx",d.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:w=>{let C=K.size(c);return{outputs:[{dims:c,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...se(w[0].dims,c)]}},getShaderSource:g}},Gu=(e,r)=>{tg(e.inputs),e.compute($t(e.inputs[0],r.perm))},Hu=e=>ke({perm:e.perm})});var ig,og,ag,sg,ug,lg,dg,cg,fg,pg,Rt,Lu,Fu,qu,Ku,Yu,Zu,Qu,Xu,Ju,el,tl=ae(()=>{"use strict";Te();De();Re();ni();Dr();ig={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"},og={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"},ag={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},sg={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ug=(e,r)=>{let t=[];for(let u=r-e;u{let t=[],u=e.length;for(let c=0;ce[c]);return[t,s]},dg=(e,r)=>{let t=e.length+r.length,u=[],s=0;for(let c=0;c{for(let t=0;t{let t=[];if(!cg(e,r)){for(let u=0;ut.push(u))}return t},pg=(e,r,t,u,s,c,f)=>{let d=t[0].dims,g=K.size(c),w=K.size(f),C=Z("_A",t[0].dataType,d),$=ne("output",s,c),A=32,P=`\n var aBestValues : array;\n `;return{name:e,shaderCache:r,getShaderSource:E=>`\n ${E.registerUniform("reduceSize","u32").declareVariables(C,$)}\n ${P}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${E.mainStart(A)}\n\n let outputIndex = global_idx / ${A};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${ag[u]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${A}) {\n let candidate = f32(${C.getByOffset("offset + k")});\n bestValue = ${ig[u]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${A}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 = ${og[u]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${$.setByOffset("outputIndex",`${u==="mean"?`${$.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${$.type.storage}(${sg[u]})`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:c,dataType:s}],dispatchGroup:{x:g},programUniforms:[{type:12,data:w}]})}},Rt=(e,r,t,u)=>{let s=e.inputs.length===1?t:Ki(e.inputs,t),c=s.axes;c.length===0&&!s.noopWithEmptyAxes&&(c=e.inputs[0].dims.map((P,x)=>x));let f=K.normalizeAxes(c,e.inputs[0].dims.length),d=f,g=e.inputs[0],w=fg(d,e.inputs[0].dims.length);w.length>0&&(g=e.compute($t(e.inputs[0],w),{inputs:[0],outputs:[-1]})[0],d=ug(d.length,g.dims.length));let[C,$]=lg(g.dims,d),A=C;s.keepDims&&(A=dg(C,f)),e.compute(pg(r,{hint:s.cacheKey,inputDependencies:["type"]},[g],u,e.inputs[0].dataType,A,$),{inputs:[g]})},Lu=(e,r)=>{Rt(e,"ReduceMeanShared",r,"mean")},Fu=(e,r)=>{Rt(e,"ReduceL1Shared",r,"l1")},qu=(e,r)=>{Rt(e,"ReduceL2Shared",r,"l2")},Ku=(e,r)=>{Rt(e,"ReduceLogSumExpShared",r,"logSumExp")},Yu=(e,r)=>{Rt(e,"ReduceMaxShared",r,"max")},Zu=(e,r)=>{Rt(e,"ReduceMinShared",r,"min")},Qu=(e,r)=>{Rt(e,"ReduceProdShared",r,"prod")},Xu=(e,r)=>{Rt(e,"ReduceSumShared",r,"sum")},Ju=(e,r)=>{Rt(e,"ReduceSumSquareShared",r,"sumSquare")},el=(e,r)=>{Rt(e,"ReduceLogSumShared",r,"logSum")}});var Bt,mg,ii,Ki,Dt,hg,gg,yg,bg,vg,wg,_g,$g,Cg,Sg,zt,rl,nl,il,ol,al,sl,ul,ll,dl,cl,ni=ae(()=>{"use strict";Te();De();nt();Re();tl();Bt=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.")},mg=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ii=(e,r,t,u,s,c,f=!1,d=!1)=>{let g=[],w=t[0].dims,C=w.length,$=K.normalizeAxes(s,C),A=!d&&$.length===0;w.forEach((O,B)=>{A||$.indexOf(B)>=0?f&&g.push(1):g.push(O)});let P=g.length,x=K.size(g);return{name:e,shaderCache:r,getShaderSource:O=>{let B=[],R=Z("_A",t[0].dataType,C),j=ne("output",c,P),U=u(R,j,$),L=U[2];for(let F=0,te=0;F=0?(f&&te++,L=`for(var j${F}: u32 = 0; j${F} < ${w[F]}; j${F}++) {\n ${U[2].includes("last_index")?`let last_index = j${F};`:""}\n ${R.indicesSet("input_indices",F,`j${F}`)}\n ${L}\n }`):(B.push(`${R.indicesSet("input_indices",F,j.indicesGet("output_indices",te))};`),te++);return`\n\n ${O.registerUniform("output_size","u32").declareVariables(R,j)}\n\n ${O.mainStart()}\n ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${R.type.indices};\n let output_indices = ${j.offsetToIndices("global_idx")};\n\n ${B.join(`\n`)}\n ${U[0]} // init ops for reduce max/min\n ${U[1]}\n ${L}\n ${U[3]}\n ${U.length===4?j.setByOffset("global_idx","value"):U.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:g,dataType:c}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:[{type:12,data:x},...se(w,g)]})}},Ki=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(u=>t.push(Number(u))),ke({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},Dt=(e,r,t,u)=>{let s=e.inputs,c=s.length===1?t:Ki(s,t);e.compute(ii(r,{hint:c.cacheKey,inputDependencies:["rank"]},[s[0]],c.noopWithEmptyAxes&&c.axes.length===0?mg:u,c.axes,s[0].dataType,c.keepDims,c.noopWithEmptyAxes),{inputs:[0]})},hg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceLogSum",r,(u,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${u.getByIndices("input_indices")};`,"value = log(value);"])},gg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceL1",r,(u,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${u.getByIndices("input_indices")});`,""])},yg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceL2",r,(u,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${u.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},bg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceLogSumExp",r,(u,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${u.getByIndices("input_indices")});`,"value = log(value);"])},vg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceMax",r,(u,s,c)=>{let f=[];for(let d=0;d=0||c.length===0)&&f.push(u.indicesSet("input_indices",d,0));return[`${f.join(`\n`)}`,`var value = ${u.getByIndices("input_indices")};`,`value = max(value, ${u.getByIndices("input_indices")});`,""]})},wg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceMean",r,(u,s,c)=>{let f=1;for(let d=0;d=0||c.length===0)&&(f*=e.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${u.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${f});`]})},_g=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceMin",r,(u,s,c)=>{let f=[];for(let d=0;d=0||c.length===0)&&f.push(`input_indices[${d}] = 0;`);return[`${f.join(`\n`)}`,`var value = ${u.getByIndices("input_indices")};`,`value = min(value, ${u.getByIndices("input_indices")});`,""]})},$g=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceProd",r,(u,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${u.getByIndices("input_indices")};`,""])},Cg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceSum",r,(u,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${u.getByIndices("input_indices")};`,""])},Sg=(e,r)=>{Bt(e.inputs),Dt(e,"ReduceSumSquare",r,(u,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${u.getByIndices("input_indices")}; value += t * t;`,""])},zt=(e,r,t)=>{if(r.length===0)return t;let u=1,s=1;for(let c=0;c1024},rl=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wg(e,r):Lu(e,r)},nl=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gg(e,r):Fu(e,r)},il=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yg(e,r):qu(e,r)},ol=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bg(e,r):Ku(e,r)},al=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?vg(e,r):Yu(e,r)},sl=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?_g(e,r):Zu(e,r)},ul=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?$g(e,r):Qu(e,r)},ll=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Cg(e,r):Xu(e,r)},dl=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Sg(e,r):Ju(e,r)},cl=(e,r)=>{zt(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?hg(e,r):el(e,r)}});var fl,pl,ml,Yi,hl=ae(()=>{"use strict";Te();nt();ni();fl=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.")},pl=(e,r)=>{fl(e.inputs);let t=(u,s,c)=>{let f=[];for(let d=0;d=0||c.length===0)&&f.push(`input_indices[${d}] = 0;`);return[`${f.join(`\n`)}`,`var value = ${u.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${u.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) {\n value = ${u.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",s.setByOffset("global_idx","best_index")]};e.compute(ii("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},ml=(e,r)=>{fl(e.inputs);let t=(u,s,c)=>{let f=[];for(let d=0;d=0||c.length===0)&&f.push(`input_indices[${d}] = 0;`);return[`${f.join(`\n`)}`,`var value = ${u.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${u.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) {\n value = ${u.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",s.setByOffset("global_idx","best_index")]};e.compute(ii("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Yi=e=>ke(e)});var xg,Ig,Ag,oi,gl,yl,Zi=ae(()=>{"use strict";Te();De();nt();Re();xg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,u=e[t],s=u.dataType,c=u.dims.length;e.forEach((f,d)=>{if(d!==t){if(f.dataType!==s)throw new Error("input tensors should be one type");if(f.dims.length!==c)throw new Error("input tensors should have the same shape");f.dims.forEach((g,w)=>{if(w!==r&&g!==u.dims[w])throw new Error("non concat dimensions must match")})}})},Ig=(e,r)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${r});\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 }`,Ag=(e,r)=>{let t=e.length,u=[];for(let s=0;s{let s=K.size(t),c=new Array(e.length),f=new Array(e.length),d=0,g=[],w=[],C=[{type:12,data:s}];for(let E=0;E`uniforms.sizeInConcatAxis${E}`).join(","),x=E=>`\n\n ${(()=>{E.registerUniform("outputSize","u32");for(let O=0;O(${P});\n ${A} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Ag(f,$)}\n }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:t,dataType:u}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:C}),getShaderSource:x}},gl=(e,r)=>{let t=e.inputs,u=t[0].dims,s=K.normalizeAxis(r.axis,u.length);xg(t,s);let c=u.slice();c[s]=t.reduce((d,g)=>d+(g.dims.length>s?g.dims[s]:0),0);let f=t.filter(d=>K.size(d.dims)>0);e.compute(oi(f,s,c,t[0].dataType),{inputs:f})},yl=e=>ke({axis:e.axis})});var Tg,Eg,Pg,kg,ai,Og,bl,Qi=ae(()=>{"use strict";Te();Xn();Re();Zi();Tg=(e,r)=>{let t=e[0],u=e[1],s=e[2],c=e[3],f=e[4],d=e[5];if(f&&d)throw new Error("Attention cannot have both past and relative_position_bias");if(t.dims.length!==3)throw new Error(\'Input "input" must have 3 dimensions\');let g=t.dims[0],w=t.dims[1],C=t.dims[2];if(s.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimensions\');if(u.dims.length!==2)throw new Error(\'Input "weights" is expected to have 2 dimensions\');if(u.dims[0]!==C)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==u.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let $=s.dims[0]/3,A=$,P=A;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let j of r.qkvHiddenSizes)if(j%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");$=r.qkvHiddenSizes[0],A=r.qkvHiddenSizes[1],P=r.qkvHiddenSizes[2]}let x=w;if($!==A)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==$+A+P)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let E=0;if(f){if(A!==P)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(f.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(f.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(f.dims[1]!==g)throw new Error(\'Input "past" second dimension must be batch_size\');if(f.dims[2]!==r.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(f.dims[4]!==A/r.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');r.pastPresentShareBuffer||(E=f.dims[3])}let O=x+E,B=-1,R=0;if(c)throw new Error("Mask not supported");if(f)throw new Error("past is not supported");return{batchSize:g,sequenceLength:w,pastSequenceLength:E,kvSequenceLength:x,totalSequenceLength:O,maxSequenceLength:B,inputHiddenSize:C,hiddenSize:$,vHiddenSize:P,headSize:Math.floor($/r.numHeads),vHeadSize:Math.floor(P/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:R,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Eg=(e,r,t,u)=>{let s=He(u),c=64,f=u/s;f{let P=ne("x",r.dataType,r.dims,s),E=[{name:"d_inv",type:at(r.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${A.registerUniforms(E).declareVariables(P)}\n ${A.mainStart([c,1,1])}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = workgroup_id.x * uniforms.d_comp + local_offset;\n\n var thread_max_vector = ${C}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n thread_max_vector = max(${C}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(s){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${s}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${c}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${C}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n sum_vector += exp(${C}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(s){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${s}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${c}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n x[offset + i] = ${P.type.value}(uniforms.d_inv);\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n var f32input = ${C}(x[offset + i]);\n x[offset + i] = ${P.type.value}(exp(f32input - max_value) / sum);\n }\n }\n }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${w};${s}`},getShaderSource:$,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:g})}},Pg=(e,r,t,u,s,c,f)=>{let d=f+s.kvSequenceLength,g=[s.batchSize,s.numHeads,s.sequenceLength,d],w=c.scale===0?1/Math.sqrt(s.headSize):c.scale,C=He(s.headSize),$=s.headSize/C,A=12,P={x:Math.ceil(d/A),y:Math.ceil(s.sequenceLength/A),z:s.batchSize*s.numHeads},x=[{type:12,data:s.sequenceLength},{type:12,data:$},{type:12,data:d},{type:12,data:s.numHeads},{type:1,data:w}],E=["type","type"];u&&(E.push("rank"),x.push(...se(u.dims)));let O=B=>{let R=Z("q",r.dataType,r.dims,C),j=Z("key",t.dataType,t.dims,C),U=[R,j],L=u?Z("relative_position_bias",u.dataType,u.dims.length):void 0;L&&U.push(L);let F=ne("output",r.dataType,g),te=at(1,C),J=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return`\n const TILE_SIZE = ${A}u;\n\n var tileQ: array<${R.type.storage}, ${A*A}>;\n var tileK: array<${R.type.storage}, ${A*A}>;\n ${B.registerUniforms(J).declareVariables(...U,F)}\n ${B.mainStart([A,A,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${te}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${te}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n let headOffset = headIdx * uniforms.M * uniforms.N;\n if (global_id.y < uniforms.M && global_id.x < uniforms.N) {\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(C){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${C}`)}})()};\n\n ${(()=>L?`\n let batch = workgroup_id.z / uniforms.num_heads;\n let head = workgroup_id.z % uniforms.num_heads;\n var indices = ${L.type.indices}(batch, head, global_id.y, global_id.x);\n output[outputIdx] = ${F.type.value}(sum * uniforms.alpha) + ${L.getByIndices("indices")};`:`output[outputIdx] = ${F.type.value} (sum * uniforms.alpha);`)()}\n }\n }`};return{name:"AttentionProbs",shaderCache:{hint:`${C}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:g,dataType:r.dataType,gpuDataType:0}],dispatchGroup:P,programUniforms:x}),getShaderSource:O}},kg=(e,r,t,u,s)=>{let c=s+u.kvSequenceLength,f=[u.batchSize,u.sequenceLength,u.vHiddenSize],d=12,g={x:Math.ceil(u.vHeadSize/d),y:Math.ceil(u.sequenceLength/d),z:u.batchSize*u.numHeads},w=[{type:12,data:u.sequenceLength},{type:12,data:c},{type:12,data:u.vHeadSize},{type:12,data:u.numHeads},{type:12,data:u.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:f,dataType:r.dataType,gpuDataType:0}],dispatchGroup:g,programUniforms:w}),getShaderSource:A=>{let P=Z("probs",r.dataType,r.dims),x=Z("v",t.dataType,t.dims),E=ne("output",r.dataType,f),O=[{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 = ${d}u;\n var tileQ: array<${P.type.value}, ${d*d}>;\n var tileK: array<${P.type.value}, ${d*d}>;\n ${A.registerUniforms(O).declareVariables(P,x,E)}\n ${A.mainStart([d,d,1])}\n let headIdx = workgroup_id.z;\n let m = global_id.y;\n let n = global_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${P.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads;\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + currentBatchHeadNumber * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`}}},ai=(e,r,t,u,s,c,f,d,g,w,C)=>{let $=e.outputCount>1,A=e.outputCount>2,P=$&&A?w.pastSequenceLength:0,x=P+w.kvSequenceLength,E=[w.batchSize,w.numHeads,x,w.headSize],O=f?[f,t]:[t],B=$?e.compute(oi(O,2,E,t.dataType),{inputs:O,outputs:[1]})[0]:t,R=[w.batchSize,w.numHeads,x,w.headSize],j=d?[d,u]:[u],U=A?e.compute(oi(j,2,R,u.dataType),{inputs:j,outputs:[2]})[0]:u,L=[r,B];g&&L.push(g);let F=e.compute(Pg(e,r,B,g,w,C,P),{inputs:L,outputs:[-1]})[0];e.compute(Eg(e,F,w.batchSize*w.numHeads*w.sequenceLength,x),{inputs:[F],outputs:[]});let te=[F,U];e.compute(kg(e,F,U,w,P),{inputs:te,outputs:[0]})},Og=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],u=r.sequenceLength,s=r.inputHiddenSize,c=r.headSize,f=12,d={x:Math.ceil(r.headSize/f),y:Math.ceil(r.sequenceLength/f),z:r.batchSize*r.numHeads},g=[e.inputs[0],e.inputs[1],e.inputs[2]],w=[{type:12,data:u},{type:12,data:s},{type:12,data:c},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],C=$=>{let A=ne("output_q",g[0].dataType,t),P=ne("output_k",g[0].dataType,t),x=ne("output_v",g[0].dataType,t),E=Z("input",g[0].dataType,g[0].dims),O=Z("weight",g[1].dataType,g[1].dims),B=Z("bias",g[2].dataType,g[2].dims),R=E.type.storage,j=[{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 = ${f}u;\n var tileInput: array<${R}, ${f*f}>;\n var tileWeightQ: array<${R}, ${f*f}>;\n var tileWeightK: array<${R}, ${f*f}>;\n var tileWeightV: array<${R}, ${f*f}>;\n ${$.registerUniforms(j).declareVariables(E,O,B,A,P,x)}\n ${$.mainStart([f,f,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${R}(0);\n var valueK = ${R}(0);\n var valueV = ${R}(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:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:w}),getShaderSource:C},{inputs:g,outputs:[-1,-1,-1]})},bl=(e,r)=>{let t=Tg(e.inputs,r),[u,s,c]=Og(e,t);return ai(e,u,s,c,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t,r)}});var Rg,Bg,Dg,vl,wl=ae(()=>{"use strict";Rr();Te();De();nt();Re();Rg=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(u,s,c)=>{let f=s.length;if(f!==u.length)throw new Error(`${c}: num dimensions != ${f}`);s.forEach((d,g)=>{if(d!==u[g])throw new Error(`${c}: dim[${g}] do not match`)})};if(e[0].dims.length>1){let u=r.format==="NHWC"?r.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,r.spatial?2:void 0);t(e[1].dims,u,"Invalid input scale"),t(e[2].dims,u,"Invalid input B"),t(e[3].dims,u,"Invalid input mean"),t(e[4].dims,u,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},Bg=(e,r)=>{let{epsilon:t,spatial:u,format:s}=r,c=e[0].dims,f=u?He(c[c.length-1]):1,d=s==="NHWC"&&c.length>1?f:1,g=K.size(c)/f,w=u,C=w?c.length:c,$=Z("x",e[0].dataType,e[0].dims,f),A=Z("scale",e[1].dataType,e[1].dims,d),P=Z("bias",e[2].dataType,e[2].dims,d),x=Z("inputMean",e[3].dataType,e[3].dims,d),E=Z("inputVar",e[4].dataType,e[4].dims,d),O=ne("y",e[0].dataType,C,f),B=()=>{let j="";if(u)j=`let cOffset = ${c.length===1?"0u":s==="NHWC"?`outputIndices[${c.length-1}] / ${f}`:"outputIndices[1]"};`;else if(s==="NCHW")j=`\n ${O.indicesSet("outputIndices","0","0")}\n let cOffset = ${O.indicesToOffset("outputIndices")};`;else{j=`var cIndices = ${A.type.indices}(0);\n cIndices[0] = outputIndices[${c.length-1}];`;for(let U=1;U`\n const epsilon = ${t};\n ${j.registerUniform("outputSize","u32").declareVariables($,A,P,x,E,O)}\n ${j.mainStart()}\n ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${O.offsetToIndices(`global_idx * ${f}`)};\n ${B()}\n let scale = ${A.getByOffset("cOffset")};\n let bias = ${P.getByOffset("cOffset")};\n let inputMean = ${x.getByOffset("cOffset")};\n let inputVar = ${E.getByOffset("cOffset")};\n let x = ${$.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${O.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${u}_${f}`,inputDependencies:w?["rank","type","type","type","type"]:void 0},getShaderSource:R,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:w?[{type:12,data:g},...se(c)]:[{type:12,data:g}]})}},Dg=e=>ke(e),vl=(e,r)=>{let{inputs:t,outputCount:u}=e,s=Dg({...r,outputCount:u});if(Or.webgpu.validateInputContent&&Rg(t,s),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Bg(t,s))}});var zg,Mg,_l,$l=ae(()=>{"use strict";De();Re();zg=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")},Mg=e=>{let r=e[0].dims,t=e[0].dims[2],u=K.size(r)/4,s=e[0].dataType,c=Z("input",s,r,4),f=Z("bias",s,[t],4),d=Z("residual",s,r,4),g=ne("output",s,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:C=>`\n const channels = ${t}u / 4;\n ${C.declareVariables(c,f,d,g)}\n\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes(u)}\n let value = ${c.getByOffset("global_idx")}\n + ${f.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")};\n ${g.setByOffset("global_idx","value")}\n }`}},_l=e=>{zg(e.inputs),e.compute(Mg(e.inputs))}});var jg,Ve,Cl,Sl,xl,Il,Al,Tl,El,Pl,kl,Ug,Ol,Rl,Bl,Dl,si,zl,ui,Ml,jl,Ul,Vl,Wl,Nl,Gl,Hl,Ll,Fl,ql,Kl,Yl,Zl,Ql,Xl,Jl,ed,Xi,Ji,td,rd,nd,li=ae(()=>{"use strict";Te();De();nt();Re();jg=(e,r,t,u,s,c)=>{let f=Math.ceil(r/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let g=Z("inputData",t,[f],4),w=ne("outputData",u,[f],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(g,w)}\n\n ${c??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${g.getByOffset("global_idx")};\n ${w.setByOffset("global_idx",d)}\n }`},Ve=(e,r,t,u,s,c=e.dataType)=>({name:r,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:f=>jg(f,K.size(e.dims),e.dataType,c,t,u),getRunData:f=>({outputs:[{dims:e.dims,dataType:c}],dispatchGroup:{x:Math.ceil(K.size(f[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(K.size(e.dims)/4)}]})}),Cl=e=>{e.compute(Ve(e.inputs[0],"Abs","abs"))},Sl=e=>{e.compute(Ve(e.inputs[0],"Acos","acos"))},xl=e=>{e.compute(Ve(e.inputs[0],"Acosh","acosh"))},Il=e=>{e.compute(Ve(e.inputs[0],"Asin","asin"))},Al=e=>{e.compute(Ve(e.inputs[0],"Asinh","asinh"))},Tl=e=>{e.compute(Ve(e.inputs[0],"Atan","atan"))},El=e=>{e.compute(Ve(e.inputs[0],"Atanh","atanh"))},Pl=e=>ke(e),kl=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute \'to\' from \'Cast\' operator): ${r.to}`)}e.compute(Ve(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},Ug=e=>{let r=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:ei,t=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:ti;return ke({min:r,max:t})},Ol=(e,r)=>{let t=e.inputs.length===1?r:Ug(e.inputs),u=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"Clip",s=>`clamp(${s}, clip_min_, clip_max_)`,`\n const clip_min_: vec4<${u}> = vec4(${u}(${t.min}));\n const clip_max_: vec4<${u}> = vec4(${u}(${t.max}));\n`,t.cacheKey),{inputs:[0]})},Rl=e=>{e.compute(Ve(e.inputs[0],"Ceil","ceil"))},Bl=e=>{e.compute(Ve(e.inputs[0],"Cos","cos"))},Dl=e=>{e.compute(Ve(e.inputs[0],"Cosh","cosh"))},si=e=>ke(e),zl=(e,r)=>{let t=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"Elu",u=>`elu_vf32(${u})`,`\n const elu_alpha_ = ${t}(${r.alpha});\n\n fn elu_f32(a: ${t}) -> ${t} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,r.cacheKey))},ui=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,Ml=e=>{let r=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ui(r)))},jl=e=>{e.compute(Ve(e.inputs[0],"Exp","exp"))},Ul=e=>{e.compute(Ve(e.inputs[0],"Floor","floor"))},Vl=e=>{let r=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ui(r)))},Wl=(e,r)=>{let t=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"LeakyRelu",u=>`select(leaky_relu_alpha_ * ${u}, ${u}, ${u} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},Nl=e=>{e.compute(Ve(e.inputs[0],"Not",r=>`!${r}`))},Gl=e=>{e.compute(Ve(e.inputs[0],"Neg",r=>`-${r}`))},Hl=e=>{e.compute(Ve(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Ll=e=>{let r=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},Fl=e=>{e.compute(Ve(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},ql=e=>ke(e),Kl=(e,r)=>{let t=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"HardSigmoid",u=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${u} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},Yl=e=>{e.compute(Ve(e.inputs[0],"Sin","sin"))},Zl=e=>{e.compute(Ve(e.inputs[0],"Sinh","sinh"))},Ql=e=>{e.compute(Ve(e.inputs[0],"Sqrt","sqrt"))},Xl=e=>{e.compute(Ve(e.inputs[0],"Tan","tan"))},Jl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,ed=e=>{e.compute(Ve(e.inputs[0],"Tanh",Jl))},Xi=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Jl("v")};\n}\n`,Ji=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,td=e=>{let r=at(e.inputs[0].dataType);e.compute(Ve(e.inputs[0],"FastGelu",Ji,Xi(r),void 0,e.inputs[0].dataType))},rd=(e,r)=>{let t=at(e.inputs[0].dataType);return e.compute(Ve(e.inputs[0],"ThresholdedRelu",u=>`select(vec4<${t}>(0.0), ${u}, ${u} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},nd=e=>{e.compute(Ve(e.inputs[0],"Log","log"))}});var Vg,Wg,od,ad=ae(()=>{"use strict";De();Re();li();Vg=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")},Wg=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Z("input",e[0].dataType,e[0].dims,4),u=Z("bias",e[0].dataType,[e[0].dims[2]],4),s=ne("output",e[0].dataType,r,4),c=K.size(r)/4,f=Ne(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)}}),getShaderSource:g=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${g.declareVariables(t,u,s)}\n\n ${ui(f)}\n\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes(c)}\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 ${s.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},od=e=>{Vg(e.inputs),e.compute(Wg(e.inputs))}});var Ng,Gg,Mt,sd,ud,ld,dd,cd,fd,pd,md,hd,gd,yd=ae(()=>{"use strict";Te();De();Re();Ng=(e,r,t,u,s,c,f,d,g,w,C,$)=>{let A,P;typeof d=="string"?A=P=(R,j)=>`${d}((${R}),(${j}))`:typeof d=="function"?A=P=d:(A=d.scalar,P=d.vector);let x=ne("outputData",C,u.length,4),E=Z("aData",g,r.length,4),O=Z("bData",w,t.length,4),B;if(s)if(c){let R=K.size(r)===1,j=K.size(t)===1,U=r.length>0&&r[r.length-1]%4===0,L=t.length>0&&t[t.length-1]%4===0;R||j?B=x.setByOffset("global_idx",P(R?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),j?`${O.type.value}(${O.getByOffset("0")}.x)`:O.getByOffset("global_idx"))):B=`\n let outputIndices = ${x.offsetToIndices("global_idx * 4u")};\n let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",x)};\n let offsetB = ${O.broadcastedIndicesToOffset("outputIndices",x)};\n ${x.setByOffset("global_idx",P(f||U?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,f||L?O.getByOffset("offsetB / 4u"):`${O.type.value}(${O.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else B=x.setByOffset("global_idx",P(E.getByOffset("global_idx"),O.getByOffset("global_idx")));else{if(!c)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let R=(j,U,L="")=>{let F=`aData[indexA${U}][componentA${U}]`,te=`bData[indexB${U}][componentB${U}]`;return`\n let outputIndices${U} = ${x.offsetToIndices(`global_idx * 4u + ${U}u`)};\n let offsetA${U} = ${E.broadcastedIndicesToOffset(`outputIndices${U}`,x)};\n let offsetB${U} = ${O.broadcastedIndicesToOffset(`outputIndices${U}`,x)};\n let indexA${U} = offsetA${U} / 4u;\n let indexB${U} = offsetB${U} / 4u;\n let componentA${U} = offsetA${U} % 4u;\n let componentB${U} = offsetB${U} % 4u;\n ${j}[${U}] = ${L}(${A(F,te)});\n `};C===9?B=`\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));`:B=`\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,O,x)}\n\n ${$??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${B}\n }`},Gg=(e,r,t,u,s,c,f=t.dataType)=>{let d=!K.areEqual(t.dims,u.dims),g=t.dims,w=K.size(t.dims),C=!1,$=!1,A=[d];if(d){let P=Ot.calcShape(t.dims,u.dims,!1);if(!P)throw new Error("Can\'t perform binary op on the given tensors");g=P,w=K.size(g);let x=K.size(t.dims)===1,E=K.size(u.dims)===1,O=t.dims.length>0&&t.dims[t.dims.length-1]%4===0,B=u.dims.length>0&&u.dims[u.dims.length-1]%4===0;A.push(x),A.push(E),A.push(O),A.push(B);let R=1;for(let j=1;jP.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:P=>Ng(P,t.dims,u.dims,g,C,d,$,s,t.dataType,u.dataType,f,c),getRunData:()=>({outputs:[{dims:g,dataType:f}],dispatchGroup:{x:Math.ceil(w/64/4)},programUniforms:[{type:12,data:Math.ceil(K.size(g)/4)},...se(t.dims,u.dims,g)]})}},Mt=(e,r,t,u,s,c)=>{e.compute(Gg(r,s??"",e.inputs[0],e.inputs[1],t,u,c))},sd=e=>{Mt(e,"Add",(r,t)=>`${r}+${t}`)},ud=e=>{Mt(e,"Div",(r,t)=>`${r}/${t}`)},ld=e=>{Mt(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},dd=e=>{Mt(e,"Mul",(r,t)=>`${r}*${t}`)},cd=e=>{let r=Z("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Mt(e,"Pow",{scalar:(u,s)=>`pow_custom(${u},${s})`,vector:(u,s)=>`pow_vector_custom(${u},${s})`},`\n fn pow_custom(a : ${r}, b : ${r}) -> ${r} {\n if (b == ${r}(0.0)) {\n return ${r}(1.0);\n } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) {\n return ${r}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> {\n // TODO: implement vectorized pow\n return vec4<${r}>(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 `)},fd=e=>{Mt(e,"Sub",(r,t)=>`${r}-${t}`)},pd=e=>{Mt(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},md=e=>{Mt(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},hd=e=>{Mt(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},gd=e=>{Mt(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}});var At,Tt,Et,di,Ft=ae(()=>{"use strict";Te();De();At=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Tt=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},Et=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},di=e=>{let r=e?.activation||"";if(r==="HardSigmoid"){let[t,u]=e?.activation_params||[.2,.5];return{activation:r,alpha:t,beta:u}}else if(r==="Clip"){let[t,u]=e?.activation_params||[ei,ti];return{activation:r,clipMax:u,clipMin:t}}else if(r==="LeakyRelu"){let[t]=e?.activation_params||[.01];return{activation:r,alpha:t}}return{activation:r}}});var st,ci,fi=ae(()=>{"use strict";st=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},ci=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var pi,eo=ae(()=>{"use strict";pi=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 Lg,Fg,cn,bd,qg,fn,Kg,mi,pn=ae(()=>{"use strict";Te();De();Re();Ft();fi();Lg=(e,r)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${r?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${r?", batchIndices":""});\n `,Fg=(e,r)=>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 ${r===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 ${r===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 ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,cn=(e,r,t="f32",u,s=!1,c=32,f=!1,d=32)=>{let g=r[1]*e[1],w=r[0]*e[0],C=s?g:c,$=s?c:g,A=C/r[0],P=c/r[1];if(!((s&&A===4&&e[1]===4||!s&&(A===3||A===4))&&C%r[0]===0&&c%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${A} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${A} must be 3 or 4.\n tileAWidth ${C} must be divisible by workgroupSize[0]${r[0]}. tileInner ${c} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${C/A}>, ${$}>;\nvar mm_Bsub: array, ${w/e[0]}>, ${c}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${A};\nconst tileInner = ${c};\n\n@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[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 = ${f?"0":"i32(globalId.z)"};\n ${u?`let batchIndices = ${u.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${g};\n\n let num_tiles = ${f?`${Math.ceil(d/c)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${f?`i32(globalId.z) * ${d}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${P};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${Lg(s,u)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${P}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${u?", 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 ${A===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${Fg(s,A)}\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}`},bd=(e,r)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${r?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${r?", batchIndices":""});\n `,qg=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",fn=(e,r,t="f32",u,s=!1,c=32,f=!1,d=32,g=!1)=>{let w=e[1]*r[1],C=e[0]*r[0],$=s?w:c,A=s?c:w;if(!(A%r[1]===0&&$%r[0]===0&&c%r[1]===0))throw new Error(`tileAHight ${A} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${$} must be divisible by workgroupSize[0]${r[0]}, tileInner ${c} must be divisible by workgroupSize[1]${r[1]}`);let P=A/r[1],x=$/r[0],E=c/r[1],O=g?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${w};\n let globalColStart = i32(workgroupId.x) * ${C};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${A}; inputRow = inputRow + ${r[1]}) {\n for (var inputCol = localCol; inputCol < ${$}; inputCol = inputCol + ${r[0]}) {\n ${bd(s,u)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${r[1]}) {\n for (var inputCol = localCol; inputCol < ${C}; inputCol = inputCol + ${r[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${u?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${t}, 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 * ${r[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${s?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[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 * ${r[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${r[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) * ${w};\n\nlet tileRowA = i32(localId.y) * ${P};\nlet tileColA = i32(localId.x) * ${x};\nlet tileRowB = i32(localId.y) * ${E};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${P}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${x}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${bd(s,u)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${E}; 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${u?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${t}, 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 ${qg(s)}\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, ${A}>;\n var mm_Bsub : array, ${c}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${c};\n\n@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[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 = ${f?"0":"i32(globalId.z)"};\n ${u?`let batchIndices = ${u.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${f?`${Math.ceil(d/c)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${f?`i32(globalId.z) * ${d}`:"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 ${O}\n }\n`},Kg=(e,r,t,u,s,c=!1)=>{let[f,d,g]=s,[w,C,$,A]=u,P=Br(f,g),x=Br(d,g),E=Ne(u[0].type.tensor),O=()=>{let j=C.rank,U=w.rank,L=`var aIndices: ${C.type.indices};`;for(let F=j-2-1,te=U-1;F>=0;F--,te--)L+=`\naIndices[${F}] = ${U>1?`batchIndices[${te}]`:"batchIndices"};`;return P.forEach(F=>{L+=`\naIndices[${F}] = 0;`}),L+=`\naIndices[${j-2}] = u32(row);\n aIndices[${j-1}] = u32(colIn);`,L},B=()=>{let j=$.rank,U=w.rank,L=`var bIndices: ${$.type.indices};`;for(let F=j-2-1,te=U-1;F>=0;F--,te--)L+=`\nbIndices[${F}] = ${U>1?`batchIndices[${te}]`:"batchIndices"};`;return x.forEach(F=>{L+=`\nbIndices[${F}] = 0;`}),L+=`\nbIndices[${j-2}] = u32(row);\n bIndices[${j-1}] = u32(colIn);`,L};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${w.type.indices}) -> ${st(e,E)} {\n var value = ${st(e,E)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n ${O()}\n value = ${C.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${w.type.indices}) -> ${st(e,E)} {\n var value = ${st(e,E)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n ${B()}\n value = ${$.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${st(e,E)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${r?`value = value + ${c?"bias[colIn]":`${st(e,E)}(bias[row])`};`:""}\n ${t}\n ${A.setByIndices("vec3(coords)","value")}\n }\n }\n `},mi=(e,r,t,u,s=!1)=>{let c=e[0].dims,f=e[1].dims,d=c.slice(0,-2),g=f.slice(0,-2),w=u?u.slice(0,-2):t.slice(0,-2),C=K.size(w),$=c[c.length-2],A=c[c.length-1],P=f[f.length-1],x=A%4===0&&P%4===0,E=$<=8?[4,1,1]:[4,4,1],O=[8,8,1],B=[Math.ceil(P/O[0]/E[0]),Math.ceil($/O[1]/E[1]),Math.ceil(C/O[2]/E[2])],R=x?4:1,j=[...d,$,A/R],U=j.length,L=[...g,A,P/R],F=L.length,te=[C,$,P/R],J=[{type:6,data:$},{type:6,data:P},{type:6,data:A}];Tt(r,J),J.push(...se(w,j,L));let oe=["rank","rank"],le=e.length>2;le&&(J.push(...se(e[2].dims)),oe.push("rank")),J.push(...se(te));let ge=X=>{let pe=w.length,we=ri("batchDims",e[0].dataType,pe,1),ue=Ne(e[0].dataType),me=Z("a",e[0].dataType,U,R),Ee=Z("b",e[1].dataType,F,R),Pe=ne("result",e[0].dataType,te.length,R),Ce=[me,Ee];if(le){let ee=s?R:1;Ce.push(Z("bias",e[2].dataType,e[2].dims.length,ee))}let be=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Et(r,be);let Ae=Ne(Pe.type.tensor),_e=At(r,Pe.type.value,Ae),Je=Kg(R,le,_e,[we,me,Ee,Pe],[d,g,w],s);return`\n ${X.registerUniforms(be).registerInternalVariables(we).declareVariables(...Ce,Pe)}\n ${Je}\n ${x?cn(E,O,ue,we):fn(E,O,ue,we)}\n `};return{name:"MatMul",shaderCache:{hint:`${E};${r.activation};${x};${s}`,inputDependencies:oe},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:B[0],y:B[1],z:B[2]},programUniforms:J}),getShaderSource:ge}}});var Yg,vd,wd=ae(()=>{"use strict";Te();Lt();Re();Ft();fi();eo();pn();Yg=(e,r,t,u,s=!1,c,f=4,d=4,g=4,w="f32")=>{let C=le=>{switch(le){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${w}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${le} is not supported.`)}},$=le=>{switch(le){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 ${le} is not supported.`)}},A=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,P=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 `,x=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",E=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",O=e?"row":"col",B=e?"col":"row",R=`\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 = ${O} / outWidth;\n let outCol = ${O} % outWidth;\n\n let WRow = ${B} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${B} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${B} % inChannels;\n var resData = ${st(f,w)}(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 < ${x} && xCol >= 0 && xCol < ${E}) {\n ${A}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${C(f)}\n }\n return resData;`,j=e?r&&u?`\n let col = colIn * ${f};\n ${R}`:`\n let col = colIn * ${f};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${R}\n }\n return ${st(f,w)}(0.0);`:u&&t?`\n let col = colIn * ${f};\n ${R}`:`\n let col = colIn * ${f};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${R}\n }\n return ${st(f,w)}(0.0);`,U=`${$(d)}`,L=st(g,w),F=e?st(f,w):st(d,w),te=e?st(d,w):st(f,w),J=At(c,L,w);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${F} {\n ${e?j:U}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${te} {\n ${e?U:j}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${L}) {\n let col = colIn * ${g};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${P}\n ${ci(s)}\n ${J}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},vd=(e,r,t,u,s,c,f,d)=>{let g=r.format==="NHWC",w=g?e[0].dims[3]:e[0].dims[1],C=t[0],$=g?t[2]:t[3],A=g?t[1]:t[2],P=g?t[3]:t[1],x=g&&(w%4===0||w%3===0)&&P%4===0,E=g?P:$*A,O=g?$*A:P,B=[8,8,1],R=u<=8?[4,1,1]:[4,4,1],j=[Math.ceil(E/B[0]/R[0]),Math.ceil(O/B[1]/R[1]),Math.ceil(C/B[2]/R[2])];Fe("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${j}`);let U=x?g&&w%4!==0?3:4:1,L=B[1]*R[1],F=B[0]*R[0],te=Math.max(B[0]*U,B[1]),J=u%L===0,oe=s%F===0,le=c%te===0,ge=x?[U,4,4]:[1,1,1],X=[{type:6,data:u},{type:6,data:s},{type:6,data:c},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];Tt(r,X),X.push(...se(e[0].dims,e[1].dims));let pe=["rank","rank"];f&&(X.push(...se(e[2].dims)),pe.push("rank")),X.push(...se(t));let we=ue=>{let me=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Et(r,me);let Ee=x?4:1,Pe=Ne(e[0].dataType),Ce=`\n fn setOutputAtIndex(flatIndex : i32, value : ${x?`vec4<${Pe}>`:Pe}) {\n result[flatIndex] = ${x?`vec4<${Pe}>`:Pe}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${x?`vec4<${Pe}>`:Pe}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${x?"/ 4":""}, value);\n }`,be=Z("x",e[0].dataType,e[0].dims.length,U===3?1:U),Ae=Z("w",e[1].dataType,e[1].dims.length,Ee),_e=[be,Ae],Je=ne("result",e[0].dataType,t.length,Ee);if(f){let ee=Z("bias",e[2].dataType,e[2].dims.length,Ee);_e.push(ee),Ce+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${x?`vec4<${Pe}>`:Pe} {\n return bias[coords.${g?"w":"y"}${x?"/ 4":""}];\n }`}return`\n ${pi("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 ${ue.registerUniforms(me).declareVariables(..._e,Je)}\n ${Ce}\n ${Yg(g,J,oe,le,f,r,ge[0],ge[1],ge[2],Pe)}\n ${x?cn(R,B,Pe,void 0,!g,te):fn(R,B,Pe,void 0,!g,te,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${U};${x};${J};${oe};${le};${L};${F};${te}`,inputDependencies:pe},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:j[0],y:j[1],z:j[2]},programUniforms:X}),getShaderSource:we}}});var to,_d,$d=ae(()=>{"use strict";Te();De();Re();ro();Ft();to=(e,r,t)=>{let u=e.length>2,s=u?"value += b[output_channel];":"",c=e[0].dims,f=e[1].dims,d=f[0]/r.group,g=r.format==="NHWC",w=hi(c,f,r.dilations,r.pads,r.strides,g),C=K.size(w),$=[{type:12,data:C},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:d}];Tt(r,$),$.push(...se(c,f));let A=["rank","rank"];u&&($.push(...se(e[2].dims)),A.push("rank")),$.push(...se(w));let P=x=>{let E=ne("output",e[0].dataType,w.length),O=Ne(E.type.tensor),B=At(r,E.type.value,O),R=Z("x",e[0].dataType,c.length),j=Z("w",e[1].dataType,f.length),U=[R,j];u&&U.push(Z("b",e[2].dataType,e[2].dims.length));let L=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Et(r,L),`\n ${x.registerUniforms(L).declareVariables(...U,E)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${E.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${g?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${g?1:2}], outputIndices[${g?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel / uniforms.output_channels_per_group;\n\n var value: ${E.type.value} = ${E.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = group_id * uniforms.w_shape[1] + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[${g?1:2}]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[${g?2:3}]) {\n continue;\n }\n\n let xVal = ${g?R.get("batch","xHeight","xWidth","input_channel"):R.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${j.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${s}\n ${B}\n ${E.setByOffset("global_idx","value")}\n }`};return{name:"GroupedConv",shaderCache:{hint:r.cacheKey,inputDependencies:A},getRunData:()=>({outputs:[{dims:t?t(w):w,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:$}),getShaderSource:P}},_d=(e,r,t)=>{let u=e.length>2,s=He(t[3]),c=He(t[2]),f=K.size(t)/s/c,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/s],g=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/s],w=[t[0],t[1],t[2],t[3]/s],C=[{type:12,data:f},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];Tt(r,C),C.push(...se(d,g,w));let $=(c-1)*r.strides[1]+g[1],A=P=>{let x=ne("output",e[0].dataType,w.length,s),E=Ne(x.type.tensor),O=At(r,x.type.value,E),B=Z("x",e[0].dataType,d.length,s),R=Z("w",e[1].dataType,g.length,s),j=[B,R];u&&j.push(Z("b",e[2].dataType,e[2].dims,s));let U=u?"value += b[output_channel];":"",L=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Et(r,L),`\n ${P.registerUniforms(L).declareVariables(...j,x)}\n ${P.mainStart()}\n ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${c}u;\n let col = (index1 % width1) * ${c}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${B.type.value}, ${$}>;\n var values: array<${x.type.value}, ${c}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w\'s height/width.\n for (var w_height: u32 = 0u; w_height < ${g[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${$}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${B.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${B.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${g[1]}; w_width++) {\n let w_val = ${R.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${c}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${c}u; i++) {\n var value = values[i];\n ${U}\n ${O}\n ${x.set("batch","row","col + i","output_channel","value")};\n }\n }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${s};${c};${$};${g[0]};${g[1]}`,inputDependencies:u?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:C}),getShaderSource:A}}});var no,Zg,Cd,io=ae(()=>{"use strict";Te();De();pn();Re();Ft();no=(e,r,t,u,s=!1)=>{let c=e[0].dims,f=e[1].dims,d=c[c.length-2],g=f[f.length-1],w=c[c.length-1],C=He(g),$=He(w),A=He(d),P=K.size(t)/C/A,x=e.length>2,E=u?u.slice(0,-2):t.slice(0,-2),B=[K.size(E),d,g],R=[{type:12,data:P},{type:12,data:d},{type:12,data:g},{type:12,data:w}];Tt(r,R),R.push(...se(E,c,f)),x&&R.push(...se(e[2].dims)),R.push(...se(B));let j=U=>{let L=ri("batch_dims",e[0].dataType,E.length),F=Z("a",e[0].dataType,c.length,$),te=Z("b",e[1].dataType,f.length,C),J=ne("output",e[0].dataType,B.length,C),oe=Ne(J.type.tensor),le=At(r,J.type.value,oe),ge=[F,te],X="";if(x){let be=s?C:1;ge.push(Z("bias",e[2].dataType,e[2].dims.length,be)),X=`${s?`value += bias[col / ${be}];`:`value += ${J.type.value}(bias[row + i]);`}`}let pe=c.slice(0,-2),we=f.slice(0,-2),ue=Br(pe,E),me=Br(we,E),Ee=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Et(r,Ee);let Pe=(be,Ae)=>{let _e=be.rank,Je=be.name;if(_e===2)return`var ${Je}_indices = ${be.type.indices}(0u, 0u);`;let ee=L.rank,ce=`var ${Je}_indices: ${be.type.indices};`;for(let Be=_e-2-1,tt=ee-1;Be>=0;Be--,tt--)ce+=`\n${Je}_indices[${Be}] = ${ee>1?`batch_indices[${tt}]`:"batch_indices"};`;return Ae.forEach(Be=>{ce+=`\n${Je}_indices[${Be}] = 0;`}),ce+=`${Je}_indices[${_e-2}] = 0u;\n ${Je}_indices[${_e-1}] = 0u;`,ce},Ce=()=>{let be=`var a_data: ${F.type.value};`;for(let Ae=0;Ae<$;Ae++)be+=`\n let b_data${Ae} = b[(b_offset + (k + ${Ae}) * uniforms.N + col) / ${C}];`;for(let Ae=0;Ae;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${$}) {\n ${Ce()}\n }\n for (var i = 0u; i < ${A}u; i++) {\n var value = values[i];\n ${X}\n ${le}\n let cur_indices = ${J.type.indices}(batch, row + i, col);\n let offset = ${J.indicesToOffset("cur_indices")};\n ${J.setByOffset(`offset / ${C}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${C};${$};${A};${s}`,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:R}),getShaderSource:j}},Zg=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.")},Cd=e=>{Zg(e.inputs);let r=Ot.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can\'t use matmul on the given tensors");let t=r[r.length-1],u=e.inputs[0].dims[e.inputs[0].dims.length-1];t<8&&u<8?e.compute(no(e.inputs,{activation:""},r)):e.compute(mi(e.inputs,{activation:""},r))}});var hi,oo,Qg,Sd,ao,Xg,Jg,so,ro=ae(()=>{"use strict";De();wd();pn();$d();Ft();io();Dr();hi=(e,r,t,u,s,c)=>{let f=e[0],d=e.slice(c?1:2,c?3:4),g=d.length,w=r[0],$=r.slice(2).map((x,E)=>x+(x-1)*(t[E]-1)),P=d.map((x,E)=>x+u[E]+u[E+g]).map((x,E)=>Math.floor((x-$[E]+s[E])/s[E]));return P.splice(0,0,f),P.splice(c?3:1,0,w),P},oo=[2,3,1,0],Qg=(e,r)=>{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 t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],u=e[1].dims[1]*r.group;if(t!==u)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 s=e[0].dims.length-2;if(r.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(r.strides.length!==s)throw new Error(`strides should be ${s}D`);if(r.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Sd=(e,r)=>{let t=e.kernelShape.slice();for(let c=2;c{let r=di(e),t=e.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,c=e.group,f=e.kernel_shape,d=e.pads,g=e.strides,w=e.w_is_const();return{autoPad:u,format:t,dilations:s,group:c,kernelShape:f,pads:d,strides:g,wIsConst:w,...r,cacheKey:`${e.format};${r.activation};`}},Xg=(e,r,t)=>{let u=Sd(t,r),s=t.format==="NHWC";if(t.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&s&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1){let te=hi(r[0].dims,r[1].dims,t.dilations,u.pads,t.strides,s),J=e.kernelCustomData.wT??e.compute($t(r[1],oo),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=J);let oe=[r[0],J];r.length===3&&oe.push(r[2]),e.compute(_d(oe,u,te),{inputs:oe})}else e.compute(to(r,u));return}let c=r.length===3,f=r[0].dims[s?1:2],d=r[0].dims[s?2:3],g=r[0].dims[s?3:1],w=r[1].dims[2],C=r[1].dims[3],$=hi(r[0].dims,r[1].dims,t.dilations,u.pads,t.strides,s),A=$[s?1:2],P=$[s?2:3],x=$[s?3:1],E=s&&w===f&&C===d&&t.pads[0]===0&&t.pads[1]===0;if(E||w===1&&C===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let F=$[0],te,J,oe,le=[];if(s){let pe=e.kernelCustomData.wT??e.compute($t(r[1],oo),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=pe),E){let we=f*d*g;te=r[0].reshape([1,F,we]),J=pe.reshape([1,we,x]),oe=[1,F,x]}else te=r[0].reshape([F,f*d,g]),J=pe.reshape([1,g,x]),oe=[F,A*P,x];le.push(te),le.push(J)}else te=r[0].reshape([F,g,f*d]),J=r[1].reshape([1,x,g]),oe=[F,x,A*P],le.push(J),le.push(te);c&&le.push(r[2]);let ge=oe[2],X=le[0].dims[le[0].dims.length-1];ge<8&&X<8?e.compute(no(le,u,$,oe,s),{inputs:le}):e.compute(mi(le,u,$,oe,s),{inputs:le});return}let O=!0,B=e.kernelCustomData.wT??e.compute($t(r[1],oo),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=B);let R=[r[0],B];c&&R.push(r[2]);let j=s?A*P:x,U=s?x:A*P,L=w*C*g;e.compute(vd(R,u,$,j,U,L,c,O),{inputs:R})},Jg=(e,r)=>{let t=r.format==="NHWC",u=[e.inputs[0].reshape(t?[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&&u.push(e.inputs[2]);let s=[0,r.pads[0],0,r.pads[1]],c=[1].concat(r.strides),f=[1].concat(r.dilations),d=[1].concat(r.kernelShape),g=Sd({...r,pads:s,strides:c,dilations:f,kernelShape:d},u);e.compute(to(u,g,w=>t?[w[0],w[2],w[3]]:[]))},so=(e,r)=>{Qg(e.inputs,r),e.inputs[0].dims.length===3?Jg(e,r):Xg(e,e.inputs,r)}});var ey,xd,Id=ae(()=>{"use strict";Te();Lt();Re();Ft();fi();eo();pn();ey=(e,r=!1,t,u,s=4)=>{let c=B=>{switch(B){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 ${u}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${B} is not supported.`)}},f=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,d=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 `,g=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",w=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",C=e?"row":"col",$=e?"col":"row",A=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${C} / outWidth;\n let outCol = ${C} % outWidth;\n\n let WRow = ${$} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${$} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${g}) || fract(xR) > 0.0) {\n return ${u}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${w}) || fract(xC) > 0.0) {\n return ${u}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${$} % inChannels;\n ${f}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,P=e?`\n let col = colIn * ${s};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${A}\n }\n return ${u}(0.0);`:`\n let col = colIn * ${s};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${A}\n }\n return ${u}(0.0);`,x=`\n let col = colIn * ${s};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${c(s)}\n }\n return ${u}(0.0);\n `,E=At(t,u);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${u} {\n ${e?P:x}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${u} {\n ${e?x:P}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${u}) {\n let col = colIn * ${s};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${d}\n ${ci(r)}\n ${E}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value;\n }\n }`},xd=(e,r,t,u,s,c,f,d)=>{let g=r.format==="NHWC",w=g?e[0].dims[3]:e[0].dims[1],C=t[0],$=g?t[2]:t[3],A=g?t[1]:t[2],P=g?t[3]:t[1],x=g&&w%4===0&&w%3&&P%4===0,E=g?P:$*A,O=g?$*A:P,B=[8,8,1],R=u<=8?[4,1,1]:[4,4,1],j=[Math.ceil(E/B[0]/R[0]),Math.ceil(O/B[1]/R[1]),Math.ceil(C/B[2]/R[2])];Fe("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${j}`);let U=x?4:1,L=Math.max(B[0]*U,B[1]),F=x?4:1,te=[r.kernelShape[g?1:2],r.kernelShape[g?2:3]],J=[te[0]+(r.dilations[0]<=1?0:(te[0]-1)*(r.dilations[0]-1)),te[1]+(r.dilations[1]<=1?0:(te[1]-1)*(r.dilations[1]-1))],oe=[J[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),J[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],le=[{type:6,data:u},{type:6,data:s},{type:6,data:c},{type:6,data:r.strides},{type:6,data:r.dilations},{type:6,data:te},{type:6,data:oe}];Tt(r,le),le.push(...se(e[0].dims,e[1].dims));let ge=["rank","rank"];f&&(le.push(...se(e[2].dims)),ge.push("rank")),le.push(...se(t));let X=pe=>{let we=Z("x",e[0].dataType,e[0].dims.length,F),ue=Z("w",e[1].dataType,e[1].dims.length,1),me=ne("result",e[0].dataType,t.length,F),Ee=[we,ue],Pe="";if(f){let Ae=Z("bias",e[2].dataType,e[2].dims.length,F);Ee.push(Ae),Pe+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${Ae.type.value} {\n return bias[coords.${g?"w":"y"}${x?"/ 4":""}];\n }`}let Ce=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:te.length},{name:"pads",type:"i32",length:oe.length}];Et(r,Ce);let be=Ne(e[0].dataType,1);if(be!=="f16"&&be!=="f32")throw new Error(`elemType ${be} is not supported.`);return`\n ${pi("uniforms.result_strides")}\n ${pe.registerUniforms(Ce).declareVariables(...Ee,me)};\n ${Pe}\n ${ey(g,f,r,we.type.value,U)}\n ${x?cn(R,B,be,void 0,!g,L):fn(R,B,be,void 0,!g,L,!1,void 0,d)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${r.cacheKey};${R};${B};${x}`,inputDependencies:ge},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:j[0],y:j[1],z:j[2]},programUniforms:le}),getShaderSource:X}}});var ty,uo,Ad=ae(()=>{"use strict";Te();Lt();De();Re();ty=(e,r,t,u,s,c=!1,f,d,g=!1)=>{let w=g?1:2,C=g?2:3,$=g?3:1,A=c?2:1,P=`\n fn setOutputAtIndex(flatIndex : u32, value : ${c?`vec4<${f}>`:f}) {\n result[flatIndex] = ${c?`vec4<${f}>`:f}(value);\n }`;u&&(P+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${c?`vec4<${f}>`:f} {\n return bias[coords.${g?"w":"y"}${c?"/ 4":""}];\n }`);let x=c?4:1,E=Z("W",r[1].dataType,r[1].dims.length,x),O=Z("Dy",r[0].dataType,r[0].dims.length,x),B=[O,E];u&&B.push(Z("bias",r[2].dataType,[t[$]].length,x));let R=ne("result",r[0].dataType,t.length,x),j=`{\n let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${s?"global_id.y":"workgroup_id.y"} * ${A};\n let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${A}>;\n for (var i = 0; i < ${A}; i++) {\n dotProd[i] = vec4<${f}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${f}(dyCorner.x) + ${f}(wR)) / ${f}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${f}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${f}(dyCorner.y) + ${f}(wC)) / ${f}(uniforms.strides.y);\n let dyC2 = (${f}(dyCorner.y) + 1.0 + ${f}(wC)) / ${f}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${f}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${f}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${O.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${f}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${O.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${f}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${$}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${O.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${f}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${O.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${f}>(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 < ${A}; i = i + 1) {\n let value = dotProd[i] + ${u?"bias[c+i]":`vec4<${f}>(0.0)`};\n ${R.set("batch","r","c + i","d1","value")};\n }\n }`,U=`\n let outputIndices = ${R.offsetToIndices("global_idx")};\n let batch = ${R.indicesGet("outputIndices",0)};\n let d1 = ${R.indicesGet("outputIndices",$)};\n let r = ${R.indicesGet("outputIndices",w)};\n let c = ${R.indicesGet("outputIndices",C)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${f}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${f}(dyRCorner) + ${f}(wR)) / ${f}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${f}(uniforms.Dy_shape[${w}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${f}(dyCCorner) + ${f}(wC)) / ${f}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${f}(uniforms.Dy_shape[${C}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${g?O.get("batch","idyR","idyC","inputChannel"):O.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${E.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${u?"bias[d1]":`${f}(0.0)`};\n ${R.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(d).declareVariables(...B,R)}\n ${P}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${c?j:U}}`},uo=(e,r,t)=>{let u=e.length>2,s=r.outputShape,c=K.size(s),f=[Math.ceil(c/64),1,1];Fe("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${f}`);let d=r.format==="NHWC",g=["rank","rank"],w=[r.strides[0],r.strides[1]],C=[r.kernelShape[d?1:2],r.kernelShape[d?2:3]],$=[r.dilations[0],r.dilations[1]],A=[C[0]+(r.dilations[0]<=1?0:(r.kernelShape[d?1:2]-1)*(r.dilations[0]-1)),C[1]+(r.dilations[1]<=1?0:(r.kernelShape[d?2:3]-1)*(r.dilations[1]-1))],P=[A[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),A[1]-1-Math.floor(r.pads[1]+r.pads[3])/2],x=!1,E=r.group,O=e[1].dims,B=O[0]/E,R=O[1],j=[{type:12,data:c},{type:12,data:w},{type:12,data:C},{type:12,data:$},{type:12,data:A},{type:6,data:P},{type:12,data:B},{type:12,data:R},...se(e[0].dims,e[1].dims)];u&&(j.push(...se(e[2].dims)),g.push("rank")),j.push(...se(s));let U=f[1]===1&&f[2]===1,L=F=>{let te=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:w.length},{name:"filter_dims",type:"u32",length:C.length},{name:"dilations",type:"u32",length:C.length},{name:"effective_filter_dims",type:"u32",length:A.length},{name:"pads",type:"i32",length:P.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],J=Ne(e[0].dataType);return`${ty(F,e,s,u,U,x,J,te,d)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:f[0],y:f[1],z:f[2]},outputs:[{dims:t?t(s):s,dataType:e[0].dataType}],programUniforms:j}),getShaderSource:L}}});var ry,ny,iy,Td,Ed,oy,ay,sy,uy,Pd,kd=ae(()=>{"use strict";Id();Ad();Ft();Dr();ry=(e,r,t,u,s,c)=>(e-1)*r+t+(u-1)*s+1-c,ny=(e,r,t,u,s)=>{let c=Math.floor(e/2);r==="SAME_UPPER"?(t[u]=c,t[s]=e-c):r==="SAME_LOWER"&&(t[u]=e-c,t[s]=c)},iy=(e,r,t,u,s,c,f,d,g,w)=>{let C=e.length-2,$=w.length===0;if(g.length===0)for(let x=0;x{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce(($,A)=>$*A,1)===0){t.length=0;for(let $=2;$$+A,0)===0){let $=r[0].dims.length-2;g=new Array($).fill(1)}let w=e.strides.slice();if(w.reduce(($,A)=>$+A,0)===0){let $=r[0].dims.length-2;w=new Array($).fill(1)}iy(d,t,g,e.autoPad,e.group,s,w,u,f,c);let C=Object.assign({},e);return Object.assign(C,{kernelShape:t,pads:s,outputPadding:f,outputShape:c,dilations:g,strides:w}),C},Ed=e=>{let r=di(e),t=e.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,c=e.group,f=e.kernelShape,d=e.pads,g=e.strides,w=e.wIsConst(),C=e.outputPadding,$=e.outputShape;return{autoPad:u,format:t,dilations:s,group:c,kernelShape:f,outputPadding:C,outputShape:$,pads:d,strides:g,wIsConst:w,...r,cacheKey:`${e.format};${r.activation};`}},oy=(e,r)=>{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 t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],u=e[1].dims[0];if(t!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let c=e[0].dims.length-2;if(r.dilations.reduce((C,$)=>C+$,0)>0&&r.dilations.length!==c)throw new Error(`dilations should be ${c}D`);if(r.strides.reduce((C,$)=>C+$,0)>0&&r.strides.length!==c)throw new Error(`strides should be ${c}D`);if(r.pads.reduce((C,$)=>C+$,0)>0&&r.pads.length!==c*2)throw new Error(`pads should be ${c*2}D`);if(r.outputPadding.length!==c&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${c}D`);if(r.kernelShape.reduce((C,$)=>C+$,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},ay=[2,3,1,0],sy=(e,r,t)=>{let u=Td(t,r),s=t.format==="NHWC",c=u.outputShape,f=c[s?3:1],d=r[0].dims[s?3:1];if(u.group!==1||f===1&&d===1){e.compute(uo(r,u));return}let g=c[s?1:2],w=c[s?2:3],C=r[1].dims[2],$=r[1].dims[3],A=s?g*w:f,P=s?f:g*w,x=C*$*d,E=!0,O=e.kernelCustomData.wT??e.compute($t(r[1],ay),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O);let B=[r[0],O],R=r.length===3;R&&(!s&&r[2].dims.length===1?B.push(r[2].reshape([r[2].dims[0],1,1])):B.push(r[2])),e.compute(xd(B,u,c,A,P,x,R,E),{inputs:B})},uy=(e,r)=>{let t=r.format==="NHWC",u=[e.inputs[0].reshape(t?[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&&u.push(e.inputs[2]);let s=r.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let c=r.dilations;(c.length===0||c[0]===0)&&(c=[1]);let f=r.strides;(f.length===0||f[0]===0)&&(f=[1]);let d=r.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],f=[1].concat(f),c=[1].concat(c),s=[1].concat(s);let g=Td({...r,pads:d,strides:f,dilations:c,kernelShape:s},u);e.compute(uo(u,g,w=>t?[w[0],w[2],w[3]]:[w[0],w[1],w[3]]))},Pd=(e,r)=>{oy(e.inputs,r),e.inputs[0].dims.length===3?uy(e,r):sy(e,e.inputs,r)}});var ly,Od,Rd,Bd=ae(()=>{"use strict";Te();De();nt();Re();ly=(e,r,t,u)=>{let s=K.size(r),c=r.length,f=Z("input",e,c),d=ne("output",e,c),g=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),w=K.normalizeAxis(g,c),C=$=>{let A=` i32(${f.indicesGet("inputIndices","uniforms.axis")}) `,P=xe("uniforms.input_shape","uniforms.axis",c),x=u.reverse?A+(u.exclusive?" + 1":""):"0",E=u.reverse?P:A+(u.exclusive?"":" + 1");return`\n ${$.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(f,d)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${d.offsetToIndices("global_idx")};\n var sum = ${d.type.value}(0);\n let first : i32 = ${x};\n let last : i32 = ${E};\n for (var i : i32 = first; i < last; i++) {\n ${f.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${f.getByIndices("inputIndices")};\n }\n ${d.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:u.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:w},...se(r,r)]}),getShaderSource:C}},Od=(e,r)=>{let t=e.inputs[0].dims,u=e.inputs[0].dataType,s=e.inputs[1];e.compute(ly(u,t,s,r),{inputs:[0]})},Rd=e=>{let r=e.exclusive===1,t=e.reverse===1;return ke({exclusive:r,reverse:t})}});var dy,cy,fy,Dd,zd,Md=ae(()=>{"use strict";Te();De();nt();Re();dy=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},cy=(e,r,t,u)=>{let s=[];s.push(`fn perm(i: ${u.type.indices}) -> ${t.type.indices} {\n var a: ${t.type.indices};`);for(let c=0;c{let t,u,s,c,f,d,g=r.format==="NHWC",w=r.blocksize,C=r.mode==="DCR";g?([t,u,s,c]=e.dims,f=C?[t,u,s,w,w,c/w**2]:[t,u,s,c/w**2,w,w],d=C?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,u,s,c]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],f=C?[t,w,w,c/w**2,u,s]:[t,c/w**2,w,w,u,s],d=C?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let $=e.reshape(f),A=$.dims.length,P=e.dataType,x=Z("a",P,A),E=ne("output",P,A),O=B=>`\n ${B.registerUniform("output_size","u32").declareVariables(x,E)}\n\n ${cy(d,A,x,E)}\n\n ${B.mainStart()}\n ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${E.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${E.setByOffset("global_idx",x.getByIndices("aIndices"))}\n }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:B=>{let R=g?[t,u*w,s*w,c/w**2]:[t,c/w**2,u*w,s*w],j=K.size(R),U=$.dims,L=K.sortBasedOnPerm(U,d);return{outputs:[{dims:R,dataType:B[0].dataType}],dispatchGroup:{x:Math.ceil(j/64)},programUniforms:[{type:12,data:j},...se(U,L)]}},getShaderSource:O}},Dd=(e,r)=>{dy(e.inputs),e.compute(fy(e.inputs[0],r))},zd=e=>ke({blocksize:e.blocksize,mode:e.mode,format:e.format})});var lo,gi,jd,py,my,co,fo,Ud,hy,Vd,Wd,Nd=ae(()=>{"use strict";Te();De();nt();Re();lo="[a-zA-Z]|\\\\.\\\\.\\\\.",gi="("+lo+")+",jd="^"+gi+"$",py="("+gi+",)*"+gi,my="^"+py+"$",co=class{constructor(r=-1){this.symbolToIndices=new Map,this.inputIndex=r}addSymbol(r,t){let u=this.symbolToIndices.get(r);u===void 0?u=[t]:u.push(t),this.symbolToIndices.set(r,u)}},fo=class{constructor(r,t){this.equation=t;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[u,s]=t.includes("->")?t.split("->",2):[t,""];if(!u.match(RegExp(my)))throw new Error("Invalid LHS term");if(u.split(",").forEach((d,g)=>{let w=r[g].dims.slice();if(!d.match(RegExp(jd)))throw new Error("Invalid LHS term");let C=this.processTerm(d,!0,w,g);this.lhs.push(C)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([d,g])=>g.count===1||d==="...").map(([d])=>d).join("");else if(!s.match(RegExp(gi)))throw new Error("Invalid RHS");s.match(RegExp(lo,"g"))?.forEach(d=>{if(d==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let g=this.symbolToInfo.get(d);if(g===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(g.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(r,t,u){let s=this.symbolToInfo.get(r);if(s!==void 0){if(s.dimValue!==t&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(u)}else s={count:1,dimValue:t,inputIndices:[u]};this.symbolToInfo.set(r,s)}processTerm(r,t,u,s=-1){let c=u.length,f=!1,d=[],g=0;if(!r.match(RegExp(jd))&&!t&&r!=="")throw new Error("Invalid LHS term");let w=r.match(RegExp(lo,"g")),C=new co(s);return w?.forEach(($,A)=>{if($==="..."){if(f)throw new Error("Only one ellipsis is allowed per input term");f=!0;let P=c-w.length+1;if(P<0)throw new Error("Ellipsis out of bounds");if(d=u.slice(g,g+P),this.hasEllipsis){if(this.ellipsisDims.length!==d.length||this.ellipsisDims.toString()!==d.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=d;else throw new Error("Ellipsis must be specified in the LHS");for(let x=0;xe+"_max",hy=(e,r,t,u)=>{let c=e.map(C=>C.length).map((C,$)=>Z(`input${$}`,r,C)),f=K.size(u),d=ne("output",r,u.length),g=[...t.symbolToInfo.keys()].filter(C=>!t.rhs.symbolToIndices.has(C)),w=C=>{let $=[],A="var prod = 1.0;",P="var sum = 0.0;",x="sum += prod;",E=[],O=[],B=[],R=[],j=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((L,F)=>{if(t.rhs.symbolToIndices.has(F)){let te=t.rhs.symbolToIndices.get(F)?.[0];te!==void 0&&t.lhs.forEach((J,oe)=>{if(L.inputIndices.includes(oe)){let le=J.symbolToIndices.get(F);if(le===void 0)throw new Error("Invalid symbol error");le.forEach(ge=>{$.push(`${c[oe].indicesSet(`input${oe}Indices`,ge,d.indicesGet("outputIndices",te))}`)})}})}else t.lhs.forEach((te,J)=>{if(L.inputIndices.includes(J)){let oe=te.symbolToIndices.get(F);if(oe===void 0)throw new Error("Invalid symbol error");oe.forEach(le=>{E.push(`${c[J].indicesSet(`input${J}Indices`,le,`${F}`)}`)}),R.push(`prod *= ${c[J].getByIndices(`input${J}Indices`)};`)}}),O.push(`for(var ${F}: u32 = 0; ${F} < uniforms.${Ud(F)}; ${F}++) {`),B.push("}")});let U=j?[...$,`let sum = ${c.map((L,F)=>L.getByIndices(`input${F}Indices`)).join(" * ")};`]:[...$,P,...O,...E,A,...R,x,...B];return`\n ${C.registerUniforms(g.map(L=>({name:`${Ud(L)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...c,d)}\n\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${d.offsetToIndices("global_idx")};\n ${c.map((L,F)=>`var input${F}Indices: ${c[F].type.indices};`).join(`\n`)}\n ${U.join(`\n`)};\n ${d.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let C=g.filter(A=>t.symbolToInfo.has(A)).map(A=>({type:12,data:t.symbolToInfo.get(A)?.dimValue||0}));C.push({type:12,data:f});let $=e.map((A,P)=>[...se(A)]).reduce((A,P)=>A.concat(P),C);return $.push(...se(u)),{outputs:[{dims:u,dataType:r}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:$}},getShaderSource:w}},Vd=(e,r)=>{let t=new fo(e.inputs,r.equation),u=t.outputDims,s=e.inputs.map((c,f)=>c.dims);e.compute(hy(s,e.inputs[0].dataType,t,u))},Wd=e=>{let r=e.equation.replace(/\\s+/g,"");return ke({equation:r})}});var gy,Gd,yy,by,Hd,Ld=ae(()=>{"use strict";Te();De();Re();gy=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),u=t.length{let t=e.length-r.length,u=[];for(let s=0;se.length>r.length?Gd(e,r):Gd(r,e),by=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),u=yy(r,t),s=e[0].dataType,c=s===9?4:1,f=Math.ceil(K.size(u)/c),d=w=>{let C=Z("input",s,r.length,c),$=ne("output",s,u.length,c),A;if(s===9){let P=(x,E,O="")=>`\n let outputIndices${E} = ${$.offsetToIndices(`outputOffset + ${E}u`)};\n let offset${E} = ${C.broadcastedIndicesToOffset(`outputIndices${E}`,$)};\n let index${E} = offset${E} / 4u;\n let component${E} = offset${E} % 4u;\n ${x}[${E}] = ${O}(${C.getByOffset(`index${E}`)}[component${E}]);\n `;A=`\n let outputOffset = global_idx * ${c};\n var data = vec4(0);\n ${P("data",0,"u32")}\n ${P("data",1,"u32")}\n ${P("data",2,"u32")}\n ${P("data",3,"u32")}\n ${$.setByOffset("global_idx","data")}\n }`}else A=`\n let outputIndices = ${$.offsetToIndices("global_idx")};\n let inputOffset = ${C.broadcastedIndicesToOffset("outputIndices",$)};\n ${$.setByOffset("global_idx",C.getByOffset("inputOffset"))}\n }`;return`\n ${w.registerUniform("vec_size","u32").declareVariables(C,$)}\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${A}`},g=[{type:12,data:f},...se(r,u)];return{name:"Expand",shaderCache:{hint:`${u.length}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:g})}},Hd=e=>{gy(e.inputs),e.compute(by(e.inputs),{inputs:[0]})}});var vy,Fd,qd=ae(()=>{"use strict";Te();De();Re();li();vy=e=>{let r=e[0].dataType,t=K.size(e[0].dims),u=K.size(e[1].dims),s=u%4===0,c=f=>{let d=Z("x",r,[1],4),g=Z("bias",r,[1],4),w=ne("y",r,[1],4),C=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],$=P=>`\n let bias${P}_offset: u32 = (global_idx * 4 + ${P}) % uniforms.bias_size;\n let bias${P} = ${g.getByOffset(`bias${P}_offset / 4`)}[bias${P}_offset % 4];`,A=s?`\n let bias = ${g.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${$(0)}${$(1)}${$(2)}${$(3)}\n let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${f.registerUniforms(C).declareVariables(d,g,w)}\n\n ${Xi(at(r))}\n\n ${f.mainStart(ur)}\n ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${d.getByOffset("global_idx")};\n ${A}\n let x_in = x + bias;\n ${w.setByOffset("global_idx",Ji("x_in"))}\n }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:c,getRunData:f=>({outputs:[{dims:f[0].dims,dataType:f[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:u}],dispatchGroup:{x:Math.ceil(t/ur/4)}})}},Fd=e=>{e.inputs.length<2||K.size(e.inputs[1].dims)===0?td(e):e.compute(vy(e.inputs))}});var wy,_y,Kd,Yd,Zd=ae(()=>{"use strict";Te();De();nt();Re();wy=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},_y=(e,r)=>{let t=e[0].dims,u=e[1].dims,s=t.length,c=K.normalizeAxis(r.axis,s),f=t.slice(0);f.splice(c,1,...u);let d=t[c],g=e[0].dataType===9?4:1,w=Math.ceil(K.size(f)/g),C=[{type:12,data:w},{type:6,data:d},{type:12,data:c},...se(e[0].dims,e[1].dims,f)],$=A=>{let P=Z("data",e[0].dataType,e[0].dims.length,g),x=Z("inputIndices",e[1].dataType,e[1].dims.length),E=ne("output",e[0].dataType,f.length,g),O=R=>{let j=u.length,U=`var indicesIndices${R} = ${x.type.indices}(0);`;for(let L=0;L1?`indicesIndices${R}[${L}]`:`indicesIndices${R}`} = ${f.length>1?`outputIndices${R}[uniforms.axis + ${L}]`:`outputIndices${R}`};`;U+=`\n var idx${R} = ${x.getByIndices(`indicesIndices${R}`)};\n if (idx${R} < 0) {\n idx${R} = idx${R} + uniforms.axisDimLimit;\n }\n var dataIndices${R} : ${P.type.indices};\n `;for(let L=0,F=0;L1?`dataIndices${R}[${L}]`:`dataIndices${R}`} = u32(idx${R});`,F+=j):(U+=`${s>1?`dataIndices${R}[${L}]`:`dataIndices${R}`} = ${f.length>1?`outputIndices${R}[${F}]`:`outputIndices${R}`};`,F++);return U},B;if(e[0].dataType===9){let R=(j,U,L="")=>`\n let outputIndices${U} = ${E.offsetToIndices(`outputOffset + ${U}u`)};\n ${O(U)};\n let offset${U} = ${P.indicesToOffset(`dataIndices${U}`)};\n let index${U} = offset${U} / 4u;\n let component${U} = offset${U} % 4u;\n ${j}[${U}] = ${L}(${P.getByOffset(`index${U}`)}[component${U}]);\n `;B=`\n let outputOffset = global_idx * ${g};\n var value = vec4(0);\n ${R("value",0,"u32")}\n ${R("value",1,"u32")}\n ${R("value",2,"u32")}\n ${R("value",3,"u32")}\n ${E.setByOffset("global_idx","value")}\n `}else B=`\n let outputIndices = ${E.offsetToIndices("global_idx")};\n ${O("")};\n let value = ${P.getByIndices("dataIndices")};\n ${E.setByOffset("global_idx","value")};\n `;return`\n ${A.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(P,x,E)}\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${B}\n }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:f,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:C}),getShaderSource:$}},Kd=e=>ke({axis:e.axis}),Yd=(e,r)=>{let t=e.inputs;wy(t),e.compute(_y(e.inputs,r))}});var $y,Cy,Qd,Xd,Jd=ae(()=>{"use strict";Te();De();nt();Re();$y=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.`)},Cy=(e,r)=>{let t=e[0].dims,u=e[0].dataType,s=t.length,c=e[1].dims,f=e[1].dataType,d=K.normalizeAxis(r.axis,s),g=t[d],w=c.slice(0),C=K.size(w),$=Z("input",u,s),A=Z("indicesInput",f,c.length),P=ne("output",u,w.length),x=[{type:12,data:C},{type:6,data:g},{type:12,data:d}];return x.push(...se(t,c,w)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:w,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:x}),getShaderSource:B=>`\n ${B.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables($,A,P)}\n ${B.mainStart()}\n ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${P.offsetToIndices("global_idx")};\n\n var idx = ${A.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${$.type.indices}(outputIndices);\n ${$.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${$.getByIndices("inputIndices")};\n\n ${P.setByOffset("global_idx","value")};\n }`}},Qd=e=>ke({axis:e.axis}),Xd=(e,r)=>{let t=e.inputs;$y(t),e.compute(Cy(e.inputs,r))}});var Sy,xy,ec,tc,rc=ae(()=>{"use strict";Te();De();Re();Sy=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")},xy=(e,r)=>{let t=e[0].dims.slice(),u=e[1].dims.slice(),[s,c,f]=Jn.getShapeOfGemmResult(t,r.transA,u,r.transB,e.length===3?e[2].dims:void 0),d=[s,c];if(!d)throw new Error("Can\'t use gemm on the given tensors");let g=K.size(d),w=[{type:12,data:g},{type:12,data:s},{type:12,data:c},{type:12,data:f},{type:1,data:r.alpha},{type:1,data:r.beta}],C=["type","type"];e.length===3&&(w.push(...se(e[2].dims)),C.push("rank")),w.push(...se(d));let $=A=>{let P="";r.transA&&r.transB?P="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?P="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?P="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(P="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let x=r.alpha===1?"":"value *= uniforms.alpha;",E=Z("a",e[0].dataType,e[0].dims),O=Z("b",e[1].dataType,e[1].dims),B=E.type.value,R=null,j=[E,O];e.length===3&&(R=Z("c",e[2].dataType,e[2].dims.length),j.push(R));let U=ne("output",e[0].dataType,d.length);j.push(U);let L=[{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 ${A.registerUniforms(L).declareVariables(...j)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${B}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${P}\n }\n\n ${x}\n ${(()=>R!=null?`let cOffset = ${R.broadcastedIndicesToOffset("vec2(m, n)",U)}; value += ${B}(uniforms.beta) * ${R.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:w}),getShaderSource:$}},ec=e=>{let r=e.transA,t=e.transB,u=e.alpha,s=e.beta;return{transA:r,transB:t,alpha:u,beta:s,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},tc=(e,r)=>{Sy(e.inputs),e.compute(xy(e.inputs,r))}});var Iy,Ay,Ty,nc,ic=ae(()=>{"use strict";Te();De();Re();Iy=(e,r)=>{let t=e[0].dims,u=t,s=2,c=K.sizeToDimension(t,s),f=K.sizeFromDimension(t,s),d=He(f),g=f/d,w=[t[0],t[1],g],C=["rank","type","type"],$=[{type:12,data:f},{type:12,data:g}];$.push(...se(w,w));let A=P=>{let x=Z("x",e[0].dataType,w.length,d),E=Z("scale",e[1].dataType,e[1].dims),O=Z("bias",e[2].dataType,e[2].dims),B=ne("output",e[0].dataType,w.length,d),R=[x,E,O,B],j=x.type.value,U=d===1?"f32":`vec${d}`,L=64,F=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${U}, ${L}>;\n const workgroupSize = ${L}u;\n ${P.registerUniforms(F).declareVariables(...R)}\n ${P.mainStart(L)}\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 = ${U}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${U}(${x.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 = ${It("workgroupShared[0]",d)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${U}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${U}(${x.get("batch","channel","h")}) - ${U}(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 = ${It("workgroupShared[0]",d)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${r.epsilon}));\n let channelScale = invStdDev * f32(${E.getByOffset("channel")});\n let channelShift = f32(${O.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${x.get("batch","channel","h")} * ${j}(${U}(channelScale)) + ${j}(${U}(channelShift));\n ${B.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${r.epsilon};${d}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:c},programUniforms:$}),getShaderSource:A}},Ay=(e,r,t,u,s,c,f,d)=>{let g=He(f),w=64,C=g===1?"vec2f":`mat2x${g}f`,$=g===1?"f32":`vec${g}f`,A=(F,te)=>`${C}(${F}, ${te})`,P=s*f/g,x=Math.ceil(c/w),E=["type"],O=[{type:12,data:x},{type:12,data:c},{type:12,data:Math.floor(f/g)},{type:12,data:Math.floor(c*f/g)}],B=F=>{let te=Z("input",r.dataType,r.dims,g);return`\n ${F.declareVariables(te)}\n @group(0) @binding(1) var output : array<${C}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${F.mainStart(w)}\n let currentImageNumber = global_idx / ${w} / uniforms.C;\n let currentChannelNumber = (global_idx / ${w}) % uniforms.C;\n let wgOffset = local_id.x * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${xt("f32",g)};\n var squaredSum = ${xt("f32",g)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${$}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${A("sum","squaredSum")};\n }`},R=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${g}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:[s,f,w,2],dataType:1}],dispatchGroup:{x:s*f/g},programUniforms:O}),getShaderSource:B},{inputs:[r],outputs:[-1]})[0],j=[{type:12,data:P},{type:12,data:c},{type:12,data:Math.floor(f/g)},{type:12,data:Math.floor(w*f/g)}],U=["type","type","type"],L=F=>{let te=Z("scale",t.dataType,t.dims,g),J=Z("bias",u.dataType,u.dims,g);return`\n @group(0) @binding(0) var input : array<${C}>;\n @group(0) @binding(1) var scale : array<${te.type.storage}>;\n @group(0) @binding(2) var bias : array<${J.type.storage}>;\n @group(0) @binding(3) var output : array<${C}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${F.mainStart()}\n ${F.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 = ${xt("f32",g)};\n var squaredSum = ${xt("f32",g)};\n for (var i: u32 = 0; i < min(${w}, uniforms.H); i++) {\n let value = input[offset + i + currentChannelNumber * ${w}];\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(${d}));\n let channelScale = invStdDev * ${$}(scale[currentChannelNumber]);\n let channelShift = ${$}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${A("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${g};${d}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:[s,f,2],dataType:1}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:j}),getShaderSource:L},{inputs:[R,t,u],outputs:[-1]})[0]},Ty=(e,r,t)=>{let u=r[0].dims,s=u,c=u[0],f=u[u.length-1],d=K.sizeFromDimension(u,1)/f,g=He(f),w=K.size(s)/g,C=[{type:12,data:d},{type:12,data:Math.floor(f/g)}],$=["type","type"],A=Ay(e,r[0],r[1],r[2],c,d,f,t.epsilon),P=x=>{let E=Ne(r[0].dataType),O=g===1?"vec2f":`mat2x${g}f`,B=g===1?E:`vec${g}<${E}>`,R=Z("input",r[0].dataType,r[0].dims,g),j=ne("output",r[0].dataType,s,g);return`\n @group(0) @binding(0) var input : array<${R.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${O}>;\n @group(0) @binding(2) var output : array<${j.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${x.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], ${B}(scale[0]), ${B}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${g}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:C}),getShaderSource:P},{inputs:[r[0],A]})},nc=(e,r)=>{r.format==="NHWC"?Ty(e,e.inputs,r):e.compute(Iy(e.inputs,r))}});var Ey,Py,oc,ac=ae(()=>{"use strict";Te();De();Re();Ey=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Py=(e,r,t)=>{let u=r.simplified,s=e[0].dims,c=e[1],f=!u&&e[2],d=s,g=K.normalizeAxis(r.axis,s.length),w=K.sizeToDimension(s,g),C=K.sizeFromDimension(s,g),$=K.size(c.dims),A=f?K.size(f.dims):0;if($!==C||f&&A!==C)throw new Error(`Size of X.shape()[axis:] == ${C}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${$} and bias size of ${A}`);let P=[];for(let L=0;L1,R=t>2,j=L=>{let F=Ne(e[0].dataType),te=[Z("x",e[0].dataType,e[0].dims,x),Z("scale",c.dataType,c.dims,x)];f&&te.push(Z("bias",f.dataType,f.dims,x)),te.push(ne("output",e[0].dataType,d,x)),B&&te.push(ne("mean_data_output",1,P)),R&&te.push(ne("inv_std_output",1,P));let J=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${L.registerUniforms(J).declareVariables(...te)}\n ${L.mainStart()}\n ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${xt("f32",x)};\n var mean_square_vector = ${xt("f32",x)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${lr(F,x,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${It("mean_vector",x)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${It("mean_square_vector",x)} / uniforms.norm_size ${u?"":"- mean * mean"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${lr(F,x,"x[j + offset]")};\n let f32scale = ${lr(F,x,"scale[j]")};\n output[j + offset] = ${te[0].type.value}((f32input ${u?"":"- mean"}) * inv_std_dev * f32scale\n ${f?`+ ${lr(F,x,"bias[j]")}`:""}\n );\n }\n\n ${B?"mean_data_output[global_idx] = mean":""};\n ${R?"inv_std_output[global_idx] = inv_std_dev":""};\n }`},U=[{dims:d,dataType:e[0].dataType}];return B&&U.push({dims:P,dataType:1}),R&&U.push({dims:P,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${x};${t};${u}`,inputDependencies:E},getRunData:()=>({outputs:U,dispatchGroup:{x:Math.ceil(w/64)},programUniforms:O}),getShaderSource:j}},oc=(e,r)=>{Ey(e.inputs),e.compute(Py(e.inputs,r,e.outputCount))}});var ky,Oy,sc,uc,lc=ae(()=>{"use strict";Te();De();nt();Re();ky=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],u=t.dims.length;if(t.dims[u-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((r.k+r.blockSize-1)/r.blockSize),c=r.blockSize/8*r.bits,f=e[1];if(!K.areEqual(f.dims,[r.n,s,c]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let g=e[2].dims;if(K.size(g)!==r.n*s)throw new Error("scales input size error.");if(e.length===4){let C=e[3].dims,$=r.bits>4?r.n*s:r.n*Math.floor((s+1)/2);if(K.size(C)!==$)throw new Error("zeroPoints input size error.")}},Oy=(e,r,t,u)=>{let s=e[0].dims,c=s.length,f=Math.floor((r.k+r.blockSize-1)/r.blockSize),d=s[c-2],g=r.k,w=r.n,C=s.slice(0,c-2),$=K.size(C),P=r.blockSize/8*r.bits/4,x=e[0].dataType,E=He(d),O=He(r.k),B=He(P),R=or(x),j=d*f*R,U=Math.floor(u/j),L=f<=t[0]&&U>0,F=!L||U>=4?He(w):U>=2&&He(w)>=2?2:1,te=C.concat([d,w]),J=K.size(te)/F/E,oe=L?[]:[{type:12,data:J},{type:12,data:r.blockSize}],le=[$,d,g/O],ge=K.convertShape(e[1].dims).slice();ge.splice(-1,1,P/B),oe.push(...se(le)),oe.push(...se(ge)),oe.push(...se(e[2].dims)),e.length===4&&oe.push(...se(K.convertShape(e[3].dims)));let X=[$,d,w/F];oe.push(...se(X));let pe=we=>{let ue=le.length,me=Z("a",e[0].dataType,ue,O),Ee=Z("b",12,ge.length,B),Pe=Z("scales",e[2].dataType,e[2].dims.length),Ce=[me,Ee,Pe],be=e.length===4?Z("zero_points",12,e[3].dims.length):void 0;be&&Ce.push(be);let Ae=X.length,_e=ne("output",e[0].dataType,Ae,F),Je=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],ee=Ne(e[0].dataType),ce=(()=>{switch(O){case 1:return`array<${ee}, 8>`;case 2:return`mat4x2<${ee}>`;case 4:return`mat2x4<${ee}>`;default:throw new Error(`${O}-component is not supported.`)}})(),Be=`\n for (var word: u32 = 0; word < ${P}; word += ${B}) {\n ${Ee.indicesSet("b_indices","2","word")};\n let b_data = ${Ee.getByIndices("b_indices")};\n for (var i: u32 = 0; i < ${B}; i++) {\n let b_value: u32 = ${B===1?"b_data":"b_data[word + i]"};\n let b_mask: u32 = 0x0F0F0F0Fu;\n let b_value_lower: vec4 = unpack4xU8(b_value & b_mask);\n let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask);\n let b_quantized_values = ${ce}(${Array.from({length:4},(Ye,Ke)=>`${ee}(b_value_lower[${Ke}]), ${ee}(b_value_upper[${Ke}])`).join(", ")});\n let b_dequantized_values = ${(()=>O===1?`${ce}(${Array.from({length:8},(Ye,Ke)=>`(b_quantized_values[${Ke}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ce}(${Array(8).fill("zero_point").join(",")})) * scale;`)()};\n // Number of B elements per 32-bit word is 32/bits = 32/4 = 8\n for (var m: u32 = 0; m < ${L?d:E}u; m++) {\n ${me.indicesSet("a_indices",ue-2,L?"m":`row * ${E} + m`)};\n ${me.indicesSet("a_indices",ue-1,"word_offset")};\n var input_offset = ${me.indicesToOffset("a_indices")};\n var a_data: ${ce};\n for (var j: u32 = 0; j < ${8/O}; j++) {\n a_data[j] = ${me.getByOffset("input_offset")};\n input_offset++;\n }\n ${L?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${F>1?"[c]":""} += ${Array.from({length:8/O},(Ye,Ke)=>`${O===1?`a_data[${Ke}] * b_dequantized_values[${Ke}]`:`dot(a_data[${Ke}], b_dequantized_values[${Ke}])`}`).join(" + ")};\n }\n word_offset += ${8/O};\n }\n }`,tt=be?`\n zero_point_offset += 4;\n if (zero_point_offset == 32) {\n zero_point_offset = 0;\n zero_point_index++;\n zero_point_word = ${be.getByOffset("zero_point_index")};\n }`:"";return L?`\n var workgroup_shared: array<${_e.type.value}, ${d*f}>;\n ${we.declareVariables(...Ce,_e)}\n ${we.mainStart([f,1,1])}\n var a_indices: ${me.type.indices};\n var block = local_id.x;\n var col = workgroup_id.y;\n var batch = workgroup_id.z;\n ${me.indicesSet("a_indices","0","batch")};\n // Two zero points are packed into one byte when uniforms.bits is 4.\n for (var c: u32 = 0; c < ${F}; c++) {\n let col_times_components_plus_c = col * ${F} + c;\n ${be?`\n var zero_point_bytes_per_col: u32 = (${f} + 1) / 2;\n var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u);\n var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u;\n var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u;\n var zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n var zero_point_word: u32 = ${be.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""}\n var b_indices: ${Ee.type.indices};\n ${Ee.indicesSet("b_indices","0","col_times_components_plus_c")};\n // The scale and zero points are computed per block.\n var scales_index = col_times_components_plus_c * ${f} + block;\n let scale = ${Pe.getByOffset("scales_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${ee}(${be?"(zero_point_word) & 0xFu":8});\n ${Ee.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block * ${r.blockSize/O};\n var workgroup_shared_offset: u32 = block * ${d};\n ${Be}\n }\n workgroupBarrier();\n if (local_id.x == 0u) {\n var output_indices: ${_e.type.indices};\n ${_e.indicesSet("output_indices","0","batch")};\n ${_e.indicesSet("output_indices",Ae-1,"col")};\n ${_e.indicesSet("output_indices",Ae-2,"0")};\n var output_offset = ${_e.indicesToOffset("output_indices")};\n for (var m: u32 = 0u; m < ${d}u; m++) {\n var output_value: ${_e.type.value} = ${_e.type.value}(0);\n var workgroup_shared_offset: u32 = m;\n for (var b: u32 = 0u; b < ${f}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${d};\n }\n ${_e.setByOffset("output_offset","output_value")};\n output_offset += ${w/F};\n }\n }\n }`:`\n ${we.registerUniforms(Je).declareVariables(...Ce,_e)}\n ${we.mainStart()}\n ${we.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var output_values: array<${_e.type.value}, ${E}>;\n var output_indices = ${_e.offsetToIndices("global_idx")};\n var col = ${_e.indicesGet("output_indices",Ae-1)};\n var row = ${_e.indicesGet("output_indices",Ae-2)};\n var a_indices: ${me.type.indices} = output_indices;\n // Two zero points are packed into one byte because uniforms.bits <= 4.\n // zero_point_offset is either 0 or 4. It is bit offset within one byte.\n // TODO support zero_point_offset for bits > 4\n ${be?`\n var zero_point_abs_offset = col * ${F} * ((${f} + 1) / 2);\n var zero_point_index: u32 = zero_point_abs_offset / 4;\n var zero_point_word: u32 = ${be.getByOffset("zero_point_index")};\n var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""}\n var scale_index = col * ${f*F};\n var b_indices: ${Ee.type.indices};\n for (var c: u32 = 0; c < ${F}; c++) {\n ${Ee.indicesSet("b_indices","0",`col * ${F} + c`)};\n var block_offset: u32 = 0;\n for (var block: u32 = 0; block < ${f}; block++) {\n // The scale and zero points are computed per block.\n let scale = ${Pe.getByOffset("scale_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${ee}(${be?"extractBits(zero_point_word, zero_point_offset, 4)":8});\n ${Ee.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block_offset;\n ${Be}\n scale_index++;\n ${tt}\n block_offset += uniforms.block_size / ${O};\n }\n // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte.\n ${be?`if (zero_point_offset % 8 > 0) {\n ${tt}\n }`:""}\n }\n for (var k: u32 = 0u; k < ${E}u; k++) {\n ${_e.indicesSet("output_indices",Ae-2,`${E} * row + k`)};\n ${_e.setByIndices("output_indices","output_values[k]")}\n }\n }`};return{name:L?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${r.cacheKey};${d};${x};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:te,dataType:x}],name:L?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:L?{x:1,y:Math.ceil(w/F),z:$}:{x:Math.ceil(J/64)},programUniforms:oe}),getShaderSource:pe}},sc=(e,r)=>{ky(e.inputs,r);let t=e.getMaxComputeWorkgroupSizes(),u=e.getMaxComputeWorkgroupStoragesize();e.compute(Oy(e.inputs,r,t,u))},uc=e=>ke(e)});var ft,Ry,cc,dc,By,po,fc,pc=ae(()=>{"use strict";Te();De();nt();Xn();Qi();Re();Dr();ft=(e,r)=>e.length>r&&e[r].dims.length>0&&K.size(e[r].dims)>0?e[r]:void 0,Ry=(e,r)=>{let t=e[0],u=ft(e,1),s=ft(e,2),c=ft(e,3),f=ft(e,4),d=ft(e,5),g=ft(e,6),w=ft(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let C=!1,$=t.dims[0],A=t.dims[1],P=t.dims.length===3?C?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],x=A,E=0,O=0,B=Math.floor(P/r.numHeads);if(g&&w){if(g.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(g.dims[0]!==$||g.dims[1]!==r.numHeads||g.dims[3]!==B)throw new Error(\'Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(w.dims[0]!==$||w.dims[1]!==r.numHeads||w.dims[3]!==B)throw new Error(\'Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(g.dims[2]!==w.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)\');if(w.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');E=g.dims[2],O=g.dims[2]}else if(g||w)throw new Error(\'Input "past_key" and "past_value" shall be both present or both absent\');let R;if(u){if(t.dims.length!==3)throw new Error(\'Input "query" is expected to have 3 dimensions when key is given\');if(u.dims.length<3||u.dims.length>5)throw new Error(\'Input "key" is expected to have 3, 4, or 5 dimensions\');if(t.dims[0]!==u.dims[0])throw new Error(\'Input "query" and "key" shall have same dim 0 (batch size)\');if(u.dims.length===3){if(u.dims[2]!==t.dims[2])throw new Error(\'Input "query" and "key" shall have same dim 2 (hidden_size)\');R=2,x=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==r.numHeads||u.dims[3]!==2||u.dims[4]!==B)throw new Error(\'Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv\');if(s)throw new Error(\'Expect "value" be none when "key" has packed kv format.\');R=5,x=u.dims[1]}else{if(u.dims[1]!==r.numHeads||u.dims[3]!==B)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');R=0,x=u.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error(\'Input "query" is expected to have 3 or 5 dimensions when key is empty\');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error(\'Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv\');R=3}if(c){if(c.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(s&&t.dims.length===5&&t.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let j=0;if(f){j=8;let J=f.dims;throw J.length===1?J[0]===$?j=1:J[0]===3*$+2&&(j=3):J.length===2&&J[0]===$&&J[1]===x&&(j=5),j===8?new Error(\'Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)\'):new Error("Mask not supported")}let U=!1,L=P;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error(\'Input "value" is expected to have 3 or 4 dimensions\');if(t.dims[0]!==s.dims[0])throw new Error(\'Input "query" and "value" shall have same dim 0 (batch_size)\');if(s.dims.length===3){if(x!==s.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');L=s.dims[2]}else{if(x!==s.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');L=s.dims[1]*s.dims[3],U=!0}}let F=E+x,te=!1;if(f)throw new Error("Key padding mask is not supported");if(d){if(d.dims.length!==4)throw new Error(\'Input "relative_position_bias" is expected to have 4 dimensions\');if(d.dims[0]!==$&&d.dims[0]!==1||d.dims[1]!==r.numHeads||d.dims[2]!==A||d.dims[3]!==F)throw new Error(\'Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)\')}return{batchSize:$,sequenceLength:A,pastSequenceLength:E,kvSequenceLength:x,totalSequenceLength:F,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:P,vHiddenSize:L,headSize:B,vHeadSize:Math.floor(L/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:j,scale:r.scale,broadcastResPosBias:te,passPastInKv:U,qkvFormat:R}},cc=e=>ke({...e}),dc=ke({perm:[0,2,1,3]}),By=(e,r,t,u,s,c,f)=>{let d=[u,s,c],g=K.size(d),w=[{type:12,data:g},{type:12,data:f},{type:12,data:c}],C=$=>{let A=ne("qkv_with_bias",r.dataType,d),P=Z("qkv",r.dataType,d),x=Z("bias",t.dataType,d),E=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${$.registerUniforms(E).declareVariables(P,x,A)}\n ${$.mainStart()}\n ${$.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:d,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:w}),getShaderSource:C},{inputs:[r,t],outputs:[-1]})[0]},po=(e,r,t,u,s,c,f,d)=>{let g=c;if(f){if(u===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return g=By(e,c,f,r,u,t*s,d),g=g.reshape([r,u,t,s]),e.compute($t(g,dc.perm),{inputs:[g],outputs:[-1]})[0]}else return c.dims.length===3&&(g=c.reshape([r,u,t,s])),e.compute($t(g,dc.perm),{inputs:[g],outputs:[-1]})[0]},fc=(e,r)=>{let t=Ry(e.inputs,r),u=e.inputs[0],s=ft(e.inputs,1),c=ft(e.inputs,2),f=ft(e.inputs,3),d=ft(e.inputs,4),g=ft(e.inputs,5),w=ft(e.inputs,6),C=ft(e.inputs,7);if(u.dims.length===5)throw new Error("Packed QKV is not implemented");if(s?.dims.length===5)throw new Error("Packed KV is not implemented");let $=s&&c&&s.dims.length===4&&c.dims.length===4,A=po(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,u,f,0);if($)return ai(e,A,s,c,d,void 0,w,C,g,t,r);if(!s||!c)throw new Error("key and value must be provided");let P=po(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,s,f,t.hiddenSize),x=po(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,c,f,2*t.hiddenSize);ai(e,A,P,x,d,void 0,w,C,g,t,r)}});var Dy,zy,My,jy,Uy,Vy,Wy,Ny,mc,hc=ae(()=>{"use strict";Te();De();Re();Dy=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},zy=(e,r,t)=>{let u="";for(let s=r-1;s>=0;--s)u+=`\n k = i32(${e.indicesGet("indices",s)}) - ${xe("uniforms.pads",s,t)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${xe("uniforms.x_shape",s,r)})) {\n break;\n }\n offset += k * i32(${xe("uniforms.x_strides",s,r)});\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 ${u}\n value = x[offset];\n }\n `},My=(e,r,t)=>{let u="";for(let s=r-1;s>=0;--s)u+=`\n k = i32(${e.indicesGet("indices",s)}) - ${xe("uniforms.pads",s,t)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${xe("uniforms.x_shape",s,r)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${xe("uniforms.x_shape",s,r)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${xe("uniforms.x_strides",s,r)});\n `;return`\n var offset = 0;\n var k = 0;\n ${u}\n value = x[offset];\n `},jy=(e,r,t)=>{let u="";for(let s=r-1;s>=0;--s)u+=`\n k = i32(${e.indicesGet("indices",s)}) - ${xe("uniforms.pads",s,t)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${xe("uniforms.x_shape",s,r)})) {\n k = i32(${xe("uniforms.x_shape",s,r)}) - 1;\n }\n offset += k * i32(${xe("uniforms.x_strides",s,r)});\n `;return`\n var offset = 0;\n var k = 0;\n ${u}\n value = x[offset];\n `},Uy=(e,r,t)=>{let u="";for(let s=r-1;s>=0;--s)u+=`\n k = i32(${e.indicesGet("indices",s)}) - ${xe("uniforms.pads",s,t)};\n if (k < 0) {\n k += i32(${xe("uniforms.x_shape",s,r)}]);\n }\n if (k >= i32(${xe("uniforms.x_shape",s,r)})) {\n k -= i32(${xe("uniforms.x_shape",s,r)});\n }\n offset += k * i32(${xe("uniforms.x_strides",s,r)});\n `;return`\n var offset = 0;\n var k = 0;\n ${u}\n value = x[offset];\n `},Vy=(e,r,t)=>{switch(t.mode){case 0:return zy(e,r,t.pads.length);case 1:return My(e,r,t.pads.length);case 2:return jy(e,r,t.pads.length);case 3:return Uy(e,r,t.pads.length);default:throw new Error("Invalid mode")}},Wy=(e,r)=>{let t=K.padShape(e[0].dims.slice(),r.pads),u=e[0].dims,s=K.size(t),c=[{type:12,data:s},{type:6,data:r.pads}];r.mode===0&&c.push({type:e[0].dataType,data:r.value}),c.push(...se(e[0].dims,t));let f=["rank"],d=g=>{let w=ne("output",e[0].dataType,t.length),C=Z("x",e[0].dataType,u.length),$=C.type.value,A=Vy(w,u.length,r),P=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&P.push({name:"constant_value",type:$}),`\n ${g.registerUniforms(P).declareVariables(C,w)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${w.offsetToIndices("global_idx")};\n\n var value = ${$}(0);\n ${A}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${r.mode}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(K.size(t)/64)},programUniforms:c}),getShaderSource:d}},Ny=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),u=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,s=e[0].dims.length,c=new Int32Array(2*s).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let g=0;gc[Number(g)]=Number(d));let f=[];return c.forEach(d=>f.push(d)),{mode:r.mode,value:u,pads:f}}else return r},mc=(e,r)=>{Dy(e.inputs);let t=Ny(e.inputs,r);e.compute(Wy(e.inputs,t),{inputs:[0]})}});var yi,gc,yc,bc,vc,Gy,Hy,wc,_c,$c,Cc,Sc,xc,Ic,Ac,Tc,Ec,Pc,kc,Oc=ae(()=>{"use strict";Rr();Te();De();Re();yi=e=>{if(Or.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},gc=(e,r,t)=>{let u=r.format==="NHWC",s=e.dims.slice();u&&s.splice(1,0,s.pop());let c=Object.hasOwnProperty.call(r,"dilations"),f=r.kernelShape.slice(),d=r.strides.slice(),g=c?r.dilations.slice():[],w=r.pads.slice();sr.adjustPoolAttributes(t,s,f,d,g,w);let C=sr.computePoolOutputShape(t,s,d,g,f,w,r.autoPad),$=Object.assign({},r);c?Object.assign($,{kernelShape:f,strides:d,pads:w,dilations:g,cacheKey:r.cacheKey}):Object.assign($,{kernelShape:f,strides:d,pads:w,cacheKey:r.cacheKey});let A=C.slice();return A.push(A.splice(1,1)[0]),[$,u?A:C]},yc=(e,r)=>{let t=r.format==="NHWC",u=K.size(e),s=K.size(r.kernelShape),c=[{type:12,data:u},{type:12,data:s}],f=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let d=r.kernelShape[r.kernelShape.length-1],g=r.strides[r.strides.length-1],w=r.pads[r.pads.length/2-1],C=r.pads[r.pads.length-1],$=!!(w+C);c.push({type:12,data:d},{type:12,data:g},{type:12,data:w},{type:12,data:C}),f.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let A=!1;if(r.kernelShape.length===2){let P=r.kernelShape[r.kernelShape.length-2],x=r.strides[r.strides.length-2],E=r.pads[r.pads.length/2-2],O=r.pads[r.pads.length-2];A=!!(E+O),c.push({type:12,data:P},{type:12,data:x},{type:12,data:E},{type:12,data:O}),f.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[c,f,!0,$,A]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=K.computeStrides(r.kernelShape);c.push({type:12,data:d},{type:12,data:r.pads},{type:12,data:r.strides}),f.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let g=r.pads.reduce((w,C)=>w+C);return[c,f,!!g,!1,!1]}},bc=(e,r,t,u,s,c,f,d,g,w,C,$)=>{let A=s.format==="NHWC",P=r.type.value,x=ne("output",r.type.tensor,u);if(s.kernelShape.length<=2){let E="",O="",B="",R=t-(A?2:1);if(C?E=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${R}] = indices[${R}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${R}] < 0 || xIndices[${R}]\n >= uniforms.x_shape[${R}]) {\n pad++;\n continue;\n }\n let x_val = x[${r.indicesToOffset("xIndices")}];\n ${c}\n }`:E=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${R}] = indices[${R}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${r.indicesToOffset("xIndices")}];\n ${c}\n }`,s.kernelShape.length===2){let U=t-(A?3:2);$?O=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${U}] = indices[${U}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${U}] < 0 || xIndices[${U}] >= uniforms.x_shape[${U}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:O=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${U}] = indices[${U}] * uniforms.sh - uniforms.phStart + j;\n `,B=`\n }\n `}return`\n ${e.registerUniforms(g).declareVariables(r,x)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${x.offsetToIndices("global_idx")};\n var xIndices = ${x.offsetToIndices("global_idx")};\n\n var value = ${P}(${d});\n var pad = 0;\n ${O}\n ${E}\n ${B}\n ${f}\n\n output[global_idx] = value;\n }`}else{if(A)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=s.kernelShape.length,O=s.pads.length,B="";return w?B=`\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[${r.indicesToOffset("xIndices")}];\n ${c}\n }`:B=`\n }\n let x_val = x[${r.indicesToOffset("xIndices")}];\n ${c}\n `,`\n ${e.registerUniforms(g).declareVariables(r,x)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${x.offsetToIndices("global_idx")};\n var xIndices = ${x.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${P}(${d});\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 < ${E-1}u; j++) {\n offsets[j] = offset / ${xe("uniforms.kernelStrides","j",E)};\n offset -= offsets[j] * ${xe("uniforms.kernelStrides","j",E)};\n }\n offsets[${E-1}] = offset;\n\n isPad = false;\n for (var j = ${t-E}u; j < ${t}u; j++) {\n xIndices[j] = indices[j] * ${xe("uniforms.strides",`j - ${t-E}u`,E)}\n + offsets[j - ${t-E}u] - ${xe("uniforms.pads","j - 2u",O)};\n ${B}\n }\n ${f}\n\n output[global_idx] = value;\n }`}},vc=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Gy=e=>`${vc(e)};${e.countIncludePad}`,Hy=e=>`${vc(e)};${e.storageOrder};${e.dilations}`,wc=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}),_c=(e,r,t,u)=>{let[s,c]=gc(r,u,t),f=Z("x",r.dataType,r.dims.length),d=f.type.value,g="value += x_val;",w="";s.countIncludePad?w+=`value /= ${d}(uniforms.kernelSize);`:w+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[C,$,A,P,x]=yc(c,s);C.push(...se(r.dims,c));let E=["rank"];return{name:e,shaderCache:{hint:`${u.cacheKey};${A};${P};${x}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:c,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(K.size(c)/64)},programUniforms:C}),getShaderSource:O=>bc(O,f,r.dims.length,c.length,s,g,w,0,$,A,P,x)}},$c=e=>{let r=e.count_include_pad!==0,t=wc(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let u={countIncludePad:r,...t,cacheKey:""};return{...u,cacheKey:Gy(u)}},Cc=(e,r)=>{yi(e.inputs),e.compute(_c("AveragePool",e.inputs[0],!1,r))},Sc={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},xc=e=>{let r=e.format;return{format:r,...Sc,cacheKey:r}},Ic=(e,r)=>{yi(e.inputs),e.compute(_c("GlobalAveragePool",e.inputs[0],!0,r))},Ac=(e,r,t,u)=>{let[s,c]=gc(r,u,t),f=`\n value = max(x_val, value);\n `,d="",g=Z("x",r.dataType,r.dims.length),w=["rank"],[C,$,A,P,x]=yc(c,s);return C.push(...se(r.dims,c)),{name:e,shaderCache:{hint:`${u.cacheKey};${A};${P};${x}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:c,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(K.size(c)/64)},programUniforms:C}),getShaderSource:E=>bc(E,g,r.dims.length,c.length,s,f,d,r.dataType===10?-65504:-1e5,$,A,P,x)}},Tc=(e,r)=>{yi(e.inputs),e.compute(Ac("MaxPool",e.inputs[0],!1,r))},Ec=e=>{let r=e.storage_order,t=e.dilations,u=wc(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(u.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let s={storageOrder:r,dilations:t,...u,cacheKey:""};return{...s,cacheKey:Hy(s)}},Pc=e=>{let r=e.format;return{format:r,...Sc,cacheKey:r}},kc=(e,r)=>{yi(e.inputs),e.compute(Ac("GlobalMaxPool",e.inputs[0],!0,r))}});var Fy,qy,Rc,Bc=ae(()=>{"use strict";Rr();Te();Re();Fy=(e,r,t)=>{let u=e===r,s=er&&t>0;if(u||s||c)throw new Error("Range these inputs\' contents are invalid.")},qy=(e,r,t,u)=>{let s=Math.abs(Math.ceil((r-e)/t)),c=[s],f=s,d=[{type:12,data:f},{type:u,data:e},{type:u,data:t},...se(c)],g=w=>{let C=ne("output",u,c.length),$=C.type.value,A=[{name:"outputSize",type:"u32"},{name:"start",type:$},{name:"delta",type:$}];return`\n ${w.registerUniforms(A).declareVariables(C)}\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${$}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${u}`},getShaderSource:g,getRunData:()=>({outputs:[{dims:c,dataType:u}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:d})}},Rc=e=>{let r=0,t=0,u=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],u=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],u=e.inputs[2].getFloat32Array()[0]),Or.webgpu.validateInputContent&&Fy(r,t,u),e.compute(qy(r,t,u,e.inputs[0].dataType),{inputs:[]})}});var Ky,Yy,Zy,Qy,Xy,Jy,e0,t0,r0,n0,i0,Dc,o0,a0,s0,u0,l0,zc,Mc,jc=ae(()=>{"use strict";Te();De();nt();Re();Ky=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.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(r.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")}},Yy=(e,r,t)=>{r.every(s=>s>=0&&s{throw new Error("Resize requires axes input values to be positive and less than rank")}));let u=new Array(t).fill(1);return r.forEach((s,c)=>u[s]=e[c]),u},Zy=(e,r,t,u,s,c)=>{let[f,d,g]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],w=e[0].dims.length;if(f>0&&e.length>f&&e[f].dims.length>0)e[f].getFloat32Array().forEach(C=>c.push(C));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&e.length>d&&e[d].dims.length>0){if(e[d].getFloat32Array().forEach(C=>u.push(C)),u.length!==0&&u.length!==w&&t>=18&&u.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Ky(u,r),r.axes.length>0&&Yy(u,r.axes,w).forEach((C,$)=>u[$]=C)}if(g>0&&e.length>g&&(e[g].getBigInt64Array().forEach(C=>s.push(Number(C))),s.length!==w||t>=18&&s.length===r.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(r.axes.length>0){if(u.length!==r.axes.length)throw new Error(\'Resize requires "scales" input size to be of axes rank when axes attributes is specified\');if(s.length!==r.axes.length)throw new Error(\'Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified\')}if(typeof u<"u"&&typeof s<"u"&&u.length>0&&s.length>w)throw new Error("Resize requires only of scales or sizes to be specified")},Qy=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return`return ${r}(xResized) / ${r}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(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 = ${r}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${r}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${r}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${r}(roiStart) * ${r}(lengthOriginal - 1) +\n (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) /\n ${r}(lengthResized - 1);\n } else {\n return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized);\n const adjustment = ${r}(lengthResized) / outputWidth;\n const center = ${r}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Xy=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{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(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Jy=(e,r,t)=>{let u=new Array(t).fill(0).concat(new Array(t).fill(1)),s=e.length===0?u:e.slice();return r.length>0?(r.forEach((c,f)=>{u[c]=s[f],u[f+t]=s[r.length+f]}),u):s},e0=(e,r,t,u)=>{let s=[];if(t.length>0)if(u.length>0){if(e.forEach(c=>s.push(c)),Math.max(...u)>e.length)throw new Error("axes is out of bound");u.forEach((c,f)=>s[c]=t[f])}else t.forEach(c=>s.push(c));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");s=e.map((c,f)=>Math.round(c*r[f]))}return s},t0=(e,r,t)=>{let u=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(c=>r[c]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(c=>r[c]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let s=e.slice();return t.axes.length>0?(t.axes.forEach(c=>r[c]=u),t.axes.forEach(c=>s[c]=Math.round(e[c]*r[c]))):(r.fill(u,0,r.length),s.forEach((c,f)=>s[f]=Math.round(c*r[f]))),s},r0=(e,r,t,u,s)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> {\n var original_indices: array<${e.type.value}, ${t.length}>;\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${xe("uniforms.scales","i",u)};\n var roi_low = ${xe("uniforms.roi","i",s)};\n var roi_hi = ${xe("uniforms.roi",`i + ${r.length}`,s)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${xe("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${xe("uniforms.output_shape","i",t.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 }`,n0=(e,r,t,u,s,c,f)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${u.length}; i++) {\n var output_index = ${r.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${xe("uniforms.scales","i",s)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${xe("uniforms.roi","i",c)};\n var roi_hi = ${xe("uniforms.roi",`i + ${t.length}`,c)};\n var input_shape_i = ${xe("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${xe("uniforms.output_shape","i",u.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${f} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${r.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 }`,i0=(e,r)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${xe("uniforms.input_shape","i",r.length)}) {\n return false;\n }\n }\n return true;\n }`,Dc=(e,r,t,u)=>e.rank>u?`\n ${e.indicesSet("input_indices",r,"channel")};\n ${e.indicesSet("input_indices",t,"batch")};\n`:"",o0=(e,r,t,u,s)=>{let[f,d,g,w]=t.length===2?[-1,0,1,-1]:[0,2,3,1],C=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${C} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",d,`max(0, min(row, ${t[d]} - 1))`)};\n ${e.indicesSet("input_indices",g,`max(0, min(col, ${t[g]} - 1))`)};\n ${Dc(e,w,f,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${C} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${C} = originalIndices[${d}];\n var col:${C} = originalIndices[${g}];\n ${u?`if (row < 0 || row > (${t[d]} - 1) || col < 0 || col > (${t[g]} - 1)) {\n return ${s};\n }`:""};\n row = max(0, min(row, ${t[d]} - 1));\n col = max(0, min(col, ${t[g]} - 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 = ${t.length>2?`u32(originalIndices[${w}])`:"0"};\n var batch: u32 = ${t.length>2?`u32(originalIndices[${f}])`:"0"};\n var x11: ${C} = getInputValue(batch, channel, row1, col1);\n var x12: ${C} = getInputValue(batch, channel, row1, col2);\n var x21: ${C} = getInputValue(batch, channel, row2, col1);\n var x22: ${C} = getInputValue(batch, channel, row2, col2);\n var dx1: ${C} = abs(row - ${C}(row1));\n var dx2: ${C} = abs(${C}(row2) - row);\n var dy1: ${C} = abs(col - ${C}(col1));\n var dy2: ${C} = abs(${C}(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 }`},a0=(e,r,t,u,s,c,f,d,g,w)=>{let C=t.length===2,$=!0,[A,P]=C?[0,1]:$?[2,3]:[1,2],x=e.type.value,E=O=>{let B=O===A?"row":"col";return`\n fn ${B}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${x} {\n var output_index = ${r.indicesGet("output_indices",O)};\n var originalIdx: ${x} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[O]},\n ${u[O]}, ${t[O]}, ${c[O]}, ${c[O]} + ${t.length});\n var fractOriginalIdx: ${x} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${d} && (originalIdx < 0 || originalIdx > (${t[O]} - 1))) {\n return ${g};\n }\n var data: array<${x}, 4> = array<${x}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${B}: ${x} = originalIdx + ${x}(i);\n if (${B} < 0 || ${B} >= ${t[O]}) {\n ${(()=>w?`coefs[i + 1] = 0.0;\n continue;`:d?`return ${g};`:`${B} = max(0, min(${B}, ${t[O]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",O,`u32(${B})`)};\n data[i + 1] = ${O===A?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${E(A)};\n ${E(P)};\n fn getCubicInterpolationCoefs(s: ${x}) -> array<${x}, 4> {\n var absS = abs(s);\n var coeffs: array<${x}, 4> = array<${x}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${x} = 1.0 - absS;\n var twoMinusAbsS: ${x} = 2.0 - absS;\n var onePlusAbsS: ${x} = 1.0 + absS;\n coeffs[0] = ((${f} * onePlusAbsS - 5 * ${f}) * onePlusAbsS + 8 * ${f}) * onePlusAbsS - 4 * ${f};\n coeffs[1] = ((${f} + 2) * absS - (${f} + 3)) * absS * absS + 1;\n coeffs[2] = ((${f} + 2) * oneMinusAbsS - (${f} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${f} * twoMinusAbsS - 5 * ${f}) * twoMinusAbsS + 8 * ${f}) * twoMinusAbsS - 4 * ${f};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${x}, 4>, coefs: array<${x}, 4>) -> ${x} {\n var coefsSum: ${x} = 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: ${r.type.indices}) -> ${x} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},s0=(e,r,t,u,s)=>{let[f,d,g,w,C]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],$=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${$} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",d,`max(0, min(depth, ${t[d]} - 1))`)};\n ${e.indicesSet("input_indices",g,`max(0, min(height, ${t[g]} - 1))`)};\n ${e.indicesSet("input_indices",w,`max(0, min(width, ${t[w]} - 1))`)};\n ${Dc(e,C,f,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${$} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${$} = originalIndices[${d}];\n var height:${$} = originalIndices[${g}];\n var width:${$} = originalIndices[${w}];\n ${u?`if (depth < 0 || depth > (${t[d]} - 1) || height < 0 || height > (${t[g]} - 1) || width < 0 || (width > ${t[w]} - 1)) {\n return ${s};\n }`:""};\n\n depth = max(0, min(depth, ${t[d]} - 1));\n height = max(0, min(height, ${t[g]} - 1));\n width = max(0, min(width, ${t[w]} - 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 = ${t.length>3?`u32(originalIndices[${C}])`:"0"};\n var batch: u32 = ${t.length>3?`u32(originalIndices[${f}])`:"0"};\n\n var x111: ${$} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${$} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${$} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${$} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${$} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${$} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${$} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${$} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${$} = abs(depth - ${$}(depth1));\n var dx2: ${$} = abs(${$}(depth2) - depth);\n var dy1: ${$} = abs(height - ${$}(height1));\n var dy2: ${$} = abs(${$}(height2) - height);\n var dz1: ${$} = abs(width - ${$}(width1));\n var dz2: ${$} = abs(${$}(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 }`},u0=(e,r,t,u,s,c)=>{let f=e.dims,d=Jy(c,r.axes,f.length),g=e0(f,u,s,r.axes),w=u.slice();u.length===0&&(w=f.map((R,j)=>R===0?1:g[j]/R),r.keepAspectRatioPolicy!=="stretch"&&(g=t0(f,w,r)));let C=ne("output",e.dataType,g.length),$=Z("input",e.dataType,f.length),A=K.size(g),P=f.length===g.length&&f.every((R,j)=>R===g[j]),x=r.coordinateTransformMode==="tf_crop_and_resize",E=r.extrapolationValue,O=$.type.value,B=R=>`\n ${P?"":`\n ${Qy(r.coordinateTransformMode,O)};\n ${(()=>{switch(r.mode){case"nearest":return`\n ${i0($,f)};\n ${Xy(r.nearestMode,t,O)};\n ${n0($,C,f,g,w.length,d.length,x)};\n `;case"linear":return`\n ${r0(C,f,g,w.length,d.length)};\n ${(()=>{if(f.length===2||f.length===4)return`${o0($,C,f,x,E)}`;if(f.length===3||f.length===5)return`${s0($,C,f,x,E)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(f.length===2||f.length===4)return`${a0($,C,f,g,w,d,r.cubicCoeffA,x,r.extrapolationValue,r.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 ${R.registerUniform("output_size","u32").registerUniform("scales","f32",w.length).registerUniform("roi","f32",d.length).declareVariables($,C)}\n ${R.mainStart()}\n ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${P?"output[global_idx] = input[global_idx];":`\n let output_indices = ${C.offsetToIndices("global_idx")};\n var input_indices: ${$.type.indices};\n ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${$.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${r.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${f.length===2||f.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()};\n`}\n }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${w.length>0?w:""}|${s.length>0?s:""}|${d.length>0?d:""}|${P}|${f}`,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:g,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:[{type:12,data:A},{type:1,data:w},{type:1,data:d},...se(f,g)]})}},l0=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},zc=(e,r)=>{let t=[],u=[],s=[],c=l0(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Zy(e.inputs,r,c,t,u,s),e.compute(u0(e.inputs[0],r,c,t,u,s),{inputs:[0]})},Mc=e=>{let r=e.antialias,t=e.axes,u=e.coordinateTransformMode,s=e.cubicCoeffA,c=e.excludeOutside!==0,f=e.extrapolationValue,d=e.keepAspectRatioPolicy,g=e.mode,w=e.nearestMode===""?"simple":e.nearestMode;return ke({antialias:r,axes:t,coordinateTransformMode:u,cubicCoeffA:s,excludeOutside:c,extrapolationValue:f,keepAspectRatioPolicy:d,mode:g,nearestMode:w})}});var d0,c0,Uc,Vc=ae(()=>{"use strict";Te();De();nt();Re();d0=(e,r)=>{let[t,u,s,c]=e,{numHeads:f,rotaryEmbeddingDim:d}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input \'x\' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!K.areEqual(u.dims,[])&&!K.areEqual(u.dims,[1])&&u.dims.length!==2)throw new Error(`Input \'position_ids\' is expected to have 0, 1, or 2 dimensions, got ${u.dims.length}`);if(s.dims.length!==2)throw new Error(`Input \'cos_cache\' is expected to have 2 dimensions, got ${s.dims.length}`);if(c.dims.length!==2)throw new Error(`Input \'sin_cache\' is expected to have 2 dimensions, got ${c.dims.length}`);if(!K.areEqual(s.dims,c.dims))throw new Error("Inputs \'cos_cache\' and \'sin_cache\' are expected to have the same shape");if(d>0&&f===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let g=t.dims[0],w=t.dims[t.dims.length-2],C=s.dims[0],$=K.sizeFromDimension(t.dims,1)/w,A=d===0?s.dims[1]*2:$/f;if(d>A)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(u.dims.length===2){if(g!==u.dims[0])throw new Error(`Input \'position_ids\' dimension 0 should be of size batch_size, got ${u.dims[0]}`);if(w!==u.dims[1])throw new Error(`Input \'position_ids\' dimension 1 should be of size sequence_length, got ${u.dims[1]}`)}if(A/2!==s.dims[1]&&d/2!==s.dims[1])throw new Error(`Input \'cos_cache\' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(w>C)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},c0=(e,r)=>{let{interleaved:t,numHeads:u,rotaryEmbeddingDim:s,scale:c}=r,f=e[0].dims[0],d=K.sizeFromDimension(e[0].dims,1),g=e[0].dims[e[0].dims.length-2],w=d/g,C=e[2].dims[1],$=s===0?C*2:w/u,A=new Array(f,g,w/$,$-C),P=K.computeStrides(A),x=[{type:1,data:c},{type:12,data:A},{type:12,data:P},...e[0].dims.length===3?new Array({type:12,data:[d,w,$,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,$,g*$,1]}):[],...se(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],E=O=>{let B=Z("input",e[0].dataType,e[0].dims.length),R=Z("position_ids",e[1].dataType,e[1].dims.length),j=Z("cos_cache",e[2].dataType,e[2].dims.length),U=Z("sin_cache",e[3].dataType,e[3].dims.length),L=ne("output",e[0].dataType,e[0].dims.length);return O.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:A.length},{name:"global_strides",type:"u32",length:P.length},{name:"input_output_strides",type:"u32",length:P.length}]),`\n ${O.declareVariables(B,R,j,U,L)}\n\n ${O.mainStart(ur)}\n let half_rotary_emb_dim = uniforms.${j.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${O.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${R.broadcastedIndicesToOffset("bsnh.xy",ne("",R.type.tensor,2))};\n let position_id =\n u32(${R.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t});\n let j = i + select(half_rotary_emb_dim, 1, ${t});\n let re = ${B.getByOffset("i")} * ${j.get("position_id","bsnh[3]")} -\n ${B.getByOffset("j")} * ${U.get("position_id","bsnh[3]")};\n ${L.setByOffset("i","re")}\n let im = ${B.getByOffset("i")} * ${U.get("position_id","bsnh[3]")} +\n ${B.getByOffset("j")} * ${j.get("position_id","bsnh[3]")};\n ${L.setByOffset("j","im")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${L.setByOffset("k",B.getByOffset("k"))}\n }\n }`};return{name:"RotaryEmbedding",shaderCache:{hint:ke({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(K.size(A)/ur)},programUniforms:x})}},Uc=(e,r)=>{d0(e.inputs,r),e.compute(c0(e.inputs,r))}});var f0,p0,Wc,Nc=ae(()=>{"use strict";Te();De();Re();f0=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],u=e[2];if(r.dataType!==t.dataType||r.dataType!==u.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let s=r.dims[r.dims.length-1],c=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==c)throw new Error("Skip must have the same sequence length as input");if(u.dims.length!==1)throw new Error("Gamma must be 1D");if(u.dims[u.dims.length-1]!==s)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let f=e[3];if(f.dims.length!==1)throw new Error("Beta must be 1D");if(f.dims[f.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let f=e[4];if(f.dims.length!==1)throw new Error("Bias must be 1D");if(f.dims[f.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},p0=(e,r,t,u)=>{let s=r.simplified,c=e[0].dims,f=K.size(c),d=c,g=f,w=c.slice(-1)[0],C=u?c.slice(0,-1).concat(1):[],$=!s&&e.length>3,A=e.length>4,P=u&&t>1,x=u&&t>2,E=t>3,O=He(w),B=[{type:12,data:g},{type:12,data:O},{type:12,data:w},{type:1,data:r.epsilon}],R=U=>{let L=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],F=[Z("x",e[0].dataType,e[0].dims,O),Z("skip",e[1].dataType,e[1].dims,O),Z("gamma",e[2].dataType,e[2].dims,O)];$&&F.push(Z("beta",e[3].dataType,e[3].dims,O)),A&&F.push(Z("bias",e[4].dataType,e[4].dims,O)),F.push(ne("output",e[0].dataType,d,O)),P&&F.push(ne("mean_output",1,C)),x&&F.push(ne("inv_std_output",1,C)),E&&F.push(ne("input_skip_bias_sum",e[0].dataType,d,O));let te=Ne(e[0].dataType);return`\n\n ${U.registerUniforms(L).declareVariables(...F)}\n\n ${U.mainStart()}\n ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")}\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n let offset = global_idx * hidden_size_vectorized;\n var sum = ${xt("f32",O)};\n var squareSum = ${xt("f32",O)};\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${A?"bias[i]":te+"(0.0)"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${E?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${lr(te,O,"value")};\n sum += f32_value;\n squareSum += f32_value * f32_value;\n }\n let mean = ${It("sum",O)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${It("squareSum",O)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon);\n ${P?"mean_output[global_idx] = mean;":""}\n ${x?"inv_std_output[global_idx] = inv_std_dev;":""}\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n output[offset + i] = (output[offset + i] ${s?"":`- ${te}(mean)`}) * ${te}(inv_std_dev) * gamma[i] ${$?"+ beta[i]":""};\n }\n }`},j=[{dims:d,dataType:e[0].dataType}];return t>1&&j.push({dims:C,dataType:1}),t>2&&j.push({dims:C,dataType:1}),t>3&&j.push({dims:c,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${O};${P};${x};${E}`,inputDependencies:e.map((U,L)=>"type")},getShaderSource:R,getRunData:()=>({outputs:j,dispatchGroup:{x:Math.ceil(g/w/64)},programUniforms:B})}},Wc=(e,r)=>{f0(e.inputs);let u=[0];e.outputCount>1&&u.push(-3),e.outputCount>2&&u.push(-3),e.outputCount>3&&u.push(3),e.compute(p0(e.inputs,r,e.outputCount,!1),{outputs:u})}});var m0,bi,h0,Gc,g0,y0,Hc,Lc,Fc=ae(()=>{"use strict";Te();De();nt();Re();m0=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,u)=>{if(e[u+1].dataType!==6&&e[u+1].dataType!==7)throw new Error(`Input ${u} must be an array of int32 or int64`)})},bi=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(u=>t.push(Number(u)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(u=>t.push(Number(u)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},h0=(e,r)=>{if(e.length>1){let t=bi(e,1),u=bi(e,2),s=bi(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),ke({starts:t,ends:u,axes:s})}else return r},Gc=(e,r,t,u,s)=>{let c=e;return e<0&&(c+=t[u[r]]),s[r]<0?Math.max(0,Math.min(c,t[u[r]]-1)):Math.max(0,Math.min(c,t[u[r]]))},g0=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${t.length}; i >= 0; i--) {\n let input_shape_i = ${xe("uniforms.input_shape","i",t.length)};\n let steps_i = ${xe("uniforms.steps","i",t.length)};\n let signs_i = ${xe("uniforms.signs","i",t.length)};\n let starts_i = ${xe("uniforms.starts","i",t.length)};\n var output_index = ${r.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 }`,y0=(e,r)=>{let t=e[0].dims,u=K.size(t),s=r.axes.length>0?K.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],c=bi(e,4);c.forEach(B=>B!==0||(()=>{throw new Error("step cannot be 0")})),c.length===0&&(c=Array(s.length).fill(1));let f=r.starts.map((B,R)=>Gc(B,R,t,s,c)),d=r.ends.map((B,R)=>Gc(B,R,t,s,c));if(s.length!==f.length||s.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==t.length)for(let B=0;BMath.sign(B));c.forEach((B,R,j)=>{if(B<0){let U=(d[R]-f[R])/B,L=f[R],F=L+U*c[R];f[R]=F,d[R]=L,j[R]=-B}});let w=t.slice(0);s.forEach((B,R)=>{w[B]=Math.ceil((d[B]-f[B])/c[B])});let C={dims:w,dataType:e[0].dataType},$=ne("output",e[0].dataType,w.length),A=Z("input",e[0].dataType,e[0].dims.length),P=K.size(w),x=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:f.length},{name:"signs",type:"i32",length:g.length},{name:"steps",type:"u32",length:c.length}],E=[{type:12,data:P},{type:12,data:f},{type:6,data:g},{type:12,data:c},...se(e[0].dims,w)],O=B=>`\n ${B.registerUniforms(x).declareVariables(A,$)}\n ${g0(A,$,t)}\n ${B.mainStart()}\n ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${$.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${$.setByOffset("global_idx",A.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${g.length}_${f.length}_${c.length}`,inputDependencies:["rank"]},getShaderSource:O,getRunData:()=>({outputs:[C],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:E})}},Hc=(e,r)=>{m0(e.inputs,r);let t=h0(e.inputs,r);e.compute(y0(e.inputs,t),{inputs:[0]})},Lc=e=>{let r=e.starts,t=e.ends,u=e.axes;return ke({starts:r,ends:t,axes:u})}});var b0,v0,qc,Kc,Yc=ae(()=>{"use strict";Te();De();nt();Re();b0=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},v0=(e,r)=>{let t=e.dims,u=K.size(t),s=64,c=r.axis;if(c<0&&(c=t.length+c),cB===4?`max(max(${O}.x, ${O}.y), max(${O}.z, ${O}.w))`:B===2?`max(${O}.x, ${O}.y)`:B===3?`max(max(${O}.x, ${O}.y), ${O}.z)`:O,$=Z("x",e.dataType,e.dims,g),A=ne("result",e.dataType,e.dims,g),P=$.type.value,x=Ne(e.dataType)==="f32"?`var threadMax = ${P}(-3.402823e+38f);`:`var threadMax = ${P}(-65504.0h);`,E=O=>`\n var rowMaxShared : ${P};\n var rowSumShared : ${P};\n var threadShared : array<${P}, ${s}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${P} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${P}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${O.registerUniform("packedCols","i32").declareVariables($,A)}\n ${O.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${s};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${x}\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 = ${P}(${C("threadShared[0]",g)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${P}(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 = ${P}(${It("threadShared[0]",g)});\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:`${g}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:t,dataType:e.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:w}]}),getShaderSource:E}},qc=(e,r)=>{b0(e.inputs),e.compute(v0(e.inputs[0],r))},Kc=e=>ke({axis:e.axis})});var w0,_0,$0,C0,S0,Zc,Qc,Xc=ae(()=>{"use strict";Te();De();nt();Re();w0=e=>{if(!e||e.length<1)throw new Error("too few inputs")},_0=(e,r)=>{let t=[],u=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),u=t.length),ke({numOutputs:u,axis:r.axis,splitSizes:t})},$0=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${xe("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,C0=e=>{let r=e.length,t=[];for(let u=0;u{let t=e[0].dims,u=K.size(t),s=e[0].dataType,c=K.normalizeAxis(r.axis,t.length),f=new Array(r.numOutputs),d=Z("input",s,t.length),g=new Array(r.numOutputs),w=[],C=[],$=0,A=[{type:12,data:u}];for(let x=0;x`\n ${x.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",g.length).declareVariables(d,...f)}\n ${$0(g.length)}\n ${C0(f)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${d.offsetToIndices("global_idx")};\n var index = ${d.indicesGet("indices",c)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${xe("uniforms.size_in_split_axis","output_number - 1u",g.length)};\n ${d.indicesSet("indices",c,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:P,getRunData:()=>({outputs:w,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:A})}},Zc=(e,r)=>{w0(e.inputs);let t=e.inputs.length===1?r:_0(e.inputs,r);e.compute(S0(e.inputs,t),{inputs:[0]})},Qc=e=>{let r=e.axis,t=e.splitSizes,u=e.numOutputs<0?t.length:e.numOutputs;if(u!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ke({axis:r,numOutputs:u,splitSizes:t})}});var Jc,x0,I0,A0,ef,tf=ae(()=>{"use strict";Te();De();Re();Jc=e=>Array.from(e.getBigInt64Array(),Number),x0=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(Jc(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")},I0=(e,r)=>{let t=[];for(let u=0;u{let r=e[0].dims,t=Jc(e[1]),u=I0(r,t),s=K.size(u),c=e[0].dataType,f=Z("input",c,r.length),d=ne("output",c,u.length),g=w=>`\n const inputShape = ${f.indices(...r)};\n ${w.registerUniform("output_size","u32").declareVariables(f,d)}\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${f.type.indices};\n for (var i = 0; i < ${r.length}; i++) {\n let input_dim_i = ${f.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i;\n\n ${f.indicesSet("input_indices","i","input_dim_value")}\n }\n ${d.setByOffset("global_idx",f.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},...se(e[0].dims,u)]}),getShaderSource:g}},ef=e=>{x0(e.inputs),e.compute(A0(e.inputs),{inputs:[0]})}});var T0,E0,rf,nf=ae(()=>{"use strict";Te();De();Re();T0=(e,r,t,u,s)=>{let c=ne("output_data",s,t.length,4),f=Z("a_data",r[1].dataType,r[1].dims.length,4),d=Z("b_data",r[2].dataType,r[2].dims.length,4),g=Z("c_data",r[0].dataType,r[0].dims.length,4),w,C=($,A,P)=>`select(${A}, ${$}, ${P})`;if(!u)w=c.setByOffset("global_idx",C(f.getByOffset("global_idx"),d.getByOffset("global_idx"),g.getByOffset("global_idx")));else{let $=(A,P,x="")=>{let E=`a_data[index_a${P}][component_a${P}]`,O=`b_data[index_b${P}][component_b${P}]`,B=`bool(c_data[index_c${P}] & (0xffu << (component_c${P} * 8)))`;return`\n let output_indices${P} = ${c.offsetToIndices(`global_idx * 4u + ${P}u`)};\n let offset_a${P} = ${f.broadcastedIndicesToOffset(`output_indices${P}`,c)};\n let offset_b${P} = ${d.broadcastedIndicesToOffset(`output_indices${P}`,c)};\n let offset_c${P} = ${g.broadcastedIndicesToOffset(`output_indices${P}`,c)};\n let index_a${P} = offset_a${P} / 4u;\n let index_b${P} = offset_b${P} / 4u;\n let index_c${P} = offset_c${P} / 4u;\n let component_a${P} = offset_a${P} % 4u;\n let component_b${P} = offset_b${P} % 4u;\n let component_c${P} = offset_c${P} % 4u;\n ${A}[${P}] = ${x}(${C(E,O,B)});\n `};s===9?w=`\n var data = vec4(0);\n ${$("data",0,"u32")}\n ${$("data",1,"u32")}\n ${$("data",2,"u32")}\n ${$("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=`\n ${$("output_data[global_idx]",0)}\n ${$("output_data[global_idx]",1)}\n ${$("output_data[global_idx]",2)}\n ${$("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(g,f,d,c)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${w}\n }`},E0=e=>{let r=e[1].dims,t=e[2].dims,u=e[0].dims,s=e[1].dataType,c=!(K.areEqual(r,t)&&K.areEqual(t,u)),f=r,d=K.size(r);if(c){let w=Ot.calcShape(Ot.calcShape(r,t,!1),u,!1);if(!w)throw new Error("Can\'t perform where op on the given tensors");f=w,d=K.size(f)}let g=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:w=>T0(w,e,f,c,s),getRunData:()=>({outputs:[{dims:f,dataType:s}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:g},...se(u,r,t,f)]})}},rf=e=>{e.compute(E0(e.inputs))}});var of,af=ae(()=>{"use strict";hl();Qi();wl();$l();ad();yd();Zi();ro();kd();Bd();Md();Nd();Ld();qd();Zd();Jd();rc();ic();ac();io();lc();pc();hc();Oc();Bc();ni();jc();Vc();Nc();Fc();Yc();Xc();tf();Dr();li();nf();of=new Map([["Abs",[Cl]],["Acos",[Sl]],["Acosh",[xl]],["Add",[sd]],["ArgMax",[ml,Yi]],["ArgMin",[pl,Yi]],["Asin",[Il]],["Asinh",[Al]],["Atan",[Tl]],["Atanh",[El]],["Attention",[bl]],["AveragePool",[Cc,$c]],["BatchNormalization",[vl]],["BiasAdd",[_l]],["BiasSplitGelu",[od]],["Cast",[kl,Pl]],["Ceil",[Rl]],["Clip",[Ol]],["Concat",[gl,yl]],["Conv",[so,ao]],["ConvTranspose",[Pd,Ed]],["Cos",[Bl]],["Cosh",[Dl]],["CumSum",[Od,Rd]],["DepthToSpace",[Dd,zd]],["Div",[ud]],["Einsum",[Vd,Wd]],["Elu",[zl,si]],["Equal",[ld]],["Erf",[Ml]],["Exp",[jl]],["Expand",[Hd]],["FastGelu",[Fd]],["Floor",[Ul]],["FusedConv",[so,ao]],["Gather",[Yd,Kd]],["GatherElements",[Xd,Qd]],["Gelu",[Vl]],["Gemm",[tc,ec]],["GlobalAveragePool",[Ic,xc]],["GlobalMaxPool",[kc,Pc]],["Greater",[pd]],["GreaterOrEqual",[hd]],["HardSigmoid",[Kl,ql]],["InstanceNormalization",[nc]],["LayerNormalization",[oc]],["LeakyRelu",[Wl,si]],["Less",[md]],["LessOrEqual",[gd]],["Log",[nd]],["MatMul",[Cd]],["MatMulNBits",[sc,uc]],["MaxPool",[Tc,Ec]],["Mul",[dd]],["MultiHeadAttention",[fc,cc]],["Neg",[Gl]],["Not",[Nl]],["Pad",[mc]],["Pow",[cd]],["Range",[Rc]],["Reciprocal",[Hl]],["ReduceMin",[sl]],["ReduceMean",[rl]],["ReduceMax",[al]],["ReduceSum",[ll]],["ReduceProd",[ul]],["ReduceL1",[nl]],["ReduceL2",[il]],["ReduceLogSum",[cl]],["ReduceLogSumExp",[ol]],["ReduceSumSquare",[dl]],["Relu",[Ll]],["Resize",[zc,Mc]],["RotaryEmbedding",[Uc]],["Sigmoid",[Fl]],["Sin",[Yl]],["Sinh",[Zl]],["Slice",[Hc,Lc]],["SkipLayerNormalization",[Wc]],["Split",[Zc,Qc]],["Sqrt",[Ql]],["Softmax",[qc,Kc]],["Sub",[fd]],["Tan",[Xl]],["Tanh",[ed]],["ThresholdedRelu",[rd,si]],["Tile",[ef]],["Transpose",[Gu,Hu]],["Where",[rf]]])});var vi,sf=ae(()=>{"use strict";Rr();Lt();Re();vi=class{constructor(r){this.backend=r;this.repo=new Map,this.attributesBound=!1}getArtifact(r){return this.repo.get(r)}setArtifact(r,t){this.repo.set(r,t)}run(r,t,u,s,c){ar(r.programInfo.name);let f=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let g=[];for(let C of t)g.push({binding:g.length,resource:{buffer:C.buffer}});for(let C of u)g.push({binding:g.length,resource:{buffer:C.buffer}});c&&g.push({binding:g.length,resource:c});let w=f.createBindGroup({layout:r.computePipeline.getBindGroupLayout(0),entries:g,label:r.programInfo.name});if(this.backend.sessionStatus==="capturing"){let C={kernelId:this.backend.currentKernelId,computePipeline:r.computePipeline,bindGroup:w,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(C)}d.setPipeline(r.computePipeline),d.setBindGroup(0,w),d.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ht(r.programInfo.name)}dispose(){}build(r,t){ar(r.name);let u=this.backend.device,s=[];u.features.has("shader-f16")&&s.push("enable f16;");let c=Wu(t,this.backend.device.limits),f=r.getShaderSource(c),d=`${s.join(`\n`)}\n${c.additionalImplementations}\n${f}`,g=u.createShaderModule({code:d,label:r.name});Fe("verbose",()=>`[WebGPU] ${r.name} shader code: ${d}`);let w=u.createComputePipeline({compute:{module:g,entryPoint:"main"},layout:"auto",label:r.name});return Ht(r.name),{programInfo:r,computePipeline:w,uniformVariablesInfo:c.variablesInfo}}normalizeDispatchGroupSize(r){let t=typeof r=="number"?r:r.x,u=typeof r=="number"?1:r.y||1,s=typeof r=="number"?1:r.z||1,c=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=c&&u<=c&&s<=c)return[t,u,s];let f=t*u*s,d=Math.ceil(Math.sqrt(f));if(d>c){if(d=Math.ceil(Math.cbrt(f)),d>c)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}});var P0,k0,mo,wi,uf=ae(()=>{"use strict";Rr();Te();Lt();Du();Vu();af();sf();P0=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let u=0;u{let u=e.name;return e.shaderCache?.hint&&(u+="["+e.shaderCache.hint+"]"),u+=":"+t+`:${P0(r,e.shaderCache?.inputDependencies??new Array(r.length).fill("dims"))}`,u},mo=class{constructor(r){r&&(this.architecture=r.architecture,this.vendor=r.vendor)}isArchitecture(r){return this.architecture===r}isVendor(r){return this.vendor===r}},wi=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let r=this.kernelCustomData.get(this.currentKernelId);return r||(r={},this.kernelCustomData.set(this.currentKernelId,r)),r}async initialize(r,t){this.env=r;let u=[],s={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:u};t.features.has("chromium-experimental-timestamp-query-inside-passes")?u.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&u.push("timestamp-query"),t.features.has("shader-f16")&&u.push("shader-f16"),this.device=await t.requestDevice(s),this.adapterInfo=new mo(await t.requestAdapterInfo()),this.gpuDataManager=Uu(this),this.programManager=new vi(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ru(r.logLevel,!!r.debug),this.device.onuncapturederror=c=>{c.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${c.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let r=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=r.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;ar(),this.endComputePass();let r;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),r=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(r,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,r,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&r.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(r.getMappedRange()),u=this.pendingQueries.get(r);for(let s=0;s"u"&&(this.queryTimeBase=P);let E=Number(P-this.queryTimeBase),O=Number(x-this.queryTimeBase);if(!Number.isSafeInteger(E)||!Number.isSafeInteger(O))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:$.map(B=>({dims:B.dims,dataType:Gt(B.dataType)})),outputsMetadata:A.map(B=>({dims:B.dims,dataType:Gt(B.dataType)})),kernelId:f,kernelType:g,kernelName:w,programName:C,startTime:E,endTime:O});else{let B="";$.forEach((j,U)=>{B+=`input[${U}]: [${j.dims}] | ${Gt(j.dataType)}, `});let R="";A.forEach((j,U)=>{R+=`output[${U}]: [${j.dims}] | ${Gt(j.dataType)}, `}),console.log(`[profiling] kernel "${f}|${g}|${w}|${C}" ${B}${R}execution time: ${O-E} ns`)}Mi("GPU",`${C}::${P}::${x}`)}r.unmap(),this.pendingQueries.delete(r)}),Ht()}run(r,t,u,s,c,f){ar(r.name);let d=[];for(let j=0;jU):u;if($.length!==g.length)throw new Error(`Output size ${$.length} must be equal to ${g.length}.`);let A=[],P=[];for(let j=0;j=f)throw new Error(`Invalid output index: ${$[j]}`);if($[j]===-3)continue;let U=$[j]===-1,L=$[j]===-2,F=U||L?c(g[j].dataType,g[j].dims):s($[j],g[j].dataType,g[j].dims);if(A.push(F),F.data===0)continue;let te=this.gpuDataManager.get(F.data);if(!te)throw new Error(`no GPU data for output: ${F.data}`);if(U&&this.temporaryData.push(te),L){let J=this.kernelPersistentData.get(this.currentKernelId);J||(J=[],this.kernelPersistentData.set(this.currentKernelId,J)),J.push(te)}P.push(te)}if(d.length!==t.length||P.length!==A.length){if(P.length===0)return Ht(r.name),A;throw new Error(`Program ${r.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let x;if(C){let j=0,U=[];C.forEach(J=>{let oe=typeof J.data=="number"?[J.data]:J.data;if(oe.length===0)return;let le=J.type===10?2:4,ge,X;J.type===10?(X=oe.length>4?16:oe.length>2?8:oe.length*le,ge=oe.length>4?16:le*oe.length):(X=oe.length<=2?oe.length*le:16,ge=16),j=Math.ceil(j/X)*X,U.push(j);let pe=J.type===10?8:4;j+=oe.length>4?Math.ceil(oe.length/pe)*ge:oe.length*le});let L=16;j=Math.ceil(j/L)*L;let F=new ArrayBuffer(j);C.forEach((J,oe)=>{let le=U[oe],ge=typeof J.data=="number"?[J.data]:J.data;if(J.type===6)new Int32Array(F,le,ge.length).set(ge);else if(J.type===12)new Uint32Array(F,le,ge.length).set(ge);else if(J.type===10)new Uint16Array(F,le,ge.length).set(ge);else if(J.type===1)new Float32Array(F,le,ge.length).set(ge);else throw new Error(`Unsupported uniform type: ${Gt(J.type)}`)});let te=this.gpuDataManager.create(j,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(te.buffer,0,F,0,j),this.gpuDataManager.release(te.id),x={offset:0,size:j,buffer:te.buffer}}let E=this.programManager.normalizeDispatchGroupSize(w),O=E[1]===1&&E[2]===1,B=k0(r,t,O),R=this.programManager.getArtifact(B);if(R||(R=this.programManager.build(r,E),this.programManager.setArtifact(B,R),Fe("info",()=>`[artifact] key: ${B}, programName: ${r.name}`)),C&&R.uniformVariablesInfo){if(C.length!==R.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${R.uniformVariablesInfo.length}, got ${C.length} in program "${R.programInfo.name}".`);for(let j=0;j`[ProgramManager] run "${r.name}" (key=${B}) with ${E[0]}x${E[1]}x${E[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let j={kernelId:this.currentKernelId,programName:R.programInfo.name,inputTensorViews:t,outputTensorViews:A};this.pendingKernels.push(j),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(j)}return this.programManager.run(R,d,P,E,x),Ht(r.name),A}upload(r,t){this.gpuDataManager.upload(r,t)}memcpy(r,t){this.gpuDataManager.memcpy(r,t)}async download(r,t){await this.gpuDataManager.download(r,t)}alloc(r){return this.gpuDataManager.create(r).id}free(r){return this.gpuDataManager.release(r)}createKernel(r,t,u,s){let c=of.get(r);if(!c)throw new Error(`kernel not implemented: ${r}`);let f={kernelType:r,kernelName:s,kernelEntry:c[0],attributes:[c[1],u]};this.kernels.set(t,f)}releaseKernel(r){let t=this.kernelPersistentData.get(r);if(t){for(let u of t)this.gpuDataManager.release(u.id);this.kernelPersistentData.delete(r)}this.kernelCustomData.delete(r),this.kernels.delete(r)}computeKernel(r,t,u){let s=this.kernels.get(r);if(!s)throw new Error(`kernel not created: ${r}`);let c=s.kernelType,f=s.kernelName,d=s.kernelEntry,g=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${c}] ${f}" is not allowed to be called recursively`);this.currentKernelId=r,g[0]&&(g[1]=g[0](g[1]),g[0]=void 0),Fe("info",()=>`[WebGPU] Start to run kernel "[${c}] ${f}"...`);let w=this.env.debug;this.temporaryData=[];try{return w&&this.device.pushErrorScope("validation"),d(t,g[1]),0}catch(C){return u.push(Promise.resolve(`[WebGPU] Kernel "[${c}] ${f}" failed. ${C}`)),1}finally{w&&u.push(this.device.popErrorScope().then(C=>C?`GPU validation error for kernel "[${c}] ${f}": ${C.message}`:null));for(let C of this.temporaryData)this.gpuDataManager.release(C.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(r,t,u,s){let c=this.sessionExternalDataMapping.get(r);c||(c=new Map,this.sessionExternalDataMapping.set(r,c));let f=c.get(t),d=this.gpuDataManager.registerExternalBuffer(u,s,f?.[1]);return c.set(t,[d,u]),d}unregisterBuffers(r){let t=this.sessionExternalDataMapping.get(r);t&&(t.forEach(u=>this.gpuDataManager.unregisterExternalBuffer(u[1])),this.sessionExternalDataMapping.delete(r))}getBuffer(r){let t=this.gpuDataManager.get(r);if(!t)throw new Error(`no GPU data for buffer: ${r}`);return t.buffer}createDownloader(r,t,u){return async()=>{let s=await Ni(this,r,t);return Bu(s.buffer,u)}}writeTimestamp(r){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,r)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Fe("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Fe("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Fe("info","replay"),this.sessionStatus="replaying";let r=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),u=r.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(r){this.unregisterBuffers(r),this.capturedCommandList.has(r)&&this.capturedCommandList.delete(r),this.capturedPendingKernels.has(r)&&this.capturedPendingKernels.delete(r),this.gpuDataManager.onReleaseSession(r)}onRunStart(r){this.currentSessionId=r,this.setQueryType()}}});var lf={};Hn(lf,{init:()=>O0});var mn,ho,O0,df=ae(()=>{"use strict";Te();uf();Lt();De();mn=class e{constructor(r,t,u,s){this.module=r;this.dataType=t;this.data=u;this.dims=s}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=K.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=K.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=K.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(K.size(r)!==K.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,r)}},ho=class{constructor(r,t,u){this.module=r;this.backend=t;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=t.adapterInfo;let s=r.HEAPU32,c=u>>>2;this.opKernelContext=s[c++];let f=s[c++];this.outputCount=s[c++],this.customDataOffset=s[c++],this.customDataSize=s[c++];let d=[];for(let g=0;gtypeof d=="number"?this.inputs[d]:d)??this.inputs,s=t?.outputs??[],c=(d,g,w)=>new mn(this.module,g,this.output(d,w),w),f=(d,g)=>{let w=or(d);if(!w)throw new Error(`Unsupported data type: ${d}`);let C=w*K.size(g),$=C>0?this.backend.gpuDataManager.create(C).id:0;return new mn(this.module,d,$,g)};return this.backend.run(r,u,s,c,f,this.outputCount)}output(r,t){let u=this.module.stackSave();try{let s=this.module.stackAlloc((1+t.length)*4),c=s>>2;this.module.HEAPU32[c++]=t.length;for(let f=0;f{let s=r.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let c=new wi;await c.initialize(t,u),s("webgpu",[c,f=>c.alloc(f),f=>c.free(f),(f,d,g,w=!1)=>{if(w)Fe("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${f}, dst=${d}, size=${g}`),c.memcpy(f,d);else{Fe("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${f}, gpuDataId=${d}, size=${g}`);let C=r.HEAPU8.subarray(f>>>0,(f>>>0)+g);c.upload(d,C)}},async(f,d,g)=>{Fe("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${f}, dataOffset=${d}, size=${g}`),await c.download(f,()=>r.HEAPU8.subarray(d>>>0,(d>>>0)+g))},(f,d,g)=>c.createKernel(f,d,g,r.UTF8ToString(r._JsepGetNodeName(d))),f=>c.releaseKernel(f),(f,d,g,w)=>{Fe("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${g}, kernel=${f}, contextDataOffset=${d}`);let C=new ho(r,c,d);return c.computeKernel(f,C,w)},()=>c.captureBegin(),()=>c.captureEnd(),()=>c.replay()])}else s("webnn")}});var au;au=Zs();var Vh=nu(),Oi,Ri=!1,qn=!1,ou=!1,Wh=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}},Nh=()=>{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}},Gh=(e,r)=>e?r?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":r?"ort-wasm-threaded.wasm":"ort-wasm.wasm",su=async e=>{if(Ri)return Promise.resolve();if(qn)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(ou)throw new Error("previous call to \'initializeWebAssembly()\' failed.");qn=!0;let r=e.initTimeout,t=e.numThreads,u=e.simd,s=Wh(t),c=u&&Nh(),f=e.wasmPaths,d=typeof f=="string"?f:void 0,g=Gh(c,s),w=typeof f=="object"?f[g]:void 0,C=!1,$=[];if(r>0&&$.push(new Promise(A=>{setTimeout(()=>{C=!0,A()},r)})),$.push(new Promise((A,P)=>{let x=s?Vh:au,E={locateFile:(O,B)=>{if(s&&O.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([iu()],{type:"text/javascript"}));if(O.endsWith(".wasm")){if(w)return w;let R=d??B;return g==="ort-wasm-simd.wasm"?R+"ort-wasm-simd.jsep.wasm":g==="ort-wasm-simd-threaded.wasm"?R+"ort-wasm-simd-threaded.jsep.wasm":R+g}return B+O}};if(s)if(E.numThreads=t,typeof Blob>"u")E.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let O=`var ortWasmThreaded=${x.toString()};`;E.mainScriptUrlOrBlob=new Blob([O],{type:"text/javascript"})}x(E).then(O=>{qn=!1,Ri=!0,Oi=O,A()},O=>{qn=!1,ou=!0,P(O)})})),await Promise.race($),C)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Qe=()=>{if(Ri&&Oi)return Oi;throw new Error("WebAssembly is not initialized yet.")};var Xe=(e,r)=>{let t=Qe(),u=t.lengthBytesUTF8(e)+1,s=t._malloc(u);return t.stringToUTF8(e,s,u),r.push(s),s},ln=(e,r,t,u)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([s,c])=>{let f=r?r+s:s;if(typeof c=="object")ln(c,f+".",t,u);else if(typeof c=="string"||typeof c=="number")u(f,c.toString());else if(typeof c=="boolean")u(f,c?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof c}`)})},Le=e=>{let r=Qe(),t=r.stackSave();try{let u=r.stackAlloc(8);r._OrtGetLastError(u,u+4);let s=r.HEAP32[u/4],c=r.HEAPU32[u/4+1],f=c?r.UTF8ToString(c):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${f}`)}finally{r.stackRestore(t)}};var uu=e=>{let r=Qe(),t=0,u=[],s=e||{};try{if(e?.logSeverityLevel===void 0)s.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)s.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&&(s.terminate=!1);let c=0;return e?.tag!==void 0&&(c=Xe(e.tag,u)),t=r._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,c),t===0&&Le("Can\'t create run options."),e?.extra!==void 0&&ln(e.extra,"",new WeakSet,(f,d)=>{let g=Xe(f,u),w=Xe(d,u);r._OrtAddRunConfigEntry(t,g,w)!==0&&Le(`Can\'t set a run config entry: ${f} - ${d}.`)}),[t,u]}catch(c){throw t!==0&&r._OrtReleaseRunOptions(t),u.forEach(f=>r._free(f)),c}};var Hh=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}`)}},Lh=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Fh=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},qh=(e,r,t)=>{for(let u of r){let s=typeof u=="string"?u:u.name;switch(s){case"webnn":if(s="WEBNN",typeof u!="string"){let f=u;if(f?.deviceType){let d=Xe("deviceType",t),g=Xe(f.deviceType,t);Qe()._OrtAddSessionConfigEntry(e,d,g)!==0&&Le(`Can\'t set a session config entry: \'deviceType\' - ${f.deviceType}.`)}if(f?.numThreads){let d=f.numThreads;(typeof d!="number"||!Number.isInteger(d)||d<0)&&(d=0);let g=Xe("numThreads",t),w=Xe(d.toString(),t);Qe()._OrtAddSessionConfigEntry(e,g,w)!==0&&Le(`Can\'t set a session config entry: \'numThreads\' - ${f.numThreads}.`)}if(f?.powerPreference){let d=Xe("powerPreference",t),g=Xe(f.powerPreference,t);Qe()._OrtAddSessionConfigEntry(e,d,g)!==0&&Le(`Can\'t set a session config entry: \'powerPreference\' - ${f.powerPreference}.`)}}break;case"webgpu":if(s="JS",typeof u!="string"){let f=u;if(f?.preferredLayout){if(f.preferredLayout!=="NCHW"&&f.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${f.preferredLayout}`);let d=Xe("preferredLayout",t),g=Xe(f.preferredLayout,t);Qe()._OrtAddSessionConfigEntry(e,d,g)!==0&&Le(`Can\'t set a session config entry: \'preferredLayout\' - ${f.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let c=Xe(s,t);Qe()._OrtAppendExecutionProvider(e,c)!==0&&Le(`Can\'t append execution provider: ${s}.`)}},lu=e=>{let r=Qe(),t=0,u=[],s=e||{};Fh(s);try{let c=Hh(s.graphOptimizationLevel??"all"),f=Lh(s.executionMode??"sequential"),d=typeof s.logId=="string"?Xe(s.logId,u):0,g=s.logSeverityLevel??2;if(!Number.isInteger(g)||g<0||g>4)throw new Error(`log serverity level is not valid: ${g}`);let w=s.logVerbosityLevel??0;if(!Number.isInteger(w)||w<0||w>4)throw new Error(`log verbosity level is not valid: ${w}`);let C=typeof s.optimizedModelFilePath=="string"?Xe(s.optimizedModelFilePath,u):0;if(t=r._OrtCreateSessionOptions(c,!!s.enableCpuMemArena,!!s.enableMemPattern,f,!!s.enableProfiling,0,d,g,w,C),t===0&&Le("Can\'t create session options."),s.executionProviders&&qh(t,s.executionProviders,u),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let $=Xe("enableGraphCapture",u),A=Xe(s.enableGraphCapture.toString(),u);r._OrtAddSessionConfigEntry(t,$,A)!==0&&Le(`Can\'t set a session config entry: \'enableGraphCapture\' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[$,A]of Object.entries(s.freeDimensionOverrides)){if(typeof $!="string")throw new Error(`free dimension override name must be a string: ${$}`);if(typeof A!="number"||!Number.isInteger(A)||A<0)throw new Error(`free dimension override value must be a non-negative integer: ${A}`);let P=Xe($,u);r._OrtAddFreeDimensionOverride(t,P,A)!==0&&Le(`Can\'t set a free dimension override: ${$} - ${A}.`)}return s.extra!==void 0&&ln(s.extra,"",new WeakSet,($,A)=>{let P=Xe($,u),x=Xe(A,u);r._OrtAddSessionConfigEntry(t,P,x)!==0&&Le(`Can\'t set a session config entry: ${$} - ${A}.`)}),[t,u]}catch(c){throw t!==0&&r._OrtReleaseSessionOptions(t),u.forEach(f=>r._free(f)),c}};Te();var cu=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(r){if(r.code==="ERR_FS_FILE_TOO_LARGE"){let t=(void 0)(e),u=[];for await(let s of t)u.push(s);return new Uint8Array(Buffer.concat(u))}throw r}else{let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),u=t?parseInt(t,10):0;if(u<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=r.body.getReader(),c;try{c=new ArrayBuffer(u)}catch(d){if(d instanceof RangeError){let g=Math.ceil(u/65536);c=new WebAssembly.Memory({initial:g,maximum:g}).buffer}else throw d}let f=0;for(;;){let{done:d,value:g}=await s.read();if(d)break;let w=g.byteLength;new Uint8Array(c,f,w).set(g),f+=w}return new Uint8Array(c,0,u)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var R0=(e,r)=>{Qe()._OrtInit(e,r)!==0&&Le("Can\'t initialize onnxruntime.")},ff=async e=>{R0(e.wasm.numThreads,dn(e.logLevel))},pf=async(e,r)=>{{let t=(df(),ir(lf)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let u=e.webgpu.adapter;if(u){if(typeof u.limits!="object"||typeof u.features!="object"||typeof u.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let c=e.webgpu.forceFallbackAdapter;if(c!==void 0&&typeof c!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${c}"`);if(u=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:c}),!u)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\')}if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await t("webgpu",Qe(),e,u)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",Qe(),e)}}},dr=new Map,B0=e=>{let r=Qe(),t=r.stackSave();try{let u=r.stackAlloc(8);return r._OrtGetInputOutputCount(e,u,u+4)!==0&&Le("Can\'t get session input/output count."),[r.HEAP32[u/4],r.HEAP32[u/4+1]]}finally{r.stackRestore(t)}},go=e=>{let r=Qe(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},mf=async(e,r)=>{let t,u,s=Qe();Array.isArray(e)?[t,u]=e:e.buffer===s.HEAPU8.buffer?[t,u]=[e.byteOffset,e.byteLength]:[t,u]=go(e);let c=0,f=0,d=0,g=[],w=[],C=[];try{if([f,g]=lu(r),r?.externalData&&s.mountExternalData){let R=[];for(let j of r.externalData){let U=typeof j=="string"?j:j.path;R.push(cu(typeof j=="string"?j:j.data).then(L=>{s.mountExternalData(U,L)}))}await Promise.all(R)}c=await s._OrtCreateSession(t,u,f),c===0&&Le("Can\'t create a session.");let[$,A]=B0(c),P=!!r?.enableGraphCapture,x=[],E=[],O=[];for(let R=0;R<$;R++){let j=s._OrtGetInputName(c,R);j===0&&Le("Can\'t get an input name."),w.push(j),x.push(s.UTF8ToString(j))}for(let R=0;RR==="gpu-buffer")&&(d=s._OrtCreateBinding(c),d===0&&Le("Can\'t create IO binding."),B={handle:d,outputPreferredLocations:O,outputPreferredLocationsEncoded:O.map(R=>Di(R))}),dr.set(c,[c,w,C,B,P,!1]),[c,x,E]}catch($){throw w.forEach(A=>s._OrtFree(A)),C.forEach(A=>s._OrtFree(A)),d!==0&&s._OrtReleaseBinding(d),c!==0&&s._OrtReleaseSession(c),$}finally{s._free(t),f!==0&&s._OrtReleaseSessionOptions(f),g.forEach($=>s._free($)),s.unmountExternalData?.()}},hf=e=>{let r=Qe(),t=dr.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[u,s,c,f,d]=t;f&&(d&&r._OrtClearBoundOutputs(f.handle),r._OrtReleaseBinding(f.handle)),r.jsepOnReleaseSession?.(e),s.forEach(g=>r._OrtFree(g)),c.forEach(g=>r._OrtFree(g)),r._OrtReleaseSession(u),dr.delete(e)},cf=(e,r,t,u,s,c=!1)=>{if(!e){r.push(0);return}let f=Qe(),d=e[0],g=e[1],w=e[3],C,$;if(d==="string"&&w==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(c&&w!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(w==="gpu-buffer"){let x=e[2].gpuBuffer,E=or(Bi(d));$=g.reduce((B,R)=>B*R,1)*E;let O=f.jsepRegisterBuffer;if(!O)throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');C=O(u,s,x,$)}else{let x=e[2];if(Array.isArray(x)){$=4*x.length,C=f._malloc($),t.push(C);let E=C/4;for(let O=0;Of.HEAP32[x++]=O);let E=f._OrtCreateTensor(Bi(d),C,$,P,g.length,Di(w));E===0&&Le(`Can\'t create tensor for input/output. session=${u}, index=${s}.`),r.push(E)}finally{f.stackRestore(A)}},gf=async(e,r,t,u,s,c)=>{let f=Qe(),d=dr.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let g=d[0],w=d[1],C=d[2],$=d[3],A=d[4],P=d[5],x=r.length,E=u.length,O=0,B=[],R=[],j=[],U=[],L=f.stackSave(),F=f.stackAlloc(x*4),te=f.stackAlloc(x*4),J=f.stackAlloc(E*4),oe=f.stackAlloc(E*4);try{[O,B]=uu(c);for(let me=0;meZe*rt,1);Ae=Gt(ce);let Pt=$?.outputPreferredLocations[u[me]];if(Ae==="string"){if(Pt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ze=[],rt=_e/4;for(let ct=0;ct0){let Ze=f.jsepGetBuffer;if(!Ze)throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');let rt=Ze(_e),ct=or(ce);if(ct===void 0||!du(Ae))throw new Error(`Unsupported data type: ${Ae}`);be=!0,ue.push([Ae,Ye,{gpuBuffer:rt,download:f.jsepCreateDownloader(rt,Ke*ct,Ae),dispose:()=>{f._OrtReleaseTensor(Ee)}},"gpu-buffer"])}else{let Ze=Kn(Ae),rt=new Ze(Ke);new Uint8Array(rt.buffer,rt.byteOffset,rt.byteLength).set(f.HEAPU8.subarray(_e,_e+rt.byteLength)),ue.push([Ae,Ye,rt,"cpu"])}}finally{f.stackRestore(Pe),Ae==="string"&&_e&&f._free(_e),be||f._OrtReleaseTensor(Ee)}}return $&&!A&&(f._OrtClearBoundOutputs($.handle),dr.set(e,[g,w,C,$,A,!1])),ue}finally{f.stackRestore(L),R.forEach(le=>f._OrtReleaseTensor(le)),j.forEach(le=>f._OrtReleaseTensor(le)),U.forEach(le=>f._free(le)),O!==0&&f._OrtReleaseRunOptions(O),B.forEach(le=>f._free(le))}},yf=e=>{let r=Qe(),t=dr.get(e);if(!t)throw new Error("invalid session id");let u=t[0],s=r._OrtEndProfiling(u);s===0&&Le("Can\'t get an profile file name."),r._OrtFree(s)},bf=e=>{let r=[];for(let t of e){let u=t[2];!Array.isArray(u)&&"buffer"in u&&r.push(u.buffer)}return r};self.onmessage=e=>{let{type:r,in:t}=e.data;try{switch(r){case"init-wasm":su(t.wasm).then(()=>{ff(t).then(()=>{postMessage({type:r})},u=>{postMessage({type:r,err:u})})},u=>{postMessage({type:r,err:u})});break;case"init-ep":{let{epName:u,env:s}=t;pf(s,u).then(()=>{postMessage({type:r})},c=>{postMessage({type:r,err:c})});break}case"copy-from":{let{buffer:u}=t,s=go(u);postMessage({type:r,out:s});break}case"create":{let{model:u,options:s}=t;mf(u,s).then(c=>{postMessage({type:r,out:c})},c=>{postMessage({type:r,err:c})});break}case"release":hf(t),postMessage({type:r});break;case"run":{let{sessionId:u,inputIndices:s,inputs:c,outputIndices:f,options:d}=t;gf(u,s,c,f,new Array(f.length).fill(null),d).then(g=>{g.some(w=>w[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:g},bf([...c,...g]))},g=>{postMessage({type:r,err:g})});break}case"end-profiling":yf(t),postMessage({type:r});break;default:}}catch(u){postMessage({type:r,err:u})}};})();\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'}),Ir,Tt,gn,Qn,Xn,Bo,Ia,Hr,qr,jf,Zn,Rf,Bf,Df,Nf,Lf,Uf,Ff,Wf=le(()=>{var t;Yt(),Ww(),Wn(),Ir=()=>!!He.wasm.proxy&&typeof document<"u",gn=!1,Qn=!1,Xn=!1,Ia=new Map,Hr=(e,r)=>{let n=Ia.get(e);n?n.push(r):Ia.set(e,[r])},qr=()=>{if(gn||!Qn||Xn||!Tt)throw new Error("worker not ready")},jf=e=>{switch(e.data.type){case"init-wasm":gn=!1,e.data.err?(Xn=!0,Bo[1](e.data.err)):(Qn=!0,Bo[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Ia.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Zn=typeof document<"u"?(t=document==null?void 0:document.currentScript)==null?void 0:t.src:void 0,Rf=async()=>{if(!Qn){if(gn)throw new Error("multiple calls to 'initWasm()' detected.");if(Xn)throw new Error("previous call to 'initWasm()' failed.");if(gn=!0,Ir())return He.wasm.wasmPaths===void 0&&Zn&&Zn.indexOf("blob:")!==0&&(He.wasm.wasmPaths=Zn.substr(0,+Zn.lastIndexOf("/")+1)),new Promise((e,r)=>{Tt==null||Tt.terminate();let n=URL.createObjectURL(new Blob([Gw()],{type:"text/javascript"}));Tt=new Worker(n,{name:"ort-wasm-proxy-worker"}),Tt.onerror=o=>r(o),Tt.onmessage=jf,URL.revokeObjectURL(n),Bo=[e,r];let a={type:"init-wasm",in:He};Tt.postMessage(a)});try{await Zl(He.wasm),await kf(He),Qn=!0}catch(e){throw Xn=!0,e}finally{gn=!1}}},Bf=async e=>{if(Ir())return qr(),new Promise((r,n)=>{Hr("init-ep",[r,n]);let a={type:"init-ep",in:{epName:e,env:He}};Tt.postMessage(a)});await Tf(He,e)},Df=async e=>Ir()?(qr(),new Promise((r,n)=>{Hr("copy-from",[r,n]);let a={type:"copy-from",in:{buffer:e}};Tt.postMessage(a,[e.buffer])})):jo(e),Nf=async(e,r)=>{if(Ir()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return qr(),new Promise((n,a)=>{Hr("create",[n,a]);let o={type:"create",in:{model:e,options:{...r}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Tt.postMessage(o,i)})}else return Af(e,r)},Lf=async e=>{if(Ir())return qr(),new Promise((r,n)=>{Hr("release",[r,n]);let a={type:"release",in:e};Tt.postMessage(a)});Mf(e)},Uf=async(e,r,n,a,o,i)=>{if(Ir()){if(n.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return qr(),new Promise((d,h)=>{Hr("run",[d,h]);let m=n,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:m,outputIndices:a,options:i}};Tt.postMessage(c,Pf(m))})}else return Of(e,r,n,a,o,i)},Ff=async e=>{if(Ir())return qr(),new Promise((r,n)=>{Hr("end-profiling",[r,n]);let a={type:"end-profiling",in:e};Tt.postMessage(a)});zf(e)}}),Do,Gf,Vf,Vw=le(()=>{Yt(),Wf(),Oe(),au(),Do=(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()}`)}},Gf=t=>{switch(t[3]){case"cpu":return new bt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Fs(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:a}=t[2];return bt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:n,dispose:a})}default:throw new Error(`invalid data location: ${t[3]}`)}},Vf=class{async fetchModelAndCopyToWasmMemory(t){return Df(await da(t))}async loadModel(t,e){Kt();let r;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?r=await da(t):r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames]=await Nf(r,e),Ut()}async dispose(){return Lf(this.sessionId)}async run(t,e,r){Kt();let n=[],a=[];Object.entries(t).forEach(_=>{let v=_[0],$=_[1],C=this.inputNames.indexOf(v);if(C===-1)throw new Error(`invalid input '${v}'`);n.push($),a.push(C)});let o=[],i=[];Object.entries(e).forEach(_=>{let v=_[0],$=_[1],C=this.outputNames.indexOf(v);if(C===-1)throw new Error(`invalid output '${v}'`);o.push($),i.push(C)});let d=n.map((_,v)=>Do(_,()=>`input "${this.inputNames[a[v]]}"`)),h=o.map((_,v)=>_?Do(_,()=>`output "${this.outputNames[i[v]]}"`):null),m=await Uf(this.sessionId,a,d,i,h,r),c={};for(let _=0;_{Yt(),Wf(),Vw(),Hf=()=>{if((typeof He.wasm.initTimeout!="number"||He.wasm.initTimeout<0)&&(He.wasm.initTimeout=0),typeof He.wasm.simd!="boolean"&&(He.wasm.simd=!0),typeof He.wasm.proxy!="boolean"&&(He.wasm.proxy=!1),typeof He.wasm.trace!="boolean"&&(He.wasm.trace=!1),typeof He.wasm.numThreads!="number"||!Number.isInteger(He.wasm.numThreads)||He.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(He.wasm.numThreads=1);let t=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;He.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},qf=class{async init(t){Hf(),await Rf(),await Bf(t)}async createInferenceSessionHandler(t,e){let r=new Vf;return await r.loadModel(t,e),Promise.resolve(r)}}}),Kf={};pn(Kf,{wasmBackend:()=>Yf});var Yf,qw=le(()=>{Hw(),Yf=new qf});Yt(),Yt(),Yt();var Kw="1.18.0",Yw=Nl;{let t=(qw(),Sr(Kf)).wasmBackend;Dr("webgpu",t,5),Dr("webnn",t,5),Dr("cpu",t,10),Dr("wasm",t,10)}Object.defineProperty(He.versions,"web",{value:Kw,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */var Qw=Object.freeze({__proto__:null,get InferenceSession(){return zs},get TRACE(){return Un},get TRACE_FUNC_BEGIN(){return Kt},get TRACE_FUNC_END(){return Ut},get Tensor(){return bt},get TrainingSession(){return Ps},default:Yw,get env(){return He},get registerBackend(){return Dr}});const Xw=(t,e)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];const n=r.getContext("2d");if(n!=null){let a,o;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],o=t.dims[3]):(a=t.dims[3],o=t.dims[2]);const i=(e==null?void 0:e.format)!==void 0?e.format:"RGB",d=e==null?void 0:e.norm;let h,m;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[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]));const c=o*a;let _=0,v=c,$=c*2,C=-1;i==="RGBA"?(_=0,v=c,$=c*2,C=c*3):i==="RGB"?(_=0,v=c,$=c*2):i==="RBG"&&(_=0,$=c,v=c*2);for(let k=0;k{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(r!=null){let a,o,i;(e==null?void 0:e.tensorLayout)!==void 0&&e.tensorLayout==="NHWC"?(a=t.dims[2],o=t.dims[1],i=t.dims[3]):(a=t.dims[3],o=t.dims[2],i=t.dims[1]);const d=e!==void 0&&e.format!==void 0?e.format:"RGB",h=e==null?void 0:e.norm;let m,c;h===void 0||h.mean===void 0?m=[255,255,255,255]:typeof h.mean=="number"?m=[h.mean,h.mean,h.mean,h.mean]:(m=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(m[3]=h.mean[3])),h===void 0||h.bias===void 0?c=[0,0,0,0]:typeof h.bias=="number"?c=[h.bias,h.bias,h.bias,h.bias]:(c=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(c[3]=h.bias[3]));const _=o*a;if(e!==void 0&&(e.format!==void 0&&i===4&&e.format!=="RGBA"||i===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const v=4;let $=0,C=1,k=2,M=3,z=0,I=_,j=_*2,R=-1;d==="RGBA"?(z=0,I=_,j=_*2,R=_*3):d==="RGB"?(z=0,I=_,j=_*2):d==="RBG"&&(z=0,j=_,I=_*2),n=r.createImageData(a,o);for(let L=0;L{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:n}=e,a=e.norm??{mean:255,bias:0};let o,i;typeof a.mean=="number"?o=[a.mean,a.mean,a.mean,a.mean]:o=[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],typeof a.bias=="number"?i=[a.bias,a.bias,a.bias,a.bias]:i=[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];const d=e.format!==void 0?e.format:"RGBA",h=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",m=r*n,c=h==="RGBA"?new Float32Array(m*4):new Float32Array(m*3);let _=4,v=0,$=1,C=2,k=3,M=0,z=m,I=m*2,j=-1;d==="RGB"&&(_=3,v=0,$=1,C=2,k=-1),h==="RGBA"?j=m*3:h==="RBG"?(M=0,I=m,z=m*2):h==="BGR"&&(I=0,z=m,M=m*2);for(let L=0;L{const r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,n=typeof ImageData<"u"&&t instanceof ImageData,a=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string";let i,d=e??{};const h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},m=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(r){const c=h();c.width=t.width,c.height=t.height;const _=m(c);if(_!=null){let v=t.height,$=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(v=e.resizedHeight,$=e.resizedWidth),e!==void 0){if(d=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=v,d.width=$}else d.tensorFormat="RGBA",d.height=v,d.width=$;_.drawImage(t,0,0),i=_.getImageData(0,0,$,v).data}else throw new Error("Can not access image data")}else if(n){let c,_;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(c=e.resizedHeight,_=e.resizedWidth):(c=t.height,_=t.width),e!==void 0&&(d=e),d.format="RGBA",d.height=c,d.width=_,e!==void 0){const v=h();v.width=_,v.height=c;const $=m(v);if($!=null)$.putImageData(t,0,0),i=$.getImageData(0,0,_,c).data;else throw new Error("Can not access image data")}else i=t.data}else if(a){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");const c=h();c.width=t.width,c.height=t.height;const _=m(c);if(_!=null){const v=t.height,$=t.width;return _.drawImage(t,0,0,$,v),i=_.getImageData(0,0,$,v).data,d.height=v,d.width=$,No(i,d)}else throw new Error("Can not access image data")}else{if(o)return new Promise((c,_)=>{const v=h(),$=m(v);if(!t||!$)return _();const C=new Image;C.crossOrigin="Anonymous",C.src=t,C.onload=()=>{v.width=C.width,v.height=C.height,$.drawImage(C,0,0,v.width,v.height);const k=$.getImageData(0,0,v.width,v.height);d.height=v.height,d.width=v.width,c(No(k.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return No(i,d);throw new Error("Input data provided is not supported - aborted tensor creation")},ev=(t,e)=>{const{width:r,height:n,download:a,dispose:o}=e,i=[1,n,r,4];return new cr({location:"texture",type:"float32",texture:t,dims:i,download:a,dispose:o})},tv=(t,e)=>{const{dataType:r,dims:n,download:a,dispose:o}=e;return new cr({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:n,download:a,dispose:o})},rv=(t,e,r)=>new cr({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]}),Aa=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Lo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Qf=!1;const nv=()=>{if(!Qf){Qf=!0;const t=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",e=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";t&&(Aa.set("int64",BigInt64Array),Lo.set(BigInt64Array,"int64")),e&&(Aa.set("uint64",BigUint64Array),Lo.set(BigUint64Array,"uint64"))}},iv=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new cr(t.type,t.data,e);case"cpu-pinned":return new cr({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new cr({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new cr({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};let cr=class{constructor(e,r,n){nv();let a,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,a=e.type,o=e.dims,e.location){case"cpu-pinned":{const d=Aa.get(a);if(!d)throw new TypeError(`unsupported type "${a}" to create tensor from pinned buffer`);if(!(e.data instanceof d))throw new TypeError(`buffer should be of type ${d.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 d,h;if(typeof e=="string")if(a=e,h=n,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");d=r}else{const m=Aa.get(e);if(m===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){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"?d=m.from(r,BigInt):d=m.from(r)}else if(r instanceof m)d=r;else throw new TypeError(`A ${a} tensor's data must be type of ${m}`)}else if(h=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const m=typeof e[0];if(m==="string")a="string",d=e;else if(m==="boolean")a="bool",d=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${m}.`)}else{const m=Lo.get(e.constructor);if(m===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);a=m,d=e}if(h===void 0)h=[d.length];else if(!Array.isArray(h))throw new TypeError("A tensor's dims must be a number array");o=h,this.cpuData=d,this.dataLocation="cpu"}const i=iv(o);if(this.cpuData&&i!==this.cpuData.length)throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=a,this.dims=o,this.size=i}static async fromImage(e,r){return Jw(e,r)}static fromTexture(e,r){return ev(e,r)}static fromGpuBuffer(e,r){return tv(e,r)}static fromPinnedBuffer(e,r,n){return rv(e,r,n)}toDataURL(e){return Xw(this,e)}toImageData(e){return Zw(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return av(this,e)}};const sv=cr,Jn=[];let Uo,Kr;Rr.IS_NODE_ENV?(Kr=Ye??fr,Jn.push("cpu"),Uo=["cpu"]):(Kr=Qw,Rr.IS_WEBGPU_AVAILABLE&&Jn.push("webgpu"),Jn.push("wasm"),Uo=["wasm"]);const ov=Kr.InferenceSession;function lv(t){let e=Uo;if(t){if(!Jn.includes(t))throw new Error(`Unsupported device: "${t}". Should be one of: ${Jn.join(", ")}.`);e=[t]}return e}async function uv(t,e){return await ov.create(t,e)}function Xf(t){return t instanceof Kr.Tensor}const tr=Kr==null?void 0:Kr.env;tr!=null&&tr.wasm&&(tr.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0-dev.20240430-204f1f59b9/dist/",tr.wasm.proxy=!Rr.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(tr.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(tr.wasm.simd=!1));function dv(){var t;return(t=tr==null?void 0:tr.wasm)==null?void 0:t.proxy}Et.backends.onnx=tr;const Zf=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 je{constructor(...e){te(this,"ort_tensor");return Xf(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new sv(e[0],e[1],e[2]),new Proxy(this,{get:(r,n)=>{if(typeof n=="string"){let a=Number(n);if(Number.isInteger(a))return r._getitem(a)}return r[n]},set:(r,n,a)=>r[n]=a})}get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...r]=this.dims;if(r.length>0){const n=r.reduce((a,o)=>a*o);for(let a=0;a0){const a=n.reduce((o,i)=>o*i);return this._subarray(e,a,n)}else return new je(this.type,[this.data[e]],n)}indexOf(e){const r=this.data;for(let n=0;nc[1])throw new Error(`Invalid slice: ${c}`);let _=[Math.max(c[0],0),Math.min(c[1],this.dims[m])];n.push(_),r.push(_[1]-_[0])}else throw new Error(`Invalid slice: ${c}`)}let a=n.map(([m,c])=>c-m),o=a.reduce((m,c)=>m*c);const i=this.data;let d=new i.constructor(o);const h=this.stride();for(let m=0;m=0;--_){const $=a[_];c+=(v%$+n[_][0])*h[_],v=Math.floor(v/$)}d[m]=i[c]}return new je(this.type,d,r)}permute(...e){return pv(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,n=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);const a=this.data;if(r===null){let d=a.reduce((h,m)=>h+m**e,0)**(1/e);return new je(this.type,[d],[])}r=Ar(r,this.dims.length);const o=this.dims.slice();o[r]=1;const i=new a.constructor(a.length/this.dims[r]);for(let d=0;d=0;--m){const v=this.dims[m];if(m!==r){const $=c%v;h+=$*_,_*=o[m]}c=Math.floor(c/v)}i[h]+=a[d]**e}if(e!==1)for(let d=0;d=0;--d){const c=this.dims[d];if(d!==r){const _=h%c;i+=_*m,m*=this.dims[d]}h=Math.floor(h/c)}a[o]/=n.data[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return mv(this.dims)}squeeze(e=null){return new je(this.type,this.data,Jf(this.dims,e))}squeeze_(e=null){return this.dims=Jf(this.dims,e),this}unsqueeze(e=null){return new je(this.type,this.data,em(this.dims,e))}unsqueeze_(e=null){return this.dims=em(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),a=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...n,a.reduce((i,d)=>i*d,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?a*o:a,1);e[r]=this.data.length/n}return new je(this.type,this.data,e)}neg_(){const e=this.data;for(let r=0;ro*i);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let a=t;for(let o=e.length-1;o>=0;o--)a=a.reduce((i,d)=>{let h=i[i.length-1];return h.lengthr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,n)=>r!==1||!e.includes(n))),t}function em(t,e){return e=Ar(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function Ar(t,e,r=null){if(t<-e||t>=e)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<0&&(t=(t%e+e)%e),t}function _r(t,e=0){e=Ar(e,t[0].dims.length);const r=t[0].dims.slice();r[e]=t.reduce((i,d)=>i+d.dims[e],0);const n=r.reduce((i,d)=>i*d,1),a=new t[0].data.constructor(n),o=t[0].type;if(e===0){let i=0;for(let d of t)a.set(d.data,i),i+=d.data.length}else{let i=0;for(let d=0;d=0;--_){const C=h.dims[_];let k=v%C;_===e&&(k+=i),c+=k*$,$*=r[_],v=Math.floor(v/C)}a[c]=h.data[m]}i+=h.dims[e]}}return new je(o,a,r)}function Fo(t,e=0){return _r(t.map(r=>r.unsqueeze(e)),e)}function hv(t,e=null,r=1,n=!1){if(e===null){const m=t.data.reduce(($,C)=>$+C,0)/t.data.length,c=Math.sqrt(t.data.reduce(($,C)=>$+(C-m)**2,0)/(t.data.length-r)),_=new je(t.type,[m],[]);return[new je(t.type,[c],[]),_]}e=Ar(e,t.dims.length);const a=Wo(t,e,n),o=t.dims.slice();o[e]=1;const i=new t.data.constructor(t.data.length/t.dims[e]);for(let h=0;h=0;--c){const $=t.dims[c];if(c!==e){const C=_%$;m+=C*v,v*=o[c]}_=Math.floor(_/$)}i[m]+=(t.data[h]-a.data[m])**2}for(let h=0;hi+d,0);return new je(t.type,[o/t.data.length],[])}e=Ar(e,t.dims.length);const n=t.dims.slice();n[e]=1;const a=new t.data.constructor(t.data.length/t.dims[e]);for(let o=0;o=0;--d){const c=t.dims[d];if(d!==e){const _=h%c;i+=_*m,m*=n[d]}h=Math.floor(h/c)}a[i]+=t.data[o]}if(t.dims[e]!==1)for(let o=0;o0||d>0;)switch(h.push(i-1),m.push(d-1),o[i][d].item()){case 0:--i,--d;break;case 1:--i;break;case 2:--d;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${d}]. Please file a bug report.`)}return h.reverse(),m.reverse(),[h,m]}function mv(t){const e=new Array(t.length);for(let r=t.length-1,n=1;r>=0;--r)e[r]=n,n*=t[r];return e}function Go(t,e,r,n){const a=t.reduce((o,i)=>o*i,1);return new je(r,new n(a).fill(e),t)}function gv(t,e){let r,n;return r="float32",n=Float32Array,Go(t,e,r,n)}function yv(t,e){return gv(t.dims,e)}function Ma(t){return Go(t,1n,"int64",BigInt64Array)}function _v(t){return Ma(t.dims)}function wv(t){return Go(t,0n,"int64",BigInt64Array)}function vv(t){return wv(t.dims)}class bv{constructor(e=(r,n)=>r>n){this._heap=[],this._comparator=e}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const r of e)this._heap.push(r),this._siftUp();return this.size}pop(){const e=this.peek(),r=this.size-1;return r>0&&this._swap(0,r),this._heap.pop(),this._siftDown(),e}replace(e){const r=this.peek();return this._heap[0]=e,this._siftDown(),r}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,r){return this._comparator(this._heap[e],this._heap[r])}_swap(e,r){const n=this._heap[e];this._heap[e]=this._heap[r],this._heap[r]=n}_siftUp(){let e=this.size-1;for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const a=new ei(this.bosTokenId,0,0,0,0),o=new ei(this.eosTokenId,1,this.len,0,0);this.nodes.push(a.clone()),this.nodes.push(o.clone()),this.beginNodes[this.len].push(o),this.endNodes[0].push(a)}insert(e,r,n,a){const o=this.nodes.length,i=new ei(a,o,e,r,n);this.beginNodes[e].push(i),this.endNodes[e+r].push(i),this.nodes.push(i)}viterbi(){const e=this.len;let r=0;for(;r<=e;){if(this.beginNodes[r].length==0)return[];for(let d of this.beginNodes[r]){d.prev=null;let h=0,m=null;for(let c of this.endNodes[r]){const _=c.backtraceScore+d.score;(m===null||_>h)&&(m=c.clone(),h=_)}if(m!==null)d.prev=m,d.backtraceScore=h;else return[]}++r}const n=[],o=this.beginNodes[e][0].prev;if(o===null)return[];let i=o.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){return this.viterbi().map(r=>this.piece(r))}tokenIds(){return this.viterbi().map(r=>r.tokenId)}}class ei{constructor(e,r,n,a,o){this.tokenId=e,this.nodeId=r,this.pos=n,this.length=a,this.score=o,this.prev=null,this.backtraceScore=0}clone(){const e=new ei(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}var Z=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),tm=Object.freeze({set:Z.Set,for:Z.For,in:Z.In,is:Z.Is,if:Z.If,else:Z.Else,endif:Z.EndIf,elif:Z.ElseIf,endfor:Z.EndFor,and:Z.And,or:Z.Or,not:Z.Not,"not in":Z.NotIn,true:Z.BooleanLiteral,false:Z.BooleanLiteral}),Yr=class{constructor(t,e){this.value=t,this.type=e}};function rm(t){return/\w/.test(t)}function Vo(t){return/[0-9]/.test(t)}var Cv=[["{%",Z.OpenStatement],["%}",Z.CloseStatement],["{{",Z.OpenExpression],["}}",Z.CloseExpression],["(",Z.OpenParen],[")",Z.CloseParen],["{",Z.OpenCurlyBracket],["}",Z.CloseCurlyBracket],["[",Z.OpenSquareBracket],["]",Z.CloseSquareBracket],[",",Z.Comma],[".",Z.Dot],[":",Z.Colon],["|",Z.Pipe],["<=",Z.ComparisonBinaryOperator],[">=",Z.ComparisonBinaryOperator],["==",Z.ComparisonBinaryOperator],["!=",Z.ComparisonBinaryOperator],["<",Z.ComparisonBinaryOperator],[">",Z.ComparisonBinaryOperator],["+",Z.AdditiveBinaryOperator],["-",Z.AdditiveBinaryOperator],["*",Z.MultiplicativeBinaryOperator],["/",Z.MultiplicativeBinaryOperator],["%",Z.MultiplicativeBinaryOperator],["=",Z.Equals]],Sv=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function Ev(t,e={}){return t.endsWith(` `)&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function kv(t,e={}){var i,d,h;const r=[],n=Ev(t,e);let a=0;const o=m=>{let c="";for(;m(n[a]);){if(n[a]==="\\"){if(++a,a>=n.length)throw new SyntaxError("Unexpected end of input");const _=n[a++],v=Sv.get(_);if(v===void 0)throw new SyntaxError(`Unexpected escaped character: ${_}`);c+=v;continue}if(c+=n[a++],a>=n.length)throw new SyntaxError("Unexpected end of input")}return c};e:for(;a0){r.push(new Yr(_,Z.Text));continue}}o(_=>/\s/.test(_));const c=n[a];if(c==="-"||c==="+"){const _=(d=r.at(-1))==null?void 0:d.type;if(_===Z.Text||_===void 0)throw new SyntaxError(`Unexpected character: ${c}`);switch(_){case Z.Identifier:case Z.NumericLiteral:case Z.BooleanLiteral:case Z.StringLiteral:case Z.CloseParen:case Z.CloseSquareBracket:break;default:{++a;const v=o(Vo);r.push(new Yr(`${c}${v}`,v.length>0?Z.NumericLiteral:Z.UnaryOperator));continue}}}for(const[_,v]of Cv)if(n.slice(a,a+_.length)===_){r.push(new Yr(_,v)),a+=_.length;continue e}if(c==="'"||c==='"'){++a;const _=o(v=>v!==c);r.push(new Yr(_,Z.StringLiteral)),++a;continue}if(Vo(c)){const _=o(Vo);r.push(new Yr(_,Z.NumericLiteral));continue}if(rm(c)){const _=o(rm),v=Object.hasOwn(tm,_)?tm[_]:Z.Identifier;v===Z.In&&((h=r.at(-1))==null?void 0:h.type)===Z.Not?(r.pop(),r.push(new Yr("not in",Z.NotIn))):r.push(new Yr(_,v));continue}throw new SyntaxError(`Unexpected character: ${c}`)}return r}var ti=class{constructor(){te(this,"type","Statement")}},Tv=class extends ti{constructor(e){super();te(this,"type","Program");this.body=e}},nm=class extends ti{constructor(e,r,n){super();te(this,"type","If");this.test=e,this.body=r,this.alternate=n}},Iv=class extends ti{constructor(e,r,n){super();te(this,"type","For");this.loopvar=e,this.iterable=r,this.body=n}},Av=class extends ti{constructor(e,r){super();te(this,"type","Set");this.assignee=e,this.value=r}},pr=class extends ti{constructor(){super(...arguments);te(this,"type","Expression")}},Mv=class extends pr{constructor(e,r,n){super();te(this,"type","MemberExpression");this.object=e,this.property=r,this.computed=n}},Ov=class extends pr{constructor(e,r){super();te(this,"type","CallExpression");this.callee=e,this.args=r}},yn=class extends pr{constructor(e){super();te(this,"type","Identifier");this.value=e}},_n=class extends pr{constructor(e){super();te(this,"type","Literal");this.value=e}},zv=class extends _n{constructor(){super(...arguments);te(this,"type","NumericLiteral")}},im=class extends _n{constructor(){super(...arguments);te(this,"type","StringLiteral")}},am=class extends _n{constructor(){super(...arguments);te(this,"type","BooleanLiteral")}},Pv=class extends _n{constructor(){super(...arguments);te(this,"type","ArrayLiteral")}},sm=class extends _n{constructor(){super(...arguments);te(this,"type","TupleLiteral")}},jv=class extends _n{constructor(){super(...arguments);te(this,"type","ObjectLiteral")}},ri=class extends pr{constructor(e,r,n){super();te(this,"type","BinaryExpression");this.operator=e,this.left=r,this.right=n}},Rv=class extends pr{constructor(e,r){super();te(this,"type","FilterExpression");this.operand=e,this.filter=r}},Bv=class extends pr{constructor(e,r,n){super();te(this,"type","TestExpression");this.operand=e,this.negate=r,this.test=n}},Dv=class extends pr{constructor(e,r){super();te(this,"type","UnaryExpression");this.operator=e,this.argument=r}},Nv=class extends pr{constructor(e=void 0,r=void 0,n=void 0){super();te(this,"type","SliceExpression");this.start=e,this.stop=r,this.step=n}},Lv=class extends pr{constructor(e,r){super();te(this,"type","KeywordArgumentExpression");this.key=e,this.value=r}};function Uv(t){const e=new Tv([]);let r=0;function n(X,U){const ne=t[r++];if(!ne||ne.type!==X)throw new Error(`Parser Error: ${U}. ${ne.type} !== ${X}.`);return ne}function a(){switch(t[r].type){case Z.Text:return d();case Z.OpenStatement:return h();case Z.OpenExpression:return m();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function o(...X){return r+X.length<=t.length&&X.some((U,ne)=>U!==t[r+ne].type)}function i(...X){return r+X.length<=t.length&&X.every((U,ne)=>U===t[r+ne].type)}function d(){return new im(n(Z.Text,"Expected text token").value)}function h(){n(Z.OpenStatement,"Expected opening statement token");let X;switch(t[r].type){case Z.Set:++r,X=c(),n(Z.CloseStatement,"Expected closing statement token");break;case Z.If:++r,X=_(),n(Z.OpenStatement,"Expected {% token"),n(Z.EndIf,"Expected endif token"),n(Z.CloseStatement,"Expected %} token");break;case Z.For:++r,X=$(),n(Z.OpenStatement,"Expected {% token"),n(Z.EndFor,"Expected endfor token"),n(Z.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type}`)}return X}function m(){n(Z.OpenExpression,"Expected opening expression token");const X=C();return n(Z.CloseExpression,"Expected closing expression token"),X}function c(){const X=C();if(i(Z.Equals)){++r;const U=c();return new Av(X,U)}return X}function _(){var ee,Ee,Te,K,he,ve,Le,Ke;const X=C();n(Z.CloseStatement,"Expected closing statement token");const U=[],ne=[];for(;!(((ee=t[r])==null?void 0:ee.type)===Z.OpenStatement&&(((Ee=t[r+1])==null?void 0:Ee.type)===Z.ElseIf||((Te=t[r+1])==null?void 0:Te.type)===Z.Else||((K=t[r+1])==null?void 0:K.type)===Z.EndIf));)U.push(a());if(((he=t[r])==null?void 0:he.type)===Z.OpenStatement&&((ve=t[r+1])==null?void 0:ve.type)!==Z.EndIf)if(++r,i(Z.ElseIf))n(Z.ElseIf,"Expected elseif token"),ne.push(_());else for(n(Z.Else,"Expected else token"),n(Z.CloseStatement,"Expected closing statement token");!(((Le=t[r])==null?void 0:Le.type)===Z.OpenStatement&&((Ke=t[r+1])==null?void 0:Ke.type)===Z.EndIf);)ne.push(a());return new nm(X,U,ne)}function v(X=!1){const U=X?ge:C,ne=[U()],ee=i(Z.Comma);for(;ee&&(++r,ne.push(U()),!!i(Z.Comma)););return ee?new sm(ne):ne[0]}function $(){const X=v(!0);if(!(X instanceof yn||X instanceof sm))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${X.type} instead`);n(Z.In,"Expected `in` keyword following loop variable");const U=C();n(Z.CloseStatement,"Expected closing statement token");const ne=[];for(;o(Z.OpenStatement,Z.EndFor);)ne.push(a());return new Iv(X,U,ne)}function C(){return k()}function k(){const X=M();if(i(Z.If)){++r;const U=M();n(Z.Else,"Expected else token");const ne=M();return new nm(U,[X],[ne])}return X}function M(){let X=z();for(;i(Z.Or);){const U=t[r];++r;const ne=z();X=new ri(U,X,ne)}return X}function z(){let X=I();for(;i(Z.And);){const U=t[r];++r;const ne=I();X=new ri(U,X,ne)}return X}function I(){let X;for(;i(Z.Not);){const U=t[r];++r;const ne=I();X=new Dv(U,ne)}return X??j()}function j(){let X=R();for(;i(Z.ComparisonBinaryOperator)||i(Z.In)||i(Z.NotIn);){const U=t[r];++r;const ne=R();X=new ri(U,X,ne)}return X}function R(){let X=Se();for(;i(Z.AdditiveBinaryOperator);){const U=t[r];++r;const ne=Se();X=new ri(U,X,ne)}return X}function L(){const X=ce();return i(Z.OpenParen)?Y(X):X}function Y(X){let U=new Ov(X,Q());return i(Z.OpenParen)&&(U=Y(U)),U}function Q(){n(Z.OpenParen,"Expected opening parenthesis for arguments list");const X=ie();return n(Z.CloseParen,"Expected closing parenthesis for arguments list"),X}function ie(){const X=[];for(;!i(Z.CloseParen);){let U=C();if(i(Z.Equals)){if(++r,!(U instanceof yn))throw new SyntaxError("Expected identifier for keyword argument");const ne=C();U=new Lv(U,ne)}X.push(U),i(Z.Comma)&&++r}return X}function pe(){const X=[];let U=!1;for(;!i(Z.CloseSquareBracket);)i(Z.Colon)?(X.push(void 0),++r,U=!0):(X.push(C()),i(Z.Colon)&&(++r,U=!0));if(X.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(U){if(X.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Nv(...X)}return X[0]}function ce(){let X=ge();for(;i(Z.Dot)||i(Z.OpenSquareBracket);){const U=t[r];++r;let ne;const ee=U.type!==Z.Dot;if(ee)ne=pe(),n(Z.CloseSquareBracket,"Expected closing square bracket");else if(ne=ge(),ne.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");X=new Mv(X,ne,ee)}return X}function Se(){let X=fe();for(;i(Z.MultiplicativeBinaryOperator);){const U=t[r];++r;const ne=fe();X=new ri(U,X,ne)}return X}function fe(){let X=me();for(;i(Z.Is);){++r;const U=i(Z.Not);U&&++r;let ne=ge();if(ne instanceof am&&(ne=new yn(ne.value.toString())),!(ne instanceof yn))throw new SyntaxError("Expected identifier for the test");X=new Bv(X,U,ne)}return X}function me(){let X=L();for(;i(Z.Pipe);){++r;let U=ge();if(!(U instanceof yn))throw new SyntaxError("Expected identifier for the filter");i(Z.OpenParen)&&(U=Y(U)),X=new Rv(X,U)}return X}function ge(){const X=t[r];switch(X.type){case Z.NumericLiteral:return++r,new zv(Number(X.value));case Z.StringLiteral:return++r,new im(X.value);case Z.BooleanLiteral:return++r,new am(X.value==="true");case Z.Identifier:return++r,new yn(X.value);case Z.OpenParen:{++r;const U=v();if(t[r].type!==Z.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,U}case Z.OpenSquareBracket:{++r;const U=[];for(;!i(Z.CloseSquareBracket);)U.push(C()),i(Z.Comma)&&++r;return++r,new Pv(U)}case Z.OpenCurlyBracket:{++r;const U=new Map;for(;!i(Z.CloseCurlyBracket);){const ne=C();n(Z.Colon,"Expected colon between key and value in object literal");const ee=C();U.set(ne,ee),i(Z.Comma)&&++r}return++r,new jv(U)}default:throw new SyntaxError(`Unexpected token: ${X.type}`)}}for(;r=0?(e=(e??(e=0))<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??(r=t.length))<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??(e=t.length-1))<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??(r=-1))<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const o=[];for(let i=e;a*ie.toUpperCase())}var wr=class{constructor(t=void 0){te(this,"type","RuntimeValue");te(this,"value");te(this,"builtins",new Map);this.value=t}__bool__(){return new at(!!this.value)}},Je=class extends wr{constructor(){super(...arguments);te(this,"type","NumericValue")}},Ue=class extends wr{constructor(){super(...arguments);te(this,"type","StringValue");te(this,"builtins",new Map([["upper",new vr(()=>new Ue(this.value.toUpperCase()))],["lower",new vr(()=>new Ue(this.value.toLowerCase()))],["strip",new vr(()=>new Ue(this.value.trim()))],["title",new vr(()=>new Ue(lm(this.value)))],["length",new Je(this.value.length)]]))}},at=class extends wr{constructor(){super(...arguments);te(this,"type","BooleanValue")}},rr=class extends wr{constructor(){super(...arguments);te(this,"type","ObjectValue");te(this,"builtins",new Map([["get",new vr(([e,r])=>{if(!(e instanceof Ue))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??r??new ni})],["items",new vr(()=>new tt(Array.from(this.value.entries()).map(([e,r])=>new tt([new Ue(e),r]))))]]))}__bool__(){return new at(this.value.size>0)}},tt=class extends wr{constructor(){super(...arguments);te(this,"type","ArrayValue");te(this,"builtins",new Map([["length",new Je(this.value.length)]]))}__bool__(){return new at(this.value.length>0)}},Wv=class extends tt{constructor(){super(...arguments);te(this,"type","TupleValue")}},vr=class extends wr{constructor(){super(...arguments);te(this,"type","FunctionValue")}},ni=class extends wr{constructor(){super(...arguments);te(this,"type","NullValue")}},nr=class extends wr{constructor(){super(...arguments);te(this,"type","UndefinedValue")}},Ho=class{constructor(t){te(this,"variables",new Map([["namespace",new vr(t=>{if(t.length===0)return new rr(new Map);if(t.length!==1||!(t[0]instanceof rr))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]));te(this,"tests",new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof vr],["odd",t=>{if(t.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!==0}],["even",t=>{if(t.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["number",t=>t.type==="NumericValue"],["integer",t=>t.type==="NumericValue"&&Number.isInteger(t.value)],["iterable",t=>t instanceof tt||t instanceof Ue],["lower",t=>{const e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value]]));this.parent=t}set(t,e){return this.declareVariable(t,za(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new nr}catch{return new nr}}},Gv=class{constructor(t){te(this,"global");this.global=t??new Ho}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new at(r.value==n.value);case"!=":return new at(r.value!=n.value)}if(r instanceof nr||n instanceof nr)throw new Error("Cannot perform operation on undefined values");if(r instanceof ni||n instanceof ni)throw new Error("Cannot perform operation on null values");if(r instanceof Je&&n instanceof Je)switch(t.operator.value){case"+":return new Je(r.value+n.value);case"-":return new Je(r.value-n.value);case"*":return new Je(r.value*n.value);case"/":return new Je(r.value/n.value);case"%":return new Je(r.value%n.value);case"<":return new at(r.value":return new at(r.value>n.value);case">=":return new at(r.value>=n.value);case"<=":return new at(r.value<=n.value)}else if(r instanceof tt&&n instanceof tt)switch(t.operator.value){case"+":return new tt(r.value.concat(n.value))}else if(n instanceof tt){const a=n.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new at(a);case"not in":return new at(!a)}}if(r instanceof Ue||n instanceof Ue)switch(t.operator.value){case"+":return new Ue(r.value.toString()+n.value.toString())}if(r instanceof Ue&&n instanceof Ue)switch(t.operator.value){case"in":return new at(n.value.includes(r.value));case"not in":return new at(!n.value.includes(r.value))}if(r instanceof Ue&&n instanceof rr)switch(t.operator.value){case"in":return new at(n.value.has(r.value));case"not in":return new at(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if(t.filter.type==="Identifier"){const n=t.filter;if(r instanceof tt)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new Je(r.value.length);case"reverse":return new tt(r.value.reverse());case"sort":return new tt(r.value.sort((a,o)=>{if(a.type!==o.type)throw new Error(`Cannot compare different types: ${a.type} and ${o.type}`);switch(a.type){case"NumericValue":return a.value-o.value;case"StringValue":return a.value.localeCompare(o.value);default:throw new Error(`Cannot compare type: ${a.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof Ue)switch(n.value){case"length":return new Je(r.value.length);case"upper":return new Ue(r.value.toUpperCase());case"lower":return new Ue(r.value.toLowerCase());case"title":return new Ue(lm(r.value));case"capitalize":return new Ue(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new Ue(r.value.trim());default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(r instanceof Je)switch(n.value){case"abs":return new Je(Math.abs(r.value));default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(r instanceof rr)switch(n.value){case"items":return new tt(Array.from(r.value.entries()).map(([a,o])=>new tt([new Ue(a),o])));case"length":return new Je(r.value.size);default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}throw new Error(`Cannot apply filter "${n.value}" to type: ${r.type}`)}else if(t.filter.type==="CallExpression"){const n=t.filter;if(n.callee.type!=="Identifier")throw new Error(`Unknown filter: ${n.callee.type}`);const a=n.callee.value;if(r instanceof tt){switch(a){case"selectattr":{if(r.value.some(c=>!(c instanceof rr)))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some(c=>c.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[o,i,d]=n.args.map(c=>this.evaluate(c,e));let h;if(i){const c=e.tests.get(i.value);if(!c)throw new Error(`Unknown test: ${i.value}`);h=c}else h=(...c)=>c[0].__bool__().value;const m=r.value.filter(c=>{const _=c.value.get(o.value);return _?h(_,d):!1});return new tt(m)}}throw new Error(`Unknown ArrayValue filter: ${a}`)}else throw new Error(`Cannot apply filter "${a}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const a=n(r);return new at(t.negate?!a:a)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);switch(t.operator.value){case"not":return new at(!r.value);default:throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const a=this.evaluate(n,e);a.type!=="NullValue"&&a.type!=="UndefinedValue"&&(r+=a.value)}return new Ue(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const r=[],n=new Map;for(const o of t.args)if(o.type==="KeywordArgumentExpression"){const i=o;n.set(i.key.value,this.evaluate(i.value,e))}else r.push(this.evaluate(o,e));n.size>0&&r.push(new rr(n));const a=this.evaluate(t.callee,e);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);return a.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof tt||t instanceof Ue))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),a=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(n instanceof Je||n instanceof nr))throw new Error("Slice start must be numeric or undefined");if(!(a instanceof Je||a instanceof nr))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof Je||o instanceof nr))throw new Error("Slice step must be numeric or undefined");return t instanceof tt?new tt(om(t.value,n.value,a.value,o.value)):new Ue(om(Array.from(t.value),n.value,a.value,o.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new Ue(t.property.value);let a;if(r instanceof rr){if(!(n instanceof Ue))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof tt||r instanceof Ue)if(n instanceof Je)a=r.value.at(n.value),r instanceof Ue&&(a=new Ue(r.value.at(n.value)));else if(n instanceof Ue)a=r.builtins.get(n.value);else throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof Ue))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=r.builtins.get(n.value)}return a instanceof wr?a:new nr}evaluateSet(t,e){const r=this.evaluate(t.value,e);if(t.assignee.type==="Identifier"){const n=t.assignee.value;e.setVariable(n,r)}else if(t.assignee.type==="MemberExpression"){const n=t.assignee,a=this.evaluate(n.object,e);if(!(a instanceof rr))throw new Error("Cannot assign to member of non-object");if(n.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");a.value.set(n.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new ni}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new Ho(e),n=this.evaluate(t.iterable,r);if(!(n instanceof tt))throw new Error(`Expected iterable type in for loop: got ${n.type}`);let a="";for(let o=0;o0?n.value[o-1]:new nr],["nextitem",oc.value.length?"few":"many"} items to unpack`);for(let _=0;_this.evaluate(r,e)));case"TupleLiteral":return new Wv(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{const r=new Map;for(const[n,a]of t.value){const o=this.evaluate(n,e);if(!(o instanceof Ue))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(a,e))}return new rr(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function za(t){switch(typeof t){case"number":return new Je(t);case"string":return new Ue(t);case"boolean":return new at(t);case"object":return t===null?new ni:Array.isArray(t)?new tt(t.map(za)):new rr(new Map(Object.entries(t).map(([e,r])=>[e,za(r)])));case"function":return new vr((e,r)=>{const n=t(...e.map(a=>a.value))??null;return za(n)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var Vv=class{constructor(t){te(this,"parsed");const e=kv(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Uv(e)}render(t){const e=new Ho;e.set("false",!1),e.set("true",!0),e.set("raise_exception",a=>{throw new Error(a)}),e.set("range",Fv);for(const[a,o]of Object.entries(t))e.set(a,o);return new Gv(e).run(this.parsed).value}};async function um(t,e){const r=await Promise.all([Br(t,"tokenizer.json",!0,e),Br(t,"tokenizer_config.json",!0,e)]);return e.legacy!==null&&(r[1].legacy=e.legacy),r}function Hv(t,e){const r=[];let n=0;for(const a of t.matchAll(e)){const o=a[0];n0&&r.push(o),n=a.index+o.length}return n=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103}function Kv(t,e,r){const n=[];let a=0;for(;athis.tokens_to_ids.get(r)??this.unk_token_id)}convert_ids_to_tokens(e){return e.map(r=>this.vocab[r]??this.unk_token)}}class Zv extends ai{constructor(e){super(e),this.tokens_to_ids=qo(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r}encode(e){const r=[];for(const n of e){const a=[...n];if(a.length>this.max_input_chars_per_word){r.push(this.unk_token);continue}let o=!1,i=0;const d=[];for(;i0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){m=c;break}--h}if(m===null){o=!0;break}d.push(m),i=h}o?r.push(this.unk_token):r.push(...d)}return r}}class Jv extends ai{constructor(e,r){super(e);const n=e.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let a=0;a[a,o])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=r.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=T0(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new $v,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const r=e.sentence,n=r.length;let a=0;for(;a{const t=[...Array.from({length:94},(a,o)=>o+33),...Array.from({length:12},(a,o)=>o+161),...Array.from({length:82},(a,o)=>o+174)],e=t.slice();let r=0;for(let a=0;a<256;++a)t.includes(a)||(t.push(a),e.push(256+r),r+=1);const n=e.map(a=>String.fromCharCode(a));return Object.fromEntries(t.map((a,o)=>[a,n[o]]))})(),eb=b0(hm);class tb extends ai{constructor(e){super(e),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=qo(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r;this.bpe_ranks=new Map(e.merges.map((r,n)=>[r,n])),this.merges=e.merges.map(r=>r.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(e){if(e.length===0)return[];const r=this.cache.get(e);if(r!==void 0)return r;const n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let a=[];if(n.length>1){const o=new bv((h,m)=>h.score`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`)):r.push(this.unk_token)}return r}}class rb extends ai{constructor(e,r){super(e),this.tokens_to_ids=qo(r.target_lang?e.vocab[r.target_lang]:e.vocab),this.bos_token=r.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=r.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=r.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=r.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[n,a]of this.tokens_to_ids)this.vocab[a]=n}encode(e){return e}}class zt extends Ot{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new pb(e);case"Precompiled":return new Mb(e);case"Sequence":return new cb(e);case"Replace":return new nb(e);case"NFC":return new ib(e);case"NFKC":return new ab(e);case"NFKD":return new sb(e);case"Strip":return new ob(e);case"StripAccents":return new lb(e);case"Lowercase":return new ub(e);case"Prepend":return new db(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class nb extends zt{normalize(e){const r=Pa(this.config.pattern);return r===null?e:e.replaceAll(r,this.config.content)}}class ib extends zt{normalize(e){return e=e.normalize("NFC"),e}}class ab extends zt{normalize(e){return e=e.normalize("NFKC"),e}}class sb extends zt{normalize(e){return e=e.normalize("NFKD"),e}}class ob extends zt{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class lb extends zt{normalize(e){return e=cm(e),e}}class ub extends zt{normalize(e){return e=e.toLowerCase(),e}}class db extends zt{normalize(e){return e=this.config.prepend+e,e}}class cb extends zt{constructor(e){super(e),this.normalizers=e.normalizers.map(r=>zt.fromConfig(r))}normalize(e){return this.normalizers.reduce((r,n)=>n.normalize(r),e)}}class pb extends zt{_tokenize_chinese_chars(e){const r=[];for(let n=0;nthis.pre_tokenize_text(n,r)):this.pre_tokenize_text(e,r)).flat()}_call(e,r){return this.pre_tokenize(e,r)}}class hb extends Ft{constructor(e){super(),this.pattern=new RegExp(`[^\\s${ii}]+|[${ii}]`,"gu")}pre_tokenize_text(e,r){return e.trim().match(this.pattern)||[]}}class fb extends Ft{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=hm,this.text_encoder=new TextEncoder}pre_tokenize_text(e,r){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(a=>Array.from(this.text_encoder.encode(a),o=>this.byte_encoder[o]).join(""))}}class mb extends Ft{constructor(e){super(),this.config=e,this.pattern=Pa(this.config.pattern,this.config.invert)}pre_tokenize_text(e,r){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:Hv(e,this.pattern)}}class gb extends Ft{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${ii}]+|[${ii}]+`,"gu")}pre_tokenize_text(e,r){return e.match(this.pattern)||[]}}class yb extends Ft{constructor(e){super(),this.config=e;const r=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(r,"gu")}pre_tokenize_text(e,r){return e.match(this.pattern)||[]}}class ja extends Ot{constructor(e){super(),this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new _b(e);case"ByteLevel":return new wb(e);case"RobertaProcessing":return new mm(e);case"BertProcessing":return new fm(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...r){throw Error("post_process should be implemented in subclass.")}_call(e,...r){return this.post_process(e,...r)}}class fm extends ja{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,r=null,{add_special_tokens:n=!0}={}){n&&(e=ht([this.cls],e,[this.sep]));let a=new Array(e.length).fill(0);if(r!==null){const o=n&&this instanceof mm?[this.sep]:[],i=n?[this.sep]:[];e=ht(e,o,r,i),a=ht(a,new Array(r.length+o.length+i.length).fill(1))}return{tokens:e,token_type_ids:a}}}class mm extends fm{}class _b extends ja{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,r=null,{add_special_tokens:n=!0}={}){const a=r===null?this.single:this.pair;let o=[],i=[];for(const d of a)"SpecialToken"in d?n&&(o.push(d.SpecialToken.id),i.push(d.SpecialToken.type_id)):"Sequence"in d&&(d.Sequence.id==="A"?(o=ht(o,e),i=ht(i,new Array(e.length).fill(d.Sequence.type_id))):d.Sequence.id==="B"&&(o=ht(o,r),i=ht(i,new Array(r.length).fill(d.Sequence.type_id))));return{tokens:o,token_type_ids:i}}}class wb extends ja{post_process(e,r=null){return r&&(e=ht(e,r)),{tokens:e}}}class Pt extends Ot{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(e===null)return null;switch(e.type){case"WordPiece":return new Cb(e);case"Metaspace":return new Ab(e);case"ByteLevel":return new Sb(e);case"Replace":return new vb(e);case"ByteFallback":return new bb(e);case"Fuse":return new $b(e);case"Strip":return new xb(e);case"Sequence":return new kb(e);case"CTC":return new Eb(e);case"BPEDecoder":return new Tb(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class vb extends Pt{decode_chain(e){const r=Pa(this.config.pattern);return r===null?e:e.map(n=>n.replaceAll(r,this.config.content))}}class bb extends Pt{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const r=[];let n=[];for(const a of e){let o=null;if(a.length===6&&a.startsWith("<0x")&&a.endsWith(">")){const i=parseInt(a.slice(3,5),16);isNaN(i)||(o=i)}if(o!==null)n.push(o);else{if(n.length>0){const i=this.text_decoder.decode(Uint8Array.from(n));r.push(i),n=[]}r.push(a)}}if(n.length>0){const a=this.text_decoder.decode(Uint8Array.from(n));r.push(a),n=[]}return r}}class $b extends Pt{decode_chain(e){return[e.join("")]}}class xb extends Pt{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map(r=>{let n=0;for(let o=0;o(n!==0&&(r.startsWith(this.config.prefix)?r=r.replace(this.config.prefix,""):r=" "+r),this.cleanup&&(r=Ko(r)),r))}}class Sb extends Pt{constructor(e){super(e),this.byte_decoder=eb,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const r=e.join(""),n=new Uint8Array([...r].map(o=>this.byte_decoder[o]));return this.text_decoder.decode(n)}decode_chain(e){const r=[];let n=[];for(const a of e)this.added_tokens.find(o=>o.content===a)!==void 0?(n.length>0&&(r.push(this.convert_tokens_to_string(n)),n=[]),r.push(a)):n.push(a);return n.length>0&&r.push(this.convert_tokens_to_string(n)),r}}class Eb extends Pt{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const r=[e[0]];for(let o=1;oo!==this.pad_token).join("");return this.cleanup&&(a=Ko(a).replaceAll(this.word_delimiter_token," ").trim()),a}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class kb extends Pt{constructor(e){super(e),this.decoders=e.decoders.map(r=>Pt.fromConfig(r))}decode_chain(e){return this.decoders.reduce((r,n)=>n.decode_chain(r),e)}}class Tb extends Pt{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map((r,n)=>r.replaceAll(this.suffix,n===e.length-1?"":" "))}}class Ib extends Pt{decode_chain(e){let r="";for(let n=1;nn.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}}class Ob extends Ft{constructor(e){super(),this.tokenizers=e.pretokenizers.map(r=>Ft.fromConfig(r))}pre_tokenize_text(e,r){return this.tokenizers.reduce((n,a)=>a.pre_tokenize(n,r),[e])}}class zb extends Ft{constructor(e){super()}pre_tokenize_text(e,r){return e.match(/\w+|[^\w\s]+/g)||[]}}class Pb extends Ft{constructor(e){super()}pre_tokenize_text(e,r){return Yv(e)}}class jb extends Ft{constructor(e){super(),this.config=e,this.pattern=Pa(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,r){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const Rb=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Bb(t,e,r,n){for(const a of Object.keys(t)){const o=e-t[a].length,i=r(a),d=new Array(o).fill(i);t[a]=n==="right"?ht(t[a],d):ht(d,t[a])}}function Db(t,e){for(const r of Object.keys(t))t[r].length=e}class Pe extends Ot{constructor(r,n){super();te(this,"return_token_type_ids",!1);te(this,"_default_chat_template",`{% for message in messages %}{{'<|im_start|>' + message['role'] + ' ' + message['content'] + '<|im_end|>' + ' '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant ' }}{% endif %}`);te(this,"padding_side","right");this._tokenizer_config=n,this.normalizer=zt.fromConfig(r.normalizer),this.pre_tokenizer=Ft.fromConfig(r.pre_tokenizer),this.model=ai.fromConfig(r.model,n),this.post_processor=ja.fromConfig(r.post_processor),this.decoder=Pt.fromConfig(r.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const a of r.added_tokens){const o=new Xv(a);this.added_tokens.push(o),this.model.tokens_to_ids.set(o.content,o.id),this.model.vocab[o.id]=o.content,o.special&&(this.special_tokens.push(o.content),this.all_special_ids.push(o.id))}if(this.additional_special_tokens=n.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.map(a=>`${a.lstrip?"\\s*":""}(${_l(a.content)})${a.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=n.model_max_length,this.remove_space=n.remove_space,this.clean_up_tokenization_spaces=n.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=n.do_lowercase_and_remove_accent??!1,n.padding_side&&(this.padding_side=n.padding_side),this.legacy=!1,this.chat_template=n.chat_template??null,Array.isArray(this.chat_template)){const a=Object.create(null);for(const{name:o,template:i}of this.chat_template){if(typeof o!="string"||typeof i!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');a[o]=i}this.chat_template=a}this._compiled_template_cache=new Map}getToken(...r){for(const n of r){const a=this._tokenizer_config[n];if(a)if(typeof a=="object"){if(a.__type==="AddedToken")return a.content;throw Error(`Unknown token: ${a}`)}else return a}return null}static async from_pretrained(r,{progress_callback:n=null,config:a=null,cache_dir:o=null,local_files_only:i=!1,revision:d="main",legacy:h=null}={}){const m=await um(r,{progress_callback:n,config:a,cache_dir:o,local_files_only:i,revision:d,legacy:h});return new this(...m)}_call(r,{text_pair:n=null,add_special_tokens:a=!0,padding:o=!1,truncation:i=null,max_length:d=null,return_tensor:h=!0}={}){const m=Array.isArray(r);let c;if(m){if(r.length===0)throw Error("text array must be non-empty");if(n!==null){if(Array.isArray(n)){if(r.length!==n.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");c=r.map((v,$)=>this._encode_plus(v,{text_pair:n[$],add_special_tokens:a}))}else c=r.map(v=>this._encode_plus(v,{add_special_tokens:a}))}else{if(r==null)throw Error("text may not be null or undefined");if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");c=[this._encode_plus(r,{text_pair:n,add_special_tokens:a})]}if(d===null?o==="max_length"?d=this.model_max_length:d=Cs(c.map(v=>v.input_ids.length))[0]:i||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),d=Math.min(d,this.model_max_length),o||i)for(let v=0;vd?i&&Db(c[v],d):o&&Bb(c[v],d,$=>$==="input_ids"?this.pad_token_id:0,this.padding_side));const _={};if(h){if(!(o&&i)&&c.some($=>{var C;for(const k of Object.keys($))if($[k].length!==((C=c[0][k])==null?void 0:C.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const v=[c.length,c[0].input_ids.length];for(const $ of Object.keys(c[0]))_[$]=new je("int64",BigInt64Array.from(c.flatMap(C=>C[$]).map(BigInt)),v)}else{for(const v of Object.keys(c[0]))_[v]=c.map($=>$[v]);if(!m)for(const v of Object.keys(_))_[v]=_[v][0]}return _}_encode_text(r){return r===null?null:(this.added_tokens_regex?r.split(this.added_tokens_regex).filter(o=>o):[r]).map((o,i)=>{if(this.added_tokens.find(h=>h.content===o)!==void 0)return o;{if(this.remove_space===!0&&(o=o.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(o=qv(o)),this.normalizer!==null&&(o=this.normalizer(o)),o.length===0)return[];const h=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:i}):[o];return this.model(h)}}).flat()}_encode_plus(r,{text_pair:n=null,add_special_tokens:a=!0}={}){const{tokens:o,token_type_ids:i}=this._tokenize_helper(r,{pair:n,add_special_tokens:a}),d=this.model.convert_tokens_to_ids(o),h={input_ids:d,attention_mask:new Array(d.length).fill(1)};return this.return_token_type_ids&&i&&(h.token_type_ids=i),h}_tokenize_helper(r,{pair:n=null,add_special_tokens:a=!1}={}){const o=this._encode_text(r),i=this._encode_text(n);return this.post_processor?this.post_processor(o,i,{add_special_tokens:a}):{tokens:ht(o??[],i??[])}}tokenize(r,{pair:n=null,add_special_tokens:a=!1}={}){return this._tokenize_helper(r,{pair:n,add_special_tokens:a}).tokens}encode(r,{text_pair:n=null,add_special_tokens:a=!0}={}){return this._encode_plus(r,{text_pair:n,add_special_tokens:a}).input_ids}batch_decode(r,n={}){return r instanceof je&&(r=r.tolist()),r.map(a=>this.decode(a,n))}decode(r,n={}){if(r instanceof je&&(r=dm(r)),!Array.isArray(r)||r.length===0||!$0(r[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(r,n)}decode_single(r,{skip_special_tokens:n=!1,clean_up_tokenization_spaces:a=null}){let o=this.model.convert_ids_to_tokens(r);n&&(o=o.filter(d=>!this.special_tokens.includes(d)));let i=this.decoder?this.decoder(o):o.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(i=i.replaceAll(this.decoder.end_of_word_suffix," "),n&&(i=i.trim())),(a??this.clean_up_tokenization_spaces)&&(i=Ko(i)),i}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(r,{chat_template:n=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:i=!1,truncation:d=!1,max_length:h=null,return_tensor:m=!0,return_dict:c=!1,tokenizer_kwargs:_={},...v}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null&&this.default_chat_template&&typeof this.default_chat_template=="object"){const M=this.chat_template??this.default_chat_template;if(n!==null&&Object.hasOwn(M,n))n=M[n];else if(n===null&&"default"in M)n=M.default;else if(n===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(M).sort()}.`)}else n??(n=this.chat_template??this.default_chat_template);if(typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let $=this._compiled_template_cache.get(n);$===void 0&&($=new Vv(n),this._compiled_template_cache.set(n,$));const C=Object.create(null);for(const M of Rb){const z=this.getToken(M);z&&(C[M]=z)}const k=$.render({messages:r,add_generation_prompt:a,...C,...v});if(o){const M=this._call(k,{add_special_tokens:!1,padding:i,truncation:d,max_length:h,return_tensor:m,..._});return c?M:M.input_ids}return k}}class Nb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Lb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ub extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Fb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Wb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Gb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Vb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Hb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class qb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Kb extends Pe{}class Yb extends Pe{}class Qb extends Pe{constructor(r,n){super(r,n);te(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Xb extends Pe{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Zb extends Pe{}class ym extends Pe{constructor(){super(...arguments);te(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}}class Jb extends Pe{}class _m extends Pe{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)),this.lang_to_token=n=>n}_build_translation_inputs(e,r,n){return Yo(this,e,r,n)}}class e1 extends _m{}class t1 extends Pe{}class r1 extends ym{constructor(e,r){var o,i;const n=".,!?…。,、।۔،",a=(i=(o=e.pre_tokenizer)==null?void 0:o.pretokenizers[0])==null?void 0:i.pattern;a&&a.Regex===` ?[^(\\s|[${n}])]+`&&(a.Regex=` ?[^\\s${n}]+`),super(e,r)}}const Ra="▁";class wm extends Pe{constructor(r,n){super(r,n);te(this,"_default_chat_template",`{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> ' + system_message + ' <> ' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> ' + content.strip() + ' <> ' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`);te(this,"DEFAULT_SYSTEM_PROMPT",`You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.`);te(this,"padding_side","left");this.use_default_system_prompt=n.use_default_system_prompt??!1,this.legacy=n.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gm({replacement:Ra,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(r){if(r===null)return null;if(this.legacy||r.length===0)return super._encode_text(r);let n=super._encode_text(Ra+r.replaceAll(Ra," "));return n.length>1&&n[0]===Ra&&this.special_tokens.includes(n[1])&&(n=n.slice(1)),n}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll(` `,"\\n").replaceAll("'","\\'"))}}class n1 extends wm{}class i1 extends Pe{}class a1 extends Pe{}class s1 extends Pe{}class o1 extends Pe{}class l1 extends Pe{}class u1 extends Pe{}class d1 extends Pe{constructor(){super(...arguments);te(this,"_default_chat_template",`{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + ' ' + message['content'] | trim + ' ' }}{% endfor %}{% if add_generation_prompt %}{{'model '}}{% endif %}`)}}class c1 extends Pe{}function Yo(t,e,r,n){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const a=n.src_lang,o=n.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(a!==void 0){if(!t.language_codes.includes(a))throw new Error(`Source language code "${a}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(const i of t.post_processor.config.single)if("SpecialToken"in i&&t.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=t.lang_to_token(a);break}}return n.forced_bos_token_id=t.model.convert_tokens_to_ids([t.lang_to_token(o)])[0],t._call(e,r)}class p1 extends Pe{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)),this.lang_to_token=n=>n}_build_translation_inputs(e,r,n){return Yo(this,e,r,n)}}class h1 extends Pe{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(n=>this.languageRegex.test(n)).map(n=>n.slice(2,-2)),this.lang_to_token=n=>`__${n}__`}_build_translation_inputs(e,r,n){return Yo(this,e,r,n)}}const vm=[["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"]],Ba=new Map(vm),f1=new Map([...vm.map(([t,e])=>[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class m1 extends Pe{constructor(){super(...arguments);te(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}_decode_asr(r,{return_timestamps:n=!1,return_language:a=!1,time_precision:o=null,force_full_sequences:i=!0}={}){if(o===null)throw Error("Must specify time_precision");let d=null;const h=n==="word";function m(){return{language:d,timestamp:[null,null],text:""}}const c=[];let _=m(),v=0;const $=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let C=[],k=[],M=!1,z=null;const I=new Set(this.all_special_ids);for(const L of r){const Y=L.tokens,Q=h?L.token_timestamps:null;let ie=null,pe=$;if("stride"in L){const[fe,me,ge]=L.stride;if(v-=me,z=fe-ge,me&&(pe=me/o+$),ge)for(let X=Y.length-1;X>=0;--X){const U=Y[X];if(U>=$){if(ie!==null&&(U-$)*o=$){const ge=(me-$)*o+v,X=ia(ge,2);if(ie!==null&&me>=ie)M=!0;else if(M||C.length>0&&me0?(C.push(ce),h&&k.push(Se)):C.every(fe=>fe.length===0)&&(_=m(),C=[],ce=[],k=[],Se=[])}if(C.length>0){if(i&&n)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[L,Y]=this.findLongestCommonSequence(C,k),Q=this.decode(L);_.text=Q,h&&(_.words=this.collateWordTimestamps(L,Y,d)),c.push(_)}let j=Object.create(null);const R=c.map(L=>L.text).join("");if(n||a){for(let L=0;L0;let h=d?[]:null,m=d?n[0]:null;for(let c=1;cX===fe[U]).length,ge=me/L+Y;me>1&&ge>v&&(v=ge,$=[Q,ie,ce,Se])}const[k,M,z,I]=$,j=Math.floor((M+k)/2),R=Math.floor((I+z)/2);i.push(...a.slice(0,j)),a=_.slice(R),o=a.length,d&&(h.push(...m.slice(0,j)),m=n[c].slice(R))}return i.push(...a),d?(h.push(...m),[i,h]):[i,[]]}collateWordTimestamps(r,n,a){const[o,i,d]=this.combineTokensIntoWords(r,a),h=[];for(let m=0;m=o){const h=ia((Number(d)-o)*a,2);i.push(`<|${h}|>`),i.push([])}else i[i.length-1].push(d);return i=i.map(d=>typeof d=="string"?d:super.decode(d,n)),i.join("")}splitTokensOnUnicode(r){const n=this.decode(r,{decode_with_timestamps:!0}),a="�",o=[],i=[],d=[];let h=[],m=[],c=0;for(let _=0;_=this.model.tokens_to_ids.get("<|endoftext|>"),k=_.startsWith(" "),M=_.trim(),z=m.test(M);if(C||k||z||i.length===0)i.push(_),d.push(v),h.push($);else{const I=i.length-1;i[I]+=_,d[I].push(...v),h[I].push(...$)}}return[i,d,h]}mergePunctuations(r,n,a,o,i){const d=structuredClone(r),h=structuredClone(n),m=structuredClone(a);let c=d.length-2,_=d.length-1;for(;c>=0;)d[c].startsWith(" ")&&o.includes(d[c].trim())?(d[_]=d[c]+d[_],h[_]=ht(h[c],h[_]),m[_]=ht(m[c],m[_]),d[c]="",h[c]=[],m[c]=[]):_=c,--c;for(c=0,_=1;_v),h.filter(v=>v.length>0),m.filter(v=>v.length>0)]}get_decoder_prompt_ids({language:r=null,task:n=null,no_timestamps:a=!0}={}){const o=[];if(r){r=r.toLowerCase();let i=f1.get(r);if(i===void 0)if(Ba.has(r))i=r;else{const m=r.length===2?Ba.keys():Ba.values();throw new Error(`Language "${r}" is not supported. Must be one of: ${JSON.stringify(m)}`)}const d=this.model.tokens_to_ids.get(`<|${i}|>`);if(d===void 0)throw new Error(`Unable to find language "${i}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);o.push(d)}else o.push(null);if(n){if(n=n.toLowerCase(),n!=="transcribe"&&n!=="translate")throw new Error(`Task "${n}" is not supported. Must be one of: ["transcribe", "translate"]`);const i=this.model.tokens_to_ids.get(`<|${n}|>`);if(i===void 0)throw new Error(`Unable to find task "${n}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);o.push(i)}else o.push(null);if(a){const i=this.model.tokens_to_ids.get("<|notimestamps|>");if(i===void 0)throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');o.push(i)}return o.map((i,d)=>[d+1,i]).filter(i=>i[1]!==null)}}class g1 extends Pe{}class y1 extends Pe{}class _1 extends Pe{}class w1 extends Pe{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(n=>this.languageRegex.test(n)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[r,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(r);if(n.length===2){const[a,o]=n;return this.supported_language_codes.includes(a)||console.warn(`Unsupported language code "${a}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),ht([a],super._encode_text(o))}}}class v1 extends Pe{}class bm extends Pe{constructor(){super(...arguments);te(this,"_default_chat_template","{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}")}}class b1 extends bm{}class $1 extends Pe{}class x1 extends Pe{}class C1 extends Pe{constructor(e,r){super(e,r),this.decoder=new Ib({})}}class S1 extends Pe{}class $m{static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:o=!1,revision:i="main",legacy:d=null}={}){var v;const[h,m]=await um(e,{progress_callback:r,config:n,cache_dir:a,local_files_only:o,revision:i,legacy:d}),c=((v=m.tokenizer_class)==null?void 0:v.replace(/Fast$/,""))??"PreTrainedTokenizer";let _=this.TOKENIZER_CLASS_MAPPING[c];return _||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),_=Pe),new _(h,m)}}te($m,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Zb,DistilBertTokenizer:Kb,CamembertTokenizer:Yb,DebertaTokenizer:Wb,DebertaV2Tokenizer:Gb,BertTokenizer:Nb,HerbertTokenizer:Vb,ConvBertTokenizer:Hb,RoFormerTokenizer:qb,XLMTokenizer:Qb,ElectraTokenizer:Xb,MobileBertTokenizer:Ub,SqueezeBertTokenizer:Fb,AlbertTokenizer:Lb,GPT2Tokenizer:ym,BartTokenizer:Jb,MBartTokenizer:_m,MBart50Tokenizer:e1,RobertaTokenizer:t1,WhisperTokenizer:m1,CodeGenTokenizer:g1,CLIPTokenizer:y1,SiglipTokenizer:_1,MarianTokenizer:w1,BloomTokenizer:r1,NllbTokenizer:p1,M2M100Tokenizer:h1,LlamaTokenizer:wm,CodeLlamaTokenizer:n1,XLMRobertaTokenizer:i1,MPNetTokenizer:a1,FalconTokenizer:s1,GPTNeoXTokenizer:o1,EsmTokenizer:l1,Wav2Vec2CTCTokenizer:v1,BlenderbotTokenizer:bm,BlenderbotSmallTokenizer:b1,SpeechT5Tokenizer:$1,NougatTokenizer:x1,VitsTokenizer:C1,Qwen2Tokenizer:u1,GemmaTokenizer:d1,Grok1Tokenizer:c1,CohereTokenizer:S1,PreTrainedTokenizer:Pe});async function E1(t,e){return await Br(t,"config.json",!0,e)}function Qo(t){const e={};let r={};switch(t.model_type){case"llava":r=Qo(t.text_config);break;case"musicgen":r=Qo(t.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":e.num_heads="num_attention_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size";break;case"llama":case"mistral":case"starcoder2":case"qwen2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size",e.num_attention_heads="num_attention_heads";break;case"openelm":e.num_heads="num_kv_heads",e.num_layers="num_transformer_layers",e.dim_kv="head_dim";break;case"gpt_neo":e.num_heads="num_heads",e.num_layers="num_layers",e.hidden_size="hidden_size";break;case"bloom":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="hidden_size";break;case"mpt":e.num_heads="n_heads",e.num_layers="n_layers",e.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":e.num_decoder_layers="num_decoder_layers",e.num_decoder_heads="num_heads",e.decoder_dim_kv="d_kv",e.num_encoder_layers="num_layers",e.num_encoder_heads="num_heads",e.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="d_model",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="d_model";break;case"speecht5":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="hidden_size",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="hidden_size";break;case"trocr":e.num_encoder_layers=e.num_decoder_layers="decoder_layers",e.num_encoder_heads=e.num_decoder_heads="decoder_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="d_model";break;case"musicgen_decoder":e.num_encoder_layers=e.num_decoder_layers="num_hidden_layers",e.num_encoder_heads=e.num_decoder_heads="num_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break}const n={...r,model_type:t.model_type,multi_query:t.multi_query,is_encoder_decoder:t.is_encoder_decoder};for(const a in e)n[a]=t[e[a]];return n}function xm(t,{prefix:e="past_key_values",encoder_add_pkv:r=!0}={}){const n={},a=t.normalized_config,o=1;if(a.is_encoder_decoder&&r){const i=a.encoder_dim_kv??a.encoder_hidden_size/a.num_encoder_heads,d=a.decoder_dim_kv??a.decoder_hidden_size/a.num_decoder_heads,h=[o,a.num_encoder_heads,0,i],m=[o,a.num_decoder_heads,0,d];for(let c=0;c1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);const n=e.length,a=r.slice([0,n],null),o=r.slice([n,r.dims[0]],null);for(let i=0;i1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(n)||n<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${n}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=n}}class U1 extends Xo{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:n=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,n),this.filter_value=r}}class F1{constructor(e){te(this,"max_length",20);te(this,"max_new_tokens",null);te(this,"min_length",0);te(this,"min_new_tokens",null);te(this,"early_stopping",!1);te(this,"max_time",null);te(this,"do_sample",!1);te(this,"num_beams",1);te(this,"num_beam_groups",1);te(this,"penalty_alpha",null);te(this,"use_cache",!0);te(this,"temperature",1);te(this,"top_k",50);te(this,"top_p",1);te(this,"typical_p",1);te(this,"epsilon_cutoff",0);te(this,"eta_cutoff",0);te(this,"diversity_penalty",0);te(this,"repetition_penalty",1);te(this,"encoder_repetition_penalty",1);te(this,"length_penalty",1);te(this,"no_repeat_ngram_size",0);te(this,"bad_words_ids",null);te(this,"force_words_ids",null);te(this,"renormalize_logits",!1);te(this,"constraints",null);te(this,"forced_bos_token_id",null);te(this,"forced_eos_token_id",null);te(this,"remove_invalid_values",!1);te(this,"exponential_decay_length_penalty",null);te(this,"suppress_tokens",null);te(this,"begin_suppress_tokens",null);te(this,"forced_decoder_ids",null);te(this,"guidance_scale",null);te(this,"num_return_sequences",1);te(this,"output_attentions",!1);te(this,"output_hidden_states",!1);te(this,"output_scores",!1);te(this,"return_dict_in_generate",!1);te(this,"pad_token_id",null);te(this,"bos_token_id",null);te(this,"eos_token_id",null);te(this,"encoder_no_repeat_ngram_size",0);te(this,"decoder_start_token_id",null);te(this,"generation_kwargs",{});Object.assign(this,dn(e,Object.getOwnPropertyNames(this)))}}class Na extends Ot{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}}class Zo extends Ot{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof Zo?e=e.criteria:e instanceof Na&&(e=[e]),this.criteria.push(...e)}_call(e,r){const n=new Array(e.length).fill(!1);for(const a of this.criteria){const o=a(e,r);for(let i=0;ir.length>=this.max_length)}}class G1 extends Na{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(n=>{const a=n.at(-1);return this.eos_token_id.some(o=>a==o)})}}class La extends Ot{constructor(e){super(),this.generation_config=e}_call(e,r=-1){return this.sample(e,r)}sample(e,r){throw Error("sample should be implemented in subclasses.")}getLogits(e,r){let n=e.dims.at(-1),a=e.data;if(r===-1)a=a.slice(-n);else{let o=r*n;a=a.slice(o,o+n)}return a}randomSelect(e){let r=e.reduce((a,o)=>a+o,0),n=Math.random()*r;for(let a=0;a1)return new q1(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 V1(e)}}class V1 extends La{sample(e,r=-1){let n=this.getLogits(e,r);return[[Cs(n)[1],0]]}}class H1 extends La{sample(e,r=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const a=this.getLogits(e,r),o=$l(a,n),i=bl(o.map(d=>d[1]));return Array.from({length:this.generation_config.num_beams},()=>{const d=this.randomSelect(i);return[o[d][0],Math.log(i[d])]})}}class q1 extends La{sample(e,r=-1){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const a=this.getLogits(e,r),o=$l(a,n),i=bl(o.map(d=>d[1]));return Array.from({length:this.generation_config.num_beams},(d,h)=>[o[h][0],Math.log(i[h])])}}const Ae={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},Ua=new Map,km=new Map,si=new Map;async function K1(t,e,r){let n=r.device;n&&typeof n!="string"&&(n.hasOwnProperty(e)?n=n[e]:(console.warn(`Device not specified for ${e}. Using the default device.`),n=null));const a=lv(n);let o=r.dtype;if(typeof o!="string"&&(o&&o.hasOwnProperty(e)?o=o[e]:(o=I1[a[0]],console.warn(`Dtype not specified for ${e}. Using the default dtype: ${o}.`))),Sm.hasOwnProperty(o)){if(o===jt.fp16&&!await T1())throw new Error("The device does not support fp16.")}else throw new Error(`Invalid dtype: ${o}. Should be one of: ${Object.keys(jt).join(", ")}`);const i=Sm[o],d=`${r.subfolder??""}/${e}${i}.onnx`,h={...r.session_options};h.executionProviders??(h.executionProviders=a);const m=ra(t,d,!0,r);let c=[];if(r.use_external_data_format){if(Rr.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const v=`${e}${i}.onnx_data`,$=`${r.subfolder??""}/${v}`;c.push(new Promise(async(C,k)=>{const M=await ra(t,$,!0,r);C({path:v,data:M})}))}else h.externalData!==void 0&&(c=h.externalData.map(async v=>{if(typeof v.data=="string"){const $=await ra(t,v.data,!0,r);return{...v,data:$}}return v}));if(c.length>0&&(h.externalData=await Promise.all(c)),n==="webgpu"){const v=xm(r.config,{prefix:"present"}),$={};for(const C in v)$[C]="gpu-buffer";h.preferredOutputLocation=$}return{buffer:await m,session_options:h}}async function Qr(t,e,r){const n=Object.keys(e),a=await Promise.all(n.map(async i=>K1(t,e[i],r))),o={};for(let i=0;i0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const a=Object.keys(e).length,o=t.inputNames.length;if(a>o){let i=Object.keys(e).filter(d=>!t.inputNames.includes(d));console.warn(`WARNING: Too many inputs were provided (${a} > ${o}). The following inputs will be ignored: "${i.join(", ")}".`)}return r}async function Mr(t,e){const r=Y1(t,e);try{const n=Object.fromEntries(Object.entries(r).map(([o,i])=>[o,i.ort_tensor]));let a=await t.run(n);return a=Tm(a),a}catch(n){throw console.error(`An error occurred during model execution: "${n}".`),console.error("Inputs given to model:",r),n}}function Tm(t){for(let e in t)Xf(t[e])?t[e]=new je(t[e]):typeof t[e]=="object"&&Tm(t[e]);return t}function Q1(t){if(t instanceof je)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 je("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new je("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function Im(t){return new je("bool",[t],[1])}async function Am(t,e){let{encoder_outputs:r,past_key_values:n}=e;if(!r){const h=dn(e,t.sessions.model.inputNames);r=(await oi(t,h)).last_hidden_state}const{input_ids:a,decoder_input_ids:o,...i}=e;return i.input_ids=o,i.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=e.attention_mask),await Jo(t,i,!0)}async function oi(t,e){const r=t.sessions.model,n=Object.create(null);for(const a of r.inputNames)n[a]=e[a];return r.inputNames.includes("token_type_ids")&&!n.token_type_ids&&(n.token_type_ids=new je("int64",new BigInt64Array(n.input_ids.data.length),n.input_ids.dims)),await Mr(r,n)}async function Jo(t,e,r=!1){const n=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:a,...o}=e;n.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=Im(!!a)),t.addPastKeyValues(o,a);const i=dn(o,n.inputNames);return await Mr(n,i)}function X1(t,e,r,n){if(t.sessions.model.inputNames.includes("position_ids")&&r.attention_mask&&!r.position_ids){const[o,i]=r.attention_mask.dims,d=new BigInt64Array(r.attention_mask.data.length);for(let h=0;h[i.at(-1)])),a.decoder_input_ids=Q1(e),a}class ue extends Ot{constructor(r,n){super();te(this,"main_input_name","input_ids");te(this,"forward_params",["input_ids","attention_mask"]);this.config=r,this.sessions=n;const a=si.get(this.constructor),o=Ua.get(a);this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,o===Ae.DecoderOnly?(this.can_generate=!0,this._forward=Jo,this._prepare_inputs_for_generation=X1):o===Ae.Seq2Seq||o===Ae.Vision2Seq||o===Ae.Musicgen?(this.can_generate=!0,this._forward=Am,this._prepare_inputs_for_generation=Z1):o===Ae.EncoderDecoder?this._forward=Am:o===Ae.ImageTextToText?(this.can_generate=!0,console.warn("TODO: Implement visionDecoderForward")):this._forward=oi,this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var n;const r=[];for(const a of Object.values(this.sessions))(n=a==null?void 0:a.handler)!=null&&n.dispose&&r.push(a.handler.dispose());return await Promise.all(r)}static async from_pretrained(r,{progress_callback:n=null,config:a=null,cache_dir:o=null,local_files_only:i=!1,revision:d="main",model_file_name:h=null,subfolder:m="onnx",device:c=null,dtype:_=null,use_external_data_format:v=null,session_options:$={}}={}){let C={progress_callback:n,config:a,cache_dir:o,local_files_only:i,revision:d,model_file_name:h,subfolder:m,device:c,dtype:_,use_external_data_format:v,session_options:$};const k=si.get(this),M=Ua.get(k),z=await Cm.from_pretrained(r,C);C.config??(C.config=z);let I;return M===Ae.DecoderOnly?I=await Promise.all([Qr(r,{model:C.model_file_name??"model"},C),Br(r,"generation_config.json",!1,C)]):M===Ae.Seq2Seq||M===Ae.Vision2Seq?I=await Promise.all([Qr(r,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},C),Br(r,"generation_config.json",!1,C)]):M===Ae.MaskGeneration?I=await Promise.all([Qr(r,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},C)]):M===Ae.EncoderDecoder?I=await Promise.all([Qr(r,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},C)]):M===Ae.ImageTextToText?I=await Promise.all([Qr(r,{embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"},C),Br(r,"generation_config.json",!1,C)]):M===Ae.Musicgen?I=await Promise.all([Qr(r,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},C),Br(r,"generation_config.json",!1,C)]):(M!==Ae.EncoderOnly&&console.warn(`Model type for '${k??(a==null?void 0:a.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),I=await Promise.all([Qr(r,{model:C.model_file_name??"model"},C)])),new this(z,...I)}async _call(r){return await this.forward(r)}async forward(r){return await this._forward(this,r)}_get_logits_warper(r){const n=new Em;return r.temperature!==null&&r.temperature!==1&&n.push(new N1(r.temperature)),r.top_k!==null&&r.top_k!==0&&n.push(new U1(r.top_k)),r.top_p!==null&&r.top_p<1&&n.push(new L1(r.top_p)),n}_get_logits_processor(r,n,a=null){const o=new Em;if(r.repetition_penalty!==null&&r.repetition_penalty!==1&&o.push(new P1(r.repetition_penalty)),r.no_repeat_ngram_size!==null&&r.no_repeat_ngram_size>0&&o.push(new z1(r.no_repeat_ngram_size)),r.bad_words_ids!==null&&o.push(new B1(r.bad_words_ids,r.eos_token_id)),r.min_length!==null&&r.eos_token_id!==null&&r.min_length>0&&o.push(new j1(r.min_length,r.eos_token_id)),r.min_new_tokens!==null&&r.eos_token_id!==null&&r.min_new_tokens>0&&o.push(new R1(n,r.min_new_tokens,r.eos_token_id)),r.forced_bos_token_id!==null&&o.push(new A1(r.forced_bos_token_id)),r.forced_eos_token_id!==null&&o.push(new M1(r.max_length,r.forced_eos_token_id)),r.begin_suppress_tokens!==null){let i=n>1||r.forced_bos_token_id===null?n:n+1;r.forced_decoder_ids!==null&&(i+=r.forced_decoder_ids[r.forced_decoder_ids.length-1][0]),o.push(new O1(r.begin_suppress_tokens,i))}return r.guidance_scale!==null&&r.guidance_scale>1&&o.push(new D1(r.guidance_scale)),a!==null&&o.extend(a),o}_prepare_generation_config(r,n){const a=new F1(this.config);return"generation_config"in this&&Object.assign(a,this.generation_config),r&&Object.assign(a,r),n&&Object.assign(a,dn(n,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(r,n=null){const a=new Zo;return r.max_length!==null&&a.push(new W1(r.max_length,this.config.max_position_embeddings??null)),r.eos_token_id!==null&&a.push(new G1(r.eos_token_id)),n&&a.extend(n),a}_validate_model_class(){if(!this.can_generate){const r=[al,Ag,Ig,Tg],n=si.get(this.constructor),a=new Set,o=this.config.model_type;for(const d of r){const h=d.get(o);h&&a.add(h[0])}let i=`The current model class (${n}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw a.size>0&&(i+=` Please use the following class instead: ${[...a].join(", ")}`),Error(i)}}prepare_inputs_for_generation(...r){return this._prepare_inputs_for_generation(this,...r)}_update_model_kwargs_for_generation({generated_input_ids:r,outputs:n,model_inputs:a,is_encoder_decoder:o}){return a.past_key_values=this.getPastKeyValues(n,a.past_key_values),a.input_ids=new je("int64",r.flat(),[r.length,1]),o||(a.attention_mask=_r([a.attention_mask,Ma([a.attention_mask.dims[0],1])],1)),a.position_ids=null,a}_prepare_model_inputs({inputs:r,bos_token_id:n,model_kwargs:a}){const o=dn(a,this.forward_params),i=this.main_input_name;if(i in o){if(r)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else o[i]=r;return{inputs_tensor:o[i],model_inputs:o,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:r,model_inputs:n,model_input_name:a,generation_config:o}){const i=dn(n,this.sessions.model.inputNames);let{last_hidden_state:d}=await oi(this,i);return o.guidance_scale!==null&&o.guidance_scale>1&&(d=_r([d,yv(d,0)],0),"attention_mask"in n&&(n.attention_mask=_r([n.attention_mask,vv(n.attention_mask)],0))),n.encoder_outputs=d,n}_prepare_decoder_input_ids_for_generation({batch_size:r,model_input_name:n,model_kwargs:a,decoder_start_token_id:o,bos_token_id:i,generation_config:d}){o=o??i;let h;if(this.config.model_type==="musicgen")h=new Array(r*this.config.decoder.num_codebooks).fill(o);else if(Array.isArray(o)){if(o.length!==r)throw new Error(`\`decoder_start_token_id\` expcted to have length ${r} but got ${o.length}`);h=o}else h=new Array(r).fill(o);const c=new je("int64",h,[h.length,1]);return a.decoder_attention_mask=_v(c),{input_ids:c,model_inputs:a}}async generate({inputs:r=null,generation_config:n=null,logits_processor:a=null,stopping_criteria:o=null,streamer:i=null,...d}){this._validate_model_class(),n=this._prepare_generation_config(n,d);let{inputs_tensor:h,model_inputs:m,model_input_name:c}=this._prepare_model_inputs({inputs:r,model_kwargs:d});const _=this.config.is_encoder_decoder;_&&("encoder_outputs"in m||(m=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:h,model_inputs:m,model_input_name:c,generation_config:n})));let v;_?{input_ids:v,model_inputs:m}=this._prepare_decoder_input_ids_for_generation({batch_size:m[c].dims.at(0),model_input_name:c,model_kwargs:m,decoder_start_token_id:n.decoder_start_token_id,bos_token_id:n.bos_token_id,generation_config:n}):v=m[c];let $=v.dims.at(-1);n.max_new_tokens!==null&&(n.max_length=$+n.max_new_tokens);const C=this._get_logits_processor(n,$,a),k=this._get_stopping_criteria(n,o),M=m[c].dims.at(0),z=La.getSampler(n),I=new Array(M).fill(0),j=v.tolist();for(i&&i.put(j);;){m=this.prepare_inputs_for_generation(j,m,n);const R=await this.forward(m),L=R.logits.slice(null,-1,null),Y=C(j,L),Q=[];for(let pe=0;pepe))break;m=this._update_model_kwargs_for_generation({generated_input_ids:Q,outputs:R,model_inputs:m,is_encoder_decoder:_})}return i&&i.end(),new je("int64",j.flat(),[j.length,j[0].length])}addAttentionsToBeam(r,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`.");r.cross_attentions||(r.cross_attentions=[]),r.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`.");r.decoder_attentions||(r.decoder_attentions=[]),r.decoder_attentions.push(n.decoder_attentions)}groupBeams(r){const n=Object.create(null);for(const a of r)n[a.id]===void 0?n[a.id]=[a]:n[a.id].push(a);return Object.values(n)}getPastKeyValues(r,n){const a=Object.create(null);for(const o in r)if(o.startsWith("present")){let i=o.replace("present","past_key_values");if(n&&o.includes("encoder"))a[i]=n[i];else{if(n){const d=n[i];d.location==="gpu-buffer"&&d.dispose()}a[i]=r[o]}}return a}getAttentions(r){const n=Object.create(null);for(const a of["cross_attentions","decoder_attentions"]){const o=[];for(const i in r)if(i.startsWith(a)){const d=i.split(".").pop();o[d]=r[i]}n[a]=o}return n}addPastKeyValues(r,n){if(n)Object.assign(r,n);else{const a=this.custom_config.kv_cache_dtype??"float32",o=a==="float16"?new Uint16Array:[],i=xm(this.config,{encoder_add_pkv:this.add_encoder_pkv??!0});for(const d in i)r[d]=new je(a,o,i[d])}}}class Wt{}class li extends ue{}class J1 extends li{}class e$ extends li{async _call(e){return new wt(await super._call(e))}}class t$ extends li{async _call(e){return new Fe(await super._call(e))}}class r$ extends li{async _call(e){return new _t(await super._call(e))}}class n$ extends li{async _call(e){return new Ct(await super._call(e))}}class i$ extends ue{}class a$ extends i${}class ui extends ue{}class s$ extends ui{}class o$ extends ui{async _call(e){return new wt(await super._call(e))}}class l$ extends ui{async _call(e){return new Fe(await super._call(e))}}class u$ extends ui{async _call(e){return new _t(await super._call(e))}}class d$ extends ui{async _call(e){return new Ct(await super._call(e))}}class di extends ue{}class c$ extends di{}class p$ extends di{async _call(e){return new wt(await super._call(e))}}class h$ extends di{async _call(e){return new Fe(await super._call(e))}}class f$ extends di{async _call(e){return new _t(await super._call(e))}}class m$ extends di{async _call(e){return new Ct(await super._call(e))}}class ci extends ue{}class g$ extends ci{}class y$ extends ci{async _call(e){return new wt(await super._call(e))}}class _$ extends ci{async _call(e){return new Fe(await super._call(e))}}class w$ extends ci{async _call(e){return new _t(await super._call(e))}}class v$ extends ci{async _call(e){return new Ct(await super._call(e))}}class pi extends ue{}class b$ extends pi{}class $$ extends pi{async _call(e){return new wt(await super._call(e))}}class x$ extends pi{async _call(e){return new Fe(await super._call(e))}}class C$ extends pi{async _call(e){return new _t(await super._call(e))}}class S$ extends pi{async _call(e){return new Ct(await super._call(e))}}class hi extends ue{}class E$ extends hi{}class k$ extends hi{async _call(e){return new wt(await super._call(e))}}class T$ extends hi{async _call(e){return new Fe(await super._call(e))}}class I$ extends hi{async _call(e){return new _t(await super._call(e))}}class A$ extends hi{async _call(e){return new Ct(await super._call(e))}}class fi extends ue{}class M$ extends fi{}class O$ extends fi{async _call(e){return new wt(await super._call(e))}}class z$ extends fi{async _call(e){return new Fe(await super._call(e))}}class P$ extends fi{async _call(e){return new _t(await super._call(e))}}class j$ extends fi{async _call(e){return new Ct(await super._call(e))}}class mi extends ue{}class R$ extends mi{}class B$ extends mi{async _call(e){return new Fe(await super._call(e))}}class D$ extends mi{async _call(e){return new _t(await super._call(e))}}class N$ extends mi{async _call(e){return new Ct(await super._call(e))}}class L$ extends mi{async _call(e){return new wt(await super._call(e))}}class Fa extends ue{}class U$ extends Fa{}class F$ extends Fa{async _call(e){return new wt(await super._call(e))}}class W$ extends Fa{async _call(e){return new Fe(await super._call(e))}}class G$ extends Fa{async _call(e){return new _t(await super._call(e))}}class Wa extends ue{}class V$ extends Wa{}class H$ extends Wa{async _call(e){return new wt(await super._call(e))}}class q$ extends Wa{async _call(e){return new Fe(await super._call(e))}}class K$ extends Wa{async _call(e){return new Ct(await super._call(e))}}class gi extends ue{}class Y$ extends gi{}class Q$ extends gi{async _call(e){return new wt(await super._call(e))}}class X$ extends gi{async _call(e){return new Fe(await super._call(e))}}class Z$ extends gi{async _call(e){return new _t(await super._call(e))}}class J$ extends gi{async _call(e){return new Ct(await super._call(e))}}class Ga extends ue{}class e2 extends Ga{}class t2 extends Ga{async _call(e){return new wt(await super._call(e))}}class r2 extends Ga{async _call(e){return new Fe(await super._call(e))}}class n2 extends Ga{async _call(e){return new Ct(await super._call(e))}}class Va extends ue{}class i2 extends Va{}class a2 extends Va{async _call(e){return new Fe(await super._call(e))}}class s2 extends Va{async _call(e){return new Ct(await super._call(e))}}class o2 extends Va{async _call(e){return new wt(await super._call(e))}}class Mm extends ue{constructor(r,n,a){super(r,n);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=a}}class l2 extends Mm{}class u2 extends Mm{}class Om extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class d2 extends Om{}class c2 extends Om{}class zm extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class p2 extends zm{}class h2 extends zm{}class el extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class f2 extends el{}class m2 extends el{}class g2 extends el{async _call(e){return new Fe(await super._call(e))}}class Ha extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class y2 extends Ha{}class _2 extends Ha{}class w2 extends Ha{async _call(e){return new Fe(await super._call(e))}}class v2 extends Ha{}class Pm extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class b2 extends Pm{}class $2 extends Pm{}class jm extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class x2 extends jm{}class C2 extends jm{}class yi extends ue{}class S2 extends yi{}class E2 extends yi{async _call(e){return new wt(await super._call(e))}}class k2 extends yi{async _call(e){return new Fe(await super._call(e))}}class T2 extends yi{async _call(e){return new _t(await super._call(e))}}class I2 extends yi{async _call(e){return new Ct(await super._call(e))}}class _i extends ue{}class A2 extends _i{}class M2 extends _i{async _call(e){return new wt(await super._call(e))}}class O2 extends _i{async _call(e){return new Fe(await super._call(e))}}class z2 extends _i{async _call(e){return new _t(await super._call(e))}}class P2 extends _i{async _call(e){return new Ct(await super._call(e))}}class wi extends ue{}class j2 extends wi{}class R2 extends wi{async _call(e){return new wt(await super._call(e))}}class B2 extends wi{async _call(e){return new Fe(await super._call(e))}}class D2 extends wi{async _call(e){return new _t(await super._call(e))}}class N2 extends wi{async _call(e){return new Ct(await super._call(e))}}class Rm extends ue{}class L2 extends Rm{}class U2 extends Rm{}class Bm extends ue{constructor(r,n,a){super(r,n);te(this,"requires_attention_mask",!1);te(this,"main_input_name","input_features");te(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=a}}class F2 extends Bm{}class W2 extends Bm{_retrieve_init_tokens(e){throw e.decoder_start_token_id,new Error("Not implemented yet")}async generate({inputs:e=null,generation_config:r=null,logits_processor:n=null,stopping_criteria:a=null,language:o=null,task:i=null,...d}){throw new Error("WhisperForConditionalGeneration.generate is not yet in Transformers.js v3.")}_extract_token_timestamps(e,r,n=null,a=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");let o=this.config.median_filter_width;o===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),o=7);const i=e.cross_attentions.map(m=>{let c=Array.from({length:this.config.decoder_layers},(M,z)=>_r(m.map(I=>I[z]),2)),_=Fo(r.map(([M,z])=>n?c[M].slice(null,z,null,[0,n]):c[M].slice(null,z)));_=_.transpose(1,0,2,3);let[v,$]=hv(_,-2,0,!0),C=_.clone();for(let M=0;M_[z+1]-_[z]),C=ht([1],$).map(M=>!!M),k=[];for(let M=0;Mv.findIndex($=>$==o)),h=d.every(v=>v===-1),m=d.every(v=>v!==-1);if(!h&&!m)throw new Error("Every input should contain either 0 or 1 image token.");if(h)return{inputs_embeds:e,attention_mask:a,position_ids:null};let c=[],_=[];for(let v=0;vo*i,1);e.input_labels=new je("int64",new BigInt64Array(a).fill(1n),n)}const r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await Mr(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new xC(await super._call(e))}}class xC extends Wt{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}}class yg extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class CC extends yg{}class SC extends yg{}class _g extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class EC extends _g{}class kC extends _g{}class Xr extends ue{}class TC extends Xr{}class IC extends Xr{async _call(e){return new wn(await super._call(e))}}class AC extends Xr{async _call(e){return new Fe(await super._call(e))}}class MC extends Xr{async _call(e){return new _t(await super._call(e))}}class rl extends ue{}class OC extends rl{}class zC extends rl{async _call(e){return new wn(await super._call(e))}}class PC extends rl{async _call(e){return new Fe(await super._call(e))}}class Ka extends ue{}class jC extends Ka{}class RC extends Ka{async _call(e){return new wn(await super._call(e))}}class BC extends Ka{async _call(e){return new Fe(await super._call(e))}}class DC extends Ka{async _call(e){return new _t(await super._call(e))}}class nl extends ue{}class NC extends nl{}class LC extends nl{async _call(e){return new wn(await super._call(e))}}class UC extends nl{async _call(e){return new Fe(await super._call(e))}}class FC extends Xr{}class WC extends Xr{async _call(e){return new wn(await super._call(e))}}class GC extends Xr{async _call(e){return new Fe(await super._call(e))}}class vi extends ue{}class VC extends vi{}class HC extends vi{async _call(e){return new wn(await super._call(e))}}class qC extends vi{async _call(e){return new Fe(await super._call(e))}}class KC extends vi{async _call(e){return new FS(await super._call(e))}}class YC extends vi{async _call(e){return new _t(await super._call(e))}}class wg extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class QC extends wg{}class XC extends wg{async generate_speech(e,r,{threshold:n=.5,minlenratio:a=0,maxlenratio:o=20,vocoder:i=null}={}){const d={input_ids:e},{encoder_outputs:h,encoder_attention_mask:m}=await oi(this,d),c=h.dims[1]/this.config.reduction_factor,_=Math.floor(c*o),v=Math.floor(c*a),$=this.config.num_mel_bins;let C=[],k=null,M=null,z=0;for(;;){++z;const R=Im(!!M);let L;M?L=M.output_sequence_out:L=new je("float32",new Float32Array($),[1,1,$]);let Y={use_cache_branch:R,output_sequence:L,encoder_attention_mask:m,speaker_embeddings:r,encoder_hidden_states:h};this.addPastKeyValues(Y,k),M=await Mr(this.sessions.decoder_model_merged,Y),k=this.getPastKeyValues(M,k);const{prob:Q,spectrum:ie}=M;if(C.push(ie),z>=v&&(Array.from(Q.data).filter(pe=>pe>=n).length>0||z>=_))break}const I=_r(C),{waveform:j}=await Mr(i.sessions.model,{spectrogram:I});return{spectrogram:I,waveform:j}}}class ZC extends ue{constructor(){super(...arguments);te(this,"main_input_name","spectrogram")}}class JC extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class eS extends JC{}class vg extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class tS extends vg{}class rS extends vg{}class bg extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class nS extends bg{}class iS extends bg{}class $g extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class aS extends $g{}class sS extends $g{}class il extends ue{}class oS extends il{}class lS extends il{static async from_pretrained(e,r={}){return r.model_file_name??(r.model_file_name="text_model"),super.from_pretrained(e,r)}}class uS extends il{static async from_pretrained(e,r={}){return r.model_file_name??(r.model_file_name="audio_model"),super.from_pretrained(e,r)}}class dS extends ue{}class xg extends dS{async _call(e){return new GS(await super._call(e))}}class Cg extends ue{}class cS extends Cg{}class pS extends Cg{}class Sg extends ue{constructor(e,r,n){super(e,r),this.generation_config=n}}class hS extends Sg{}class fS extends Sg{}class Eg extends ue{}class mS extends Eg{}class gS extends Eg{async _call(e){return new Fe(await super._call(e))}}class kg extends ue{constructor(r,n,a){super(r,n);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=a}_apply_and_filter_by_delay_pattern_mask(r){const[n,a]=r.dims,o=this.config.decoder.num_codebooks,i=a-o;let d=0;for(let c=0;c0&&$<=i&&(r.data[d++]=r.data[c])}const h=Math.floor(n/o),m=d/(h*o);return new je(r.type,r.data.slice(0,d),[h,o,m])}prepare_inputs_for_generation(r,n,a){let o=structuredClone(r);for(let d=0;d=h&&(o[d][h]=BigInt(this.config.decoder.pad_token_id));return a.guidance_scale!==null&&a.guidance_scale>1&&(o=o.concat(o)),super.prepare_inputs_for_generation(o,n,a)}async generate(r){const n=await super.generate(r),a=this._apply_and_filter_by_delay_pattern_mask(n).unsqueeze_(0),{audio_values:o}=await Mr(this.sessions.encodec_decode,{audio_codes:a});return o}}class Ya{static async from_pretrained(e,{progress_callback:r=null,config:n=null,cache_dir:a=null,local_files_only:o=!1,revision:i="main",model_file_name:d=null,subfolder:h="onnx",device:m=null,dtype:c=null,use_external_data_format:_=null,session_options:v={}}={}){let $={progress_callback:r,config:n,cache_dir:a,local_files_only:o,revision:i,model_file_name:d,subfolder:h,device:m,dtype:c,use_external_data_format:_,session_options:v};if(n=await Cm.from_pretrained(e,$),$.config||($.config=n),!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 k=C.get(n.model_type);if(k)return await k[1].from_pretrained(e,$)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${n.model_type}", attempting to construct from base class.`),await ue.from_pretrained(e,$);throw Error(`Unsupported model type: ${n.model_type}`)}}te(Ya,"MODEL_CLASS_MAPPINGS",null),te(Ya,"BASE_IF_FAIL",!1);const yS=new Map([["bert",["BertModel",J1]],["nomic_bert",["NomicBertModel",a$]],["roformer",["RoFormerModel",s$]],["electra",["ElectraModel",g$]],["esm",["EsmModel",U$]],["convbert",["ConvBertModel",c$]],["camembert",["CamembertModel",b$]],["deberta",["DebertaModel",E$]],["deberta-v2",["DebertaV2Model",M$]],["mpnet",["MPNetModel",Y$]],["albert",["AlbertModel",i2]],["distilbert",["DistilBertModel",R$]],["roberta",["RobertaModel",S2]],["xlm",["XLMModel",A2]],["xlm-roberta",["XLMRobertaModel",j2]],["clap",["ClapModel",oS]],["clip",["CLIPModel",q2]],["clipseg",["CLIPSegModel",tx]],["chinese_clip",["ChineseCLIPModel",ex]],["siglip",["SiglipModel",Q2]],["mobilebert",["MobileBertModel",V$]],["squeezebert",["SqueezeBertModel",e2]],["wav2vec2",["Wav2Vec2Model",TC]],["wav2vec2-bert",["Wav2Vec2BertModel",NC]],["unispeech",["UniSpeechModel",OC]],["unispeech-sat",["UniSpeechSatModel",jC]],["hubert",["HubertModel",FC]],["wavlm",["WavLMModel",VC]],["audio-spectrogram-transformer",["ASTModel",L2]],["vits",["VitsModel",xg]],["detr",["DetrModel",Wx]],["table-transformer",["TableTransformerModel",qx]],["vit",["ViTModel",Mx]],["mobilevit",["MobileViTModel",jx]],["owlvit",["OwlViTModel",Bx]],["owlv2",["Owlv2Model",Nx]],["beit",["BeitModel",Ux]],["deit",["DeiTModel",Qx]],["convnext",["ConvNextModel",pC]],["convnextv2",["ConvNextV2Model",fC]],["dinov2",["Dinov2Model",gC]],["resnet",["ResNetModel",Zx]],["swin",["SwinModel",eC]],["swin2sr",["Swin2SRModel",rC]],["donut-swin",["DonutSwinModel",cC]],["yolos",["YolosModel",_C]],["dpt",["DPTModel",iC]],["glpn",["GLPNModel",lC]],["hifigan",["SpeechT5HifiGan",ZC]],["efficientnet",["EfficientNetModel",mS]]]),_S=new Map([["t5",["T5Model",l2]],["longt5",["LongT5Model",d2]],["mt5",["MT5Model",p2]],["bart",["BartModel",f2]],["mbart",["MBartModel",y2]],["marian",["MarianModel",CC]],["whisper",["WhisperModel",F2]],["m2m_100",["M2M100Model",EC]],["blenderbot",["BlenderbotModel",b2]],["blenderbot-small",["BlenderbotSmallModel",x2]]]),wS=new Map([["bloom",["BloomModel",Sx]],["gpt2",["GPT2Model",nx]],["gptj",["GPTJModel",ux]],["gpt_bigcode",["GPTBigCodeModel",cx]],["gpt_neo",["GPTNeoModel",ax]],["gpt_neox",["GPTNeoXModel",ox]],["codegen",["CodeGenModel",hx]],["llama",["LlamaModel",mx]],["openelm",["OpenELMModel",yx]],["qwen2",["Qwen2Model",wx]],["phi",["PhiModel",bx]],["phi3",["Phi3Model",xx]],["mpt",["MptModel",kx]],["opt",["OPTModel",Ix]],["mistral",["MistralModel",tS]],["starcoder2",["Starcoder2Model",nS]],["falcon",["FalconModel",aS]],["stablelm",["StableLmModel",hS]]]),Tg=new Map([["speecht5",["SpeechT5ForSpeechToText",QC]],["whisper",["WhisperForConditionalGeneration",W2]]]),vS=new Map([["speecht5",["SpeechT5ForTextToSpeech",XC]]]),bS=new Map([["vits",["VitsModel",xg]],["musicgen",["MusicgenForConditionalGeneration",kg]]]),$S=new Map([["bert",["BertForSequenceClassification",t$]],["roformer",["RoFormerForSequenceClassification",l$]],["electra",["ElectraForSequenceClassification",_$]],["esm",["EsmForSequenceClassification",W$]],["convbert",["ConvBertForSequenceClassification",h$]],["camembert",["CamembertForSequenceClassification",x$]],["deberta",["DebertaForSequenceClassification",T$]],["deberta-v2",["DebertaV2ForSequenceClassification",z$]],["mpnet",["MPNetForSequenceClassification",X$]],["albert",["AlbertForSequenceClassification",a2]],["distilbert",["DistilBertForSequenceClassification",B$]],["roberta",["RobertaForSequenceClassification",k2]],["xlm",["XLMForSequenceClassification",O2]],["xlm-roberta",["XLMRobertaForSequenceClassification",B2]],["bart",["BartForSequenceClassification",g2]],["mbart",["MBartForSequenceClassification",w2]],["mobilebert",["MobileBertForSequenceClassification",q$]],["squeezebert",["SqueezeBertForSequenceClassification",r2]]]),xS=new Map([["bert",["BertForTokenClassification",r$]],["roformer",["RoFormerForTokenClassification",u$]],["electra",["ElectraForTokenClassification",w$]],["esm",["EsmForTokenClassification",G$]],["convbert",["ConvBertForTokenClassification",f$]],["camembert",["CamembertForTokenClassification",C$]],["deberta",["DebertaForTokenClassification",I$]],["deberta-v2",["DebertaV2ForTokenClassification",P$]],["mpnet",["MPNetForTokenClassification",Z$]],["distilbert",["DistilBertForTokenClassification",D$]],["roberta",["RobertaForTokenClassification",T2]],["xlm",["XLMForTokenClassification",z2]],["xlm-roberta",["XLMRobertaForTokenClassification",D2]]]),Ig=new Map([["t5",["T5ForConditionalGeneration",u2]],["longt5",["LongT5ForConditionalGeneration",c2]],["mt5",["MT5ForConditionalGeneration",h2]],["bart",["BartForConditionalGeneration",m2]],["mbart",["MBartForConditionalGeneration",_2]],["marian",["MarianMTModel",SC]],["m2m_100",["M2M100ForConditionalGeneration",kC]],["blenderbot",["BlenderbotForConditionalGeneration",$2]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",C2]]]),al=new Map([["bloom",["BloomForCausalLM",Ex]],["gpt2",["GPT2LMHeadModel",ix]],["gptj",["GPTJForCausalLM",dx]],["gpt_bigcode",["GPTBigCodeForCausalLM",px]],["gpt_neo",["GPTNeoForCausalLM",sx]],["gpt_neox",["GPTNeoXForCausalLM",lx]],["codegen",["CodeGenForCausalLM",fx]],["llama",["LlamaForCausalLM",gx]],["openelm",["OpenELMForCausalLM",_x]],["qwen2",["Qwen2ForCausalLM",vx]],["phi",["PhiForCausalLM",$x]],["phi3",["Phi3ForCausalLM",Cx]],["mpt",["MptForCausalLM",Tx]],["opt",["OPTForCausalLM",Ax]],["mbart",["MBartForCausalLM",v2]],["mistral",["MistralForCausalLM",rS]],["starcoder2",["Starcoder2ForCausalLM",iS]],["falcon",["FalconForCausalLM",sS]],["trocr",["TrOCRForCausalLM",eS]],["stablelm",["StableLmForCausalLM",fS]]]),CS=new Map([["bert",["BertForMaskedLM",e$]],["roformer",["RoFormerForMaskedLM",o$]],["electra",["ElectraForMaskedLM",y$]],["esm",["EsmForMaskedLM",F$]],["convbert",["ConvBertForMaskedLM",p$]],["camembert",["CamembertForMaskedLM",$$]],["deberta",["DebertaForMaskedLM",k$]],["deberta-v2",["DebertaV2ForMaskedLM",O$]],["mpnet",["MPNetForMaskedLM",Q$]],["albert",["AlbertForMaskedLM",o2]],["distilbert",["DistilBertForMaskedLM",L$]],["roberta",["RobertaForMaskedLM",E2]],["xlm",["XLMWithLMHeadModel",M2]],["xlm-roberta",["XLMRobertaForMaskedLM",R2]],["mobilebert",["MobileBertForMaskedLM",H$]],["squeezebert",["SqueezeBertForMaskedLM",t2]]]),SS=new Map([["bert",["BertForQuestionAnswering",n$]],["roformer",["RoFormerForQuestionAnswering",d$]],["electra",["ElectraForQuestionAnswering",v$]],["convbert",["ConvBertForQuestionAnswering",m$]],["camembert",["CamembertForQuestionAnswering",S$]],["deberta",["DebertaForQuestionAnswering",A$]],["deberta-v2",["DebertaV2ForQuestionAnswering",j$]],["mpnet",["MPNetForQuestionAnswering",J$]],["albert",["AlbertForQuestionAnswering",s2]],["distilbert",["DistilBertForQuestionAnswering",N$]],["roberta",["RobertaForQuestionAnswering",I2]],["xlm",["XLMForQuestionAnswering",P2]],["xlm-roberta",["XLMRobertaForQuestionAnswering",N2]],["mobilebert",["MobileBertForQuestionAnswering",K$]],["squeezebert",["SqueezeBertForQuestionAnswering",n2]]]),Ag=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",G2]]]),ES=new Map([["llava",["LlavaForConditionalGeneration",H2]]]),kS=new Map([["vit",["ViTForImageClassification",Ox]],["mobilevit",["MobileViTForImageClassification",Rx]],["beit",["BeitForImageClassification",Fx]],["deit",["DeiTForImageClassification",Xx]],["convnext",["ConvNextForImageClassification",hC]],["convnextv2",["ConvNextV2ForImageClassification",mC]],["dinov2",["Dinov2ForImageClassification",yC]],["resnet",["ResNetForImageClassification",Jx]],["swin",["SwinForImageClassification",tC]],["segformer",["SegformerForImageClassification",cS]],["efficientnet",["EfficientNetForImageClassification",gS]]]),TS=new Map([["detr",["DetrForObjectDetection",Gx]],["table-transformer",["TableTransformerForObjectDetection",Kx]],["yolos",["YolosForObjectDetection",wC]]]),IS=new Map([["owlvit",["OwlViTForObjectDetection",Dx]],["owlv2",["Owlv2ForObjectDetection",Lx]]]),AS=new Map([["detr",["DetrForSegmentation",Vx]],["clipseg",["CLIPSegForImageSegmentation",rx]]]),MS=new Map([["segformer",["SegformerForSemanticSegmentation",pS]]]),OS=new Map([["sam",["SamModel",$C]]]),zS=new Map([["wav2vec2",["Wav2Vec2ForCTC",IC]],["wav2vec2-bert",["Wav2Vec2BertForCTC",LC]],["unispeech",["UniSpeechForCTC",zC]],["unispeech-sat",["UniSpeechSatForCTC",RC]],["wavlm",["WavLMForCTC",HC]],["hubert",["HubertForCTC",WC]]]),PS=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",AC]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",UC]],["unispeech",["UniSpeechForSequenceClassification",PC]],["unispeech-sat",["UniSpeechSatForSequenceClassification",BC]],["wavlm",["WavLMForSequenceClassification",qC]],["hubert",["HubertForSequenceClassification",GC]],["audio-spectrogram-transformer",["ASTForAudioClassification",U2]]]),jS=new Map([["wavlm",["WavLMForXVector",KC]]]),RS=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",DC]],["wavlm",["WavLMForAudioFrameClassification",YC]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",MC]]]),BS=new Map([["vitmatte",["VitMatteForImageMatting",Px]]]),DS=new Map([["swin2sr",["Swin2SRForImageSuperResolution",nC]]]),NS=new Map([["dpt",["DPTForDepthEstimation",aC]],["depth_anything",["DepthAnythingForDepthEstimation",oC]],["glpn",["GLPNForDepthEstimation",uC]]]),LS=new Map([["clip",["CLIPVisionModelWithProjection",Y2]],["siglip",["SiglipVisionModel",Z2]]]),Mg=[[yS,Ae.EncoderOnly],[_S,Ae.EncoderDecoder],[wS,Ae.DecoderOnly],[$S,Ae.EncoderOnly],[xS,Ae.EncoderOnly],[Ig,Ae.Seq2Seq],[Tg,Ae.Seq2Seq],[al,Ae.DecoderOnly],[CS,Ae.EncoderOnly],[SS,Ae.EncoderOnly],[Ag,Ae.Vision2Seq],[ES,Ae.ImageTextToText],[kS,Ae.EncoderOnly],[AS,Ae.EncoderOnly],[MS,Ae.EncoderOnly],[BS,Ae.EncoderOnly],[DS,Ae.EncoderOnly],[NS,Ae.EncoderOnly],[TS,Ae.EncoderOnly],[IS,Ae.EncoderOnly],[OS,Ae.MaskGeneration],[zS,Ae.EncoderOnly],[PS,Ae.EncoderOnly],[vS,Ae.Seq2Seq],[bS,Ae.EncoderOnly],[jS,Ae.EncoderOnly],[RS,Ae.EncoderOnly],[LS,Ae.EncoderOnly]];for(const[t,e]of Mg)for(const[r,n]of t.values())Ua.set(r,e),si.set(n,r),km.set(r,n);const US=[["MusicgenForConditionalGeneration",kg,Ae.Musicgen],["CLIPTextModelWithProjection",K2,Ae.EncoderOnly],["SiglipTextModel",X2,Ae.EncoderOnly],["ClapTextModelWithProjection",lS,Ae.EncoderOnly],["ClapAudioModelWithProjection",uS,Ae.EncoderOnly]];for(const[t,e,r]of US)Ua.set(t,r),si.set(e,t),km.set(t,e);class Og extends Ya{}te(Og,"MODEL_CLASS_MAPPINGS",Mg.map(e=>e[0])),te(Og,"BASE_IF_FAIL",!0);class zg extends Ya{}te(zg,"MODEL_CLASS_MAPPINGS",[al]);class Fe extends Wt{constructor({logits:e}){super(),this.logits=e}}class FS extends Wt{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}}class _t extends Wt{constructor({logits:e}){super(),this.logits=e}}class wt extends Wt{constructor({logits:e}){super(),this.logits=e}}class Ct extends Wt{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}}class wn extends Wt{constructor({logits:e}){super(),this.logits=e}}class WS extends Wt{constructor({alphas:e}){super(),this.alphas=e}}class GS extends Wt{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}}if(!(typeof self<"u")){if(!Ye)throw new Error("Unable to load image processing library.")}class VS{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Pg=Rr.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t);class HS extends VS{constructor(e,{skip_prompt:r=!1,...n}={}){super(),this.tokenizer=e,this.skip_prompt=r,this.decode_kwargs=n,this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");const r=e[0];if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}this.token_cache=ht(this.token_cache,r);const n=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let a;n.endsWith(` `)?(a=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&pm(n.charCodeAt(n.length-1))?(a=n.slice(this.print_len),this.print_len+=a.length):(a=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=a.length),this.on_finalized_text(a,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,r){Pg(e),r&&Pg(` `)}}Et.backends.onnx.wasm.wasmPaths="/";class qS extends HS{constructor(e,r){super(e,{skip_prompt:!0,skip_special_tokens:!0}),this.cb=r}on_finalized_text(e){this.cb(e)}}class KS extends Na{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}}const Qa=new KS;async function YS(){try{return(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{return!1}}class vn{static async getInstance(e=null){return this.model_id??(this.model_id=await YS()?"Xenova/Phi-3-mini-4k-instruct_fp16":"Xenova/Phi-3-mini-4k-instruct"),this.tokenizer??(this.tokenizer=$m.from_pretrained(this.model_id,{legacy:!0,progress_callback:e})),this.model??(this.model=zg.from_pretrained(this.model_id,{dtype:"q4",device:"webgpu",use_external_data_format:!0,progress_callback:e})),Promise.all([this.tokenizer,this.model])}}te(vn,"model_id",null),te(vn,"model",null),te(vn,"tokenizer",null),te(vn,"streamer",null);async function QS(t){const[e,r]=await vn.getInstance(),n=e.apply_chat_template(t,{add_generation_prompt:!0,return_dict:!0});{let a,o=0;const i=c=>{a??(a=performance.now());let _;o++>0&&(_=o/(performance.now()-a)*1e3),self.postMessage({status:"update",output:c,tps:_,numTokens:o})},d=new qS(e,i);self.postMessage({status:"start"});const h=await r.generate({...n,max_new_tokens:512,streamer:d,stopping_criteria:Qa}),m=e.batch_decode(h,{skip_special_tokens:!1});self.postMessage({status:"complete",output:m})}}async function XS(){self.postMessage({status:"loading",data:"Loading model..."});const[t,e]=await vn.getInstance(n=>{self.postMessage(n)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const r=t("a");await e.generate({...r,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async t=>{const{type:e,data:r}=t.data;switch(e){case"load":XS();break;case"generate":Qa.reset(),QS(r);break;case"interrupt":Qa.interrupt();break;case"reset":Qa.reset();break}})})();