diff --git "a/demo/ort-phi3/dist/esm/ort.all.min.js" "b/demo/ort-phi3/dist/esm/ort.all.min.js" new file mode 100644--- /dev/null +++ "b/demo/ort-phi3/dist/esm/ort.all.min.js" @@ -0,0 +1,4177 @@ +/*! + * ONNX Runtime Web v1.18.0 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +var I1=Object.create;var ta=Object.defineProperty;var C1=Object.getOwnPropertyDescriptor;var A1=Object.getOwnPropertyNames;var E1=Object.getPrototypeOf,O1=Object.prototype.hasOwnProperty;var q=(n,e)=>()=>(n&&(e=n(n=0)),e);var ht=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Tn=(n,e)=>{for(var r in e)ta(n,r,{get:e[r],enumerable:!0})},hf=(n,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of A1(e))!O1.call(n,i)&&i!==r&&ta(n,i,{get:()=>e[i],enumerable:!(t=C1(e,i))||t.enumerable});return n};var fi=(n,e,r)=>(r=n!=null?I1(E1(n)):{},hf(e||!n||!n.__esModule?ta(r,"default",{value:n,enumerable:!0}):r,n)),Kr=n=>hf(ta({},"__esModule",{value:!0}),n);var ra,Sn,rn,P1,na,ia=q(()=>{"use strict";ra=new Map,Sn=[],rn=(n,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let t=ra.get(n);if(t===void 0)ra.set(n,{backend:e,priority:r});else{if(t.priority>r)return;if(t.priority===r&&t.backend!==e)throw new Error(`cannot register backend "${n}" using priority ${r}`)}if(r>=0){let i=Sn.indexOf(n);i!==-1&&Sn.splice(i,1);for(let o=0;o{let e=ra.get(n);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(n)),await e.initPromise,e.initialized=!0,e.backend}catch(t){return r||(e.error=`${t}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},na=async n=>{let e=n.executionProviders||[],r=e.map(u=>typeof u=="string"?u:u.name),t=r.length===0?Sn:r,i,o=[],s=new Set;for(let u of t){let d=await P1(u);typeof d=="string"?o.push({name:u,err:d}):(i||(i=d),i===d&&s.add(u))}if(!i)throw new Error(`no available backend found. ERR: ${o.map(u=>`[${u.name}] ${u.err}`).join(", ")}`);for(let{name:u,err:d}of o)r.includes(u)&&console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${d}`);let a=e.filter(u=>s.has(typeof u=="string"?u:u.name));return[i,new Proxy(n,{get:(u,d)=>d==="executionProviders"?a:Reflect.get(u,d)})]}});var mf=q(()=>{"use strict";ia()});var gf,yf=q(()=>{"use strict";gf="1.18.0"});var bf,ar,Ls=q(()=>{"use strict";yf();bf="warning",ar={wasm:{},webgl:{},webgpu:{},versions:{common:gf},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);bf=n}},get logLevel(){return bf}};Object.defineProperty(ar,"logLevel",{enumerable:!0})});var De,vf=q(()=>{"use strict";Ls();De=ar});var wf,_f,xf=q(()=>{"use strict";wf=(n,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=n.dims[3],r.height=n.dims[2];let t=r.getContext("2d");if(t!=null){let i,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],o=n.dims[3]):(i=n.dims[3],o=n.dims[2]);let s=e?.format!==void 0?e.format:"RGB",a=e?.norm,u,d;a===void 0||a.mean===void 0?u=[255,255,255,255]:typeof a.mean=="number"?u=[a.mean,a.mean,a.mean,a.mean]:(u=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(u[3]=a.mean[3])),a===void 0||a.bias===void 0?d=[0,0,0,0]:typeof a.bias=="number"?d=[a.bias,a.bias,a.bias,a.bias]:(d=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(d[3]=a.bias[3]));let m=o*i,b=0,w=m,x=m*2,$=-1;s==="RGBA"?(b=0,w=m,x=m*2,$=m*3):s==="RGB"?(b=0,w=m,x=m*2):s==="RBG"&&(b=0,x=m,w=m*2);for(let I=0;I{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),t;if(r!=null){let i,o,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],o=n.dims[1],s=n.dims[3]):(i=n.dims[3],o=n.dims[2],s=n.dims[1]);let a=e!==void 0&&e.format!==void 0?e.format:"RGB",u=e?.norm,d,m;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?m=[0,0,0,0]:typeof u.bias=="number"?m=[u.bias,u.bias,u.bias,u.bias]:(m=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(m[3]=u.bias[3]));let b=o*i;if(e!==void 0&&(e.format!==void 0&&s===4&&e.format!=="RGBA"||s===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,x=0,$=1,I=2,A=3,k=0,P=b,z=b*2,U=-1;a==="RGBA"?(k=0,P=b,z=b*2,U=b*3):a==="RGB"?(k=0,P=b,z=b*2):a==="RBG"&&(k=0,z=b,P=b*2),t=r.createImageData(i,o);for(let F=0;F{"use strict";oa();js=(n,e)=>{if(n===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:t}=e,i=e.norm??{mean:255,bias:0},o,s;typeof i.mean=="number"?o=[i.mean,i.mean,i.mean,i.mean]:o=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let a=e.format!==void 0?e.format:"RGBA",u=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",d=r*t,m=u==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),b=4,w=0,x=1,$=2,I=3,A=0,k=d,P=d*2,z=-1;a==="RGB"&&(b=3,w=0,x=1,$=2,I=-1),u==="RGBA"?z=d*3:u==="RBG"?(A=0,P=d,k=d*2):u==="BGR"&&(P=0,k=d,A=d*2);for(let F=0;F{let r=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,t=typeof ImageData<"u"&&n instanceof ImageData,i=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,o=typeof n=="string",s,a=e??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=m=>m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(r){let m=u();m.width=n.width,m.height=n.height;let b=d(m);if(b!=null){let w=n.height,x=n.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(w=e.resizedHeight,x=e.resizedWidth),e!==void 0){if(a=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=w,a.width=x}else a.tensorFormat="RGBA",a.height=w,a.width=x;b.drawImage(n,0,0),s=b.getImageData(0,0,x,w).data}else throw new Error("Can not access image data")}else if(t){let m,b;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(m=e.resizedHeight,b=e.resizedWidth):(m=n.height,b=n.width),e!==void 0&&(a=e),a.format="RGBA",a.height=m,a.width=b,e!==void 0){let w=u();w.width=b,w.height=m;let x=d(w);if(x!=null)x.putImageData(n,0,0),s=x.getImageData(0,0,b,m).data;else throw new Error("Can not access image data")}else s=n.data}else if(i){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=u();m.width=n.width,m.height=n.height;let b=d(m);if(b!=null){let w=n.height,x=n.width;return b.drawImage(n,0,0,x,w),s=b.getImageData(0,0,x,w).data,a.height=w,a.width=x,js(s,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((m,b)=>{let w=u(),x=d(w);if(!n||!x)return b();let $=new Image;$.crossOrigin="Anonymous",$.src=n,$.onload=()=>{w.width=$.width,w.height=$.height,x.drawImage($,0,0,w.width,w.height);let I=x.getImageData(0,0,w.width,w.height);a.height=w.height,a.width=w.width,m(js(I.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return js(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Tf=(n,e)=>{let{width:r,height:t,download:i,dispose:o}=e,s=[1,t,r,4];return new Ht({location:"texture",type:"float32",texture:n,dims:s,download:i,dispose:o})},Sf=(n,e)=>{let{dataType:r,dims:t,download:i,dispose:o}=e;return new Ht({location:"gpu-buffer",type:r??"float32",gpuBuffer:n,dims:t,download:i,dispose:o})},If=(n,e,r)=>new Ht({location:"cpu-pinned",type:n,data:e,dims:r??[e.length]})});var In,to,Af,Ef,Of=q(()=>{"use strict";In=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),to=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Af=!1,Ef=()=>{if(!Af){Af=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;n&&(In.set("int64",BigInt64Array),to.set(BigInt64Array,"int64")),e&&(In.set("uint64",BigUint64Array),to.set(BigUint64Array,"uint64")),r?(In.set("float16",Float16Array),to.set(Float16Array,"float16")):In.set("float16",Uint16Array)}}});var Pf,kf,Df=q(()=>{"use strict";oa();Pf=n=>{let e=1;for(let r=0;r{switch(n.location){case"cpu":return new Ht(n.type,n.data,e);case"cpu-pinned":return new Ht({location:"cpu-pinned",data:n.data,type:n.type,dims:e});case"texture":return new Ht({location:"texture",texture:n.texture,type:n.type,dims:e});case"gpu-buffer":return new Ht({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}}});var Ht,oa=q(()=>{"use strict";xf();Cf();Of();Df();Ht=class{constructor(e,r,t){Ef();let i,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,o=e.dims,e.location){case"cpu-pinned":{let a=In.get(i);if(!a)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool")throw new TypeError(`unsupported type "${i}" 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 a,u;if(typeof e=="string")if(i=e,u=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");a=r}else{let d=In.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&d===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?a=d.from(r,BigInt):a=d.from(r)}else if(r instanceof d)a=r;else throw new TypeError(`A ${i} tensor's data must be type of ${d}`)}else if(u=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")i="string",a=e;else if(d==="boolean")i="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{let d=to.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=d,a=e}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");o=u,this.cpuData=a,this.dataLocation="cpu"}let s=Pf(o);if(this.cpuData&&s!==this.cpuData.length)throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=o,this.size=s}static async fromImage(e,r){return $f(e,r)}static fromTexture(e,r){return Tf(e,r)}static fromGpuBuffer(e,r){return Sf(e,r)}static fromPinnedBuffer(e,r,t){return If(e,r,t)}toDataURL(e){return wf(this,e)}toImageData(e){return _f(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let 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 kf(this,e)}}});var Dt,aa=q(()=>{"use strict";oa();Dt=Ht});var sa,Bf,sr,Xt,Us=q(()=>{"use strict";Ls();sa=(n,e)=>{(typeof ar.trace>"u"?!ar.wasm.trace:!ar.trace)||console.timeStamp(`${n}::ORT::${e}`)},Bf=(n,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],t=!1;for(let i=0;i{(typeof ar.trace>"u"?!ar.wasm.trace:!ar.trace)||Bf("BEGIN",n)},Xt=n=>{(typeof ar.trace>"u"?!ar.wasm.trace:!ar.trace)||Bf("END",n)}});var ua,Rf=q(()=>{"use strict";ia();aa();Us();ua=class n{constructor(e){this.handler=e}async run(e,r,t){sr();let i={},o={};if(typeof e!="object"||e===null||e instanceof Dt||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Dt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let d of r){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,m=Object.getOwnPropertyNames(r);for(let b of this.outputNames)if(m.indexOf(b)!==-1){let w=r[b];(w===null||w instanceof Dt)&&(d=!0,s=!1,i[b]=w)}if(d){if(typeof t=="object"&&t!==null)o=t;else if(typeof t<"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 d of this.inputNames)if(typeof e[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(s)for(let d of this.outputNames)i[d]=null;let a=await this.handler.run(e,i,o),u={};for(let d in a)if(Object.hasOwnProperty.call(a,d)){let m=a[d];m instanceof Dt?u[d]=m:u[d]=new Dt(m.type,m.data,m.dims)}return Xt(),u}async release(){return this.handler.dispose()}static async create(e,r,t,i){sr();let o,s={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)s=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)s=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 m=e,b=0,w=e.byteLength;if(typeof r=="object"&&r!==null)s=r;else if(typeof r=="number"){if(b=r,!Number.isSafeInteger(b))throw new RangeError("'byteOffset' must be an integer.");if(b<0||b>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(w=e.byteLength-b,typeof t=="number"){if(w=t,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||b+w>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-b}].`);if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof t<"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(m,b,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,u]=await na(s),d=await a.createInferenceSessionHandler(o,u);return Xt(),new n(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var k1,zf=q(()=>{"use strict";Rf();k1=ua});var Mf=q(()=>{"use strict"});var Nf=q(()=>{"use strict"});var Lf=q(()=>{"use strict"});var jf=q(()=>{"use strict"});var D1,la,Uf=q(()=>{"use strict";ia();aa();D1="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",la=class n{constructor(e,r,t){this.handler=e,this.hasOptimizerModel=r,this.hasEvalModel=t}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 t=e.evalModel||"",i=e.optimizerModel||"",o=r||{},[s,a]=await na(o);if(s.createTrainingSessionHandler){let u=await s.createTrainingSessionHandler(e.checkpointState,e.trainModel,t,i,a);return new n(u,!!e.optimizerModel,!!e.evalModel)}else throw new Error(D1)}typeNarrowingForRunStep(e,r,t,i,o){let s={},a={};if(typeof t!="object"||t===null||t instanceof Dt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let u=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof Dt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");u=!1;for(let d of i){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);s[d]=null}if(typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,m=Object.getOwnPropertyNames(i);for(let b of r)if(m.indexOf(b)!==-1){let w=i[b];(w===null||w instanceof Dt)&&(d=!0,u=!1,s[b]=w)}if(d){if(typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else a=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let d of e)if(typeof t[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(u)for(let d of r)s[d]=null;return[s,a]}convertHandlerReturnTypeToMapOfTensors(e){let r={};for(let t in e)if(Object.hasOwnProperty.call(e,t)){let i=e[t];i instanceof Dt?r[t]=i:r[t]=new Dt(i.type,i.data,i.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,r,t){let[i,o]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,r,t),s=await this.handler.runTrainStep(e,i,o);return this.convertHandlerReturnTypeToMapOfTensors(s)}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,t){if(this.hasEvalModel){let[i,o]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,r,t),s=await this.handler.runEvalStep(e,i,o);return this.convertHandlerReturnTypeToMapOfTensors(s)}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 t=await this.getParametersSize(r);if(e.length!==4*t)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()}}});var B1,Ff=q(()=>{"use strict";Uf();B1=la});var Fs={};Tn(Fs,{InferenceSession:()=>k1,TRACE:()=>sa,TRACE_FUNC_BEGIN:()=>sr,TRACE_FUNC_END:()=>Xt,Tensor:()=>Dt,TrainingSession:()=>B1,env:()=>De,registerBackend:()=>rn});var Lt=q(()=>{"use strict";mf();vf();zf();aa();Mf();Nf();Us();Lf();jf();Ff()});function nn(n,e,r,t){if(e===void 0)return z1(n);if(r===void 0)da(n,e,1);else if(typeof r=="number"&&t===void 0)da(n,e,r);else if(typeof r=="string"&&t===void 0)da(n,r,1,e);else if(typeof r=="string"&&typeof t=="number")da(n,r,t,e);else throw new TypeError("input is valid")}function z1(n){return{verbose:nn.verbose.bind(null,n),info:nn.info.bind(null,n),warning:nn.warning.bind(null,n),error:nn.error.bind(null,n),fatal:nn.fatal.bind(null,n)}}function da(n,e,r,t){let i=ro[t||""]||ro[""];Gf[n]{"use strict";Vs=class{log(e,r,t){}},Gs=class{log(e,r,t){console.log(`${this.color(e)} ${t?"\x1B[35m"+t+"\x1B[0m ":""}${r}`)}color(e){switch(e){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${e}`)}}},Gf={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},R1={none:new Vs,console:new Gs},Wf={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},ro={"":Wf};(u=>{function n(d,m){u("verbose",d,m)}u.verbose=n;function e(d,m){u("info",d,m)}u.info=e;function r(d,m){u("warning",d,m)}u.warning=r;function t(d,m){u("error",d,m)}u.error=t;function i(d,m){u("fatal",d,m)}u.fatal=i;function o(d){ro={},s("",d||{})}u.reset=o;function s(d,m){if(d==="*")o(m);else{let b=ro[d]||Wf;ro[d]={provider:m.provider||b.provider,minimalSeverity:m.minimalSeverity||b.minimalSeverity,logDateTime:m.logDateTime===void 0?b.logDateTime:m.logDateTime,logSourceLocation:m.logSourceLocation===void 0?b.logSourceLocation:m.logSourceLocation}}}u.set=s;function a(d){let m={};d.logLevel&&(m.minimalSeverity=d.logLevel),s("",m)}u.setWithEnv=a})(nn||={});at=nn,fa=class{constructor(e,r,t,i,o,s){this.category=e;this.name=r;this.startTime=t;this.endCallback=i;this.timer=o;this.ctx=s}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},pa=class{constructor(e,r,t,i){this.category=e;this.name=r;this.startTime=t;this.endTime=i}},ha=class{constructor(e,r,t){this._started=!1;this._flushPointer=0;this._started=!1,this._maxNumberEvents=e===void 0?1e4:e,this._flushBatchSize=r===void 0?10:r,this._flushIntervalInMilliseconds=t===void 0?5e3:t}static create(e){return e===void 0?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=ca(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer{a.then(async m=>{o&&await o.end(),u(m)},async m=>{o&&await o.end(),d(m)})});if(!s&&o){let u=o.end();if(u&&typeof u.then=="function")return new Promise((d,m)=>{u.then(()=>{d(a)},b=>{m(b)})})}return a}begin(e,r,t){if(!this._started)throw new Error("profiler is not started yet");if(t===void 0){let i=ca();return this.flush(i),new fa(e,r,i,o=>this.endSync(o))}else{let i=t.beginTimer();return new fa(e,r,0,async o=>this.end(o),i,t)}}async end(e){let r=await e.checkTimer();this._timingEvents.length=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(let r=this._flushPointer;this._flushPointerperformance.now():Date.now});function Hf(n,e,r){for(let t of r){let i=t[0],o=t[1],s=t[2],a=t[3],u=t[4];if(n.opType===i){for(let d of e)if((d.domain===o||d.domain==="ai.onnx"&&o==="")&&M1(d.version,s))return{opImpl:a,opInit:u}}}throw new TypeError(`cannot resolve operator '${n.opType}' with opsets: ${e.map(t=>`${t.domain||"ai.onnx"} v${t.version}`).join(", ")}`)}function M1(n,e){if(e.endsWith("+")){let r=Number.parseInt(e.substring(0,e.length-1),10);return!isNaN(r)&&r<=n}else if(e.split("-").length===2){let r=e.split("-"),t=Number.parseInt(r[0],10),i=Number.parseInt(r[1],10);return!isNaN(t)&&!isNaN(i)&&t<=n&&n<=i}else return Number.parseInt(e,10)===n}var qf=q(()=>{"use strict"});var Kf=ht(Ws=>{"use strict";Ws.__esModule=!0;var N1=function(){function n(e){if(!e)throw new TypeError("Invalid argument; `value` has no value.");this.value=n.EMPTY,e&&n.isGuid(e)&&(this.value=e)}return n.isGuid=function(e){var r=e.toString();return e&&(e instanceof n||n.validator.test(r))},n.create=function(){return new n([n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-"))},n.createEmpty=function(){return new n("emptyguid")},n.parse=function(e){return new n(e)},n.raw=function(){return[n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-")},n.gen=function(e){for(var r="",t=0;t>>=0,(i=0<=n&&n<256)&&(t=Zf[n],t)?t:(r=nt(n,0,!0),i&&(Zf[n]=r),r)):(n|=0,(i=-128<=n&&n<128)&&(t=Xf[n],t)?t:(r=nt(n,n<0?-1:0,!1),i&&(Xf[n]=r),r))}function pr(n,e){if(isNaN(n))return e?Yr:$r;if(e){if(n<0)return Yr;if(n>=tp)return ip}else{if(n<=-Qf)return Zt;if(n+1>=Qf)return np}return n<0?pr(-n,e).neg():nt(n%hi|0,n/hi|0,e)}function nt(n,e,r){return new mt(n,e,r)}function qs(n,e,r){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(r=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?Yr:$r;if(r=r||10,r<2||360)throw Error("interior hyphen");if(t===0)return qs(n.substring(1),e,r).neg();for(var i=pr(ma(r,8)),o=$r,s=0;s{fr=null;try{fr=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}mt.prototype.__isLong__;Object.defineProperty(mt.prototype,"__isLong__",{value:!0});mt.isLong=jt;Xf={},Zf={};mt.fromInt=Cn;mt.fromNumber=pr;mt.fromBits=nt;ma=Math.pow;mt.fromString=qs;mt.fromValue=Tr;Jf=65536,L1=1<<24,hi=Jf*Jf,tp=hi*hi,Qf=tp/2,ep=Cn(L1),$r=Cn(0);mt.ZERO=$r;Yr=Cn(0,!0);mt.UZERO=Yr;pi=Cn(1);mt.ONE=pi;rp=Cn(1,!0);mt.UONE=rp;Hs=Cn(-1);mt.NEG_ONE=Hs;np=nt(-1,2147483647,!1);mt.MAX_VALUE=np;ip=nt(-1,-1,!0);mt.MAX_UNSIGNED_VALUE=ip;Zt=nt(0,-2147483648,!1);mt.MIN_VALUE=Zt;ue=mt.prototype;ue.toInt=function(){return this.unsigned?this.low>>>0:this.low};ue.toNumber=function(){return this.unsigned?(this.high>>>0)*hi+(this.low>>>0):this.high*hi+(this.low>>>0)};ue.toString=function(e){if(e=e||10,e<2||36>>0,m=d.toString(e);if(s=u,s.isZero())return m+a;for(;m.length<6;)m="0"+m;a=""+m+a}};ue.getHighBits=function(){return this.high};ue.getHighBitsUnsigned=function(){return this.high>>>0};ue.getLowBits=function(){return this.low};ue.getLowBitsUnsigned=function(){return this.low>>>0};ue.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Zt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,r=31;r>0&&!(e&1<=0};ue.isOdd=function(){return(this.low&1)===1};ue.isEven=function(){return(this.low&1)===0};ue.equals=function(e){return jt(e)||(e=Tr(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};ue.eq=ue.equals;ue.notEquals=function(e){return!this.eq(e)};ue.neq=ue.notEquals;ue.ne=ue.notEquals;ue.lessThan=function(e){return this.comp(e)<0};ue.lt=ue.lessThan;ue.lessThanOrEqual=function(e){return this.comp(e)<=0};ue.lte=ue.lessThanOrEqual;ue.le=ue.lessThanOrEqual;ue.greaterThan=function(e){return this.comp(e)>0};ue.gt=ue.greaterThan;ue.greaterThanOrEqual=function(e){return this.comp(e)>=0};ue.gte=ue.greaterThanOrEqual;ue.ge=ue.greaterThanOrEqual;ue.compare=function(e){if(jt(e)||(e=Tr(e)),this.eq(e))return 0;var r=this.isNegative(),t=e.isNegative();return r&&!t?-1:!r&&t?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};ue.comp=ue.compare;ue.negate=function(){return!this.unsigned&&this.eq(Zt)?Zt:this.not().add(pi)};ue.neg=ue.negate;ue.add=function(e){jt(e)||(e=Tr(e));var r=this.high>>>16,t=this.high&65535,i=this.low>>>16,o=this.low&65535,s=e.high>>>16,a=e.high&65535,u=e.low>>>16,d=e.low&65535,m=0,b=0,w=0,x=0;return x+=o+d,w+=x>>>16,x&=65535,w+=i+u,b+=w>>>16,w&=65535,b+=t+a,m+=b>>>16,b&=65535,m+=r+s,m&=65535,nt(w<<16|x,m<<16|b,this.unsigned)};ue.subtract=function(e){return jt(e)||(e=Tr(e)),this.add(e.neg())};ue.sub=ue.subtract;ue.multiply=function(e){if(this.isZero())return this;if(jt(e)||(e=Tr(e)),fr){var r=fr.mul(this.low,this.high,e.low,e.high);return nt(r,fr.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Yr:$r;if(this.eq(Zt))return e.isOdd()?Zt:$r;if(e.eq(Zt))return this.isOdd()?Zt:$r;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(ep)&&e.lt(ep))return pr(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,i=this.high&65535,o=this.low>>>16,s=this.low&65535,a=e.high>>>16,u=e.high&65535,d=e.low>>>16,m=e.low&65535,b=0,w=0,x=0,$=0;return $+=s*m,x+=$>>>16,$&=65535,x+=o*m,w+=x>>>16,x&=65535,x+=s*d,w+=x>>>16,x&=65535,w+=i*m,b+=w>>>16,w&=65535,w+=o*d,b+=w>>>16,w&=65535,w+=s*u,b+=w>>>16,w&=65535,b+=t*m+i*d+o*u+s*a,b&=65535,nt(x<<16|$,b<<16|w,this.unsigned)};ue.mul=ue.multiply;ue.divide=function(e){if(jt(e)||(e=Tr(e)),e.isZero())throw Error("division by zero");if(fr){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var r=(this.unsigned?fr.div_u:fr.div_s)(this.low,this.high,e.low,e.high);return nt(r,fr.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Yr:$r;var t,i,o;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Yr;if(e.gt(this.shru(1)))return rp;o=Yr}else{if(this.eq(Zt)){if(e.eq(pi)||e.eq(Hs))return Zt;if(e.eq(Zt))return pi;var s=this.shr(1);return t=s.div(e).shl(1),t.eq($r)?e.isNegative()?pi:Hs:(i=this.sub(e.mul(t)),o=t.add(i.div(e)),o)}else if(e.eq(Zt))return this.unsigned?Yr:$r;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();o=$r}for(i=this;i.gte(e);){t=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(t)/Math.LN2),u=a<=48?1:ma(2,a-48),d=pr(t),m=d.mul(e);m.isNegative()||m.gt(i);)t-=u,d=pr(t,this.unsigned),m=d.mul(e);d.isZero()&&(d=pi),o=o.add(d),i=i.sub(m)}return o};ue.div=ue.divide;ue.modulo=function(e){if(jt(e)||(e=Tr(e)),fr){var r=(this.unsigned?fr.rem_u:fr.rem_s)(this.low,this.high,e.low,e.high);return nt(r,fr.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};ue.mod=ue.modulo;ue.rem=ue.modulo;ue.not=function(){return nt(~this.low,~this.high,this.unsigned)};ue.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};ue.clz=ue.countLeadingZeros;ue.countTrailingZeros=function(){return this.low?Yf(this.low):Yf(this.high)+32};ue.ctz=ue.countTrailingZeros;ue.and=function(e){return jt(e)||(e=Tr(e)),nt(this.low&e.low,this.high&e.high,this.unsigned)};ue.or=function(e){return jt(e)||(e=Tr(e)),nt(this.low|e.low,this.high|e.high,this.unsigned)};ue.xor=function(e){return jt(e)||(e=Tr(e)),nt(this.low^e.low,this.high^e.high,this.unsigned)};ue.shiftLeft=function(e){return jt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?nt(this.low<>>32-e,this.unsigned):nt(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):nt(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};ue.shr=ue.shiftRight;ue.shiftRightUnsigned=function(e){return jt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?nt(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?nt(this.high,0,this.unsigned):nt(this.high>>>e-32,0,this.unsigned)};ue.shru=ue.shiftRightUnsigned;ue.shr_u=ue.shiftRightUnsigned;ue.rotateLeft=function(e){var r;return jt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?nt(this.high,this.low,this.unsigned):e<32?(r=32-e,nt(this.low<>>r,this.high<>>r,this.unsigned)):(e-=32,r=32-e,nt(this.high<>>r,this.low<>>r,this.unsigned))};ue.rotl=ue.rotateLeft;ue.rotateRight=function(e){var r;return jt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?nt(this.high,this.low,this.unsigned):e<32?(r=32-e,nt(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,r=32-e,nt(this.low<>>e,this.high<>>e,this.unsigned))};ue.rotr=ue.rotateRight;ue.toSigned=function(){return this.unsigned?nt(this.low,this.high,!1):this};ue.toUnsigned=function(){return this.unsigned?this:nt(this.low,this.high,!0)};ue.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};ue.toBytesLE=function(){var e=this.high,r=this.low;return[r&255,r>>>8&255,r>>>16&255,r>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};ue.toBytesBE=function(){var e=this.high,r=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,r>>>24,r>>>16&255,r>>>8&255,r&255]};mt.fromBytes=function(e,r,t){return t?mt.fromBytesLE(e,r):mt.fromBytesBE(e,r)};mt.fromBytesLE=function(e,r){return new mt(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,r)};mt.fromBytesBE=function(e,r){return new mt(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],r)};Xr=mt});var K,ga=q(()=>{K={};K.Offset;K.Table;K.SIZEOF_SHORT=2;K.SIZEOF_INT=4;K.FILE_IDENTIFIER_LENGTH=4;K.SIZE_PREFIX_LENGTH=4;K.Encoding={UTF8_BYTES:1,UTF16_STRING:2};K.int32=new Int32Array(2);K.float32=new Float32Array(K.int32.buffer);K.float64=new Float64Array(K.int32.buffer);K.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;K.Long=function(n,e){this.low=n|0,this.high=e|0};K.Long.create=function(n,e){return n==0&&e==0?K.Long.ZERO:new K.Long(n,e)};K.Long.prototype.toFloat64=function(){return(this.low>>>0)+this.high*4294967296};K.Long.prototype.equals=function(n){return this.low==n.low&&this.high==n.high};K.Long.ZERO=new K.Long(0,0);K.Builder=function(n){if(n)var e=n;else var e=1024;this.bb=K.ByteBuffer.allocate(e),this.space=e,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1};K.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1};K.Builder.prototype.forceDefaults=function(n){this.force_defaults=n};K.Builder.prototype.dataBuffer=function(){return this.bb};K.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())};K.Builder.prototype.prep=function(n,e){n>this.minalign&&(this.minalign=n);for(var r=~(this.bb.capacity()-this.space+e)+1&n-1;this.space=0&&this.vtable[e]==0;e--);for(var r=e+1;e>=0;e--)this.addInt16(this.vtable[e]!=0?n-this.vtable[e]:0);var t=2;this.addInt16(n-this.object_start);var i=(r+t)*K.SIZEOF_SHORT;this.addInt16(i);var o=0,s=this.space;e:for(e=0;e=0;o--)this.writeInt8(i.charCodeAt(o))}this.prep(this.minalign,K.SIZEOF_INT+t),this.addOffset(n),t&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)};K.Builder.prototype.finishSizePrefixed=function(n,e){this.finish(n,e,!0)};K.Builder.prototype.requiredField=function(n,e){var r=this.bb.capacity()-n,t=r-this.bb.readInt32(r),i=this.bb.readInt16(t+e)!=0;if(!i)throw new Error("FlatBuffers: field "+e+" must be set")};K.Builder.prototype.startVector=function(n,e,r){this.notNested(),this.vector_num_elems=e,this.prep(K.SIZEOF_INT,n*e),this.prep(r,n*e)};K.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()};K.Builder.prototype.createString=function(n){if(n instanceof Uint8Array)var e=n;else for(var e=[],r=0;r=56320)t=i;else{var o=n.charCodeAt(r++);t=(i<<10)+o+(65536-56623104-56320)}t<128?e.push(t):(t<2048?e.push(t>>6&31|192):(t<65536?e.push(t>>12&15|224):e.push(t>>18&7|240,t>>12&63|128),e.push(t>>6&63|128)),e.push(t&63|128))}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(var r=0,s=this.space,a=this.bb.bytes();r>24};K.ByteBuffer.prototype.readUint8=function(n){return this.bytes_[n]};K.ByteBuffer.prototype.readInt16=function(n){return this.readUint16(n)<<16>>16};K.ByteBuffer.prototype.readUint16=function(n){return this.bytes_[n]|this.bytes_[n+1]<<8};K.ByteBuffer.prototype.readInt32=function(n){return this.bytes_[n]|this.bytes_[n+1]<<8|this.bytes_[n+2]<<16|this.bytes_[n+3]<<24};K.ByteBuffer.prototype.readUint32=function(n){return this.readInt32(n)>>>0};K.ByteBuffer.prototype.readInt64=function(n){return new K.Long(this.readInt32(n),this.readInt32(n+4))};K.ByteBuffer.prototype.readUint64=function(n){return new K.Long(this.readUint32(n),this.readUint32(n+4))};K.ByteBuffer.prototype.readFloat32=function(n){return K.int32[0]=this.readInt32(n),K.float32[0]};K.ByteBuffer.prototype.readFloat64=function(n){return K.int32[K.isLittleEndian?0:1]=this.readInt32(n),K.int32[K.isLittleEndian?1:0]=this.readInt32(n+4),K.float64[0]};K.ByteBuffer.prototype.writeInt8=function(n,e){this.bytes_[n]=e};K.ByteBuffer.prototype.writeUint8=function(n,e){this.bytes_[n]=e};K.ByteBuffer.prototype.writeInt16=function(n,e){this.bytes_[n]=e,this.bytes_[n+1]=e>>8};K.ByteBuffer.prototype.writeUint16=function(n,e){this.bytes_[n]=e,this.bytes_[n+1]=e>>8};K.ByteBuffer.prototype.writeInt32=function(n,e){this.bytes_[n]=e,this.bytes_[n+1]=e>>8,this.bytes_[n+2]=e>>16,this.bytes_[n+3]=e>>24};K.ByteBuffer.prototype.writeUint32=function(n,e){this.bytes_[n]=e,this.bytes_[n+1]=e>>8,this.bytes_[n+2]=e>>16,this.bytes_[n+3]=e>>24};K.ByteBuffer.prototype.writeInt64=function(n,e){this.writeInt32(n,e.low),this.writeInt32(n+4,e.high)};K.ByteBuffer.prototype.writeUint64=function(n,e){this.writeUint32(n,e.low),this.writeUint32(n+4,e.high)};K.ByteBuffer.prototype.writeFloat32=function(n,e){K.float32[0]=e,this.writeInt32(n,K.int32[0])};K.ByteBuffer.prototype.writeFloat64=function(n,e){K.float64[0]=e,this.writeInt32(n,K.int32[K.isLittleEndian?0:1]),this.writeInt32(n+4,K.int32[K.isLittleEndian?1:0])};K.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10)+55296,(o&1024-1)+56320))}return t};K.ByteBuffer.prototype.__indirect=function(n){return n+this.readInt32(n)};K.ByteBuffer.prototype.__vector=function(n){return n+this.readInt32(n)+K.SIZEOF_INT};K.ByteBuffer.prototype.__vector_len=function(n){return this.readInt32(n+this.readInt32(n))};K.ByteBuffer.prototype.__has_identifier=function(n){if(n.length!=K.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+K.FILE_IDENTIFIER_LENGTH);for(var e=0;e{"use strict";ga();(e=>{let n;(t=>{let r;(o=>{let i;(z=>(z[z.UNDEFINED=0]="UNDEFINED",z[z.FLOAT=1]="FLOAT",z[z.INT=2]="INT",z[z.STRING=3]="STRING",z[z.TENSOR=4]="TENSOR",z[z.GRAPH=5]="GRAPH",z[z.FLOATS=6]="FLOATS",z[z.INTS=7]="INTS",z[z.STRINGS=8]="STRINGS",z[z.TENSORS=9]="TENSORS",z[z.GRAPHS=10]="GRAPHS",z[z.SPARSE_TENSOR=11]="SPARSE_TENSOR",z[z.SPARSE_TENSORS=12]="SPARSE_TENSORS"))(i=o.AttributeType||={})})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{let i;(d=>(d[d.UNKNOWN=0]="UNKNOWN",d[d.VALUE=1]="VALUE",d[d.PARAM=2]="PARAM"))(i=o.DimensionValueType||={})})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{let i;(se=>(se[se.UNDEFINED=0]="UNDEFINED",se[se.FLOAT=1]="FLOAT",se[se.UINT8=2]="UINT8",se[se.INT8=3]="INT8",se[se.UINT16=4]="UINT16",se[se.INT16=5]="INT16",se[se.INT32=6]="INT32",se[se.INT64=7]="INT64",se[se.STRING=8]="STRING",se[se.BOOL=9]="BOOL",se[se.FLOAT16=10]="FLOAT16",se[se.DOUBLE=11]="DOUBLE",se[se.UINT32=12]="UINT32",se[se.UINT64=13]="UINT64",se[se.COMPLEX64=14]="COMPLEX64",se[se.COMPLEX128=15]="COMPLEX128",se[se.BFLOAT16=16]="BFLOAT16",se[se.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",se[se.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",se[se.FLOAT8E5M2=19]="FLOAT8E5M2",se[se.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"))(i=o.TensorDataType||={})})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{let i;(u=>(u[u.Primitive=0]="Primitive",u[u.Fused=1]="Fused"))(i=o.NodeType||={})})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{let i;(m=>(m[m.NONE=0]="NONE",m[m.tensor_type=1]="tensor_type",m[m.sequence_type=2]="sequence_type",m[m.map_type=3]="map_type"))(i=o.TypeInfoValue||={})})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsShape(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsShape(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}dim(a,u){let d=this.bb.__offset(this.bb_pos,4);return d?(u||new e.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}dimLength(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__vector_len(this.bb_pos+a):0}static startShape(a){a.startObject(1)}static addDim(a,u){a.addFieldOffset(0,u,0)}static createDimVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startDimVector(a,u){a.startVector(4,u,4)}static endShape(a){return a.endObject()}static createShape(a,u){return i.startShape(a),i.addDim(a,u),i.endShape(a)}}o.Shape=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsDimension(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsDimension(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}value(a){let u=this.bb.__offset(this.bb_pos,4);return u?(a||new e.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}denotation(a){let u=this.bb.__offset(this.bb_pos,6);return u?this.bb.__string(this.bb_pos+u,a):null}static startDimension(a){a.startObject(2)}static addValue(a,u){a.addFieldOffset(0,u,0)}static addDenotation(a,u){a.addFieldOffset(1,u,0)}static endDimension(a){return a.endObject()}static createDimension(a,u,d){return i.startDimension(a),i.addValue(a,u),i.addDenotation(a,d),i.endDimension(a)}}o.Dimension=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsDimensionValue(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsDimensionValue(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}dimType(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.readInt8(this.bb_pos+a):0}dimValue(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.readInt64(this.bb_pos+a):this.bb.createLong(0,0)}dimParam(a){let u=this.bb.__offset(this.bb_pos,8);return u?this.bb.__string(this.bb_pos+u,a):null}static startDimensionValue(a){a.startObject(3)}static addDimType(a,u){a.addFieldInt8(0,u,0)}static addDimValue(a,u){a.addFieldInt64(1,u,a.createLong(0,0))}static addDimParam(a,u){a.addFieldOffset(2,u,0)}static endDimensionValue(a){return a.endObject()}static createDimensionValue(a,u,d,m){return i.startDimensionValue(a),i.addDimType(a,u),i.addDimValue(a,d),i.addDimParam(a,m),i.endDimensionValue(a)}}o.DimensionValue=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsTensorTypeAndShape(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsTensorTypeAndShape(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}elemType(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.readInt32(this.bb_pos+a):0}shape(a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new e.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}static startTensorTypeAndShape(a){a.startObject(2)}static addElemType(a,u){a.addFieldInt32(0,u,0)}static addShape(a,u){a.addFieldOffset(1,u,0)}static endTensorTypeAndShape(a){return a.endObject()}static createTensorTypeAndShape(a,u,d){return i.startTensorTypeAndShape(a),i.addElemType(a,u),i.addShape(a,d),i.endTensorTypeAndShape(a)}}o.TensorTypeAndShape=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsMapType(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsMapType(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}keyType(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.readInt32(this.bb_pos+a):0}valueType(a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}static startMapType(a){a.startObject(2)}static addKeyType(a,u){a.addFieldInt32(0,u,0)}static addValueType(a,u){a.addFieldOffset(1,u,0)}static endMapType(a){return a.endObject()}static createMapType(a,u,d){return i.startMapType(a),i.addKeyType(a,u),i.addValueType(a,d),i.endMapType(a)}}o.MapType=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsSequenceType(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsSequenceType(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}elemType(a){let u=this.bb.__offset(this.bb_pos,4);return u?(a||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}static startSequenceType(a){a.startObject(1)}static addElemType(a,u){a.addFieldOffset(0,u,0)}static endSequenceType(a){return a.endObject()}static createSequenceType(a,u){return i.startSequenceType(a),i.addElemType(a,u),i.endSequenceType(a)}}o.SequenceType=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(a,u,d,m){return a.prep(4,12),a.writeInt32(m),a.writeInt32(d),a.writeInt32(u),a.offset()}}o.EdgeEnd=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsNodeEdge(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsNodeEdge(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}nodeIndex(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.readUint32(this.bb_pos+a):0}inputEdges(a,u){let d=this.bb.__offset(this.bb_pos,6);return d?(u||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+d)+a*12,this.bb):null}inputEdgesLength(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__vector_len(this.bb_pos+a):0}outputEdges(a,u){let d=this.bb.__offset(this.bb_pos,8);return d?(u||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+d)+a*12,this.bb):null}outputEdgesLength(){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__vector_len(this.bb_pos+a):0}static startNodeEdge(a){a.startObject(3)}static addNodeIndex(a,u){a.addFieldInt32(0,u,0)}static addInputEdges(a,u){a.addFieldOffset(1,u,0)}static startInputEdgesVector(a,u){a.startVector(12,u,4)}static addOutputEdges(a,u){a.addFieldOffset(2,u,0)}static startOutputEdgesVector(a,u){a.startVector(12,u,4)}static endNodeEdge(a){return a.endObject()}static createNodeEdge(a,u,d,m){return i.startNodeEdge(a),i.addNodeIndex(a,u),i.addInputEdges(a,d),i.addOutputEdges(a,m),i.endNodeEdge(a)}}o.NodeEdge=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsNode(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsNode(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}name(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}docString(a){let u=this.bb.__offset(this.bb_pos,6);return u?this.bb.__string(this.bb_pos+u,a):null}domain(a){let u=this.bb.__offset(this.bb_pos,8);return u?this.bb.__string(this.bb_pos+u,a):null}sinceVersion(){let a=this.bb.__offset(this.bb_pos,10);return a?this.bb.readInt32(this.bb_pos+a):0}index(){let a=this.bb.__offset(this.bb_pos,12);return a?this.bb.readUint32(this.bb_pos+a):0}opType(a){let u=this.bb.__offset(this.bb_pos,14);return u?this.bb.__string(this.bb_pos+u,a):null}type(){let a=this.bb.__offset(this.bb_pos,16);return a?this.bb.readInt32(this.bb_pos+a):0}executionProviderType(a){let u=this.bb.__offset(this.bb_pos,18);return u?this.bb.__string(this.bb_pos+u,a):null}inputs(a,u){let d=this.bb.__offset(this.bb_pos,20);return d?this.bb.__string(this.bb.__vector(this.bb_pos+d)+a*4,u):null}inputsLength(){let a=this.bb.__offset(this.bb_pos,20);return a?this.bb.__vector_len(this.bb_pos+a):0}outputs(a,u){let d=this.bb.__offset(this.bb_pos,22);return d?this.bb.__string(this.bb.__vector(this.bb_pos+d)+a*4,u):null}outputsLength(){let a=this.bb.__offset(this.bb_pos,22);return a?this.bb.__vector_len(this.bb_pos+a):0}attributes(a,u){let d=this.bb.__offset(this.bb_pos,24);return d?(u||new e.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}attributesLength(){let a=this.bb.__offset(this.bb_pos,24);return a?this.bb.__vector_len(this.bb_pos+a):0}inputArgCounts(a){let u=this.bb.__offset(this.bb_pos,26);return u?this.bb.readInt32(this.bb.__vector(this.bb_pos+u)+a*4):0}inputArgCountsLength(){let a=this.bb.__offset(this.bb_pos,26);return a?this.bb.__vector_len(this.bb_pos+a):0}inputArgCountsArray(){let a=this.bb.__offset(this.bb_pos,26);return a?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+a),this.bb.__vector_len(this.bb_pos+a)):null}implicitInputs(a,u){let d=this.bb.__offset(this.bb_pos,28);return d?this.bb.__string(this.bb.__vector(this.bb_pos+d)+a*4,u):null}implicitInputsLength(){let a=this.bb.__offset(this.bb_pos,28);return a?this.bb.__vector_len(this.bb_pos+a):0}static startNode(a){a.startObject(13)}static addName(a,u){a.addFieldOffset(0,u,0)}static addDocString(a,u){a.addFieldOffset(1,u,0)}static addDomain(a,u){a.addFieldOffset(2,u,0)}static addSinceVersion(a,u){a.addFieldInt32(3,u,0)}static addIndex(a,u){a.addFieldInt32(4,u,0)}static addOpType(a,u){a.addFieldOffset(5,u,0)}static addType(a,u){a.addFieldInt32(6,u,0)}static addExecutionProviderType(a,u){a.addFieldOffset(7,u,0)}static addInputs(a,u){a.addFieldOffset(8,u,0)}static createInputsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startInputsVector(a,u){a.startVector(4,u,4)}static addOutputs(a,u){a.addFieldOffset(9,u,0)}static createOutputsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startOutputsVector(a,u){a.startVector(4,u,4)}static addAttributes(a,u){a.addFieldOffset(10,u,0)}static createAttributesVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startAttributesVector(a,u){a.startVector(4,u,4)}static addInputArgCounts(a,u){a.addFieldOffset(11,u,0)}static createInputArgCountsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addInt32(u[d]);return a.endVector()}static startInputArgCountsVector(a,u){a.startVector(4,u,4)}static addImplicitInputs(a,u){a.addFieldOffset(12,u,0)}static createImplicitInputsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startImplicitInputsVector(a,u){a.startVector(4,u,4)}static endNode(a){return a.endObject()}static createNode(a,u,d,m,b,w,x,$,I,A,k,P,z,U){return i.startNode(a),i.addName(a,u),i.addDocString(a,d),i.addDomain(a,m),i.addSinceVersion(a,b),i.addIndex(a,w),i.addOpType(a,x),i.addType(a,$),i.addExecutionProviderType(a,I),i.addInputs(a,A),i.addOutputs(a,k),i.addAttributes(a,P),i.addInputArgCounts(a,z),i.addImplicitInputs(a,U),i.endNode(a)}}o.Node=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsValueInfo(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsValueInfo(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}name(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}docString(a){let u=this.bb.__offset(this.bb_pos,6);return u?this.bb.__string(this.bb_pos+u,a):null}type(a){let u=this.bb.__offset(this.bb_pos,8);return u?(a||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}static startValueInfo(a){a.startObject(3)}static addName(a,u){a.addFieldOffset(0,u,0)}static addDocString(a,u){a.addFieldOffset(1,u,0)}static addType(a,u){a.addFieldOffset(2,u,0)}static endValueInfo(a){return a.endObject()}static createValueInfo(a,u,d,m){return i.startValueInfo(a),i.addName(a,u),i.addDocString(a,d),i.addType(a,m),i.endValueInfo(a)}}o.ValueInfo=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsTypeInfo(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsTypeInfo(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}denotation(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}valueType(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.readUint8(this.bb_pos+a):0}value(a){let u=this.bb.__offset(this.bb_pos,8);return u?this.bb.__union(a,this.bb_pos+u):null}static startTypeInfo(a){a.startObject(3)}static addDenotation(a,u){a.addFieldOffset(0,u,0)}static addValueType(a,u){a.addFieldInt8(1,u,0)}static addValue(a,u){a.addFieldOffset(2,u,0)}static endTypeInfo(a){return a.endObject()}static createTypeInfo(a,u,d,m){return i.startTypeInfo(a),i.addDenotation(a,u),i.addValueType(a,d),i.addValue(a,m),i.endTypeInfo(a)}}o.TypeInfo=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsOperatorSetId(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsOperatorSetId(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}domain(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}version(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.readInt64(this.bb_pos+a):this.bb.createLong(0,0)}static startOperatorSetId(a){a.startObject(2)}static addDomain(a,u){a.addFieldOffset(0,u,0)}static addVersion(a,u){a.addFieldInt64(1,u,a.createLong(0,0))}static endOperatorSetId(a){return a.endObject()}static createOperatorSetId(a,u,d){return i.startOperatorSetId(a),i.addDomain(a,u),i.addVersion(a,d),i.endOperatorSetId(a)}}o.OperatorSetId=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsTensor(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsTensor(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}name(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}docString(a){let u=this.bb.__offset(this.bb_pos,6);return u?this.bb.__string(this.bb_pos+u,a):null}dims(a){let u=this.bb.__offset(this.bb_pos,8);return u?this.bb.readInt64(this.bb.__vector(this.bb_pos+u)+a*8):this.bb.createLong(0,0)}dimsLength(){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__vector_len(this.bb_pos+a):0}dataType(){let a=this.bb.__offset(this.bb_pos,10);return a?this.bb.readInt32(this.bb_pos+a):0}rawData(a){let u=this.bb.__offset(this.bb_pos,12);return u?this.bb.readUint8(this.bb.__vector(this.bb_pos+u)+a):0}rawDataLength(){let a=this.bb.__offset(this.bb_pos,12);return a?this.bb.__vector_len(this.bb_pos+a):0}rawDataArray(){let a=this.bb.__offset(this.bb_pos,12);return a?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+a),this.bb.__vector_len(this.bb_pos+a)):null}stringData(a,u){let d=this.bb.__offset(this.bb_pos,14);return d?this.bb.__string(this.bb.__vector(this.bb_pos+d)+a*4,u):null}stringDataLength(){let a=this.bb.__offset(this.bb_pos,14);return a?this.bb.__vector_len(this.bb_pos+a):0}static startTensor(a){a.startObject(6)}static addName(a,u){a.addFieldOffset(0,u,0)}static addDocString(a,u){a.addFieldOffset(1,u,0)}static addDims(a,u){a.addFieldOffset(2,u,0)}static createDimsVector(a,u){a.startVector(8,u.length,8);for(let d=u.length-1;d>=0;d--)a.addInt64(u[d]);return a.endVector()}static startDimsVector(a,u){a.startVector(8,u,8)}static addDataType(a,u){a.addFieldInt32(3,u,0)}static addRawData(a,u){a.addFieldOffset(4,u,0)}static createRawDataVector(a,u){a.startVector(1,u.length,1);for(let d=u.length-1;d>=0;d--)a.addInt8(u[d]);return a.endVector()}static startRawDataVector(a,u){a.startVector(1,u,1)}static addStringData(a,u){a.addFieldOffset(5,u,0)}static createStringDataVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startStringDataVector(a,u){a.startVector(4,u,4)}static endTensor(a){return a.endObject()}static createTensor(a,u,d,m,b,w,x){return i.startTensor(a),i.addName(a,u),i.addDocString(a,d),i.addDims(a,m),i.addDataType(a,b),i.addRawData(a,w),i.addStringData(a,x),i.endTensor(a)}}o.Tensor=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsSparseTensor(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsSparseTensor(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}values(a){let u=this.bb.__offset(this.bb_pos,4);return u?(a||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}indices(a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}dims(a){let u=this.bb.__offset(this.bb_pos,8);return u?this.bb.readInt64(this.bb.__vector(this.bb_pos+u)+a*8):this.bb.createLong(0,0)}dimsLength(){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__vector_len(this.bb_pos+a):0}static startSparseTensor(a){a.startObject(3)}static addValues(a,u){a.addFieldOffset(0,u,0)}static addIndices(a,u){a.addFieldOffset(1,u,0)}static addDims(a,u){a.addFieldOffset(2,u,0)}static createDimsVector(a,u){a.startVector(8,u.length,8);for(let d=u.length-1;d>=0;d--)a.addInt64(u[d]);return a.endVector()}static startDimsVector(a,u){a.startVector(8,u,8)}static endSparseTensor(a){return a.endObject()}static createSparseTensor(a,u,d,m){return i.startSparseTensor(a),i.addValues(a,u),i.addIndices(a,d),i.addDims(a,m),i.endSparseTensor(a)}}o.SparseTensor=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsAttribute(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsAttribute(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}name(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}docString(a){let u=this.bb.__offset(this.bb_pos,6);return u?this.bb.__string(this.bb_pos+u,a):null}type(){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.readInt32(this.bb_pos+a):0}f(){let a=this.bb.__offset(this.bb_pos,10);return a?this.bb.readFloat32(this.bb_pos+a):0}i(){let a=this.bb.__offset(this.bb_pos,12);return a?this.bb.readInt64(this.bb_pos+a):this.bb.createLong(0,0)}s(a){let u=this.bb.__offset(this.bb_pos,14);return u?this.bb.__string(this.bb_pos+u,a):null}t(a){let u=this.bb.__offset(this.bb_pos,16);return u?(a||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}g(a){let u=this.bb.__offset(this.bb_pos,18);return u?(a||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}floats(a){let u=this.bb.__offset(this.bb_pos,20);return u?this.bb.readFloat32(this.bb.__vector(this.bb_pos+u)+a*4):0}floatsLength(){let a=this.bb.__offset(this.bb_pos,20);return a?this.bb.__vector_len(this.bb_pos+a):0}floatsArray(){let a=this.bb.__offset(this.bb_pos,20);return a?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+a),this.bb.__vector_len(this.bb_pos+a)):null}ints(a){let u=this.bb.__offset(this.bb_pos,22);return u?this.bb.readInt64(this.bb.__vector(this.bb_pos+u)+a*8):this.bb.createLong(0,0)}intsLength(){let a=this.bb.__offset(this.bb_pos,22);return a?this.bb.__vector_len(this.bb_pos+a):0}strings(a,u){let d=this.bb.__offset(this.bb_pos,24);return d?this.bb.__string(this.bb.__vector(this.bb_pos+d)+a*4,u):null}stringsLength(){let a=this.bb.__offset(this.bb_pos,24);return a?this.bb.__vector_len(this.bb_pos+a):0}tensors(a,u){let d=this.bb.__offset(this.bb_pos,26);return d?(u||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}tensorsLength(){let a=this.bb.__offset(this.bb_pos,26);return a?this.bb.__vector_len(this.bb_pos+a):0}graphs(a,u){let d=this.bb.__offset(this.bb_pos,28);return d?(u||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}graphsLength(){let a=this.bb.__offset(this.bb_pos,28);return a?this.bb.__vector_len(this.bb_pos+a):0}static startAttribute(a){a.startObject(13)}static addName(a,u){a.addFieldOffset(0,u,0)}static addDocString(a,u){a.addFieldOffset(1,u,0)}static addType(a,u){a.addFieldInt32(2,u,0)}static addF(a,u){a.addFieldFloat32(3,u,0)}static addI(a,u){a.addFieldInt64(4,u,a.createLong(0,0))}static addS(a,u){a.addFieldOffset(5,u,0)}static addT(a,u){a.addFieldOffset(6,u,0)}static addG(a,u){a.addFieldOffset(7,u,0)}static addFloats(a,u){a.addFieldOffset(8,u,0)}static createFloatsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addFloat32(u[d]);return a.endVector()}static startFloatsVector(a,u){a.startVector(4,u,4)}static addInts(a,u){a.addFieldOffset(9,u,0)}static createIntsVector(a,u){a.startVector(8,u.length,8);for(let d=u.length-1;d>=0;d--)a.addInt64(u[d]);return a.endVector()}static startIntsVector(a,u){a.startVector(8,u,8)}static addStrings(a,u){a.addFieldOffset(10,u,0)}static createStringsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startStringsVector(a,u){a.startVector(4,u,4)}static addTensors(a,u){a.addFieldOffset(11,u,0)}static createTensorsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startTensorsVector(a,u){a.startVector(4,u,4)}static addGraphs(a,u){a.addFieldOffset(12,u,0)}static createGraphsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startGraphsVector(a,u){a.startVector(4,u,4)}static endAttribute(a){return a.endObject()}static createAttribute(a,u,d,m,b,w,x,$,I,A,k,P,z,U){return i.startAttribute(a),i.addName(a,u),i.addDocString(a,d),i.addType(a,m),i.addF(a,b),i.addI(a,w),i.addS(a,x),i.addT(a,$),i.addG(a,I),i.addFloats(a,A),i.addInts(a,k),i.addStrings(a,P),i.addTensors(a,z),i.addGraphs(a,U),i.endAttribute(a)}}o.Attribute=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsGraph(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsGraph(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}initializers(a,u){let d=this.bb.__offset(this.bb_pos,4);return d?(u||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}initializersLength(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__vector_len(this.bb_pos+a):0}nodeArgs(a,u){let d=this.bb.__offset(this.bb_pos,6);return d?(u||new e.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}nodeArgsLength(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__vector_len(this.bb_pos+a):0}nodes(a,u){let d=this.bb.__offset(this.bb_pos,8);return d?(u||new e.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}nodesLength(){let a=this.bb.__offset(this.bb_pos,8);return a?this.bb.__vector_len(this.bb_pos+a):0}maxNodeIndex(){let a=this.bb.__offset(this.bb_pos,10);return a?this.bb.readUint32(this.bb_pos+a):0}nodeEdges(a,u){let d=this.bb.__offset(this.bb_pos,12);return d?(u||new e.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}nodeEdgesLength(){let a=this.bb.__offset(this.bb_pos,12);return a?this.bb.__vector_len(this.bb_pos+a):0}inputs(a,u){let d=this.bb.__offset(this.bb_pos,14);return d?this.bb.__string(this.bb.__vector(this.bb_pos+d)+a*4,u):null}inputsLength(){let a=this.bb.__offset(this.bb_pos,14);return a?this.bb.__vector_len(this.bb_pos+a):0}outputs(a,u){let d=this.bb.__offset(this.bb_pos,16);return d?this.bb.__string(this.bb.__vector(this.bb_pos+d)+a*4,u):null}outputsLength(){let a=this.bb.__offset(this.bb_pos,16);return a?this.bb.__vector_len(this.bb_pos+a):0}sparseInitializers(a,u){let d=this.bb.__offset(this.bb_pos,18);return d?(u||new e.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}sparseInitializersLength(){let a=this.bb.__offset(this.bb_pos,18);return a?this.bb.__vector_len(this.bb_pos+a):0}static startGraph(a){a.startObject(8)}static addInitializers(a,u){a.addFieldOffset(0,u,0)}static createInitializersVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startInitializersVector(a,u){a.startVector(4,u,4)}static addNodeArgs(a,u){a.addFieldOffset(1,u,0)}static createNodeArgsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startNodeArgsVector(a,u){a.startVector(4,u,4)}static addNodes(a,u){a.addFieldOffset(2,u,0)}static createNodesVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startNodesVector(a,u){a.startVector(4,u,4)}static addMaxNodeIndex(a,u){a.addFieldInt32(3,u,0)}static addNodeEdges(a,u){a.addFieldOffset(4,u,0)}static createNodeEdgesVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startNodeEdgesVector(a,u){a.startVector(4,u,4)}static addInputs(a,u){a.addFieldOffset(5,u,0)}static createInputsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startInputsVector(a,u){a.startVector(4,u,4)}static addOutputs(a,u){a.addFieldOffset(6,u,0)}static createOutputsVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startOutputsVector(a,u){a.startVector(4,u,4)}static addSparseInitializers(a,u){a.addFieldOffset(7,u,0)}static createSparseInitializersVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startSparseInitializersVector(a,u){a.startVector(4,u,4)}static endGraph(a){return a.endObject()}static createGraph(a,u,d,m,b,w,x,$,I){return i.startGraph(a),i.addInitializers(a,u),i.addNodeArgs(a,d),i.addNodes(a,m),i.addMaxNodeIndex(a,b),i.addNodeEdges(a,w),i.addInputs(a,x),i.addOutputs(a,$),i.addSparseInitializers(a,I),i.endGraph(a)}}o.Graph=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsModel(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsModel(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}irVersion(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.readInt64(this.bb_pos+a):this.bb.createLong(0,0)}opsetImport(a,u){let d=this.bb.__offset(this.bb_pos,6);return d?(u||new e.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}opsetImportLength(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__vector_len(this.bb_pos+a):0}producerName(a){let u=this.bb.__offset(this.bb_pos,8);return u?this.bb.__string(this.bb_pos+u,a):null}producerVersion(a){let u=this.bb.__offset(this.bb_pos,10);return u?this.bb.__string(this.bb_pos+u,a):null}domain(a){let u=this.bb.__offset(this.bb_pos,12);return u?this.bb.__string(this.bb_pos+u,a):null}modelVersion(){let a=this.bb.__offset(this.bb_pos,14);return a?this.bb.readInt64(this.bb_pos+a):this.bb.createLong(0,0)}docString(a){let u=this.bb.__offset(this.bb_pos,16);return u?this.bb.__string(this.bb_pos+u,a):null}graph(a){let u=this.bb.__offset(this.bb_pos,18);return u?(a||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}graphDocString(a){let u=this.bb.__offset(this.bb_pos,20);return u?this.bb.__string(this.bb_pos+u,a):null}static startModel(a){a.startObject(9)}static addIrVersion(a,u){a.addFieldInt64(0,u,a.createLong(0,0))}static addOpsetImport(a,u){a.addFieldOffset(1,u,0)}static createOpsetImportVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startOpsetImportVector(a,u){a.startVector(4,u,4)}static addProducerName(a,u){a.addFieldOffset(2,u,0)}static addProducerVersion(a,u){a.addFieldOffset(3,u,0)}static addDomain(a,u){a.addFieldOffset(4,u,0)}static addModelVersion(a,u){a.addFieldInt64(5,u,a.createLong(0,0))}static addDocString(a,u){a.addFieldOffset(6,u,0)}static addGraph(a,u){a.addFieldOffset(7,u,0)}static addGraphDocString(a,u){a.addFieldOffset(8,u,0)}static endModel(a){return a.endObject()}static createModel(a,u,d,m,b,w,x,$,I,A){return i.startModel(a),i.addIrVersion(a,u),i.addOpsetImport(a,d),i.addProducerName(a,m),i.addProducerVersion(a,b),i.addDomain(a,w),i.addModelVersion(a,x),i.addDocString(a,$),i.addGraph(a,I),i.addGraphDocString(a,A),i.endModel(a)}}o.Model=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsKernelCreateInfos(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsKernelCreateInfos(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}nodeIndices(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.readUint32(this.bb.__vector(this.bb_pos+u)+a*4):0}nodeIndicesLength(){let a=this.bb.__offset(this.bb_pos,4);return a?this.bb.__vector_len(this.bb_pos+a):0}nodeIndicesArray(){let a=this.bb.__offset(this.bb_pos,4);return a?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+a),this.bb.__vector_len(this.bb_pos+a)):null}kernelDefHashes(a){let u=this.bb.__offset(this.bb_pos,6);return u?this.bb.readUint64(this.bb.__vector(this.bb_pos+u)+a*8):this.bb.createLong(0,0)}kernelDefHashesLength(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__vector_len(this.bb_pos+a):0}static startKernelCreateInfos(a){a.startObject(2)}static addNodeIndices(a,u){a.addFieldOffset(0,u,0)}static createNodeIndicesVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addInt32(u[d]);return a.endVector()}static startNodeIndicesVector(a,u){a.startVector(4,u,4)}static addKernelDefHashes(a,u){a.addFieldOffset(1,u,0)}static createKernelDefHashesVector(a,u){a.startVector(8,u.length,8);for(let d=u.length-1;d>=0;d--)a.addInt64(u[d]);return a.endVector()}static startKernelDefHashesVector(a,u){a.startVector(8,u,8)}static endKernelCreateInfos(a){return a.endObject()}static createKernelCreateInfos(a,u,d){return i.startKernelCreateInfos(a),i.addNodeIndices(a,u),i.addKernelDefHashes(a,d),i.endKernelCreateInfos(a)}}o.KernelCreateInfos=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsSubGraphSessionState(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsSubGraphSessionState(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}graphId(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}sessionState(a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}static startSubGraphSessionState(a){a.startObject(2)}static addGraphId(a,u){a.addFieldOffset(0,u,0)}static addSessionState(a,u){a.addFieldOffset(1,u,0)}static endSubGraphSessionState(a){let u=a.endObject();return a.requiredField(u,4),u}static createSubGraphSessionState(a,u,d){return i.startSubGraphSessionState(a),i.addGraphId(a,u),i.addSessionState(a,d),i.endSubGraphSessionState(a)}}o.SubGraphSessionState=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsSessionState(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsSessionState(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}kernels(a){let u=this.bb.__offset(this.bb_pos,4);return u?(a||new e.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}subGraphSessionStates(a,u){let d=this.bb.__offset(this.bb_pos,6);return d?(u||new e.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+d)+a*4),this.bb):null}subGraphSessionStatesLength(){let a=this.bb.__offset(this.bb_pos,6);return a?this.bb.__vector_len(this.bb_pos+a):0}static startSessionState(a){a.startObject(2)}static addKernels(a,u){a.addFieldOffset(0,u,0)}static addSubGraphSessionStates(a,u){a.addFieldOffset(1,u,0)}static createSubGraphSessionStatesVector(a,u){a.startVector(4,u.length,4);for(let d=u.length-1;d>=0;d--)a.addOffset(u[d]);return a.endVector()}static startSubGraphSessionStatesVector(a,u){a.startVector(4,u,4)}static endSessionState(a){return a.endObject()}static createSessionState(a,u,d){return i.startSessionState(a),i.addKernels(a,u),i.addSubGraphSessionStates(a,d),i.endSessionState(a)}}o.SessionState=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={});(e=>{let n;(t=>{let r;(o=>{class i{constructor(){this.bb=null;this.bb_pos=0}__init(a,u){return this.bb_pos=a,this.bb=u,this}static getRootAsInferenceSession(a,u){return(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static getSizePrefixedRootAsInferenceSession(a,u){return a.setPosition(a.position()+K.SIZE_PREFIX_LENGTH),(u||new i).__init(a.readInt32(a.position())+a.position(),a)}static bufferHasIdentifier(a){return a.__has_identifier("ORTM")}ortVersion(a){let u=this.bb.__offset(this.bb_pos,4);return u?this.bb.__string(this.bb_pos+u,a):null}model(a){let u=this.bb.__offset(this.bb_pos,6);return u?(a||new e.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}sessionState(a){let u=this.bb.__offset(this.bb_pos,8);return u?(a||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+u),this.bb):null}static startInferenceSession(a){a.startObject(3)}static addOrtVersion(a,u){a.addFieldOffset(0,u,0)}static addModel(a,u){a.addFieldOffset(1,u,0)}static addSessionState(a,u){a.addFieldOffset(2,u,0)}static endInferenceSession(a){return a.endObject()}static finishInferenceSessionBuffer(a,u){a.finish(u,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(a,u){a.finish(u,"ORTM",!0)}static createInferenceSession(a,u,d,m){return i.startInferenceSession(a),i.addOrtVersion(a,u),i.addModel(a,d),i.addSessionState(a,m),i.endInferenceSession(a)}}o.InferenceSession=i})(r=t.fbs||={})})(n=e.experimental||={})})(xe||={})});var ap=ht((l3,op)=>{"use strict";op.exports=j1;function j1(n,e){for(var r=new Array(arguments.length-1),t=0,i=2,o=!0;i{"use strict";var ya=lp;ya.length=function(e){var r=e.length;if(!r)return 0;for(var t=0;--r%4>1&&e.charAt(r)==="=";)++t;return Math.ceil(e.length*3)/4-t};var mi=new Array(64),up=new Array(123);for(Sr=0;Sr<64;)up[mi[Sr]=Sr<26?Sr+65:Sr<52?Sr+71:Sr<62?Sr-4:Sr-59|43]=Sr++;var Sr;ya.encode=function(e,r,t){for(var i=null,o=[],s=0,a=0,u;r>2],u=(d&3)<<4,a=1;break;case 1:o[s++]=mi[u|d>>4],u=(d&15)<<2,a=2;break;case 2:o[s++]=mi[u|d>>6],o[s++]=mi[d&63],a=0;break}s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0)}return a&&(o[s++]=mi[u],o[s++]=61,a===1&&(o[s++]=61)),i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))};var sp="invalid encoding";ya.decode=function(e,r,t){for(var i=t,o=0,s,a=0;a1)break;if((u=up[u])===void 0)throw Error(sp);switch(o){case 0:s=u,o=1;break;case 1:r[t++]=s<<2|(u&48)>>4,s=u,o=2;break;case 2:r[t++]=(s&15)<<4|(u&60)>>2,s=u,o=3;break;case 3:r[t++]=(s&3)<<6|u,o=0;break}}if(o===1)throw Error(sp);return t-i};ya.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var fp=ht((c3,cp)=>{"use strict";cp.exports=ba;function ba(){this._listeners={}}ba.prototype.on=function(e,r,t){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:t||this}),this};ba.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var t=this._listeners[e],i=0;i{"use strict";bp.exports=pp(pp);function pp(n){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),t=r[3]===128;function i(u,d,m){e[0]=u,d[m]=r[0],d[m+1]=r[1],d[m+2]=r[2],d[m+3]=r[3]}function o(u,d,m){e[0]=u,d[m]=r[3],d[m+1]=r[2],d[m+2]=r[1],d[m+3]=r[0]}n.writeFloatLE=t?i:o,n.writeFloatBE=t?o:i;function s(u,d){return r[0]=u[d],r[1]=u[d+1],r[2]=u[d+2],r[3]=u[d+3],e[0]}function a(u,d){return r[3]=u[d],r[2]=u[d+1],r[1]=u[d+2],r[0]=u[d+3],e[0]}n.readFloatLE=t?s:a,n.readFloatBE=t?a:s}():function(){function e(t,i,o,s){var a=i<0?1:0;if(a&&(i=-i),i===0)t(1/i>0?0:2147483648,o,s);else if(isNaN(i))t(2143289344,o,s);else if(i>34028234663852886e22)t((a<<31|2139095040)>>>0,o,s);else if(i<11754943508222875e-54)t((a<<31|Math.round(i/1401298464324817e-60))>>>0,o,s);else{var u=Math.floor(Math.log(i)/Math.LN2),d=Math.round(i*Math.pow(2,-u)*8388608)&8388607;t((a<<31|u+127<<23|d)>>>0,o,s)}}n.writeFloatLE=e.bind(null,hp),n.writeFloatBE=e.bind(null,mp);function r(t,i,o){var s=t(i,o),a=(s>>31)*2+1,u=s>>>23&255,d=s&8388607;return u===255?d?NaN:a*(1/0):u===0?a*1401298464324817e-60*d:a*Math.pow(2,u-150)*(d+8388608)}n.readFloatLE=r.bind(null,gp),n.readFloatBE=r.bind(null,yp)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),t=r[7]===128;function i(u,d,m){e[0]=u,d[m]=r[0],d[m+1]=r[1],d[m+2]=r[2],d[m+3]=r[3],d[m+4]=r[4],d[m+5]=r[5],d[m+6]=r[6],d[m+7]=r[7]}function o(u,d,m){e[0]=u,d[m]=r[7],d[m+1]=r[6],d[m+2]=r[5],d[m+3]=r[4],d[m+4]=r[3],d[m+5]=r[2],d[m+6]=r[1],d[m+7]=r[0]}n.writeDoubleLE=t?i:o,n.writeDoubleBE=t?o:i;function s(u,d){return r[0]=u[d],r[1]=u[d+1],r[2]=u[d+2],r[3]=u[d+3],r[4]=u[d+4],r[5]=u[d+5],r[6]=u[d+6],r[7]=u[d+7],e[0]}function a(u,d){return r[7]=u[d],r[6]=u[d+1],r[5]=u[d+2],r[4]=u[d+3],r[3]=u[d+4],r[2]=u[d+5],r[1]=u[d+6],r[0]=u[d+7],e[0]}n.readDoubleLE=t?s:a,n.readDoubleBE=t?a:s}():function(){function e(t,i,o,s,a,u){var d=s<0?1:0;if(d&&(s=-s),s===0)t(0,a,u+i),t(1/s>0?0:2147483648,a,u+o);else if(isNaN(s))t(0,a,u+i),t(2146959360,a,u+o);else if(s>17976931348623157e292)t(0,a,u+i),t((d<<31|2146435072)>>>0,a,u+o);else{var m;if(s<22250738585072014e-324)m=s/5e-324,t(m>>>0,a,u+i),t((d<<31|m/4294967296)>>>0,a,u+o);else{var b=Math.floor(Math.log(s)/Math.LN2);b===1024&&(b=1023),m=s*Math.pow(2,-b),t(m*4503599627370496>>>0,a,u+i),t((d<<31|b+1023<<20|m*1048576&1048575)>>>0,a,u+o)}}}n.writeDoubleLE=e.bind(null,hp,0,4),n.writeDoubleBE=e.bind(null,mp,4,0);function r(t,i,o,s,a){var u=t(s,a+i),d=t(s,a+o),m=(d>>31)*2+1,b=d>>>20&2047,w=4294967296*(d&1048575)+u;return b===2047?w?NaN:m*(1/0):b===0?m*5e-324*w:m*Math.pow(2,b-1075)*(w+4503599627370496)}n.readDoubleLE=r.bind(null,gp,0,4),n.readDoubleBE=r.bind(null,yp,4,0)}(),n}function hp(n,e,r){e[r]=n&255,e[r+1]=n>>>8&255,e[r+2]=n>>>16&255,e[r+3]=n>>>24}function mp(n,e,r){e[r]=n>>>24,e[r+1]=n>>>16&255,e[r+2]=n>>>8&255,e[r+3]=n&255}function gp(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function yp(n,e){return(n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3])>>>0}});var wp=ht((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(n){}return null}});var xp=ht(_p=>{"use strict";var Ys=_p;Ys.length=function(e){for(var r=0,t=0,i=0;i191&&u<224?s[a++]=(u&31)<<6|e[r++]&63:u>239&&u<365?(u=((u&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,s[a++]=55296+(u>>10),s[a++]=56320+(u&1023)):s[a++]=(u&15)<<12|(e[r++]&63)<<6|e[r++]&63,a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0);return o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};Ys.write=function(e,r,t){for(var i=t,o,s,a=0;a>6|192,r[t++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(a+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++a,r[t++]=o>>18|240,r[t++]=o>>12&63|128,r[t++]=o>>6&63|128,r[t++]=o&63|128):(r[t++]=o>>12|224,r[t++]=o>>6&63|128,r[t++]=o&63|128);return t-i}});var Tp=ht((h3,$p)=>{"use strict";$p.exports=U1;function U1(n,e,r){var t=r||8192,i=t>>>1,o=null,s=t;return function(u){if(u<1||u>i)return n(u);s+u>t&&(o=n(t),s=0);var d=e.call(o,s,s+=u);return s&7&&(s=(s|7)+1),d}}});var Ip=ht((m3,Sp)=>{"use strict";Sp.exports=Bt;var io=an();function Bt(n,e){this.lo=n>>>0,this.hi=e>>>0}var An=Bt.zero=new Bt(0,0);An.toNumber=function(){return 0};An.zzEncode=An.zzDecode=function(){return this};An.length=function(){return 1};var F1=Bt.zeroHash="\0\0\0\0\0\0\0\0";Bt.fromNumber=function(e){if(e===0)return An;var r=e<0;r&&(e=-e);var t=e>>>0,i=(e-t)/4294967296>>>0;return r&&(i=~i>>>0,t=~t>>>0,++t>4294967295&&(t=0,++i>4294967295&&(i=0))),new Bt(t,i)};Bt.from=function(e){if(typeof e=="number")return Bt.fromNumber(e);if(io.isString(e))if(io.Long)e=io.Long.fromString(e);else return Bt.fromNumber(parseInt(e,10));return e.low||e.high?new Bt(e.low>>>0,e.high>>>0):An};Bt.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,t=~this.hi>>>0;return r||(t=t+1>>>0),-(r+t*4294967296)}return this.lo+this.hi*4294967296};Bt.prototype.toLong=function(e){return io.Long?new io.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var on=String.prototype.charCodeAt;Bt.fromHash=function(e){return e===F1?An:new Bt((on.call(e,0)|on.call(e,1)<<8|on.call(e,2)<<16|on.call(e,3)<<24)>>>0,(on.call(e,4)|on.call(e,5)<<8|on.call(e,6)<<16|on.call(e,7)<<24)>>>0)};Bt.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};Bt.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};Bt.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};Bt.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,t=this.hi>>>24;return t===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:t<128?9:10}});var an=ht(Xs=>{"use strict";var Se=Xs;Se.asPromise=ap();Se.base64=dp();Se.EventEmitter=fp();Se.float=vp();Se.inquire=wp();Se.utf8=xp();Se.pool=Tp();Se.LongBits=Ip();Se.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);Se.global=Se.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||Xs;Se.emptyArray=Object.freeze?Object.freeze([]):[];Se.emptyObject=Object.freeze?Object.freeze({}):{};Se.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Se.isString=function(e){return typeof e=="string"||e instanceof String};Se.isObject=function(e){return e&&typeof e=="object"};Se.isset=Se.isSet=function(e,r){var t=e[r];return t!=null&&e.hasOwnProperty(r)?typeof t!="object"||(Array.isArray(t)?t.length:Object.keys(t).length)>0:!1};Se.Buffer=function(){try{var n=Se.inquire("buffer").Buffer;return n.prototype.utf8Write?n:null}catch{return null}}();Se._Buffer_from=null;Se._Buffer_allocUnsafe=null;Se.newBuffer=function(e){return typeof e=="number"?Se.Buffer?Se._Buffer_allocUnsafe(e):new Se.Array(e):Se.Buffer?Se._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Se.Array=typeof Uint8Array<"u"?Uint8Array:Array;Se.Long=Se.global.dcodeIO&&Se.global.dcodeIO.Long||Se.global.Long||Se.inquire("long");Se.key2Re=/^true|false|0|1$/;Se.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Se.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Se.longToHash=function(e){return e?Se.LongBits.from(e).toHash():Se.LongBits.zeroHash};Se.longFromHash=function(e,r){var t=Se.LongBits.fromHash(e);return Se.Long?Se.Long.fromBits(t.lo,t.hi,r):t.toNumber(!!r)};function Cp(n,e,r){for(var t=Object.keys(e),i=0;i-1;--o)if(r[i[o]]===1&&this[i[o]]!==void 0&&this[i[o]]!==null)return i[o]}};Se.oneOfSetter=function(e){return function(r){for(var t=0;t{"use strict";kp.exports=tt;var hr=an(),Zs,va=hr.LongBits,Ep=hr.base64,Op=hr.utf8;function oo(n,e,r){this.fn=n,this.len=e,this.next=void 0,this.val=r}function Qs(){}function V1(n){this.head=n.head,this.tail=n.tail,this.len=n.len,this.next=n.states}function tt(){this.len=0,this.head=new oo(Qs,0,0),this.tail=this.head,this.states=null}var Pp=function(){return hr.Buffer?function(){return(tt.create=function(){return new Zs})()}:function(){return new tt}};tt.create=Pp();tt.alloc=function(e){return new hr.Array(e)};hr.Array!==Array&&(tt.alloc=hr.pool(tt.alloc,hr.Array.prototype.subarray));tt.prototype._push=function(e,r,t){return this.tail=this.tail.next=new oo(e,r,t),this.len+=r,this};function eu(n,e,r){e[r]=n&255}function G1(n,e,r){for(;n>127;)e[r++]=n&127|128,n>>>=7;e[r]=n}function tu(n,e){this.len=n,this.next=void 0,this.val=e}tu.prototype=Object.create(oo.prototype);tu.prototype.fn=G1;tt.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new tu((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};tt.prototype.int32=function(e){return e<0?this._push(ru,10,va.fromNumber(e)):this.uint32(e)};tt.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ru(n,e,r){for(;n.hi;)e[r++]=n.lo&127|128,n.lo=(n.lo>>>7|n.hi<<25)>>>0,n.hi>>>=7;for(;n.lo>127;)e[r++]=n.lo&127|128,n.lo=n.lo>>>7;e[r++]=n.lo}tt.prototype.uint64=function(e){var r=va.from(e);return this._push(ru,r.length(),r)};tt.prototype.int64=tt.prototype.uint64;tt.prototype.sint64=function(e){var r=va.from(e).zzEncode();return this._push(ru,r.length(),r)};tt.prototype.bool=function(e){return this._push(eu,1,e?1:0)};function Js(n,e,r){e[r]=n&255,e[r+1]=n>>>8&255,e[r+2]=n>>>16&255,e[r+3]=n>>>24}tt.prototype.fixed32=function(e){return this._push(Js,4,e>>>0)};tt.prototype.sfixed32=tt.prototype.fixed32;tt.prototype.fixed64=function(e){var r=va.from(e);return this._push(Js,4,r.lo)._push(Js,4,r.hi)};tt.prototype.sfixed64=tt.prototype.fixed64;tt.prototype.float=function(e){return this._push(hr.float.writeFloatLE,4,e)};tt.prototype.double=function(e){return this._push(hr.float.writeDoubleLE,8,e)};var W1=hr.Array.prototype.set?function(e,r,t){r.set(e,t)}:function(e,r,t){for(var i=0;i>>0;if(!r)return this._push(eu,1,0);if(hr.isString(e)){var t=tt.alloc(r=Ep.length(e));Ep.decode(e,t,0),e=t}return this.uint32(r)._push(W1,r,e)};tt.prototype.string=function(e){var r=Op.length(e);return r?this.uint32(r)._push(Op.write,r,e):this._push(eu,1,0)};tt.prototype.fork=function(){return this.states=new V1(this),this.head=this.tail=new oo(Qs,0,0),this.len=0,this};tt.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new oo(Qs,0,0),this.len=0),this};tt.prototype.ldelim=function(){var e=this.head,r=this.tail,t=this.len;return this.reset().uint32(t),t&&(this.tail.next=e.next,this.tail=r,this.len+=t),this};tt.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),t=0;e;)e.fn(e.val,r,t),t+=e.len,e=e.next;return r};tt._configure=function(n){Zs=n,tt.create=Pp(),Zs._configure()}});var Rp=ht((b3,Bp)=>{"use strict";Bp.exports=zr;var Dp=nu();(zr.prototype=Object.create(Dp.prototype)).constructor=zr;var sn=an();function zr(){Dp.call(this)}zr._configure=function(){zr.alloc=sn._Buffer_allocUnsafe,zr.writeBytesBuffer=sn.Buffer&&sn.Buffer.prototype instanceof Uint8Array&&sn.Buffer.prototype.set.name==="set"?function(e,r,t){r.set(e,t)}:function(e,r,t){if(e.copy)e.copy(r,t,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(zr.writeBytesBuffer,r,e),this};function H1(n,e,r){n.length<40?sn.utf8.write(n,e,r):e.utf8Write?e.utf8Write(n,r):e.write(n,r)}zr.prototype.string=function(e){var r=sn.Buffer.byteLength(e);return this.uint32(r),r&&this._push(H1,r,e),this};zr._configure()});var au=ht((v3,jp)=>{"use strict";jp.exports=It;var Ir=an(),ou,Np=Ir.LongBits,q1=Ir.utf8;function Cr(n,e){return RangeError("index out of range: "+n.pos+" + "+(e||1)+" > "+n.len)}function It(n){this.buf=n,this.pos=0,this.len=n.length}var zp=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new It(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new It(e);throw Error("illegal buffer")},Lp=function(){return Ir.Buffer?function(r){return(It.create=function(i){return Ir.Buffer.isBuffer(i)?new ou(i):zp(i)})(r)}:zp};It.create=Lp();It.prototype._slice=Ir.Array.prototype.subarray||Ir.Array.prototype.slice;It.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Cr(this,10);return e}}();It.prototype.int32=function(){return this.uint32()|0};It.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function iu(){var n=new Np(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(n.lo=(n.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n;if(n.lo=(n.lo|(this.buf[this.pos]&127)<<28)>>>0,n.hi=(n.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return n;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Cr(this);if(n.lo=(n.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}return n.lo=(n.lo|(this.buf[this.pos++]&127)<>>0,n}if(this.len-this.pos>4){for(;e<5;++e)if(n.hi=(n.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}else for(;e<5;++e){if(this.pos>=this.len)throw Cr(this);if(n.hi=(n.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return n}throw Error("invalid varint encoding")}It.prototype.bool=function(){return this.uint32()!==0};function wa(n,e){return(n[e-4]|n[e-3]<<8|n[e-2]<<16|n[e-1]<<24)>>>0}It.prototype.fixed32=function(){if(this.pos+4>this.len)throw Cr(this,4);return wa(this.buf,this.pos+=4)};It.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Cr(this,4);return wa(this.buf,this.pos+=4)|0};function Mp(){if(this.pos+8>this.len)throw Cr(this,8);return new Np(wa(this.buf,this.pos+=4),wa(this.buf,this.pos+=4))}It.prototype.float=function(){if(this.pos+4>this.len)throw Cr(this,4);var e=Ir.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};It.prototype.double=function(){if(this.pos+8>this.len)throw Cr(this,4);var e=Ir.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};It.prototype.bytes=function(){var e=this.uint32(),r=this.pos,t=this.pos+e;if(t>this.len)throw Cr(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,t);if(r===t){var i=Ir.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,t)};It.prototype.string=function(){var e=this.bytes();return q1.read(e,0,e.length)};It.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Cr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Cr(this);while(this.buf[this.pos++]&128);return this};It.prototype.skipType=function(n){switch(n){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(n=this.uint32()&7)!==4;)this.skipType(n);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+n+" at offset "+this.pos)}return this};It._configure=function(n){ou=n,It.create=Lp(),ou._configure();var e=Ir.Long?"toLong":"toNumber";Ir.merge(It.prototype,{int64:function(){return iu.call(this)[e](!1)},uint64:function(){return iu.call(this)[e](!0)},sint64:function(){return iu.call(this).zzDecode()[e](!1)},fixed64:function(){return Mp.call(this)[e](!0)},sfixed64:function(){return Mp.call(this)[e](!1)}})}});var Gp=ht((w3,Vp)=>{"use strict";Vp.exports=En;var Fp=au();(En.prototype=Object.create(Fp.prototype)).constructor=En;var Up=an();function En(n){Fp.call(this,n)}En._configure=function(){Up.Buffer&&(En.prototype._slice=Up.Buffer.prototype.slice)};En.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};En._configure()});var Hp=ht((_3,Wp)=>{"use strict";Wp.exports=ao;var su=an();(ao.prototype=Object.create(su.EventEmitter.prototype)).constructor=ao;function ao(n,e,r){if(typeof n!="function")throw TypeError("rpcImpl must be a function");su.EventEmitter.call(this),this.rpcImpl=n,this.requestDelimited=!!e,this.responseDelimited=!!r}ao.prototype.rpcCall=function n(e,r,t,i,o){if(!i)throw TypeError("request must be specified");var s=this;if(!o)return su.asPromise(n,s,e,r,t,i);if(!s.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return s.rpcImpl(e,r[s.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(u,d){if(u)return s.emit("error",u,e),o(u);if(d===null){s.end(!0);return}if(!(d instanceof t))try{d=t[s.responseDelimited?"decodeDelimited":"decode"](d)}catch(m){return s.emit("error",m,e),o(m)}return s.emit("data",d,e),o(null,d)})}catch(a){s.emit("error",a,e),setTimeout(function(){o(a)},0);return}};ao.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var Kp=ht(qp=>{"use strict";var K1=qp;K1.Service=Hp()});var Xp=ht(($3,Yp)=>{"use strict";Yp.exports={}});var Qp=ht(Jp=>{"use strict";var Jt=Jp;Jt.build="minimal";Jt.Writer=nu();Jt.BufferWriter=Rp();Jt.Reader=au();Jt.BufferReader=Gp();Jt.util=an();Jt.rpc=Kp();Jt.roots=Xp();Jt.configure=Zp;function Zp(){Jt.util._configure(),Jt.Writer._configure(Jt.BufferWriter),Jt.Reader._configure(Jt.BufferReader)}Zp()});var th=ht((S3,eh)=>{"use strict";eh.exports=Qp()});var gi=ht((I3,rh)=>{"use strict";var gt=th(),fe=gt.Reader,Ct=gt.Writer,j=gt.util,B=gt.roots.default||(gt.roots.default={});B.onnx=function(){var n={};return n.Version=function(){var e={},r=Object.create(e);return r[e[0]="_START_VERSION"]=0,r[e[1]="IR_VERSION_2017_10_10"]=1,r[e[2]="IR_VERSION_2017_10_30"]=2,r[e[3]="IR_VERSION_2017_11_3"]=3,r[e[4]="IR_VERSION_2019_1_22"]=4,r[e[5]="IR_VERSION_2019_3_18"]=5,r[e[6]="IR_VERSION_2019_9_19"]=6,r[e[7]="IR_VERSION_2020_5_8"]=7,r[e[8]="IR_VERSION_2021_7_30"]=8,r[e[9]="IR_VERSION"]=9,r}(),n.AttributeProto=function(){function e(r){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],r)for(var t=Object.keys(r),i=0;i>>3){case 1:{s.name=t.string();break}case 21:{s.refAttrName=t.string();break}case 13:{s.docString=t.string();break}case 20:{s.type=t.int32();break}case 2:{s.f=t.float();break}case 3:{s.i=t.int64();break}case 4:{s.s=t.bytes();break}case 5:{s.t=B.onnx.TensorProto.decode(t,t.uint32());break}case 6:{s.g=B.onnx.GraphProto.decode(t,t.uint32());break}case 22:{s.sparseTensor=B.onnx.SparseTensorProto.decode(t,t.uint32());break}case 14:{s.tp=B.onnx.TypeProto.decode(t,t.uint32());break}case 7:{if(s.floats&&s.floats.length||(s.floats=[]),(a&7)===2)for(var u=t.uint32()+t.pos;t.pos>>0,t.i.high>>>0).toNumber())),t.s!=null&&(typeof t.s=="string"?j.base64.decode(t.s,i.s=j.newBuffer(j.base64.length(t.s)),0):t.s.length>=0&&(i.s=t.s)),t.t!=null){if(typeof t.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");i.t=B.onnx.TensorProto.fromObject(t.t)}if(t.g!=null){if(typeof t.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");i.g=B.onnx.GraphProto.fromObject(t.g)}if(t.sparseTensor!=null){if(typeof t.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");i.sparseTensor=B.onnx.SparseTensorProto.fromObject(t.sparseTensor)}if(t.tp!=null){if(typeof t.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");i.tp=B.onnx.TypeProto.fromObject(t.tp)}if(t.floats){if(!Array.isArray(t.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");i.floats=[];for(var o=0;o>>0,t.ints[o].high>>>0).toNumber())}if(t.strings){if(!Array.isArray(t.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");i.strings=[];for(var o=0;o=0&&(i.strings[o]=t.strings[o])}if(t.tensors){if(!Array.isArray(t.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");i.tensors=[];for(var o=0;o>>0,t.i.high>>>0).toNumber():t.i),t.s!=null&&t.hasOwnProperty("s")&&(o.s=i.bytes===String?j.base64.encode(t.s,0,t.s.length):i.bytes===Array?Array.prototype.slice.call(t.s):t.s),t.t!=null&&t.hasOwnProperty("t")&&(o.t=B.onnx.TensorProto.toObject(t.t,i)),t.g!=null&&t.hasOwnProperty("g")&&(o.g=B.onnx.GraphProto.toObject(t.g,i)),t.floats&&t.floats.length){o.floats=[];for(var a=0;a>>0,t.ints[a].high>>>0).toNumber():t.ints[a]}if(t.strings&&t.strings.length){o.strings=[];for(var a=0;a>>3){case 1:{s.name=t.string();break}case 2:{s.type=B.onnx.TypeProto.decode(t,t.uint32());break}case 3:{s.docString=t.string();break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.name!=null&&t.hasOwnProperty("name")&&!j.isString(t.name))return"name: string expected";if(t.type!=null&&t.hasOwnProperty("type")){var i=B.onnx.TypeProto.verify(t.type);if(i)return"type."+i}return t.docString!=null&&t.hasOwnProperty("docString")&&!j.isString(t.docString)?"docString: string expected":null},e.fromObject=function(t){if(t instanceof B.onnx.ValueInfoProto)return t;var i=new B.onnx.ValueInfoProto;if(t.name!=null&&(i.name=String(t.name)),t.type!=null){if(typeof t.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");i.type=B.onnx.TypeProto.fromObject(t.type)}return t.docString!=null&&(i.docString=String(t.docString)),i},e.toObject=function(t,i){i||(i={});var o={};return i.defaults&&(o.name="",o.type=null,o.docString=""),t.name!=null&&t.hasOwnProperty("name")&&(o.name=t.name),t.type!=null&&t.hasOwnProperty("type")&&(o.type=B.onnx.TypeProto.toObject(t.type,i)),t.docString!=null&&t.hasOwnProperty("docString")&&(o.docString=t.docString),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},e.getTypeUrl=function(t){return t===void 0&&(t="type.googleapis.com"),t+"/onnx.ValueInfoProto"},e}(),n.NodeProto=function(){function e(r){if(this.input=[],this.output=[],this.attribute=[],r)for(var t=Object.keys(r),i=0;i>>3){case 1:{s.input&&s.input.length||(s.input=[]),s.input.push(t.string());break}case 2:{s.output&&s.output.length||(s.output=[]),s.output.push(t.string());break}case 3:{s.name=t.string();break}case 4:{s.opType=t.string();break}case 7:{s.domain=t.string();break}case 5:{s.attribute&&s.attribute.length||(s.attribute=[]),s.attribute.push(B.onnx.AttributeProto.decode(t,t.uint32()));break}case 6:{s.docString=t.string();break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.input!=null&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(var i=0;i>>3){case 1:{s.initialization=B.onnx.GraphProto.decode(t,t.uint32());break}case 2:{s.algorithm=B.onnx.GraphProto.decode(t,t.uint32());break}case 3:{s.initializationBinding&&s.initializationBinding.length||(s.initializationBinding=[]),s.initializationBinding.push(B.onnx.StringStringEntryProto.decode(t,t.uint32()));break}case 4:{s.updateBinding&&s.updateBinding.length||(s.updateBinding=[]),s.updateBinding.push(B.onnx.StringStringEntryProto.decode(t,t.uint32()));break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.initialization!=null&&t.hasOwnProperty("initialization")){var i=B.onnx.GraphProto.verify(t.initialization);if(i)return"initialization."+i}if(t.algorithm!=null&&t.hasOwnProperty("algorithm")){var i=B.onnx.GraphProto.verify(t.algorithm);if(i)return"algorithm."+i}if(t.initializationBinding!=null&&t.hasOwnProperty("initializationBinding")){if(!Array.isArray(t.initializationBinding))return"initializationBinding: array expected";for(var o=0;o>>3){case 1:{s.irVersion=t.int64();break}case 8:{s.opsetImport&&s.opsetImport.length||(s.opsetImport=[]),s.opsetImport.push(B.onnx.OperatorSetIdProto.decode(t,t.uint32()));break}case 2:{s.producerName=t.string();break}case 3:{s.producerVersion=t.string();break}case 4:{s.domain=t.string();break}case 5:{s.modelVersion=t.int64();break}case 6:{s.docString=t.string();break}case 7:{s.graph=B.onnx.GraphProto.decode(t,t.uint32());break}case 14:{s.metadataProps&&s.metadataProps.length||(s.metadataProps=[]),s.metadataProps.push(B.onnx.StringStringEntryProto.decode(t,t.uint32()));break}case 20:{s.trainingInfo&&s.trainingInfo.length||(s.trainingInfo=[]),s.trainingInfo.push(B.onnx.TrainingInfoProto.decode(t,t.uint32()));break}case 25:{s.functions&&s.functions.length||(s.functions=[]),s.functions.push(B.onnx.FunctionProto.decode(t,t.uint32()));break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.irVersion!=null&&t.hasOwnProperty("irVersion")&&!j.isInteger(t.irVersion)&&!(t.irVersion&&j.isInteger(t.irVersion.low)&&j.isInteger(t.irVersion.high)))return"irVersion: integer|Long expected";if(t.opsetImport!=null&&t.hasOwnProperty("opsetImport")){if(!Array.isArray(t.opsetImport))return"opsetImport: array expected";for(var i=0;i>>0,t.irVersion.high>>>0).toNumber())),t.opsetImport){if(!Array.isArray(t.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");i.opsetImport=[];for(var o=0;o>>0,t.modelVersion.high>>>0).toNumber())),t.docString!=null&&(i.docString=String(t.docString)),t.graph!=null){if(typeof t.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");i.graph=B.onnx.GraphProto.fromObject(t.graph)}if(t.metadataProps){if(!Array.isArray(t.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");i.metadataProps=[];for(var o=0;o>>0,t.irVersion.high>>>0).toNumber():t.irVersion),t.producerName!=null&&t.hasOwnProperty("producerName")&&(o.producerName=t.producerName),t.producerVersion!=null&&t.hasOwnProperty("producerVersion")&&(o.producerVersion=t.producerVersion),t.domain!=null&&t.hasOwnProperty("domain")&&(o.domain=t.domain),t.modelVersion!=null&&t.hasOwnProperty("modelVersion")&&(typeof t.modelVersion=="number"?o.modelVersion=i.longs===String?String(t.modelVersion):t.modelVersion:o.modelVersion=i.longs===String?j.Long.prototype.toString.call(t.modelVersion):i.longs===Number?new j.LongBits(t.modelVersion.low>>>0,t.modelVersion.high>>>0).toNumber():t.modelVersion),t.docString!=null&&t.hasOwnProperty("docString")&&(o.docString=t.docString),t.graph!=null&&t.hasOwnProperty("graph")&&(o.graph=B.onnx.GraphProto.toObject(t.graph,i)),t.opsetImport&&t.opsetImport.length){o.opsetImport=[];for(var a=0;a>>3){case 1:{s.key=t.string();break}case 2:{s.value=t.string();break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){return typeof t!="object"||t===null?"object expected":t.key!=null&&t.hasOwnProperty("key")&&!j.isString(t.key)?"key: string expected":t.value!=null&&t.hasOwnProperty("value")&&!j.isString(t.value)?"value: string expected":null},e.fromObject=function(t){if(t instanceof B.onnx.StringStringEntryProto)return t;var i=new B.onnx.StringStringEntryProto;return t.key!=null&&(i.key=String(t.key)),t.value!=null&&(i.value=String(t.value)),i},e.toObject=function(t,i){i||(i={});var o={};return i.defaults&&(o.key="",o.value=""),t.key!=null&&t.hasOwnProperty("key")&&(o.key=t.key),t.value!=null&&t.hasOwnProperty("value")&&(o.value=t.value),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},e.getTypeUrl=function(t){return t===void 0&&(t="type.googleapis.com"),t+"/onnx.StringStringEntryProto"},e}(),n.TensorAnnotation=function(){function e(r){if(this.quantParameterTensorNames=[],r)for(var t=Object.keys(r),i=0;i>>3){case 1:{s.tensorName=t.string();break}case 2:{s.quantParameterTensorNames&&s.quantParameterTensorNames.length||(s.quantParameterTensorNames=[]),s.quantParameterTensorNames.push(B.onnx.StringStringEntryProto.decode(t,t.uint32()));break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.tensorName!=null&&t.hasOwnProperty("tensorName")&&!j.isString(t.tensorName))return"tensorName: string expected";if(t.quantParameterTensorNames!=null&&t.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(t.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var i=0;i>>3){case 1:{s.node&&s.node.length||(s.node=[]),s.node.push(B.onnx.NodeProto.decode(t,t.uint32()));break}case 2:{s.name=t.string();break}case 5:{s.initializer&&s.initializer.length||(s.initializer=[]),s.initializer.push(B.onnx.TensorProto.decode(t,t.uint32()));break}case 15:{s.sparseInitializer&&s.sparseInitializer.length||(s.sparseInitializer=[]),s.sparseInitializer.push(B.onnx.SparseTensorProto.decode(t,t.uint32()));break}case 10:{s.docString=t.string();break}case 11:{s.input&&s.input.length||(s.input=[]),s.input.push(B.onnx.ValueInfoProto.decode(t,t.uint32()));break}case 12:{s.output&&s.output.length||(s.output=[]),s.output.push(B.onnx.ValueInfoProto.decode(t,t.uint32()));break}case 13:{s.valueInfo&&s.valueInfo.length||(s.valueInfo=[]),s.valueInfo.push(B.onnx.ValueInfoProto.decode(t,t.uint32()));break}case 14:{s.quantizationAnnotation&&s.quantizationAnnotation.length||(s.quantizationAnnotation=[]),s.quantizationAnnotation.push(B.onnx.TensorAnnotation.decode(t,t.uint32()));break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.node!=null&&t.hasOwnProperty("node")){if(!Array.isArray(t.node))return"node: array expected";for(var i=0;i>>3){case 1:{if(s.dims&&s.dims.length||(s.dims=[]),(a&7)===2)for(var u=t.uint32()+t.pos;t.pos>>0,t.dims[o].high>>>0).toNumber())}if(t.dataType!=null&&(i.dataType=t.dataType|0),t.segment!=null){if(typeof t.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");i.segment=B.onnx.TensorProto.Segment.fromObject(t.segment)}if(t.floatData){if(!Array.isArray(t.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");i.floatData=[];for(var o=0;o=0&&(i.stringData[o]=t.stringData[o])}if(t.int64Data){if(!Array.isArray(t.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");i.int64Data=[];for(var o=0;o>>0,t.int64Data[o].high>>>0).toNumber())}if(t.name!=null&&(i.name=String(t.name)),t.docString!=null&&(i.docString=String(t.docString)),t.rawData!=null&&(typeof t.rawData=="string"?j.base64.decode(t.rawData,i.rawData=j.newBuffer(j.base64.length(t.rawData)),0):t.rawData.length>=0&&(i.rawData=t.rawData)),t.externalData){if(!Array.isArray(t.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");i.externalData=[];for(var o=0;o>>0,t.uint64Data[o].high>>>0).toNumber(!0))}return i},e.toObject=function(t,i){i||(i={});var o={};if((i.arrays||i.defaults)&&(o.dims=[],o.floatData=[],o.int32Data=[],o.stringData=[],o.int64Data=[],o.doubleData=[],o.uint64Data=[],o.externalData=[]),i.defaults&&(o.dataType=0,o.segment=null,o.name="",i.bytes===String?o.rawData="":(o.rawData=[],i.bytes!==Array&&(o.rawData=j.newBuffer(o.rawData))),o.docString="",o.dataLocation=i.enums===String?"DEFAULT":0),t.dims&&t.dims.length){o.dims=[];for(var s=0;s>>0,t.dims[s].high>>>0).toNumber():t.dims[s]}if(t.dataType!=null&&t.hasOwnProperty("dataType")&&(o.dataType=t.dataType),t.segment!=null&&t.hasOwnProperty("segment")&&(o.segment=B.onnx.TensorProto.Segment.toObject(t.segment,i)),t.floatData&&t.floatData.length){o.floatData=[];for(var s=0;s>>0,t.int64Data[s].high>>>0).toNumber():t.int64Data[s]}if(t.name!=null&&t.hasOwnProperty("name")&&(o.name=t.name),t.rawData!=null&&t.hasOwnProperty("rawData")&&(o.rawData=i.bytes===String?j.base64.encode(t.rawData,0,t.rawData.length):i.bytes===Array?Array.prototype.slice.call(t.rawData):t.rawData),t.doubleData&&t.doubleData.length){o.doubleData=[];for(var s=0;s>>0,t.uint64Data[s].high>>>0).toNumber(!0):t.uint64Data[s]}if(t.docString!=null&&t.hasOwnProperty("docString")&&(o.docString=t.docString),t.externalData&&t.externalData.length){o.externalData=[];for(var s=0;s>>3){case 1:{a.begin=i.int64();break}case 2:{a.end=i.int64();break}default:i.skipType(u&7);break}}return a},r.decodeDelimited=function(i){return i instanceof fe||(i=new fe(i)),this.decode(i,i.uint32())},r.verify=function(i){return typeof i!="object"||i===null?"object expected":i.begin!=null&&i.hasOwnProperty("begin")&&!j.isInteger(i.begin)&&!(i.begin&&j.isInteger(i.begin.low)&&j.isInteger(i.begin.high))?"begin: integer|Long expected":i.end!=null&&i.hasOwnProperty("end")&&!j.isInteger(i.end)&&!(i.end&&j.isInteger(i.end.low)&&j.isInteger(i.end.high))?"end: integer|Long expected":null},r.fromObject=function(i){if(i instanceof B.onnx.TensorProto.Segment)return i;var o=new B.onnx.TensorProto.Segment;return i.begin!=null&&(j.Long?(o.begin=j.Long.fromValue(i.begin)).unsigned=!1:typeof i.begin=="string"?o.begin=parseInt(i.begin,10):typeof i.begin=="number"?o.begin=i.begin:typeof i.begin=="object"&&(o.begin=new j.LongBits(i.begin.low>>>0,i.begin.high>>>0).toNumber())),i.end!=null&&(j.Long?(o.end=j.Long.fromValue(i.end)).unsigned=!1:typeof i.end=="string"?o.end=parseInt(i.end,10):typeof i.end=="number"?o.end=i.end:typeof i.end=="object"&&(o.end=new j.LongBits(i.end.low>>>0,i.end.high>>>0).toNumber())),o},r.toObject=function(i,o){o||(o={});var s={};if(o.defaults){if(j.Long){var a=new j.Long(0,0,!1);s.begin=o.longs===String?a.toString():o.longs===Number?a.toNumber():a}else s.begin=o.longs===String?"0":0;if(j.Long){var a=new j.Long(0,0,!1);s.end=o.longs===String?a.toString():o.longs===Number?a.toNumber():a}else s.end=o.longs===String?"0":0}return i.begin!=null&&i.hasOwnProperty("begin")&&(typeof i.begin=="number"?s.begin=o.longs===String?String(i.begin):i.begin:s.begin=o.longs===String?j.Long.prototype.toString.call(i.begin):o.longs===Number?new j.LongBits(i.begin.low>>>0,i.begin.high>>>0).toNumber():i.begin),i.end!=null&&i.hasOwnProperty("end")&&(typeof i.end=="number"?s.end=o.longs===String?String(i.end):i.end:s.end=o.longs===String?j.Long.prototype.toString.call(i.end):o.longs===Number?new j.LongBits(i.end.low>>>0,i.end.high>>>0).toNumber():i.end),s},r.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},r.getTypeUrl=function(i){return i===void 0&&(i="type.googleapis.com"),i+"/onnx.TensorProto.Segment"},r}(),e.DataLocation=function(){var r={},t=Object.create(r);return t[r[0]="DEFAULT"]=0,t[r[1]="EXTERNAL"]=1,t}(),e}(),n.SparseTensorProto=function(){function e(r){if(this.dims=[],r)for(var t=Object.keys(r),i=0;i>>3){case 1:{s.values=B.onnx.TensorProto.decode(t,t.uint32());break}case 2:{s.indices=B.onnx.TensorProto.decode(t,t.uint32());break}case 3:{if(s.dims&&s.dims.length||(s.dims=[]),(a&7)===2)for(var u=t.uint32()+t.pos;t.pos>>0,t.dims[o].high>>>0).toNumber())}return i},e.toObject=function(t,i){i||(i={});var o={};if((i.arrays||i.defaults)&&(o.dims=[]),i.defaults&&(o.values=null,o.indices=null),t.values!=null&&t.hasOwnProperty("values")&&(o.values=B.onnx.TensorProto.toObject(t.values,i)),t.indices!=null&&t.hasOwnProperty("indices")&&(o.indices=B.onnx.TensorProto.toObject(t.indices,i)),t.dims&&t.dims.length){o.dims=[];for(var s=0;s>>0,t.dims[s].high>>>0).toNumber():t.dims[s]}return o},e.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},e.getTypeUrl=function(t){return t===void 0&&(t="type.googleapis.com"),t+"/onnx.SparseTensorProto"},e}(),n.TensorShapeProto=function(){function e(r){if(this.dim=[],r)for(var t=Object.keys(r),i=0;i>>3){case 1:{s.dim&&s.dim.length||(s.dim=[]),s.dim.push(B.onnx.TensorShapeProto.Dimension.decode(t,t.uint32()));break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.dim!=null&&t.hasOwnProperty("dim")){if(!Array.isArray(t.dim))return"dim: array expected";for(var i=0;i>>3){case 1:{u.dimValue=o.int64();break}case 2:{u.dimParam=o.string();break}case 3:{u.denotation=o.string();break}default:o.skipType(d&7);break}}return u},r.decodeDelimited=function(o){return o instanceof fe||(o=new fe(o)),this.decode(o,o.uint32())},r.verify=function(o){if(typeof o!="object"||o===null)return"object expected";var s={};if(o.dimValue!=null&&o.hasOwnProperty("dimValue")&&(s.value=1,!j.isInteger(o.dimValue)&&!(o.dimValue&&j.isInteger(o.dimValue.low)&&j.isInteger(o.dimValue.high))))return"dimValue: integer|Long expected";if(o.dimParam!=null&&o.hasOwnProperty("dimParam")){if(s.value===1)return"value: multiple values";if(s.value=1,!j.isString(o.dimParam))return"dimParam: string expected"}return o.denotation!=null&&o.hasOwnProperty("denotation")&&!j.isString(o.denotation)?"denotation: string expected":null},r.fromObject=function(o){if(o instanceof B.onnx.TensorShapeProto.Dimension)return o;var s=new B.onnx.TensorShapeProto.Dimension;return o.dimValue!=null&&(j.Long?(s.dimValue=j.Long.fromValue(o.dimValue)).unsigned=!1:typeof o.dimValue=="string"?s.dimValue=parseInt(o.dimValue,10):typeof o.dimValue=="number"?s.dimValue=o.dimValue:typeof o.dimValue=="object"&&(s.dimValue=new j.LongBits(o.dimValue.low>>>0,o.dimValue.high>>>0).toNumber())),o.dimParam!=null&&(s.dimParam=String(o.dimParam)),o.denotation!=null&&(s.denotation=String(o.denotation)),s},r.toObject=function(o,s){s||(s={});var a={};return s.defaults&&(a.denotation=""),o.dimValue!=null&&o.hasOwnProperty("dimValue")&&(typeof o.dimValue=="number"?a.dimValue=s.longs===String?String(o.dimValue):o.dimValue:a.dimValue=s.longs===String?j.Long.prototype.toString.call(o.dimValue):s.longs===Number?new j.LongBits(o.dimValue.low>>>0,o.dimValue.high>>>0).toNumber():o.dimValue,s.oneofs&&(a.value="dimValue")),o.dimParam!=null&&o.hasOwnProperty("dimParam")&&(a.dimParam=o.dimParam,s.oneofs&&(a.value="dimParam")),o.denotation!=null&&o.hasOwnProperty("denotation")&&(a.denotation=o.denotation),a},r.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},r.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TensorShapeProto.Dimension"},r}(),e}(),n.TypeProto=function(){function e(t){if(t)for(var i=Object.keys(t),o=0;o>>3){case 1:{a.tensorType=B.onnx.TypeProto.Tensor.decode(i,i.uint32());break}case 4:{a.sequenceType=B.onnx.TypeProto.Sequence.decode(i,i.uint32());break}case 5:{a.mapType=B.onnx.TypeProto.Map.decode(i,i.uint32());break}case 9:{a.optionalType=B.onnx.TypeProto.Optional.decode(i,i.uint32());break}case 8:{a.sparseTensorType=B.onnx.TypeProto.SparseTensor.decode(i,i.uint32());break}case 6:{a.denotation=i.string();break}default:i.skipType(u&7);break}}return a},e.decodeDelimited=function(i){return i instanceof fe||(i=new fe(i)),this.decode(i,i.uint32())},e.verify=function(i){if(typeof i!="object"||i===null)return"object expected";var o={};if(i.tensorType!=null&&i.hasOwnProperty("tensorType")){o.value=1;{var s=B.onnx.TypeProto.Tensor.verify(i.tensorType);if(s)return"tensorType."+s}}if(i.sequenceType!=null&&i.hasOwnProperty("sequenceType")){if(o.value===1)return"value: multiple values";o.value=1;{var s=B.onnx.TypeProto.Sequence.verify(i.sequenceType);if(s)return"sequenceType."+s}}if(i.mapType!=null&&i.hasOwnProperty("mapType")){if(o.value===1)return"value: multiple values";o.value=1;{var s=B.onnx.TypeProto.Map.verify(i.mapType);if(s)return"mapType."+s}}if(i.optionalType!=null&&i.hasOwnProperty("optionalType")){if(o.value===1)return"value: multiple values";o.value=1;{var s=B.onnx.TypeProto.Optional.verify(i.optionalType);if(s)return"optionalType."+s}}if(i.sparseTensorType!=null&&i.hasOwnProperty("sparseTensorType")){if(o.value===1)return"value: multiple values";o.value=1;{var s=B.onnx.TypeProto.SparseTensor.verify(i.sparseTensorType);if(s)return"sparseTensorType."+s}}return i.denotation!=null&&i.hasOwnProperty("denotation")&&!j.isString(i.denotation)?"denotation: string expected":null},e.fromObject=function(i){if(i instanceof B.onnx.TypeProto)return i;var o=new B.onnx.TypeProto;if(i.tensorType!=null){if(typeof i.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");o.tensorType=B.onnx.TypeProto.Tensor.fromObject(i.tensorType)}if(i.sequenceType!=null){if(typeof i.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");o.sequenceType=B.onnx.TypeProto.Sequence.fromObject(i.sequenceType)}if(i.mapType!=null){if(typeof i.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");o.mapType=B.onnx.TypeProto.Map.fromObject(i.mapType)}if(i.optionalType!=null){if(typeof i.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");o.optionalType=B.onnx.TypeProto.Optional.fromObject(i.optionalType)}if(i.sparseTensorType!=null){if(typeof i.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");o.sparseTensorType=B.onnx.TypeProto.SparseTensor.fromObject(i.sparseTensorType)}return i.denotation!=null&&(o.denotation=String(i.denotation)),o},e.toObject=function(i,o){o||(o={});var s={};return o.defaults&&(s.denotation=""),i.tensorType!=null&&i.hasOwnProperty("tensorType")&&(s.tensorType=B.onnx.TypeProto.Tensor.toObject(i.tensorType,o),o.oneofs&&(s.value="tensorType")),i.sequenceType!=null&&i.hasOwnProperty("sequenceType")&&(s.sequenceType=B.onnx.TypeProto.Sequence.toObject(i.sequenceType,o),o.oneofs&&(s.value="sequenceType")),i.mapType!=null&&i.hasOwnProperty("mapType")&&(s.mapType=B.onnx.TypeProto.Map.toObject(i.mapType,o),o.oneofs&&(s.value="mapType")),i.denotation!=null&&i.hasOwnProperty("denotation")&&(s.denotation=i.denotation),i.sparseTensorType!=null&&i.hasOwnProperty("sparseTensorType")&&(s.sparseTensorType=B.onnx.TypeProto.SparseTensor.toObject(i.sparseTensorType,o),o.oneofs&&(s.value="sparseTensorType")),i.optionalType!=null&&i.hasOwnProperty("optionalType")&&(s.optionalType=B.onnx.TypeProto.Optional.toObject(i.optionalType,o),o.oneofs&&(s.value="optionalType")),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},e.getTypeUrl=function(i){return i===void 0&&(i="type.googleapis.com"),i+"/onnx.TypeProto"},e.Tensor=function(){function t(i){if(i)for(var o=Object.keys(i),s=0;s>>3){case 1:{u.elemType=o.int32();break}case 2:{u.shape=B.onnx.TensorShapeProto.decode(o,o.uint32());break}default:o.skipType(d&7);break}}return u},t.decodeDelimited=function(o){return o instanceof fe||(o=new fe(o)),this.decode(o,o.uint32())},t.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.elemType!=null&&o.hasOwnProperty("elemType")&&!j.isInteger(o.elemType))return"elemType: integer expected";if(o.shape!=null&&o.hasOwnProperty("shape")){var s=B.onnx.TensorShapeProto.verify(o.shape);if(s)return"shape."+s}return null},t.fromObject=function(o){if(o instanceof B.onnx.TypeProto.Tensor)return o;var s=new B.onnx.TypeProto.Tensor;if(o.elemType!=null&&(s.elemType=o.elemType|0),o.shape!=null){if(typeof o.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");s.shape=B.onnx.TensorShapeProto.fromObject(o.shape)}return s},t.toObject=function(o,s){s||(s={});var a={};return s.defaults&&(a.elemType=0,a.shape=null),o.elemType!=null&&o.hasOwnProperty("elemType")&&(a.elemType=o.elemType),o.shape!=null&&o.hasOwnProperty("shape")&&(a.shape=B.onnx.TensorShapeProto.toObject(o.shape,s)),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},t.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto.Tensor"},t}(),e.Sequence=function(){function t(i){if(i)for(var o=Object.keys(i),s=0;s>>3){case 1:{u.elemType=B.onnx.TypeProto.decode(o,o.uint32());break}default:o.skipType(d&7);break}}return u},t.decodeDelimited=function(o){return o instanceof fe||(o=new fe(o)),this.decode(o,o.uint32())},t.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.elemType!=null&&o.hasOwnProperty("elemType")){var s=B.onnx.TypeProto.verify(o.elemType);if(s)return"elemType."+s}return null},t.fromObject=function(o){if(o instanceof B.onnx.TypeProto.Sequence)return o;var s=new B.onnx.TypeProto.Sequence;if(o.elemType!=null){if(typeof o.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");s.elemType=B.onnx.TypeProto.fromObject(o.elemType)}return s},t.toObject=function(o,s){s||(s={});var a={};return s.defaults&&(a.elemType=null),o.elemType!=null&&o.hasOwnProperty("elemType")&&(a.elemType=B.onnx.TypeProto.toObject(o.elemType,s)),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},t.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto.Sequence"},t}(),e.Map=function(){function t(i){if(i)for(var o=Object.keys(i),s=0;s>>3){case 1:{u.keyType=o.int32();break}case 2:{u.valueType=B.onnx.TypeProto.decode(o,o.uint32());break}default:o.skipType(d&7);break}}return u},t.decodeDelimited=function(o){return o instanceof fe||(o=new fe(o)),this.decode(o,o.uint32())},t.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.keyType!=null&&o.hasOwnProperty("keyType")&&!j.isInteger(o.keyType))return"keyType: integer expected";if(o.valueType!=null&&o.hasOwnProperty("valueType")){var s=B.onnx.TypeProto.verify(o.valueType);if(s)return"valueType."+s}return null},t.fromObject=function(o){if(o instanceof B.onnx.TypeProto.Map)return o;var s=new B.onnx.TypeProto.Map;if(o.keyType!=null&&(s.keyType=o.keyType|0),o.valueType!=null){if(typeof o.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");s.valueType=B.onnx.TypeProto.fromObject(o.valueType)}return s},t.toObject=function(o,s){s||(s={});var a={};return s.defaults&&(a.keyType=0,a.valueType=null),o.keyType!=null&&o.hasOwnProperty("keyType")&&(a.keyType=o.keyType),o.valueType!=null&&o.hasOwnProperty("valueType")&&(a.valueType=B.onnx.TypeProto.toObject(o.valueType,s)),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},t.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto.Map"},t}(),e.Optional=function(){function t(i){if(i)for(var o=Object.keys(i),s=0;s>>3){case 1:{u.elemType=B.onnx.TypeProto.decode(o,o.uint32());break}default:o.skipType(d&7);break}}return u},t.decodeDelimited=function(o){return o instanceof fe||(o=new fe(o)),this.decode(o,o.uint32())},t.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.elemType!=null&&o.hasOwnProperty("elemType")){var s=B.onnx.TypeProto.verify(o.elemType);if(s)return"elemType."+s}return null},t.fromObject=function(o){if(o instanceof B.onnx.TypeProto.Optional)return o;var s=new B.onnx.TypeProto.Optional;if(o.elemType!=null){if(typeof o.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");s.elemType=B.onnx.TypeProto.fromObject(o.elemType)}return s},t.toObject=function(o,s){s||(s={});var a={};return s.defaults&&(a.elemType=null),o.elemType!=null&&o.hasOwnProperty("elemType")&&(a.elemType=B.onnx.TypeProto.toObject(o.elemType,s)),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},t.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto.Optional"},t}(),e.SparseTensor=function(){function t(i){if(i)for(var o=Object.keys(i),s=0;s>>3){case 1:{u.elemType=o.int32();break}case 2:{u.shape=B.onnx.TensorShapeProto.decode(o,o.uint32());break}default:o.skipType(d&7);break}}return u},t.decodeDelimited=function(o){return o instanceof fe||(o=new fe(o)),this.decode(o,o.uint32())},t.verify=function(o){if(typeof o!="object"||o===null)return"object expected";if(o.elemType!=null&&o.hasOwnProperty("elemType")&&!j.isInteger(o.elemType))return"elemType: integer expected";if(o.shape!=null&&o.hasOwnProperty("shape")){var s=B.onnx.TensorShapeProto.verify(o.shape);if(s)return"shape."+s}return null},t.fromObject=function(o){if(o instanceof B.onnx.TypeProto.SparseTensor)return o;var s=new B.onnx.TypeProto.SparseTensor;if(o.elemType!=null&&(s.elemType=o.elemType|0),o.shape!=null){if(typeof o.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");s.shape=B.onnx.TensorShapeProto.fromObject(o.shape)}return s},t.toObject=function(o,s){s||(s={});var a={};return s.defaults&&(a.elemType=0,a.shape=null),o.elemType!=null&&o.hasOwnProperty("elemType")&&(a.elemType=o.elemType),o.shape!=null&&o.hasOwnProperty("shape")&&(a.shape=B.onnx.TensorShapeProto.toObject(o.shape,s)),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},t.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto.SparseTensor"},t}(),e}(),n.OperatorSetIdProto=function(){function e(r){if(r)for(var t=Object.keys(r),i=0;i>>3){case 1:{s.domain=t.string();break}case 2:{s.version=t.int64();break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){return typeof t!="object"||t===null?"object expected":t.domain!=null&&t.hasOwnProperty("domain")&&!j.isString(t.domain)?"domain: string expected":t.version!=null&&t.hasOwnProperty("version")&&!j.isInteger(t.version)&&!(t.version&&j.isInteger(t.version.low)&&j.isInteger(t.version.high))?"version: integer|Long expected":null},e.fromObject=function(t){if(t instanceof B.onnx.OperatorSetIdProto)return t;var i=new B.onnx.OperatorSetIdProto;return t.domain!=null&&(i.domain=String(t.domain)),t.version!=null&&(j.Long?(i.version=j.Long.fromValue(t.version)).unsigned=!1:typeof t.version=="string"?i.version=parseInt(t.version,10):typeof t.version=="number"?i.version=t.version:typeof t.version=="object"&&(i.version=new j.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber())),i},e.toObject=function(t,i){i||(i={});var o={};if(i.defaults)if(o.domain="",j.Long){var s=new j.Long(0,0,!1);o.version=i.longs===String?s.toString():i.longs===Number?s.toNumber():s}else o.version=i.longs===String?"0":0;return t.domain!=null&&t.hasOwnProperty("domain")&&(o.domain=t.domain),t.version!=null&&t.hasOwnProperty("version")&&(typeof t.version=="number"?o.version=i.longs===String?String(t.version):t.version:o.version=i.longs===String?j.Long.prototype.toString.call(t.version):i.longs===Number?new j.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber():t.version),o},e.prototype.toJSON=function(){return this.constructor.toObject(this,gt.util.toJSONOptions)},e.getTypeUrl=function(t){return t===void 0&&(t="type.googleapis.com"),t+"/onnx.OperatorSetIdProto"},e}(),n.OperatorStatus=function(){var e={},r=Object.create(e);return r[e[0]="EXPERIMENTAL"]=0,r[e[1]="STABLE"]=1,r}(),n.FunctionProto=function(){function e(r){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],r)for(var t=Object.keys(r),i=0;i>>3){case 1:{s.name=t.string();break}case 4:{s.input&&s.input.length||(s.input=[]),s.input.push(t.string());break}case 5:{s.output&&s.output.length||(s.output=[]),s.output.push(t.string());break}case 6:{s.attribute&&s.attribute.length||(s.attribute=[]),s.attribute.push(t.string());break}case 11:{s.attributeProto&&s.attributeProto.length||(s.attributeProto=[]),s.attributeProto.push(B.onnx.AttributeProto.decode(t,t.uint32()));break}case 7:{s.node&&s.node.length||(s.node=[]),s.node.push(B.onnx.NodeProto.decode(t,t.uint32()));break}case 8:{s.docString=t.string();break}case 9:{s.opsetImport&&s.opsetImport.length||(s.opsetImport=[]),s.opsetImport.push(B.onnx.OperatorSetIdProto.decode(t,t.uint32()));break}case 10:{s.domain=t.string();break}default:t.skipType(a&7);break}}return s},e.decodeDelimited=function(t){return t instanceof fe||(t=new fe(t)),this.decode(t,t.uint32())},e.verify=function(t){if(typeof t!="object"||t===null)return"object expected";if(t.name!=null&&t.hasOwnProperty("name")&&!j.isString(t.name))return"name: string expected";if(t.input!=null&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(var i=0;i{"use strict";ga();Ks();yt=fi(gi());Bn();On=class{static arraysEqual(e,r){if(e.length!==r.length)return!1;for(let t=0;t1&&m>1)return;a[s-u]=Math.max(d,m)}return a}static index(e,r){let t=new Array(r.length);return n.fillIndex(e,r,t),t}static fillIndex(e,r,t){let i=e.length-r.length;for(let o=0;o=0;P--)d[P]=A%s[P],A=Math.floor(A/s[P]);$||(n.fillIndex(d,e.dims,m),w=e.get(m)),I||(n.fillIndex(d,r.dims,b),x=r.get(b)),u.set(d,t(w,x))}}return u}}static isValidBroadcast(e,r){let t=e.length,i=r.length;if(t>i)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[i-o])return!1;return!0}static getBroadcastDims(e,r){let t=e.length,i=[];for(let o=0;o1&&a===1&&i.unshift(s)}return i}},_a=class{static getShapeOfGemmResult(e,r,t,i,o){if(e.length!==2||t.length!==2)throw new Error("shape need to be of size 2");let s,a,u;r?(s=e[1],a=e[0]):(s=e[0],a=e[1]);let d=-1;if(i?(u=t[0],d=1):(u=t[1],d=0),t[d]!==a)throw new Error("dimension mismatch");if(s<=0||u<=0||a<=0)throw new Error("invalid shape specified");if(o&&!qt.isValidBroadcast(o,[s,u]))throw new Error("gemm: invalid bias shape for broadcast");return[s,u,a]}},Nt=class n{static tensorDataTypeFromProto(e){switch(e){case yt.onnx.TensorProto.DataType.INT8:return"int8";case yt.onnx.TensorProto.DataType.UINT8:return"uint8";case yt.onnx.TensorProto.DataType.BOOL:return"bool";case yt.onnx.TensorProto.DataType.INT16:return"int16";case yt.onnx.TensorProto.DataType.UINT16:return"uint16";case yt.onnx.TensorProto.DataType.INT32:return"int32";case yt.onnx.TensorProto.DataType.UINT32:return"uint32";case yt.onnx.TensorProto.DataType.FLOAT:return"float32";case yt.onnx.TensorProto.DataType.DOUBLE:return"float64";case yt.onnx.TensorProto.DataType.STRING:return"string";case yt.onnx.TensorProto.DataType.INT64:return"int32";case yt.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${yt.onnx.TensorProto.DataType[e]}`)}}static tensorDataTypeStringToEnum(e){switch(e){case"int8":return yt.onnx.TensorProto.DataType.INT8;case"uint8":return yt.onnx.TensorProto.DataType.UINT8;case"bool":return yt.onnx.TensorProto.DataType.BOOL;case"int16":return yt.onnx.TensorProto.DataType.INT16;case"uint16":return yt.onnx.TensorProto.DataType.UINT16;case"int32":return yt.onnx.TensorProto.DataType.INT32;case"uint32":return yt.onnx.TensorProto.DataType.UINT32;case"float32":return yt.onnx.TensorProto.DataType.FLOAT;case"float64":return yt.onnx.TensorProto.DataType.DOUBLE;case"string":return yt.onnx.TensorProto.DataType.STRING;case"int64":return yt.onnx.TensorProto.DataType.INT64;case"uint64":return yt.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${e}`)}}static tensorDimsFromProto(e){return e.map(r=>Xr.isLong(r)?r.toNumber():r)}static tensorValueTypeFromProto(e){return{tensorType:n.tensorDataTypeFromProto(e.elemType),shape:{dims:n.tensorDimsFromProto(e.shape.dim.map(r=>r.dimValue))}}}static tensorDimsFromORTFormat(e){let r=[];for(let t=0;te.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return n.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 n.getSizeFromDimensionRange(e,0,r)}static getSizeFromDimensionRange(e,r,t){let i=1;for(let o=r;o=0;--i)t[i]=t[i+1]*e[i+1];return t}static transpose(e){return e.slice().reverse()}static indicesToOffset(e,r,t){t===void 0&&(t=e.length);let i=0;for(let o=0;o=r)throw new Error("unsupported axis for this operation.");return e<0?e+r:e}static normalizeAxes(e,r){return e.map(t=>this.normalizeAxis(t,r))}static incrementIndex(e,r,t){if(r.length===0||e.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(t===void 0)t=r.length;else if(t<=0||t>r.length)throw new Error("Incorrect axis to increment on");for(let i=t-1;i>=0&&(e[i]++,!(e[i]=e.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");i[u]=e[u]}else i[u]=r[u];s*=i[u]}}let a=n.size(e);if(o!==-1){if(a%s!==0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${r}]`);i[o]=a/s}else if(s!==a)throw new Error("reshapedDims and originalDims don't have matching sizes");return i}static sortBasedOnPerm(e,r){return r?r.map(t=>e[t]):e.slice().reverse()}static padShape(e,r){let t=e.length;return e.map((i,o)=>i+r[o]+r[o+t])}static areEqual(e,r){return e.length!==r.length?!1:e.every((t,i)=>t===r[i])}static validateDimsAndCalcSize(e){if(e.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let r=1;for(let t of e){if(!Number.isInteger(t))throw new TypeError(`Invalid shape: ${t} is not an integer`);if(t<0||t>2147483647)throw new TypeError(`Invalid shape: length ${t} is not allowed`);r*=t}return r}static flattenShape(e,r){r<0&&(r+=e.length);let t=e.reduce((s,a)=>s*a,1),i=e.slice(r).reduce((s,a)=>s*a,1);return[t/i,i]}static squeezeShape(e,r){let t=new Array;r=n.normalizeAxes(r,e.length);for(let i=0;i=0;if(o&&e[i]!==1)throw new Error("squeeze an axis of size different than 1");(r.length===0&&e[i]>1||r.length>0&&!o)&&t.push(e[i])}return t}static unsqueezeShape(e,r){let t=new Array(e.length+r.length);t.fill(0);for(let o=0;o=t.length)throw new Error("'axes' has an out of range axis");if(t[s]!==0)throw new Error("'axes' has a duplicate axis");t[s]=1}let i=0;for(let o=0;o=t.length?t.push(r[a+2]):t[a]=r[a+2];for(let a=0;a=t[a]||s[a+t.length]>=t[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,r,t,i,o,s){if(s){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(i.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let a=0;a{"use strict";oh=fi(Kf());Ks();no();qe=fi(gi());it();lu=xe.experimental.fbs,Pt=class n{constructor(e,r,t,i,o,s=oh.Guid.create()){this.dims=e;this.type=r;this.dataProvider=t;this.asyncDataProvider=i;this.cache=o;this.dataId=s;this.size=be.validateDimsAndCalcSize(e);let a=this.size,u=t===void 0&&i===void 0&&o===void 0;if(o!==void 0&&o.length!==a)throw new RangeError("Input dims doesn't match data length.");if(r==="string"){if(o!==void 0&&(!Array.isArray(o)||!o.every(d=>typeof d=="string")))throw new TypeError("cache should be a string array");u&&(this.cache=new Array(a))}else{if(o!==void 0){let d=ah(r);if(!(o instanceof d))throw new TypeError(`cache should be type ${d.name}`)}if(u){let d=new ArrayBuffer(a*Y1(r));this.cache=X1(d,r)}}}get data(){if(this.cache===void 0){let e=this.dataProvider(this.dataId);if(e.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=e}return this.cache}get stringData(){if(this.type!=="string")throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw new TypeError("type cannot be non-number (string)")}get(e){return this.data[be.indicesToOffset(e,this.strides)]}set(e,r){this.data[be.indicesToOffset(e,this.strides)]=r}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=be.computeStrides(this.dims)),this._strides}static fromProto(e){if(!e)throw new Error("cannot construct Value from an empty tensor");let r=Nt.tensorDataTypeFromProto(e.dataType),t=Nt.tensorDimsFromProto(e.dims),i=new n(t,r);if(r==="string")e.stringData.forEach((o,s)=>{i.data[s]=uo(o)});else if(e.rawData&&typeof e.rawData.byteLength=="number"&&e.rawData.byteLength>0){let o=i.data,s=new DataView(e.rawData.buffer,e.rawData.byteOffset,e.rawData.byteLength),a=nh(e.dataType),u=e.rawData.byteLength/a;if(e.rawData.byteLength%a!==0)throw new Error("invalid buffer length");if(o.length!==u)throw new Error("buffer length mismatch");for(let d=0;d0){let o=i.data,s=new DataView(e.rawDataArray().buffer,e.rawDataArray().byteOffset,e.rawDataLength()),a=nh(e.dataType()),u=e.rawDataLength()/a;if(e.rawDataLength()%a!==0)throw new Error("invalid buffer length");if(o.length!==u)throw new Error("buffer length mismatch");for(let d=0;d{"use strict";Z1={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},J1={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"}});var Je=q(()=>{"use strict"});async function cu(n,e=t=>0,r){return new Promise((t,i)=>{let o=0,s=()=>{if(n()){t();return}o++;let a=e(o);if(r!=null&&o>=r){i();return}setTimeout(s,a)};s()})}function xa(n){return yi(typeof n<"u"&&n.length!==0,()=>"empty string found for sampler name"),"get"+n.charAt(0).toUpperCase()+n.slice(1)}function dh(n){return yi(typeof n<"u"&&n.length!==0,()=>"empty string found for sampler name"),"get"+n.charAt(0).toUpperCase()+n.slice(1)+"AtOutCoords"}function bi(n,e){let r=JSON.parse(JSON.stringify(n));return r=e,r}function vi(n,e){return e.map(r=>n[r]).join(", ")}function Kt(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function Ar(n=6){return["x","y","z","w","u","v"].slice(0,n)}var Mr=q(()=>{"use strict";it()});function Q1(n,e){return Ar(e).map(r=>`${n}.${r}`)}function wi(n,e){return e===1?[n]:Q1(n,e)}function Nr(){return` + float getChannel(vec4 frag, int dim) { + int modCoord = imod(dim, 2); + return modCoord == 0 ? frag.r : frag.g; + } + + float getChannel(vec4 frag, vec2 innerDims) { + vec2 modCoord = mod(innerDims, 2.); + return modCoord.x == 0. ? + (modCoord.y == 0. ? frag.r : frag.g) : + (modCoord.y == 0. ? frag.b : frag.a); + } + `}var Rn=q(()=>{"use strict";Mr()});function t$(n,e,r){if(n===0)return"false";if(n===1)return`rc > ${e[0]}`;let t="";for(let i=n-2;i= ${e[i-n+2]}`,i= ${n[0]} ? 0. : getA(rc + 1), + 0, 0`;let t="r, c",i="r, cp1",o="rp1, c",s="rp1, cp1",a="";if(r>2)for(let u=0;u= ${t}; + bool cEdge = cp1 >= ${r}; + `}var ch,e$,fh,ph=q(()=>{"use strict";vt();Je();Mr();Rn();ch={name:"pack",inputNames:["A"],inputTypes:[1]},e$=(n,e)=>{let r=Ie(n.session.backend.glContext.version),t=e.dims,i=t.length,o=e.dims.length,s=Kt(o),a=wi("rc",o),u=n$(o,a,t[t.length-2],t[t.length-1]),d;i===0?d=[1,1]:i===1?d=[t[0],1]:d=[t[o-1],t[o-2]];let m=t$(o,d,a),b=r$(t,a),w=` + void main() { + ${s} rc = getOutputCoords(); + + if(${m}) { + ${r.output} = vec4(0); + } else { + ${u} + + ${r.output} = vec4(${b}); + } + } + `;return{...ch,hasMain:!0,output:{dims:e.dims,type:e.type,textureType:2},shaderSource:w}},fh=(n,e)=>({...ch,get:()=>e$(n,e)})});function fu(n){if(n.length===0)return[1,1,1];let e=1;for(let r=0;r1?n[n.length-2]:1,n[n.length-1]]}function mh(n,e){let r=!1;return n.length===0||e.length===0?r=!0:n.length<2||e.length<2?r=n[n.length-1]===e[e.length-1]:r=n[n.length-1]===e[e.length-1]&&n[n.length-2]===e[e.length-2],r}function a$(n){let e=be.computeStrides(n),r=["b","r","c"],t="index";return` + ivec3 inputCoordsFromReshapedOutCoords(int index) { + ${e.map((o,s)=>{let a=`int ${r[s]} = ${t} / ${o}`,u=s===e.length-1?`int ${r[s+1]} = ${t} - ${r[s]} * ${o}`:`index -= ${r[s]} * ${o}`;return`${a}; ${u};`}).join("")} + return ivec3(b, r, c); + } + `}function s$(n){let e=be.computeStrides(n);return` + int getFlattenedIndex(ivec3 coords) { + // reverse y, z order + return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y; + } +`}var i$,o$,hh,gh=q(()=>{"use strict";it();vt();Je();Rn();i$=n=>({name:"Reshape (packed)",inputTypes:[2],inputNames:["A"],cacheHint:`${n}`}),o$=(n,e,r,t)=>{let i=e.dims,o=t,s="";for(let d=0;d<4;d++){let m="";switch(d){case 0:m="outputCoords = rc;";break;case 1:m="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:m="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:m="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}s+=` + ${m} + ${d>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} + int flattenedIndex = getFlattenedIndex(outputCoords); + + ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); + vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); + + result[${d}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); + + ${d>0?"}":""} + `}let a=Ie(n.session.backend.glContext.version),u=` + ${a$(i)} + ${s$(o)} + ${Nr()} + + void main() { + ivec3 rc = getOutputCoords(); + + vec4 result = vec4(0.0); + + ivec3 outputCoords; + int rows = ${o[2]}; + int cols = ${o[1]}; + + ${s} + ${a.output} = result; + } + `;return{...r,output:{dims:o,type:e.type,textureType:2},shaderSource:u,hasMain:!0}},hh=(n,e,r)=>{let t=i$(r);return{...t,get:()=>o$(n,e,t,r)}}});var pu,yh=q(()=>{"use strict";vt();Je();pu=(n,e)=>{let r=e.shape,t=Ie(n.session.backend.glContext.version),i=` + const float FLOAT_MAX = 1.70141184e38; + const float FLOAT_MIN = 1.17549435e-38; + + bool isNaN(float val) { + return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; + } + + highp vec4 encodeAsUint8(highp float v) { + if (isNaN(v)) { + return vec4(255, 255, 255, 255); + } + + highp float av = abs(v); + + if(av < FLOAT_MIN) { + return vec4(0.0, 0.0, 0.0, 0.0); + } else if(v > FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; + } else if(v < -FLOAT_MAX) { + return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; + } + + highp vec4 c = vec4(0,0,0,0); + + highp float e = floor(log2(av)); + highp float m = exp2(fract(log2(av))) - 1.0; + + c[2] = floor(128.0 * m); + m -= c[2] / 128.0; + c[1] = floor(32768.0 * m); + m -= c[1] / 32768.0; + c[0] = floor(8388608.0 * m); + + highp float ebias = e + 127.0; + c[3] = floor(ebias / 2.0); + ebias -= c[3] * 2.0; + c[2] += floor(ebias) * 128.0; + + c[3] += 128.0 * step(0.0, -v); + + return c / 255.0; + } + + void main() { + float value = ${t.texture2D}(X,TexCoords).r; + ${t.output} = encodeAsUint8(value); + }`,o={name:"Uint8Encode",inputTypes:[0],inputNames:["X"],output:{dims:r,type:e.tensor.type,textureType:3},shaderSource:i,hasMain:!0};return n.executeProgram(o,[e.tensor])}});function l$(n,e){if(n===1)return"rc";let r="";for(let t=0;t{"use strict";vt();Je();Mr();Rn();bh={name:"unpack",inputNames:["A"],inputTypes:[2]},u$=(n,e)=>{let r=e.dims.length,t=wi("rc",r),i=t.slice(-2),o=Kt(r),s=Nr(),u=e.dims.length===0?"":l$(r,t),d=r<=1?"rc":`vec2(${i.join(",")})`,m=Ie(n.session.backend.glContext.version),b=` + ${s} + void main() { + ${o} rc = getOutputCoords(); + + // Sample the texture with the coords to get the rgba channel value. + vec4 packedInput = getA(${u}); + + ${m.output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0); + } + `;return{...bh,hasMain:!0,output:{dims:e.dims,type:e.type,textureType:0},shaderSource:b}},vh=(n,e)=>({...bh,get:()=>u$(n,e)})});var $a,lo,Ta,co=q(()=>{"use strict";cr();$a=class{constructor(e,r=1){if(r===1)this.internalFormat=e.R32F,this.format=e.RED,this.textureType=e.FLOAT,this.channelSize=r;else if(r===4)this.internalFormat=e.RGBA32F,this.format=e.RGBA,this.textureType=e.FLOAT,this.channelSize=r;else throw new Error(`Invalid number of channels: ${r}`)}encode(e,r){let t,i;return e.constructor!==Float32Array&&(at.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(e)),r*this.channelSize>e.length?(at.warning("Encoder","Source data too small. Allocating larger array"),i=e,t=this.allocate(r*this.channelSize),i.forEach((o,s)=>t[s]=o)):(i=e,t=i),t}allocate(e){return new Float32Array(e*4)}decode(e,r){return this.channelSize===1?e.filter((i,o)=>o%4===0).subarray(0,r):e.subarray(0,r)}},lo=class{constructor(e,r=1,t){if(r!==1&&r!==4)throw new Error(`Invalid number of channels: ${r}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.channelSize=r,this.textureType=t||e.FLOAT}encode(e,r){let t=e;return this.channelSize===1&&(at.verbose("Encoder","Exploding into a larger array"),t=this.allocate(r),e.forEach((i,o)=>t[o*4]=i)),t}allocate(e){return new Float32Array(e*4)}decode(e,r){return this.channelSize===1?e.filter((i,o)=>o%4===0).subarray(0,r):e.subarray(0,r)}},Ta=class{constructor(e,r=1){this.channelSize=4;if(r===1)this.internalFormat=e.ALPHA,this.format=e.ALPHA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=r;else if(r===4)this.internalFormat=e.RGBA,this.format=e.RGBA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=r;else throw new Error(`Invalid number of channels: ${r}`)}encode(e,r){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}allocate(e){return new Uint8Array(e*this.channelSize)}decode(e,r){if(e instanceof Uint8Array)return e.subarray(0,r);throw new Error(`Invalid array type: ${e.constructor}`)}}});var fo,_h,hu,xh=q(()=>{"use strict";it();Je();fo=(n,e,r)=>{let t=r===0||r===1?1:4,i=r===2,o=r===1||r===2,s=r===4?e.length-1:void 0,a=r===4?e.map((u,d)=>d===e.length-1?u*4:u):void 0;return hu(n,e,t,a,{isPacked:i,reverseWH:o,breakAxis:s})},_h=(n,e,r)=>{let t=fo(n,e,r);return[t.width,t.height]},hu=(n,e,r=1,t,i)=>{let o=!!(i&&i.isPacked),[s,a]=n.computeTextureWH(o&&t||e,i),u=e.length,d=e.slice(0);if(u===0&&(d=[1]),r===1)t=e;else if(o){if(r!==4)throw new Error("a packed texture must be 4-channel");t=e,u>0&&(d[u-1]=Math.ceil(d[u-1]/2)),u>1&&(d[u-2]=Math.ceil(d[u-2]/2))}else if(!t)throw new Error("Unpacked shape is needed when using channels > 1");return{width:s,height:a,channels:r,isPacked:o,shape:d,strides:be.computeStrides(d),unpackedShape:t,reversedWH:i&&i.reverseWH}}});var c$,Sa,Th=q(()=>{"use strict";cr();Bn();it();ph();gh();yh();wh();co();xh();Je();c$=(n,e)=>{let r=e.map(i=>`${i.unpackedShape.join(",")};${i.width}x${i.height}`).join("_"),t=n.name;return n.cacheHint&&(t+="["+n.cacheHint+"]"),t+=":"+r,t},Sa=class{constructor(e){this.session=e;this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,r){return _h(this.session.layoutStrategy,e,r)}executeProgram(e,r){if(r.lengththis.readTexture(s),async a=>this.readTextureAsync(s),void 0,o),texture:t};return this.setTextureData(s.tensor.dataId,s,e.isPacked),s}getTextureData(e,r=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,r):r?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,r,t=!1){this.session.isInitializer(e)?this.session.setTextureData(e,r,t):(t?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,r)}isTextureLayoutCached(e,r=!1){return!!this.getTextureData(e.dataId,r)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat(pu(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat(pu(this,e))}pack(e){return this.executeProgram(fh(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram(vh(this,e.tensor),[e.tensor])}}});var mu,Fe,Rt=q(()=>{"use strict";mu=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Fe=n=>new mu(n)});var Sh,Ih,Ch,f$,p$,Ah=q(()=>{"use strict";Rt();vt();Je();Sh={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[0,0,0,0,0]},Ih=(n,e,r)=>(p$(e),[n.run({...Sh,cacheHint:r.cacheKey,get:()=>f$(n,e,r)},e)]),Ch=n=>{let e=n.attributes.getFloat("epsilon",1e-5),r=n.attributes.getFloat("momentum",.9),t=n.attributes.getInt("spatial",1);return Fe({epsilon:e,momentum:r,spatial:t})},f$=(n,e,r)=>{let t=Ie(n.session.backend.glContext.version),i=e[0].dims.length,[o,s]=n.calculateTextureWidthAndHeight(e[1].dims,0),a=` + float process(int[${i}] indices) { + vec2 position = offsetToCoords(indices[1], ${o}, ${s}); + float scale = getColorAsFloat(${t.texture2D}(Scale, position)); + float mean = getColorAsFloat(${t.texture2D}(Mean, position)); + float variance = getColorAsFloat(${t.texture2D}(Variance, position)); + float b = getColorAsFloat(${t.texture2D}(B, position)); + + return scale * ( (_A(indices) - mean) / sqrt(variance + float(${r.epsilon})) ) + b; + }`;return{...Sh,output:{dims:e[0].dims,type:e[0].type,textureType:0},shaderSource:a}},p$=n=>{if(!n||n.length!==5)throw new Error("BatchNormalization requires 5 inputs.");let e=n[0],r=n[1],t=n[2],i=n[3],o=n[4];if(e.dims.length<3||r.dims.length!==1||t.dims.length!==1||i.dims.length!==1||o.dims.length!==1)throw new Error("invalid input shape.");if(r.dims[0]!==e.dims[1]||t.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1]||o.dims[0]!==e.dims[1])throw new Error("invalid input shape.");if(e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64"||t.type!=="float32"&&t.type!=="float64"||i.type!=="float32"&&i.type!=="float64"||o.type!=="float32"&&o.type!=="float64")throw new Error("invalid input tensor types.")}});var Ia,mr,me,po,Ca,Zr=q(()=>{"use strict";Ia=class{constructor(e,r,t,i){this.glContext=e;this.programInfo=r;this.inputTextureLayouts=t;this.outputTextureLayout=i}},mr=class{constructor(e){this.context=e}},me=class{constructor(e,r){this.routineBody=e;this.dependencies=r}},po=class{constructor(e,r,t){this.name=e;t?this.dependencies=t:this.dependencies=[],r&&(this.routineBody=r)}addDependency(e){e&&this.dependencies.push(e)}},Ca=class{static returnOrderedNodes(e){if(!e||e.length===0)return[];if(e.length===1)return e;let r=new Set,t=new Set,i=new Array;return this.createOrderedNodes(e,r,t,i),i}static createOrderedNodes(e,r,t,i){for(let o=0;o0)for(let s=0;s b); + } + vec4 ${n}(vec4 v1, vec4 v2) { + return vec4( v1.r > v2.r , + v1.g > v2.g, + v1.b > v2.b, + v1.a > v2.a ); + } + `,name:n,type:0}}function _$(){let n="less_";return{body:` + float ${n}(float a, float b) { + return float(a < b); + } + vec4 ${n}(vec4 v1, vec4 v2) { + return vec4( v1.r < v2.r , + v1.g < v2.g, + v1.b < v2.b, + v1.a < v2.a ); + } + `,name:n,type:0}}function x$(){let n="and_";return{body:` + float ${n}(float a, float b) { + return float( bool(a) && bool(b) ); + } + vec4 ${n}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r && b2.r , + b1.g && b2.g, + b1.b && b2.b, + b1.a && b2.a ); + } + `,name:n,type:0}}function $$(){let n="or_";return{body:` + float ${n}(float a, float b) { + return float( bool(a) || bool(b) ); + } + vec4 ${n}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r || b2.r , + b1.g || b2.g, + b1.b || b2.b, + b1.a || b2.a ); + } + `,name:n,type:0}}function T$(){let n="xor_";return{body:` + float ${n}(float a, float b) { + return float( bool(a) ^^ bool(b) ); + } + vec4 ${n}(vec4 v1, vec4 v2) { + bvec4 b1 = bvec4(v1); + bvec4 b2 = bvec4(v2); + return vec4( b1.r ^^ b2.r , + b1.g ^^ b2.g, + b1.b ^^ b2.b, + b1.a ^^ b2.a ); + } + `,name:n,type:0}}function S$(){return C$("pow")}function I$(){let n="prelu_";return{body:` + float ${n}(float a, float b) { + return a < 0.0 ? a * b: a; + } + vec4 ${n}(vec4 v1, vec4 v2) { + return vec4( + v1.r < 0.0 ? v1.r * v2.r: v1.r, + v1.g < 0.0 ? v1.g * v2.g: v1.g, + v1.b < 0.0 ? v1.b * v2.b: v1.b, + v1.a < 0.0 ? v1.a * v2.a: v1.a + ); + } + `,name:n,type:0}}function C$(n){let e=`${n}_`;return{body:` + float ${e}(float a, float b) { + return ${n}(a, b); + } + vec4 ${e}(vec4 v1, vec4 v2) { + return ${n}(v1, v2); + } + `,name:e,type:0}}var gr,A$,Eh,Oh,Ph,kh,Dh,Bh,Rh,zh,Mh,Nh,Lh,jh,Uh=q(()=>{"use strict";it();Zr();vt();Je();gr=(n,e,r,t=e[0].type,i)=>{let o=n.session.pack?2:0;return{name:r.name,inputNames:["A","B"],inputTypes:[o,o],cacheHint:i,get:()=>A$(n,e,r,t)}},A$=(n,e,r,t=e[0].type)=>{let i=n.session.pack?2:0,o=!be.areEqual(e[0].dims,e[1].dims),s=e[0].dims,a=n.session.pack;if(o){let m=qt.calcShape(e[0].dims,e[1].dims,!1);if(!m)throw new Error("Can't perform binary op on the given tensors");s=m;let b=s.length,w=e[0].dims.length!==0?e[0].dims.length:1,x=e[1].dims.length!==0?e[1].dims.length:1,$=e[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",I=e[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",A=Ie(n.session.backend.glContext.version),k=a?` + ${r.body} + void main() { + vec4 a = getAAtOutCoords(); + vec4 b = getBAtOutCoords(); + vec4 result = ${r.name}(a, b); + ${A.output} = result; + }`:` + ${r.body} + float process(int indices[${b}]) { + int aindices[${w}]; + int bindices[${x}]; + ${$} + ${I} + return ${r.name}(_A(aindices), _B(bindices)); + }`;return{name:r.name,inputNames:["A","B"],inputTypes:[i,i],output:{dims:s,type:t,textureType:i},shaderSource:k,hasMain:a}}let u=Ie(n.session.backend.glContext.version),d=` + ${r.body} + void main() { + vec4 v1 = ${u.texture2D}(A, TexCoords); + vec4 v2 = ${u.texture2D}(B, TexCoords); + vec4 result = ${r.name}(v1, v2); + ${u.output} = result; + } + `;return{name:r.name,inputNames:["A","B"],inputTypes:[i,i],output:{dims:e[0].dims,type:t,textureType:i},shaderSource:d,hasMain:!0}},Eh=(n,e)=>[n.run(gr(n,e,m$()),e)],Oh=(n,e)=>[n.run(gr(n,e,x$(),"bool"),e)],Ph=(n,e)=>[n.run(gr(n,e,g$()),e)],kh=(n,e)=>[n.run(gr(n,e,v$(),"bool"),e)],Dh=(n,e)=>[n.run(gr(n,e,w$(),"bool"),e)],Bh=(n,e)=>[n.run(gr(n,e,_$(),"bool"),e)],Rh=(n,e)=>[n.run(gr(n,e,y$()),e)],zh=(n,e)=>[n.run(gr(n,e,$$(),"bool"),e)],Mh=(n,e)=>[n.run(gr(n,e,S$()),e)],Nh=(n,e)=>[n.run(gr(n,e,I$()),e)],Lh=(n,e)=>[n.run(gr(n,e,b$()),e)],jh=(n,e)=>[n.run(gr(n,e,T$(),"bool"),e)]});var Fh,Vh,O$,Gh=q(()=>{"use strict";it();Fh=(n,e,r)=>(O$(e),[n.cast(e[0],r)]),Vh=n=>Nt.tensorDataTypeFromProto(n.attributes.getInt("to")),O$=n=>{if(!n||n.length!==1)throw new Error("Cast requires 1 input.");if(n[0].type==="string")throw new Error("Invalid input type.")}});var P$,k$,Wh,Aa,Hh=q(()=>{"use strict";vt();Je();Mr();Rn();P$=(n,e)=>({name:"Concat (packed)",inputNames:Array.from({length:n},(r,t)=>`X${t}`),inputTypes:Array(n).fill(2),cacheHint:e}),k$=(n,e,r,t)=>{let i=r[0].dims.slice();if(t>=i.length||t<-1*i.length)throw new Error("axis specified for concat doesn't match input dimensionality");t<0&&(t=i.length+t);let o=i.slice(0);for(let F=1;FF.dims),b=Ar(s),w=new Array(m.length-1);w[0]=m[0][t];for(let F=1;F= ${w[F-1]}) { + return getChannel( + getX${F}(${Aa(b,x,Y)}), + vec2(${Aa($,x,Y)})); + }`}let k=w.length,P=w[w.length-1];A+=` + return getChannel( + getX${k}(${Aa(b,x,P)}), + vec2(${Aa($,x,P)}));`;let z=Ie(n.session.backend.glContext.version),U=` + ${d} + float getValue(${b.map(F=>"int "+F)}) { + ${A} + } + + void main() { + ${u} coords = getOutputCoords(); + int lastDim = coords.${b[s-1]}; + coords.${b[s-1]} = coords.${b[s-2]}; + coords.${b[s-2]} = lastDim; + + vec4 result = vec4(getValue(${a}), 0., 0., 0.); + + ${a[s-1]} = ${a[s-1]} + 1; + if (${a[s-1]} < ${o[s-1]}) { + result.g = getValue(${a}); + } + + ${a[s-2]} = ${a[s-2]} + 1; + if (${a[s-2]} < ${o[s-2]}) { + result.a = getValue(${a}); + } + + ${a[s-1]} = ${a[s-1]} - 1; + if (${a[s-2]} < ${o[s-2]} && + ${a[s-1]} < ${o[s-1]}) { + result.b = getValue(${a}); + } + ${z.output} = result; + } + `;return{...e,output:{dims:o,type:r[0].type,textureType:2},shaderSource:U,hasMain:!0}},Wh=(n,e,r)=>{let t=P$(e.length,r.cacheKey);return{...t,get:()=>k$(n,t,e,r.axis)}},Aa=(n,e,r)=>{let t=n.indexOf(e);return n.map((o,s)=>s===t?`${o} - ${r}`:o).join()}});var qh,D$,B$,R$,Kh,z$,M$,N$,Yh,L$,Xh=q(()=>{"use strict";Rt();Je();Hh();qh=(n,e,r)=>(L$(e),n.session.pack&&e[0].dims.length>1?[n.run(Wh(n,e,r),e)]:[n.run(R$(n,e,r),e)]),D$=(n,e)=>({name:"Concat",inputNames:Array.from({length:n},(r,t)=>`X${t}`),inputTypes:Array(n).fill(0),cacheHint:e}),B$=(n,e,r,t)=>{let i=r[0].dims.slice();if(t>=i.length||t<-1*i.length)throw new Error("axis specified for concat doesn't match input dimensionality");t<0&&(t=i.length+t);let o=i.slice(0);for(let x=1;x{let t=D$(e.length,r.cacheKey);return{...t,get:()=>B$(n,t,e,r.axis)}},Kh=n=>`int getTextureWhereDataResides(int index) { + ${n.map((r,t)=>`if(index<${r}) {return ${t};} +`).join("")} + }`,z$=n=>Kh(n),M$=(n,e)=>{let r=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`];for(let t=0;t{let e=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let r=0;rFe({axis:n.attributes.getInt("axis")}),L$=n=>{if(!n||n.length<1)throw new Error("too few inputs");let e=n[0].type,r=n[0].dims.length;if(e==="string")throw new Error("string tensor is not supported yet");for(let t of n){if(t.type!==e)throw new Error("input tensors should be one type");if(t.dims.length!==r)throw new Error("input tensors should have the same shape")}}});function j$(){return yr("abs")}function U$(){return yr("acos")}function F$(){return yr("asin")}function V$(){return yr("atan")}function G$(){return yr("ceil")}function W$(){return yr("cos")}function H$(n){let e="elu";return{body:` + const float alpha = float(${n}); + + float ${e}_(float a) { + return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; + } + vec4 ${e}_(vec4 v) { + return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); + } + `,name:e,type:0}}function q$(){return yr("exp")}function K$(){return yr("floor")}function gu(n,e){let r="clip";return{body:` + const float min = float(${n}); + const float max = float(${e}); + + float ${r}_(float a) { + return clamp(a, min, max); + } + vec4 ${r}_(vec4 v) { + return clamp(v, min, max); + } + `,name:r,type:0}}function Y$(){let n="indentity";return{body:` + float ${n}_(float a) { + return a; + } + vec4 ${n}_(vec4 v) { + return v; + } + `,name:n,type:0}}function X$(n){let e="leakyRelu";return{body:` + const float alpha = float(${n}); + + float ${e}_(float a) { + return a < 0.0 ? a * alpha : a; + } + vec4 ${e}_(vec4 v) { + return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); + } + `,name:e,type:0}}function Z$(){return yr("log")}function J$(){let n="neg";return{body:` + float ${n}_(float a) { + return -a; + } + vec4 ${n}_(vec4 v) { + return -v; + } + `,name:n,type:0}}function Q$(){let n="not";return{body:` + float ${n}_(float a) { + return float( ! bool(a) ); + } + bool ${n}_(bool a) { + return !a; + } + vec4 ${n}_(vec4 v) { + return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); + } + bvec4 ${n}_(bvec4 v) { + return bvec4(!v.x, !v.y, !v.z, !v.w); + } + `,name:n,type:0}}function eT(){return yr("sin")}function yu(){let n="relu";return{body:` + float ${n}_(float a) { + return max( a, 0.0 ); + } + vec4 ${n}_(vec4 v) { + return max( v, 0.0 ); + } + `,name:n,type:0}}function bu(){let n="sigmoid";return{body:` + float ${n}_(float a) { + return 1.0 / (1.0 + exp(-a)); + } + vec4 ${n}_(vec4 v) { + return 1.0 / (1.0 + exp(-v)); + } + `,name:n,type:0}}function tT(){return yr("sqrt")}function rT(){return yr("tan")}function nT(){let n="tanh";return{body:` + float ${n}_(float a) { + a = clamp(a, -10., 10.); + a = exp(2.*a); + return (a - 1.) / (a + 1.); + } + vec4 ${n}_(vec4 v) { + v = clamp(v, -10., 10.); + v = exp(2.*v); + return (v - 1.) / (v + 1.); + } + `,name:n,type:0}}function yr(n){return{body:` + float ${n}_(float a) { + return ${n}(a); + } + vec4 ${n}_(vec4 v) { + return ${n}(v); + } + `,name:n,type:0}}var iT,At,Zh,Jh,Qh,em,vu,tm,rm,oT,nm,im,om,am,sm,um,wu,lm,dm,cm,fm,pm,hm,mm,gm,ym,bm,vm,_u=q(()=>{"use strict";Rt();it();Zr();vt();Je();iT=(n,e,r,t)=>{let i=n.session.pack?2:0,o=Ie(n.session.backend.glContext.version);return{...e,output:{dims:r.dims,type:r.type,textureType:i},shaderSource:` + ${t.body} + void main() { + vec4 v = ${o.texture2D}(A, TexCoords); + v = ${t.name}_(v); + ${o.output} = v; + } + `,hasMain:!0}},At=(n,e,r,t)=>{let i=n.session.pack?2:0,o={name:r.name,inputTypes:[i],inputNames:["A"],cacheHint:t};return{...o,get:()=>iT(n,o,e,r)}},Zh=(n,e)=>[n.run(At(n,e[0],j$()),e)],Jh=(n,e)=>[n.run(At(n,e[0],U$()),e)],Qh=(n,e)=>[n.run(At(n,e[0],F$()),e)],em=(n,e)=>[n.run(At(n,e[0],V$()),e)],vu=(n,e,r)=>[n.run(At(n,e[0],gu(r.min,r.max),r.cacheKey),e)],tm=n=>Fe({min:n.attributes.getFloat("min",kn),max:n.attributes.getFloat("max",Dn)}),rm=(n,e)=>{let r=oT(n,e);return vu(n,[e[0]],r)},oT=(n,e)=>{if(e.length>=3&&(!n.session.isInitializer(e[1].dataId)||!n.session.isInitializer(e[2].dataId)))throw new Error("dynamic clip attributes are not allowed");let r=e.length>=3?e[1].numberData[0]:kn,t=e.length>=3?e[2].numberData[0]:Dn;return Fe({min:r,max:t})},nm=(n,e)=>[n.run(At(n,e[0],G$()),e)],im=(n,e)=>[n.run(At(n,e[0],W$()),e)],om=(n,e,r)=>[n.run(At(n,e[0],H$(r.alpha),r.cacheKey),e)],am=n=>Fe({alpha:n.attributes.getFloat("alpha",1)}),sm=(n,e)=>[n.run(At(n,e[0],q$()),e)],um=(n,e)=>[n.run(At(n,e[0],K$()),e)],wu=(n,e)=>[n.run(At(n,e[0],Y$()),e)],lm=(n,e,r)=>[n.run(At(n,e[0],X$(r.alpha),r.cacheKey),e)],dm=n=>Fe({alpha:n.attributes.getFloat("alpha",.01)}),cm=(n,e)=>[n.run(At(n,e[0],Z$()),e)],fm=(n,e)=>[n.run(At(n,e[0],J$()),e)],pm=(n,e)=>[n.run(At(n,e[0],Q$()),e)],hm=(n,e)=>[n.run(At(n,e[0],yu()),e)],mm=(n,e)=>[n.run(At(n,e[0],bu()),e)],gm=(n,e)=>[n.run(At(n,e[0],eT()),e)],ym=(n,e)=>[n.run(At(n,e[0],tT()),e)],bm=(n,e)=>[n.run(At(n,e[0],rT()),e)],vm=(n,e)=>[n.run(At(n,e[0],nT()),e)]});function Lr(n){let e;switch(n.activation){case"Relu":e=yu();break;case"Sigmoid":e=bu();break;case"Clip":e=gu(n.clipMin,n.clipMax);break;default:return{activationFunction:"",applyActivation:""}}let r=e.name,t=e.body,i=`value = ${r}_(value);`;return{activationFunction:t,applyActivation:i}}var _i,zn=q(()=>{"use strict";it();_u();_i=n=>{let e=n.getString("activation","");if(e==="Clip"){let[r,t]=n.getFloats("activation_params",[kn,Dn]);return{activation:e,clipMax:t,clipMin:r,activationCacheKey:`${e}:${r},${t}`}}return{activation:e,activationCacheKey:e}}});var sT,uT,wm,_m=q(()=>{"use strict";cr();vt();Je();Ea();zn();sT=(n,e)=>({name:"GroupedConv",inputNames:n?["X","W","Bias"]:["X","W"],inputTypes:n?[0,0,0]:[0,0],cacheHint:e}),uT=(n,e,r,t)=>{let o=e.length>2?"value += getBias(output_channel);":"",s=e[0].dims.slice(),a=e[1].dims.slice(),u=a[0]/t.group;at.verbose("GroupedConv",`autpPad:${t.autoPad}, dilations:${t.dilations}, group:${t.group}, kernelShape:${t.kernelShape}, pads:${t.pads}, strides:${t.strides}`);let d=xi(s,a,t.dilations,t.pads,t.strides),m=Ie(n.session.backend.glContext.version),{activationFunction:b,applyActivation:w}=Lr(t),x=` + const ivec2 strides = ivec2(${t.strides[0]}, ${t.strides[1]}); + const ivec2 pads = ivec2(${t.pads[0]}, ${t.pads[1]}); + ${b} + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int output_channel = coords.y; + ivec2 xRCCorner = coords.zw * strides - pads; + int group_id = output_channel / ${u}; + + float value = 0.0; + for (int wInChannel = 0; wInChannel < ${a[1]}; wInChannel++) { + int input_channel = group_id * ${a[1]} + wInChannel; + for (int wHeight = 0; wHeight < ${a[2]}; wHeight++) { + int xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}; + + if (xHeight < 0 || xHeight >= ${s[2]}) { + continue; + } + + for (int wWidth = 0; wWidth < ${a[3]}; wWidth++) { + int xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}; + if (xWidth < 0 || xWidth >= ${s[3]}) { + continue; + } + + float xVal = getX(batch, input_channel, xWidth, xHeight); + float wVal = getW(output_channel, wInChannel, wWidth, wHeight); + value += xVal*wVal; + } + } + } + ${o} + ${w} + ${m.output} = vec4(value, .0, .0, .0); + } +`;return{...r,output:{dims:d,type:e[0].type,textureType:0},shaderSource:x,hasMain:!0}},wm=(n,e,r)=>{let t=sT(e.length>2,r.cacheKey);return{...t,get:()=>uT(n,e,t,r)}}});var lT,dT,xm,$m=q(()=>{"use strict";vt();Je();Rn();lT=n=>({name:"Im2Col (packed)",inputNames:["A"],inputTypes:[2],cacheHint:n}),dT=(n,e,r,t,i,o)=>{let s=r.dims,a=t.dims,u=2,d=3,m=i.length,b=[a[1]*a[2]*a[3],i[2]*i[3]],w=a[2]*a[3],x=Nr(),$=Ie(n.session.backend.glContext.version),I="";for(let k=0;k<=1;k++)for(let P=0;P<=1;P++)I+=` + blockIndex = rc.x + ${P}; + pos = rc.y + ${k}; + + if(blockIndex < ${b[1]} && pos < ${b[0]}) { + offsetY = int(blockIndex / (${i[m-1]})) * ${o.strides[0]} - + ${o.pads[0]}; + d0 = offsetY + ${o.dilations[0]} * (imod(pos, ${w}) / ${a[2]}); + + if(d0 < ${s[u]} && d0 >= 0) { + offsetX = imod(blockIndex, ${i[m-1]}) * ${o.strides[1]} - + ${o.pads[1]}; + d1 = offsetX + ${o.dilations[1]} * imod(imod(pos, ${w}), ${a[2]}); + + if(d1 < ${s[d]} && d1 >= 0) { + + ch = int(float(pos)/ ${w}.); + innerDims = vec2(d0, d1); + result[${k*2+P}] = getChannel( + getA(0, ch, int(innerDims.x), + int(innerDims.y)), innerDims); + } + } + } + + `;let A=` + ${x} + + void main() { + ivec2 rc = getOutputCoords(); + vec4 result = vec4(0.0); + int blockIndex, pos, offsetY, d0, offsetX, d1, ch; + vec2 innerDims; + ${I} + ${$.output} = result; + } + `;return{...e,output:{dims:b,type:r.type,textureType:2},shaderSource:A,hasMain:!0}},xm=(n,e,r,t,i)=>{let o=lT(i.cacheKey);return{...o,get:()=>dT(n,o,e,r,t,i)}}});function fT(n,e,r){let t=e[0].dims,i=e[1].dims,o=qt.calcShape(t,i,!0);if(!o)throw new Error("Can't use matmul on the given tensors");let s=Kt(o.length),a=Ar(),{activationFunction:u,applyActivation:d}=Lr(r),m=e.length>2,b=m?"value += getBiasForMatmul();":"",w=m?`${$u(s,a,e[2].dims,o,!1)}`:"",x=o.length,$=t.length,I=i.length,A=t[t.length-1],k=` + ${u} + ${w} + float process(int indices[${x}]) { + int a[${$}]; + int b[${I}]; + bcastMatmulIndices_A(indices, a); + bcastMatmulIndices_B(indices, b); + + float value; + for (int k=0; k<${A}; ++k) { + a[${$-1}] = k; + b[${I-2}] = k; + value += _A(a) * _B(b); + } + ${b} + ${d} + return value; + }`;return{...n,output:{dims:o,type:e[0].type,textureType:0},shaderSource:k}}function xu(n,e){let r=cT(n.length>2,e.activationCacheKey);return{...r,get:()=>fT(r,n,e)}}function $u(n,e,r,t,i){let o="",s=r.length,a=t.length,u=a-s;a<2&&s>0?o="coords":o=r.map((I,A)=>`coords.${e[A+u]}`).join(", ");let m=qt.getBroadcastDims(r,t).map(I=>`coords.${e[I+u]} = 0;`).join(` +`),w=be.size(r)===1,x="vec4(outputValue.xx, outputValue.yy)";return w&&(x="vec4(outputValue.x)"),i?` +vec4 getBiasForMatmul() { + ${n} coords = getOutputCoords(); + ${m} + vec4 outputValue = getBias(${o}); + return ${x}; +}`:` +float getBiasForMatmul() { + ${n} coords = getOutputCoords(); + ${m} + return getBias(coords.x); +}`}var Tm,Sm,cT,pT,Oa=q(()=>{"use strict";it();Je();Mr();zn();Tu();Tm=(n,e,r)=>(pT(e),n.session.pack?[n.run(Pa(n,e,r),e)]:[n.run(xu(e,r),e)]),Sm=n=>_i(n.attributes),cT=(n,e)=>({name:"MatMul",inputNames:n?["A","B","Bias"]:["A","B"],inputTypes:n?[0,0,0]:[0,0],cacheHint:e});pT=n=>{if(!n||n.length!==2)throw new Error("MatMul requires 2 inputs.");if(n[0].dims[n[0].dims.length-1]!==n[1].dims[n[1].dims.length-2])throw new Error("shared dimension does not match.");if(n[0].type!=="float32"&&n[0].type!=="float64"||n[1].type!=="float32"&&n[1].type!=="float64")throw new Error("inputs should be float type");if(n[0].type!==n[1].type)throw new Error("inputs types should match")}});function gT(n,e,r,t){let i=[],o=[],s=r[0].dims,a=r[1].dims,u=s.length,d=a.length,m=t.length,b=m-u,w=m-d;i=s.map((z,U)=>`coords.${e[U+b]}`),i[u-1]="i*2",i.join(", "),o=a.map((z,U)=>`coords.${e[U+w]}`),o[d-2]="i*2",o.join(", ");let x=qt.getBroadcastDims(s,t),$=qt.getBroadcastDims(a,t),I=x.map(z=>`coords.${e[z+b]} = 0;`).join(` +`),A=$.map(z=>`coords.${e[z+w]} = 0;`).join(` +`),k=`int lastDim = coords.${e[m-1]}; + coords.${e[m-1]} = coords.${e[m-2]}; + coords.${e[m-2]} = lastDim;`;return` +vec4 getAAtOutCoordsMatmul(int i) { + ${n} coords = getOutputCoords(); + ${k} + ${I} + vec4 outputValue = getA(${i}); + return outputValue; +} + +vec4 getBAtOutCoordsMatmul(int i) { + ${n} coords = getOutputCoords(); + ${k} + ${A} + vec4 outputValue = getB(${o}); + return outputValue; +}`}function yT(n,e){let r="";for(let t=0;t{"use strict";it();vt();Je();Mr();zn();Oa();hT=(n,e)=>({name:"MatMul (packed)",inputNames:n?["A","B","Bias"]:["A","B"],inputTypes:n?[2,2,2]:[2,2],cacheHint:e}),mT=(n,e,r,t)=>{let i=r.length>2,o=i?"value += getBiasForMatmul();":"",s=r[0].dims,a=r[1].dims,u=qt.calcShape(s,a,!0),d=!be.areEqual(r[0].dims,r[1].dims);if(!u)throw new Error("Can't use matmul on the given tensors");let m=s[s.length-1],b=Math.ceil(m/2),w=s.length,x=a.length,$=Ie(n.session.backend.glContext.version),I=Kt(u.length),A=u.length,k=Ar(),{activationFunction:P,applyActivation:z}=Lr(t),U=i?`${$u(I,k,r[2].dims,u,!0)}`:"",F=d?`${gT(I,k,r,u)}`:"",Y=d?"getAAtOutCoordsMatmul(i)":`getA(${yT(k,w)})`,ie=d?"getBAtOutCoordsMatmul(i)":`getB(${bT(k,x)})`,ne=d?"":`${I} rc = + getOutputCoords(); int lastDim = rc.${k[A-1]}; rc.${k[A-1]} = + rc.${k[A-2]}; rc.${k[A-2]} = lastDim; + `,le=` + ${F} + ${U} + ${P} + void main() { + ${ne} + + vec4 value = vec4(0); + for (int i = 0; i < ${b}; i++) { + vec4 a = ${Y}; + vec4 b = ${ie}; + + value += (a.rrbb * b.rgrg); + value += (a.ggaa * b.baba); + } + ${o} + ${z} + ${$.output} = value; + }`;return{...e,output:{dims:u,type:r[0].type,textureType:2},shaderSource:le,hasMain:!0}},Pa=(n,e,r)=>{let t=hT(e.length>2,r.activationCacheKey);return{...t,get:()=>mT(n,t,e,r)}}});var Im,Cm=q(()=>{"use strict";Ea();$m();Tu();Im=(n,e,r)=>{let t=e[0].dims,i=e[1].dims,o=xi(t,i,r.dilations,r.pads,r.strides),s=n.run(xm(n,e[0],e[1],o,r),[e[0]]),a=n.reshapePacked(e[1],[i[0],i[1]*i[2]*i[3]]),u=e.length===3?[a,s,e[2]]:[a,s],d=n.run(Pa(n,u,r),u);return n.reshapePacked(d,o)}});var vT,wT,Am,Su,Iu=q(()=>{"use strict";Je();vT=n=>({name:"Im2Col",inputNames:["X"],inputTypes:[0],cacheHint:n}),wT=(n,e,r,t,i,o)=>{let s=r.dims,a=t.dims,u=i.length,d=Su(s,a,i,4),m=` + const int XC = ${s[1]}; + const int XH = ${s[2]}; + const int XW = ${s[3]}; + const int KH = ${o.kernelShape[0]}; + const int KW = ${o.kernelShape[1]}; + const int dilationH = ${o.dilations[0]}; + const int dilationW = ${o.dilations[1]}; + const int strideH = ${o.strides[0]}; + const int strideW = ${o.strides[1]}; + const int padH = ${o.pads[0]}; + const int padW = ${o.pads[1]}; + const int KHKW = KH*KW; + const int XCKHKW = XC * KHKW; + const int outputChannels = 4; + vec4 process(int indices[${u}]) { + int b = indices[0]; // batch size + int oh = indices[1] * strideH - padH; //output height + int ow = indices[2] * strideW - padW; //output width + int p = indices[3] * outputChannels; //patch + vec4 value = vec4(0.0); + for(int i=0; i < outputChannels; ++i) { + if(p < XCKHKW) { + int patchC = p / KHKW; + int patchH = (p - patchC*KHKW) / KW; + int patchW = (p - patchC*KHKW) - patchH * KW; + int xh2 = oh + patchH * dilationH; + int xw2 = ow + patchW * dilationW; + int x[${s.length}]; + x[0] = b; + x[1] = patchC; + x[2] = xh2; + x[3] = xw2; + if(xh2 >= 0 && + xh2 < XH && + xw2 >= 0 && + xw2 < XW) { + value[i] = _X(x); + } + } + ++p; + } + return value; + } + `;return{...e,output:{dims:d,type:r.type,textureType:4},shaderSource:m}},Am=(n,e,r,t,i)=>{let o=vT(i.cacheKey);return{...o,get:()=>wT(n,o,e,r,t,i)}},Su=(n,e,r,t=4)=>[r[0],r[2],r[3],Math.ceil(n[1]*e[2]*e[3]/t)]});var _T,xT,Em,Om=q(()=>{"use strict";it();vt();Je();zn();Iu();_T=(n,e)=>({name:"ConvDotProduct",inputNames:n?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:n?[0,4,0]:[0,4],cacheKey:e.activationCacheKey}),xT=(n,e,r,t,i)=>{let o=r[0].dims,s=r[1].dims,a=[s[0],Math.ceil(o[1]*s[2]*s[3]/4)],u=Su(o,s,t),[d,m]=n.calculateTextureWidthAndHeight(a,4),b=be.computeStrides(u),[w,x]=n.calculateTextureWidthAndHeight(u,4),$=t.length,I=r.length<3?"0.0":"_B(b)",A=Math.ceil(o[1]*s[2]*s[3]/4),{activationFunction:k,applyActivation:P}=Lr(i),z=Ie(n.session.backend.glContext.version),U=` +${k} +float process(int indices[${$}]) { + int b[1]; + b[0] = indices[1]; + int im2col[4]; + im2col[0] = indices[0]; + im2col[1] = indices[2]; + im2col[2] = indices[3]; + int im2colOffset = im2col[0] * ${b[0]} + im2col[1] * ${b[1]} + im2col[2] * ${b[2]}; + int kernelOffset = indices[1] * ${a[1]}; + float value = ${I}; + for (int i = 0; i < ${A}; ++i) { + vec2 im2colCoords = offsetToCoords(im2colOffset, ${w}, ${x}); + vec2 kernelCoords = offsetToCoords(kernelOffset, ${d}, ${m}); + value += dot(${z.texture2D}(Im2Col, im2colCoords), ${z.texture2D}(K, kernelCoords)); + ++im2colOffset; + ++kernelOffset; + } + ${P} + return value; +}`;return{...e,output:{dims:t,type:r[0].type,textureType:0},shaderSource:U}},Em=(n,e,r,t)=>{let i=_T(e.length>2,t);return{...i,get:()=>xT(n,i,e,r,t)}}});var xi,Cu,$T,TT,ST,IT,Au,CT,Ea=q(()=>{"use strict";Rt();it();_m();Cm();Om();zn();Iu();Oa();xi=(n,e,r,t,i)=>{let o=n[0],s=n.slice(2),a=s.length,u=e[0],m=e.slice(2).map(($,I)=>$+($-1)*(r[I]-1)),w=s.map(($,I)=>$+t[I]+t[I+a]).map(($,I)=>Math.floor(($-m[I]+i[I])/i[I]));return[o,u].concat(...w)},Cu=(n,e,r)=>(CT(e,r),$T(n,e,r)),$T=(n,e,r)=>{let t=IT(r,e),i=n.session.pack,o=t.kernelShape[0]===1&&t.kernelShape[1]===1;return t.group>1?[n.run(wm(n,e,t),e)]:o&&i?[TT(n,e,t)]:i&&e[0].dims.length===4&&e[0].dims[0]===1&&!o?[Im(n,e,t)]:[ST(n,e,t)]},TT=(n,e,r)=>{let t=e[0].dims,i=e[1].dims,o=xi(t,i,r.dilations,r.pads,r.strides),s=n.reshapeUnpacked(e[0],[t[1],t[2]*t[3]]),a=n.reshapeUnpacked(e[1],[i[0],i[1]]),u=e.length>2?[a,s,e[2]]:[a,s],d=n.run(xu(u,r),u);return n.reshapeUnpacked(d,o)},ST=(n,e,r)=>{let t=e[0].dims,i=e[1].dims,o=xi(t,i,r.dilations,r.pads,r.strides),s=n.run(Am(n,e[0],e[1],o,r),[e[0]]),a=e.length===3?[s,e[1],e[2]]:[s,e[1]];return n.run(Em(n,e,o,r),a)},IT=(n,e)=>{let r=n.kernelShape.slice();if(n.kernelShape.length===0)for(let o=2;o{let e=n.attributes,r=_i(e),t=e.getString("auto_pad","NOTSET"),i=e.getInts("dilations",[1,1]),o=e.getInt("group",1),s=e.getInts("kernel_shape",[]),a=e.getInts("pads",[0,0,0,0]),u=e.getInts("strides",[1,1]);return Fe({autoPad:t,dilations:i,group:o,kernelShape:s,pads:a,strides:u,...r})},CT=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4||n[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let r=n[0].dims[1],t=n[1].dims[1]*e.group;if(r!==t)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(n.length===3&&(n[2].dims.length!==1||n[1].dims[0]!==n[2].dims[0]))throw new Error("invalid bias");let i=n[0].dims.length-2;if(e.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(e.strides.length!==i)throw new Error(`strides should be ${i}D`);if(e.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(n[0].type!=="float32"||n[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(n.length===3&&n[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}});var AT,ET,OT,Pm,PT,kT,DT,BT,RT,zT,km,MT,Dm=q(()=>{"use strict";Rt();vt();Je();zn();AT=(n,e,r,t,i,o)=>(n-1)*e+r+(t-1)*i+1-o,ET=(n,e,r,t,i)=>{let o=Math.floor(n/2);e==="SAME_UPPER"?(r[t]=o,r[i]=n-o):e==="SAME_LOWER"&&(r[t]=n-o,r[i]=o)},OT=(n,e,r,t,i,o,s,a)=>{let u=n.length-2,d=a.length===0;for(let m=0;m(MT(e,r),PT(n,e,r)),PT=(n,e,r)=>{let t=zT(r,e);return[RT(n,e,t)]},kT=(n,e)=>({name:"ConvTranspose",inputNames:n?["X","W","B"]:["X","W"],inputTypes:n?[0,0,0]:[0,0],cacheHint:e}),DT=(n,e,r,t)=>{let o=e.length>2?"getB(output_channel)":"0.0",s=e[0].dims,a=e[1].dims,u=a[1],d=a[0]/t.group,m=[e[0].dims[0],e[1].dims[1]*t.group,...t.outputShape],b=Ie(n.session.backend.glContext.version),{activationFunction:w,applyActivation:x}=Lr(t),$=` + const ivec2 strides = ivec2(${t.strides[0]}, ${t.strides[1]}); + const ivec2 pads = ivec2(${t.pads[0]}, ${t.pads[1]}); + ${w} + void main() { + ivec4 coords = getOutputCoords(); + int batch = coords.x; + int output_channel = coords.y; + + ivec2 loc = coords.zw + pads; + + int group_id = output_channel / ${u}; + int wOutChannel = output_channel - group_id * ${u}; + + float value = ${o}; + for (int inChannelOffset = 0; inChannelOffset < ${d}; inChannelOffset++) { + int input_channel = group_id * ${d} + inChannelOffset; + for (int wWOff = 0; wWOff < ${a[2]}; wWOff++) { + for (int wHOff = 0; wHOff < ${a[3]}; wHOff++) { + ivec2 wOff = ivec2(wWOff * ${t.dilations[0]}, wHOff * ${t.dilations[1]}); + ivec2 wLoc = loc - wOff; + ivec2 wLocIn = wLoc / strides; + if ( + wLocIn * strides == wLoc && + wLocIn.x >= 0 && wLocIn.x < ${s[2]} && + wLocIn.y >= 0 && wLocIn.y < ${s[3]} + ) { + float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); + float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); + value += xVal * wVal; + } + } + } + } + ${x} + ${b.output} = vec4(value, .0, .0, .0); + } +`;return{...r,output:{dims:m,type:e[0].type,textureType:0},shaderSource:$,hasMain:!0}},BT=(n,e,r)=>{let t=kT(e.length>2,r.cacheKey);return{...t,get:()=>DT(n,e,t,r)}},RT=(n,e,r)=>n.run(BT(n,e,r),e),zT=(n,e)=>{let r=n.kernelShape.slice();if(n.kernelShape.length===0)for(let a=2;a{let e=n.attributes,r=_i(e),t=e.getString("auto_pad","NOTSET"),i=e.getInts("dilations",[1,1]),o=e.getInt("group",1),s=e.getInts("kernel_shape",[]),a=e.getInts("output_padding",[0,0]),u=e.getInts("output_shape",[]),d=e.getInts("pads",[0,0,0,0]),m=e.getInts("strides",[1,1]);return Fe({autoPad:t,dilations:i,group:o,kernelShape:s,outputPadding:a,outputShape:u,pads:d,strides:m,...r})},MT=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4||n[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let r=n[0].dims[1],t=n[1].dims[0];if(r!==t)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=n[1].dims[1]*e.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==i))throw new Error("invalid bias");let o=n[0].dims.length-2;if(e.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(e.strides.length!==o)throw new Error(`strides should be ${o}D`);if(e.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(e.outputPadding.length!==o)throw new Error(`output_padding should be ${o}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(e.outputShape.length!==0&&e.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape");if(n[0].type!=="float32"||n[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(n.length===3&&n[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}});var Bm,Mn,Rm,NT,zm,LT,jT,UT,ka=q(()=>{"use strict";Rt();it();Je();Bm={name:"Transpose",inputNames:["A"],inputTypes:[0]},Mn=(n,e,r)=>(UT(e),[n.run({...Bm,cacheHint:r.cacheKey,get:()=>NT(n,e[0],r.perm)},e)]),Rm=n=>Fe({perm:n.attributes.getInts("perm",[])}),NT=(n,e,r)=>{let t=e.dims;r=zm(t,r);let i=LT(t,r),o=t.length,s=` + ${jT("perm",r,o)} + float process(int indices[${o}]) { + int a[${o}]; + perm(a, indices); + return _A(a); + }`;return{...Bm,output:{dims:i,type:e.type,textureType:0},shaderSource:s}},zm=(n,e)=>(e&&e.length!==n.length&&(e=[...n.keys()].reverse()),e),LT=(n,e)=>(e=zm(n,e),be.sortBasedOnPerm(n,e)),jT=(n,e,r)=>{let t=[];t.push(`void ${n}(out int a[${r}], int src[${r}]) {`);for(let i=0;i{if(!n||n.length!==1)throw new Error("Transpose requires 1 input.");if(n[0].type!=="float32"&&n[0].type!=="float64")throw new Error("input should be float tensor")}});var Mm,Nm,FT,Lm=q(()=>{"use strict";ka();Mm=(n,e,r)=>{FT(e);let t=r.blocksize,i=t*t,o=r.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],s=r.mode==="DCR"?[e[0].dims[0],t,t,e[0].dims[1]/i,e[0].dims[2],e[0].dims[3]]:[e[0].dims[0],e[0].dims[1]/i,t,t,e[0].dims[2],e[0].dims[3]],a=n.reshapeUnpacked(e[0],s),u={perm:o,cacheKey:`${o}`},[d]=Mn(n,[a],u),m=[e[0].dims[0],e[0].dims[1]/i,e[0].dims[2]*t,e[0].dims[3]*t];return[n.reshapeUnpacked(d,m)]},Nm=n=>{let e=n.attributes.getInt("blocksize");if(e<1)throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`);let r=n.attributes.getString("mode","DCR");if(r!=="DCR"&&r!=="CRD")throw new Error(`unrecognized mode: ${r} for DepthToSpace`);return{mode:r,blocksize:e}},FT=n=>{if(n.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${n.length}`);if(n[0].type==="string"||n[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}});var jm,Um,VT,Fm=q(()=>{"use strict";it();jm=(n,e,r)=>{VT(e,r);let t=be.flattenShape(e[0].dims,r);return[n.reshapeUnpacked(e[0],t)]},Um=n=>n.attributes.getInt("axis",1),VT=(n,e)=>{if(!n||n.length!==1)throw new Error("Flatten requires 1 input.");let r=n[0].dims.length;if(r===0)throw new Error("scalar tensor is not supported.");if(e<-r||e>r)throw new Error("Invalid axis");if(n[0].type==="string")throw new Error("string tensor is not supported.")}});var un,ho=q(()=>{"use strict";un=["float32","float64","int32","int16","int8","uint16","uint32","uint8"]});var Vm,Gm,GT,WT,HT,qT,Wm=q(()=>{"use strict";Rt();ho();it();Je();Vm=(n,e,r)=>(qT(e,r.axis),[n.run(HT(n,e,r),e)]),Gm=n=>Fe({axis:n.attributes.getInt("axis",0)}),GT={name:"Gather",inputNames:["A","B"],inputTypes:[0,0]},WT=(n,e,r,t)=>{let i=r[0].dims.slice(),o=r[1].dims.slice(),s=new Array(i.length+o.length-1);t=be.normalizeAxis(t,i.length);let a=[];for(let w=0;w{let t={...GT,cacheHint:r.cacheKey};return{...t,get:()=>WT(n,t,e,r.axis)}},qT=(n,e)=>{if(!n||n.length!==2)throw new Error("Gather requires 2 inputs.");let r=n[0].dims.length;if(r<1)throw new Error("Invalid input shape.");if(e<-r||e>r-1)throw new Error("Invalid axis.");if(un.indexOf(n[0].type)===-1)throw new Error("Invaid input type.");if(n[1].type!=="int32"&&n[1].type!=="int16")throw new Error("Invaid input type.")}});var Eu,Hm,qm,Km,KT,YT,XT,Ym=q(()=>{"use strict";Rt();it();Je();Eu=(n,e,r)=>(XT(e,r),[n.run(KT(e,r),e)]),Hm=(n,e)=>{let r=n.attributes.getInt("transA",0)!==0,t=n.attributes.getInt("transB",0)!==0,i=n.attributes.getFloat("alpha",1),o=n.attributes.getFloat("beta",1);return Fe({transA:r,transB:t,alpha:i,beta:o,isOptionalC:e})},qm=n=>Hm(n,!1),Km=n=>Hm(n,!0),KT=(n,e)=>{let r={name:"Gemm",inputNames:n.length===3?["A","B","C"]:["A","B"],inputTypes:n.length===3?[0,0,0]:[0,0],key:e.cacheKey};return{...r,get:()=>YT(r,n,e)}},YT=(n,e,r)=>{let t=e[0].dims.slice(),i=e[1].dims.slice(),[o,s]=_a.getShapeOfGemmResult(t,r.transA,i,r.transB,e.length===3?e[2].dims:void 0),a=[o,s];if(!a)throw new Error("Can't use gemm on the given tensors");let u=t[t.length-1],d="";r.transA&&(u=t[0]),r.transA&&r.transB?d="value += _A_T(a) * _B_T(b);":r.transA&&!r.transB?d="value += _A_T(a) * _B(b);":!r.transA&&r.transB?d="value += _A(a) * _B_T(b);":!r.transA&&!r.transB&&(d="value += _A(a) * _B(b);");let m=a.length,b=e.length===3?`int c[${e[2].dims.length}];`:"",w=e.length===3?"bcastIndices_C(indices, c);":"",x=e.length===3?"value += beta * _C(c);":"",$=` + float process(int indices[${m}]) { + int a[${m}]; + int b[${m}]; + ${b} + + copyVec(indices, a); + copyVec(indices, b); + ${w} + + float value = 0.0; + for (int k=0; k<${u}; ++k) { + a[${m-1}] = k; + b[${m-2}] = k; + ${d} + } + + value = value * alpha; + ${x} + return value; + }`;return{...n,output:{dims:a,type:e[0].type,textureType:0},variables:[{name:"alpha",type:"float",data:r.alpha},{name:"beta",type:"float",data:r.beta}],shaderSource:$}},XT=(n,e)=>{if(!n)throw new Error("Input is missing");if(e.isOptionalC&&(n.length<2||n.length>3))throw new Error("Invaid input shape.");if(!e.isOptionalC&&n.length!==3)throw new Error("Gemm requires 3 inputs");if(n.length===3&&n[2].dims.length!==1&&n[2].dims.length!==2)throw new Error("Invalid input shape of C");if(n[0].type!=="float32"&&n[0].type!=="float64"||n[1].type!=="float32"&&n[1].type!=="float64"||n.length===3&&n[2].type!=="float32"&&n[2].type!=="float64")throw new Error("Invalid input type.");if(n[0].type!==n[1].type||n.length===3&&n[0].type!==n[2].type)throw new Error("Input types are mismatched")}});var Xm,Zm,ZT,JT,QT,eS,tS,Jm=q(()=>{"use strict";Rt();Je();Xm=(n,e,r)=>(tS(e),[n.run(QT(n,e,r),e)]),Zm=n=>{let e=n.attributes.getFloat("scale"),r=n.attributes.getFloats("bias");return Fe({scale:e,bias:r})},ZT={name:"ImageScaler",inputNames:["X"],inputTypes:[0]},JT=(n,e,r,t)=>{let i=r[0].dims.slice(),o=i.length,a=` + ${eS(t.bias.length)} + float process(int indices[${o}]) { + return _X(indices) * scale + getBias(bias, indices[1]); + }`;return{...e,output:{dims:i,type:r[0].type,textureType:0},variables:[{name:"bias",type:"float",arrayLength:t.bias.length,data:t.bias},{name:"scale",type:"float",data:t.scale}],shaderSource:a}},QT=(n,e,r)=>{let t={...ZT,cacheHint:r.cacheKey};return{...t,get:()=>JT(n,t,e,r)}},eS=n=>{let e=[`float getBias(float bias[${n}], int channel) {`];for(let r=0;r{if(!n||n.length!==1)throw new Error("ImageScaler requires 1 input.");if(n[0].dims.length!==4)throw new Error("Invalid input shape.");if(n[0].type!=="float32"&&n[0].type!=="float64")throw new Error("Invalid input type.")}});var eg,tg,Qm,rS,nS,iS,oS,aS,sS,rg=q(()=>{"use strict";vt();Je();eg=(n,e,r)=>{sS(e);let t=n.run(nS(e[0]),e);return[n.run(aS(n,e[0],r,t.dims),[e[0],t,e[1],e[2]])]},tg=n=>n.attributes.getFloat("epsilon",1e-5),Qm={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[0]},rS=(n,e)=>{let r=e.dims.slice(),t=r[1],i=r[2]*r[3],o=[r[0],t],s=` + vec4 process(int[2] indices) { + vec4 v = vec4(0.0); + int a[4]; + a[0] = indices[0]; + a[1] = indices[1]; + float temp = 0.0; + for(int a2=0; a2<${r[2]}; a2++) { + a[2] = a2; + for(int a3=0; a3<${r[3]}; a3++) { + a[3] = a3; + float x = _X(a); + temp += x; + } + } + float mean = temp / float(${i}); + temp = 0.0; + for(int a2=0; a2<${r[2]}; a2++) { + a[2] = a2; + for(int a3=0; a3<${r[3]}; a3++) { + a[3] = a3; + float x = _X(a); + temp += (x - mean) * (x - mean); + } + } + v.r = mean; + v.g = temp / float(${i}); + + return v; + }`;return{...n,output:{dims:o,type:e.type,textureType:4},shaderSource:s}},nS=n=>({...Qm,get:()=>rS(Qm,n)}),iS={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[0,4,0,0]},oS=(n,e,r,t,i)=>{let o=Ie(n.session.backend.glContext.version),[s,a]=n.calculateTextureWidthAndHeight(i,4),[u,d]=[s/4,a],m=` + vec4 get_MeanAndVariance(int[2] mv) { + int offset = indicesToOffset_MeanAndVariance(mv); + vec2 coords = offsetToCoords(offset, ${u}, ${d}); + return ${o.texture2D}(MeanAndVariance, coords); + } + + float process(int[4] indices) { + int mv[2]; + mv[0] = indices[0]; + mv[1] = indices[1]; + vec4 mean_and_variance = get_MeanAndVariance(mv); + float mean = mean_and_variance.r; + float variance = mean_and_variance.g; + + int sb[1]; + sb[0] = indices[1]; + float scale = _Scale(sb); + float b = _B(sb); + + return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; + }`;return{...e,output:{dims:r.dims,type:r.type,textureType:0},variables:[{name:"epsilon",type:"float",data:t}],shaderSource:m}},aS=(n,e,r,t)=>{let i={...iS,cacheHint:`${r}`};return{...i,get:()=>oS(n,i,e,r,t)}},sS=n=>{if(!n||n.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");let e=n[0],r=n[1],t=n[2];if(e.dims.length<3||r.dims.length!==1||t.dims.length!==1)throw new Error("Invalid input shape.");if(r.dims[0]!==e.dims[1]||t.dims[0]!==e.dims[1])throw new Error("Input shapes are mismatched.");if(e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64"||t.type!=="float32"&&t.type!=="float64")throw new Error("Invalid input type.");if(n[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}});function uS(n,e){let r=n[0].dims[1],t=n[0].dims.length,i=-Math.floor((e.size-1)/2),o=Math.ceil((e.size-1)/2),s=`float(${e.alpha}) / float(${e.size})`,a=`float(${e.bias})`,u=`float(${e.beta})`,d=` + float process(int indices[${t}]) { + int c = indices[1]; + float x = _X(indices); + float square_sum = 0.0; + + for (int i = ${i}; i <= ${o}; i++) { + int idx = c + i; + if (c >= 0 && c < ${r}) { + indices[1] = idx; + float j = _X(indices); + square_sum += j * j; + } + } + return x / pow(${a} + ${s} * square_sum, ${u}); + }`;return{...og,cacheHint:e.cacheKey,output:{dims:n[0].dims,type:n[0].type,textureType:0},shaderSource:d}}function lS(n,e){return{...og,cacheHint:e.cacheKey,get:()=>uS(n,e)}}var ng,ig,og,dS,ag=q(()=>{"use strict";Rt();Je();ng=(n,e,r)=>(dS(e),[n.run(lS(e,r),e)]),ig=n=>{let e=n.attributes.getFloat("alpha",1e-4),r=n.attributes.getFloat("beta",.75),t=n.attributes.getFloat("bias",1),i=n.attributes.getInt("size");return Fe({alpha:e,beta:r,bias:t,size:i})},og={name:"LRN",inputNames:["X"],inputTypes:[0]};dS=n=>{if(!n||n.length!==1)throw new Error("LRN requires 1 input.");if(n[0].dims.length!==4)throw new Error('currently only support LRN for input with "NCHW" format');if(n[0].type!=="float32")throw new Error("input should be float type")}});var cS,Ou,sg,ug,lg,fS,pS,hS,mS,gS,yS,bS,vS,dg=q(()=>{"use strict";Rt();it();vt();Je();cS={name:"Pad",inputNames:["A"],inputTypes:[0]},Ou=(n,e,r)=>(hS(e),[n.run({...cS,cacheHint:r.cacheKey,get:()=>pS(n,e[0],r)},e)]),sg=n=>{let e=n.attributes.getString("mode","constant"),r=n.attributes.getFloat("value",0),t=n.attributes.getInts("pads");return Fe({mode:e,value:r,pads:t})},ug=(n,e,r)=>{mS(e);let t=fS(n,e,r);return Ou(n,[e[0]],t)},lg=n=>n.attributes.getString("mode","constant"),fS=(n,e,r)=>{if(!n.session.isInitializer(e[1].dataId)||e.length>=3&&!n.session.isInitializer(e[2].dataId))throw new Error("dynamic pad attributes are not allowed");let t=Array.from(e[1].integerData),i=e.length>=3?e[2].floatData[0]:0;return Fe({mode:r,pads:t,value:i})},pS=(n,e,r)=>{let t=be.padShape(e.dims.slice(),r.pads),i=t.length,s=` + ${gS(n,e,r)} + float process(int[${i}] indices) { + return padA(indices); + }`;return{name:"Pad",inputNames:["A"],inputTypes:[0],output:{dims:t,type:e.type,textureType:0},shaderSource:s}},hS=n=>{if(!n||n.length!==1)throw new Error("Pad requires 1 input");if(n[0].type!=="float32"&&n[0].type!=="float64")throw new Error("Invalid input type.")},mS=n=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(n[1].type!=="int32")throw new Error("Invalid input type.");if(n.length>=3&&n[2].type==="string")throw new Error("Invalid input type.")},gS=(n,e,r)=>{let t=Ie(n.session.backend.glContext.version),[i,o]=n.calculateTextureWidthAndHeight(e.dims,0),s=be.computeStrides(e.dims);switch(r.mode){case"constant":return yS(t,e.dims,s,i,o,r.pads,r.value);case"reflect":return bS(t,e.dims,s,i,o,r.pads);case"edge":return vS(t,e.dims,s,i,o,r.pads);default:throw new Error("Invalid mode")}},yS=(n,e,r,t,i,o,s)=>{let a=e.length,u="";for(let d=a-1;d>=0;--d)u+=` + k = m[${d}] - ${o[d]}; + if (k < 0) return constant; + if (k >= ${e[d]}) return constant; + offset += k * ${r[d]}; + `;return` + float padA(int m[${a}]) { + const float constant = float(${s}); + int offset = 0; + int k = 0; + ${u} + vec2 coords = offsetToCoords(offset, ${t}, ${i}); + float value = getColorAsFloat(${n.texture2D}(A, coords)); + return value; + } + `},bS=(n,e,r,t,i,o)=>{let s=e.length,a="";for(let u=s-1;u>=0;--u)a+=` + k = m[${u}] - ${o[u]}; + if (k < 0) { k = -k; } + { + const int _2n_1 = ${2*(e[u]-1)}; + k = int( mod( float(k), float(_2n_1) ) ) ; + if(k >= ${e[u]}) { k = _2n_1 - k; } + } + offset += k * ${r[u]}; + `;return` + float padA(int m[${s}]) { + int offset = 0; + int k = 0; + ${a} + vec2 coords = offsetToCoords(offset, ${t}, ${i}); + float value = getColorAsFloat(${n.texture2D}(A, coords)); + return value; + } + `},vS=(n,e,r,t,i,o)=>{let s=e.length,a="";for(let u=s-1;u>=0;--u)a+=` + k = m[${u}] - ${o[u]}; + if (k < 0) k = 0; + if (k >= ${e[u]}) k = ${e[u]-1}; + offset += k * ${r[u]}; + `;return` + float padA(int m[${s}]) { + int offset = 0; + int k = 0; + ${a} + vec2 coords = offsetToCoords(offset, ${t}, ${i}); + float value = getColorAsFloat(${n.texture2D}(A, coords)); + return value; + } + `}});var fg,pg,hg,mg,gg,yg,bg,vg,wg,wS,cg,_g,Ba,xg,Da,_S,$g=q(()=>{"use strict";Rt();it();Je();fg=(n,e,r)=>{Ba(e);let t={name:"AveragePool",inputNames:["X"],inputTypes:[0],cacheHint:r.cacheKey};return[n.run({...t,get:()=>hg(e,t,!1,r)},e)]},pg=n=>{let e=n.attributes.getString("auto_pad","NOTSET"),r=n.attributes.getInt("ceil_mode",0),t=n.attributes.getInt("count_include_pad",0)!==0,i=n.attributes.getInts("kernel_shape"),o=n.attributes.getInts("strides",[]),s=n.attributes.getInts("pads",[]);if(r!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return Fe({autoPad:e,ceilMode:r,countIncludePad:t,kernelShape:i,strides:o,pads:s})},hg=(n,e,r,t)=>{let[i,o]=wg(n,t,r),s=be.size(i.kernelShape),a="value += _X(x);",u="";i.countIncludePad?u+=`value /= float(${s});`:u+=`value /= float(${s} - pad);`;let m=` + ${xg(n[0].dims,i,a,u,"0.0")} + `;return{...e,output:{dims:o,type:n[0].type,textureType:0},shaderSource:m}},mg=(n,e,r)=>{Ba(e);let t={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[0],cacheHint:`${r.countIncludePad}`};return[n.run({...t,get:()=>hg(e,t,!0,r)},e)]},gg=n=>{let e=n.attributes.getInt("count_include_pad",0)!==0;return Fe({autoPad:"",ceilMode:0,countIncludePad:e,kernelShape:[],strides:[],pads:[]})},yg=(n,e,r)=>{Ba(e);let t={name:"MaxPool",inputNames:["X"],inputTypes:[0],cacheHint:r.cacheKey};return[n.run({...t,get:()=>vg(e,t,!1,r)},e)]},bg=n=>{let e=n.attributes.getString("auto_pad","NOTSET"),r=n.attributes.getInt("ceil_mode",0),t=n.attributes.getInts("kernel_shape"),i=n.attributes.getInts("strides",[]),o=n.attributes.getInts("pads",[]),s=n.attributes.getInt("storage_order",0),a=n.attributes.getInts("dilations",[]);if(s!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(r!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return Fe({autoPad:e,ceilMode:r,countIncludePad:!1,kernelShape:t,strides:i,pads:o,storageOrder:s,dilations:a})},vg=(n,e,r,t)=>{let[i,o]=wg(n,t,r),s=` + value = max(_X(x), value); + `,a="",d=` + ${xg(n[0].dims,i,s,a,"-1e5")} + `;return{...e,output:{dims:o,type:n[0].type,textureType:0},shaderSource:d}},wg=(n,e,r)=>{let t=n[0].dims.slice(),i=Object.hasOwnProperty.call(e,"dilations"),o=e.kernelShape.slice(),s=e.strides.slice(),a=i?e.dilations.slice():[],u=e.pads.slice();Pn.adjustPoolAttributes(r,t,o,s,a,u);let d=Pn.computePoolOutputShape(r,t,s,a,o,u,e.autoPad),m=Object.assign({},e);return i?Object.assign(m,{kernelShape:o,strides:s,pads:u,dilations:a,cacheKey:e.cacheKey}):Object.assign(m,{kernelShape:o,strides:s,pads:u,cacheKey:e.cacheKey}),[m,d]},wS={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},cg={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[0]},_g=(n,e)=>(Ba(e),[n.run({...cg,get:()=>vg(e,cg,!0,wS)},e)]),Ba=n=>{if(!n||n.length!==1)throw new Error("Pool ops requires 1 input.");if(n[0].type!=="float32"&&n[0].type!=="float64")throw new Error("Invalid input type.")},xg=(n,e,r,t,i)=>{let o=n.length;if(e.kernelShape.length<=2){let s=e.kernelShape[e.kernelShape.length-1],a=e.strides[e.strides.length-1],u=e.pads[e.pads.length/2-1],d=e.pads[e.pads.length-1],m=n[o-1],b="",w="",x="";if(u+d!==0?b=` + for (int i = 0; i < ${s}; i++) { + x[${o} - 1] = indices[${o} - 1] * ${a} - ${u} + i; + if (x[${o} - 1] < 0 || x[${o} - 1] >= ${m}) { + pad++; + continue; + } + ${r} + }`:b=` + for (int i = 0; i < ${s}; i++) { + x[${o} - 1] = indices[${o} - 1] * ${a} - ${u} + i; + ${r} + }`,e.kernelShape.length===2){let I=e.kernelShape[e.kernelShape.length-2],A=e.strides[e.strides.length-2],k=e.pads[e.pads.length/2-2],P=e.pads[e.pads.length-2],z=n[o-2];k+P!==0?w=` + for (int j = 0; j < ${I}; j++) { + x[${o} - 2] = indices[${o} - 2] * ${A} - ${k} + j; + if (x[${o} - 2] < 0 || x[${o} - 2] >= ${z}) { + pad+= ${s}; + continue; + } + `:w=` + for (int j = 0; j < ${I}; j++) { + x[${o} - 2] = indices[${o} - 2] * ${A} - ${k} + j; + `,x=` + } + `}return` + float process(int indices[${o}]) { + int x[${o}]; + copyVec(indices, x); + + float value = ${i}; + int pad = 0; + ${w} + ${b} + ${x} + ${t} + return value; + } + `}else{let s=be.size(e.kernelShape),a=be.computeStrides(e.kernelShape),u=a.length,d=e.pads.length,m=_S(u),b=Da(n,"inputDims"),w=Da(e.pads,"pads"),x=Da(a,"kernelStrides"),$=Da(e.strides,"strides"),I=e.pads.reduce((P,z)=>P+z),A="";return I?A=` + if (x[j] >= inputDims[j] || x[j] < 0) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + ${r} + }`:A=` + } + ${r} + `,` + ${m} + float process(int indices[${o}]) { + int x[${o}]; + copyVec(indices, x); + int offset[${u}]; + int pads[${d}]; + int inputDims[${o}]; + int kernelStrides[${u}]; + int strides[${u}]; + ${w} + ${b} + ${$} + ${x} + + float value = ${i}; + int pad = 0; + bool isPad = false; + for (int i = 0; i < ${s}; i++) { + offsetToIndices(i, kernelStrides, offset); + isPad = false; + for (int j = ${o} - ${u}; j < ${o}; j++) { + x[j] = indices[j] * strides[j - ${o} + ${u}] + + offset[j - ${o} + ${u}] - pads[j - 2]; + ${A} + } + ${t} + + return value; + } + `}},Da=(n,e)=>{let r="";for(let t=0;t` + void offsetToIndices(int offset, int[${n}] strides, out int[${n}] indices) { + if (${n} == 0) { + return; + } + for (int i = 0; i < ${n} - 1; ++i) { + indices[i] = offset / strides[i]; + offset -= indices[i] * strides[i]; + } + indices[${n} - 1] = offset; + }`});var Nn,ln,xS,$S,Tg,Sg,Ig,Cg,Ag,Eg,Og,Pg=q(()=>{"use strict";Rt();ho();it();Je();Nn=(n,e,r,t,i)=>{$S(e);let o={name:t,inputNames:["A"],inputTypes:[0]};return[n.run({...o,cacheHint:r.cacheKey,get:()=>xS(n,e,r,t,i,o)},e)]},ln=n=>{let e=n.attributes.getInts("axes",[]),r=n.attributes.getInt("keepdims",1)===1;return Fe({axes:e,keepDims:r})},xS=(n,e,r,t,i,o)=>{let s=[],a=e[0].dims.length||1,u=[],d=be.normalizeAxes(r.axes,e[0].dims.length),m=i(e,d),b=m[1];for(let $=0;$=0||d.length===0?(r.keepDims&&s.push(1),b=` + for(int j${$} = 0; j${$} < ${e[0].dims[$]}; j${$}++) { + inputIdx[${$}] = j${$}; + ${b} + }`):(u.push(`inputIdx[${$}] = outputIdx[${s.length}];`),s.push(e[0].dims[$]));let x=` + float process(int outputIdx[${s.length||1}]) { + float value; // final result + int inputIdx[${a}]; // addressing input data + ${u.join(` +`)} + ${m[0]} // init ops for reduce max/min + ${b} + ${m[2]} // final computation for reduce mean + return value; + }`;return{...o,output:{dims:s,type:e[0].type,textureType:0},shaderSource:x}},$S=n=>{if(!n||n.length!==1)throw new Error("Reduce op requires 1 input.");if(un.indexOf(n[0].type)===-1)throw new Error("Invalid input type.")},Tg=(n,e,r)=>Nn(n,e,r,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),Sg=(n,e,r)=>Nn(n,e,r,"ReduceMean",(i,o)=>{let s=1;for(let a=0;a=0||o.length===0)&&(s*=i[0].dims[a]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${s}.;`]}),Ig=(n,e,r)=>Nn(n,e,r,"ReduceMax",(i,o)=>{let s=[];for(let a=0;a=0||o.length===0)&&s.push(`inputIdx[${a}] = 0;`);return[`${s.join(` +`)} +value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),Cg=(n,e,r)=>Nn(n,e,r,"ReduceMin",(i,o)=>{let s=[];for(let a=0;a=0||o.length===0)&&s.push(`inputIdx[${a}] = 0;`);return[`${s.join(` +`)} +value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),Ag=(n,e,r)=>Nn(n,e,r,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),Eg=(n,e,r)=>Nn(n,e,r,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),Og=(n,e,r)=>Nn(n,e,r,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])});var kg,Dg=q(()=>{"use strict";it();kg=(n,e)=>{let r=be.calculateReshapedDims(e[0].dims,e[1].integerData);return n.session.pack?[n.reshapePacked(e[0],r)]:[n.reshapeUnpacked(e[0],r)]}});var Bg,Pu,Rg,zg,mo,TS,ku,Ra,Du=q(()=>{"use strict";Rt();vt();Je();Bg={name:"Upsample",inputNames:["X"],inputTypes:[0]},Pu=(n,e,r)=>(ku(e,r),[n.run({...Bg,cacheHint:r.cacheKey,get:()=>TS(n,e,r)},e)]),Rg=n=>mo(n,7),zg=n=>mo(n,9),mo=(n,e)=>{let r=e>=10,t=n.attributes.getString("mode","nearest");if(t!=="nearest"&&t!=="linear"&&(e<11||t!=="cubic"))throw new Error(`unrecognized mode: ${t}`);let i=[];e<9&&(i=n.attributes.getFloats("scales"),Ra(i,t,r));let o=n.attributes.getFloat("extrapolation_value",0),s=e>10?n.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(s)===-1)throw new Error(`coordinate_transform_mode '${s}' is not supported`);let a=s==="tf_crop_and_resize",u=a,d=t==="nearest"&&e>=11?n.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(d)===-1)throw new Error(`nearest_mode '${d}' is not supported`);let m=n.attributes.getFloat("cubic_coeff_a",-.75),b=n.attributes.getInt("exclude_outside",0)!==0;if(b&&t!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");let w=e<11?!0:t==="nearest"&&s==="asymmetric"&&d==="floor",x=0,$=0,I=0;return e>10?n.inputs.length>2?(x=1,$=2,I=3):($=1,I=2):e===9&&($=1),Fe({opset:e,isResize:r,mode:t,scales:i,extrapolationValue:o,coordinateTransformMode:s,useExtrapolation:u,needRoiInput:a,nearestMode:d,cubicCoefficientA:m,excludeOutside:b,useNearest2xOptimization:w,roiInputIdx:x,scalesInputIdx:$,sizesInputIdx:I})},TS=(n,e,r)=>{let t=Ie(n.session.backend.glContext.version),[i,o]=n.calculateTextureWidthAndHeight(e[0].dims,0),s=e[0].dims.map((I,A)=>Math.floor(I*r.scales[A])),[a,u]=n.calculateTextureWidthAndHeight(s,0),d=s.length,m=new Array(d),b=new Array(d),w=` + int output_pitches[${d}]; + int input_pitches[${d}]; + `;for(let I=d-1;I>=0;I--)m[I]=I===d-1?1:m[I+1]*s[I+1],b[I]=I===d-1?1:b[I+1]*e[0].dims[I+1],w+=` + output_pitches[${I}] = ${m[I]}; + input_pitches[${I}] = ${b[I]}; + `;let x=` + float getInputFloat(int index) { + vec2 coords = offsetToCoords(index, ${i}, ${o}); + float value = getColorAsFloat(${t.texture2D}(X, coords)); + return value; + } + `,$=r.mode==="nearest"?` + ${x} + float process(int indices[${d}]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${a}, ${u}); + + ${w} + + int d, m; + for (int dim = 0; dim < ${d}; ++dim) { + d = output_index / output_pitches[dim]; + m = output_index - d * output_pitches[dim]; + output_index = m; + + if (scales[dim] != 1 && d > 0) { + int d2 = d / scales[dim]; + m = d - d2 * scales[dim]; + d = d2; + } + input_index += input_pitches[dim] * d; + } + + return getInputFloat(input_index); + }`:d===4?` + ${x} + float process(int indices[4]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${a}, ${u}); + + ${w} + + int m; + int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; + index_of_dim0 = output_index / output_pitches[0]; + m = output_index - index_of_dim0 * output_pitches[0]; + index_of_dim1 = m / output_pitches[1]; + m = m - index_of_dim1 * output_pitches[1]; + index_of_dim2 = m / output_pitches[2]; + m = m - index_of_dim2 * output_pitches[2]; + index_of_dim3 = m; + + int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; + index_of_input_dim2 = index_of_dim2 / scales[2]; + y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; + index_of_input_dim3 = index_of_dim3 / scales[3]; + x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; + + input_index = index_of_dim0 * input_pitches[0] + + index_of_dim1 * input_pitches[1] + + index_of_input_dim2 * input_pitches[2] + + index_of_input_dim3; + + float x00 = getInputFloat(input_index); + float x10, x01, x11; + + bool end_of_dim2 = false; + if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) { + // It's the end in dimension 2 + x01 = x00; + end_of_dim2 = true; + } else { + x01 = getInputFloat(input_index + input_pitches[2]); + } + + if (index_of_input_dim3 == (input_pitches[2] - 1)) { + // It's the end in dimension 3 + x10 = x00; + x11 = x01; + } + else { + x10 = getInputFloat(input_index + 1); + x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); + } + + float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); + float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); + return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); + }`:` + ${x} + float process(int indices[2]) { + int input_index = 0; + int output_index = coordsToOffset(TexCoords, ${a}, ${u}); + + ${w} + + int m; + int index_of_dim0, index_of_dim1; + index_of_dim0 = output_index / output_pitches[0]; + m = output_index - index_of_dim0 * output_pitches[0]; + index_of_dim1 = m; + + int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; + index_of_input_dim0 = index_of_dim0 / scales[0]; + y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; + index_of_input_dim1 = index_of_dim1 / scales[1]; + x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; + + input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; + + float x00 = getInputFloat(input_index); + float x10, x01, x11; + + bool end_of_dim0 = false; + if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) { + // It's the end in dimension 0 + x01 = x00; + end_of_dim0 = true; + } else { + x01 = getInputFloat(input_index + input_pitches[0]); + } + + if (index_of_input_dim1 == (input_pitches[0] - 1)) { + // It's the end in dimension 1 + x10 = x00; + x11 = x01; + } + else { + x10 = getInputFloat(input_index + 1); + x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); + } + + float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); + float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); + return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); + }`;return{...Bg,output:{dims:s,type:e[0].type,textureType:0},shaderSource:$,variables:[{name:"scales",type:"int",arrayLength:r.scales.length,data:r.scales.map(I=>Math.ceil(I))}]}},ku=(n,e)=>{if(!n||e.opset<9&&n.length!==1||e.opset>=9&&e.opset<11&&n.length!==2||e.opset>=11&&n.length<2)throw new Error("invalid inputs.");if(e.scales.length>0&&n[0].dims.length!==e.scales.length)throw new Error("Invalid input shape.");if(n[0].type==="string")throw new Error("Invalid input tensor types.")},Ra=(n,e,r)=>{if(r){for(let t of n)if(t<=0)throw new Error("Scale value should be greater than 0.")}else for(let t of n)if(t<1)throw new Error("Scale value should be greater than or equal to 1.");if((e==="linear"||e==="cubic")&&n.length!==2&&(n.length!==4||n[0]!==1||n[1]!==1))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${r?"Resize":"Upsample"} opeartor.`)}});var Bu,Ru,Mg,Ng,SS,IS,CS,AS,Lg=q(()=>{"use strict";vt();Je();Mr();Rn();Du();Bu={name:"Resize",inputNames:["A"],inputTypes:[2]},Ru=(n,e,r)=>(ku(e,r),[n.run({...Bu,cacheHint:r.cacheKey,get:()=>SS(n,e,r)},e)]),Mg=n=>mo(n,10),Ng=n=>mo(n,11),SS=(n,e,r)=>{let t=Ie(n.session.backend.glContext.version),[i,o]=IS(e,r);if(i.every(z=>z===1)&&r.coordinateTransformMode!=="tf_crop_and_resize")return{...Bu,output:{dims:o,type:e[0].type,textureType:2},hasMain:!0,shaderSource:`void main() { + vec4 v = ${t.texture2D}(X, TexCoords); + ${t.output} = v; + }`};let a=o.length;if(a<2)throw new Error(`output dimension should be at least 2, but got ${a}`);let u=o[a-2],d=o[a-1],m=e[0].dims;if(a!==m.length)throw new Error(`output dimension should match input ${m.length}, but got ${a}`);let b=m[a-2],w=m[a-1],x=i[a-2],$=i[a-1],I="";if(r.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${r.mode}'`);switch(r.coordinateTransformMode){case"asymmetric":I=` + vec4 getSourceFracIndex(ivec4 coords) { + return vec4(coords) / scaleWHWH; + } + `;break;case"half_pixel":I=` + vec4 getSourceFracIndex(ivec4 coords) { + return (vec4(coords) + 0.5) / scaleWHWH - 0.5; + } + `;break;case"pytorch_half_pixel":I=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 fcoords = vec4(coords); + return vec4( + ${d}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, + ${u}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, + ${d}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, + ${u}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 + ); + } + `;break;case"align_corners":I=` + vec4 getSourceFracIndex(ivec4 coords) { + vec4 resized = vec4(${d}.0 - 1.0, ${u}.0 - 1.0, ${d}.0 - 1.0, + ${u}.0 - 1.0); + vec4 original = vec4(${w}.0 - 1.0, ${b}.0 - 1.0, ${w}.0 - 1.0, + ${b}.0 - 1.0); + vec4 new_scale = original / resized; + return vec4(coords) * new_scale; + } + `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${r.coordinateTransformMode}'`)}let A=Kt(a),k=Nr(),P=` + const vec2 inputWH = vec2(${b}.0, ${w}.0); + const vec4 scaleWHWH = vec4(float(${x}), float(${$}), float(${x}), float(${$})); + ${k} + ${I} + float getAValue(int x10, int r, int c, int d) { + return getChannel(getA(x10, r, c, d), vec2(c, d)); + } + void main() { + ${A} rc = getOutputCoords(); + + int batch = rc[0]; + int depth = rc[1]; + + // retrieve the 4 coordinates that is used in the 4 packed output values. + ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); + + // calculate the source index in fraction + vec4 sourceFrac = getSourceFracIndex(coords); + + // get the lower and upper bound of the 4 values that will be packed into one texel. + ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); + ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); + ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); + ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); + + bool hasNextRow = rc.w < ${u-1}; + bool hasNextCol = rc.z < ${d-1}; + + // pack x00, x01, x10, x11's top-left corner into one vec4 structure + vec4 topLeft = vec4( + getAValue(batch, depth, x00.x, x00.y), + hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); + + // pack x00, x01, x10, x11's top-right corner into one vec4 structure + vec4 topRight = vec4( + getAValue(batch, depth, x00.x, x00.w), + hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); + + // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure + vec4 bottomLeft = vec4( + getAValue(batch, depth, x00.z, x00.y), + hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); + + // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure + vec4 bottomRight = vec4( + getAValue(batch, depth, x00.z, x00.w), + hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, + hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, + (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); + + // calculate the interpolation fraction on u and v direction + vec4 frac = vec4(sourceFrac) - floor(sourceFrac); + vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); + + vec4 top = mix(topLeft, topRight, clampFrac.ywyw); + vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); + vec4 newValue = mix(top, bottom, clampFrac.xxzz); + + ${t.output} = vec4(newValue); + } + `;return{...Bu,output:{dims:o,type:e[0].type,textureType:2},hasMain:!0,shaderSource:P}},IS=(n,e)=>{let t=n[0].dims,i=e.scales,o;if(i.length===0){let a=n[e.scalesInputIdx];if(a&&a.size!==0){if(n[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=CS(a,e.mode,e.isResize)}else{let u=n[e.sizesInputIdx];if(!u||u.size===0)throw new Error("Either scales or sizes MUST be provided as input.");o=Array.from(u.integerData),i=AS(o,t,e.mode,e.isResize)}}else if(n[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");let s=o||t.map((a,u)=>Math.floor(a*i[u]));return[i,s]},CS=(n,e,r)=>{let t=Array.from(n.floatData);return Ra(t,e,r),t},AS=(n,e,r,t)=>{let i=e.length,o=new Array(i);for(let s=0,a=i;s{"use strict";Bn();jg=(n,e)=>(ES(e),[new Pt([e[0].dims.length],"int32",void 0,void 0,new Int32Array(e[0].dims))]),ES=n=>{if(!n||n.length!==1)throw new Error("Shape requires 1 input.")}});var zu,Fg,Vg,Gg,OS,Wg,PS,kS,Hg=q(()=>{"use strict";Rt();ho();it();Je();zu={name:"Slice",inputNames:["A"],inputTypes:[0]},Fg=(n,e,r)=>(OS(e),[n.run({...zu,cacheHint:r.cacheKey,get:()=>Gg(n,e[0],r)},e)]),Vg=n=>{let e=n.attributes.getInts("starts"),r=n.attributes.getInts("ends"),t=n.attributes.getInts("axes",[]);return Fe({starts:e,ends:r,axes:t})},Gg=(n,e,r)=>{let t=r.axes.length===0?e.dims.slice(0).map((b,w)=>w):r.axes,i=be.normalizeAxes(t,e.dims.length),o=r.starts.map((b,w)=>b>e.dims[i[w]]-1?e.dims[i[w]]:be.normalizeAxis(b,e.dims[i[w]])),s=r.ends.map((b,w)=>b>e.dims[i[w]]-1?e.dims[i[w]]:be.normalizeAxis(b,e.dims[i[w]])),a=e.dims.slice(),u=[];for(let b=0;b0&&u.push(`outputIdx[${i[b]}] += ${o[b]};`);let m=` + float process(int outputIdx[${a.length}]) { + ${u.join(` + `)} + return _A(outputIdx); + }`;return{...zu,output:{dims:a,type:e.type,textureType:0},shaderSource:m}},OS=n=>{if(!n||n.length!==1)throw new Error("Slice requires 1 input.");if(un.indexOf(n[0].type)===-1)throw new Error("Invalid input type.")},Wg=(n,e)=>{kS(e);let r=PS(n,e);return[n.run({...zu,cacheHint:r.cacheKey,get:()=>Gg(n,e[0],r)},[e[0]])]},PS=(n,e)=>{if(!n.session.isInitializer(e[1].dataId)||!n.session.isInitializer(e[2].dataId)||e.length>=4&&!n.session.isInitializer(e[3].dataId)||e.length>=5&&!n.session.isInitializer(e[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(e.length>=5&&e[4].integerData.some(s=>s!==1))throw new Error("currently non-1 steps is not supported for Slice");let r=Array.from(e[1].integerData),t=Array.from(e[2].integerData),i=e.length>=4?Array.from(e[3].integerData):[],o=`${i};${r};${t}`;return{starts:r,ends:t,axes:i,cacheKey:o}},kS=n=>{if(!n||n.length<3||n.length>5)throw new Error("Invalid input number.");if(n[1].type!=="int32"||n[1].dims.length!==1)throw new Error("Invalid input type.");if(n[2].type!=="int32"||n[2].dims.length!==1)throw new Error("Invalid input type.");if(n.length>=4&&(n[3].type!=="int32"||n[3].dims.length!==1))throw new Error("Invalid input type.");if(n.length>=5&&(n[4].type!=="int32"||n[4].dims.length!==1))throw new Error("Invalid input type.")}});var qg,Kg,Yg,Xg,Zg,Jg,Qg,ey,DS,BS,RS,ty,ry=q(()=>{"use strict";Rt();it();vt();Je();ka();qg={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[0]},Kg={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[0,0]},Yg={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[0,0,0]},Xg=(n,e,r)=>{ty(e);let t=e[0].dims.slice(),i=be.normalizeAxis(r.axis,t.length),o=be.sizeToDimension(t,i),s=be.sizeFromDimension(t,i);return ey(n,e,r,o,s)},Zg=n=>Fe({axis:n.attributes.getInt("axis",1)}),Jg=n=>Fe({axis:n.attributes.getInt("axis",-1)}),Qg=(n,e,r)=>{ty(e);let t=e[0].dims.slice(),i=be.normalizeAxis(r.axis,t.length),o=t.length,s=i!==o-1,a=[],u=[],d=[],m;s&&(u=Array.from({length:o}).map(($,I)=>I),u[i]=o-1,u[o-1]=i,u.map($=>a.push(t[$])),m=Fe({perm:u}),d=Mn(n,e,m));let b=s?be.sizeToDimension(a,o-1):be.sizeToDimension(t,o-1),w=s?be.sizeFromDimension(a,o-1):be.sizeFromDimension(t,o-1),x=ey(n,s?d:e,r,b,w);return s?Mn(n,x,m):x},ey=(n,e,r,t,i)=>{let o=DS(n,e[0],t,i,[t]),s=n.run({...qg,cacheHint:r.cacheKey,get:()=>o},e),a=BS(n,e[0],t,i,o.output.dims,[t]),u=n.run({...Kg,cacheHint:r.cacheKey,get:()=>a},[e[0],s]),d=RS(n,e[0],t,i,o.output.dims,a.output.dims);return[n.run({...Yg,cacheHint:r.cacheKey,get:()=>d},[e[0],s,u])]},DS=(n,e,r,t,i)=>{let[o,s]=n.calculateTextureWidthAndHeight(e.dims,0),a=i.length;if(r<1||t<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(i.length!==1)throw new Error("Dimensionality of the output should be 1");if(i[0]!==r)throw new Error("Shape of the output should be equal to logical row count");let u=Ie(n.session.backend.glContext.version),d=` + float process(int[${a}] indices) { + int logical_row_start_offset = indices[0] * ${t}; + + float max = getColorAsFloat(${u.texture2D}(A, offsetToCoords(logical_row_start_offset, ${o}, + ${s} ))); + for(int i=1; i<${t}; ++i) + { + float current = getColorAsFloat(${u.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${o}, ${s}))); + if(current > max) + max = current; + } + + return max; + }`;return{...qg,output:{dims:i,type:e.type,textureType:0},shaderSource:d}},BS=(n,e,r,t,i,o)=>{let[s,a]=n.calculateTextureWidthAndHeight(e.dims,0),u=o.length;if(r<1||t<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(o.length!==1)throw new Error("Dimensionality of the output should be 1");if(o[0]!==r)throw new Error("Shape of the output should be equal to logical row count");if(i.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==r)throw new Error("Shape of the intermediate results should be equal to logical row count");let d=Ie(n.session.backend.glContext.version),m=` + float process(int[${u}] indices) { + int logical_row_start_offset = indices[0] * ${t}; + + float norm_factor = 0.0; + float max = _Max(indices); + for(int i=0; i<${t}; ++i) + { + norm_factor += exp(getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${s}, ${a}))) - max); + } + + return norm_factor; + }`;return{...Kg,output:{dims:o,type:e.type,textureType:0},shaderSource:m}},RS=(n,e,r,t,i,o)=>{let[s,a]=n.calculateTextureWidthAndHeight(e.dims,0),u=e.dims.length;if(r<1||t<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(i.length!==1||o.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==r||o[0]!==r)throw new Error("Shape of the intermediate results should be equal to logical row count");let d=` + float process(int[${u}] indices) { + + // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) + int offset = coordsToOffset(TexCoords, ${s}, ${a}); + + //determine the logical row for this index + int logical_row_index[1]; + logical_row_index[0] = offset / ${t}; + + float norm_factor = _Norm(logical_row_index); + + // avoid possible division by 0 + // if norm_facor is 0, all elements are zero + // if so, return 0 + if(norm_factor == 0.0) + return 0.0; + + return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; + }`;return{...Yg,output:{dims:e.dims,type:e.type,textureType:0},shaderSource:d}},ty=n=>{if(!n||n.length!==1)throw new Error("Softmax requires 1 input.");if(n[0].type!=="float32"&&n[0].type!=="float64")throw new Error("Invalid input type")}});var ny,iy,oy,zS,MS,NS,ay=q(()=>{"use strict";Rt();it();Je();ny={name:"Split",inputNames:["A"],inputTypes:[0]},iy=(n,e,r)=>{NS(e);let t=be.normalizeAxis(r.axis,e[0].dims.length),i=zS(n,e,t,r),o=[];for(let s=0;sMS(n,e[0],r,t,s)},e));return o},oy=n=>{let e=n.attributes.getInt("axis",0),r=n.attributes.getInts("split",[]),t=n.outputs.length;return Fe({axis:e,split:r,numOutputs:t})},zS=(n,e,r,t)=>{let[,i]=so.splitShape(e[0].dims,r,t.split,t.numOutputs);return i.length},MS=(n,e,r,t,i)=>{let[o,s]=so.splitShape(e.dims,t,r.split,r.numOutputs),a=s[i],u=o[i],m=` + float process(int indices[${u.length}]) { + indices[${t}] += ${a}; + return _A(indices); + } + `;return{...ny,cacheHint:`${r.cacheKey}:${i}`,output:{dims:u,type:e.type,textureType:0},shaderSource:m}},NS=n=>{if(!n||n.length!==1)throw new Error("Split requires one input.");if(n[0].type!=="int8"&&n[0].type!=="uint8"&&n[0].type!=="int16"&&n[0].type!=="uint16"&&n[0].type!=="int32"&&n[0].type!=="uint32"&&n[0].type!=="float32"&&n[0].type!=="float64"&&n[0].type!=="bool")throw new Error("Invalid input type.")}});var Mu,sy,uy,LS,jS,ly=q(()=>{"use strict";it();Mu=(n,e,r)=>{LS(e);let t=be.squeezeShape(e[0].dims,r);return[n.reshapeUnpacked(e[0],t)]},sy=(n,e)=>(jS(e),Mu(n,[e[0]],Array.from(e[1].integerData))),uy=n=>n.attributes.getInts("axes"),LS=n=>{if(!n||n.length!==1)throw new Error("Squeeze requires 1 input.");if(n[0].type==="string")throw new Error("invalid input tensor types.")},jS=n=>{if(!n||n.length!==2)throw new Error("Squeeze requires 2 inputs.");if(n[1].type!=="int32")throw new Error("Invalid input type.")}});var dy,US,FS,cy=q(()=>{"use strict";vt();Je();dy=(n,e)=>{FS(e);let r={name:"Sum",inputNames:e.map((i,o)=>`X${o}`),inputTypes:new Array(e.length).fill(0)};return[n.run({...r,get:()=>US(n,e,r)},e)]},US=(n,e,r)=>{let t=Ie(n.session.backend.glContext.version),i=e[0].dims.slice(),s=` + void main() { + vec4 result = ${e.map((a,u)=>`${t.texture2D}(X${u},TexCoords)`).join(" + ")}; + ${t.output} = result; + } + `;return{...r,output:{dims:i,type:e[0].type,textureType:0},hasMain:!0,shaderSource:s}},FS=n=>{if(!n||n.length===0)throw new Error("Sum requires inputs.");let e=n[0].dims.length;for(let r=1;r{"use strict";ho();Je();fy=(n,e)=>{GS(e);let r={name:"Tile",inputNames:["A"],inputTypes:[0]};return[n.run({...r,get:()=>VS(n,e,r)},e)]},VS=(n,e,r)=>{let t=e[0].dims.slice(),i=new Array(t.length),o=[];for(let u=0;u{if(!n||n.length!==2)throw new Error("Tile requires 2 input.");if(n[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(n[1].dims[0]!==n[0].dims.length)throw new Error("Invalid input shape.");if(un.indexOf(n[0].type)===-1)throw new Error("Invalid input type.");if(n[1].type!=="int32"&&n[1].type!=="int16")throw new Error("Invalid repeat type.")}});var Nu,hy,my,WS,HS,gy=q(()=>{"use strict";it();Nu=(n,e,r)=>{WS(e);let t=be.unsqueezeShape(e[0].dims,r);return[n.reshapeUnpacked(e[0],t)]},hy=(n,e)=>(HS(e),Nu(n,[e[0]],Array.from(e[1].integerData))),my=n=>n.attributes.getInts("axes"),WS=n=>{if(!n||n.length!==1)throw new Error("Unsqueeze requires 1 input.");if(n[0].type==="string")throw new Error("invalid input tensor types.")},HS=n=>{if(!n||n.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(n[1].type!=="int32")throw new Error("Invalid input type.")}});var yy,by=q(()=>{"use strict";Ah();Uh();Gh();Xh();Ea();Dm();Lm();Fm();Wm();Ym();Jm();rg();ag();Oa();dg();$g();Pg();Dg();Lg();Ug();Hg();ry();ay();ly();cy();py();ka();_u();gy();Du();yy=[["Abs","","6+",Zh],["Acos","","7+",Jh],["Add","","7+",Eh],["And","","7+",Oh],["Asin","","7+",Qh],["Atan","","7+",em],["AveragePool","","7+",fg,pg],["BatchNormalization","","7+",Ih,Ch],["Cast","","6+",Fh,Vh],["Ceil","","6+",nm],["Clip","","6-10",vu,tm],["Clip","","11+",rm],["Concat","","4+",qh,Yh],["Conv","","1+",Cu,Au],["ConvTranspose","","1+",Pm,km],["Cos","","7+",im],["Div","","7+",Ph],["Dropout","","7+",wu],["DepthToSpace","","1+",Mm,Nm],["Equal","","7+",kh],["Elu","","6+",om,am],["Exp","","6+",sm],["Flatten","","1+",jm,Um],["Floor","","6+",um],["FusedConv","com.microsoft","1+",Cu,Au],["Gather","","1+",Vm,Gm],["Gemm","","7-10",Eu,qm],["Gemm","","11+",Eu,Km],["GlobalAveragePool","","1+",mg,gg],["GlobalMaxPool","","1+",_g],["Greater","","7+",Dh],["Identity","","1+",wu],["ImageScaler","","1+",Xm,Zm],["InstanceNormalization","","6+",eg,tg],["LeakyRelu","","6+",lm,dm],["Less","","7+",Bh],["LRN","","1+",ng,ig],["Log","","6+",cm],["MatMul","","1+",Tm,Sm],["MaxPool","","1+",yg,bg],["Mul","","7+",Rh],["Neg","","6+",fm],["Not","","1+",pm],["Or","","7+",zh],["Pad","","2-10",Ou,sg],["Pad","","11+",ug,lg],["Pow","","7+",Mh],["PRelu","","7+",Nh],["ReduceLogSum","","1+",Eg,ln],["ReduceMax","","1+",Ig,ln],["ReduceMean","","1+",Sg,ln],["ReduceMin","","1+",Cg,ln],["ReduceProd","","1+",Ag,ln],["ReduceSum","","1-12",Tg,ln],["ReduceSumSquare","","1+",Og,ln],["Relu","","6+",hm],["Reshape","","5+",kg],["Resize","","10",Ru,Mg],["Resize","","11+",Ru,Ng],["Shape","","1+",jg],["Sigmoid","","6+",mm],["Sin","","7+",gm],["Slice","","10+",Wg],["Slice","","1-9",Fg,Vg],["Softmax","","1-12",Xg,Zg],["Softmax","","13+",Qg,Jg],["Split","","2-12",iy,oy],["Sqrt","","6+",ym],["Squeeze","","1-12",Mu,uy],["Squeeze","","13+",sy],["Sub","","7+",Lh],["Sum","","6+",dy],["Tan","","7+",bm],["Tanh","","6+",vm],["Tile","","6+",fy],["Transpose","","1+",Mn,Rm],["Upsample","","7-8",Pu,Rg],["Upsample","","9",Pu,zg],["Unsqueeze","","1-12",Nu,my],["Unsqueeze","","13+",hy],["Xor","","7+",jh]]});function wy(n){let e={},r;for(;(r=vy.exec(n))!==null;){let t=r[3].split(",").map(i=>{let o=i.trim().split(" ");return o&&o.length===2?{type:o[0],name:o[1]}:null}).filter(i=>i!==null);e[r[2]]={params:t,body:r[4]}}for(let t in e){let i=qS.replace("__FUNC__",t),o=new RegExp(i,"gm");for(;(r=o.exec(n))!==null;){let s=r[1],a=r[2],u=r[3].split(","),d=s?`${s} ${a};`:"",m=e[t].body,b="";e[t].params.forEach((x,$)=>{x&&(b+=`${x.type} ${x.name} = ${u[$]}; +`)}),m=`${b} + ${m}`,m=m.replace("return",`${a} = `);let w=` + ${d} + { + ${m} + } + `;n=n.replace(r[0],w)}}return n=n.replace(vy,""),n}var vy,qS,_y=q(()=>{"use strict";vy=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm,qS="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"});function $i(n,e){let r=[],t=[],i=e!=null&&Array.isArray(e)&&e.length===0,o=e==null||i?null:KS(e,n).sort(),s=0;for(let a=0;aa)&&n[a]===1&&(r.push(n[a]),t.push(a)),o[s]<=a&&s++}n[a]!==1&&(r.push(n[a]),t.push(a))}return{newShape:r,keptDims:t}}function KS(n,e){let r=e.length;return n=n==null?e.map((t,i)=>i):[].concat(n),yi(n.every(t=>t>=-r&&t`All values in axis param must be in range [-${r}, ${r}) but got axis ${n}`),yi(n.every(YS),()=>`All values in axis param must be integers but got axis ${n}`),n.map(t=>t<0?r+t:t)}function YS(n){return n%1===0}function XS(n){if(n.length===0)return 1;let e=n[0];for(let r=1;r{"use strict";cr();it();za=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,r){let t=this.computeTexture(e,r);return r&&r.isPacked&&(t[0]/=2,t[1]/=2),r&&r.reverseWH?[t[1],t[0]]:t}computeTexture(e,r){let t=r&&r.isPacked;if(e.length===0)return t?[2,2]:[1,1];let i=this.maxTextureSize;if(r&&r.breakAxis!==void 0){let a=r.breakAxis>=e.length?1:e.slice(r.breakAxis).reduce((d,m)=>d*m),u=r.breakAxis<=0?1:e.slice(0,r.breakAxis).reduce((d,m)=>d*m);if(a>i||u>i)at.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${r.breakAxis}`);else return[a,u]}let o=e.slice(0);t&&(i=i*2,o=o.map((a,u)=>u>=o.length-2?o[u]%2===0?o[u]:o[u]+1:o[u]),o.length===1&&(o=[2,o[0]])),o.length!==2&&(o=$i(o).newShape);let s=XS(o);return o.length<=1&&s<=i?[1,s]:o.length===2&&o[0]<=i&&o[1]<=i?o:o.length===3&&o[0]*o[1]<=i&&o[2]<=i?[o[0]*o[1],o[2]]:o.length===3&&o[0]<=i&&o[1]*o[2]<=i?[o[0],o[1]*o[2]]:o.length===4&&o[0]*o[1]*o[2]<=i&&o[3]<=i?[o[0]*o[1]*o[2],o[3]]:o.length===4&&o[0]<=i&&o[1]*o[2]*o[3]<=i?[o[0],o[1]*o[2]*o[3]]:t?xy(s/4).map(a=>a*2):xy(s)}}});var Ma,$y=q(()=>{"use strict";it();Zr();vt();Lu();Mr();Ma=class extends mr{constructor(r){super(r)}getFunctions(){return{...this.offsetToCoords(),...this.coordsToOffset(),...this.toVec(),...this.valueFrom(),...this.getCommonUtilFuncs(),...this.getInputsSamplingSnippets(),...this.getOutputSamplingSnippet()}}getCustomTypes(){return{}}offsetToCoords(){let r="offsetToCoords";return{offsetToCoords:new me(` + vec2 ${r}(int offset, int width, int height) { + int t = offset / width; + int s = offset - t*width; + vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); + return coords; + } + `)}}coordsToOffset(){let r="coordsToOffset";return{coordsToOffset:new me(` + int ${r}(vec2 coords, int width, int height) { + float s = coords.s * float(width); + float t = coords.t * float(height); + int offset = int(t) * width + int(s); + return offset; + } + `)}}getOutputSamplingSnippet(){let r=this.context.outputTextureLayout;return r.isPacked?this.getPackedOutputSamplingSnippet(r):this.getUnpackedOutputSamplingSnippet(r)}getPackedOutputSamplingSnippet(r){let t=r.unpackedShape,i=[r.width,r.height],o={},s="getOutputCoords";switch(t.length){case 0:o[s]=this.getOutputScalarCoords();break;case 1:o[s]=this.getOutputPacked1DCoords(t,i);break;case 2:o[s]=this.getOutputPacked2DCoords(t,i);break;case 3:o[s]=this.getOutputPacked3DCoords(t,i);break;default:o[s]=this.getOutputPackedNDCoords(t,i)}let u=` + void setOutput(vec4 val) { + ${Ie(this.context.glContext.version).output} = val; + } + `,d="floatTextureSetRGBA";return o[d]=new me(u),o}getUnpackedOutputSamplingSnippet(r){let t=r.unpackedShape,i=[r.width,r.height],o={},s="getOutputCoords";switch(t.length){case 0:o[s]=this.getOutputScalarCoords();break;case 1:o[s]=this.getOutputUnpacked1DCoords(t,i);break;case 2:o[s]=this.getOutputUnpacked2DCoords(t,i);break;case 3:o[s]=this.getOutputUnpacked3DCoords(t,i);break;case 4:o[s]=this.getOutputUnpacked4DCoords(t,i);break;case 5:o[s]=this.getOutputUnpacked5DCoords(t,i);break;case 6:o[s]=this.getOutputUnpacked6DCoords(t,i);break;default:throw new Error(`Unsupported output dimensionality: ${t.length}`)}let u=` + void setOutput(float val) { + ${Ie(this.context.glContext.version).output} = vec4(val, 0, 0, 0); + } + `,d="floatTextureSetR";return o[d]=new me(u),o}getOutputScalarCoords(){return new me(` + int getOutputCoords() { + return 0; + } + `)}getOutputPacked1DCoords(r,t){let i=t,o="";return i[0]===1?(o=` + int getOutputCoords() { + return 2 * int(TexCoords.y * ${i[1]}.0); + } + `,new me(o)):i[1]===1?(o=` + int getOutputCoords() { + return 2 * int(TexCoords.x * ${i[0]}.0); + } + `,new me(o)):(o=` + int getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${i[0]}, ${i[1]})); + return 2 * (resTexRC.y * ${i[0]} + resTexRC.x); + } + `,new me(o))}getOutputPacked2DCoords(r,t){let i="";if(On.arraysEqual(r,t))return i=` + ivec2 getOutputCoords() { + return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); + } + `,new me(i);let o=t,s=Math.ceil(r[1]/2);return i=` + ivec2 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${o[0]}, ${o[1]})); + + int index = resTexRC.y * ${o[0]} + resTexRC.x; + + // reverse r and c order for packed texture + int r = imod(index, ${s}) * 2; + int c = 2 * (index / ${s}); + + return ivec2(r, c); + } + `,new me(i)}getOutputPacked3DCoords(r,t){let i=[t[0],t[1]],o=Math.ceil(r[2]/2),s=o*Math.ceil(r[1]/2),a=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${i[0]}, ${i[1]})); + int index = resTexRC.y * ${i[0]} + resTexRC.x; + + int b = index / ${s}; + index -= b * ${s}; + + // reverse r and c order for packed texture + int r = imod(index, ${o}) * 2; + int c = 2 * (index / ${o}); + + return ivec3(b, r, c); + } + `;return new me(a)}getOutputPackedNDCoords(r,t){let i=[t[0],t[1]],o=Math.ceil(r[r.length-1]/2),s=o*Math.ceil(r[r.length-2]/2),a=s,u="",d="b, r, c";for(let b=2;b=0;--d)s[d]=s[d+1]*r[d+1];let a=["r","c","d"],u=s.map((d,m)=>{let b=`int ${a[m]} = index / ${d}`,w=m===s.length-1?`int ${a[m+1]} = index - ${a[m]} * ${d}`:`index -= ${a[m]} * ${d}`;return`${b}; ${w};`}).join("");return i=` + ivec3 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${u} + return ivec3(r, c, d); + } + `,new me(i)}getOutputUnpacked4DCoords(r,t){let i="",o=r.length,s=null;o<2&&(s=[]),s=new Array(o-1),s[o-2]=r[o-1];for(let d=o-3;d>=0;--d)s[d]=s[d+1]*r[d+1];let a=["r","c","d","d2"],u=s.map((d,m)=>{let b=`int ${a[m]} = index / ${d}`,w=m===s.length-1?`int ${a[m+1]} = index - ${a[m]} * ${d}`:`index -= ${a[m]} * ${d}`;return`${b}; ${w};`}).join("");return i=` + ivec4 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${u} + return ivec4(r, c, d, d2); + } + `,new me(i)}getOutputUnpacked5DCoords(r,t){let i="",o=r.length,s=null;o<2&&(s=[]),s=new Array(o-1),s[o-2]=r[o-1];for(let d=o-3;d>=0;--d)s[d]=s[d+1]*r[d+1];let a=["r","c","d","d2","d3"],u=s.map((d,m)=>{let b=`int ${a[m]} = index / ${d}`,w=m===s.length-1?`int ${a[m+1]} = index - ${a[m]} * ${d}`:`index -= ${a[m]} * ${d}`;return`${b}; ${w};`}).join("");return i=` + ivec5 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${u} + return ivec5(r, c, d, d2, d3); + } + `,new me(i)}getOutputUnpacked6DCoords(r,t){let i="",o=r.length,s=null;o<2&&(s=[]),s=new Array(o-1),s[o-2]=r[o-1];for(let d=o-3;d>=0;--d)s[d]=s[d+1]*r[d+1];let a=["r","c","d","d2","d3","d4"],u=s.map((d,m)=>{let b=`int ${a[m]} = index / ${d}`,w=m===s.length-1?`int ${a[m+1]} = index - ${a[m]} * ${d}`:`index -= ${a[m]} * ${d}`;return`${b}; ${w};`}).join("");return i=` + ivec6 getOutputCoords() { + ivec2 resTexRC = ivec2(TexCoords.xy * + vec2(${t[0]}, ${t[1]})); + int index = resTexRC.y * ${t[0]} + resTexRC.x; + ${u} + return ivec6(r, c, d, d2, d3, d4); + } + `,new me(i)}getCommonUtilFuncs(){let r={},t="uvFromFlat";r[t]=new me(` + vec2 uvFromFlat(int texNumR, int texNumC, int index) { + int texC = index / texNumR; + int texR = index - texC * texNumR; + // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to + // v. + return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); + } + `),t="packedUVfrom1D",r[t]=new me(` + vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { + int texelIndex = index / 2; + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),t="packedUVfrom2D",r[t]=new me(` + vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { + int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); + int texR = texelIndex / texNumC; + int texC = texelIndex - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),t="packedUVfrom3D",r[t]=new me(` + vec2 packedUVfrom3D(int texNumR, int texNumC, + int texelsInBatch, int texelsInLogicalRow, int b, + int row, int col) { + int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); + int texR = index / texNumC; + int texC = index - texR * texNumC; + return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); + } + `),t="sampleTexture";let i=Ie(this.context.glContext.version);return r[t]=new me(` + float sampleTexture(sampler2D textureSampler, vec2 uv) { + return ${i.texture2D}(textureSampler, uv).r; + }`),r}getInputsSamplingSnippets(){let r={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((i,o)=>{let s=this.context.inputTextureLayouts[o],a=xa(i);s.isPacked?r[a]=this.getPackedSamplerFromInput(a,i,s):r[a]=this.getUnpackedSamplerFromInput(a,i,s);let u=dh(i);s.unpackedShape.length<=t.unpackedShape.length&&(s.isPacked?r[u]=this.getPackedSamplerAtOutputCoords(u,s,t,i):r[u]=this.getUnpackedSamplerAtOutputCoords(u,s,t,i))}),r}getPackedSamplerAtOutputCoords(r,t,i,o){let s=t.unpackedShape,a=i.unpackedShape,d=xa(o),m=s.length,b=a.length,w=qt.getBroadcastDims(s,a),x=Kt(b),$=b-m,I,A=Ar();m===0?I="":b<2&&w.length>=1?I="coords = 0;":I=w.map(le=>`coords.${A[le+$]} = 0;`).join(` +`);let k="";b<2&&m>0?k="coords":k=s.map((le,ge)=>`coords.${A[ge+$]}`).join(", ");let P="return outputValue;",U=be.size(s)===1,Y=be.size(a)===1;if(m===1&&!U&&!Y)P=` + return vec4(outputValue.xy, outputValue.xy); + `;else if(U&&!Y)b===1?P=` + return vec4(outputValue.x, outputValue.x, 0., 0.); + `:P=` + return vec4(outputValue.x); + `;else if(w.length){let le=m-2,ge=m-1;w.indexOf(le)>-1&&w.indexOf(ge)>-1?P="return vec4(outputValue.x);":w.indexOf(le)>-1?P="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":w.indexOf(ge)>-1&&(P="return vec4(outputValue.xx, outputValue.zz);")}let ie=` + int lastDim = coords.${A[b-1]}; + coords.${A[b-1]} = coords.${A[b-2]}; + coords.${A[b-2]} = lastDim; + `,ne=` + vec4 ${r}() { + ${x} coords = getOutputCoords(); + ${ie} + ${I} + vec4 outputValue = ${d}(${k}); + ${P} + } + `;return new me(ne,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(r,t,i,o){let s=[i.width,i.height],a=[t.width,t.height],u=t.unpackedShape.length,d=i.unpackedShape.length,m=t.unpackedShape,b=i.unpackedShape,w=xa(o);if(u===d&&On.arraysEqual(a,s)){let U=` + float ${r}() { + return sampleTexture(${o}, TexCoords); + } + `;return new me(U,["coordinates.sampleTexture"])}let x=Kt(d),$=qt.getBroadcastDims(m,b),I=d-u,A,k=Ar();u===0?A="":d<2&&$.length>=1?A="coords = 0;":A=$.map(U=>`coords.${k[U+I]} = 0;`).join(` +`);let P="";d<2&&u>0?P="coords":P=t.unpackedShape.map((U,F)=>`coords.${k[F+I]}`).join(", ");let z=` + float ${r}() { + ${x} coords = getOutputCoords(); + ${A} + return ${w}(${P}); + } + `;return new me(z,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(r,t,i){switch(i.unpackedShape.length){case 0:return this.getPackedSamplerScalar(r,t);case 1:return this.getPackedSampler1D(r,t,i);case 2:return this.getPackedSampler2D(r,t,i);case 3:return this.getPackedSampler3D(r,t,i);default:return this.getPackedSamplerND(r,t,i)}}getUnpackedSamplerFromInput(r,t,i){let o=i.unpackedShape;switch(o.length){case 0:return this.getUnpackedSamplerScalar(r,t,i);case 1:return this.getUnpackedSampler1D(r,t,i);case 2:return this.getUnpackedSampler2D(r,t,i);case 3:return this.getUnpackedSampler3D(r,t,i);case 4:return this.getUnpackedSampler4D(r,t,i);case 5:return this.getUnpackedSampler5D(r,t,i);case 6:return this.getUnpackedSampler6D(r,t,i);default:throw new Error(`Unsupported dimension ${o.length}-D`)}}getPackedSamplerScalar(r,t){let i=Ie(this.context.glContext.version),o=` + vec4 ${r}() { + return ${i.texture2D}(${t}, halfCR); + } + `;return new me(o)}getPackedSampler1D(r,t,i){let o=[i.width,i.height],s=[o[1],o[0]],a=Ie(this.context.glContext.version),d=`vec4 ${r}(int index) { + vec2 uv = packedUVfrom1D( + ${s[0]}, ${s[1]}, index); + return ${a.texture2D}(${t}, uv); + }`;return new me(d,["coordinates.packedUVfrom1D"])}getPackedSampler2D(r,t,i){let o=i.unpackedShape,s=[i.width,i.height],a=Ie(this.context.glContext.version),u=s[0],d=s[1];if(s!=null&&On.arraysEqual(o,s)){let $=`vec4 ${r}(int row, int col) { + vec2 uv = (vec2(col, row) + halfCR) / vec2(${d}.0, ${u}.0); + return ${a.texture2D}(${t}, uv); + }`;return new me($)}let m=s,b=Math.ceil(o[1]/2),x=`vec4 ${r}(int row, int col) { + vec2 uv = packedUVfrom2D(${m[1]}, ${m[0]}, ${b}, row, col); + return ${a.texture2D}(${t}, uv); + }`;return new me(x,["coordinates.packedUVfrom2D"])}getPackedSampler3D(r,t,i){let o=i.unpackedShape,s=[i.width,i.height],a=[s[0],s[1]],u=Ie(this.context.glContext.version);if(o[0]===1){let I=o.slice(1),A=[1,2],k=bi(o,I),P=["b","row","col"],z=JSON.parse(JSON.stringify(i));z.unpackedShape=k;let U=this.getPackedSamplerFromInput(r,t,z),Y=`${U.routineBody} + vec4 ${r}(int b, int row, int col) { + return ${r}(${vi(P,A)}); + } `;return new me(Y,U.dependencies)}let d=a[0],m=a[1],b=Math.ceil(o[2]/2),w=b*Math.ceil(o[1]/2),$=`vec4 ${r}(int b, int row, int col) { + vec2 uv = packedUVfrom3D( + ${m}, ${d}, ${w}, ${b}, b, row, col); + return ${u.texture2D}(${t}, uv);}`;return new me($,["coordinates.packedUVfrom3D"])}getPackedSamplerND(r,t,i){let o=i.unpackedShape,s=o.length,a=[i.width,i.height],u=Ie(this.context.glContext.version),d=[a[0],a[1]],m=d[1],b=d[0],w=Math.ceil(o[s-1]/2),x=w*Math.ceil(o[s-2]/2),$="int b, int row, int col",I=`b * ${x} + (row / 2) * ${w} + (col / 2)`;for(let P=2;P{let o=this.context.inputTextureLayouts[i],a=(o.unpackedShape.length>0?o.unpackedShape:o.shape).length,u=`_${t}`;r[u]=new me(this.getValueFromSingle(t,a,o.width,o.height,!1),[`shapeUtils.indicesToOffset${u}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),u=u+"_T",r[u]=new me(this.getValueFromSingle(t,a,o.width,o.height,!0),[`shapeUtils.indicesToOffset${u}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),r}getValueFromSingle(r,t,i,o,s){let a=`_${r}`;s&&(a=a+"_T");let u=Ie(this.context.glContext.version);return` + float ${a}(int m[${t}]) { + int offset = indicesToOffset${a}(m); + vec2 coords = offsetToCoords(offset, ${i}, ${o}); + float value = getColorAsFloat(${u.texture2D}(${r}, coords)); + return value; + } + `}getPackedValueFrom(r,t,i,o,s){let a=`_${r}_Pack`;s&&(a=a+"_T");let u=Ie(this.context.glContext.version);return` + vec4 ${a}(int m[${t}]) { + int offset = indicesToOffset_${r}(m); + vec2 coords = offsetToCoords(offset, ${i}, ${o}); + return ${u.texture2D}(${r}, coords); + } + `}}});var Na,Ty=q(()=>{"use strict";Zr();Na=class n extends mr{constructor(e){super(e)}getFunctions(){return{...this.encodeFloat32(),...this.decodeFloat32()}}getCustomTypes(){return{}}encodeFloat32(){return{encode:new me(`highp vec4 encode(highp float f) { + return vec4(f, 0.0, 0.0, 0.0); + } + `)}}decodeFloat32(){return{decode:new me(`highp float decode(highp vec4 rgba) { + return rgba.r; + } + `)}}encodeUint8(){let e=n.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new me(` + highp vec4 encode(highp float f) { + highp float F = abs(f); + highp float Sign = step(0.0,-f); + highp float Exponent = floor(log2(F)); + highp float Mantissa = (exp2(- Exponent) * F); + Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); + highp vec4 rgba; + rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); + rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); + rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); + rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); + ${e} + rgba = rgba / 255.0; // values need to be normalized to [0,1] + return rgba; + } + `)}}decodeUint8(){let e=n.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new me(` + highp float decode(highp vec4 rgba) { + rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] + ${e} + highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; + highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; + highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); + highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); + return Result; + } + `)}}static isLittleEndian(){let e=new ArrayBuffer(4),r=new Uint32Array(e),t=new Uint8Array(e);if(r[0]=3735928559,t[0]===239)return!0;if(t[0]===222)return!1;throw new Error("unknown endianness")}}});var La,Sy=q(()=>{"use strict";Zr();vt();La=class extends mr{constructor(e){super(e)}getFunctions(){return{...this.setFragColor(),...this.getColorAsFloat()}}getCustomTypes(){return{}}setFragColor(){let e=Ie(this.context.glContext.version);return{setFragColor:new me(` + void setFragColor(float value) { + ${e.output} = encode(value); + } + `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new me(` + float getColorAsFloat(vec4 color) { + return decode(color); + } + `,["encoding.decode"])}}}});var ja,Iy=q(()=>{"use strict";Zr();ja=class n extends mr{constructor(e){super(e)}getFunctions(){return{...this.bcastIndex(),...this.bcastMatmulIndex(),...this.offsetToIndices(),...this.indicesToOffset(),...this.incrementIndices()}}getCustomTypes(){return{}}bcastIndex(){let e=this.context.outputTextureLayout.shape.length,r={};return this.context.programInfo.inputNames.forEach((t,i)=>{let o=this.context.inputTextureLayouts[i].unpackedShape;if(o.length<=e){let s=o.length,a=e-s,u=`bcastIndices_${t}`,d="";for(let b=0;b{let o=this.context.inputTextureLayouts[i].shape;if(!(o.length<2||o.length>e)){let s=o.length,a=e-s,u=`bcastMatmulIndices_${t}`,d="";for(let b=0;b{let i=this.context.inputTextureLayouts[t].shape,o=this.context.inputTextureLayouts[t].strides,s=i.length,a=`indicesToOffset_${r}`;e[a]=new me(n.indexToOffsetSingle(a,s,o)),a=`indicesToOffset_${r}_T`,e[a]=new me(n.indexToOffsetSingle(a,s,o.slice().reverse()))}),e}static indexToOffsetSingle(e,r,t){let i="";for(let o=r-1;o>=0;--o)i+=` + offset += indices[${o}] * ${t[o]}; + `;return` + int ${e}(int indices[${r}]) { + int offset = 0; + ${i} + return offset; + } + `}offsetToIndices(){let e={};return this.context.programInfo.inputNames.forEach((r,t)=>{let i=this.context.inputTextureLayouts[t].shape,o=this.context.inputTextureLayouts[t].strides,s=i.length,a=`offsetToIndices_${r}`;e[a]=new me(n.offsetToIndicesSingle(a,s,o)),a=`offsetToIndices_${r}_T`,e[a]=new me(n.offsetToIndicesSingle(a,s,o.slice().reverse()))}),e}static offsetToIndicesSingle(e,r,t){let i=[];for(let o=0;o{let i=this.context.inputTextureLayouts[t].shape,o=i.length,s=`incrementIndices_${r}`,a="";for(let d=0;d= 0; --i) { + if(i > axis) continue; + indices[i] += 1; + if(indices[i] < shape[i]) { + break; + } + indices[i] = 0; + } + } + `;e[s]=new me(u)}),e}}});var Ua,Cy=q(()=>{"use strict";Zr();Ua=class extends mr{constructor(e){super(e)}getCustomTypes(){return{}}getFunctions(){return{...this.binaryVecFunctions(),...this.copyVec(),...this.setVecItem(),...this.getVecItem()}}binaryVecFunctions(){let r=this.context.outputTextureLayout.shape.length,t={add:"+=",sub:"-=",mul:"*=",div:"/="},i={};for(let o in t){let s=`${o}Vec`,a="";for(let d=0;d{"use strict";$y();Ty();Sy();Iy();Cy();ju={encoding:Na,fragcolor:La,vec:Ua,shapeUtils:ja,coordinates:Ma}});var Fa,Ey=q(()=>{"use strict";Zr();_y();Ay();vt();Fa=class{constructor(e,r,t,i){this.libs={};this.glslLibRoutineDependencyGraph={};this.context=new Ia(e,r,t,i),Object.keys(ju).forEach(s=>{let a=new ju[s](this.context);this.libs[s]=a});let o=this.glslLibRoutineDependencyGraph;for(let s in this.libs){let u=this.libs[s].getFunctions();for(let d in u){let m=s+"."+d,b;o[m]?(b=o[m],b.routineBody=u[d].routineBody):(b=new po(m,u[d].routineBody),o[m]=b);let w=u[d].dependencies;if(w)for(let x=0;x{let i=t.split(".")[1];e.indexOf(i)!==-1&&r.push(this.glslLibRoutineDependencyGraph[t])}),Ca.returnOrderedNodes(r)}getUniforms(e,r){let t=[];if(e)for(let i of e)t.push(`uniform sampler2D ${i};`);if(r)for(let i of r)t.push(`uniform ${i.type} ${i.name}${i.arrayLength?`[${i.arrayLength}]`:""};`);return t.join(` +`)}}});var Va,Oy=q(()=>{"use strict";Lt();cr();Ey();vt();Va=class{constructor(e,r,t){this.profiler=e;this.glContext=r;this.textureLayoutStrategy=t;this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t){this.profiler.event("op",`ProgramManager.run ${e.programInfo.name??"unknown kernel"}`,()=>{let i=this.glContext.gl,o=e.program;i.useProgram(o);try{this.bindOutput(t),this.attributesBound||this.bindAttributes(e.attribLocations),this.bindUniforms(e.uniformLocations,e.programInfo.variables??[],r)}catch(s){throw at.error("ProgramManager",e.programInfo.shaderSource),s}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(e=>this.glContext.deleteProgram(e.program))}build(e,r,t){return this.profiler.event("backend","ProgramManager.build",()=>{let i=new Fa(this.glContext,e,r,t),o=i.preprocess(),s=this.compile(o);return{programInfo:e,program:s,uniformLocations:this.getUniformLocations(s,i.context.programInfo.inputNames,i.context.programInfo.variables),attribLocations:this.getAttribLocations(s)}})}compile(e){if(!this.vertexShader){at.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");let i=sh(this.glContext.version);this.vertexShader=this.glContext.compileShader(i,this.glContext.gl.VERTEX_SHADER)}De.debug&&at.verbose("ProrgramManager",`FragShader: +${e} +`);let r=this.glContext.compileShader(e,this.glContext.gl.FRAGMENT_SHADER),t=this.glContext.createProgram(this.vertexShader,r);return this.glContext.deleteShader(r),t}bindOutput(e){let r=e.width,t=e.height;at.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${r}/${t}, shape=${e.shape}, type=${e.tensor.type}`),this.glContext.attachFramebuffer(e.texture,r,t)}bindAttributes(e){let r=e.position,t=e.textureCoord;this.glContext.setVertexAttributes(r,t),this.attributesBound=!0}bindUniforms(e,r,t){let i=this.glContext.gl,o=0;for(let{name:s,type:a,location:u,arrayLength:d}of e){let m=r.find(b=>b.name===s)?.data;if(a!=="sampler2D"&&!m)throw new Error(`variable '${s}' does not have data defined in program info`);switch(a){case"sampler2D":this.bindTexture(t[o],u,o),o++;break;case"float":d?i.uniform1fv(u,m):i.uniform1f(u,m);break;case"int":d?i.uniform1iv(u,m):i.uniform1i(u,m);break;default:throw new Error(`Uniform not implemented: ${a}`)}}}bindTexture(e,r,t){this.glContext.bindTextureToUniform(e.texture,t,r)}getAttribLocations(e){return{position:this.getAttribLocation(e,"position"),textureCoord:this.getAttribLocation(e,"textureCoord")}}getUniformLocations(e,r,t){let i=[];if(r)for(let o of r)i.push({name:o,type:"sampler2D",location:this.getUniformLocation(e,o)});if(t)for(let o of t)i.push({...o,location:this.getUniformLocation(e,o.name)});return i}getUniformLocation(e,r){let i=this.glContext.gl.getUniformLocation(e,r);if(i===null)throw new Error(`Uniform ${r} not found.`);return i}getAttribLocation(e,r){return this.glContext.gl.getAttribLocation(e,r)}}});var Ga,Py=q(()=>{"use strict";cr();co();Ga=class{constructor(e,r,t,i){this.glContext=e;this.layoutStrategy=r;this.profiler=t;this.config=i;this.pendingRead=new Map;i.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(e,r,t,i){let o=this.toEncoderType(e),s=this.glContext.getEncoder(o,r.channels||1,i);if(r.isPacked&&i===1)throw new Error("not implemented");let a=r.width,u=r.height,d,m;if(this.config.reuseTextures){d=`${a}x${u}_${s.format}_${s.internalFormat}_${s.textureType}`,m=this.inUseTextures.get(d),m||(m=[],this.inUseTextures.set(d,m));let w=this.idleTextures.get(d);if(w&&w.length>0){let x=w.pop();return m.push(x),i===1&&this.glContext.updateTexture(x,a,u,s,this.toTextureData(e,t)),x}}at.verbose("TextureManager",`Creating new texture of size ${r.width}x${r.height}`);let b=this.glContext.allocateTexture(a,u,s,this.toTextureData(e,t));return this.config.reuseTextures&&(m.push(b),this.textureLookup.set(b,d)),b}readTexture(e,r,t){return t||(t=1),this.profiler.event("backend","TextureManager.readTexture",()=>{let i=e.shape.reduce((s,a)=>s*a)*t,o=this.glContext.readTexture(e.texture,e.width,e.height,i,this.toEncoderType(r),t);return this.toTensorData(r,o)})}async readTextureAsync(e,r,t){let i=e.tensor.dataId;if(t||(t=1),this.pendingRead.has(i)){let o=this.pendingRead.get(i);return new Promise(s=>o?.push(s))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(i,[]);let o=e.shape.reduce((d,m)=>d*m)*t;await this.glContext.createAndWaitForFence();let s=this.glContext.readTexture(e.texture,e.width,e.height,o,this.toEncoderType(r),t),a=this.toTensorData(r,s),u=this.pendingRead.get(i);return this.pendingRead.delete(i),u?.forEach(d=>d(a)),a})}readUint8TextureAsFloat(e){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{let r=e.shape.reduce((i,o)=>i*o),t=this.glContext.readTexture(e.texture,e.width,e.height,r*4,"byte",4);return new Float32Array(t.buffer,t.byteOffset,r)})}releaseTexture(e,r){let t;if(this.config.reuseTextures&&(t=this.textureLookup.get(e.texture),t)){r&&this.textureLookup.delete(t);let i=this.inUseTextures.get(t);if(i){let o=i.indexOf(e.texture);if(o!==-1){i.splice(o,1);let s=this.idleTextures.get(t);s||(s=[],this.idleTextures.set(t,s)),s.push(e.texture)}}}(!t||r)&&(at.verbose("TextureManager",`Deleting texture of size ${e.width}x${e.height}`),this.glContext.deleteTexture(e.texture))}toTensorData(e,r){switch(e){case"int16":return r instanceof Int16Array?r:Int16Array.from(r);case"int32":return r instanceof Int32Array?r:Int32Array.from(r);case"int8":return r instanceof Int8Array?r:Int8Array.from(r);case"uint16":return r instanceof Uint16Array?r:Uint16Array.from(r);case"uint32":return r instanceof Uint32Array?r:Uint32Array.from(r);case"uint8":case"bool":return r instanceof Uint8Array?r:Uint8Array.from(r);case"float32":return r instanceof Float32Array?r:Float32Array.from(r);case"float64":return r instanceof Float64Array?r:Float64Array.from(r);default:throw new Error(`TensorData type ${e} is not supported`)}}toTextureData(e,r){if(r)return r instanceof Float32Array?r:new Float32Array(r)}toEncoderType(e){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}});var Wa,ky=q(()=>{"use strict";cr();qf();Th();by();Oy();Lu();Py();Wa=class{constructor(e,r){this.backend=e;this.context=r;this.layoutStrategy=new za(e.glContext.maxTextureSize),this.programManager=new Va(this.context.profiler,e.glContext,this.layoutStrategy),this.textureManager=new Ga(e.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:e.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=e.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new Sa(this)}onGraphInitialized(e){let r=e.getValues().filter(t=>t.from===-1&&t.tensor).map(t=>t.tensor.dataId);this.initializers=new Set(r)}isInitializer(e){return this.initializers?this.initializers.has(e):!1}addInitializer(e){this.initializers.add(e)}getTextureData(e,r){return r?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,r,t=!1){at.verbose("WebGLSessionHandler","Storing Texture data in cache"),t?this.packedTextureDataCache.set(e,r):this.unpackedTextureDataCache.set(e,r)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.unpackedTextureDataCache=new Map}resolve(e,r,t){let i=Hf(e,r,yy);return{impl:i.opImpl,context:i.opInit?i.opInit(e,t):e}}}});function ZS(n){let e=0;for(;e{"use strict";Lt();co();co();Mr();go=class{constructor(e,r){this.frameBufferBound=!1;this.itemsToPoll=[];this.gl=e,this.version=r,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(e,r,t,i){let o=this.gl,s=o.createTexture();o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);let a=i?t.encode(i,e*r):null;return o.texImage2D(o.TEXTURE_2D,0,t.internalFormat,e,r,0,t.format,t.textureType,a),this.checkError(),s}updateTexture(e,r,t,i,o){let s=this.gl;s.bindTexture(s.TEXTURE_2D,e);let a=i.encode(o,r*t);s.texSubImage2D(s.TEXTURE_2D,0,0,0,r,t,i.format,i.textureType,a),this.checkError()}attachFramebuffer(e,r,t){let i=this.gl;i.bindTexture(i.TEXTURE_2D,e),i.bindFramebuffer(i.FRAMEBUFFER,this.framebuffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0),this.checkError(),i.viewport(0,0,r,t),i.scissor(0,0,r,t)}readTexture(e,r,t,i,o,s){let a=this.gl;s||(s=1),this.frameBufferBound||this.attachFramebuffer(e,r,t);let u=this.getEncoder(o,s),d=u.allocate(r*t);return a.bindTexture(a.TEXTURE_2D,e),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e,0),a.readPixels(0,0,r,t,a.RGBA,u.textureType,d),this.checkError(),u.decode(d,i)}isFramebufferReady(){return!0}getActiveTexture(){let e=this.gl;return`TEXTURE${e.getParameter(this.gl.ACTIVE_TEXTURE)-e.TEXTURE0}`}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(e,r){let t=this.gl;t.vertexAttribPointer(e,3,t.FLOAT,!1,20,0),t.enableVertexAttribArray(e),r!==-1&&(t.vertexAttribPointer(r,2,t.FLOAT,!1,20,12),t.enableVertexAttribArray(r)),this.checkError()}createProgram(e,r){let t=this.gl,i=t.createProgram();return t.attachShader(i,e),t.attachShader(i,r),t.linkProgram(i),i}compileShader(e,r){let t=this.gl,i=t.createShader(r);if(!i)throw new Error(`createShader() returned null with type ${r}`);if(t.shaderSource(i,e),t.compileShader(i),t.getShaderParameter(i,t.COMPILE_STATUS)===!1)throw new Error(`Failed to compile shader: ${t.getShaderInfoLog(i)} +Shader source: +${e}`);return i}deleteShader(e){this.gl.deleteShader(e)}bindTextureToUniform(e,r,t){let i=this.gl;i.activeTexture(i.TEXTURE0+r),this.checkError(),i.bindTexture(i.TEXTURE_2D,e),this.checkError(),i.uniform1i(t,r),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(De.debug){let e=this.gl,r=e.getError(),t="";switch(r){case e.NO_ERROR:return;case e.INVALID_ENUM:t="INVALID_ENUM";break;case e.INVALID_VALUE:t="INVALID_VALUE";break;case e.INVALID_OPERATION:t="INVALID_OPERATION";break;case e.INVALID_FRAMEBUFFER_OPERATION:t="INVALID_FRAMEBUFFER_OPERATION";break;case e.OUT_OF_MEMORY:t="OUT_OF_MEMORY";break;case e.CONTEXT_LOST_WEBGL:t="CONTEXT_LOST_WEBGL";break;default:t=`Unknown WebGL Error: ${r.toString(16)}`}throw new Error(t)}}deleteTexture(e){this.gl.deleteTexture(e)}deleteProgram(e){this.gl.deleteProgram(e)}getEncoder(e,r,t=0){if(this.version===2)return new $a(this.gl,r);switch(e){case"float":return t===1||this.isRenderFloat32Supported?new lo(this.gl,r):new lo(this.gl,r,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new Ta(this.gl,r);default:throw new Error(`Invalid dataType: ${e}`)}}clearActiveTextures(){let e=this.gl;for(let r=0;rthis.isTimerResultAvailable(e)),this.getTimerResult(e)}async createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let r,t=e,i=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),i===null?r=()=>!0:r=()=>{let o=t.clientWaitSync(i,0,0);return o===t.ALREADY_SIGNALED||o===t.CONDITION_SATISFIED},{query:i,isFencePassed:r}}async pollFence(e){return new Promise(r=>{this.addItemToPoll(()=>e.isFencePassed(),()=>r())})}pollItems(){let e=ZS(this.itemsToPoll.map(r=>r.isDoneFn));for(let r=0;r<=e;++r){let{resolveFn:t}=this.itemsToPoll[r];t()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,r){this.itemsToPoll.push({isDoneFn:e,resolveFn:r}),!(this.itemsToPoll.length>1)&&await cu(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function Uu(n){let e;if((!n||n==="webgl2")&&"webgl2"in Ti?e=Ti.webgl2:(!n||n==="webgl")&&"webgl"in Ti&&(e=Ti.webgl),!e)try{let t=QS();e=By(t,n)}catch{let i=JS();e=By(i,n)}n=n||e.version===1?"webgl":"webgl2";let r=e.gl;return Ti[n]=e,r.isContextLost()?(delete Ti[n],Uu(n)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),e)}function By(n,e){let r={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},t,i=r;if((!e||e==="webgl2")&&(t=n.getContext("webgl2",i),t))try{return new go(t,2)}catch(o){at.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${o}`)}if((!e||e==="webgl")&&(t=n.getContext("webgl",i)||n.getContext("experimental-webgl",i),t))try{return new go(t,1)}catch(o){at.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${o}`)}throw new Error("WebGL is not supported")}function JS(){if(typeof document>"u")throw new TypeError("failed to create canvas: document is not supported");let n=document.createElement("canvas");return n.width=1,n.height=1,n}function QS(){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var Ti,Ry=q(()=>{"use strict";cr();Dy();Ti={}});var Ha,zy=q(()=>{"use strict";Lt();cr();ky();Ry();Ha=class{get contextId(){return De.webgl.contextId}set contextId(e){De.webgl.contextId=e}get matmulMaxBatchSize(){return De.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){De.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return De.webgl.textureCacheMode}set textureCacheMode(e){De.webgl.textureCacheMode=e}get pack(){return De.webgl.pack}set pack(e){De.webgl.pack=e}get async(){return De.webgl.async}set async(e){De.webgl.async=e}initialize(){try{return this.glContext=Uu(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),at.setWithEnv(De),De.webgl.context||Object.defineProperty(De.webgl,"context",{value:this.glContext.gl}),at.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(e){return at.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),!1}}createSessionHandler(e){return new Wa(this,e)}dispose(){this.glContext.dispose()}}});async function Fu(n){if(n){let e=typeof n=="string"?[n]:n;for(let r of e){let t=My.get(r);if(t)return t;let i=await tI(r);if(i)return i}}else return Fu(["webgl"]);throw new Error("no available backend to use")}async function tI(n){let e=eI;if(typeof e[n]<"u"&&rI(e[n])){let r=e[n],t=r.initialize();if(typeof t=="object"&&"then"in t&&(t=await t),t)return My.set(n,r),r}}function rI(n){let e=n;return"initialize"in e&&typeof e.initialize=="function"&&"createSessionHandler"in e&&typeof e.createSessionHandler=="function"&&"dispose"in e&&typeof e.dispose=="function"}var My,eI,Ny=q(()=>{"use strict";zy();My=new Map,eI={webgl:new Ha}});var Vu,qa,Ly=q(()=>{"use strict";cr();Vu=class{constructor(e,r){this.op=e;this.node=r}},qa=class{constructor(e,r,t){this.graph=e;this.profiler=t;this.initialize(r)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",()=>{let r=this.graph.getNodes();if(r.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map((t,i)=>new Vu(t,r[i])),this.reset(),this._starter=[],this._ops.forEach((t,i)=>{let o=!0;for(let s of t.node.inputs)if(!this._values[s]&&this.graph.getInputIndices().indexOf(s)===-1){o=!1;break}o&&this._starter.push(i)})})}reset(){this._values=this.graph.getValues().map(e=>e.tensor)}async execute(e,r){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let t=e.createInferenceHandler(),i=this.graph.getInputIndices();if(r.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${r.length} expected: ${i.length}`);r.forEach((m,b)=>{let w=i[b];this._values[w]=m});let o=this._starter.slice(0),s=this.graph.getValues(),a=this.graph.getNodes(),u=0;for(;uthis._values[A]);if(w.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${b.node}`);let x=w;at.verbose("ExecPlan",`Runing op:${b.node.name} (${x.map((A,k)=>`'${b.node.inputs[k]}': ${A.type}[${A.dims.join(",")}]`).join(", ")})`);let $=await this.profiler.event("node",b.node.name,async()=>b.op.impl(t,x,b.op.context));if($.length!==b.node.outputs.length)throw new Error("the size of output does not match model definition.");$.forEach((A,k)=>{let P=b.node.outputs[k];if(this._values[P])throw new Error(`output [${P}] already has value: op:${b.node.name}`);this._values[P]=A});let I=new Set;$.forEach((A,k)=>{let P=b.node.outputs[k];for(let z of s[P].to){let U=a[z],F=!0;for(let Y of U.inputs)if(!this._values[Y]){F=!1;break}F&&I.add(z)}}),o.push(...I)}let d=[];for(let m=0;m{"use strict";no();Ze=fi(gi());Bn();it();br=xe.experimental.fbs,yo=class n{constructor(e){if(this._attributes=new Map,e!=null){for(let r of e)r instanceof Ze.onnx.AttributeProto?this._attributes.set(r.name,[n.getValue(r),n.getType(r)]):r instanceof br.Attribute&&this._attributes.set(r.name(),[n.getValue(r),n.getType(r)]);if(this._attributes.sizePt.fromProto(o));if(e instanceof br.Attribute)return t.map(o=>Pt.fromOrtTensor(o))}return r===Ze.onnx.AttributeProto.AttributeType.STRING&&e instanceof Ze.onnx.AttributeProto?uo(t):r===Ze.onnx.AttributeProto.AttributeType.STRINGS&&e instanceof Ze.onnx.AttributeProto?t.map(uo):t}static getValueNoCheck(e){return e instanceof Ze.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(e):this.getValueNoCheckFromOrtFormat(e)}static getValueNoCheckFromOnnxFormat(e){switch(e.type){case Ze.onnx.AttributeProto.AttributeType.FLOAT:return e.f;case Ze.onnx.AttributeProto.AttributeType.INT:return e.i;case Ze.onnx.AttributeProto.AttributeType.STRING:return e.s;case Ze.onnx.AttributeProto.AttributeType.TENSOR:return e.t;case Ze.onnx.AttributeProto.AttributeType.GRAPH:return e.g;case Ze.onnx.AttributeProto.AttributeType.FLOATS:return e.floats;case Ze.onnx.AttributeProto.AttributeType.INTS:return e.ints;case Ze.onnx.AttributeProto.AttributeType.STRINGS:return e.strings;case Ze.onnx.AttributeProto.AttributeType.TENSORS:return e.tensors;case Ze.onnx.AttributeProto.AttributeType.GRAPHS:return e.graphs;default:throw new Error(`unsupported attribute type: ${Ze.onnx.AttributeProto.AttributeType[e.type]}`)}}static getValueNoCheckFromOrtFormat(e){switch(e.type()){case br.AttributeType.FLOAT:return e.f();case br.AttributeType.INT:return e.i();case br.AttributeType.STRING:return e.s();case br.AttributeType.TENSOR:return e.t();case br.AttributeType.GRAPH:return e.g();case br.AttributeType.FLOATS:return e.floatsArray();case br.AttributeType.INTS:{let r=[];for(let t=0;t{"use strict";jy();no();Wu=fi(gi());Bn();it();Ka=xe.experimental.fbs,Hu={from:(n,e)=>new Gu(n,e)},jr=class{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=Nt.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}},Ya=class{constructor(e,r){e instanceof Wu.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new yo(e.attribute)):e instanceof Ka.Node&&(this.name=r??e.name(),this.opType=e.opType(),this.attributes=new yo(Nt.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=!0}},Gu=class{constructor(e,r){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(r),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(e){if(e instanceof Wu.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else if(e instanceof Ka.Graph)this.buildGraphFromOrtFormat(e);else throw new TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(e){let r=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let t=new Map;if(!e.input)throw new Error("missing information in graph: input");let i=[];for(let o of e.input){if(r.has(o.name))throw new Error(`duplicated input name: ${o.name}`);let s=this._allData.push(new jr(o))-1;r.set(o.name,s),i.push(o.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(let o of e.initializer){let s=r.get(o.name);if(s===void 0){let a=new jr;a.type={shape:{dims:Nt.tensorDimsFromProto(o.dims)},tensorType:Nt.tensorDataTypeFromProto(o.dataType)},s=this._allData.push(a)-1,r.set(o.name,s)}this._allData[s]._from=-1,this._allData[s].tensor=Pt.fromProto(o)}for(let o=0;o"u"&&(d=this._allData.push(new jr)-1,r.set(u,d)),s.outputs.push(d),this._allData[d]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${d}`);if(this._allData[d]._from=o,a.opType==="Constant"){if(!a.attribute||a.attribute.length!==1||!a.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!a.output||a.output.length!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");s.outputs.pop(),s.executeNode=!1,this._allData[d]._from=-1,this._allData[d].tensor=Pt.fromProto(a.attribute[0].t)}}}for(let o=0;o"u"){if(u===""&&(a.input.length===3||a.input.length===4)&&a.opType==="Resize")continue;throw new Error(`unrecognized input '${u}' for node: ${a.name}`)}s.inputs.push(d),this._allData[d]._to.push(o)}}return!0}buildGraphFromOrtFormat(e){let r=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let t=new Map,i=[];for(let o=0;o"u"&&(m=this._allData.push(new jr)-1,r.set(d,m)),s.outputs.push(m),this._allData[m]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${m}`);if(this._allData[m]._from=o,a.opType()==="Constant"){if(a.attributesLength()!==1||!a.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(a.outputsLength()!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");s.outputs.pop(),s.executeNode=!1,this._allData[m]._from=-1,this._allData[m].tensor=Pt.fromOrtTensor(a.attributes(0).t())}}}for(let o=0;o"u")throw new Error(`unrecognized input '${d}' for node: ${a.name()}`);s.inputs.push(m),this._allData[m]._to.push(o)}}}checkIsAcyclic(){let e=new Set;this._allInputIndices.forEach(i=>{this._allData[i]._to.forEach(s=>{e.add(s)})});let r=Array.from(e),t=new Array(this._nodes.length).fill("white");for(;r.length>0;){let i=r.pop();t[i]==="gray"?t[i]="black":(r.push(i),t[i]="gray",this._nodes[i].outputs.forEach(o=>{let s=this._allData[o];if(typeof s.tensor<"u")throw new Error("node outputs should not be initialized");if(s._from!==i)throw new Error("from property of the Value object doesn't match index of Node being processed");s._to.forEach(a=>{if(t[a]==="gray")throw new Error("model graph is cyclic");t[a]==="white"&&r.push(a)})}))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0,r=new Array(this._nodes.length,0),t=0;for(let i=0;i{this._allData[o]._from=-2});this._nodes.splice(t,this._nodes.length-t);for(let i=0;i=0)o._to[s]=r[o._to[s]];else throw new Error("Trying to update a removed node")}e=0;for(let i=0;i0){let o=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(o=this._nodes[this._allData[i].from].outputs.indexOf(i+e),o!==-1&&(this._nodes[this._allData[i].from].outputs[o]=i)):(o=this._allInputIndices.indexOf(i+e),o!==-1&&(this._allInputIndices[o]=i)),this._allData[i].to.forEach(s=>{o=this._nodes[s].inputs.indexOf(i+e),o!==-1&&(this._nodes[s].inputs[o]=i)}),this._allData[i].to.length===0&&(o=this._allOutputIndices.indexOf(i+e),o!==-1&&(this._allOutputIndices[o]=i))}}}deleteNode(e){let r=this._nodes[e];if(r.outputs.length>1){for(let a=1;a0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}r.executeNode=!1;let t=r.inputs[0],i=r.outputs[0],o=this._allData[i].to;for(let a=0;a0)for(let a of o){let u=this._nodes[a].inputs.indexOf(i);if(u===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[a].inputs[u]=t,this._allData[t].to.push(a)}}removeAllDropoutNodes(){let e=0;for(let r of this._nodes){if(r.opType==="Dropout"){if(r.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(r.outputs.length!==1&&r.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(r.outputs.length===2&&this._allData[r.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(let r of this._nodes)r.opType==="Identity"&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let e of this._nodes)if(e.opType==="Conv"){let r=this._allData[e.outputs[0]]._to;if(r.length===1&&this.isActivation(this._nodes[r[0]])){let t=this._nodes[r[0]];if(t.opType==="Clip")if(t.inputs.length===1)try{e.attributes.set("activation_params","floats",[t.attributes.getFloat("min"),t.attributes.getFloat("max")])}catch{e.attributes.set("activation_params","floats",[kn,Dn])}else if(t.inputs.length>=3&&this._allData[t.inputs[1]].tensor!==void 0&&this._allData[t.inputs[2]].tensor!==void 0)e.attributes.set("activation_params","floats",[this._allData[t.inputs[1]].tensor.floatData[0],this._allData[t.inputs[2]].tensor.floatData[0]]);else continue;e.attributes.set("activation","string",t.opType),this.deleteNode(r[0])}}}}});var Fy,nI,Xa,Vy=q(()=>{"use strict";ga();Uy();no();Fy=fi(gi());it();nI=xe.experimental.fbs,Xa=class{constructor(){}load(e,r,t){let i;if(!t)try{this.loadFromOnnxFormat(e,r);return}catch(o){if(t!==void 0)throw o;i=o}try{this.loadFromOrtFormat(e,r)}catch(o){throw t!==void 0?o:new Error(`Failed to load model as ONNX format: ${i} +as ORT format: ${o}`)}}loadFromOnnxFormat(e,r){let t=Fy.onnx.ModelProto.decode(e);if(Qt.longToNumber(t.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=t.opsetImport.map(o=>({domain:o.domain,version:Qt.longToNumber(o.version)})),this._graph=Hu.from(t.graph,r)}loadFromOrtFormat(e,r){let t=new K.ByteBuffer(e),i=nI.InferenceSession.getRootAsInferenceSession(t).model();if(Qt.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let s=0;s{"use strict";Ny();Ly();cr();Vy();Za=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=ha.create(e.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(e,r,t){await this.profiler.event("session","Session.loadModel",async()=>{let i=await Fu(this.backendHint);if(this.sessionHandler=i.createSessionHandler(this.context),this._model=new Xa,typeof e=="string"){let o=e.endsWith(".ort");if(typeof process<"u"&&process.versions&&process.versions.node){let s=await(void 0)(e);this.initialize(s,o)}else{let a=await(await fetch(e)).arrayBuffer();this.initialize(new Uint8Array(a),o)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{let o=new Uint8Array(e,r||0,t||e.byteLength);this.initialize(o)}})}initialize(e,r){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let t=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,t,r),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new qa(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let r=this.normalizeAndValidateInputs(e),t=await this._executionPlan.execute(this.sessionHandler,r);return this.createOutput(t)})}normalizeAndValidateInputs(e){let r=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==r.length)throw new Error(`incorrect input array length: expected ${r.length} but got ${e.length}`)}else{if(e.size!==r.length)throw new Error(`incorrect input map size: expected ${r.length} but got ${e.size}`);let t=new Array(e.size),i=0;for(let o=0;o{"use strict";Lt();Bn();Ja=class{constructor(e){this.session=e;this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(e,r,t){let i=new Map;for(let a in e)if(Object.hasOwnProperty.call(e,a)){let u=e[a];i.set(a,new Pt(u.dims,u.type,void 0,void 0,u.data))}let o=await this.session.run(i),s={};return o.forEach((a,u)=>{s[u]=new Dt(a.type,a.data,a.dims)}),s}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}});var Hy={};Tn(Hy,{onnxjsBackend:()=>oI});var qu,oI,qy=q(()=>{"use strict";Gy();Wy();qu=class{async init(){}async createInferenceSessionHandler(e,r){let t=new Za(r);return typeof e=="string"?await t.loadModel(e):await t.loadModel(e),new Ja(t)}},oI=new qu});var Qa={};Tn(Qa,{createReadStream:()=>Ky,readFile:()=>aI,readFileSync:()=>sI});var aI,sI,Ky,es=q(()=>{aI=void 0,sI=void 0,Ky=void 0});var Ku={};Tn(Ku,{join:()=>uI});var uI,Yu=q(()=>{uI=void 0});var Zy=ht((Xy,Xu)=>{"use strict";var Yy=(()=>{var n=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(n||=__filename),function(e={}){var r=e,t,i,o=new Promise((l,c)=>{t=l,i=c});r.mountExternalData=(l,c)=>{(r.Ph||(r.Ph=new Map)).set(l,c)},r.unmountExternalData=()=>{delete r.Ph};let s=()=>{let l=(f,p,h)=>(...g)=>{let v=or,_=p?.();g=f(...g);let T=p?.();return _!==T&&(f=T,h(_),p=h=null),or!=v?Lo():g},c=f=>async(...p)=>{try{if(r.Oh)throw Error("Session already started");let h=r.Oh={gi:p[0],errors:[]},g=await f(...p);if(r.Oh!==h)throw Error("Session mismatch");r.Uh?.flush();let v=h.errors;if(0T),0<_.length)throw Error(_.join(` +`))}return g}finally{r.Oh=null}};r._OrtCreateSession=l(r._OrtCreateSession,()=>r._OrtCreateSession,f=>r._OrtCreateSession=f),r._OrtRun=c(l(r._OrtRun,()=>r._OrtRun,f=>r._OrtRun=f)),r._OrtRunWithBinding=c(l(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,f=>r._OrtRunWithBinding=f)),r._OrtBindInput=l(r._OrtBindInput,()=>r._OrtBindInput,f=>r._OrtBindInput=f),s=void 0};r.jsepInit=(l,c)=>{if(s?.(),l==="webgpu"){[r.Uh,r.Zh,r.ci,r.Vh,r.bi,r.je,r.di,r.fi,r.$h,r.ai,r.ei]=c;let f=r.Uh;r.jsepRegisterBuffer=(p,h,g,v)=>f.registerBuffer(p,h,g,v),r.jsepGetBuffer=p=>f.getBuffer(p),r.jsepCreateDownloader=(p,h,g)=>f.createDownloader(p,h,g),r.jsepOnReleaseSession=p=>{f.onReleaseSession(p)},r.jsepOnRunStart=p=>f.onRunStart(p)}};var a=Object.assign({},r),u="./this.program",d=(l,c)=>{throw c},m=typeof window=="object",b=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",x="",$,I,A;if(w){var k=(es(),Kr(Qa)),P=(Yu(),Kr(Ku));x=b?P.dirname(x)+"/":__dirname+"/",$=(l,c)=>(l=Et(l)?new URL(l):P.normalize(l),k.readFileSync(l,c?void 0:"utf8")),A=l=>(l=$(l,!0),l.buffer||(l=new Uint8Array(l)),l),I=(l,c,f,p=!0)=>{l=Et(l)?new URL(l):P.normalize(l),k.readFile(l,p?void 0:"utf8",(h,g)=>{h?f(h):c(p?g.buffer:g)})},!r.thisProgram&&1{throw process.exitCode=l,c}}else(m||b)&&(b?x=self.location.href:typeof document<"u"&&document.currentScript&&(x=document.currentScript.src),n&&(x=n),x.startsWith("blob:")?x="":x=x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1),$=l=>{var c=new XMLHttpRequest;return c.open("GET",l,!1),c.send(null),c.responseText},b&&(A=l=>{var c=new XMLHttpRequest;return c.open("GET",l,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),I=(l,c,f)=>{var p=new XMLHttpRequest;p.open("GET",l,!0),p.responseType="arraybuffer",p.onload=()=>{p.status==200||p.status==0&&p.response?c(p.response):f()},p.onerror=f,p.send(null)});var z=console.log.bind(console),U=console.error.bind(console);Object.assign(r,a),a=null;var F,Y=!1,ie,ne,le,ge,se,re,_e,Oe,he,$e,je;function Ue(){var l=F.buffer;r.HEAP8=ne=new Int8Array(l),r.HEAP16=ge=new Int16Array(l),r.HEAPU8=le=new Uint8Array(l),r.HEAPU16=se=new Uint16Array(l),r.HEAP32=re=new Int32Array(l),r.HEAPU32=_e=new Uint32Array(l),r.HEAPF32=Oe=new Float32Array(l),r.HEAPF64=je=new Float64Array(l),r.HEAP64=he=new BigInt64Array(l),r.HEAPU64=$e=new BigUint64Array(l)}var Be=[],Ae=[],Le=[],Pe=0,Tt=null,oe=null;function ve(l){throw l="Aborted("+l+")",U(l),Y=!0,ie=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),i(l),l}var He=l=>l.startsWith("data:application/octet-stream;base64,"),Et=l=>l.startsWith("file://"),wt;if(wt="ort-wasm-simd.wasm",!He(wt)){var bt=wt;wt=r.locateFile?r.locateFile(bt,x):x+bt}function Br(l){if(A)return A(l);throw"both async and sync fetching of the wasm failed"}function _t(l){if(m||b){if(typeof fetch=="function"&&!Et(l))return fetch(l,{credentials:"same-origin"}).then(c=>{if(!c.ok)throw`failed to load wasm binary file at '${l}'`;return c.arrayBuffer()}).catch(()=>Br(l));if(I)return new Promise((c,f)=>{I(l,p=>c(new Uint8Array(p)),f)})}return Promise.resolve().then(()=>Br(l))}function Ot(l,c,f){return _t(l).then(p=>WebAssembly.instantiate(p,c)).then(f,p=>{U(`failed to asynchronously prepare wasm: ${p}`),ve(p)})}function Yt(l,c){var f=wt;return typeof WebAssembly.instantiateStreaming!="function"||He(f)||Et(f)||w||typeof fetch!="function"?Ot(f,l,c):fetch(f,{credentials:"same-origin"}).then(p=>WebAssembly.instantiateStreaming(p,l).then(c,function(h){return U(`wasm streaming compile failed: ${h}`),U("falling back to ArrayBuffer instantiation"),Ot(f,l,c)}))}var Jr={1261504:(l,c,f,p)=>{if(typeof r>"u"||!r.Ph)return 1;if(l=pt(l>>>0),l.startsWith("./")&&(l=l.substring(2)),l=r.Ph.get(l),!l)return 2;if(c>>>=0,f>>>=0,c+f>l.byteLength)return 3;try{return le.set(l.subarray(c,c+f),p>>>0>>>0),0}catch{return 4}},1262005:(l,c,f)=>{f=pt(f);let p=new Uint8Array(c);p.set(le.subarray(l>>>0,l+c>>>0)),typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"?(es(),Kr(Qa)).writeFileSync(f,p):(l=new File([p],f,{type:"application/octet-stream"}),l=URL.createObjectURL(l),window.open(l,"_blank"))},1262513:()=>{r.$h()},1262544:()=>{r.ai()},1262573:()=>{r.ei()},1262598:l=>r.Zh(l),1262631:l=>r.ci(l),1262663:(l,c,f)=>{r.Vh(l,c,f,!0)},1262702:(l,c,f)=>{r.Vh(l,c,f)},1262735:l=>{r.je("Abs",l,void 0)},1262786:l=>{r.je("Neg",l,void 0)},1262837:l=>{r.je("Floor",l,void 0)},1262890:l=>{r.je("Ceil",l,void 0)},1262942:l=>{r.je("Reciprocal",l,void 0)},1263e3:l=>{r.je("Sqrt",l,void 0)},1263052:l=>{r.je("Exp",l,void 0)},1263103:l=>{r.je("Erf",l,void 0)},1263154:l=>{r.je("Sigmoid",l,void 0)},1263209:(l,c,f)=>{r.je("HardSigmoid",l,{alpha:c,beta:f})},1263288:l=>{r.je("Log",l,void 0)},1263339:l=>{r.je("Sin",l,void 0)},1263390:l=>{r.je("Cos",l,void 0)},1263441:l=>{r.je("Tan",l,void 0)},1263492:l=>{r.je("Asin",l,void 0)},1263544:l=>{r.je("Acos",l,void 0)},1263596:l=>{r.je("Atan",l,void 0)},1263648:l=>{r.je("Sinh",l,void 0)},1263700:l=>{r.je("Cosh",l,void 0)},1263752:l=>{r.je("Asinh",l,void 0)},1263805:l=>{r.je("Acosh",l,void 0)},1263858:l=>{r.je("Atanh",l,void 0)},1263911:l=>{r.je("Tanh",l,void 0)},1263963:l=>{r.je("Not",l,void 0)},1264014:(l,c,f)=>{r.je("Clip",l,{min:c,max:f})},1264083:l=>{r.je("Clip",l,void 0)},1264135:(l,c)=>{r.je("Elu",l,{alpha:c})},1264193:l=>{r.je("Relu",l,void 0)},1264245:(l,c)=>{r.je("LeakyRelu",l,{alpha:c})},1264309:(l,c)=>{r.je("ThresholdedRelu",l,{alpha:c})},1264379:(l,c)=>{r.je("Cast",l,{to:c})},1264437:l=>{r.je("Add",l,void 0)},1264488:l=>{r.je("Sub",l,void 0)},1264539:l=>{r.je("Mul",l,void 0)},1264590:l=>{r.je("Div",l,void 0)},1264641:l=>{r.je("Pow",l,void 0)},1264692:l=>{r.je("Equal",l,void 0)},1264745:l=>{r.je("Greater",l,void 0)},1264800:l=>{r.je("GreaterOrEqual",l,void 0)},1264862:l=>{r.je("Less",l,void 0)},1264914:l=>{r.je("LessOrEqual",l,void 0)},1264973:(l,c,f,p,h)=>{r.je("ReduceMean",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1265132:(l,c,f,p,h)=>{r.je("ReduceMax",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1265290:(l,c,f,p,h)=>{r.je("ReduceMin",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1265448:(l,c,f,p,h)=>{r.je("ReduceProd",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1265607:(l,c,f,p,h)=>{r.je("ReduceSum",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1265765:(l,c,f,p,h)=>{r.je("ReduceL1",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1265922:(l,c,f,p,h)=>{r.je("ReduceL2",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1266079:(l,c,f,p,h)=>{r.je("ReduceLogSum",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1266240:(l,c,f,p,h)=>{r.je("ReduceSumSquare",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1266404:(l,c,f,p,h)=>{r.je("ReduceLogSumExp",l,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1266568:l=>{r.je("Where",l,void 0)},1266621:(l,c,f)=>{r.je("Transpose",l,{perm:c?Array.from(re.subarray(c>>>0,f>>>0)):[]})},1266729:(l,c,f,p)=>{r.je("DepthToSpace",l,{blocksize:c,mode:pt(f),format:p?"NHWC":"NCHW"})},1266862:(l,c,f,p)=>{r.je("DepthToSpace",l,{blocksize:c,mode:pt(f),format:p?"NHWC":"NCHW"})},1266995:(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)=>{r.je("ConvTranspose",l,{format:T?"NHWC":"NCHW",autoPad:c,dilations:[f],group:p,kernelShape:[h],pads:[g,v],strides:[_],wIsConst:()=>!!ne[C>>>0],outputPadding:E?Array.from(re.subarray(E>>>0,R>>>0)):[],outputShape:N?Array.from(re.subarray(N>>>0,D>>>0)):[],activation:pt(V)})},1267396:(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>{r.je("ConvTranspose",l,{format:_?"NHWC":"NCHW",autoPad:c,dilations:Array.from(re.subarray(f>>>0,(f>>>0)+2>>>0)),group:p,kernelShape:Array.from(re.subarray(h>>>0,(h>>>0)+2>>>0)),pads:Array.from(re.subarray(g>>>0,(g>>>0)+4>>>0)),strides:Array.from(re.subarray(v>>>0,(v>>>0)+2>>>0)),wIsConst:()=>!!ne[T>>>0],outputPadding:C?Array.from(re.subarray(C>>>0,E>>>0)):[],outputShape:R?Array.from(re.subarray(R>>>0,N>>>0)):[],activation:pt(D)})},1267961:(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)=>{r.je("ConvTranspose",l,{format:T?"NHWC":"NCHW",autoPad:c,dilations:[f],group:p,kernelShape:[h],pads:[g,v],strides:[_],wIsConst:()=>!!ne[C>>>0],outputPadding:E?Array.from(re.subarray(E>>>0,R>>>0)):[],outputShape:N?Array.from(re.subarray(N>>>0,D>>>0)):[],activation:pt(V)})},1268362:(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>{r.je("ConvTranspose",l,{format:_?"NHWC":"NCHW",autoPad:c,dilations:Array.from(re.subarray(f>>>0,(f>>>0)+2>>>0)),group:p,kernelShape:Array.from(re.subarray(h>>>0,(h>>>0)+2>>>0)),pads:Array.from(re.subarray(g>>>0,(g>>>0)+4>>>0)),strides:Array.from(re.subarray(v>>>0,(v>>>0)+2>>>0)),wIsConst:()=>!!ne[T>>>0],outputPadding:C?Array.from(re.subarray(C>>>0,E>>>0)):[],outputShape:R?Array.from(re.subarray(R>>>0,N>>>0)):[],activation:pt(D)})},1268927:(l,c)=>{r.je("GlobalAveragePool",l,{format:c?"NHWC":"NCHW"})},1269018:(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>{r.je("AveragePool",l,{format:Q?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:p,storage_order:h,dilations:[g,v],kernel_shape:[_,T],pads:[C,E,R,N],strides:[D,V]})},1269302:(l,c)=>{r.je("GlobalAveragePool",l,{format:c?"NHWC":"NCHW"})},1269393:(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>{r.je("AveragePool",l,{format:Q?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:p,storage_order:h,dilations:[g,v],kernel_shape:[_,T],pads:[C,E,R,N],strides:[D,V]})},1269677:(l,c)=>{r.je("GlobalMaxPool",l,{format:c?"NHWC":"NCHW"})},1269764:(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>{r.je("MaxPool",l,{format:Q?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:p,storage_order:h,dilations:[g,v],kernel_shape:[_,T],pads:[C,E,R,N],strides:[D,V]})},1270044:(l,c)=>{r.je("GlobalMaxPool",l,{format:c?"NHWC":"NCHW"})},1270131:(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>{r.je("MaxPool",l,{format:Q?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:p,storage_order:h,dilations:[g,v],kernel_shape:[_,T],pads:[C,E,R,N],strides:[D,V]})},1270411:(l,c,f,p,h)=>{r.je("Gemm",l,{alpha:c,beta:f,transA:p,transB:h})},1270515:l=>{r.je("MatMul",l,void 0)},1270569:(l,c,f,p)=>{r.je("ArgMax",l,{keepDims:!!c,selectLastIndex:!!f,axis:p})},1270677:(l,c,f,p)=>{r.je("ArgMin",l,{keepDims:!!c,selectLastIndex:!!f,axis:p})},1270785:(l,c)=>{r.je("Softmax",l,{axis:c})},1270848:(l,c)=>{r.je("Concat",l,{axis:c})},1270908:(l,c,f,p,h)=>{r.je("Split",l,{axis:c,numOutputs:f,splitSizes:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1271048:l=>{r.je("Expand",l,void 0)},1271102:(l,c)=>{r.je("Gather",l,{axis:Number(c)})},1271173:(l,c)=>{r.je("GatherElements",l,{axis:Number(c)})},1271252:(l,c,f,p,h,g,v,_,T,C,E)=>{r.je("Resize",l,{antialias:c,axes:f?Array.from(re.subarray(f>>>0,p>>>0)):[],coordinateTransformMode:pt(h),cubicCoeffA:g,excludeOutside:v,extrapolationValue:_,keepAspectRatioPolicy:pt(T),mode:pt(C),nearestMode:pt(E)})},1271598:(l,c,f,p,h,g,v)=>{r.je("Slice",l,{starts:c?Array.from(re.subarray(c>>>0,f>>>0)):[],ends:p?Array.from(re.subarray(p>>>0,h>>>0)):[],axes:g?Array.from(re.subarray(g>>>0,v>>>0)):[]})},1271814:l=>{r.je("Tile",l,void 0)},1271866:(l,c,f,p)=>{r.je("LayerNormalization",l,{axis:c,epsilon:f,simplified:!!p})},1271977:(l,c,f)=>{r.je("InstanceNormalization",l,{epsilon:c,format:f?"NHWC":"NCHW"})},1272091:(l,c,f)=>{r.je("InstanceNormalization",l,{epsilon:c,format:f?"NHWC":"NCHW"})},1272205:l=>{r.je("Range",l,void 0)},1272258:(l,c)=>{r.je("Einsum",l,{equation:pt(c)})},1272339:(l,c,f,p,h)=>{r.je("Pad",l,{mode:c,value:f,pads:p?Array.from(re.subarray(p>>>0,h>>>0)):[]})},1272466:(l,c,f,p,h,g)=>{r.je("BatchNormalization",l,{epsilon:c,momentum:f,spatial:!!h,trainingMode:!!p,format:g?"NHWC":"NCHW"})},1272635:(l,c,f,p,h,g)=>{r.je("BatchNormalization",l,{epsilon:c,momentum:f,spatial:!!h,trainingMode:!!p,format:g?"NHWC":"NCHW"})},1272804:(l,c,f)=>{r.je("CumSum",l,{exclusive:Number(c),reverse:Number(f)})},1272901:(l,c,f,p,h,g,v,_,T)=>{r.je("Attention",l,{numHeads:c,isUnidirectional:f,maskFilterValue:p,scale:h,doRotary:g,qkvHiddenSizes:v?Array.from(re.subarray(Number(_)>>>0,Number(_)+v>>>0)):[],pastPresentShareBuffer:!!T})},1273173:l=>{r.je("BiasAdd",l,void 0)},1273228:l=>{r.je("BiasSplitGelu",l,void 0)},1273289:l=>{r.je("FastGelu",l,void 0)},1273345:(l,c,f,p,h,g,v,_,T,C,E,R,N)=>{r.je("Conv",l,{format:T?"NHWC":"NCHW",auto_pad:c,dilations:[f],group:p,kernel_shape:[h],pads:g?Array.from(re.subarray(g>>>0,v>>>0)):[],strides:[_],w_is_const:()=>!!ne[C>>>0],activation:pt(E),activation_params:R?Array.from(Oe.subarray(R>>>0,N>>>0)):[]})},1273715:(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>{r.je("Conv",l,{format:R?"NHWC":"NCHW",auto_pad:c,dilations:[f,p],group:h,kernel_shape:[g,v],pads:_?Array.from(re.subarray(_>>>0,T>>>0)):[],strides:[C,E],w_is_const:()=>!!ne[N>>>0],activation:pt(D),activation_params:V?Array.from(Oe.subarray(V>>>0,Q>>>0)):[]})},1274106:l=>{r.je("Gelu",l,void 0)},1274158:(l,c,f,p,h,g)=>{r.je("MatMulNBits",l,{k:c,n:f,accuracyLevel:p,bits:h,blockSize:g})},1274285:(l,c,f,p,h,g)=>{r.je("MultiHeadAttention",l,{numHeads:c,isUnidirectional:f,maskFilterValue:p,scale:h,doRotary:g})},1274444:(l,c,f,p,h)=>{r.je("RotaryEmbedding",l,{interleaved:!!c,numHeads:f,rotaryEmbeddingDim:p,scale:h})},1274583:(l,c,f)=>{r.je("SkipLayerNormalization",l,{epsilon:c,simplified:!!f})},1274685:(l,c,f)=>{r.je("SkipLayerNormalization",l,{epsilon:c,simplified:!!f})},1274787:(l,c,f,p)=>{r.je("LayerNormalization",l,{axis:c,epsilon:f,simplified:!!p})},1274898:l=>{r.di(l)},1274932:(l,c)=>r.fi(l,c,r.Oh.gi,r.Oh.errors)};function Qr(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var tr=[],pn=0,Vt=0;class Wn{constructor(c){this.Nh=c,this.Ih=c-24}}var Hn=l=>{var c=Vt;if(!c)return wn(0),0;var f=new Wn(c);_e[f.Ih+16>>>2>>>0]=c;var p=_e[f.Ih+4>>>2>>>0];if(!p)return wn(0),c;for(var h in l){var g=l[h];if(g===0||g===p)break;if(Zo(g,p,f.Ih+16))return wn(g),c}return wn(p),c},Oi=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Io=(l,c,f)=>{c>>>=0;var p=c+f;for(f=c;l[f]&&!(f>=p);)++f;if(16h?p+=String.fromCharCode(h):(h-=65536,p+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else p+=String.fromCharCode(h)}return p},pt=(l,c)=>(l>>>=0)?Io(le,l,c):"",hn=l=>{for(var c=0,f=0;f=p?c++:2047>=p?c+=2:55296<=p&&57343>=p?(c+=4,++f):c+=3}return c},ur=(l,c,f,p)=>{if(f>>>=0,!(0=v){var _=l.charCodeAt(++g);v=65536+((v&1023)<<10)|_&1023}if(127>=v){if(f>=p)break;c[f++>>>0]=v}else{if(2047>=v){if(f+1>=p)break;c[f++>>>0]=192|v>>6}else{if(65535>=v){if(f+2>=p)break;c[f++>>>0]=224|v>>12}else{if(f+3>=p)break;c[f++>>>0]=240|v>>18,c[f++>>>0]=128|v>>12&63}c[f++>>>0]=128|v>>6&63}c[f++>>>0]=128|v&63}}return c[f>>>0]=0,f-h},qn,rr=l=>{for(var c="";le[l>>>0];)c+=qn[le[l++>>>0]];return c},Kn={},Yn={},Co={},zt;function Ao(l,c,f={}){var p=c.name;if(!l)throw new zt(`type "${p}" must have a positive integer typeid pointer`);if(Yn.hasOwnProperty(l)){if(f.Xh)return;throw new zt(`Cannot register type '${p}' twice`)}Yn[l]=c,delete Co[l],Kn.hasOwnProperty(l)&&(c=Kn[l],delete Kn[l],c.forEach(h=>h()))}function nr(l,c,f={}){if(!("argPackAdvance"in c))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Ao(l,c,f)}var Re=(l,c,f)=>{switch(c){case 1:return f?p=>ne[p>>>0]:p=>le[p>>>0];case 2:return f?p=>ge[p>>>1>>>0]:p=>se[p>>>1>>>0];case 4:return f?p=>re[p>>>2>>>0]:p=>_e[p>>>2>>>0];case 8:return f?p=>he[p>>>3]:p=>$e[p>>>3];default:throw new TypeError(`invalid integer width (${c}): ${l}`)}},en=[],lr=[];function Pi(l){l>>>=0,9{if(!l)throw new zt("Cannot use deleted val. handle = "+l);return lr[l]},ir=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let c=en.pop()||lr.length;return lr[c]=l,lr[c+1]=1,c}};function Xn(l){return this.fromWireType(_e[l>>>2>>>0])}var Eo={name:"emscripten::val",fromWireType:l=>{var c=Mt(l);return Pi(l),c},toWireType:(l,c)=>ir(c),argPackAdvance:8,readValueFromPointer:Xn,Mh:null},Oo=(l,c)=>{switch(c){case 4:return function(f){return this.fromWireType(Oe[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(je[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${c}): ${l}`)}},ki=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Di=(l,c)=>{for(var f=l>>1,p=f+c/2;!(f>=p)&&se[f>>>0];)++f;if(f<<=1,32>>0,f>>>0));for(f="",p=0;!(p>=c/2);++p){var h=ge[l+2*p>>>1>>>0];if(h==0)break;f+=String.fromCharCode(h)}return f},Po=(l,c,f)=>{if(f??=2147483647,2>f)return 0;f-=2;var p=c;f=f<2*l.length?f/2:l.length;for(var h=0;h>>1>>>0]=l.charCodeAt(h),c+=2;return ge[c>>>1>>>0]=0,c-p},ko=l=>2*l.length,Do=(l,c)=>{for(var f=0,p="";!(f>=c/4);){var h=re[l+4*f>>>2>>>0];if(h==0)break;++f,65536<=h?(h-=65536,p+=String.fromCharCode(55296|h>>10,56320|h&1023)):p+=String.fromCharCode(h)}return p},Bo=(l,c,f)=>{if(c>>>=0,f??=2147483647,4>f)return 0;var p=c;f=p+f-4;for(var h=0;h=g){var v=l.charCodeAt(++h);g=65536+((g&1023)<<10)|v&1023}if(re[c>>>2>>>0]=g,c+=4,c+4>f)break}return re[c>>>2>>>0]=0,c-p},Ro=l=>{for(var c=0,f=0;f=p&&++f,c+=4}return c},Zn=(l,c)=>{var f=Yn[l];if(f===void 0)throw l=Ui(l),f=rr(l),dr(l),new zt(`${c} has unknown type ${f}`);return f},Bi=(l,c,f)=>{var p=[];return l=l.toWireType(p,f),p.length&&(_e[c>>>2>>>0]=ir(p)),l},mn=l=>{try{l()}catch(c){ve(c)}},zo=l=>{if(!Y)try{l();try{ie=ie=l=ie,r.onExit?.(l),Y=!0,d(l,new Qr(l))}catch(c){c instanceof Qr||c=="unwind"||d(1,c)}}catch(c){c instanceof Qr||c=="unwind"||d(1,c)}};function Mo(){var l=L,c={};for(let[f,p]of Object.entries(l))c[f]=typeof p=="function"?(...h)=>{gn.push(f);try{return p(...h)}finally{Y||(gn.pop(),or&&_r===1&&gn.length===0&&(_r=0,mn(df),typeof Fibers<"u"&&Fibers.mi()))}}:p;return c}var _r=0,or=null,Ri=0,gn=[],Jn={},yn={},tn=0,Qn=null,No=[];function Lo(){return new Promise((l,c)=>{Qn={resolve:l,reject:c}})}function jo(){var l=vn(65548),c=l+12;_e[l>>>2>>>0]=c,_e[l+4>>>2>>>0]=c+65536,c=gn[0];var f=Jn[c];return f===void 0&&(f=tn++,Jn[c]=f,yn[f]=c),re[l+8>>>2>>>0]=f,l}function Uo(l){if(!Y){if(_r===0){var c=!1,f=!1;l((p=0)=>{if(!Y&&(Ri=p,c=!0,f)){_r=2,mn(()=>cf(or)),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.resume(),p=!1;try{var h=(0,L[yn[re[or+8>>>2>>>0]]])()}catch(_){h=_,p=!0}var g=!1;if(!or){var v=Qn;v&&(Qn=null,(p?v.reject:v.resolve)(h),g=!0)}if(p&&!g)throw h}}),f=!0,c||(_r=1,or=jo(),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.pause(),mn(()=>lf(or)))}else _r===2?(_r=0,mn(ff),dr(or),or=null,No.forEach(zo)):ve(`invalid state: ${_r}`);return Ri}}function ei(l){return Uo(c=>{l().then(c)})}var bn=[],Ds={},lt=l=>{var c=Ds[l];return c===void 0?rr(l):c},ti=()=>typeof globalThis=="object"?globalThis:Function("return this")(),zi=l=>{var c=bn.length;return bn.push(l),c},Fo=(l,c)=>{for(var f=Array(l),p=0;p>>2>>>0],"parameter "+p);return f},ri=(l,c)=>Object.defineProperty(c,"name",{value:l});function Vo(l){var c=Function;if(!(c instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof c} which is not a function`);var f=ri(c.name||"unknownFunctionName",function(){});return f.prototype=c.prototype,f=new f,l=c.apply(f,l),l instanceof Object?l:f}var qr=l=>l%4===0&&(l%100!==0||l%400===0),Mi=[0,31,60,91,121,152,182,213,244,274,305,335],Ni=[0,31,59,90,120,151,181,212,243,273,304,334],ni=[],Go=(l,c)=>{ni.length=0;for(var f;f=le[l++>>>0];){var p=f!=105;p&=f!=112,c+=p&&c%8?4:0,ni.push(f==112?_e[c>>>2>>>0]:f==106?he[c>>>3]:f==105?re[c>>>2>>>0]:je[c>>>3>>>0]),c+=p?8:4}return ni},ii={},Li=()=>{if(!oi){var l={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:u||"./this.program"},c;for(c in ii)ii[c]===void 0?delete l[c]:l[c]=ii[c];var f=[];for(c in l)f.push(`${c}=${l[c]}`);oi=f}return oi},oi,Bs=[null,[],[]],Wo=[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 ai(l){var c=Array(hn(l)+1);return ur(l,c,0,c.length),c}function Ho(l,c,f,p){function h(D,V,Q){for(D=typeof D=="number"?D.toString():D||"";D.lengthye?-1:0ce-D.getDate())V-=ce-D.getDate()+1,D.setDate(1),11>Q?D.setMonth(Q+1):(D.setMonth(0),D.setFullYear(D.getFullYear()+1));else{D.setDate(D.getDate()+V);break}}return Q=new Date(D.getFullYear()+1,0,4),V=_(new Date(D.getFullYear(),0,4)),Q=_(Q),0>=v(V,D)?0>=v(Q,D)?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}l>>>=0,c>>>=0,f>>>=0,p>>>=0;var C=_e[p+40>>>2>>>0];p={ji:re[p>>>2>>>0],ii:re[p+4>>>2>>>0],Qh:re[p+8>>>2>>>0],Th:re[p+12>>>2>>>0],Rh:re[p+16>>>2>>>0],Lh:re[p+20>>>2>>>0],Jh:re[p+24>>>2>>>0],Kh:re[p+28>>>2>>>0],li:re[p+32>>>2>>>0],hi:re[p+36>>>2>>>0],ki:C?pt(C):""},f=pt(f),C={"%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 E in C)f=f.replace(new RegExp(E,"g"),C[E]);var R="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),N="January February March April May June July August September October November December".split(" ");C={"%a":D=>R[D.Jh].substring(0,3),"%A":D=>R[D.Jh],"%b":D=>N[D.Rh].substring(0,3),"%B":D=>N[D.Rh],"%C":D=>g((D.Lh+1900)/100|0,2),"%d":D=>g(D.Th,2),"%e":D=>h(D.Th,2," "),"%g":D=>T(D).toString().substring(2),"%G":T,"%H":D=>g(D.Qh,2),"%I":D=>(D=D.Qh,D==0?D=12:12{for(var V=0,Q=0;Q<=D.Rh-1;V+=(qr(D.Lh+1900)?Wo:ji)[Q++]);return g(D.Th+V,3)},"%m":D=>g(D.Rh+1,2),"%M":D=>g(D.ii,2),"%n":()=>` +`,"%p":D=>0<=D.Qh&&12>D.Qh?"AM":"PM","%S":D=>g(D.ji,2),"%t":()=>" ","%u":D=>D.Jh||7,"%U":D=>g(Math.floor((D.Kh+7-D.Jh)/7),2),"%V":D=>{var V=Math.floor((D.Kh+7-(D.Jh+6)%7)/7);if(2>=(D.Jh+371-D.Kh-2)%7&&V++,V)V==53&&(Q=(D.Jh+371-D.Kh)%7,Q==4||Q==3&&qr(D.Lh)||(V=1));else{V=52;var Q=(D.Jh+7-D.Kh-1)%7;(Q==4||Q==5&&qr(D.Lh%400-1))&&V++}return g(V,2)},"%w":D=>D.Jh,"%W":D=>g(Math.floor((D.Kh+7-(D.Jh+6)%7)/7),2),"%y":D=>(D.Lh+1900).toString().substring(2),"%Y":D=>D.Lh+1900,"%z":D=>{D=D.hi;var V=0<=D;return D=Math.abs(D)/60,(V?"+":"-")+("0000"+(D/60*100+D%60)).slice(-4)},"%Z":D=>D.ki,"%%":()=>"%"},f=f.replace(/%%/g,"\0\0");for(E in C)f.includes(E)&&(f=f.replace(new RegExp(E,"g"),C[E](p)));return f=f.replace(/\0\0/g,"%"),E=ai(f),E.length>c?0:(ne.set(E,l>>>0),E.length-1)}for(var xr=Array(256),Gt=0;256>Gt;++Gt)xr[Gt]=String.fromCharCode(Gt);qn=xr,zt=r.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},r.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},lr.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>lr.length/2-5-en.length;var qo={bd:function(l,c,f){return ei(async()=>{await r.bi(l,c,f)})},v:function(l){if(l=new Wn(l>>>0),ne[l.Ih+12>>>0]==0&&(ne[l.Ih+12>>>0]=1,pn--),ne[l.Ih+13>>>0]=0,tr.push(l),Xo(l.Nh),Jo(_e[l.Ih+4>>>2>>>0]))l=_e[l.Nh>>>2>>>0];else{var c=_e[l.Ih+16>>>2>>>0];l=c!==0?c:l.Nh}return l},N:()=>{G(0,0);var l=tr.pop();Yo(l.Nh),Vt=0},a:function(){return Hn([])},m:function(l){return Hn([l>>>0])},x:function(l,c){return Hn([l>>>0,c>>>0])},q:function(l,c,f){return Hn([l>>>0,c>>>0,f>>>0])},Bb:()=>{var l=tr.pop();l||ve("no exception to throw");var c=l.Nh;throw ne[l.Ih+13>>>0]==0&&(tr.push(l),ne[l.Ih+13>>>0]=1,ne[l.Ih+12>>>0]=0,pn++),Vt=c,Vt},s:function(l,c,f){l>>>=0;var p=new Wn(l);throw _e[p.Ih+16>>>2>>>0]=0,_e[p.Ih+4>>>2>>>0]=c>>>0,_e[p.Ih+8>>>2>>>0]=f>>>0,Vt=l,pn++,Vt},fb:()=>pn,g:function(l){throw Vt||=l>>>0,Vt},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(l,c,f){c=rr(c>>>0),nr(l>>>0,{name:c,fromWireType:p=>p,toWireType:function(p,h){if(typeof h!="bigint"&&typeof h!="number")throw h===null?h="null":(p=typeof h,h=p==="object"||p==="array"||p==="function"?h.toString():""+h),new TypeError(`Cannot convert "${h}" to ${this.name}`);return typeof h=="number"&&(h=BigInt(h)),h},argPackAdvance:8,readValueFromPointer:Re(c,f>>>0,c.indexOf("u")==-1),Mh:null})},Ec:function(l,c,f,p){c=rr(c>>>0),nr(l>>>0,{name:c,fromWireType:function(h){return!!h},toWireType:function(h,g){return g?f:p},argPackAdvance:8,readValueFromPointer:function(h){return this.fromWireType(le[h>>>0])},Mh:null})},Cc:function(l){return nr(l>>>0,Eo)},Vb:function(l,c,f){c=rr(c>>>0),nr(l>>>0,{name:c,fromWireType:p=>p,toWireType:(p,h)=>h,argPackAdvance:8,readValueFromPointer:Oo(c,f>>>0),Mh:null})},Aa:function(l,c,f,p,h){if(l>>>=0,f>>>=0,c=rr(c>>>0),h===-1&&(h=4294967295),h=_=>_,p===0){var g=32-8*f;h=_=>_<>>g}var v=c.includes("unsigned")?function(_,T){return T>>>0}:function(_,T){return T};nr(l,{name:c,fromWireType:h,toWireType:v,argPackAdvance:8,readValueFromPointer:Re(c,f,p!==0),Mh:null})},_:function(l,c,f){function p(g){return new h(ne.buffer,_e[g+4>>>2>>>0],_e[g>>>2>>>0])}var h=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][c];f=rr(f>>>0),nr(l>>>0,{name:f,fromWireType:p,argPackAdvance:8,readValueFromPointer:p},{Xh:!0})},Xb:function(l,c){c=rr(c>>>0);var f=c==="std::string";nr(l>>>0,{name:c,fromWireType:function(p){var h=_e[p>>>2>>>0],g=p+4;if(f)for(var v=g,_=0;_<=h;++_){var T=g+_;if(_==h||le[T>>>0]==0){if(v=pt(v,T-v),C===void 0)var C=v;else C+=String.fromCharCode(0),C+=v;v=T+1}}else{for(C=Array(h),_=0;_>>0]);C=C.join("")}return dr(p),C},toWireType:function(p,h){h instanceof ArrayBuffer&&(h=new Uint8Array(h));var g=typeof h=="string";if(!(g||h instanceof Uint8Array||h instanceof Uint8ClampedArray||h instanceof Int8Array))throw new zt("Cannot pass non-string to std::string");var v=f&&g?hn(h):h.length,_=vn(4+v+1),T=_+4;if(_e[_>>>2>>>0]=v,f&&g)ur(h,le,T,v+1);else if(g)for(g=0;g>>0]=C}else for(g=0;g>>0]=h[g];return p!==null&&p.push(dr,_),_},argPackAdvance:8,readValueFromPointer:Xn,Mh(p){dr(p)}})},Ab:function(l,c,f){if(c>>>=0,f>>>=0,f=rr(f),c===2)var p=Di,h=Po,g=ko,v=_=>se[_>>>1>>>0];else c===4&&(p=Do,h=Bo,g=Ro,v=_=>_e[_>>>2>>>0]);nr(l>>>0,{name:f,fromWireType:_=>{for(var T=_e[_>>>2>>>0],C,E=_+4,R=0;R<=T;++R){var N=_+4+R*c;(R==T||v(N)==0)&&(E=p(E,N-E),C===void 0?C=E:(C+=String.fromCharCode(0),C+=E),E=N+c)}return dr(_),C},toWireType:(_,T)=>{if(typeof T!="string")throw new zt(`Cannot pass non-string to C++ string type ${f}`);var C=g(T),E=vn(4+C+c);return _e[E>>>2>>>0]=C/c,h(T,E+4,C+c),_!==null&&_.push(dr,E),E},argPackAdvance:8,readValueFromPointer:Xn,Mh(_){dr(_)}})},Fc:function(l,c){c=rr(c>>>0),nr(l>>>0,{Yh:!0,name:c,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ad:()=>1,kd:function(l,c,f){return c>>>=0,f>>>=0,l=Mt(l>>>0),c=Zn(c,"emval::as"),Bi(c,f,l)},Cd:function(l){return l>>>=0,ei(()=>(l=Mt(l),l.then(ir)))},ud:function(l,c,f,p){return f>>>=0,p>>>=0,l=bn[l>>>0],c=Mt(c>>>0),l(null,c,f,p)},ia:function(l,c,f,p,h){return f>>>=0,p>>>=0,h>>>=0,l=bn[l>>>0],c=Mt(c>>>0),f=lt(f),l(c,c[f],p,h)},Bc:Pi,qd:function(l,c){return c>>>=0,l=Mt(l>>>0),c=Mt(c),l==c},zd:function(l){return l>>>=0,l===0?ir(ti()):(l=lt(l),ir(ti()[l]))},ha:function(l,c,f){c=Fo(l,c>>>0);var p=c.shift();l--;var h=`return function (obj, func, destructorsRef, args) { +`,g=0,v=[];f===0&&v.push("obj");for(var _=["retType"],T=[p],C=0;CE.name).join(", ")}) => ${p.name}>`,zi(ri(f,l))},yd:function(l,c){return c>>>=0,l=Mt(l>>>0),c=Mt(c),ir(l[c])},ba:function(l){l>>>=0,9>>0);for(var c=Array(l.length),f=0;f>>0))},Xa:function(){return ir({})},vd:function(l){l>>>=0;for(var c=Mt(l);c.length;){var f=c.pop();c.pop()(f)}Pi(l)},sd:function(l,c,f){c>>>=0,f>>>=0,l=Mt(l>>>0),c=Mt(c),f=Mt(f),l[c]=f},zb:function(l,c){return c>>>=0,l=Zn(l>>>0,"_emval_take_value"),l=l.readValueFromPointer(c),ir(l)},Rc:function(l,c){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),re[c>>>2>>>0]=l.getUTCSeconds(),re[c+4>>>2>>>0]=l.getUTCMinutes(),re[c+8>>>2>>>0]=l.getUTCHours(),re[c+12>>>2>>>0]=l.getUTCDate(),re[c+16>>>2>>>0]=l.getUTCMonth(),re[c+20>>>2>>>0]=l.getUTCFullYear()-1900,re[c+24>>>2>>>0]=l.getUTCDay(),re[c+28>>>2>>>0]=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Sc:function(l,c){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),re[c>>>2>>>0]=l.getSeconds(),re[c+4>>>2>>>0]=l.getMinutes(),re[c+8>>>2>>>0]=l.getHours(),re[c+12>>>2>>>0]=l.getDate(),re[c+16>>>2>>>0]=l.getMonth(),re[c+20>>>2>>>0]=l.getFullYear()-1900,re[c+24>>>2>>>0]=l.getDay(),re[c+28>>>2>>>0]=(qr(l.getFullYear())?Mi:Ni)[l.getMonth()]+l.getDate()-1|0,re[c+36>>>2>>>0]=-(60*l.getTimezoneOffset());var f=new Date(l.getFullYear(),6,1).getTimezoneOffset(),p=new Date(l.getFullYear(),0,1).getTimezoneOffset();re[c+32>>>2>>>0]=(f!=p&&l.getTimezoneOffset()==Math.min(p,f))|0},Tc:function(l){l>>>=0;var c=new Date(re[l+20>>>2>>>0]+1900,re[l+16>>>2>>>0],re[l+12>>>2>>>0],re[l+8>>>2>>>0],re[l+4>>>2>>>0],re[l>>>2>>>0],0),f=re[l+32>>>2>>>0],p=c.getTimezoneOffset(),h=new Date(c.getFullYear(),6,1).getTimezoneOffset(),g=new Date(c.getFullYear(),0,1).getTimezoneOffset(),v=Math.min(g,h);return 0>f?re[l+32>>>2>>>0]=+(h!=g&&v==p):0>>2>>>0]=c.getDay(),re[l+28>>>2>>>0]=(qr(c.getFullYear())?Mi:Ni)[c.getMonth()]+c.getDate()-1|0,re[l>>>2>>>0]=c.getSeconds(),re[l+4>>>2>>>0]=c.getMinutes(),re[l+8>>>2>>>0]=c.getHours(),re[l+12>>>2>>>0]=c.getDate(),re[l+16>>>2>>>0]=c.getMonth(),re[l+20>>>2>>>0]=c.getYear(),l=c.getTime(),BigInt(isNaN(l)?-1:l/1e3)},Pc:function(){return-52},Qc:function(){},Ic:function(l,c,f,p){f>>>=0,p>>>=0;var h=new Date().getFullYear(),g=new Date(h,0,1),v=new Date(h,6,1);h=g.getTimezoneOffset();var _=v.getTimezoneOffset();_e[l>>>0>>>2>>>0]=60*Math.max(h,_),re[c>>>0>>>2>>>0]=+(h!=_),l=T=>T.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],g=l(g),v=l(v),_{ve("")},A:function(l,c,f){return l>>>=0,c=Go(c>>>0,f>>>0),Jr[l](...c)},bc:function(l,c,f){return l>>>=0,c=Go(c>>>0,f>>>0),Jr[l](...c)},$b:()=>Date.now(),Jc:function(){return 4294901760},ga:()=>performance.now(),Hc:function(l){l>>>=0;var c=le.length;if(4294901760=f;f*=2){var p=c*(1+.2/f);p=Math.min(p,l+100663296);var h=Math;p=Math.max(l,p);e:{h=(h.min.call(h,4294901760,p+(65536-p%65536)%65536)-F.buffer.byteLength+65535)/65536;try{F.grow(h),Ue();var g=1;break e}catch{}g=void 0}if(g)return!0}return!1},Wc:function(l,c){l>>>=0,c>>>=0;var f=0;return Li().forEach((p,h)=>{var g=c+f;for(h=_e[l+4*h>>>2>>>0]=g,g=0;g>>0]=p.charCodeAt(g);ne[h>>>0]=0,f+=p.length+1}),0},Xc:function(l,c){l>>>=0,c>>>=0;var f=Li();_e[l>>>2>>>0]=f.length;var p=0;return f.forEach(h=>p+=h.length+1),_e[c>>>2>>>0]=p,0},Db:()=>52,Zb:function(){return 52},Vc:function(){return 70},Yb:function(l,c,f,p){c>>>=0,f>>>=0,p>>>=0;for(var h=0,g=0;g>>2>>>0],_=_e[c+4>>>2>>>0];c+=8;for(var T=0;T<_;T++){var C=le[v+T>>>0],E=Bs[l];C===0||C===10?((l===1?z:U)(Io(E,0)),E.length=0):E.push(C)}h+=_}return _e[p>>>2>>>0]=h,0},xb:Z_,cd:$1,ua:$2,W:f1,$:p1,ra:Jx,ta:Y_,dd:x1,ob:x2,P:Ox,z:B_,b:y_,Ub:E_,ya:O_,e:m_,kb:d1,h:h_,X:J2,i:$_,ed:w1,j:x_,t:__,r:j_,o:H_,Wa:tx,Ca:M2,ma:F_,Qb:Cx,db:Px,Ib:N2,mb:C2,kc:e1,xc:ix,hc:i1,ic:r1,ac:v1,oa:n2,yb:W_,Ba:Z2,Eb:y1,ea:i2,jc:t1,Ta:Dx,F:v_,G:gx,Gb:Q2,jd:n1,qa:y2,O:wx,V:yx,T:Rx,y:P_,Fb:u1,gc:o1,D:G2,Hb:q2,id:a1,Ua:Ex,wa:d2,lc:K2,cc:b1,Nb:e2,aa:X_,I:k_,C:lx,_a:W2,fc:s1,Q:vx,d:w_,ab:xx,n:b_,Ya:l1,va:_2,wb:ox,f:g_,yc:nx,da:X2,gb:Tx,Da:Qx,lb:A2,hb:sx,c:T_,vc:cx,od:L2,k:S_,tc:$x,l:I_,wc:ux,sc:Sx,rd:O2,p:C_,Ra:jx,tb:Lx,Qa:Ux,Kb:T2,B:U_,K:D_,S:V_,$a:j2,pc:g2,ub:_x,za:Bx,ka:A_,xa:Ax,Sb:G_,La:b2,jb:_1,Ga:D2,nc:B2,Ha:k2,Ia:E2,fd:g1,xd:Ix,Z:Kx,pa:w2,pd:z2,wd:Mx,Mb:t2,Ma:h2,Ka:v2,Tb:M_,rc:o2,Ja:S2,Na:p2,pb:r2,la:c2,Ea:zx,mc:H2,qc:u2,Jb:R2,Fa:F2,ja:hx,Ad:Q_,nd:U2,R:s2,eb:L_,Za:Y2,ec:h1,ib:ax,E:K_,M:z_,Va:rx,ld:V2,ca:ex,nb:I2,na:l2,dc:m1,Ac:N_,u:R_,L:fx,td:m2,Pb:Hx,oc:P2,Bd:J_,Ob:qx,Lb:a2,cb:kx,zc:q_,Rb:mx,Oa:f2,Y:Yx,uc:px,J:bx,gd:c1,vb:dx,sa:Zx,H:Xx,rb:Gx,Pa:Vx,Sa:Nx,sb:Fx,qb:Wx,w:function(l){return l>>>0},Dc:Ho,fa:function(l,c,f,p){return Ho(l>>>0,c>>>0,f>>>0,p>>>0)}},L=function(){function l(f){return L=f.exports,L=Mo(),L=T1(),F=L.Dd,Ue(),Ae.unshift(L.Ed),Pe--,Pe==0&&(Tt!==null&&(clearInterval(Tt),Tt=null),oe&&(f=oe,oe=null,f())),L}var c={a:qo};if(Pe++,r.instantiateWasm)try{return r.instantiateWasm(c,l)}catch(f){U(`Module.instantiateWasm callback failed with error: ${f}`),i(f)}return Yt(c,function(f){l(f.instance)}).catch(i),{}}(),Ui=l=>(Ui=L.Fd)(l);r._OrtInit=(l,c)=>(r._OrtInit=L.Gd)(l,c),r._OrtGetLastError=(l,c)=>(r._OrtGetLastError=L.Hd)(l,c),r._OrtCreateSessionOptions=(l,c,f,p,h,g,v,_,T,C)=>(r._OrtCreateSessionOptions=L.Id)(l,c,f,p,h,g,v,_,T,C),r._OrtAppendExecutionProvider=(l,c)=>(r._OrtAppendExecutionProvider=L.Jd)(l,c),r._OrtAddFreeDimensionOverride=(l,c,f)=>(r._OrtAddFreeDimensionOverride=L.Kd)(l,c,f),r._OrtAddSessionConfigEntry=(l,c,f)=>(r._OrtAddSessionConfigEntry=L.Ld)(l,c,f),r._OrtReleaseSessionOptions=l=>(r._OrtReleaseSessionOptions=L.Md)(l),r._OrtCreateSession=(l,c,f)=>(r._OrtCreateSession=L.Nd)(l,c,f),r._OrtReleaseSession=l=>(r._OrtReleaseSession=L.Od)(l),r._OrtGetInputOutputCount=(l,c,f)=>(r._OrtGetInputOutputCount=L.Pd)(l,c,f),r._OrtGetInputName=(l,c)=>(r._OrtGetInputName=L.Qd)(l,c),r._OrtGetOutputName=(l,c)=>(r._OrtGetOutputName=L.Rd)(l,c),r._OrtFree=l=>(r._OrtFree=L.Sd)(l),r._OrtCreateTensor=(l,c,f,p,h,g)=>(r._OrtCreateTensor=L.Td)(l,c,f,p,h,g),r._OrtGetTensorData=(l,c,f,p,h)=>(r._OrtGetTensorData=L.Ud)(l,c,f,p,h),r._OrtReleaseTensor=l=>(r._OrtReleaseTensor=L.Vd)(l),r._OrtCreateRunOptions=(l,c,f,p)=>(r._OrtCreateRunOptions=L.Wd)(l,c,f,p),r._OrtAddRunConfigEntry=(l,c,f)=>(r._OrtAddRunConfigEntry=L.Xd)(l,c,f),r._OrtReleaseRunOptions=l=>(r._OrtReleaseRunOptions=L.Yd)(l),r._OrtCreateBinding=l=>(r._OrtCreateBinding=L.Zd)(l),r._OrtBindInput=(l,c,f)=>(r._OrtBindInput=L._d)(l,c,f),r._OrtBindOutput=(l,c,f,p)=>(r._OrtBindOutput=L.$d)(l,c,f,p),r._OrtClearBoundOutputs=l=>(r._OrtClearBoundOutputs=L.ae)(l),r._OrtReleaseBinding=l=>(r._OrtReleaseBinding=L.be)(l),r._OrtRunWithBinding=(l,c,f,p,h)=>(r._OrtRunWithBinding=L.ce)(l,c,f,p,h),r._OrtRun=(l,c,f,p,h,g,v,_)=>(r._OrtRun=L.de)(l,c,f,p,h,g,v,_),r._OrtEndProfiling=l=>(r._OrtEndProfiling=L.ee)(l),r._JsepOutput=(l,c,f)=>(r._JsepOutput=L.fe)(l,c,f),r._JsepGetNodeName=l=>(r._JsepGetNodeName=L.ge)(l);var vn=r._malloc=l=>(vn=r._malloc=L.he)(l),dr=r._free=l=>(dr=r._free=L.ie)(l),G=(l,c)=>(G=L.ke)(l,c),wn=l=>(wn=L.le)(l),W=l=>(W=L.me)(l),Ko=l=>(Ko=L.ne)(l),H=()=>(H=L.oe)(),Yo=l=>(Yo=L.pe)(l),Xo=l=>(Xo=L.qe)(l),Zo=(l,c,f)=>(Zo=L.re)(l,c,f),Jo=l=>(Jo=L.se)(l),_n=r.dynCall_vii=(l,c,f)=>(_n=r.dynCall_vii=L.te)(l,c,f),si=r.dynCall_iiii=(l,c,f,p)=>(si=r.dynCall_iiii=L.ue)(l,c,f,p),Fi=r.dynCall_iii=(l,c,f)=>(Fi=r.dynCall_iii=L.ve)(l,c,f),Vi=r.dynCall_ii=(l,c)=>(Vi=r.dynCall_ii=L.we)(l,c),Gi=r.dynCall_iiiiiii=(l,c,f,p,h,g,v)=>(Gi=r.dynCall_iiiiiii=L.xe)(l,c,f,p,h,g,v),ui=r.dynCall_vi=(l,c)=>(ui=r.dynCall_vi=L.ye)(l,c),li=r.dynCall_v=l=>(li=r.dynCall_v=L.ze)(l),Wi=r.dynCall_iiiiii=(l,c,f,p,h,g)=>(Wi=r.dynCall_iiiiii=L.Ae)(l,c,f,p,h,g),Hi=r.dynCall_iiij=(l,c,f,p)=>(Hi=r.dynCall_iiij=L.Be)(l,c,f,p),qi=r.dynCall_iiiii=(l,c,f,p,h)=>(qi=r.dynCall_iiiii=L.Ce)(l,c,f,p,h),di=r.dynCall_viii=(l,c,f,p)=>(di=r.dynCall_viii=L.De)(l,c,f,p),xn=r.dynCall_viiiii=(l,c,f,p,h,g)=>(xn=r.dynCall_viiiii=L.Ee)(l,c,f,p,h,g),ci=r.dynCall_viiii=(l,c,f,p,h)=>(ci=r.dynCall_viiii=L.Fe)(l,c,f,p,h),Ki=r.dynCall_viiiiii=(l,c,f,p,h,g,v)=>(Ki=r.dynCall_viiiiii=L.Ge)(l,c,f,p,h,g,v),Yi=r.dynCall_viiji=(l,c,f,p,h)=>(Yi=r.dynCall_viiji=L.He)(l,c,f,p,h),Xi=r.dynCall_viiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R)=>(Xi=r.dynCall_viiiiiiiiiii=L.Ie)(l,c,f,p,h,g,v,_,T,C,E,R),Zi=r.dynCall_viiijjjii=(l,c,f,p,h,g,v,_,T)=>(Zi=r.dynCall_viiijjjii=L.Je)(l,c,f,p,h,g,v,_,T),Ji=r.dynCall_iid=(l,c,f)=>(Ji=r.dynCall_iid=L.Ke)(l,c,f),Qo=r.dynCall_iif=(l,c,f)=>(Qo=r.dynCall_iif=L.Le)(l,c,f),$n=r.dynCall_iij=(l,c,f)=>($n=r.dynCall_iij=L.Me)(l,c,f),Qi=r.dynCall_jii=(l,c,f)=>(Qi=r.dynCall_jii=L.Ne)(l,c,f),y=r.dynCall_i=l=>(y=r.dynCall_i=L.Oe)(l),S=r.dynCall_viiiiiiii=(l,c,f,p,h,g,v,_,T)=>(S=r.dynCall_viiiiiiii=L.Pe)(l,c,f,p,h,g,v,_,T),O=r.dynCall_viiiiij=(l,c,f,p,h,g,v)=>(O=r.dynCall_viiiiij=L.Qe)(l,c,f,p,h,g,v),M=r.dynCall_ji=(l,c)=>(M=r.dynCall_ji=L.Re)(l,c),X=r.dynCall_viij=(l,c,f,p)=>(X=r.dynCall_viij=L.Se)(l,c,f,p),te=r.dynCall_iiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R)=>(te=r.dynCall_iiiiiiiiiiii=L.Te)(l,c,f,p,h,g,v,_,T,C,E,R),ae=r.dynCall_viiiiiiiii=(l,c,f,p,h,g,v,_,T,C)=>(ae=r.dynCall_viiiiiiiii=L.Ue)(l,c,f,p,h,g,v,_,T,C),Ce=r.dynCall_ij=(l,c)=>(Ce=r.dynCall_ij=L.Ve)(l,c),Te=r.dynCall_iiiiij=(l,c,f,p,h,g)=>(Te=r.dynCall_iiiiij=L.We)(l,c,f,p,h,g),we=r.dynCall_j=l=>(we=r.dynCall_j=L.Xe)(l),Ee=r.dynCall_vij=(l,c,f)=>(Ee=r.dynCall_vij=L.Ye)(l,c,f),Xe=r.dynCall_viijjjiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R)=>(Xe=r.dynCall_viijjjiiiiii=L.Ze)(l,c,f,p,h,g,v,_,T,C,E,R),Qe=r.dynCall_viiijiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R)=>(Qe=r.dynCall_viiijiiiiiii=L._e)(l,c,f,p,h,g,v,_,T,C,E,R),Z=r.dynCall_iiiiiiii=(l,c,f,p,h,g,v,_)=>(Z=r.dynCall_iiiiiiii=L.$e)(l,c,f,p,h,g,v,_),Me=r.dynCall_viiiiiii=(l,c,f,p,h,g,v,_)=>(Me=r.dynCall_viiiiiii=L.af)(l,c,f,p,h,g,v,_),et=r.dynCall_iiiiiiiij=(l,c,f,p,h,g,v,_,T)=>(et=r.dynCall_iiiiiiiij=L.bf)(l,c,f,p,h,g,v,_,T),Rr=r.dynCall_viiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>(Rr=r.dynCall_viiiiiiiiiiiii=L.cf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D),eo=r.dynCall_iiiiiiiii=(l,c,f,p,h,g,v,_,T)=>(eo=r.dynCall_iiiiiiiii=L.df)(l,c,f,p,h,g,v,_,T),Ml=r.dynCall_iiiiijiiiii=(l,c,f,p,h,g,v,_,T,C,E)=>(Ml=r.dynCall_iiiiijiiiii=L.ef)(l,c,f,p,h,g,v,_,T,C,E),Nl=r.dynCall_vijjjiiij=(l,c,f,p,h,g,v,_,T)=>(Nl=r.dynCall_vijjjiiij=L.ff)(l,c,f,p,h,g,v,_,T),Ll=r.dynCall_fi=(l,c)=>(Ll=r.dynCall_fi=L.gf)(l,c),jl=r.dynCall_fii=(l,c,f)=>(jl=r.dynCall_fii=L.hf)(l,c,f),Ul=r.dynCall_di=(l,c)=>(Ul=r.dynCall_di=L.jf)(l,c),Fl=r.dynCall_dii=(l,c,f)=>(Fl=r.dynCall_dii=L.kf)(l,c,f),Vl=r.dynCall_vijj=(l,c,f,p)=>(Vl=r.dynCall_vijj=L.lf)(l,c,f,p),Gl=r.dynCall_iiiiiiiiii=(l,c,f,p,h,g,v,_,T,C)=>(Gl=r.dynCall_iiiiiiiiii=L.mf)(l,c,f,p,h,g,v,_,T,C),Wl=r.dynCall_viijiii=(l,c,f,p,h,g,v)=>(Wl=r.dynCall_viijiii=L.nf)(l,c,f,p,h,g,v),Hl=r.dynCall_viid=(l,c,f,p)=>(Hl=r.dynCall_viid=L.of)(l,c,f,p),ql=r.dynCall_viffiii=(l,c,f,p,h,g,v)=>(ql=r.dynCall_viffiii=L.pf)(l,c,f,p,h,g,v),Kl=r.dynCall_viifiii=(l,c,f,p,h,g,v)=>(Kl=r.dynCall_viifiii=L.qf)(l,c,f,p,h,g,v),Yl=r.dynCall_viiiiidiidi=(l,c,f,p,h,g,v,_,T,C,E)=>(Yl=r.dynCall_viiiiidiidi=L.rf)(l,c,f,p,h,g,v,_,T,C,E),Xl=r.dynCall_viiiiiiiiidi=(l,c,f,p,h,g,v,_,T,C,E,R)=>(Xl=r.dynCall_viiiiiiiiidi=L.sf)(l,c,f,p,h,g,v,_,T,C,E,R),Zl=r.dynCall_jiii=(l,c,f,p)=>(Zl=r.dynCall_jiii=L.tf)(l,c,f,p),Jl=r.dynCall_vjiiiiii=(l,c,f,p,h,g,v,_)=>(Jl=r.dynCall_vjiiiiii=L.uf)(l,c,f,p,h,g,v,_),Ql=r.dynCall_viiid=(l,c,f,p,h)=>(Ql=r.dynCall_viiid=L.vf)(l,c,f,p,h),ed=r.dynCall_viiiiiiiiiji=(l,c,f,p,h,g,v,_,T,C,E,R)=>(ed=r.dynCall_viiiiiiiiiji=L.wf)(l,c,f,p,h,g,v,_,T,C,E,R),td=r.dynCall_viji=(l,c,f,p)=>(td=r.dynCall_viji=L.xf)(l,c,f,p),rd=r.dynCall_vijjjjjjjjjjjjji=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>(rd=r.dynCall_vijjjjjjjjjjjjji=L.yf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q),nd=r.dynCall_viiiji=(l,c,f,p,h,g)=>(nd=r.dynCall_viiiji=L.zf)(l,c,f,p,h,g),id=r.dynCall_vijjjiiji=(l,c,f,p,h,g,v,_,T)=>(id=r.dynCall_vijjjiiji=L.Af)(l,c,f,p,h,g,v,_,T),od=r.dynCall_iiiji=(l,c,f,p,h)=>(od=r.dynCall_iiiji=L.Bf)(l,c,f,p,h),ad=r.dynCall_iiijiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>(ad=r.dynCall_iiijiiiiiiiiii=L.Cf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D),sd=r.dynCall_vj=(l,c)=>(sd=r.dynCall_vj=L.Df)(l,c),ud=r.dynCall_jjj=(l,c,f)=>(ud=r.dynCall_jjj=L.Ef)(l,c,f),ld=r.dynCall_iiijiiiiii=(l,c,f,p,h,g,v,_,T,C)=>(ld=r.dynCall_iiijiiiiii=L.Ff)(l,c,f,p,h,g,v,_,T,C),dd=r.dynCall_vfiii=(l,c,f,p,h)=>(dd=r.dynCall_vfiii=L.Gf)(l,c,f,p,h),cd=r.dynCall_viiiiff=(l,c,f,p,h,g,v)=>(cd=r.dynCall_viiiiff=L.Hf)(l,c,f,p,h,g,v),fd=r.dynCall_viiiiiff=(l,c,f,p,h,g,v,_)=>(fd=r.dynCall_viiiiiff=L.If)(l,c,f,p,h,g,v,_),pd=r.dynCall_viiff=(l,c,f,p,h)=>(pd=r.dynCall_viiff=L.Jf)(l,c,f,p,h),hd=r.dynCall_viiiiiiiiifiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>(hd=r.dynCall_viiiiiiiiifiii=L.Kf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D),md=r.dynCall_viiiiiiiijj=(l,c,f,p,h,g,v,_,T,C,E)=>(md=r.dynCall_viiiiiiiijj=L.Lf)(l,c,f,p,h,g,v,_,T,C,E),gd=r.dynCall_iiiiiiiiiiiiiifii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce)=>(gd=r.dynCall_iiiiiiiiiiiiiifii=L.Mf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce),yd=r.dynCall_viiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(yd=r.dynCall_viiiiiiiiiiii=L.Nf)(l,c,f,p,h,g,v,_,T,C,E,R,N),bd=r.dynCall_iiiiiiiiiiiiiiiiifii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye)=>(bd=r.dynCall_iiiiiiiiiiiiiiiiifii=L.Of)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye),vd=r.dynCall_vijjiiiiii=(l,c,f,p,h,g,v,_,T,C)=>(vd=r.dynCall_vijjiiiiii=L.Pf)(l,c,f,p,h,g,v,_,T,C),wd=r.dynCall_iiiijjj=(l,c,f,p,h,g,v)=>(wd=r.dynCall_iiiijjj=L.Qf)(l,c,f,p,h,g,v),_d=r.dynCall_viiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E)=>(_d=r.dynCall_viiiiiiiiii=L.Rf)(l,c,f,p,h,g,v,_,T,C,E),xd=r.dynCall_iiijjj=(l,c,f,p,h,g)=>(xd=r.dynCall_iiijjj=L.Sf)(l,c,f,p,h,g),$d=r.dynCall_fffffff=(l,c,f,p,h,g,v)=>($d=r.dynCall_fffffff=L.Tf)(l,c,f,p,h,g,v),Td=r.dynCall_viiiij=(l,c,f,p,h,g)=>(Td=r.dynCall_viiiij=L.Uf)(l,c,f,p,h,g),Sd=r.dynCall_viiiiiijiifiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>(Sd=r.dynCall_viiiiiijiifiii=L.Vf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D),Id=r.dynCall_vjjjjjjffjifiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye)=>(Id=r.dynCall_vjjjjjjffjifiiiiii=L.Wf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye),Cd=r.dynCall_viiiiiiffjifiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce)=>(Cd=r.dynCall_viiiiiiffjifiiiii=L.Xf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce),Ad=r.dynCall_viiiiiiffjfiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>(Ad=r.dynCall_viiiiiiffjfiiiii=L.Yf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q),Ed=r.dynCall_viiiiiiffjiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)=>(Ed=r.dynCall_viiiiiiffjiiiii=L.Zf)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V),Od=r.dynCall_vjjjjjjjjfffiiifiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st)=>(Od=r.dynCall_vjjjjjjjjfffiiifiiiii=L._f)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st),Pd=r.dynCall_vjjjjjjfffifijiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke)=>(Pd=r.dynCall_vjjjjjjfffifijiiiii=L.$f)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke),kd=r.dynCall_vjjjjjjfffifiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye)=>(kd=r.dynCall_vjjjjjjfffifiiiiii=L.ag)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye),Dd=r.dynCall_vjjjjjjjjfffjifiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st)=>(Dd=r.dynCall_vjjjjjjjjfffjifiiiiii=L.bg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st),Bd=r.dynCall_vijiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(Bd=r.dynCall_vijiiiiiiiiii=L.cg)(l,c,f,p,h,g,v,_,T,C,E,R,N),Rd=r.dynCall_vijjfffiii=(l,c,f,p,h,g,v,_,T,C)=>(Rd=r.dynCall_vijjfffiii=L.dg)(l,c,f,p,h,g,v,_,T,C),zd=r.dynCall_viiiiiiijiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(zd=r.dynCall_viiiiiiijiiii=L.eg)(l,c,f,p,h,g,v,_,T,C,E,R,N),Md=r.dynCall_vijjjjjjifiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)=>(Md=r.dynCall_vijjjjjjifiiiii=L.fg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V),Nd=r.dynCall_viifi=(l,c,f,p,h)=>(Nd=r.dynCall_viifi=L.gg)(l,c,f,p,h),Ld=r.dynCall_vjjjjjiiii=(l,c,f,p,h,g,v,_,T,C)=>(Ld=r.dynCall_vjjjjjiiii=L.hg)(l,c,f,p,h,g,v,_,T,C),jd=r.dynCall_vjjjjfiii=(l,c,f,p,h,g,v,_,T)=>(jd=r.dynCall_vjjjjfiii=L.ig)(l,c,f,p,h,g,v,_,T),Ud=r.dynCall_viiiiiijiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>(Ud=r.dynCall_viiiiiijiiiiii=L.jg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D),Fd=r.dynCall_vijjii=(l,c,f,p,h,g)=>(Fd=r.dynCall_vijjii=L.kg)(l,c,f,p,h,g),Vd=r.dynCall_viiiiijjiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(Vd=r.dynCall_viiiiijjiiiii=L.lg)(l,c,f,p,h,g,v,_,T,C,E,R,N),Gd=r.dynCall_iiiiiji=(l,c,f,p,h,g,v)=>(Gd=r.dynCall_iiiiiji=L.mg)(l,c,f,p,h,g,v),Wd=r.dynCall_iiiiji=(l,c,f,p,h,g)=>(Wd=r.dynCall_iiiiji=L.ng)(l,c,f,p,h,g),Hd=r.dynCall_viiiiijiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(Hd=r.dynCall_viiiiijiiiiii=L.og)(l,c,f,p,h,g,v,_,T,C,E,R,N),qd=r.dynCall_viiijiiiiii=(l,c,f,p,h,g,v,_,T,C,E)=>(qd=r.dynCall_viiijiiiiii=L.pg)(l,c,f,p,h,g,v,_,T,C,E),Kd=r.dynCall_viijj=(l,c,f,p,h)=>(Kd=r.dynCall_viijj=L.qg)(l,c,f,p,h),Yd=r.dynCall_viiiijii=(l,c,f,p,h,g,v,_)=>(Yd=r.dynCall_viiiijii=L.rg)(l,c,f,p,h,g,v,_),Xd=r.dynCall_viijjiii=(l,c,f,p,h,g,v,_)=>(Xd=r.dynCall_viijjiii=L.sg)(l,c,f,p,h,g,v,_),Zd=r.dynCall_ijii=(l,c,f,p)=>(Zd=r.dynCall_ijii=L.tg)(l,c,f,p),Jd=r.dynCall_viiiiijjji=(l,c,f,p,h,g,v,_,T,C)=>(Jd=r.dynCall_viiiiijjji=L.ug)(l,c,f,p,h,g,v,_,T,C),Qd=r.dynCall_vijjjjiij=(l,c,f,p,h,g,v,_,T)=>(Qd=r.dynCall_vijjjjiij=L.vg)(l,c,f,p,h,g,v,_,T),ec=r.dynCall_viiiiijij=(l,c,f,p,h,g,v,_,T)=>(ec=r.dynCall_viiiiijij=L.wg)(l,c,f,p,h,g,v,_,T),tc=r.dynCall_viiiiiijij=(l,c,f,p,h,g,v,_,T,C)=>(tc=r.dynCall_viiiiiijij=L.xg)(l,c,f,p,h,g,v,_,T,C),rc=r.dynCall_vijiii=(l,c,f,p,h,g)=>(rc=r.dynCall_vijiii=L.yg)(l,c,f,p,h,g),nc=r.dynCall_viiiiiiiiifi=(l,c,f,p,h,g,v,_,T,C,E,R)=>(nc=r.dynCall_viiiiiiiiifi=L.zg)(l,c,f,p,h,g,v,_,T,C,E,R),ic=r.dynCall_iiijiiii=(l,c,f,p,h,g,v,_)=>(ic=r.dynCall_iiijiiii=L.Ag)(l,c,f,p,h,g,v,_),oc=r.dynCall_viiiiiijjiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>(oc=r.dynCall_viiiiiijjiiiii=L.Bg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D),ac=r.dynCall_viiiiiiijiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)=>(ac=r.dynCall_viiiiiiijiiiiii=L.Cg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V),sc=r.dynCall_vif=(l,c,f)=>(sc=r.dynCall_vif=L.Dg)(l,c,f),uc=r.dynCall_viif=(l,c,f,p)=>(uc=r.dynCall_viif=L.Eg)(l,c,f,p),lc=r.dynCall_fiii=(l,c,f,p)=>(lc=r.dynCall_fiii=L.Fg)(l,c,f,p),dc=r.dynCall_diii=(l,c,f,p)=>(dc=r.dynCall_diii=L.Gg)(l,c,f,p),cc=r.dynCall_viiiiiifii=(l,c,f,p,h,g,v,_,T,C)=>(cc=r.dynCall_viiiiiifii=L.Hg)(l,c,f,p,h,g,v,_,T,C),fc=r.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st,St,Wt,Rs,zs,Ms)=>(fc=r.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=L.Ig)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st,St,Wt,Rs,zs,Ms),pc=r.dynCall_viijji=(l,c,f,p,h,g)=>(pc=r.dynCall_viijji=L.Jg)(l,c,f,p,h,g),hc=r.dynCall_iiiiiiiiiiiji=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(hc=r.dynCall_iiiiiiiiiiiji=L.Kg)(l,c,f,p,h,g,v,_,T,C,E,R,N),mc=r.dynCall_viifiifijjjii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(mc=r.dynCall_viifiifijjjii=L.Lg)(l,c,f,p,h,g,v,_,T,C,E,R,N),gc=r.dynCall_viiiiiiiiiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st)=>(gc=r.dynCall_viiiiiiiiiiiiiiiiiiii=L.Mg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st),yc=r.dynCall_viiiiifiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(yc=r.dynCall_viiiiifiiiiii=L.Ng)(l,c,f,p,h,g,v,_,T,C,E,R,N),bc=r.dynCall_vijiiiiiiijjii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D)=>(bc=r.dynCall_vijiiiiiiijjii=L.Og)(l,c,f,p,h,g,v,_,T,C,E,R,N,D),vc=r.dynCall_viiiiiiiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke)=>(vc=r.dynCall_viiiiiiiiiiiiiiiiii=L.Pg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke),wc=r.dynCall_viiiiiiiiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye)=>(wc=r.dynCall_viiiiiiiiiiiiiiiiiii=L.Qg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye),_c=r.dynCall_viiiiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)=>(_c=r.dynCall_viiiiiiiiiiiiiii=L.Rg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q),xc=r.dynCall_viiiiiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce)=>(xc=r.dynCall_viiiiiiiiiiiiiiii=L.Sg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce),$c=r.dynCall_viiiijjj=(l,c,f,p,h,g,v,_)=>($c=r.dynCall_viiiijjj=L.Tg)(l,c,f,p,h,g,v,_),Tc=r.dynCall_iiiiid=(l,c,f,p,h,g)=>(Tc=r.dynCall_iiiiid=L.Ug)(l,c,f,p,h,g),Sc=r.dynCall_viiiiiiijjj=(l,c,f,p,h,g,v,_,T,C,E)=>(Sc=r.dynCall_viiiiiiijjj=L.Vg)(l,c,f,p,h,g,v,_,T,C,E),Ic=r.dynCall_iiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E)=>(Ic=r.dynCall_iiiiiiiiiii=L.Wg)(l,c,f,p,h,g,v,_,T,C,E),Cc=r.dynCall_iiiiiiiiiiiiiiiiiifi=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye)=>(Cc=r.dynCall_iiiiiiiiiiiiiiiiiifi=L.Xg)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye),Ac=r.dynCall_viiif=(l,c,f,p,h)=>(Ac=r.dynCall_viiif=L.Yg)(l,c,f,p,h),Ec=r.dynCall_viiijiiiii=(l,c,f,p,h,g,v,_,T,C)=>(Ec=r.dynCall_viiijiiiii=L.Zg)(l,c,f,p,h,g,v,_,T,C),Oc=r.dynCall_viiij=(l,c,f,p,h)=>(Oc=r.dynCall_viiij=L._g)(l,c,f,p,h),Pc=r.dynCall_iijjj=(l,c,f,p,h)=>(Pc=r.dynCall_iijjj=L.$g)(l,c,f,p,h),kc=r.dynCall_viiiiji=(l,c,f,p,h,g,v)=>(kc=r.dynCall_viiiiji=L.ah)(l,c,f,p,h,g,v),Dc=r.dynCall_iijjji=(l,c,f,p,h,g)=>(Dc=r.dynCall_iijjji=L.bh)(l,c,f,p,h,g),Bc=r.dynCall_ijijji=(l,c,f,p,h,g)=>(Bc=r.dynCall_ijijji=L.ch)(l,c,f,p,h,g),Rc=r.dynCall_viiijjiii=(l,c,f,p,h,g,v,_,T)=>(Rc=r.dynCall_viiijjiii=L.dh)(l,c,f,p,h,g,v,_,T),zc=r.dynCall_iiiiijji=(l,c,f,p,h,g,v,_)=>(zc=r.dynCall_iiiiijji=L.eh)(l,c,f,p,h,g,v,_),Mc=r.dynCall_iiiifi=(l,c,f,p,h,g)=>(Mc=r.dynCall_iiiifi=L.fh)(l,c,f,p,h,g),Nc=r.dynCall_iiijii=(l,c,f,p,h,g)=>(Nc=r.dynCall_iiijii=L.gh)(l,c,f,p,h,g),Lc=r.dynCall_iiiiiiiiijii=(l,c,f,p,h,g,v,_,T,C,E,R)=>(Lc=r.dynCall_iiiiiiiiijii=L.hh)(l,c,f,p,h,g,v,_,T,C,E,R),jc=r.dynCall_iiiijjii=(l,c,f,p,h,g,v,_)=>(jc=r.dynCall_iiiijjii=L.ih)(l,c,f,p,h,g,v,_),Uc=r.dynCall_iiiiiijjjii=(l,c,f,p,h,g,v,_,T,C,E)=>(Uc=r.dynCall_iiiiiijjjii=L.jh)(l,c,f,p,h,g,v,_,T,C,E),Fc=r.dynCall_iiijiii=(l,c,f,p,h,g,v)=>(Fc=r.dynCall_iiijiii=L.kh)(l,c,f,p,h,g,v),Vc=r.dynCall_iiiiiiiijjjfi=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(Vc=r.dynCall_iiiiiiiijjjfi=L.lh)(l,c,f,p,h,g,v,_,T,C,E,R,N),Gc=r.dynCall_iijiiii=(l,c,f,p,h,g,v)=>(Gc=r.dynCall_iijiiii=L.mh)(l,c,f,p,h,g,v),Wc=r.dynCall_iijjjii=(l,c,f,p,h,g,v)=>(Wc=r.dynCall_iijjjii=L.nh)(l,c,f,p,h,g,v),Hc=r.dynCall_jij=(l,c,f)=>(Hc=r.dynCall_jij=L.oh)(l,c,f),qc=r.dynCall_iiji=(l,c,f,p)=>(qc=r.dynCall_iiji=L.ph)(l,c,f,p),Kc=r.dynCall_iiif=(l,c,f,p)=>(Kc=r.dynCall_iiif=L.qh)(l,c,f,p),Yc=r.dynCall_vidi=(l,c,f,p)=>(Yc=r.dynCall_vidi=L.rh)(l,c,f,p),Xc=r.dynCall_vjiii=(l,c,f,p,h)=>(Xc=r.dynCall_vjiii=L.sh)(l,c,f,p,h),Zc=r.dynCall_diiii=(l,c,f,p,h)=>(Zc=r.dynCall_diiii=L.th)(l,c,f,p,h),Jc=r.dynCall_diiiii=(l,c,f,p,h,g)=>(Jc=r.dynCall_diiiii=L.uh)(l,c,f,p,h,g),Qc=r.dynCall_viiijjiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R)=>(Qc=r.dynCall_viiijjiiiiii=L.vh)(l,c,f,p,h,g,v,_,T,C,E,R),ef=r.dynCall_viijjijjjjiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(ef=r.dynCall_viijjijjjjiii=L.wh)(l,c,f,p,h,g,v,_,T,C,E,R,N),tf=r.dynCall_iiiij=(l,c,f,p,h)=>(tf=r.dynCall_iiiij=L.xh)(l,c,f,p,h),rf=r.dynCall_viiijii=(l,c,f,p,h,g,v)=>(rf=r.dynCall_viiijii=L.yh)(l,c,f,p,h,g,v),nf=r.dynCall_viijiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N)=>(nf=r.dynCall_viijiiiiiiiii=L.zh)(l,c,f,p,h,g,v,_,T,C,E,R,N),of=r.dynCall_fiiii=(l,c,f,p,h)=>(of=r.dynCall_fiiii=L.Ah)(l,c,f,p,h),af=r.dynCall_jfi=(l,c,f)=>(af=r.dynCall_jfi=L.Bh)(l,c,f),sf=r.dynCall_viiiiiiiiiiiiii=(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)=>(sf=r.dynCall_viiiiiiiiiiiiii=L.Ch)(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V),uf=r.dynCall_jiij=(l,c,f,p)=>(uf=r.dynCall_jiij=L.Dh)(l,c,f,p),lf=l=>(lf=L.Eh)(l),df=()=>(df=L.Fh)(),cf=l=>(cf=L.Gh)(l),ff=()=>(ff=L.Hh)();r.___start_em_js=1275044,r.___stop_em_js=1275205;function h_(l,c,f,p){var h=H();try{return si(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function m_(l,c,f){var p=H();try{return Fi(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function g_(l,c,f){var p=H();try{_n(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function y_(l,c){var f=H();try{return Vi(l,c)}catch(p){if(W(f),p!==p+0)throw p;G(1,0)}}function b_(l,c){var f=H();try{ui(l,c)}catch(p){if(W(f),p!==p+0)throw p;G(1,0)}}function v_(l,c,f,p){var h=H();try{return Hi(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function w_(l){var c=H();try{li(l)}catch(f){if(W(c),f!==f+0)throw f;G(1,0)}}function __(l,c,f,p,h,g,v){var _=H();try{return Gi(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function x_(l,c,f,p,h,g){var v=H();try{return Wi(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function $_(l,c,f,p,h){var g=H();try{return qi(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function T_(l,c,f,p){var h=H();try{di(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function S_(l,c,f,p,h){var g=H();try{ci(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function I_(l,c,f,p,h,g){var v=H();try{xn(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function C_(l,c,f,p,h,g,v){var _=H();try{Ki(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function A_(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{Xi(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function E_(l,c,f){var p=H();try{return Ji(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function O_(l,c,f){var p=H();try{return Qo(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function P_(l,c,f){var p=H();try{return $n(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function k_(l,c,f){var p=H();try{return Qi(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;return G(1,0),0n}}function D_(l,c,f,p,h,g,v,_,T){var C=H();try{S(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function B_(l){var c=H();try{return y(l)}catch(f){if(W(c),f!==f+0)throw f;G(1,0)}}function R_(l,c,f){var p=H();try{Ee(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function z_(l,c,f,p,h){var g=H();try{Yi(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function M_(l,c,f,p,h,g,v){var _=H();try{O(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function N_(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{Xe(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function L_(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{Qe(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function j_(l,c,f,p,h,g,v,_){var T=H();try{return Z(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function U_(l,c,f,p,h,g,v,_){var T=H();try{Me(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function F_(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{return te(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function V_(l,c,f,p,h,g,v,_,T,C){var E=H();try{ae(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function G_(l,c,f,p,h,g,v,_,T,C,E,R,N,D){var V=H();try{Rr(l,c,f,p,h,g,v,_,T,C,E,R,N,D)}catch(Q){if(W(V),Q!==Q+0)throw Q;G(1,0)}}function W_(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{return Ml(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function H_(l,c,f,p,h,g,v,_,T){var C=H();try{return eo(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function q_(l,c,f,p,h,g,v,_,T){var C=H();try{Nl(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function K_(l,c,f,p){var h=H();try{X(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function Y_(l,c){var f=H();try{return Ll(l,c)}catch(p){if(W(f),p!==p+0)throw p;G(1,0)}}function X_(l,c){var f=H();try{return M(l,c)}catch(p){if(W(f),p!==p+0)throw p;return G(1,0),0n}}function Z_(l,c){var f=H();try{return Ul(l,c)}catch(p){if(W(f),p!==p+0)throw p;G(1,0)}}function J_(l,c,f,p){var h=H();try{Vl(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function Q_(l,c,f,p,h,g,v){var _=H();try{rf(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function ex(l,c,f,p,h){var g=H();try{Kd(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function tx(l,c,f,p,h,g,v,_,T,C){var E=H();try{return Gl(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function rx(l,c,f,p,h,g,v){var _=H();try{Wl(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function nx(l,c,f,p){var h=H();try{Hl(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function ix(l,c,f,p,h,g,v,_,T){var C=H();try{return et(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function ox(l,c,f,p,h,g,v){var _=H();try{ql(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function ax(l,c,f,p,h,g,v,_,T){var C=H();try{Zi(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function sx(l,c,f,p,h,g,v){var _=H();try{Kl(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function ux(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{Yl(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function lx(l,c,f,p){var h=H();try{return Zl(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;return G(1,0),0n}}function dx(l,c,f,p,h,g,v,_){var T=H();try{Jl(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function cx(l,c,f,p,h){var g=H();try{Ql(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function fx(l,c,f,p){var h=H();try{td(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function px(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q){var ce=H();try{rd(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)}catch(ye){if(W(ce),ye!==ye+0)throw ye;G(1,0)}}function hx(l,c,f,p,h,g){var v=H();try{nd(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function mx(l,c,f,p,h,g,v,_,T){var C=H();try{id(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function gx(l,c,f,p,h){var g=H();try{return od(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function yx(l,c,f,p,h,g,v,_,T,C,E,R,N,D){var V=H();try{return ad(l,c,f,p,h,g,v,_,T,C,E,R,N,D)}catch(Q){if(W(V),Q!==Q+0)throw Q;G(1,0)}}function bx(l,c){var f=H();try{sd(l,c)}catch(p){if(W(f),p!==p+0)throw p;G(1,0)}}function vx(l,c,f){var p=H();try{return ud(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;return G(1,0),0n}}function wx(l,c,f,p,h,g,v,_,T,C){var E=H();try{return ld(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function _x(l,c,f,p,h,g,v,_,T,C,E,R,N,D){var V=H();try{hd(l,c,f,p,h,g,v,_,T,C,E,R,N,D)}catch(Q){if(W(V),Q!==Q+0)throw Q;G(1,0)}}function xx(l,c,f,p,h){var g=H();try{dd(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function $x(l,c,f,p,h,g,v){var _=H();try{cd(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function Tx(l,c,f,p,h){var g=H();try{pd(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function Sx(l,c,f,p,h,g,v,_){var T=H();try{fd(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function Ix(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{md(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function Cx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce){var ye=H();try{return gd(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce)}catch(ke){if(W(ye),ke!==ke+0)throw ke;G(1,0)}}function Ax(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{yd(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function Ex(l,c){var f=H();try{return Ce(l,c)}catch(p){if(W(f),p!==p+0)throw p;G(1,0)}}function Ox(l,c,f,p,h){var g=H();try{return of(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function Px(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye){var st=H();try{return bd(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye)}catch(St){if(W(st),St!==St+0)throw St;G(1,0)}}function kx(l,c,f,p,h,g,v,_,T,C){var E=H();try{vd(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function Dx(l,c,f,p,h,g,v){var _=H();try{return wd(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function Bx(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{_d(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function Rx(l,c,f,p,h,g){var v=H();try{return xd(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function zx(l,c,f,p,h,g){var v=H();try{Td(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function Mx(l,c,f,p,h,g,v,_,T,C,E,R,N,D){var V=H();try{Sd(l,c,f,p,h,g,v,_,T,C,E,R,N,D)}catch(Q){if(W(V),Q!==Q+0)throw Q;G(1,0)}}function Nx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye){var ke=H();try{Id(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye)}catch(Ye){if(W(ke),Ye!==Ye+0)throw Ye;G(1,0)}}function Lx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce){var ye=H();try{Cd(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce)}catch(ke){if(W(ye),ke!==ke+0)throw ke;G(1,0)}}function jx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q){var ce=H();try{Ad(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)}catch(ye){if(W(ce),ye!==ye+0)throw ye;G(1,0)}}function Ux(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V){var Q=H();try{Ed(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)}catch(ce){if(W(Q),ce!==ce+0)throw ce;G(1,0)}}function Fx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st){var St=H();try{Od(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st)}catch(Wt){if(W(St),Wt!==Wt+0)throw Wt;G(1,0)}}function Vx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke){var Ye=H();try{Pd(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke)}catch(st){if(W(Ye),st!==st+0)throw st;G(1,0)}}function Gx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye){var ke=H();try{kd(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye)}catch(Ye){if(W(ke),Ye!==Ye+0)throw Ye;G(1,0)}}function Wx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st){var St=H();try{Dd(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st)}catch(Wt){if(W(St),Wt!==Wt+0)throw Wt;G(1,0)}}function Hx(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{Bd(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function qx(l,c,f,p,h,g,v,_,T,C){var E=H();try{Rd(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function Kx(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{zd(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function Yx(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V){var Q=H();try{Md(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)}catch(ce){if(W(Q),ce!==ce+0)throw ce;G(1,0)}}function Xx(l,c,f,p,h,g,v,_,T,C){var E=H();try{Ld(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function Zx(l,c,f,p,h,g,v,_,T){var C=H();try{jd(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function Jx(l,c,f,p,h,g,v){var _=H();try{return $d(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function Qx(l,c,f,p,h){var g=H();try{Nd(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function e2(l,c,f){var p=H();try{return af(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;return G(1,0),0n}}function t2(l,c,f,p,h,g,v,_,T,C,E,R,N,D){var V=H();try{Ud(l,c,f,p,h,g,v,_,T,C,E,R,N,D)}catch(Q){if(W(V),Q!==Q+0)throw Q;G(1,0)}}function r2(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{Vd(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function n2(l,c,f,p,h,g,v){var _=H();try{return Gd(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function i2(l,c,f,p,h,g){var v=H();try{return Wd(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function o2(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{Hd(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function a2(l,c,f,p,h,g){var v=H();try{Fd(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function s2(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{qd(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function u2(l,c,f,p,h,g,v,_){var T=H();try{Yd(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function l2(l,c,f,p,h,g,v,_){var T=H();try{Xd(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function d2(l,c,f,p){var h=H();try{return Zd(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function c2(l,c,f,p,h,g,v,_,T,C){var E=H();try{Jd(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function f2(l,c,f,p,h,g,v,_,T){var C=H();try{Qd(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function p2(l,c,f,p,h,g,v,_,T){var C=H();try{ec(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function h2(l,c,f,p,h,g,v,_,T,C){var E=H();try{tc(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function m2(l,c,f,p,h,g){var v=H();try{rc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function g2(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{nc(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function y2(l,c,f,p,h,g,v,_){var T=H();try{return ic(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function b2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V){var Q=H();try{sf(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)}catch(ce){if(W(Q),ce!==ce+0)throw ce;G(1,0)}}function v2(l,c,f,p,h,g,v,_,T,C,E,R,N,D){var V=H();try{oc(l,c,f,p,h,g,v,_,T,C,E,R,N,D)}catch(Q){if(W(V),Q!==Q+0)throw Q;G(1,0)}}function w2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V){var Q=H();try{ac(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V)}catch(ce){if(W(Q),ce!==ce+0)throw ce;G(1,0)}}function _2(l,c,f){var p=H();try{sc(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function x2(l,c,f,p){var h=H();try{return lc(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function $2(l,c,f,p){var h=H();try{return dc(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function T2(l,c,f,p,h,g,v,_,T,C){var E=H();try{cc(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function S2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st,St,Wt,Rs,zs,Ms){var S1=H();try{fc(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st,St,Wt,Rs,zs,Ms)}catch(Ns){if(W(S1),Ns!==Ns+0)throw Ns;G(1,0)}}function I2(l,c,f,p,h,g){var v=H();try{pc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function C2(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{return hc(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function A2(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{mc(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function E2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st){var St=H();try{gc(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye,st)}catch(Wt){if(W(St),Wt!==Wt+0)throw Wt;G(1,0)}}function O2(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{yc(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function P2(l,c,f,p,h,g,v,_,T,C,E,R,N,D){var V=H();try{bc(l,c,f,p,h,g,v,_,T,C,E,R,N,D)}catch(Q){if(W(V),Q!==Q+0)throw Q;G(1,0)}}function k2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye){var st=H();try{wc(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye)}catch(St){if(W(st),St!==St+0)throw St;G(1,0)}}function D2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce){var ye=H();try{xc(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce)}catch(ke){if(W(ye),ke!==ke+0)throw ke;G(1,0)}}function B2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke){var Ye=H();try{vc(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke)}catch(st){if(W(Ye),st!==st+0)throw st;G(1,0)}}function R2(l,c,f,p,h,g,v,_){var T=H();try{$c(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function z2(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{Sc(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function M2(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{return Ic(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function N2(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye){var st=H();try{return Cc(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q,ce,ye,ke,Ye)}catch(St){if(W(st),St!==St+0)throw St;G(1,0)}}function L2(l,c,f,p,h){var g=H();try{Ac(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function j2(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{Xl(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function U2(l,c,f,p,h,g,v,_,T,C){var E=H();try{Ec(l,c,f,p,h,g,v,_,T,C)}catch(R){if(W(E),R!==R+0)throw R;G(1,0)}}function F2(l,c,f,p,h){var g=H();try{Oc(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function V2(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{nf(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function G2(l,c,f,p,h){var g=H();try{return Pc(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function W2(l,c,f,p){var h=H();try{return uf(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;return G(1,0),0n}}function H2(l,c,f,p,h,g,v){var _=H();try{kc(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function q2(l,c,f,p,h,g){var v=H();try{return Dc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function K2(l,c,f,p,h,g){var v=H();try{return Bc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function Y2(l,c,f,p,h,g,v,_,T){var C=H();try{Rc(l,c,f,p,h,g,v,_,T)}catch(E){if(W(C),E!==E+0)throw E;G(1,0)}}function X2(l,c,f,p){var h=H();try{uc(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function Z2(l,c,f,p,h,g,v,_){var T=H();try{return zc(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function J2(l,c,f,p,h,g){var v=H();try{return Mc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function Q2(l,c,f,p,h,g){var v=H();try{return Nc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function e1(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{return Lc(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function t1(l,c,f,p,h,g,v,_){var T=H();try{return jc(l,c,f,p,h,g,v,_)}catch(C){if(W(T),C!==C+0)throw C;G(1,0)}}function r1(l,c,f,p,h,g,v,_,T,C,E){var R=H();try{return Uc(l,c,f,p,h,g,v,_,T,C,E)}catch(N){if(W(R),N!==N+0)throw N;G(1,0)}}function n1(l,c,f,p,h,g,v){var _=H();try{return Fc(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function i1(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{return Vc(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function o1(l,c,f,p,h,g,v){var _=H();try{return Gc(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function a1(l,c,f,p,h,g,v){var _=H();try{return Wc(l,c,f,p,h,g,v)}catch(T){if(W(_),T!==T+0)throw T;G(1,0)}}function s1(l,c,f){var p=H();try{return Hc(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;return G(1,0),0n}}function u1(l,c,f,p){var h=H();try{return qc(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function l1(l,c,f,p){var h=H();try{Yc(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function d1(l,c,f,p){var h=H();try{return Kc(l,c,f,p)}catch(g){if(W(h),g!==g+0)throw g;G(1,0)}}function c1(l,c,f,p,h){var g=H();try{Xc(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function f1(l,c,f,p,h){var g=H();try{return Zc(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function p1(l,c,f,p,h,g){var v=H();try{return Jc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function h1(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{Qc(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function m1(l,c,f,p,h,g,v,_,T,C,E,R,N){var D=H();try{ef(l,c,f,p,h,g,v,_,T,C,E,R,N)}catch(V){if(W(D),V!==V+0)throw V;G(1,0)}}function g1(l,c,f,p,h,g,v,_,T,C,E,R){var N=H();try{ed(l,c,f,p,h,g,v,_,T,C,E,R)}catch(D){if(W(N),D!==D+0)throw D;G(1,0)}}function y1(l,c,f,p,h){var g=H();try{return tf(l,c,f,p,h)}catch(v){if(W(g),v!==v+0)throw v;G(1,0)}}function b1(l){var c=H();try{return we(l)}catch(f){if(W(c),f!==f+0)throw f;return G(1,0),0n}}function v1(l,c,f,p,h,g){var v=H();try{return Te(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function w1(l,c,f,p,h,g){var v=H();try{return Tc(l,c,f,p,h,g)}catch(_){if(W(v),_!==_+0)throw _;G(1,0)}}function _1(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q){var ce=H();try{_c(l,c,f,p,h,g,v,_,T,C,E,R,N,D,V,Q)}catch(ye){if(W(ce),ye!==ye+0)throw ye;G(1,0)}}function x1(l,c,f){var p=H();try{return jl(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function $1(l,c,f){var p=H();try{return Fl(l,c,f)}catch(h){if(W(p),h!==h+0)throw h;G(1,0)}}function T1(){var l=L;l=Object.assign({},l);var c=f=>p=>f(p)>>>0;return l.Fd=c(l.Fd),l.he=c(l.he),l.ne=c(l.ne),l.oe=(f=>()=>f()>>>0)(l.oe),l}r.stackSave=()=>H(),r.stackRestore=l=>W(l),r.stackAlloc=l=>Ko(l),r.UTF8ToString=pt,r.stringToUTF8=(l,c,f)=>ur(l,le,c,f),r.lengthBytesUTF8=hn;var ea;oe=function l(){ea||pf(),ea||(oe=l)};function pf(){if(!(0Yy)});var Jy=ht(()=>{});var Qy=ht(()=>{});var eb={};Tn(eb,{cpus:()=>lI});var lI,tb=q(()=>{lI=void 0});var ib=ht((nb,Zu)=>{"use strict";var rb=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(e={}){function r(){return Oe.buffer!=Be.buffer&&oe(),Be}function t(){return Oe.buffer!=Be.buffer&&oe(),Ae}function i(){return Oe.buffer!=Be.buffer&&oe(),Le}function o(){return Oe.buffer!=Be.buffer&&oe(),Pe}function s(){return Oe.buffer!=Be.buffer&&oe(),Tt}var a=e,u,d;a.ready=new Promise((y,S)=>{u=y,d=S}),a.jsepInit=(y,S,O,M,X,te,ae,Ce)=>{a.Qb=y,a.wb=S,a.yb=O,a.jb=M,a.xb=X,a.Ea=te,a.zb=ae,a.Ab=Ce,S=(Te,we,Ee)=>(...Xe)=>{let Qe=Gt,Z=we?.();Xe=Te(...Xe);let Me=we?.();return Z!==Me&&(Te=Me,Ee(Z),we=Ee=null),Gt!=Qe?W():Xe},O=Te=>async(...we)=>{try{if(a.bb)throw Error("Session already started");let Ee=a.bb={Fb:we[0],errors:[]},Xe=await Te(...we);if(a.bb!==Ee)throw Error("Session mismatch");y.flush();let Qe=Ee.errors;if(0Me),0a._OrtRun,Te=>a._OrtRun=Te)),a._OrtRunWithBinding=O(S(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,Te=>a._OrtRunWithBinding=Te)),a._OrtBindInput=S(a._OrtBindInput,()=>a._OrtBindInput,Te=>a._OrtBindInput=Te),a.jsepRegisterBuffer=(Te,we,Ee,Xe)=>y.registerBuffer(Te,we,Ee,Xe),a.jsepUnregisterBuffers=Te=>{y.unregisterBuffers(Te)},a.jsepGetBuffer=Te=>y.getBuffer(Te),a.jsepCreateDownloader=(Te,we,Ee)=>y.createDownloader(Te,we,Ee)};var m=Object.assign({},a),b="./this.program",w=(y,S)=>{throw S},x=typeof window=="object",$=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",A=a.ENVIRONMENT_IS_PTHREAD||!1,k="";function P(y){return a.locateFile?a.locateFile(y,k):k+y}var z,U,F;if(I){var Y=(es(),Kr(Qa)),ie=(Yu(),Kr(Ku));k=$?ie.dirname(k)+"/":__dirname+"/",z=(S,O)=>(S=S.startsWith("file://")?new URL(S):ie.normalize(S),Y.readFileSync(S,O?void 0:"utf8")),F=S=>(S=z(S,!0),S.buffer||(S=new Uint8Array(S)),S),U=(S,O,M,X=!0)=>{S=S.startsWith("file://")?new URL(S):ie.normalize(S),Y.readFile(S,X?void 0:"utf8",(te,ae)=>{te?M(te):O(X?ae.buffer:ae)})},!a.thisProgram&&1{throw process.exitCode=S,O},a.inspect=()=>"[Emscripten Module object]";let y;try{y=Jy()}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(x||$)&&($?k=self.location.href:typeof document<"u"&&document.currentScript&&(k=document.currentScript.src),typeof n<"u"&&n&&(k=n),k.indexOf("blob:")!==0?k=k.substr(0,k.replace(/[?#].*/,"").lastIndexOf("/")+1):k="",I||(z=y=>{var S=new XMLHttpRequest;return S.open("GET",y,!1),S.send(null),S.responseText},$&&(F=y=>{var S=new XMLHttpRequest;return S.open("GET",y,!1),S.responseType="arraybuffer",S.send(null),new Uint8Array(S.response)}),U=(y,S,O)=>{var M=new XMLHttpRequest;M.open("GET",y,!0),M.responseType="arraybuffer",M.onload=()=>{M.status==200||M.status==0&&M.response?S(M.response):O()},M.onerror=O,M.send(null)}));I&&typeof performance>"u"&&(global.performance=Qy().performance);var ne=console.log.bind(console),le=console.error.bind(console);I&&(ne=(...y)=>Y.writeSync(1,y.join(" ")+` +`),le=(...y)=>Y.writeSync(2,y.join(" ")+` +`));var ge=a.print||ne,se=a.printErr||le;Object.assign(a,m),m=null,a.thisProgram&&(b=a.thisProgram),a.quit&&(w=a.quit);var re;a.wasmBinary&&(re=a.wasmBinary);var _e=a.noExitRuntime||!0;typeof WebAssembly!="object"&&tr("no native wasm support detected");var Oe,he,$e,je=!1,Ue,Be,Ae,Le,Pe,Tt;function oe(){var y=Oe.buffer;a.HEAP8=Be=new Int8Array(y),a.HEAP16=new Int16Array(y),a.HEAP32=Le=new Int32Array(y),a.HEAPU8=Ae=new Uint8Array(y),a.HEAPU16=new Uint16Array(y),a.HEAPU32=Pe=new Uint32Array(y),a.HEAPF32=new Float32Array(y),a.HEAPF64=Tt=new Float64Array(y)}var ve=a.INITIAL_MEMORY||16777216;if(5242880<=ve||tr("INITIAL_MEMORY should be larger than STACK_SIZE, was "+ve+"! (STACK_SIZE=5242880)"),A)Oe=a.wasmMemory;else if(a.wasmMemory)Oe=a.wasmMemory;else if(Oe=new WebAssembly.Memory({initial:ve/65536,maximum:65536,shared:!0}),!(Oe.buffer instanceof SharedArrayBuffer))throw se("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&&se("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");oe(),ve=Oe.buffer.byteLength;var He=[],Et=[],wt=[],bt=0;function Br(){return _e||0{if(!S.ok)throw"failed to load wasm binary file at '"+y+"'";return S.arrayBuffer()}).catch(()=>Wn(y));if(U)return new Promise((S,O)=>{U(y,M=>S(new Uint8Array(M)),O)})}return Promise.resolve().then(()=>Wn(y))}function Oi(y,S,O){return Hn(y).then(M=>WebAssembly.instantiate(M,S)).then(M=>M).then(O,M=>{se("failed to asynchronously prepare wasm: "+M),tr(M)})}function Io(y,S){var O=Vt;return re||typeof WebAssembly.instantiateStreaming!="function"||pn(O)||O.startsWith("file://")||I||typeof fetch!="function"?Oi(O,y,S):fetch(O,{credentials:"same-origin"}).then(M=>WebAssembly.instantiateStreaming(M,y).then(S,function(X){return se("wasm streaming compile failed: "+X),se("falling back to ArrayBuffer instantiation"),Oi(O,y,S)}))}var pt,hn={906828:y=>{a.Ea("Abs",y,void 0)},906879:y=>{a.Ea("Neg",y,void 0)},906930:y=>{a.Ea("Floor",y,void 0)},906983:y=>{a.Ea("Ceil",y,void 0)},907035:y=>{a.Ea("Reciprocal",y,void 0)},907093:y=>{a.Ea("Sqrt",y,void 0)},907145:y=>{a.Ea("Exp",y,void 0)},907196:y=>{a.Ea("Erf",y,void 0)},907247:y=>{a.Ea("Sigmoid",y,void 0)},907302:y=>{a.Ea("Log",y,void 0)},907353:y=>{a.Ea("Sin",y,void 0)},907404:y=>{a.Ea("Cos",y,void 0)},907455:y=>{a.Ea("Tan",y,void 0)},907506:y=>{a.Ea("Asin",y,void 0)},907558:y=>{a.Ea("Acos",y,void 0)},907610:y=>{a.Ea("Atan",y,void 0)},907662:y=>{a.Ea("Sinh",y,void 0)},907714:y=>{a.Ea("Cosh",y,void 0)},907766:y=>{a.Ea("Asinh",y,void 0)},907819:y=>{a.Ea("Acosh",y,void 0)},907872:y=>{a.Ea("Atanh",y,void 0)},907925:y=>{a.Ea("Tanh",y,void 0)},907977:y=>{a.Ea("Not",y,void 0)},908028:(y,S,O)=>{a.Ea("ClipV10",y,{min:S,max:O})},908100:y=>{a.Ea("Clip",y,void 0)},908152:(y,S)=>{a.Ea("Elu",y,{alpha:S})},908210:y=>{a.Ea("Relu",y,void 0)},908262:(y,S)=>{a.Ea("LeakyRelu",y,{alpha:S})},908326:(y,S)=>{a.Ea("ThresholdedRelu",y,{alpha:S})},908396:(y,S)=>{a.Ea("Cast",y,{to:S})},908454:y=>{a.Ea("Add",y,void 0)},908505:y=>{a.Ea("Sub",y,void 0)},908556:y=>{a.Ea("Mul",y,void 0)},908607:y=>{a.Ea("Div",y,void 0)},908658:y=>{a.Ea("Pow",y,void 0)},908709:y=>{a.Ea("Equal",y,void 0)},908762:y=>{a.Ea("Greater",y,void 0)},908817:y=>{a.Ea("GreaterOrEqual",y,void 0)},908879:y=>{a.Ea("Less",y,void 0)},908931:y=>{a.Ea("LessOrEqual",y,void 0)},908990:(y,S,O,M,X)=>{a.Ea("ReduceMean",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},909154:(y,S,O,M,X)=>{a.Ea("ReduceMax",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},909317:(y,S,O,M,X)=>{a.Ea("ReduceMin",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},909480:(y,S,O,M,X)=>{a.Ea("ReduceProd",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},909644:(y,S,O,M,X)=>{a.Ea("ReduceSum",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},909807:(y,S,O,M,X)=>{a.Ea("ReduceL1",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},909969:(y,S,O,M,X)=>{a.Ea("ReduceL2",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},910131:(y,S,O,M,X)=>{a.Ea("ReduceLogSum",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},910297:(y,S,O,M,X)=>{a.Ea("ReduceSumSquare",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},910466:(y,S,O,M,X)=>{a.Ea("ReduceLogSumExp",y,{keepDims:!!S,noopWithEmptyAxes:!!O,axes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},910635:y=>{a.Ea("Where",y,void 0)},910688:(y,S,O)=>{a.Ea("Transpose",y,{perm:S?Array.from(i().subarray(O>>>0,O+S>>>0)):[]})},910801:(y,S,O,M,X,te,ae,Ce,Te,we)=>{a.Ea("Conv",y,{format:Te?"NHWC":"NCHW",auto_pad:S,dilations:[O],group:M,kernel_shape:[X],pads:[te,ae],strides:[Ce],w_is_const:()=>!!r()[we>>>0]})},911029:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z,Me)=>{a.Ea("Conv",y,{format:Z?"NHWC":"NCHW",auto_pad:S,dilations:[O,M],group:X,kernel_shape:[te,ae],pads:[Ce,Te,we,Ee],strides:[Xe,Qe],w_is_const:()=>!!r()[Me>>>0]})},911288:(y,S,O,M,X,te,ae,Ce,Te,we)=>{a.Ea("Conv",y,{format:Te?"NHWC":"NCHW",auto_pad:S,dilations:[O],group:M,kernel_shape:[X],pads:[te,ae],strides:[Ce],w_is_const:()=>!!r()[we>>>0]})},911516:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z,Me)=>{a.Ea("Conv",y,{format:Z?"NHWC":"NCHW",auto_pad:S,dilations:[O,M],group:X,kernel_shape:[te,ae],pads:[Ce,Te,we,Ee],strides:[Xe,Qe],w_is_const:()=>!!r()[Me>>>0]})},911775:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z)=>{a.Ea("ConvTranspose",y,{format:Te?"NHWC":"NCHW",autoPad:S,dilations:[O],group:M,kernel_shape:[X],pads:[te,ae],strides:[Ce],wIsConst:()=>!!r()[we>>>0],outputPadding:Ee?Array.from(i().subarray(Xe>>>0,Xe+Ee>>>0)):[],outputShape:Qe?Array.from(i().subarray(Z>>>0,Z+Qe>>>0)):[]})},912155:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe)=>{a.Ea("ConvTranspose",y,{format:Ce?"NHWC":"NCHW",autoPad:S,dilations:Array.from(i().subarray(O>>>0,O+2>>>0)),group:M,kernelShape:Array.from(i().subarray(X>>>0,X+2>>>0)),pads:Array.from(i().subarray(te>>>0,te+4>>>0)),strides:Array.from(i().subarray(ae>>>0,ae+2>>>0)),wIsConst:()=>!!r()[Te>>>0],outputPadding:0>>0,Ee+we>>>0)):[],outputShape:0>>0,Qe+Xe>>>0)):[]})},912678:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z)=>{a.Ea("ConvTranspose",y,{format:Te?"NHWC":"NCHW",autoPad:S,dilations:[O],group:M,kernel_shape:[X],pads:[te,ae],strides:[Ce],wIsConst:()=>!!r()[we>>>0],outputPadding:Ee?Array.from(i().subarray(Xe>>>0,Xe+Ee>>>0)):[],outputShape:Qe?Array.from(i().subarray(Z>>>0,Z+Qe>>>0)):[]})},913058:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe)=>{a.Ea("ConvTranspose",y,{format:Ce?"NHWC":"NCHW",autoPad:S,dilations:Array.from(i().subarray(O>>>0,O+2>>>0)),group:M,kernelShape:Array.from(i().subarray(X>>>0,X+2>>>0)),pads:Array.from(i().subarray(te>>>0,te+4>>>0)),strides:Array.from(i().subarray(ae>>>0,ae+2>>>0)),wIsConst:()=>!!r()[Te>>>0],outputPadding:0>>0,Ee+we>>>0)):[],outputShape:0>>0,Qe+Xe>>>0)):[]})},913581:(y,S)=>{a.Ea("GlobalAveragePool",y,{format:S?"NHWC":"NCHW"})},913672:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z,Me,et)=>{a.Ea("AveragePool",y,{format:et?"NHWC":"NCHW",auto_pad:S,ceil_mode:O,count_include_pad:M,storage_order:X,dilations:[te,ae],kernel_shape:[Ce,Te],pads:[we,Ee,Xe,Qe],strides:[Z,Me]})},913956:(y,S)=>{a.Ea("GlobalAveragePool",y,{format:S?"NHWC":"NCHW"})},914047:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z,Me,et)=>{a.Ea("AveragePool",y,{format:et?"NHWC":"NCHW",auto_pad:S,ceil_mode:O,count_include_pad:M,storage_order:X,dilations:[te,ae],kernel_shape:[Ce,Te],pads:[we,Ee,Xe,Qe],strides:[Z,Me]})},914331:(y,S)=>{a.Ea("GlobalMaxPool",y,{format:S?"NHWC":"NCHW"})},914418:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z,Me,et)=>{a.Ea("MaxPool",y,{format:et?"NHWC":"NCHW",auto_pad:S,ceil_mode:O,count_include_pad:M,storage_order:X,dilations:[te,ae],kernel_shape:[Ce,Te],pads:[we,Ee,Xe,Qe],strides:[Z,Me]})},914698:(y,S)=>{a.Ea("GlobalMaxPool",y,{format:S?"NHWC":"NCHW"})},914785:(y,S,O,M,X,te,ae,Ce,Te,we,Ee,Xe,Qe,Z,Me,et)=>{a.Ea("MaxPool",y,{format:et?"NHWC":"NCHW",auto_pad:S,ceil_mode:O,count_include_pad:M,storage_order:X,dilations:[te,ae],kernel_shape:[Ce,Te],pads:[we,Ee,Xe,Qe],strides:[Z,Me]})},915065:(y,S,O,M,X)=>{a.Ea("Gemm",y,{alpha:S,beta:O,transA:M,transB:X})},915169:y=>{a.Ea("MatMul",y,void 0)},915223:(y,S,O,M)=>{a.Ea("ArgMax",y,{keepDims:!!S,selectLastIndex:!!O,axis:M})},915331:(y,S,O,M)=>{a.Ea("ArgMin",y,{keepDims:!!S,selectLastIndex:!!O,axis:M})},915439:(y,S)=>{a.Ea("Softmax",y,{axis:S})},915502:(y,S)=>{a.Ea("Concat",y,{axis:S})},915562:(y,S,O,M,X)=>{a.Ea("Split",y,{axis:S,numOutputs:O,splitSizes:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},915707:y=>{a.Ea("Expand",y,void 0)},915761:(y,S)=>{a.Ea("Gather",y,{axis:Number(S)})},915832:(y,S)=>{a.Ea("GatherElements",y,{axis:Number(S)})},915911:(y,S,O,M,X,te,ae,Ce,Te,we,Ee)=>{a.Ea("Resize",y,{antialias:S,axes:O?Array.from(i().subarray(M>>>0,M+O>>>0)):[],coordinateTransformMode:zt(X),cubicCoeffA:te,excludeOutside:ae,extrapolationValue:Ce,keepAspectRatioPolicy:zt(Te),mode:zt(we),nearestMode:zt(Ee)})},916262:(y,S,O,M,X,te,ae)=>{a.Ea("Slice",y,{starts:S?Array.from(i().subarray(O>>>0,O+S>>>0)):[],ends:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[],axes:te?Array.from(i().subarray(ae>>>0,ae+te>>>0)):[]})},916493:y=>{a.Ea("Tile",y,void 0)},916545:(y,S,O)=>{a.Ea("LayerNormalization",y,{axis:Number(S),epsilon:Number(O)})},916652:(y,S,O)=>{a.Ea("InstanceNormalization",y,{epsilon:S,format:O?"NHWC":"NCHW"})},916766:(y,S,O)=>{a.Ea("InstanceNormalization",y,{epsilon:S,format:O?"NHWC":"NCHW"})},916880:y=>{a.Ea("Range",y,void 0)},916933:(y,S)=>{a.Ea("Einsum",y,{equation:zt(S)})},917014:(y,S,O,M,X)=>{a.Ea("Pad",y,{mode:S,value:O,pads:M?Array.from(i().subarray(X>>>0,X+M>>>0)):[]})},917146:y=>{a.Ea("Gelu",y,void 0)},917198:y=>{a.Ea("BiasAdd",y,void 0)},917253:y=>{a.Ea("BiasSplitGelu",y,void 0)},917314:(y,S)=>{a.Ea("SkipLayerNormalization",y,{epsilon:S})},917395:y=>{a.zb(y)},917429:(y,S)=>a.Ab(y,S,a.bb.Fb,a.bb.errors),917541:y=>a.wb(y),917574:y=>a.yb(y),917606:(y,S,O)=>{a.jb(y,S,O,!0)},917645:(y,S,O)=>{a.jb(y,S,O)}};function ur(y){this.name="ExitStatus",this.message=`Program terminated with exit(${y})`,this.status=y}function qn(y){y.terminate(),y.onmessage=()=>{}}function rr(y){(y=Re.Qa[y])||tr(),Re.Eb(y)}function Kn(y){var S=Re.tb();if(!S)return 6;Re.Ya.push(S),Re.Qa[y.Xa]=S,S.Xa=y.Xa;var O={cmd:"run",start_routine:y.Gb,arg:y.rb,pthread_ptr:y.Xa};return I&&S.unref(),S.postMessage(O,y.Mb),0}var Yn=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Co=(y,S,O)=>{S>>>=0;var M=S+O;for(O=S;y[O]&&!(O>=M);)++O;if(16X?M+=String.fromCharCode(X):(X-=65536,M+=String.fromCharCode(55296|X>>10,56320|X&1023))}}else M+=String.fromCharCode(X)}return M},zt=(y,S)=>(y>>>=0)?Co(t(),y,S):"";function Ao(y){if(A)return lt(1,1,y);Ue=y,Br()||(Re.Hb(),a.onExit&&a.onExit(y),je=!0),w(y,new ur(y))}var nr=y=>{if(Ue=y,A)throw lr(y),"unwind";Ao(y)},Re={ab:[],Ya:[],mb:[],Qa:{},gb:function(){A?Re.vb():Re.ub()},ub:function(){He.unshift(()=>{Jr(),Re.Bb(()=>Qr())})},vb:function(){Re.receiveObjectTransfer=Re.Db,Re.threadInitTLS=Re.lb,Re.setExitStatus=Re.kb,_e=!1},kb:function(y){Ue=y},Sb:["$terminateWorker"],Hb:function(){for(var y of Re.Ya)qn(y);for(y of Re.ab)qn(y);Re.ab=[],Re.Ya=[],Re.Qa=[]},Eb:function(y){var S=y.Xa;delete Re.Qa[S],Re.ab.push(y),Re.Ya.splice(Re.Ya.indexOf(y),1),y.Xa=0,ui(S)},Db:function(){},lb:function(){Re.mb.forEach(y=>y())},Cb:y=>new Promise(S=>{y.onmessage=te=>{te=te.data;var ae=te.cmd;if(te.targetThread&&te.targetThread!=_n()){var Ce=Re.Qa[te.Rb];Ce?Ce.postMessage(te,te.transferList):se('Internal error! Worker sent a message "'+ae+'" to target pthread '+te.targetThread+", but that thread no longer exists!")}else ae==="checkMailbox"?yn():ae==="spawnThread"?Kn(te):ae==="cleanupThread"?rr(te.thread):ae==="killThread"?(te=te.thread,ae=Re.Qa[te],delete Re.Qa[te],qn(ae),ui(te),Re.Ya.splice(Re.Ya.indexOf(ae),1),ae.Xa=0):ae==="cancelThread"?Re.Qa[te.thread].postMessage({cmd:"cancel"}):ae==="loaded"?(y.loaded=!0,S(y)):ae==="alert"?alert("Thread "+te.threadId+": "+te.text):te.target==="setimmediate"?y.postMessage(te):ae==="callHandler"?a[te.handler](...te.args):ae&&se("worker sent an unknown command "+ae)},y.onerror=te=>{throw se("worker sent an error! "+te.filename+":"+te.lineno+": "+te.message),te},I&&(y.on("message",function(te){y.onmessage({data:te})}),y.on("error",function(te){y.onerror(te)}));var O=[],M=["onExit","onAbort","print","printErr"],X;for(X of M)a.hasOwnProperty(X)&&O.push(X);y.postMessage({cmd:"load",handlers:O,urlOrBlob:a.mainScriptUrlOrBlob||n,wasmMemory:Oe,wasmModule:$e})}),Bb:function(y){y()},qb:function(){var y=P("ort-wasm-simd-threaded.worker.js");y=new Worker(y),Re.ab.push(y)},tb:function(){return Re.ab.length==0&&(Re.qb(),Re.Cb(Re.ab[0])),Re.ab.pop()}};a.PThread=Re;var en=y=>{for(;0>2>>>0];y=i()[y+56>>2>>>0],qi(S,S-y),xn(S)};function lr(y){if(A)return lt(2,0,y);nr(y)}a.invokeEntryPoint=function(y,S){y=Ki.apply(null,[y,S]),Br()?Re.kb(y):li(y)};function Pi(y){this.fb=y-24,this.pb=function(S){o()[this.fb+4>>2>>>0]=S},this.ob=function(S){o()[this.fb+8>>2>>>0]=S},this.gb=function(S,O){this.nb(),this.pb(S),this.ob(O)},this.nb=function(){o()[this.fb+16>>2>>>0]=0}}var Mt=0,ir=0;function Xn(y,S,O,M){return A?lt(3,1,y,S,O,M):Eo(y,S,O,M)}function Eo(y,S,O,M){if(y>>>=0,S>>>=0,O>>>=0,M>>>=0,typeof SharedArrayBuffer>"u")return se("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var X=[];return A&&X.length===0?Xn(y,S,O,M):(y={Gb:O,Xa:y,rb:M,Mb:X},A?(y.Ob="spawnThread",postMessage(y,X),0):Kn(y))}function Oo(y,S,O){return A?lt(4,1,y,S,O):0}function ki(y,S){if(A)return lt(5,1,y,S)}var Di=y=>{for(var S=0,O=0;O=M?S++:2047>=M?S+=2:55296<=M&&57343>=M?(S+=4,++O):S+=3}return S},Po=(y,S,O,M)=>{if(O>>>=0,!(0=ae){var Ce=y.charCodeAt(++te);ae=65536+((ae&1023)<<10)|Ce&1023}if(127>=ae){if(O>=M)break;S[O++>>>0]=ae}else{if(2047>=ae){if(O+1>=M)break;S[O++>>>0]=192|ae>>6}else{if(65535>=ae){if(O+2>=M)break;S[O++>>>0]=224|ae>>12}else{if(O+3>=M)break;S[O++>>>0]=240|ae>>18,S[O++>>>0]=128|ae>>12&63}S[O++>>>0]=128|ae>>6&63}S[O++>>>0]=128|ae&63}}return S[O>>>0]=0,O-X},ko=(y,S,O)=>Po(y,t(),S,O);function Do(y,S){if(A)return lt(6,1,y,S)}function Bo(y,S,O){if(A)return lt(7,1,y,S,O)}function Ro(y,S,O){return A?lt(8,1,y,S,O):0}function Zn(y,S){if(A)return lt(9,1,y,S)}function Bi(y,S,O){if(A)return lt(10,1,y,S,O)}function mn(y,S,O,M){if(A)return lt(11,1,y,S,O,M)}function zo(y,S,O,M){if(A)return lt(12,1,y,S,O,M)}function Mo(y,S,O,M){if(A)return lt(13,1,y,S,O,M)}function _r(y){if(A)return lt(14,1,y)}function or(y,S){if(A)return lt(15,1,y,S)}function Ri(y,S,O){if(A)return lt(16,1,y,S,O)}var gn=y=>{if(!je)try{if(y(),!Br())try{A?li(Ue):nr(Ue)}catch(S){S instanceof ur||S=="unwind"||w(1,S)}}catch(S){S instanceof ur||S=="unwind"||w(1,S)}};function Jn(y){y>>>=0,typeof Atomics.Nb=="function"&&(Atomics.Nb(i(),y>>2,y).value.then(yn),y+=128,Atomics.store(i(),y>>2,1))}a.__emscripten_thread_mailbox_await=Jn;function yn(){var y=_n();y&&(Jn(y),gn(()=>Wi()))}a.checkMailbox=yn;var tn=y=>y%4===0&&(y%100!==0||y%400===0),Qn=[0,31,60,91,121,152,182,213,244,274,305,335],No=[0,31,59,90,120,151,181,212,243,273,304,334];function Lo(y,S,O,M,X,te,ae,Ce){return A?lt(17,1,y,S,O,M,X,te,ae,Ce):-52}function jo(y,S,O,M,X,te,ae){if(A)return lt(18,1,y,S,O,M,X,te,ae)}var Uo=y=>{var S=Di(y)+1,O=si(S);return O&&ko(y,O,S),O},ei=[],bn=(y,S)=>{ei.length=0;var O;for(S>>=2;O=t()[y++>>>0];)S+=O!=105&S,ei.push(O==105?i()[S>>>0]:s()[S++>>>1]),++S;return ei},Ds=y=>{var S=di();return y=y(),xn(S),y};function lt(y,S){var O=arguments.length-2,M=arguments;return Ds(()=>{for(var X=ci(8*O),te=X>>3,ae=0;ae>>0]=Ce}return Gi(y,O,X,S)})}var ti=[],zi={},Fo=()=>{if(!ri){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",_:b||"./this.program"},S;for(S in zi)zi[S]===void 0?delete y[S]:y[S]=zi[S];var O=[];for(S in y)O.push(`${S}=${y[S]}`);ri=O}return ri},ri;function Vo(y,S){if(A)return lt(19,1,y,S);y>>>=0,S>>>=0;var O=0;return Fo().forEach(function(M,X){var te=S+O;for(X=o()[y+4*X>>2>>>0]=te,te=0;te>0>>>0]=M.charCodeAt(te);r()[X>>0>>>0]=0,O+=M.length+1}),0}function qr(y,S){if(A)return lt(20,1,y,S);y>>>=0,S>>>=0;var O=Fo();o()[y>>2>>>0]=O.length;var M=0;return O.forEach(function(X){M+=X.length+1}),o()[S>>2>>>0]=M,0}function Mi(y){return A?lt(21,1,y):52}function Ni(y,S,O,M){return A?lt(22,1,y,S,O,M):52}function ni(y,S,O,M,X){return A?lt(23,1,y,S,O,M,X):70}var Go=[null,[],[]];function ii(y,S,O,M){if(A)return lt(24,1,y,S,O,M);S>>>=0,O>>>=0,M>>>=0;for(var X=0,te=0;te>2>>>0],Ce=o()[S+4>>2>>>0];S+=8;for(var Te=0;Te>>0],Ee=Go[y];we===0||we===10?((y===1?ge:se)(Co(Ee,0)),Ee.length=0):Ee.push(we)}X+=Ce}return o()[M>>2>>>0]=X,0}var Li=[31,29,31,30,31,30,31,31,30,31,30,31],oi=[31,28,31,30,31,30,31,31,30,31,30,31];function Bs(y){var S=Array(Di(y)+1);return Po(y,S,0,S.length),S}var Wo=(y,S)=>{r().set(y,S>>>0)};function ji(y,S,O,M){function X(Z,Me,et){for(Z=typeof Z=="number"?Z.toString():Z||"";Z.lengtheo?-1:0Rr-Z.getDate())Me-=Rr-Z.getDate()+1,Z.setDate(1),11>et?Z.setMonth(et+1):(Z.setMonth(0),Z.setFullYear(Z.getFullYear()+1));else{Z.setDate(Z.getDate()+Me);break}}return et=new Date(Z.getFullYear()+1,0,4),Me=Ce(new Date(Z.getFullYear(),0,4)),et=Ce(et),0>=ae(Me,Z)?0>=ae(et,Z)?Z.getFullYear()+1:Z.getFullYear():Z.getFullYear()-1}y>>>=0,S>>>=0,O>>>=0,M>>>=0;var we=i()[M+40>>2>>>0];M={Kb:i()[M>>2>>>0],Jb:i()[M+4>>2>>>0],cb:i()[M+8>>2>>>0],ib:i()[M+12>>2>>>0],eb:i()[M+16>>2>>>0],$a:i()[M+20>>2>>>0],Wa:i()[M+24>>2>>>0],Za:i()[M+28>>2>>>0],Tb:i()[M+32>>2>>>0],Ib:i()[M+36>>2>>>0],Lb:we?zt(we):""},O=zt(O),we={"%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 Ee in we)O=O.replace(new RegExp(Ee,"g"),we[Ee]);var Xe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Qe="January February March April May June July August September October November December".split(" ");we={"%a":Z=>Xe[Z.Wa].substring(0,3),"%A":Z=>Xe[Z.Wa],"%b":Z=>Qe[Z.eb].substring(0,3),"%B":Z=>Qe[Z.eb],"%C":Z=>te((Z.$a+1900)/100|0,2),"%d":Z=>te(Z.ib,2),"%e":Z=>X(Z.ib,2," "),"%g":Z=>Te(Z).toString().substring(2),"%G":Z=>Te(Z),"%H":Z=>te(Z.cb,2),"%I":Z=>(Z=Z.cb,Z==0?Z=12:12{for(var Me=0,et=0;et<=Z.eb-1;Me+=(tn(Z.$a+1900)?Li:oi)[et++]);return te(Z.ib+Me,3)},"%m":Z=>te(Z.eb+1,2),"%M":Z=>te(Z.Jb,2),"%n":()=>` +`,"%p":Z=>0<=Z.cb&&12>Z.cb?"AM":"PM","%S":Z=>te(Z.Kb,2),"%t":()=>" ","%u":Z=>Z.Wa||7,"%U":Z=>te(Math.floor((Z.Za+7-Z.Wa)/7),2),"%V":Z=>{var Me=Math.floor((Z.Za+7-(Z.Wa+6)%7)/7);if(2>=(Z.Wa+371-Z.Za-2)%7&&Me++,Me)Me==53&&(et=(Z.Wa+371-Z.Za)%7,et==4||et==3&&tn(Z.$a)||(Me=1));else{Me=52;var et=(Z.Wa+7-Z.Za-1)%7;(et==4||et==5&&tn(Z.$a%400-1))&&Me++}return te(Me,2)},"%w":Z=>Z.Wa,"%W":Z=>te(Math.floor((Z.Za+7-(Z.Wa+6)%7)/7),2),"%y":Z=>(Z.$a+1900).toString().substring(2),"%Y":Z=>Z.$a+1900,"%z":Z=>{Z=Z.Ib;var Me=0<=Z;return Z=Math.abs(Z)/60,(Me?"+":"-")+("0000"+(Z/60*100+Z%60)).slice(-4)},"%Z":Z=>Z.Lb,"%%":()=>"%"},O=O.replace(/%%/g,"\0\0");for(Ee in we)O.includes(Ee)&&(O=O.replace(new RegExp(Ee,"g"),we[Ee](M)));return O=O.replace(/\0\0/g,"%"),Ee=Bs(O),Ee.length>S?0:(Wo(Ee,y),Ee.length-1)}function ai(y){try{y()}catch(S){tr(S)}}function Ho(y){var S={},O;for(O in y)(function(M){var X=y[M];S[M]=typeof X=="function"?function(){L.push(M);try{return X.apply(null,arguments)}finally{je||(L.pop()===M||tr(),Gt&&xr===1&&L.length===0&&(xr=0,bt+=1,ai(Xi),typeof Fibers<"u"&&Fibers.Ub()))}}:X})(O);return S}var xr=0,Gt=null,qo=0,L=[],Ui={},vn={},dr=0,G=null,wn=[];function W(){return new Promise((y,S)=>{G={resolve:y,reject:S}})}function Ko(){var y=si(65548),S=y+12;o()[y>>2>>>0]=S,o()[y+4>>2>>>0]=S+65536,S=L[0];var O=Ui[S];return O===void 0&&(O=dr++,Ui[S]=O,vn[O]=S),S=O,i()[y+8>>2>>>0]=S,y}function H(){var y=i()[Gt+8>>2>>>0];return y=he[vn[y]],--bt,y()}function Yo(y){if(!je){if(xr===0){var S=!1,O=!1;y((M=0)=>{if(!je&&(qo=M,S=!0,O)){xr=2,ai(()=>Zi(Gt)),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.resume(),M=!1;try{var X=H()}catch(Ce){X=Ce,M=!0}var te=!1;if(!Gt){var ae=G;ae&&(G=null,(M?ae.reject:ae.resolve)(X),te=!0)}if(M&&!te)throw X}}),O=!0,S||(xr=1,Gt=Ko(),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.pause(),ai(()=>Yi(Gt)))}else xr===2?(xr=0,ai(Ji),Fi(Gt),Gt=null,wn.forEach(M=>gn(M))):tr(`invalid state: ${xr}`);return qo}}function Xo(y){return Yo(S=>{y().then(S)})}Re.gb();var Zo=[null,Ao,lr,Xn,Oo,ki,Do,Bo,Ro,Zn,Bi,mn,zo,Mo,_r,or,Ri,Lo,jo,Vo,qr,Mi,Ni,ni,ii],Jo={r:function(y,S,O){return Xo(async()=>{await a.xb(y,S,O)})},b:function(y,S,O){throw y>>>=0,new Pi(y).gb(S>>>0,O>>>0),Mt=y,ir++,Mt},O:function(y){Vi(y>>>0,!$,1,!x,131072,!1),Re.lb()},l:function(y){y>>>=0,A?postMessage({cmd:"cleanupThread",thread:y}):rr(y)},I:Eo,i:Oo,U:ki,E:Do,G:Bo,V:Ro,S:Zn,K:Bi,R:mn,p:zo,F:Mo,C:_r,T:or,D:Ri,q:()=>!0,A:function(y,S){y>>>=0,y==S>>>0?setTimeout(()=>yn()):A?postMessage({targetThread:y,cmd:"checkMailbox"}):(y=Re.Qa[y])&&y.postMessage({cmd:"checkMailbox"})},M:function(){return-1},N:Jn,X:function(y){I&&Re.Qa[y>>>0].ref()},u:function(y,S,O){y=S+2097152>>>0<4194305-!!y?(y>>>0)+4294967296*S:NaN,O>>>=0,y=new Date(1e3*y),i()[O>>2>>>0]=y.getUTCSeconds(),i()[O+4>>2>>>0]=y.getUTCMinutes(),i()[O+8>>2>>>0]=y.getUTCHours(),i()[O+12>>2>>>0]=y.getUTCDate(),i()[O+16>>2>>>0]=y.getUTCMonth(),i()[O+20>>2>>>0]=y.getUTCFullYear()-1900,i()[O+24>>2>>>0]=y.getUTCDay(),y=(y.getTime()-Date.UTC(y.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[O+28>>2>>>0]=y},v:function(y,S,O){y=S+2097152>>>0<4194305-!!y?(y>>>0)+4294967296*S:NaN,O>>>=0,y=new Date(1e3*y),i()[O>>2>>>0]=y.getSeconds(),i()[O+4>>2>>>0]=y.getMinutes(),i()[O+8>>2>>>0]=y.getHours(),i()[O+12>>2>>>0]=y.getDate(),i()[O+16>>2>>>0]=y.getMonth(),i()[O+20>>2>>>0]=y.getFullYear()-1900,i()[O+24>>2>>>0]=y.getDay(),S=(tn(y.getFullYear())?Qn:No)[y.getMonth()]+y.getDate()-1|0,i()[O+28>>2>>>0]=S,i()[O+36>>2>>>0]=-(60*y.getTimezoneOffset()),S=new Date(y.getFullYear(),6,1).getTimezoneOffset();var M=new Date(y.getFullYear(),0,1).getTimezoneOffset();y=(S!=M&&y.getTimezoneOffset()==Math.min(M,S))|0,i()[O+32>>2>>>0]=y},w:function(y){y>>>=0;var S=new Date(i()[y+20>>2>>>0]+1900,i()[y+16>>2>>>0],i()[y+12>>2>>>0],i()[y+8>>2>>>0],i()[y+4>>2>>>0],i()[y>>2>>>0],0),O=i()[y+32>>2>>>0],M=S.getTimezoneOffset(),X=new Date(S.getFullYear(),6,1).getTimezoneOffset(),te=new Date(S.getFullYear(),0,1).getTimezoneOffset(),ae=Math.min(te,X);return 0>O?i()[y+32>>2>>>0]=+(X!=te&&ae==M):0>2>>>0]=S.getDay(),O=(tn(S.getFullYear())?Qn:No)[S.getMonth()]+S.getDate()-1|0,i()[y+28>>2>>>0]=O,i()[y>>2>>>0]=S.getSeconds(),i()[y+4>>2>>>0]=S.getMinutes(),i()[y+8>>2>>>0]=S.getHours(),i()[y+12>>2>>>0]=S.getDate(),i()[y+16>>2>>>0]=S.getMonth(),i()[y+20>>2>>>0]=S.getYear(),y=S.getTime()/1e3,Hi((pt=y,1<=+Math.abs(pt)?0>>0:~~+Math.ceil((pt-+(~~pt>>>0))/4294967296)>>>0:0)),y>>>0},s:Lo,t:jo,z:function(y,S,O){function M(we){return(we=we.toTimeString().match(/\(([A-Za-z ]+)\)$/))?we[1]:"GMT"}y>>>=0,S>>>=0,O>>>=0;var X=new Date().getFullYear(),te=new Date(X,0,1),ae=new Date(X,6,1);X=te.getTimezoneOffset();var Ce=ae.getTimezoneOffset(),Te=Math.max(X,Ce);o()[y>>2>>>0]=60*Te,i()[S>>2>>>0]=+(X!=Ce),y=M(te),S=M(ae),y=Uo(y),S=Uo(S),Ce>2>>>0]=y,o()[O+4>>2>>>0]=S):(o()[O>>2>>>0]=S,o()[O+4>>2>>>0]=y)},d:()=>{tr("")},c:function(y,S,O){return y>>>=0,S=bn(S>>>0,O>>>0),hn[y].apply(null,S)},k:function(y,S,O){return y>>>=0,S=bn(S>>>0,O>>>0),hn[y].apply(null,S)},m:function(){},j:function(){return Date.now()},W:()=>{throw bt+=1,"unwind"},B:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:function(){return I?(tb(),Kr(eb)).cpus().length:navigator.hardwareConcurrency},L:function(y,S,O,M){for(Re.Pb=S>>>0,ti.length=O,S=M>>>0>>3,M=0;M>>0];return(0>y?hn[-y-1]:Zo[y]).apply(null,ti)},y:function(y){y>>>=0;var S=t().length;if(y<=S||4294901760=O;O*=2){var M=S*(1+.2/O);M=Math.min(M,y+100663296);var X=Math;M=Math.max(y,M);e:{X=X.min.call(X,4294901760,M+(65536-M%65536)%65536)-Oe.buffer.byteLength+65535>>>16;try{Oe.grow(X),oe();var te=1;break e}catch{}te=void 0}if(te)return!0}return!1},P:Vo,Q:qr,H:nr,h:Mi,o:Ni,x:ni,n:ii,a:Oe||a.wasmMemory,J:ji,e:function(y,S,O,M){return ji(y>>>0,S>>>0,O>>>0,M>>>0)}};(function(){function y(O,M){return O=O.exports,O=Ho(O),he=O=Qo(O),Re.mb.push(he.Da),Et.unshift(he.Y),$e=M,Qr(),O}var S={a:Jo};if(Jr(),a.instantiateWasm)try{return a.instantiateWasm(S,y)}catch(O){se("Module.instantiateWasm callback failed with error: "+O),d(O)}return Io(S,function(O){y(O.instance,O.module)}).catch(d),{}})(),a._OrtInit=(y,S)=>(a._OrtInit=he.Z)(y,S),a._OrtGetLastError=(y,S)=>(a._OrtGetLastError=he._)(y,S),a._OrtCreateSessionOptions=(y,S,O,M,X,te,ae,Ce,Te,we)=>(a._OrtCreateSessionOptions=he.$)(y,S,O,M,X,te,ae,Ce,Te,we),a._OrtAppendExecutionProvider=(y,S)=>(a._OrtAppendExecutionProvider=he.aa)(y,S),a._OrtAddFreeDimensionOverride=(y,S,O)=>(a._OrtAddFreeDimensionOverride=he.ba)(y,S,O),a._OrtAddSessionConfigEntry=(y,S,O)=>(a._OrtAddSessionConfigEntry=he.ca)(y,S,O),a._OrtReleaseSessionOptions=y=>(a._OrtReleaseSessionOptions=he.da)(y),a._OrtCreateSession=(y,S,O)=>(a._OrtCreateSession=he.ea)(y,S,O),a._OrtReleaseSession=y=>(a._OrtReleaseSession=he.fa)(y),a._OrtGetInputOutputCount=(y,S,O)=>(a._OrtGetInputOutputCount=he.ga)(y,S,O),a._OrtGetInputName=(y,S)=>(a._OrtGetInputName=he.ha)(y,S),a._OrtGetOutputName=(y,S)=>(a._OrtGetOutputName=he.ia)(y,S),a._OrtFree=y=>(a._OrtFree=he.ja)(y),a._OrtCreateTensor=(y,S,O,M,X,te)=>(a._OrtCreateTensor=he.ka)(y,S,O,M,X,te),a._OrtGetTensorData=(y,S,O,M,X)=>(a._OrtGetTensorData=he.la)(y,S,O,M,X),a._OrtReleaseTensor=y=>(a._OrtReleaseTensor=he.ma)(y),a._OrtCreateRunOptions=(y,S,O,M)=>(a._OrtCreateRunOptions=he.na)(y,S,O,M),a._OrtAddRunConfigEntry=(y,S,O)=>(a._OrtAddRunConfigEntry=he.oa)(y,S,O),a._OrtReleaseRunOptions=y=>(a._OrtReleaseRunOptions=he.pa)(y),a._OrtCreateBinding=y=>(a._OrtCreateBinding=he.qa)(y),a._OrtBindInput=(y,S,O)=>(a._OrtBindInput=he.ra)(y,S,O),a._OrtBindOutput=(y,S,O,M)=>(a._OrtBindOutput=he.sa)(y,S,O,M),a._OrtClearBoundOutputs=y=>(a._OrtClearBoundOutputs=he.ta)(y),a._OrtReleaseBinding=y=>(a._OrtReleaseBinding=he.ua)(y),a._OrtRunWithBinding=(y,S,O,M,X)=>(a._OrtRunWithBinding=he.va)(y,S,O,M,X),a._OrtRun=(y,S,O,M,X,te,ae,Ce)=>(a._OrtRun=he.wa)(y,S,O,M,X,te,ae,Ce),a._OrtEndProfiling=y=>(a._OrtEndProfiling=he.xa)(y),a._JsepOutput=(y,S,O)=>(a._JsepOutput=he.ya)(y,S,O),a._JsepGetNodeName=y=>(a._JsepGetNodeName=he.za)(y);var _n=a._pthread_self=()=>(_n=a._pthread_self=he.Aa)(),si=a._malloc=y=>(si=a._malloc=he.Ba)(y),Fi=a._free=y=>(Fi=a._free=he.Ca)(y);a.__emscripten_tls_init=()=>(a.__emscripten_tls_init=he.Da)();var Vi=a.__emscripten_thread_init=(y,S,O,M,X,te)=>(Vi=a.__emscripten_thread_init=he.Fa)(y,S,O,M,X,te);a.__emscripten_thread_crashed=()=>(a.__emscripten_thread_crashed=he.Ga)();var Gi=(y,S,O,M)=>(Gi=he.Ha)(y,S,O,M),ui=y=>(ui=he.Ia)(y),li=a.__emscripten_thread_exit=y=>(li=a.__emscripten_thread_exit=he.Ja)(y),Wi=a.__emscripten_check_mailbox=()=>(Wi=a.__emscripten_check_mailbox=he.Ka)(),Hi=y=>(Hi=he.La)(y),qi=(y,S)=>(qi=he.Ma)(y,S),di=()=>(di=he.Na)(),xn=y=>(xn=he.Oa)(y),ci=y=>(ci=he.Pa)(y),Ki=a.dynCall_ii=(y,S)=>(Ki=a.dynCall_ii=he.Ra)(y,S),Yi=y=>(Yi=he.Sa)(y),Xi=()=>(Xi=he.Ta)(),Zi=y=>(Zi=he.Ua)(y),Ji=()=>(Ji=he.Va)();a.___start_em_js=917678,a.___stop_em_js=917839;function Qo(y){y=Object.assign({},y);var S=M=>()=>M()>>>0,O=M=>X=>M(X)>>>0;return y.__errno_location=S(y.__errno_location),y.pthread_self=S(y.pthread_self),y.malloc=O(y.malloc),y.stackSave=S(y.stackSave),y.stackAlloc=O(y.stackAlloc),y}a.keepRuntimeAlive=Br,a.wasmMemory=Oe,a.stackAlloc=ci,a.stackSave=di,a.stackRestore=xn,a.UTF8ToString=zt,a.stringToUTF8=ko,a.lengthBytesUTF8=Di,a.ExitStatus=ur,a.PThread=Re;var $n;Yt=function y(){$n||Qi(),$n||(Yt=y)};function Qi(){function y(){if(!$n&&($n=!0,a.calledRun=!0,!je)&&(A||en(Et),u(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),!A)){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;){var S=a.postRun.shift();wt.unshift(S)}en(wt)}}if(!(0<_t))if(A)u(a),A||en(Et),startWorker(a);else{if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)He.unshift(a.preRun.shift());en(He),0<_t||(a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),y()},1)):y())}}if(a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);0rb)});var ob=ht((Y4,dI)=>{dI.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 sb,cI,Ju,Qu,ts,ab,fI,pI,hI,ub,xt,Si=q(()=>{"use strict";sb=Zy();cI=ib(),Qu=!1,ts=!1,ab=!1,fI=n=>{if(n===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+n+", 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}},pI=()=>{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}},hI=(n,e)=>n?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":e?"ort-wasm-threaded.wasm":"ort-wasm.wasm",ub=async n=>{if(Qu)return Promise.resolve();if(ts)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ab)throw new Error("previous call to 'initializeWebAssembly()' failed.");ts=!0;let e=n.initTimeout,r=n.numThreads,t=n.simd,i=fI(r),o=t&&pI(),s=n.wasmPaths,a=typeof s=="string"?s:void 0,u=hI(o,i),d=typeof s=="object"?s[u]:void 0,m=!1,b=[];if(e>0&&b.push(new Promise(w=>{setTimeout(()=>{m=!0,w()},e)})),b.push(new Promise((w,x)=>{let $=i?cI:sb,I={locateFile:(A,k)=>{if(i&&A.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([ob()],{type:"text/javascript"}));if(A.endsWith(".wasm")){if(d)return d;let P=a??k;return u==="ort-wasm-simd.wasm"?P+"ort-wasm-simd.jsep.wasm":u==="ort-wasm-simd-threaded.wasm"?P+"ort-wasm-simd-threaded.jsep.wasm":P+u}return k+A}};if(i)if(I.numThreads=r,typeof Blob>"u")I.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let A=`var ortWasmThreaded=${$.toString()};`;I.mainScriptUrlOrBlob=new Blob([A],{type:"text/javascript"})}$(I).then(A=>{ts=!1,Qu=!0,Ju=A,w()},A=>{ts=!1,ab=!0,x(A)})})),await Promise.race(b),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},xt=()=>{if(Qu&&Ju)return Ju;throw new Error("WebAssembly is not initialized yet.")}});var $t,bo,ct,rs=q(()=>{"use strict";Si();$t=(n,e)=>{let r=xt(),t=r.lengthBytesUTF8(n)+1,i=r._malloc(t);return r.stringToUTF8(n,i,t),e.push(i),i},bo=(n,e,r,t)=>{if(typeof n=="object"&&n!==null){if(r.has(n))throw new Error("Circular reference in options");r.add(n)}Object.entries(n).forEach(([i,o])=>{let s=e?e+i:i;if(typeof o=="object")bo(o,s+".",r,t);else if(typeof o=="string"||typeof o=="number")t(s,o.toString());else if(typeof o=="boolean")t(s,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},ct=n=>{let e=xt(),r=e.stackSave();try{let t=e.stackAlloc(8);e._OrtGetLastError(t,t+4);let i=e.HEAP32[t/4],o=e.HEAPU32[t/4+1],s=o?e.UTF8ToString(o):"";throw new Error(`${n} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{e.stackRestore(r)}}});var lb,db=q(()=>{"use strict";Si();rs();lb=n=>{let e=xt(),r=0,t=[],i=n||{};try{if(n?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof n.logSeverityLevel!="number"||!Number.isInteger(n.logSeverityLevel)||n.logSeverityLevel<0||n.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${n.logSeverityLevel}`);if(n?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof n.logVerbosityLevel!="number"||!Number.isInteger(n.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${n.logVerbosityLevel}`);n?.terminate===void 0&&(i.terminate=!1);let o=0;return n?.tag!==void 0&&(o=$t(n.tag,t)),r=e._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,o),r===0&&ct("Can't create run options."),n?.extra!==void 0&&bo(n.extra,"",new WeakSet,(s,a)=>{let u=$t(s,t),d=$t(a,t);e._OrtAddRunConfigEntry(r,u,d)!==0&&ct(`Can't set a run config entry: ${s} - ${a}.`)}),[r,t]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),t.forEach(s=>e._free(s)),o}}});var mI,gI,yI,bI,cb,fb=q(()=>{"use strict";Si();rs();mI=n=>{switch(n){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${n}`)}},gI=n=>{switch(n){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${n}`)}},yI=n=>{n.extra||(n.extra={}),n.extra.session||(n.extra.session={});let e=n.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),n.executionProviders&&n.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(n.enableMemPattern=!1)},bI=(n,e,r)=>{for(let t of e){let i=typeof t=="string"?t:t.name;switch(i){case"webnn":if(i="WEBNN",typeof t!="string"){let s=t;if(s?.deviceType){let a=$t("deviceType",r),u=$t(s.deviceType,r);xt()._OrtAddSessionConfigEntry(n,a,u)!==0&&ct(`Can't set a session config entry: 'deviceType' - ${s.deviceType}.`)}if(s?.numThreads){let a=s.numThreads;(typeof a!="number"||!Number.isInteger(a)||a<0)&&(a=0);let u=$t("numThreads",r),d=$t(a.toString(),r);xt()._OrtAddSessionConfigEntry(n,u,d)!==0&&ct(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s?.powerPreference){let a=$t("powerPreference",r),u=$t(s.powerPreference,r);xt()._OrtAddSessionConfigEntry(n,a,u)!==0&&ct(`Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof t!="string"){let s=t;if(s?.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let a=$t("preferredLayout",r),u=$t(s.preferredLayout,r);xt()._OrtAddSessionConfigEntry(n,a,u)!==0&&ct(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let o=$t(i,r);xt()._OrtAppendExecutionProvider(n,o)!==0&&ct(`Can't append execution provider: ${i}.`)}},cb=n=>{let e=xt(),r=0,t=[],i=n||{};yI(i);try{let o=mI(i.graphOptimizationLevel??"all"),s=gI(i.executionMode??"sequential"),a=typeof i.logId=="string"?$t(i.logId,t):0,u=i.logSeverityLevel??2;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log serverity level is not valid: ${u}`);let d=i.logVerbosityLevel??0;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log verbosity level is not valid: ${d}`);let m=typeof i.optimizedModelFilePath=="string"?$t(i.optimizedModelFilePath,t):0;if(r=e._OrtCreateSessionOptions(o,!!i.enableCpuMemArena,!!i.enableMemPattern,s,!!i.enableProfiling,0,a,u,d,m),r===0&&ct("Can't create session options."),i.executionProviders&&bI(r,i.executionProviders,t),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let b=$t("enableGraphCapture",t),w=$t(i.enableGraphCapture.toString(),t);e._OrtAddSessionConfigEntry(r,b,w)!==0&&ct(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[b,w]of Object.entries(i.freeDimensionOverrides)){if(typeof b!="string")throw new Error(`free dimension override name must be a string: ${b}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let x=$t(b,t);e._OrtAddFreeDimensionOverride(r,x,w)!==0&&ct(`Can't set a free dimension override: ${b} - ${w}.`)}return i.extra!==void 0&&bo(i.extra,"",new WeakSet,(b,w)=>{let x=$t(b,t),$=$t(w,t);e._OrtAddSessionConfigEntry(r,x,$)!==0&&ct(`Can't set a session config entry: ${b} - ${w}.`)}),[r,t]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r),t.forEach(s=>e._free(s)),o}}});var el,dn,Ln,ns,vo,is,tl,Ne=q(()=>{"use strict";el=n=>{switch(n){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: ${n}`)}},dn=n=>{switch(n){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: ${n}`)}},Ln=n=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][n],ns=n=>{switch(n){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: ${n}`)}},vo=n=>{switch(n){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: ${n}`)}},is=n=>n==="float32"||n==="float16"||n==="int32"||n==="int64"||n==="uint32"||n==="uint8"||n==="bool",tl=n=>{switch(n){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: ${n}`)}}});var wo,rl=q(()=>{"use strict";wo=async n=>{if(typeof n=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(n))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(n),t=[];for await(let i of r)t.push(i);return new Uint8Array(Buffer.concat(t))}throw e}else{let e=await fetch(n);if(!e.ok)throw new Error(`failed to load external data file: ${n}`);let r=e.headers.get("Content-Length"),t=r?parseInt(r,10):0;if(t<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${n}, no response body.`);let i=e.body.getReader(),o;try{o=new ArrayBuffer(t)}catch(a){if(a instanceof RangeError){let u=Math.ceil(t/65536);o=new WebAssembly.Memory({initial:u,maximum:u}).buffer}else throw a}let s=0;for(;;){let{done:a,value:u}=await i.read();if(a)break;let d=u.byteLength;new Uint8Array(o,s,d).set(u),s+=d}return new Uint8Array(o,0,t)}}else return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n instanceof Uint8Array?n:new Uint8Array(n)}});var vI,wI,pb,hb,mb,_I,ft,cn=q(()=>{"use strict";Ne();vI=["V","I","W","E","F"],wI=(n,e)=>{console.log(`[${vI[n]},${new Date().toISOString()}]${e}`)},mb=(n,e)=>{pb=n,hb=e},_I=(n,e)=>{let r=vo(n),t=vo(pb);r>=t&&wI(r,typeof e=="function"?e():e)},ft=(...n)=>{hb&&_I(...n)}});var gb,yb=q(()=>{"use strict";Ne();gb=(n,e)=>new(ns(e))(n)});var os=q(()=>{"use strict"});var bb,nl,il,xI,$I,vb,al,ol,_b,xb=q(()=>{"use strict";cn();os();bb=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]]),nl=[],il=n=>Math.ceil(n/16)*16,xI=n=>{for(let e=0;e$I++,al=async(n,e,r,t)=>{let i=il(r),o=n.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=n.getCommandEncoder();n.endComputePass(),s.copyBufferToBuffer(e,0,o,0,i),n.flush(),await o.mapAsync(GPUMapMode.READ);let a=o.getMappedRange();if(t){let u=t();return u.set(new Uint8Array(a,0,r)),u}else return new Uint8Array(a.slice(0,r))}finally{o.destroy()}},ol=class{constructor(e){this.backend=e;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[r]of bb)nl.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[])}upload(e,r){let t=r.buffer,i=r.byteOffset,o=r.byteLength,s=il(o),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(a.originalSize!==o)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${o}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:s,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(t,i,o)),u.unmap();let m=this.backend.getCommandEncoder();this.backend.endComputePass(),m.copyBufferToBuffer(u,0,a.gpuData.buffer,0,s),ft("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(r);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=il(t.originalSize),s=this.backend.getCommandEncoder();this.backend.endComputePass(),s.copyBufferToBuffer(t.gpuData.buffer,0,i.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let i;if(t){if(i=this.externalBuffers.get(t),i===void 0)throw new Error("previous buffer is not registered");if(e===t)return ft("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`);this.externalBuffers.delete(t)}else i=vb();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:r}),this.externalBuffers.set(e,i),ft("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){let r=this.externalBuffers.get(e);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(e),ft("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=xI(e),i,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,s=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||s){let d=(o?this.freeBuffers:this.freeUniformBuffers).get(t);d?d.length>0?i=d.pop():i=this.backend.device.createBuffer({size:t,usage:r}):i=this.backend.device.createBuffer({size:t,usage:r})}else i=this.backend.device.createBuffer({size:t,usage:r});let a={id:vb(),type:0,buffer:i};return this.storageCache.set(a.id,{gpuData:a,originalSize:e}),ft("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`),a}get(e){return this.storageCache.get(e)?.gpuData}release(e){let r=this.storageCache.get(e);if(!r)throw new Error("releasing data does not exist");return ft("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("data does not exist");await al(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=bb.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e))}},_b=(...n)=>new ol(...n)});var sl,Ve,kt=q(()=>{"use strict";sl=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Ve=n=>new sl(n)});var ul,Ur,J,jn,as,ss,us,Ke=q(()=>{"use strict";ul=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Ur=class{static calcShape(e,r,t=!1){let i=e.length,o=r.length;if(i===0)return r;if(o===0)return e;let s=Math.max(e.length,r.length),a=new Array(s);if(t){if(i<2||o<2)return;let u=ul.calcMatMulShape([e[i-2],e[i-1]],[r[o-2],r[o-1]]);if(u===void 0)return;[a[s-2],a[s-1]]=u}for(let u=t?3:1;u<=s;u++){let d=i-u<0?1:e[i-u],m=o-u<0?1:r[o-u];if(d!==m&&d>1&&m>1)return;let b=Math.max(d,m);if(d&&m)a[s-u]=Math.max(d,m);else{if(b>1)return;a[s-u]=0}}return a}static isValidBroadcast(e,r){let t=e.length,i=r.length;if(t>i)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[i-o])return!1;return!0}},J=class n{static size(e){return n.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,r=4){let t=e.length;if(t===0)return[];let i=new Array(t),o=t-1;for(;o>=0;){if(e[o]%r===0){i[o]=e[o]/r;break}if(r%e[o]!==0)throw new Error("cannot convert shape");i[o]=1,r/=e[o],o--}for(o--;o>=0;o--)i[o]=e[o];return i}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 n.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 n.getSizeFromDimensionRange(e,0,r)}static getSizeFromDimensionRange(e,r,t){let i=1;for(let o=r;o=0;--i)t[i]=t[i+1]*e[i+1];return t}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(t=>this.normalizeAxis(t,r??e.length))}static sortBasedOnPerm(e,r){return r?r.map(t=>e[t]):e.slice().reverse()}static padShape(e,r){let t=e.length;return e.map((i,o)=>i+r[o]+r[o+t])}static areEqual(e,r){return e.length!==r.length?!1:e.every((t,i)=>t===r[i])}},jn=class n{static adjustPoolAttributes(e,r,t,i,o,s){if(!e&&t.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 a=0;a=t.length?t.push(r[a+2]):t[a]=r[a+2];for(let a=0;a=t[a]||s[a+t.length]>=t[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,r,t,i,o,s,a){if(a){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(i.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let u=0;u{"use strict";Ne();Ke();Un=64,dl=(n,e)=>{if(e===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(n){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: ${n}`)}},ut=(n,e=1)=>{let r=dl(n,e);return typeof r=="string"?r:r[0]},Ut=(n,e=1)=>{let r=dl(n,e);return typeof r=="string"?r:r[1]},pe=(...n)=>{let e=[];return n.forEach(r=>{r.length!==0&&e.push({type:12,data:r},{type:12,data:J.computeStrides(r)})}),e},dt=n=>n%4===0?4:n%2===0?2:1,Er=(n="f32",e,r="0")=>!e||e===1?`${n}(${r})`:`vec${e}<${n}>(${r})`,Fn=(n,e,r)=>n==="f32"?r:e===1?`f32(${r})`:`vec${e}(${r})`,Or=(n,e)=>e===4?`(${n}.x + ${n}.y + ${n}.z + ${n}.w)`:e===2?`(${n}.x + ${n}.y)`:e===3?`(${n}.x + ${n}.y + ${n}.z)`:n,ze=(n,e,r,t)=>n.startsWith("uniforms.")&&r>4?typeof e=="string"?t==="f16"?`${n}[(${e}) / 8][(${e}) % 8 / 4][(${e}) % 8 % 4]`:`${n}[(${e}) / 4][(${e}) % 4]`:t==="f16"?`${n}[${Math.floor(e/8)}][${Math.floor(e%8/4)}][${e%8%4}]`:`${n}[${Math.floor(e/4)}][${e%4}]`:r>1?`${n}[${e}]`:n,cl=(n,e,r,t,i)=>{let o=typeof r=="number",s=o?r:r.length,a=[...new Array(s).keys()],u=s<2?"u32":s<=4?`vec${s}`:`array`,d=dl(e,i),m=typeof d=="string"?d:d[1],b=typeof d=="string"?d:d[0],w={indices:u,value:m,storage:b,tensor:e},x=oe=>typeof oe=="string"?oe:`${oe}u`,$={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},I=o?"uniforms.":"",A=`${I}${n}_shape`,k=`${I}${n}_strides`,P="";for(let oe=0;oe ${w.indices} { + var indices: ${w.indices}; + var current = offset; + ${P} + return indices; + }`,U=oe=>($.offsetToIndices=!0,s<2?oe:`o2i_${n}(${oe})`),F=[];if(s>=2)for(let oe=s-1;oe>=0;oe--)F.push(`${ze(k,oe,s)} * (indices[${oe}])`);let Y=s<2?"":` + fn i2o_${n}(indices: ${w.indices}) -> u32 { + return ${F.join("+")}; + }`,ie=oe=>($.indicesToOffset=!0,s<2?oe:`i2o_${n}(${oe})`),ne=(...oe)=>s===0?"0u":`${w.indices}(${oe.map(x).join(",")})`,le=(oe,ve)=>s<2?`${oe}`:`${ze(oe,ve,s)}`,ge=(oe,ve,He)=>s<2?`${oe}=${He};`:`${ze(oe,ve,s)}=${He};`,se={},re=(oe,ve)=>{$.broadcastedIndicesToOffset=!0;let He=`${ve.name}broadcastedIndicesTo${n}Offset`;if(He in se)return`${He}(${oe})`;let Et=[];for(let wt=s-1;wt>=0;wt--){let bt=ve.indicesGet("outputIndices",wt+ve.rank-s);Et.push(`${le(k,wt)} * (${bt} % ${le(A,wt)})`)}return se[He]=`fn ${He}(outputIndices: ${ve.type.indices}) -> u32 { + return ${Et.length>0?Et.join("+"):"0u"}; + }`,`${He}(${oe})`},_e=(oe,ve)=>(()=>{if(w.storage===w.value)return`${n}[${oe}]=${ve};`;if(w.storage==="vec2"&&w.value==="i32")return`${n}[${oe}]=vec2(u32(${ve}), select(0u, 0xFFFFFFFFu, ${ve} < 0));`;if(w.storage==="vec2"&&w.value==="u32")return`${n}[${oe}]=vec2(u32(${ve}), 0u);`;if(w.storage==="u32"&&w.value==="vec4")return`${n}[${oe}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ve}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),Oe=oe=>(()=>{if(w.storage===w.value)return`${n}[${oe}]`;if(w.storage==="vec2"&&w.value==="i32")return`i32(${n}[${oe}].x)`;if(w.storage==="vec2"&&w.value==="u32")return`u32(${n}[${oe}].x)`;if(w.storage==="u32"&&w.value==="vec4")return`vec4(bool(${n}[${oe}] & 0xFFu), bool(${n}[${oe}] & 0xFF00u), bool(${n}[${oe}] & 0xFF0000u), bool(${n}[${oe}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),he=s<2?"":` + fn get_${n}ByIndices(indices: ${w.indices}) -> ${m} { + return ${Oe(`i2o_${n}(indices)`)}; + }`,$e=s<2?"":(()=>{let oe=a.map(He=>`d${He}: u32`).join(", "),ve=a.map(He=>`d${He}`).join(", ");return` + fn get_${n}(${oe}) -> ${m} { + return get_${n}ByIndices(${ne(ve)}); + }`})(),je=(...oe)=>{if(oe.length!==s)throw new Error(`indices length must be ${s}`);let ve=oe.map(x).join(",");return s===0?Oe("0u"):s===1?Oe(ve[0]):($.get=!0,$.getByIndices=!0,$.indicesToOffset=!0,`get_${n}(${ve})`)},Ue=oe=>s<2?Oe(oe):($.getByIndices=!0,$.indicesToOffset=!0,`get_${n}ByIndices(${oe})`),Be=s<2?"":` + fn set_${n}ByIndices(indices: ${w.indices}, value: ${m}) { + ${_e(`i2o_${n}(indices)`,"value")} + }`,Ae=s<2?"":(()=>{let oe=a.map(He=>`d${He}: u32`).join(", "),ve=a.map(He=>`d${He}`).join(", ");return` + fn set_${n}(${oe}, value: ${m}) { + set_${n}ByIndices(${ne(ve)}, value); + }`})();return{impl:()=>{let oe=[],ve=!1;return $.offsetToIndices&&(oe.push(z),ve=!0),$.indicesToOffset&&(oe.push(Y),ve=!0),$.broadcastedIndicesToOffset&&(Object.values(se).forEach(He=>oe.push(He)),ve=!0),$.set&&(oe.push(Ae),ve=!0),$.setByIndices&&(oe.push(Be),ve=!0),$.get&&(oe.push($e),ve=!0),$.getByIndices&&(oe.push(he),ve=!0),!o&&ve&&oe.unshift(`const ${A} = ${w.indices}(${r.join(",")});`,`const ${k} = ${w.indices}(${J.computeStrides(r).join(",")});`),oe.join(` +`)},type:w,offsetToIndices:U,indicesToOffset:ie,broadcastedIndicesToOffset:re,indices:ne,indicesGet:le,indicesSet:ge,set:(...oe)=>{if(oe.length!==s+1)throw new Error(`indices length must be ${s}`);let ve=oe[s];if(typeof ve!="string")throw new Error("value must be string");let He=oe.slice(0,s).map(x).join(",");return s===0?_e("0u",ve):s===1?_e(He[0],ve):($.set=!0,$.setByIndices=!0,$.indicesToOffset=!0,`set_${n}(${He}, ${ve})`)},setByOffset:_e,setByIndices:(oe,ve)=>s<2?_e(oe,ve):($.setByIndices=!0,$.indicesToOffset=!0,`set_${n}ByIndices(${oe}, ${ve});`),get:je,getByOffset:Oe,getByIndices:Ue,usage:t,name:n,strides:k,shape:A,rank:s}},ee=(n,e,r,t=1)=>cl(n,e,r,"input",t),de=(n,e,r,t=1)=>cl(n,e,r,"output",t),ls=(n,e,r,t=1)=>cl(n,e,r,"internal",t),ll=class{constructor(e,r){this.normalizedDispatchGroup=e;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Un){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],i=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,s=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,a=o?"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) * ${r*t*i}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${i}) + fn main(${s}) { + ${a} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",i=e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${i}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:i}of this.uniforms)if(i&&i>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(i/8)}>`):e.push(`${r}:array, ${Math.ceil(i/4)}>`);else{let o=i==null||i===1?t:`vec${i}<${t}>`;e.push(`${r}:${o}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},$b=(n,e)=>new ll(n,e),Ii=(n,e)=>{let r=n.length,t=[];for(let i=0;i1&&s===1&&t.unshift(o)}return t}});var TI,Tb,SI,II,vr,Sb,Ib,Ci=q(()=>{"use strict";Ne();Ke();kt();We();TI=n=>{if(!n||n.length!==1)throw new Error("Transpose requires 1 input.")},Tb=(n,e)=>e&&e.length!==n?[...new Array(n).keys()].reverse():e,SI=(n,e)=>J.sortBasedOnPerm(n,Tb(n.length,e)),II=(n,e,r,t)=>{let i=[];i.push(`fn perm(i: ${t.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let o=0;o{let r=n.dataType,t=n.dims.length,i=Tb(t,e),o=SI(n.dims,i),s=de("output",r,o.length),a=ee("a",r,t),u=d=>` + ${d.registerUniform("output_size","u32").declareVariables(a,s)} + + ${II(i,t,a,s)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${s.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${s.setByOffset("global_idx",a.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:["rank"]},getRunData:d=>{let m=J.size(o);return{outputs:[{dims:o,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...pe(d[0].dims,o)]}},getShaderSource:u}},Sb=(n,e)=>{TI(n.inputs),n.compute(vr(n.inputs[0],e.perm))},Ib=n=>Ve({perm:n.perm})});var CI,AI,EI,OI,PI,kI,DI,BI,RI,zI,Fr,Cb,Ab,Eb,Ob,Pb,kb,Db,Bb,Rb,zb,Mb=q(()=>{"use strict";Ne();Ke();We();ds();Ci();CI={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"},AI={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"},EI={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},OI={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},PI=(n,e)=>{let r=[];for(let t=e-n;t{let r=[],t=n.length;for(let o=0;on[o]);return[r,i]},DI=(n,e)=>{let r=n.length+e.length,t=[],i=0;for(let o=0;o{for(let r=0;r{let r=[];if(!BI(n,e)){for(let t=0;tr.push(t))}return r},zI=(n,e,r,t,i,o,s)=>{let a=r[0].dims,u=J.size(o),d=J.size(s),m=ee("_A",r[0].dataType,a),b=de("output",i,o),w=32,x=` + var aBestValues : array; + `;return{name:n,shaderCache:e,getShaderSource:I=>` + ${I.registerUniform("reduceSize","u32").declareVariables(m,b)} + ${x} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${I.mainStart(w)} + + let outputIndex = global_idx / ${w}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${EI[t]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${w}) { + let candidate = f32(${m.getByOffset("offset + k")}); + bestValue = ${CI[t]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${w}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 = ${AI[t]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${b.setByOffset("outputIndex",`${t==="mean"?`${b.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${b.type.storage}(${OI[t]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:u},programUniforms:[{type:12,data:d}]})}},Fr=(n,e,r,t)=>{let i=n.inputs.length===1?r:fl(n.inputs,r),o=i.axes;o.length===0&&!i.noopWithEmptyAxes&&(o=n.inputs[0].dims.map((x,$)=>$));let s=J.normalizeAxes(o,n.inputs[0].dims.length),a=s,u=n.inputs[0],d=RI(a,n.inputs[0].dims.length);d.length>0&&(u=n.compute(vr(n.inputs[0],d),{inputs:[0],outputs:[-1]})[0],a=PI(a.length,u.dims.length));let[m,b]=kI(u.dims,a),w=m;i.keepDims&&(w=DI(m,s)),n.compute(zI(e,{hint:i.cacheKey,inputDependencies:["type"]},[u],t,n.inputs[0].dataType,w,b),{inputs:[u]})},Cb=(n,e)=>{Fr(n,"ReduceMeanShared",e,"mean")},Ab=(n,e)=>{Fr(n,"ReduceL1Shared",e,"l1")},Eb=(n,e)=>{Fr(n,"ReduceL2Shared",e,"l2")},Ob=(n,e)=>{Fr(n,"ReduceLogSumExpShared",e,"logSumExp")},Pb=(n,e)=>{Fr(n,"ReduceMaxShared",e,"max")},kb=(n,e)=>{Fr(n,"ReduceMinShared",e,"min")},Db=(n,e)=>{Fr(n,"ReduceProdShared",e,"prod")},Bb=(n,e)=>{Fr(n,"ReduceSumShared",e,"sum")},Rb=(n,e)=>{Fr(n,"ReduceSumSquareShared",e,"sumSquare")},zb=(n,e)=>{Fr(n,"ReduceLogSumShared",e,"logSum")}});var Vr,MI,cs,fl,Gr,NI,LI,jI,UI,FI,VI,GI,WI,HI,qI,Wr,Nb,Lb,jb,Ub,Fb,Vb,Gb,Wb,Hb,qb,ds=q(()=>{"use strict";Ne();Ke();kt();We();Mb();Vr=n=>{if(!n||n.length===0||n.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(n.length===2&&n[1].dims.length!==1)throw new Error("Invalid axes input dims.")},MI=n=>["","",`var value = ${n.getByIndices("input_indices")};`,""],cs=(n,e,r,t,i,o,s=!1,a=!1)=>{let u=[],d=r[0].dims,m=d.length,b=J.normalizeAxes(i,m),w=!a&&b.length===0;d.forEach((A,k)=>{w||b.indexOf(k)>=0?s&&u.push(1):u.push(A)});let x=u.length,$=J.size(u);return{name:n,shaderCache:e,getShaderSource:A=>{let k=[],P=ee("_A",r[0].dataType,m),z=de("output",o,x),U=t(P,z,b),F=U[2];for(let Y=0,ie=0;Y=0?(s&&ie++,F=`for(var j${Y}: u32 = 0; j${Y} < ${d[Y]}; j${Y}++) { + ${U[2].includes("last_index")?`let last_index = j${Y};`:""} + ${P.indicesSet("input_indices",Y,`j${Y}`)} + ${F} + }`):(k.push(`${P.indicesSet("input_indices",Y,z.indicesGet("output_indices",ie))};`),ie++);return` + + ${A.registerUniform("output_size","u32").declareVariables(P,z)} + + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${P.type.indices}; + let output_indices = ${z.offsetToIndices("global_idx")}; + + ${k.join(` +`)} + ${U[0]} // init ops for reduce max/min + ${U[1]} + ${F} + ${U[3]} + ${U.length===4?z.setByOffset("global_idx","value"):U.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...pe(d,u)]})}},fl=(n,e)=>{let r=[];return n[1].dims[0]>0&&n[1].getBigInt64Array().forEach(t=>r.push(Number(t))),Ve({axes:r,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},Gr=(n,e,r,t)=>{let i=n.inputs,o=i.length===1?r:fl(i,r);n.compute(cs(e,{hint:o.cacheKey,inputDependencies:["rank"]},[i[0]],o.noopWithEmptyAxes&&o.axes.length===0?MI:t,o.axes,i[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},NI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceLogSum",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},LI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceL1",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},jI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceL2",e,(t,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},UI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceLogSumExp",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},FI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceMax",e,(t,i,o)=>{let s=[];for(let a=0;a=0||o.length===0)&&s.push(t.indicesSet("input_indices",a,0));return[`${s.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},VI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceMean",e,(t,i,o)=>{let s=1;for(let a=0;a=0||o.length===0)&&(s*=n.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${s});`]})},GI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceMin",e,(t,i,o)=>{let s=[];for(let a=0;a=0||o.length===0)&&s.push(`input_indices[${a}] = 0;`);return[`${s.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},WI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceProd",e,(t,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},HI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceSum",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},qI=(n,e)=>{Vr(n.inputs),Gr(n,"ReduceSumSquare",e,(t,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},Wr=(n,e,r)=>{if(e.length===0)return r;let t=1,i=1;for(let o=0;o1024},Nb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?VI(n,e):Cb(n,e)},Lb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?LI(n,e):Ab(n,e)},jb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?jI(n,e):Eb(n,e)},Ub=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?UI(n,e):Ob(n,e)},Fb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?FI(n,e):Pb(n,e)},Vb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?GI(n,e):kb(n,e)},Gb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?WI(n,e):Db(n,e)},Wb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?HI(n,e):Bb(n,e)},Hb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?qI(n,e):Rb(n,e)},qb=(n,e)=>{Wr(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?NI(n,e):zb(n,e)}});var Kb,Yb,Xb,pl,Zb=q(()=>{"use strict";Ne();kt();ds();Kb=n=>{if(!n||n.length===0||n.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(n[0].dataType!==1)throw new Error("Invalid input type.")},Yb=(n,e)=>{Kb(n.inputs);let r=(t,i,o)=>{let s=[];for(let a=0;a=0||o.length===0)&&s.push(`input_indices[${a}] = 0;`);return[`${s.join(` +`)}`,`var value = ${t.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${t.getByIndices("input_indices")} ${e.selectLastIndex>0?"<=":"<"} value) { + value = ${t.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};n.compute(cs("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},Xb=(n,e)=>{Kb(n.inputs);let r=(t,i,o)=>{let s=[];for(let a=0;a=0||o.length===0)&&s.push(`input_indices[${a}] = 0;`);return[`${s.join(` +`)}`,`var value = ${t.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${t.getByIndices("input_indices")} ${e.selectLastIndex>0?">=":">"} value) { + value = ${t.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};n.compute(cs("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],r,[e.axis],7,e.keepDims),{inputs:[0]})},pl=n=>Ve(n)});var KI,YI,XI,fs,Jb,Qb,hl=q(()=>{"use strict";Ne();Ke();kt();We();KI=(n,e)=>{if(!n||n.length<1)throw new Error("too few inputs");let r=0,t=n[r],i=t.dataType,o=t.dims.length;n.forEach((s,a)=>{if(a!==r){if(s.dataType!==i)throw new Error("input tensors should be one type");if(s.dims.length!==o)throw new Error("input tensors should have the same shape");s.dims.forEach((u,d)=>{if(d!==e&&u!==t.dims[d])throw new Error("non concat dimensions must match")})}})},YI=(n,e)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${e}); + for (var i: u32 = 0u; i < ${n}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${n}u; + }`,XI=(n,e)=>{let r=n.length,t=[];for(let i=0;i{let i=J.size(r),o=new Array(n.length),s=new Array(n.length),a=0,u=[],d=[],m=[{type:12,data:i}];for(let I=0;I`uniforms.sizeInConcatAxis${I}`).join(","),$=I=>` + + ${(()=>{I.registerUniform("outputSize","u32");for(let A=0;A(${x}); + ${w} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${XI(s,b)} + }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:t}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:m}),getShaderSource:$}},Jb=(n,e)=>{let r=n.inputs,t=r[0].dims,i=J.normalizeAxis(e.axis,t.length);KI(r,i);let o=t.slice();o[i]=r.reduce((a,u)=>a+(u.dims.length>i?u.dims[i]:0),0);let s=r.filter(a=>J.size(a.dims)>0);n.compute(fs(s,i,o,r[0].dataType),{inputs:s})},Qb=n=>Ve({axis:n.axis})});var ZI,JI,QI,eC,ps,tC,e0,ml=q(()=>{"use strict";Ne();os();We();hl();ZI=(n,e)=>{let r=n[0],t=n[1],i=n[2],o=n[3],s=n[4],a=n[5];if(s&&a)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 u=r.dims[0],d=r.dims[1],m=r.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(t.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(t.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==t.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let b=i.dims[0]/3,w=b,x=w;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let z of e.qkvHiddenSizes)if(z%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");b=e.qkvHiddenSizes[0],w=e.qkvHiddenSizes[1],x=e.qkvHiddenSizes[2]}let $=d;if(b!==w)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==b+w+x)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let I=0;if(s){if(w!==x)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(s.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(s.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==u)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==e.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==w/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(I=s.dims[3])}let A=$+I,k=-1,P=0;if(o)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");return{batchSize:u,sequenceLength:d,pastSequenceLength:I,kvSequenceLength:$,totalSequenceLength:A,maxSequenceLength:k,inputHiddenSize:m,hiddenSize:b,vHiddenSize:x,headSize:Math.floor(b/e.numHeads),vHeadSize:Math.floor(x/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:P,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},JI=(n,e,r,t)=>{let i=dt(t),o=64,s=t/i;s{let x=de("x",e.dataType,e.dims,i),I=[{name:"d_inv",type:Ut(e.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${w.registerUniforms(I).declareVariables(x)} + ${w.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 = ${m}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${m}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(i){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${i}`)}})()}; + 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 = ${m}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${m}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(i){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${i}`)}})()}; + 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] = ${x.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 = ${m}(x[offset + i]); + x[offset + i] = ${x.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${o};${d};${i}`},getShaderSource:b,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:u})}},QI=(n,e,r,t,i,o,s)=>{let a=s+i.kvSequenceLength,u=[i.batchSize,i.numHeads,i.sequenceLength,a],d=o.scale===0?1/Math.sqrt(i.headSize):o.scale,m=dt(i.headSize),b=i.headSize/m,w=12,x={x:Math.ceil(a/w),y:Math.ceil(i.sequenceLength/w),z:i.batchSize*i.numHeads},$=[{type:12,data:i.sequenceLength},{type:12,data:b},{type:12,data:a},{type:12,data:i.numHeads},{type:1,data:d}],I=["type","type"];t&&(I.push("rank"),$.push(...pe(t.dims)));let A=k=>{let P=ee("q",e.dataType,e.dims,m),z=ee("key",r.dataType,r.dims,m),U=[P,z],F=t?ee("relative_position_bias",t.dataType,t.dims.length):void 0;F&&U.push(F);let Y=de("output",e.dataType,u),ie=Ut(1,m),ne=[{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 = ${w}u; + + var tileQ: array<${P.type.storage}, ${w*w}>; + var tileK: array<${P.type.storage}, ${w*w}>; + ${k.registerUniforms(ne).declareVariables(...U,Y)} + ${k.mainStart([w,w,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 = ${ie}(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 += ${ie}(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(m){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: ${m}`)}})()}; + + ${(()=>F?` + let batch = workgroup_id.z / uniforms.num_heads; + let head = workgroup_id.z % uniforms.num_heads; + var indices = ${F.type.indices}(batch, head, global_id.y, global_id.x); + output[outputIdx] = ${Y.type.value}(sum * uniforms.alpha) + ${F.getByIndices("indices")};`:`output[outputIdx] = ${Y.type.value} (sum * uniforms.alpha);`)()} + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${m}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:u,dataType:e.dataType,gpuDataType:0}],dispatchGroup:x,programUniforms:$}),getShaderSource:A}},eC=(n,e,r,t,i)=>{let o=i+t.kvSequenceLength,s=[t.batchSize,t.sequenceLength,t.vHiddenSize],a=12,u={x:Math.ceil(t.vHeadSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[{type:12,data:t.sequenceLength},{type:12,data:o},{type:12,data:t.vHeadSize},{type:12,data:t.numHeads},{type:12,data:t.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:s,dataType:e.dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:d}),getShaderSource:w=>{let x=ee("probs",e.dataType,e.dims),$=ee("v",r.dataType,r.dims),I=de("output",e.dataType,s),A=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return` + const TILE_SIZE = ${a}u; + var tileQ: array<${x.type.value}, ${a*a}>; + var tileK: array<${x.type.value}, ${a*a}>; + ${w.registerUniforms(A).declareVariables(x,$,I)} + ${w.mainStart([a,a,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 = ${x.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; + } + }`}}},ps=(n,e,r,t,i,o,s,a,u,d,m)=>{let b=n.outputCount>1,w=n.outputCount>2,x=b&&w?d.pastSequenceLength:0,$=x+d.kvSequenceLength,I=[d.batchSize,d.numHeads,$,d.headSize],A=s?[s,r]:[r],k=b?n.compute(fs(A,2,I,r.dataType),{inputs:A,outputs:[1]})[0]:r,P=[d.batchSize,d.numHeads,$,d.headSize],z=a?[a,t]:[t],U=w?n.compute(fs(z,2,P,t.dataType),{inputs:z,outputs:[2]})[0]:t,F=[e,k];u&&F.push(u);let Y=n.compute(QI(n,e,k,u,d,m,x),{inputs:F,outputs:[-1]})[0];n.compute(JI(n,Y,d.batchSize*d.numHeads*d.sequenceLength,$),{inputs:[Y],outputs:[]});let ie=[Y,U];n.compute(eC(n,Y,U,d,x),{inputs:ie,outputs:[0]})},tC=(n,e)=>{let r=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],t=e.sequenceLength,i=e.inputHiddenSize,o=e.headSize,s=12,a={x:Math.ceil(e.headSize/s),y:Math.ceil(e.sequenceLength/s),z:e.batchSize*e.numHeads},u=[n.inputs[0],n.inputs[1],n.inputs[2]],d=[{type:12,data:t},{type:12,data:i},{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}],m=b=>{let w=de("output_q",u[0].dataType,r),x=de("output_k",u[0].dataType,r),$=de("output_v",u[0].dataType,r),I=ee("input",u[0].dataType,u[0].dims),A=ee("weight",u[1].dataType,u[1].dims),k=ee("bias",u[2].dataType,u[2].dims),P=I.type.storage,z=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${s}u; + var tileInput: array<${P}, ${s*s}>; + var tileWeightQ: array<${P}, ${s*s}>; + var tileWeightK: array<${P}, ${s*s}>; + var tileWeightV: array<${P}, ${s*s}>; + ${b.registerUniforms(z).declareVariables(I,A,k,w,x,$)} + ${b.mainStart([s,s,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 = ${P}(0); + var valueK = ${P}(0); + var valueV = ${P}(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:n.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:n.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:d}),getShaderSource:m},{inputs:u,outputs:[-1,-1,-1]})},e0=(n,e)=>{let r=ZI(n.inputs,e),[t,i,o]=tC(n,r);return ps(n,t,i,o,n.inputs[4],void 0,void 0,void 0,n.inputs[5],r,e)}});var rC,nC,iC,t0,r0=q(()=>{"use strict";Lt();Ne();Ke();kt();We();rC=(n,e)=>{if(!n||n.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(t,i,o)=>{let s=i.length;if(s!==t.length)throw new Error(`${o}: num dimensions != ${s}`);i.forEach((a,u)=>{if(a!==t[u])throw new Error(`${o}: dim[${u}] do not match`)})};if(n[0].dims.length>1){let t=e.format==="NHWC"?e.spatial?n[0].dims.slice(-1):n[0].dims.slice(-1).concat(n[0].dims.slice(1,n[0].dims.length-1)):n[0].dims.slice(1,e.spatial?2:void 0);r(n[1].dims,t,"Invalid input scale"),r(n[2].dims,t,"Invalid input B"),r(n[3].dims,t,"Invalid input mean"),r(n[4].dims,t,"Invalid input var")}else r(n[1].dims,[1],"Invalid input scale"),r(n[2].dims,[1],"Invalid input B"),r(n[3].dims,[1],"Invalid input mean"),r(n[4].dims,[1],"Invalid input var")},nC=(n,e)=>{let{epsilon:r,spatial:t,format:i}=e,o=n[0].dims,s=t?dt(o[o.length-1]):1,a=i==="NHWC"&&o.length>1?s:1,u=J.size(o)/s,d=t,m=d?o.length:o,b=ee("x",n[0].dataType,n[0].dims,s),w=ee("scale",n[1].dataType,n[1].dims,a),x=ee("bias",n[2].dataType,n[2].dims,a),$=ee("inputMean",n[3].dataType,n[3].dims,a),I=ee("inputVar",n[4].dataType,n[4].dims,a),A=de("y",n[0].dataType,m,s),k=()=>{let z="";if(t)z=`let cOffset = ${o.length===1?"0u":i==="NHWC"?`outputIndices[${o.length-1}] / ${s}`:"outputIndices[1]"};`;else if(i==="NCHW")z=` + ${A.indicesSet("outputIndices","0","0")} + let cOffset = ${A.indicesToOffset("outputIndices")};`;else{z=`var cIndices = ${w.type.indices}(0); + cIndices[0] = outputIndices[${o.length-1}];`;for(let U=1;U` + const epsilon = ${r}; + ${z.registerUniform("outputSize","u32").declareVariables(b,w,x,$,I,A)} + ${z.mainStart()} + ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${A.offsetToIndices(`global_idx * ${s}`)}; + ${k()} + let scale = ${w.getByOffset("cOffset")}; + let bias = ${x.getByOffset("cOffset")}; + let inputMean = ${$.getByOffset("cOffset")}; + let inputVar = ${I.getByOffset("cOffset")}; + let x = ${b.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${A.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${e.epsilon}_${e.format}_${t}_${s}`,inputDependencies:d?["rank","type","type","type","type"]:void 0},getShaderSource:P,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d?[{type:12,data:u},...pe(o)]:[{type:12,data:u}]})}},iC=n=>Ve(n),t0=(n,e)=>{let{inputs:r,outputCount:t}=n,i=iC({...e,outputCount:t});if(De.webgpu.validateInputContent&&rC(r,i),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");n.compute(nC(r,i))}});var oC,aC,n0,i0=q(()=>{"use strict";Ke();We();oC=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(n[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},aC=n=>{let e=n[0].dims,r=n[0].dims[2],t=J.size(e)/4,i=n[0].dataType,o=ee("input",i,e,4),s=ee("bias",i,[r],4),a=ee("residual",i,e,4),u=de("output",i,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)}}),getShaderSource:m=>` + const channels = ${r}u / 4; + ${m.declareVariables(o,s,a,u)} + + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes(t)} + let value = ${o.getByOffset("global_idx")} + + ${s.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${u.setByOffset("global_idx","value")} + }`}},n0=n=>{oC(n.inputs),n.compute(aC(n.inputs))}});var sC,ot,o0,a0,s0,u0,l0,d0,c0,f0,p0,uC,h0,m0,g0,y0,hs,b0,ms,v0,w0,_0,x0,$0,T0,S0,I0,C0,A0,E0,O0,P0,k0,D0,B0,R0,z0,gl,yl,M0,N0,L0,gs=q(()=>{"use strict";Ne();Ke();kt();We();sC=(n,e,r,t,i,o)=>{let s=Math.ceil(e/4),a="";typeof i=="string"?a=`${i}(a)`:a=i("a");let u=ee("inputData",r,[s],4),d=de("outputData",t,[s],4);return` + ${n.registerUniform("vec_size","u32").declareVariables(u,d)} + + ${o??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${d.setByOffset("global_idx",a)} + }`},ot=(n,e,r,t,i,o=n.dataType)=>({name:e,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:s=>sC(s,J.size(n.dims),n.dataType,o,r,t),getRunData:s=>({outputs:[{dims:n.dims,dataType:o}],dispatchGroup:{x:Math.ceil(J.size(s[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(J.size(n.dims)/4)}]})}),o0=n=>{n.compute(ot(n.inputs[0],"Abs","abs"))},a0=n=>{n.compute(ot(n.inputs[0],"Acos","acos"))},s0=n=>{n.compute(ot(n.inputs[0],"Acosh","acosh"))},u0=n=>{n.compute(ot(n.inputs[0],"Asin","asin"))},l0=n=>{n.compute(ot(n.inputs[0],"Asinh","asinh"))},d0=n=>{n.compute(ot(n.inputs[0],"Atan","atan"))},c0=n=>{n.compute(ot(n.inputs[0],"Atanh","atanh"))},f0=n=>Ve(n),p0=(n,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}`)}n.compute(ot(n.inputs[0],"Cast",r,void 0,e.cacheKey,e.to))},uC=n=>{let e=n.length>=2&&n[1].data!==0?n[1].getFloat32Array()[0]:ss,r=n.length>=3&&n[2].data!==0?n[2].getFloat32Array()[0]:us;return Ve({min:e,max:r})},h0=(n,e)=>{let r=n.inputs.length===1?e:uC(n.inputs),t=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"Clip",i=>`clamp(${i}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${t}> = vec4(${t}(${r.min})); + const clip_max_: vec4<${t}> = vec4(${t}(${r.max})); +`,r.cacheKey),{inputs:[0]})},m0=n=>{n.compute(ot(n.inputs[0],"Ceil","ceil"))},g0=n=>{n.compute(ot(n.inputs[0],"Cos","cos"))},y0=n=>{n.compute(ot(n.inputs[0],"Cosh","cosh"))},hs=n=>Ve(n),b0=(n,e)=>{let r=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"Elu",t=>`elu_vf32(${t})`,` + 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))},ms=(n="f32")=>` +const r0: ${n} = 0.3275911; +const r1: ${n} = 0.254829592; +const r2: ${n} = -0.284496736; +const r3: ${n} = 1.421413741; +const r4: ${n} = -1.453152027; +const r5: ${n} = 1.061405429; + +fn erf_vf32(v: vec4<${n}>) -> vec4<${n}> { + 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)); +}`,v0=n=>{let e=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"Erf",r=>`erf_vf32(${r})`,ms(e)))},w0=n=>{n.compute(ot(n.inputs[0],"Exp","exp"))},_0=n=>{n.compute(ot(n.inputs[0],"Floor","floor"))},x0=n=>{let e=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,ms(e)))},$0=(n,e)=>{let r=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"LeakyRelu",t=>`select(leaky_relu_alpha_ * ${t}, ${t}, ${t} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${e.alpha});`,e.cacheKey))},T0=n=>{n.compute(ot(n.inputs[0],"Not",e=>`!${e}`))},S0=n=>{n.compute(ot(n.inputs[0],"Neg",e=>`-${e}`))},I0=n=>{n.compute(ot(n.inputs[0],"Reciprocal",e=>`1.0/${e}`))},C0=n=>{let e=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"Relu",r=>`select(vec4<${e}>(0.0), ${r}, ${r} > vec4<${e}>(0.0))`))},A0=n=>{n.compute(ot(n.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},E0=n=>Ve(n),O0=(n,e)=>{let r=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"HardSigmoid",t=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${e.alpha} * ${t} + vec4<${r}>(${e.beta})))`,void 0,e.cacheKey))},P0=n=>{n.compute(ot(n.inputs[0],"Sin","sin"))},k0=n=>{n.compute(ot(n.inputs[0],"Sinh","sinh"))},D0=n=>{n.compute(ot(n.inputs[0],"Sqrt","sqrt"))},B0=n=>{n.compute(ot(n.inputs[0],"Tan","tan"))},R0=n=>`sign(${n}) * (1 - exp(-2 * abs(${n}))) / (1 + exp(-2 * abs(${n})))`,z0=n=>{n.compute(ot(n.inputs[0],"Tanh",R0))},gl=(n="f32")=>` +const fast_gelu_a: ${n} = 0.5; +const fast_gelu_b: ${n} = 0.7978845608028654; +const fast_gelu_c: ${n} = 0.035677408136300125; + +fn tanh_v(v: vec4<${n}>) -> vec4<${n}> { + return ${R0("v")}; +} +`,yl=n=>`(fast_gelu_a + fast_gelu_a * tanh_v(${n} * (fast_gelu_c * ${n} * ${n} + fast_gelu_b))) * ${n}`,M0=n=>{let e=Ut(n.inputs[0].dataType);n.compute(ot(n.inputs[0],"FastGelu",yl,gl(e),void 0,n.inputs[0].dataType))},N0=(n,e)=>{let r=Ut(n.inputs[0].dataType);return n.compute(ot(n.inputs[0],"ThresholdedRelu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${e.alpha});`,e.cacheKey)),0},L0=n=>{n.compute(ot(n.inputs[0],"Log","log"))}});var lC,dC,U0,F0=q(()=>{"use strict";Ke();We();gs();lC=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(n[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},dC=n=>{let e=n[0].dims.slice();e[2]=e[2]/2;let r=ee("input",n[0].dataType,n[0].dims,4),t=ee("bias",n[0].dataType,[n[0].dims[2]],4),i=de("output",n[0].dataType,e,4),o=J.size(e)/4,s=ut(n[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:e,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${n[0].dims[2]/4/2}u; + + ${u.declareVariables(r,t,i)} + + ${ms(s)} + + ${u.mainStart()} + ${u.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); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},U0=n=>{lC(n.inputs),n.compute(dC(n.inputs))}});var cC,fC,Hr,V0,G0,W0,H0,q0,K0,Y0,X0,Z0,J0,Q0=q(()=>{"use strict";Ne();Ke();We();cC=(n,e,r,t,i,o,s,a,u,d,m,b)=>{let w,x;typeof a=="string"?w=x=(P,z)=>`${a}((${P}),(${z}))`:typeof a=="function"?w=x=a:(w=a.scalar,x=a.vector);let $=de("outputData",m,t.length,4),I=ee("aData",u,e.length,4),A=ee("bData",d,r.length,4),k;if(i)if(o){let P=J.size(e)===1,z=J.size(r)===1,U=e.length>0&&e[e.length-1]%4===0,F=r.length>0&&r[r.length-1]%4===0;P||z?k=$.setByOffset("global_idx",x(P?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"),z?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):k=` + let outputIndices = ${$.offsetToIndices("global_idx * 4u")}; + let offsetA = ${I.broadcastedIndicesToOffset("outputIndices",$)}; + let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",$)}; + ${$.setByOffset("global_idx",x(s||U?I.getByOffset("offsetA / 4u"):`${I.type.value}(${I.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||F?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else k=$.setByOffset("global_idx",x(I.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let P=(z,U,F="")=>{let Y=`aData[indexA${U}][componentA${U}]`,ie=`bData[indexB${U}][componentB${U}]`;return` + let outputIndices${U} = ${$.offsetToIndices(`global_idx * 4u + ${U}u`)}; + let offsetA${U} = ${I.broadcastedIndicesToOffset(`outputIndices${U}`,$)}; + let offsetB${U} = ${A.broadcastedIndicesToOffset(`outputIndices${U}`,$)}; + let indexA${U} = offsetA${U} / 4u; + let indexB${U} = offsetB${U} / 4u; + let componentA${U} = offsetA${U} % 4u; + let componentB${U} = offsetB${U} % 4u; + ${z}[${U}] = ${F}(${w(Y,ie)}); + `};m===9?k=` + var data = vec4(0); + ${P("data",0,"u32")} + ${P("data",1,"u32")} + ${P("data",2,"u32")} + ${P("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:k=` + ${P("outputData[global_idx]",0)} + ${P("outputData[global_idx]",1)} + ${P("outputData[global_idx]",2)} + ${P("outputData[global_idx]",3)} + `}return` + ${n.registerUniform("vec_size","u32").declareVariables(I,A,$)} + + ${b??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${k} + }`},fC=(n,e,r,t,i,o,s=r.dataType)=>{let a=!J.areEqual(r.dims,t.dims),u=r.dims,d=J.size(r.dims),m=!1,b=!1,w=[a];if(a){let x=Ur.calcShape(r.dims,t.dims,!1);if(!x)throw new Error("Can't perform binary op on the given tensors");u=x,d=J.size(u);let $=J.size(r.dims)===1,I=J.size(t.dims)===1,A=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,k=t.dims.length>0&&t.dims[t.dims.length-1]%4===0;w.push($),w.push(I),w.push(A),w.push(k);let P=1;for(let z=1;zx.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:x=>cC(x,r.dims,t.dims,u,m,a,b,i,r.dataType,t.dataType,s,o),getRunData:()=>({outputs:[{dims:u,dataType:s}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(J.size(u)/4)},...pe(r.dims,t.dims,u)]})}},Hr=(n,e,r,t,i,o)=>{n.compute(fC(e,i??"",n.inputs[0],n.inputs[1],r,t,o))},V0=n=>{Hr(n,"Add",(e,r)=>`${e}+${r}`)},G0=n=>{Hr(n,"Div",(e,r)=>`${e}/${r}`)},W0=n=>{Hr(n,"Equal",{scalar:(e,r)=>`u32(${e}==${r})`,vector:(e,r)=>`vec4(${e}==${r})`},void 0,void 0,9)},H0=n=>{Hr(n,"Mul",(e,r)=>`${e}*${r}`)},q0=n=>{let e=ee("input",n.inputs[0].dataType,n.inputs[0].dims).type.value;Hr(n,"Pow",{scalar:(t,i)=>`pow_custom(${t},${i})`,vector:(t,i)=>`pow_vector_custom(${t},${i})`},` + 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)); + } + `)},K0=n=>{Hr(n,"Sub",(e,r)=>`${e}-${r}`)},Y0=n=>{Hr(n,"Greater",{scalar:(e,r)=>`u32(${e}>${r})`,vector:(e,r)=>`vec4(${e}>${r})`},void 0,void 0,9)},X0=n=>{Hr(n,"Less",{scalar:(e,r)=>`u32(${e}<${r})`,vector:(e,r)=>`vec4(${e}<${r})`},void 0,void 0,9)},Z0=n=>{Hr(n,"GreaterOrEqual",{scalar:(e,r)=>`u32(${e}>=${r})`,vector:(e,r)=>`vec4(${e}>=${r})`},void 0,void 0,9)},J0=n=>{Hr(n,"LessOrEqual",{scalar:(e,r)=>`u32(${e}<=${r})`,vector:(e,r)=>`vec4(${e}<=${r})`},void 0,void 0,9)}});var Pr,kr,Dr,ys,fn=q(()=>{"use strict";Ne();Ke();Pr=(n,e,r="f32")=>{switch(n.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 ${n.activation}`)}},kr=(n,e)=>{n.activation==="Clip"?e.push({type:1,data:n.clipMax},{type:1,data:n.clipMin}):n.activation==="HardSigmoid"?e.push({type:1,data:n.alpha},{type:1,data:n.beta}):n.activation==="LeakyRelu"&&e.push({type:1,data:n.alpha})},Dr=(n,e)=>{n.activation==="Clip"?e.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):n.activation==="HardSigmoid"?e.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):n.activation==="LeakyRelu"&&e.push({name:"alpha",type:"f32"})},ys=n=>{let e=n?.activation||"";if(e==="HardSigmoid"){let[r,t]=n?.activation_params||[.2,.5];return{activation:e,alpha:r,beta:t}}else if(e==="Clip"){let[r,t]=n?.activation_params||[ss,us];return{activation:e,clipMax:t,clipMin:r}}else if(e==="LeakyRelu"){let[r]=n?.activation_params||[.01];return{activation:e,alpha:r}}return{activation:e}}});var Ft,bs,vs=q(()=>{"use strict";Ft=(n,e)=>{switch(n){case 1:return e;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${n}-component is not supported.`)}},bs=n=>` + ${n?"value = value + getBiasByOutputCoords(coords);":""} + `});var ws,bl=q(()=>{"use strict";ws=n=>` +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(${n}.x), i32(${n}.y), i32(${n}.z), 1)); +} +`});var hC,mC,_o,ev,gC,xo,yC,_s,$o=q(()=>{"use strict";Ne();Ke();We();fn();vs();hC=(n,e)=>n?` + 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":""}); + `,mC=(n,e)=>n?` + 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];"} + }`,_o=(n,e,r="f32",t,i=!1,o=32,s=!1,a=32)=>{let u=e[1]*n[1],d=e[0]*n[0],m=i?u:o,b=i?o:u,w=m/e[0],x=o/e[1];if(!((i&&w===4&&n[1]===4||!i&&(w===3||w===4))&&m%e[0]===0&&o%e[1]===0&&n[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${w} and workPerThread[1] ${n[1]} must be 4. + Otherwise, innerElementSize ${w} must be 3 or 4. + tileAWidth ${m} must be divisible by workgroupSize[0]${e[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${n[0]} must be 4.`);return` +var mm_Asub: array, ${m/w}>, ${b}>; +var mm_Bsub: array, ${d/n[0]}>, ${o}>; + +const rowPerThread = ${n[1]}; +const colPerThread = ${n[0]}; +const innerElementSize = ${w}; +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 = ${s?"0":"i32(globalId.z)"}; + ${t?`let batchIndices = ${t.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${u}; + + let num_tiles = ${s?`${Math.ceil(a/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${s?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${x}; + 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; + ${hC(i,t)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${x}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${t?", 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]; + ${w===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${mC(i,w)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},ev=(n,e)=>n?` + 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":""}); + `,gC=n=>n?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",xo=(n,e,r="f32",t,i=!1,o=32,s=!1,a=32,u=!1)=>{let d=n[1]*e[1],m=n[0]*e[0],b=i?d:o,w=i?o:d;if(!(w%e[1]===0&&b%e[0]===0&&o%e[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${b} must be divisible by workgroupSize[0]${e[0]}, tileInner ${o} must be divisible by workgroupSize[1]${e[1]}`);let x=w/e[1],$=b/e[0],I=o/e[1],A=u?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${d}; + let globalColStart = i32(workgroupId.x) * ${m}; + + // 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 < ${w}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${b}; inputCol = inputCol + ${e[0]}) { + ${ev(i,t)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${e[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${t?", 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 = ${i?`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) * ${d}; + +let tileRowA = i32(localId.y) * ${x}; +let tileColA = i32(localId.x) * ${$}; +let tileRowB = i32(localId.y) * ${I}; +// 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 < ${x}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${$}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${ev(i,t)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${I}; 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${t?", 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) { + ${gC(i)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${w}>; + var mm_Bsub : array, ${o}>; + const rowPerThread = ${n[1]}; + const colPerThread = ${n[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 = ${s?"0":"i32(globalId.z)"}; + ${t?`let batchIndices = ${t.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${s?`${Math.ceil(a/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${s?`i32(globalId.z) * ${a}`:"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; + } + } + ${A} + } +`},yC=(n,e,r,t,i,o=!1)=>{let[s,a,u]=i,[d,m,b,w]=t,x=Ii(s,u),$=Ii(a,u),I=ut(t[0].type.tensor),A=()=>{let z=m.rank,U=d.rank,F=`var aIndices: ${m.type.indices};`;for(let Y=z-2-1,ie=U-1;Y>=0;Y--,ie--)F+=` +aIndices[${Y}] = ${U>1?`batchIndices[${ie}]`:"batchIndices"};`;return x.forEach(Y=>{F+=` +aIndices[${Y}] = 0;`}),F+=` +aIndices[${z-2}] = u32(row); + aIndices[${z-1}] = u32(colIn);`,F},k=()=>{let z=b.rank,U=d.rank,F=`var bIndices: ${b.type.indices};`;for(let Y=z-2-1,ie=U-1;Y>=0;Y--,ie--)F+=` +bIndices[${Y}] = ${U>1?`batchIndices[${ie}]`:"batchIndices"};`;return $.forEach(Y=>{F+=` +bIndices[${Y}] = 0;`}),F+=` +bIndices[${z-2}] = u32(row); + bIndices[${z-1}] = u32(colIn);`,F};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${Ft(n,I)} { + var value = ${Ft(n,I)}(0.0); + let col = colIn * ${n}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${A()} + value = ${m.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${Ft(n,I)} { + var value = ${Ft(n,I)}(0.0); + let col = colIn * ${n}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${k()} + value = ${b.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ft(n,I)}) { + let col = colIn * ${n}; + 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]":`${Ft(n,I)}(bias[row])`};`:""} + ${r} + ${w.setByIndices("vec3(coords)","value")} + } + } + `},_s=(n,e,r,t,i=!1)=>{let o=n[0].dims,s=n[1].dims,a=o.slice(0,-2),u=s.slice(0,-2),d=t?t.slice(0,-2):r.slice(0,-2),m=J.size(d),b=o[o.length-2],w=o[o.length-1],x=s[s.length-1],$=w%4===0&&x%4===0,I=b<=8?[4,1,1]:[4,4,1],A=[8,8,1],k=[Math.ceil(x/A[0]/I[0]),Math.ceil(b/A[1]/I[1]),Math.ceil(m/A[2]/I[2])],P=$?4:1,z=[...a,b,w/P],U=z.length,F=[...u,w,x/P],Y=F.length,ie=[m,b,x/P],ne=[{type:6,data:b},{type:6,data:x},{type:6,data:w}];kr(e,ne),ne.push(...pe(d,z,F));let le=["rank","rank"],ge=n.length>2;ge&&(ne.push(...pe(n[2].dims)),le.push("rank")),ne.push(...pe(ie));let se=re=>{let _e=d.length,Oe=ls("batchDims",n[0].dataType,_e,1),he=ut(n[0].dataType),$e=ee("a",n[0].dataType,U,P),je=ee("b",n[1].dataType,Y,P),Ue=de("result",n[0].dataType,ie.length,P),Be=[$e,je];if(ge){let oe=i?P:1;Be.push(ee("bias",n[2].dataType,n[2].dims.length,oe))}let Ae=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Dr(e,Ae);let Le=ut(Ue.type.tensor),Pe=Pr(e,Ue.type.value,Le),Tt=yC(P,ge,Pe,[Oe,$e,je,Ue],[a,u,d],i);return` + ${re.registerUniforms(Ae).registerInternalVariables(Oe).declareVariables(...Be,Ue)} + ${Tt} + ${$?_o(I,A,he,Oe):xo(I,A,he,Oe)} + `};return{name:"MatMul",shaderCache:{hint:`${I};${e.activation};${$};${i}`,inputDependencies:le},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:k[0],y:k[1],z:k[2]},programUniforms:ne}),getShaderSource:se}}});var bC,tv,rv=q(()=>{"use strict";Ne();cn();We();fn();vs();bl();$o();bC=(n,e,r,t,i=!1,o,s=4,a=4,u=4,d="f32")=>{let m=ge=>{switch(ge){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${d}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${ge} is not supported.`)}},b=ge=>{switch(ge){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 ${ge} is not supported.`)}},w=n?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,x=n?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,$=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",I=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=n?"row":"col",k=n?"col":"row",P=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${A} / outWidth; + let outCol = ${A} % outWidth; + + let WRow = ${k} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${k} / 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 = ${k} % inChannels; + var resData = ${Ft(s,d)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${$} && xCol >= 0 && xCol < ${I}) { + ${w} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${m(s)} + } + return resData;`,z=n?e&&t?` + let col = colIn * ${s}; + ${P}`:` + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${P} + } + return ${Ft(s,d)}(0.0);`:t&&r?` + let col = colIn * ${s}; + ${P}`:` + let col = colIn * ${s}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${P} + } + return ${Ft(s,d)}(0.0);`,U=`${b(a)}`,F=Ft(u,d),Y=n?Ft(s,d):Ft(a,d),ie=n?Ft(a,d):Ft(s,d),ne=Pr(o,F,d);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Y} { + ${n?z:U} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${ie} { + ${n?U:z} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${F}) { + let col = colIn * ${u}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${x} + ${bs(i)} + ${ne} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},tv=(n,e,r,t,i,o,s,a)=>{let u=e.format==="NHWC",d=u?n[0].dims[3]:n[0].dims[1],m=r[0],b=u?r[2]:r[3],w=u?r[1]:r[2],x=u?r[3]:r[1],$=u&&(d%4===0||d%3===0)&&x%4===0,I=u?x:b*w,A=u?b*w:x,k=[8,8,1],P=t<=8?[4,1,1]:[4,4,1],z=[Math.ceil(I/k[0]/P[0]),Math.ceil(A/k[1]/P[1]),Math.ceil(m/k[2]/P[2])];ft("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${z}`);let U=$?u&&d%4!==0?3:4:1,F=k[1]*P[1],Y=k[0]*P[0],ie=Math.max(k[0]*U,k[1]),ne=t%F===0,le=i%Y===0,ge=o%ie===0,se=$?[U,4,4]:[1,1,1],re=[{type:6,data:t},{type:6,data:i},{type:6,data:o},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];kr(e,re),re.push(...pe(n[0].dims,n[1].dims));let _e=["rank","rank"];s&&(re.push(...pe(n[2].dims)),_e.push("rank")),re.push(...pe(r));let Oe=he=>{let $e=[{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}];Dr(e,$e);let je=$?4:1,Ue=ut(n[0].dataType),Be=` + fn setOutputAtIndex(flatIndex : i32, value : ${$?`vec4<${Ue}>`:Ue}) { + result[flatIndex] = ${$?`vec4<${Ue}>`:Ue}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${$?`vec4<${Ue}>`:Ue}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${$?"/ 4":""}, value); + }`,Ae=ee("x",n[0].dataType,n[0].dims.length,U===3?1:U),Le=ee("w",n[1].dataType,n[1].dims.length,je),Pe=[Ae,Le],Tt=de("result",n[0].dataType,r.length,je);if(s){let oe=ee("bias",n[2].dataType,n[2].dims.length,je);Pe.push(oe),Be+=` + fn getBiasByOutputCoords(coords : vec4) -> ${$?`vec4<${Ue}>`:Ue} { + return bias[coords.${u?"w":"y"}${$?"/ 4":""}]; + }`}return` + ${ws("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 }; + ${he.registerUniforms($e).declareVariables(...Pe,Tt)} + ${Be} + ${bC(u,ne,le,ge,s,e,se[0],se[1],se[2],Ue)} + ${$?_o(P,k,Ue,void 0,!u,ie):xo(P,k,Ue,void 0,!u,ie,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${U};${$};${ne};${le};${ge};${F};${Y};${ie}`,inputDependencies:_e},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:z[0],y:z[1],z:z[2]},programUniforms:re}),getShaderSource:Oe}}});var vl,nv,iv=q(()=>{"use strict";Ne();Ke();We();wl();fn();vl=(n,e,r)=>{let t=n.length>2,i=t?"value += b[output_channel];":"",o=n[0].dims,s=n[1].dims,a=s[0]/e.group,u=e.format==="NHWC",d=xs(o,s,e.dilations,e.pads,e.strides,u),m=J.size(d),b=[{type:12,data:m},{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:a}];kr(e,b),b.push(...pe(o,s));let w=["rank","rank"];t&&(b.push(...pe(n[2].dims)),w.push("rank")),b.push(...pe(d));let x=$=>{let I=de("output",n[0].dataType,d.length),A=ut(I.type.tensor),k=Pr(e,I.type.value,A),P=ee("x",n[0].dataType,o.length),z=ee("w",n[1].dataType,s.length),U=[P,z];t&&U.push(ee("b",n[2].dataType,n[2].dims.length));let F=[{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 Dr(e,F),` + ${$.registerUniforms(F).declareVariables(...U,I)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${I.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${u?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${u?1:2}], outputIndices[${u?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${I.type.value} = ${I.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[${u?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[${u?2:3}]) { + continue; + } + + let xVal = ${u?P.get("batch","xHeight","xWidth","input_channel"):P.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${z.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${i} + ${k} + ${I.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:e.cacheKey,inputDependencies:w},getRunData:()=>({outputs:[{dims:r?r(d):d,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:b}),getShaderSource:x}},nv=(n,e,r)=>{let t=n.length>2,i=dt(r[3]),o=dt(r[2]),s=J.size(r)/i/o,a=[n[0].dims[0],n[0].dims[1],n[0].dims[2],n[0].dims[3]/i],u=[n[1].dims[0],n[1].dims[1],n[1].dims[2],n[1].dims[3]/i],d=[r[0],r[1],r[2],r[3]/i],m=[{type:12,data:s},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];kr(e,m),m.push(...pe(a,u,d));let b=(o-1)*e.strides[1]+u[1],w=x=>{let $=de("output",n[0].dataType,d.length,i),I=ut($.type.tensor),A=Pr(e,$.type.value,I),k=ee("x",n[0].dataType,a.length,i),P=ee("w",n[1].dataType,u.length,i),z=[k,P];t&&z.push(ee("b",n[2].dataType,n[2].dims,i));let U=t?"value += b[output_channel];":"",F=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Dr(e,F),` + ${x.registerUniforms(F).declareVariables(...z,$)} + ${x.mainStart()} + ${x.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<${k.type.value}, ${b}>; + var values: array<${$.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 < ${u[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${b}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${k.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${k.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${P.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]; + ${U} + ${A} + ${$.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${i};${o};${b};${u[0]};${u[1]}`,inputDependencies:t?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:m}),getShaderSource:w}}});var _l,vC,ov,xl=q(()=>{"use strict";Ne();Ke();$o();We();fn();_l=(n,e,r,t,i=!1)=>{let o=n[0].dims,s=n[1].dims,a=o[o.length-2],u=s[s.length-1],d=o[o.length-1],m=dt(u),b=dt(d),w=dt(a),x=J.size(r)/m/w,$=n.length>2,I=t?t.slice(0,-2):r.slice(0,-2),k=[J.size(I),a,u],P=[{type:12,data:x},{type:12,data:a},{type:12,data:u},{type:12,data:d}];kr(e,P),P.push(...pe(I,o,s)),$&&P.push(...pe(n[2].dims)),P.push(...pe(k));let z=U=>{let F=ls("batch_dims",n[0].dataType,I.length),Y=ee("a",n[0].dataType,o.length,b),ie=ee("b",n[1].dataType,s.length,m),ne=de("output",n[0].dataType,k.length,m),le=ut(ne.type.tensor),ge=Pr(e,ne.type.value,le),se=[Y,ie],re="";if($){let Ae=i?m:1;se.push(ee("bias",n[2].dataType,n[2].dims.length,Ae)),re=`${i?`value += bias[col / ${Ae}];`:`value += ${ne.type.value}(bias[row + i]);`}`}let _e=o.slice(0,-2),Oe=s.slice(0,-2),he=Ii(_e,I),$e=Ii(Oe,I),je=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Dr(e,je);let Ue=(Ae,Le)=>{let Pe=Ae.rank,Tt=Ae.name;if(Pe===2)return`var ${Tt}_indices = ${Ae.type.indices}(0u, 0u);`;let oe=F.rank,ve=`var ${Tt}_indices: ${Ae.type.indices};`;for(let He=Pe-2-1,Et=oe-1;He>=0;He--,Et--)ve+=` +${Tt}_indices[${He}] = ${oe>1?`batch_indices[${Et}]`:"batch_indices"};`;return Le.forEach(He=>{ve+=` +${Tt}_indices[${He}] = 0;`}),ve+=`${Tt}_indices[${Pe-2}] = 0u; + ${Tt}_indices[${Pe-1}] = 0u;`,ve},Be=()=>{let Ae=`var a_data: ${Y.type.value};`;for(let Le=0;Le; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${b}) { + ${Be()} + } + for (var i = 0u; i < ${w}u; i++) { + var value = values[i]; + ${re} + ${ge} + let cur_indices = ${ne.type.indices}(batch, row + i, col); + let offset = ${ne.indicesToOffset("cur_indices")}; + ${ne.setByOffset(`offset / ${m}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${m};${b};${w};${i}`,inputDependencies:$?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:P}),getShaderSource:z}},vC=n=>{if(!n||n.length!==2)throw new Error("MatMul requires 2 inputs.");if(n[0].dims[n[0].dims.length-1]!==n[1].dims[n[1].dims.length-2])throw new Error("shared dimension does not match.")},ov=n=>{vC(n.inputs);let e=Ur.calcShape(n.inputs[0].dims,n.inputs[1].dims,!0);if(!e)throw new Error("Can't use matmul on the given tensors");let r=e[e.length-1],t=n.inputs[0].dims[n.inputs[0].dims.length-1];r<8&&t<8?n.compute(_l(n.inputs,{activation:""},e)):n.compute(_s(n.inputs,{activation:""},e))}});var xs,$l,wC,av,Tl,_C,xC,Sl,wl=q(()=>{"use strict";Ke();rv();$o();iv();fn();xl();Ci();xs=(n,e,r,t,i,o)=>{let s=n[0],a=n.slice(o?1:2,o?3:4),u=a.length,d=e[0],b=e.slice(2).map(($,I)=>$+($-1)*(r[I]-1)),x=a.map(($,I)=>$+t[I]+t[I+u]).map(($,I)=>Math.floor(($-b[I]+i[I])/i[I]));return x.splice(0,0,s),x.splice(o?3:1,0,d),x},$l=[2,3,1,0],wC=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4&&n[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let r=n[0].dims[e.format==="NHWC"?n[0].dims.length-1:1],t=n[1].dims[1]*e.group;if(r!==t)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(n.length===3&&(n[2].dims.length!==1||n[1].dims[0]!==n[2].dims[0]))throw new Error("invalid bias");let i=n[0].dims.length-2;if(e.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(e.strides.length!==i)throw new Error(`strides should be ${i}D`);if(e.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape")},av=(n,e)=>{let r=n.kernelShape.slice();for(let o=2;o{let e=ys(n),r=n.format,t=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],i=n.dilations,o=n.group,s=n.kernel_shape,a=n.pads,u=n.strides,d=n.w_is_const();return{autoPad:t,format:r,dilations:i,group:o,kernelShape:s,pads:a,strides:u,wIsConst:d,...e,cacheKey:`${n.format};${e.activation};`}},_C=(n,e,r)=>{let t=av(r,e),i=r.format==="NHWC";if(r.group!==1){if(!n.adapterInfo.isArchitecture("ampere")&&i&&e[1].dims[0]===r.group&&e[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let ie=xs(e[0].dims,e[1].dims,r.dilations,t.pads,r.strides,i),ne=n.kernelCustomData.wT??n.compute(vr(e[1],$l),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=ne);let le=[e[0],ne];e.length===3&&le.push(e[2]),n.compute(nv(le,t,ie),{inputs:le})}else n.compute(vl(e,t));return}let o=e.length===3,s=e[0].dims[i?1:2],a=e[0].dims[i?2:3],u=e[0].dims[i?3:1],d=e[1].dims[2],m=e[1].dims[3],b=xs(e[0].dims,e[1].dims,r.dilations,t.pads,r.strides,i),w=b[i?1:2],x=b[i?2:3],$=b[i?3:1],I=i&&d===s&&m===a&&r.pads[0]===0&&r.pads[1]===0;if(I||d===1&&m===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let Y=b[0],ie,ne,le,ge=[];if(i){let _e=n.kernelCustomData.wT??n.compute(vr(e[1],$l),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=_e),I){let Oe=s*a*u;ie=e[0].reshape([1,Y,Oe]),ne=_e.reshape([1,Oe,$]),le=[1,Y,$]}else ie=e[0].reshape([Y,s*a,u]),ne=_e.reshape([1,u,$]),le=[Y,w*x,$];ge.push(ie),ge.push(ne)}else ie=e[0].reshape([Y,u,s*a]),ne=e[1].reshape([1,$,u]),le=[Y,$,w*x],ge.push(ne),ge.push(ie);o&&ge.push(e[2]);let se=le[2],re=ge[0].dims[ge[0].dims.length-1];se<8&&re<8?n.compute(_l(ge,t,b,le,i),{inputs:ge}):n.compute(_s(ge,t,b,le,i),{inputs:ge});return}let A=!0,k=n.kernelCustomData.wT??n.compute(vr(e[1],$l),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=k);let P=[e[0],k];o&&P.push(e[2]);let z=i?w*x:$,U=i?$:w*x,F=d*m*u;n.compute(tv(P,t,b,z,U,F,o,A),{inputs:P})},xC=(n,e)=>{let r=e.format==="NHWC",t=[n.inputs[0].reshape(r?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&t.push(n.inputs[2]);let i=[0,e.pads[0],0,e.pads[1]],o=[1].concat(e.strides),s=[1].concat(e.dilations),a=[1].concat(e.kernelShape),u=av({...e,pads:i,strides:o,dilations:s,kernelShape:a},t);n.compute(vl(t,u,d=>r?[d[0],d[2],d[3]]:[]))},Sl=(n,e)=>{wC(n.inputs,e),n.inputs[0].dims.length===3?xC(n,e):_C(n,n.inputs,e)}});var $C,sv,uv=q(()=>{"use strict";Ne();cn();We();fn();vs();bl();$o();$C=(n,e=!1,r,t,i=4)=>{let o=k=>{switch(k){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 ${t}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${k} is not supported.`)}},s=n?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,a=n?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,u=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",d=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=n?"row":"col",b=n?"col":"row",w=` + let inChannels = ${n?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${m} / outWidth; + let outCol = ${m} % outWidth; + + let WRow = ${b} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${b} / 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(${u}) || fract(xR) > 0.0) { + return ${t}(0.0); + } + if (xC < 0.0 || xC >= f32(${d}) || fract(xC) > 0.0) { + return ${t}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${b} % inChannels; + ${s} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,x=n?` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${w} + } + return ${t}(0.0);`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${w} + } + return ${t}(0.0);`,$=` + let col = colIn * ${i}; + let inChannels = ${n?"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 (${n?"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(i)} + } + return ${t}(0.0); + `,I=Pr(r,t);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${t} { + ${n?x:$} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${t} { + ${n?$:x} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${t}) { + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${a} + ${bs(e)} + ${I} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value; + } + }`},sv=(n,e,r,t,i,o,s,a)=>{let u=e.format==="NHWC",d=u?n[0].dims[3]:n[0].dims[1],m=r[0],b=u?r[2]:r[3],w=u?r[1]:r[2],x=u?r[3]:r[1],$=u&&d%4===0&&d%3&&x%4===0,I=u?x:b*w,A=u?b*w:x,k=[8,8,1],P=t<=8?[4,1,1]:[4,4,1],z=[Math.ceil(I/k[0]/P[0]),Math.ceil(A/k[1]/P[1]),Math.ceil(m/k[2]/P[2])];ft("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${z}`);let U=$?4:1,F=Math.max(k[0]*U,k[1]),Y=$?4:1,ie=[e.kernelShape[u?1:2],e.kernelShape[u?2:3]],ne=[ie[0]+(e.dilations[0]<=1?0:(ie[0]-1)*(e.dilations[0]-1)),ie[1]+(e.dilations[1]<=1?0:(ie[1]-1)*(e.dilations[1]-1))],le=[ne[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),ne[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],ge=[{type:6,data:t},{type:6,data:i},{type:6,data:o},{type:6,data:e.strides},{type:6,data:e.dilations},{type:6,data:ie},{type:6,data:le}];kr(e,ge),ge.push(...pe(n[0].dims,n[1].dims));let se=["rank","rank"];s&&(ge.push(...pe(n[2].dims)),se.push("rank")),ge.push(...pe(r));let re=_e=>{let Oe=ee("x",n[0].dataType,n[0].dims.length,Y),he=ee("w",n[1].dataType,n[1].dims.length,1),$e=de("result",n[0].dataType,r.length,Y),je=[Oe,he],Ue="";if(s){let Le=ee("bias",n[2].dataType,n[2].dims.length,Y);je.push(Le),Ue+=` + fn getBiasByOutputCoords(coords : vec4) -> ${Le.type.value} { + return bias[coords.${u?"w":"y"}${$?"/ 4":""}]; + }`}let Be=[{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:ie.length},{name:"pads",type:"i32",length:le.length}];Dr(e,Be);let Ae=ut(n[0].dataType,1);if(Ae!=="f16"&&Ae!=="f32")throw new Error(`elemType ${Ae} is not supported.`);return` + ${ws("uniforms.result_strides")} + ${_e.registerUniforms(Be).declareVariables(...je,$e)}; + ${Ue} + ${$C(u,s,e,Oe.type.value,U)} + ${$?_o(P,k,Ae,void 0,!u,F):xo(P,k,Ae,void 0,!u,F,!1,void 0,a)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${e.cacheKey};${P};${k};${$}`,inputDependencies:se},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:z[0],y:z[1],z:z[2]},programUniforms:ge}),getShaderSource:re}}});var TC,Il,lv=q(()=>{"use strict";Ne();cn();Ke();We();TC=(n,e,r,t,i,o=!1,s,a,u=!1)=>{let d=u?1:2,m=u?2:3,b=u?3:1,w=o?2:1,x=` + fn setOutputAtIndex(flatIndex : u32, value : ${o?`vec4<${s}>`:s}) { + result[flatIndex] = ${o?`vec4<${s}>`:s}(value); + }`;t&&(x+=` + fn getBiasByOutputCoords(coords : vec4) -> ${o?`vec4<${s}>`:s} { + return bias[coords.${u?"w":"y"}${o?"/ 4":""}]; + }`);let $=o?4:1,I=ee("W",e[1].dataType,e[1].dims.length,$),A=ee("Dy",e[0].dataType,e[0].dims.length,$),k=[A,I];t&&k.push(ee("bias",e[2].dataType,[r[b]].length,$));let P=de("result",e[0].dataType,r.length,$),z=`{ + let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${i?"global_id.y":"workgroup_id.y"} * ${w}; + let d1: u32 = ${i?"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, ${w}>; + for (var i = 0; i < ${w}; i++) { + dotProd[i] = vec4<${s}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${s}(dyCorner.x) + ${s}(wR)) / ${s}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${s}(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 = (${s}(dyCorner.y) + ${s}(wC)) / ${s}(uniforms.strides.y); + let dyC2 = (${s}(dyCorner.y) + 1.0 + ${s}(wC)) / ${s}(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 >= ${s}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${s}(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 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${A.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${s}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${A.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${s}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${b}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${A.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${s}>(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 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${A.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${s}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${w}; i = i + 1) { + let value = dotProd[i] + ${t?"bias[c+i]":`vec4<${s}>(0.0)`}; + ${P.set("batch","r","c + i","d1","value")}; + } + }`,U=` + let outputIndices = ${P.offsetToIndices("global_idx")}; + let batch = ${P.indicesGet("outputIndices",0)}; + let d1 = ${P.indicesGet("outputIndices",b)}; + let r = ${P.indicesGet("outputIndices",d)}; + let c = ${P.indicesGet("outputIndices",m)}; + 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 = ${s}(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 = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${d}]) || 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 = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${m}]) || + 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 = ${u?A.get("batch","idyR","idyC","inputChannel"):A.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${I.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${t?"bias[d1]":`${s}(0.0)`}; + ${P.setByOffset("global_idx","value")}; + `;return` + ${n.registerUniforms(a).declareVariables(...k,P)} + ${x} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${o?z:U}}`},Il=(n,e,r)=>{let t=n.length>2,i=e.outputShape,o=J.size(i),s=[Math.ceil(o/64),1,1];ft("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let a=e.format==="NHWC",u=["rank","rank"],d=[e.strides[0],e.strides[1]],m=[e.kernelShape[a?1:2],e.kernelShape[a?2:3]],b=[e.dilations[0],e.dilations[1]],w=[m[0]+(e.dilations[0]<=1?0:(e.kernelShape[a?1:2]-1)*(e.dilations[0]-1)),m[1]+(e.dilations[1]<=1?0:(e.kernelShape[a?2:3]-1)*(e.dilations[1]-1))],x=[w[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),w[1]-1-Math.floor(e.pads[1]+e.pads[3])/2],$=!1,I=e.group,A=n[1].dims,k=A[0]/I,P=A[1],z=[{type:12,data:o},{type:12,data:d},{type:12,data:m},{type:12,data:b},{type:12,data:w},{type:6,data:x},{type:12,data:k},{type:12,data:P},...pe(n[0].dims,n[1].dims)];t&&(z.push(...pe(n[2].dims)),u.push("rank")),z.push(...pe(i));let U=s[1]===1&&s[2]===1,F=Y=>{let ie=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:d.length},{name:"filter_dims",type:"u32",length:m.length},{name:"dilations",type:"u32",length:m.length},{name:"effective_filter_dims",type:"u32",length:w.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],ne=ut(n[0].dataType);return`${TC(Y,n,i,t,U,$,ne,ie,a)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};`,inputDependencies:u},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:r?r(i):i,dataType:n[0].dataType}],programUniforms:z}),getShaderSource:F}}});var SC,IC,CC,dv,cv,AC,EC,OC,PC,fv,pv=q(()=>{"use strict";uv();lv();fn();Ci();SC=(n,e,r,t,i,o)=>(n-1)*e+r+(t-1)*i+1-o,IC=(n,e,r,t,i)=>{let o=Math.floor(n/2);e==="SAME_UPPER"?(r[t]=o,r[i]=n-o):e==="SAME_LOWER"&&(r[t]=n-o,r[i]=o)},CC=(n,e,r,t,i,o,s,a,u,d)=>{let m=n.length-2,b=d.length===0;if(u.length===0)for(let $=0;${let r=n.kernelShape.slice();if(n.kernelShape.length===0||n.kernelShape.reduce((b,w)=>b*w,1)===0){r.length=0;for(let b=2;bb+w,0)===0){let b=e[0].dims.length-2;u=new Array(b).fill(1)}let d=n.strides.slice();if(d.reduce((b,w)=>b+w,0)===0){let b=e[0].dims.length-2;d=new Array(b).fill(1)}CC(a,r,u,n.autoPad,n.group,i,d,t,s,o);let m=Object.assign({},n);return Object.assign(m,{kernelShape:r,pads:i,outputPadding:s,outputShape:o,dilations:u,strides:d}),m},cv=n=>{let e=ys(n),r=n.format,t=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof n.autoPad>"u"?0:n.autoPad],i=n.dilations,o=n.group,s=n.kernelShape,a=n.pads,u=n.strides,d=n.wIsConst(),m=n.outputPadding,b=n.outputShape;return{autoPad:t,format:r,dilations:i,group:o,kernelShape:s,outputPadding:m,outputShape:b,pads:a,strides:u,wIsConst:d,...e,cacheKey:`${n.format};${e.activation};`}},AC=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4&&n[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let r=n[0].dims[e.format==="NHWC"?n[0].dims.length-1:1],t=n[1].dims[0];if(r!==t)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=n[1].dims[1]*e.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==i))throw new Error("invalid bias");let o=n[0].dims.length-2;if(e.dilations.reduce((m,b)=>m+b,0)>0&&e.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(e.strides.reduce((m,b)=>m+b,0)>0&&e.strides.length!==o)throw new Error(`strides should be ${o}D`);if(e.pads.reduce((m,b)=>m+b,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((m,b)=>m+b,0)>0&&e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(e.outputShape.length!==0&&e.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape")},EC=[2,3,1,0],OC=(n,e,r)=>{let t=dv(r,e),i=r.format==="NHWC",o=t.outputShape,s=o[i?3:1],a=e[0].dims[i?3:1];if(t.group!==1||s===1&&a===1){n.compute(Il(e,t));return}let u=o[i?1:2],d=o[i?2:3],m=e[1].dims[2],b=e[1].dims[3],w=i?u*d:s,x=i?s:u*d,$=m*b*a,I=!0,A=n.kernelCustomData.wT??n.compute(vr(e[1],EC),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=A);let k=[e[0],A],P=e.length===3;P&&(!i&&e[2].dims.length===1?k.push(e[2].reshape([e[2].dims[0],1,1])):k.push(e[2])),n.compute(sv(k,t,o,w,x,$,P,I),{inputs:k})},PC=(n,e)=>{let r=e.format==="NHWC",t=[n.inputs[0].reshape(r?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&t.push(n.inputs[2]);let i=e.kernelShape;(i.length===0||i[0]===0)&&(i=[n.inputs[1].dims[2]]);let o=e.dilations;(o.length===0||o[0]===0)&&(o=[1]);let s=e.strides;(s.length===0||s[0]===0)&&(s=[1]);let a=e.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],s=[1].concat(s),o=[1].concat(o),i=[1].concat(i);let u=dv({...e,pads:a,strides:s,dilations:o,kernelShape:i},t);n.compute(Il(t,u,d=>r?[d[0],d[2],d[3]]:[d[0],d[1],d[3]]))},fv=(n,e)=>{AC(n.inputs,e),n.inputs[0].dims.length===3?PC(n,e):OC(n,n.inputs,e)}});var kC,hv,mv,gv=q(()=>{"use strict";Ne();Ke();kt();We();kC=(n,e,r,t)=>{let i=J.size(e),o=e.length,s=ee("input",n,o),a=de("output",n,o),u=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),d=J.normalizeAxis(u,o),m=b=>{let w=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,x=ze("uniforms.input_shape","uniforms.axis",o),$=t.reverse?w+(t.exclusive?" + 1":""):"0",I=t.reverse?x:w+(t.exclusive?"":" + 1");return` + ${b.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,a)} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${$}; + let last : i32 = ${I}; + for (var i : i32 = first; i < last; i++) { + ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${s.getByIndices("inputIndices")}; + } + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:e,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:d},...pe(e,e)]}),getShaderSource:m}},hv=(n,e)=>{let r=n.inputs[0].dims,t=n.inputs[0].dataType,i=n.inputs[1];n.compute(kC(t,r,i,e),{inputs:[0]})},mv=n=>{let e=n.exclusive===1,r=n.reverse===1;return Ve({exclusive:e,reverse:r})}});var DC,BC,RC,yv,bv,vv=q(()=>{"use strict";Ne();Ke();kt();We();DC=n=>{if(!n||n.length!==1)throw new Error("DepthToSpace requires 1 input.");if(n[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},BC=(n,e,r,t)=>{let i=[];i.push(`fn perm(i: ${t.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let o=0;o{let r,t,i,o,s,a,u=e.format==="NHWC",d=e.blocksize,m=e.mode==="DCR";u?([r,t,i,o]=n.dims,s=m?[r,t,i,d,d,o/d**2]:[r,t,i,o/d**2,d,d],a=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,t,i,o]=[n.dims[0],n.dims[2],n.dims[3],n.dims[1]],s=m?[r,d,d,o/d**2,t,i]:[r,o/d**2,d,d,t,i],a=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let b=n.reshape(s),w=b.dims.length,x=n.dataType,$=ee("a",x,w),I=de("output",x,w),A=k=>` + ${k.registerUniform("output_size","u32").declareVariables($,I)} + + ${BC(a,w,$,I)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${I.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${I.setByOffset("global_idx",$.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${n.dims};${e.blocksize};${e.mode}`,inputDependencies:["rank"]},getRunData:k=>{let P=u?[r,t*d,i*d,o/d**2]:[r,o/d**2,t*d,i*d],z=J.size(P),U=b.dims,F=J.sortBasedOnPerm(U,a);return{outputs:[{dims:P,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(z/64)},programUniforms:[{type:12,data:z},...pe(U,F)]}},getShaderSource:A}},yv=(n,e)=>{DC(n.inputs),n.compute(RC(n.inputs[0],e))},bv=n=>Ve({blocksize:n.blocksize,mode:n.mode,format:n.format})});var Cl,$s,wv,zC,MC,Al,El,_v,NC,xv,$v,Tv=q(()=>{"use strict";Ne();Ke();kt();We();Cl="[a-zA-Z]|\\.\\.\\.",$s="("+Cl+")+",wv="^"+$s+"$",zC="("+$s+",)*"+$s,MC="^"+zC+"$",Al=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},El=class{constructor(e,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,i]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(MC)))throw new Error("Invalid LHS term");if(t.split(",").forEach((a,u)=>{let d=e[u].dims.slice();if(!a.match(RegExp(wv)))throw new Error("Invalid LHS term");let m=this.processTerm(a,!0,d,u);this.lhs.push(m)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([a,u])=>u.count===1||a==="...").map(([a])=>a).join("");else if(!i.match(RegExp($s)))throw new Error("Invalid RHS");i.match(RegExp(Cl,"g"))?.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let u=this.symbolToInfo.get(a);if(u===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(u.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(e,r,t){let i=this.symbolToInfo.get(e);if(i!==void 0){if(i.dimValue!==r&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(t)}else i={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,i)}processTerm(e,r,t,i=-1){let o=t.length,s=!1,a=[],u=0;if(!e.match(RegExp(wv))&&!r&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Cl,"g")),m=new Al(i);return d?.forEach((b,w)=>{if(b==="..."){if(s)throw new Error("Only one ellipsis is allowed per input term");s=!0;let x=o-d.length+1;if(x<0)throw new Error("Ellipsis out of bounds");if(a=t.slice(u,u+x),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let $=0;$n+"_max",NC=(n,e,r,t)=>{let o=n.map(m=>m.length).map((m,b)=>ee(`input${b}`,e,m)),s=J.size(t),a=de("output",e,t.length),u=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),d=m=>{let b=[],w="var prod = 1.0;",x="var sum = 0.0;",$="sum += prod;",I=[],A=[],k=[],P=[],z=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((F,Y)=>{if(r.rhs.symbolToIndices.has(Y)){let ie=r.rhs.symbolToIndices.get(Y)?.[0];ie!==void 0&&r.lhs.forEach((ne,le)=>{if(F.inputIndices.includes(le)){let ge=ne.symbolToIndices.get(Y);if(ge===void 0)throw new Error("Invalid symbol error");ge.forEach(se=>{b.push(`${o[le].indicesSet(`input${le}Indices`,se,a.indicesGet("outputIndices",ie))}`)})}})}else r.lhs.forEach((ie,ne)=>{if(F.inputIndices.includes(ne)){let le=ie.symbolToIndices.get(Y);if(le===void 0)throw new Error("Invalid symbol error");le.forEach(ge=>{I.push(`${o[ne].indicesSet(`input${ne}Indices`,ge,`${Y}`)}`)}),P.push(`prod *= ${o[ne].getByIndices(`input${ne}Indices`)};`)}}),A.push(`for(var ${Y}: u32 = 0; ${Y} < uniforms.${_v(Y)}; ${Y}++) {`),k.push("}")});let U=z?[...b,`let sum = ${o.map((F,Y)=>F.getByIndices(`input${Y}Indices`)).join(" * ")};`]:[...b,x,...A,...I,w,...P,$,...k];return` + ${m.registerUniforms(u.map(F=>({name:`${_v(F)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,a)} + + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${a.offsetToIndices("global_idx")}; + ${o.map((F,Y)=>`var input${Y}Indices: ${o[Y].type.indices};`).join(` +`)} + ${U.join(` +`)}; + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:n.map(()=>"rank")},getRunData:()=>{let m=u.filter(w=>r.symbolToInfo.has(w)).map(w=>({type:12,data:r.symbolToInfo.get(w)?.dimValue||0}));m.push({type:12,data:s});let b=n.map((w,x)=>[...pe(w)]).reduce((w,x)=>w.concat(x),m);return b.push(...pe(t)),{outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:b}},getShaderSource:d}},xv=(n,e)=>{let r=new El(n.inputs,e.equation),t=r.outputDims,i=n.inputs.map((o,s)=>o.dims);n.compute(NC(i,n.inputs[0].dataType,r,t))},$v=n=>{let e=n.equation.replace(/\s+/g,"");return Ve({equation:e})}});var LC,Sv,jC,UC,Iv,Cv=q(()=>{"use strict";Ne();Ke();We();LC=n=>{if(!n||n.length!==2)throw new Error("Expand requires 2 input.");let e=n[0].dims,r=Array.from(n[1].getBigInt64Array(),Number),t=r.length{let r=n.length-e.length,t=[];for(let i=0;in.length>e.length?Sv(n,e):Sv(e,n),UC=n=>{let e=n[0].dims,r=Array.from(n[1].getBigInt64Array(),Number),t=jC(e,r),i=n[0].dataType,o=i===9?4:1,s=Math.ceil(J.size(t)/o),a=d=>{let m=ee("input",i,e.length,o),b=de("output",i,t.length,o),w;if(i===9){let x=($,I,A="")=>` + let outputIndices${I} = ${b.offsetToIndices(`outputOffset + ${I}u`)}; + let offset${I} = ${m.broadcastedIndicesToOffset(`outputIndices${I}`,b)}; + let index${I} = offset${I} / 4u; + let component${I} = offset${I} % 4u; + ${$}[${I}] = ${A}(${m.getByOffset(`index${I}`)}[component${I}]); + `;w=` + let outputOffset = global_idx * ${o}; + var data = vec4(0); + ${x("data",0,"u32")} + ${x("data",1,"u32")} + ${x("data",2,"u32")} + ${x("data",3,"u32")} + ${b.setByOffset("global_idx","data")} + }`}else w=` + let outputIndices = ${b.offsetToIndices("global_idx")}; + let inputOffset = ${m.broadcastedIndicesToOffset("outputIndices",b)}; + ${b.setByOffset("global_idx",m.getByOffset("inputOffset"))} + }`;return` + ${d.registerUniform("vec_size","u32").declareVariables(m,b)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${w}`},u=[{type:12,data:s},...pe(e,t)];return{name:"Expand",shaderCache:{hint:`${t.length}`,inputDependencies:["rank"]},getShaderSource:a,getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},Iv=n=>{LC(n.inputs),n.compute(UC(n.inputs),{inputs:[0]})}});var FC,Av,Ev=q(()=>{"use strict";Ne();Ke();We();gs();FC=n=>{let e=n[0].dataType,r=J.size(n[0].dims),t=J.size(n[1].dims),i=t%4===0,o=s=>{let a=ee("x",e,[1],4),u=ee("bias",e,[1],4),d=de("y",e,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],b=x=>` + let bias${x}_offset: u32 = (global_idx * 4 + ${x}) % uniforms.bias_size; + let bias${x} = ${u.getByOffset(`bias${x}_offset / 4`)}[bias${x}_offset % 4];`,w=i?` + let bias = ${u.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${b(0)}${b(1)}${b(2)}${b(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${s.registerUniforms(m).declareVariables(a,u,d)} + + ${gl(Ut(e))} + + ${s.mainStart(Un)} + ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${w} + let x_in = x + bias; + ${d.setByOffset("global_idx",yl("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:s=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:t}],dispatchGroup:{x:Math.ceil(r/Un/4)}})}},Av=n=>{n.inputs.length<2||J.size(n.inputs[1].dims)===0?M0(n):n.compute(FC(n.inputs))}});var VC,GC,Ov,Pv,kv=q(()=>{"use strict";Ne();Ke();kt();We();VC=n=>{if(!n||n.length!==2)throw new Error("Gather requires 2 inputs.")},GC=(n,e)=>{let r=n[0].dims,t=n[1].dims,i=r.length,o=J.normalizeAxis(e.axis,i),s=r.slice(0);s.splice(o,1,...t);let a=r[o],u=n[0].dataType===9?4:1,d=Math.ceil(J.size(s)/u),m=[{type:12,data:d},{type:6,data:a},{type:12,data:o},...pe(n[0].dims,n[1].dims,s)],b=w=>{let x=ee("data",n[0].dataType,n[0].dims.length,u),$=ee("inputIndices",n[1].dataType,n[1].dims.length),I=de("output",n[0].dataType,s.length,u),A=P=>{let z=t.length,U=`var indicesIndices${P} = ${$.type.indices}(0);`;for(let F=0;F1?`indicesIndices${P}[${F}]`:`indicesIndices${P}`} = ${s.length>1?`outputIndices${P}[uniforms.axis + ${F}]`:`outputIndices${P}`};`;U+=` + var idx${P} = ${$.getByIndices(`indicesIndices${P}`)}; + if (idx${P} < 0) { + idx${P} = idx${P} + uniforms.axisDimLimit; + } + var dataIndices${P} : ${x.type.indices}; + `;for(let F=0,Y=0;F1?`dataIndices${P}[${F}]`:`dataIndices${P}`} = u32(idx${P});`,Y+=z):(U+=`${i>1?`dataIndices${P}[${F}]`:`dataIndices${P}`} = ${s.length>1?`outputIndices${P}[${Y}]`:`outputIndices${P}`};`,Y++);return U},k;if(n[0].dataType===9){let P=(z,U,F="")=>` + let outputIndices${U} = ${I.offsetToIndices(`outputOffset + ${U}u`)}; + ${A(U)}; + let offset${U} = ${x.indicesToOffset(`dataIndices${U}`)}; + let index${U} = offset${U} / 4u; + let component${U} = offset${U} % 4u; + ${z}[${U}] = ${F}(${x.getByOffset(`index${U}`)}[component${U}]); + `;k=` + let outputOffset = global_idx * ${u}; + var value = vec4(0); + ${P("value",0,"u32")} + ${P("value",1,"u32")} + ${P("value",2,"u32")} + ${P("value",3,"u32")} + ${I.setByOffset("global_idx","value")} + `}else k=` + let outputIndices = ${I.offsetToIndices("global_idx")}; + ${A("")}; + let value = ${x.getByIndices("dataIndices")}; + ${I.setByOffset("global_idx","value")}; + `;return` + ${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(x,$,I)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${k} + }`};return{name:"Gather",shaderCache:{hint:e.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m}),getShaderSource:b}},Ov=n=>Ve({axis:n.axis}),Pv=(n,e)=>{let r=n.inputs;VC(r),n.compute(GC(n.inputs,e))}});var WC,HC,Dv,Bv,Rv=q(()=>{"use strict";Ne();Ke();kt();We();WC=n=>{if(!n||n.length!==2)throw new Error("GatherElements requires 2 inputs.");if(n[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(n[0].dims.length!==n[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},HC=(n,e)=>{let r=n[0].dims,t=n[0].dataType,i=r.length,o=n[1].dims,s=n[1].dataType,a=J.normalizeAxis(e.axis,i),u=r[a],d=o.slice(0),m=J.size(d),b=ee("input",t,i),w=ee("indicesInput",s,o.length),x=de("output",t,d.length),$=[{type:12,data:m},{type:6,data:u},{type:12,data:a}];return $.push(...pe(r,o,d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:$}),getShaderSource:k=>` + ${k.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(b,w,x)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${x.offsetToIndices("global_idx")}; + + var idx = ${w.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${b.type.indices}(outputIndices); + ${b.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${b.getByIndices("inputIndices")}; + + ${x.setByOffset("global_idx","value")}; + }`}},Dv=n=>Ve({axis:n.axis}),Bv=(n,e)=>{let r=n.inputs;WC(r),n.compute(HC(n.inputs,e))}});var qC,KC,zv,Mv,Nv=q(()=>{"use strict";Ne();Ke();We();qC=n=>{if(!n)throw new Error("Input is missing");if(n.length<2||n.length>3)throw new Error("Invaid input number.");if(n.length===3&&n[2].dims.length>2)throw new Error("Invalid input shape of C");if(n[0].dataType!==n[1].dataType||n.length===3&&n[0].dataType!==n[2].dataType)throw new Error("Input types are mismatched")},KC=(n,e)=>{let r=n[0].dims.slice(),t=n[1].dims.slice(),[i,o,s]=as.getShapeOfGemmResult(r,e.transA,t,e.transB,n.length===3?n[2].dims:void 0),a=[i,o];if(!a)throw new Error("Can't use gemm on the given tensors");let u=J.size(a),d=[{type:12,data:u},{type:12,data:i},{type:12,data:o},{type:12,data:s},{type:1,data:e.alpha},{type:1,data:e.beta}],m=["type","type"];n.length===3&&(d.push(...pe(n[2].dims)),m.push("rank")),d.push(...pe(a));let b=w=>{let x="";e.transA&&e.transB?x="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":e.transA&&!e.transB?x="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!e.transA&&e.transB?x="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!e.transA&&!e.transB&&(x="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let $=e.alpha===1?"":"value *= uniforms.alpha;",I=ee("a",n[0].dataType,n[0].dims),A=ee("b",n[1].dataType,n[1].dims),k=I.type.value,P=null,z=[I,A];n.length===3&&(P=ee("c",n[2].dataType,n[2].dims.length),z.push(P));let U=de("output",n[0].dataType,a.length);z.push(U);let F=[{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` + ${w.registerUniforms(F).declareVariables(...z)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${k}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${x} + } + + ${$} + ${(()=>P!=null?`let cOffset = ${P.broadcastedIndicesToOffset("vec2(m, n)",U)}; value += ${k}(uniforms.beta) * ${P.getByOffset("cOffset")};`:"")()} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:a,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:b}},zv=n=>{let e=n.transA,r=n.transB,t=n.alpha,i=n.beta;return{transA:e,transB:r,alpha:t,beta:i,cacheKey:`${n.transA};${n.transB};${n.alpha===1}`}},Mv=(n,e)=>{qC(n.inputs),n.compute(KC(n.inputs,e))}});var YC,XC,ZC,Lv,jv=q(()=>{"use strict";Ne();Ke();We();YC=(n,e)=>{let r=n[0].dims,t=r,i=2,o=J.sizeToDimension(r,i),s=J.sizeFromDimension(r,i),a=dt(s),u=s/a,d=[r[0],r[1],u],m=["rank","type","type"],b=[{type:12,data:s},{type:12,data:u}];b.push(...pe(d,d));let w=x=>{let $=ee("x",n[0].dataType,d.length,a),I=ee("scale",n[1].dataType,n[1].dims),A=ee("bias",n[2].dataType,n[2].dims),k=de("output",n[0].dataType,d.length,a),P=[$,I,A,k],z=$.type.value,U=a===1?"f32":`vec${a}`,F=64,Y=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${U}, ${F}>; + const workgroupSize = ${F}u; + ${x.registerUniforms(Y).declareVariables(...P)} + ${x.mainStart(F)} + 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 = ${U}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${U}(${$.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 = ${Or("workgroupShared[0]",a)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${U}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${U}(${$.get("batch","channel","h")}) - ${U}(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 = ${Or("workgroupShared[0]",a)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${e.epsilon})); + let channelScale = invStdDev * f32(${I.getByOffset("channel")}); + let channelShift = f32(${A.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${$.get("batch","channel","h")} * ${z}(${U}(channelScale)) + ${z}(${U}(channelShift)); + ${k.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${e.epsilon};${a}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:o},programUniforms:b}),getShaderSource:w}},XC=(n,e,r,t,i,o,s,a)=>{let u=dt(s),d=64,m=u===1?"vec2f":`mat2x${u}f`,b=u===1?"f32":`vec${u}f`,w=(Y,ie)=>`${m}(${Y}, ${ie})`,x=i*s/u,$=Math.ceil(o/d),I=["type"],A=[{type:12,data:$},{type:12,data:o},{type:12,data:Math.floor(s/u)},{type:12,data:Math.floor(o*s/u)}],k=Y=>{let ie=ee("input",e.dataType,e.dims,u);return` + ${Y.declareVariables(ie)} + @group(0) @binding(1) var output : array<${m}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${Y.mainStart(d)} + let currentImageNumber = global_idx / ${d} / uniforms.C; + let currentChannelNumber = (global_idx / ${d}) % 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 = ${Er("f32",u)}; + var squaredSum = ${Er("f32",u)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${b}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${w("sum","squaredSum")}; + }`},P=n.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${u}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:[i,s,d,2],dataType:1}],dispatchGroup:{x:i*s/u},programUniforms:A}),getShaderSource:k},{inputs:[e],outputs:[-1]})[0],z=[{type:12,data:x},{type:12,data:o},{type:12,data:Math.floor(s/u)},{type:12,data:Math.floor(d*s/u)}],U=["type","type","type"],F=Y=>{let ie=ee("scale",r.dataType,r.dims,u),ne=ee("bias",t.dataType,t.dims,u);return` + @group(0) @binding(0) var input : array<${m}>; + @group(0) @binding(1) var scale : array<${ie.type.storage}>; + @group(0) @binding(2) var bias : array<${ne.type.storage}>; + @group(0) @binding(3) var output : array<${m}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${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 = ${Er("f32",u)}; + var squaredSum = ${Er("f32",u)}; + for (var i: u32 = 0; i < min(${d}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${d}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${a})); + let channelScale = invStdDev * ${b}(scale[currentChannelNumber]); + let channelShift = ${b}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${w("channelScale","channelShift")}; + }`};return n.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${u};${a}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:[i,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:z}),getShaderSource:F},{inputs:[P,r,t],outputs:[-1]})[0]},ZC=(n,e,r)=>{let t=e[0].dims,i=t,o=t[0],s=t[t.length-1],a=J.sizeFromDimension(t,1)/s,u=dt(s),d=J.size(i)/u,m=[{type:12,data:a},{type:12,data:Math.floor(s/u)}],b=["type","type"],w=XC(n,e[0],e[1],e[2],o,a,s,r.epsilon),x=$=>{let I=ut(e[0].dataType),A=u===1?"vec2f":`mat2x${u}f`,k=u===1?I:`vec${u}<${I}>`,P=ee("input",e[0].dataType,e[0].dims,u),z=de("output",e[0].dataType,i,u);return` + @group(0) @binding(0) var input : array<${P.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${A}>; + @group(0) @binding(2) var output : array<${z.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${$.mainStart()} + let currentImageNumber = global_idx / (uniforms.C * uniforms.H); + let currentChannelNumber = global_idx % uniforms.C; + + let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; + let scale = scaleInput[scaleOffset]; + output[global_idx] = fma(input[global_idx], ${k}(scale[0]), ${k}(scale[1])); + }`};n.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${u}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m}),getShaderSource:x},{inputs:[e[0],w]})},Lv=(n,e)=>{e.format==="NHWC"?ZC(n,n.inputs,e):n.compute(YC(n.inputs,e))}});var JC,QC,Uv,Fv=q(()=>{"use strict";Ne();Ke();We();JC=n=>{if(!n||n.length<2)throw new Error("layerNorm requires at least 2 inputs.")},QC=(n,e,r)=>{let t=e.simplified,i=n[0].dims,o=n[1],s=!t&&n[2],a=i,u=J.normalizeAxis(e.axis,i.length),d=J.sizeToDimension(i,u),m=J.sizeFromDimension(i,u),b=J.size(o.dims),w=s?J.size(s.dims):0;if(b!==m||s&&w!==m)throw new Error(`Size of X.shape()[axis:] == ${m}. + Size of scale and bias (if provided) must match this. + Got scale size of ${b} and bias size of ${w}`);let x=[];for(let F=0;F1,P=r>2,z=F=>{let Y=ut(n[0].dataType),ie=[ee("x",n[0].dataType,n[0].dims,$),ee("scale",o.dataType,o.dims,$)];s&&ie.push(ee("bias",s.dataType,s.dims,$)),ie.push(de("output",n[0].dataType,a,$)),k&&ie.push(de("mean_data_output",1,x)),P&&ie.push(de("inv_std_output",1,x));let ne=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${F.registerUniforms(ne).declareVariables(...ie)} + ${F.mainStart()} + ${F.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Er("f32",$)}; + var mean_square_vector = ${Er("f32",$)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Fn(Y,$,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Or("mean_vector",$)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Or("mean_square_vector",$)} / uniforms.norm_size ${t?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Fn(Y,$,"x[j + offset]")}; + let f32scale = ${Fn(Y,$,"scale[j]")}; + output[j + offset] = ${ie[0].type.value}((f32input ${t?"":"- mean"}) * inv_std_dev * f32scale + ${s?`+ ${Fn(Y,$,"bias[j]")}`:""} + ); + } + + ${k?"mean_data_output[global_idx] = mean":""}; + ${P?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},U=[{dims:a,dataType:n[0].dataType}];return k&&U.push({dims:x,dataType:1}),P&&U.push({dims:x,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${$};${r};${t}`,inputDependencies:I},getRunData:()=>({outputs:U,dispatchGroup:{x:Math.ceil(d/64)},programUniforms:A}),getShaderSource:z}},Uv=(n,e)=>{JC(n.inputs),n.compute(QC(n.inputs,e,n.outputCount))}});var eA,tA,Vv,Gv,Wv=q(()=>{"use strict";Ne();Ke();kt();We();eA=(n,e)=>{if(n.length<3||n.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=n[0],t=r.dims.length;if(r.dims[t-1]!==e.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((e.k+e.blockSize-1)/e.blockSize),o=e.blockSize/8*e.bits,s=n[1];if(!J.areEqual(s.dims,[e.n,i,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=n[2].dims;if(J.size(u)!==e.n*i)throw new Error("scales input size error.");if(n.length===4){let m=n[3].dims,b=e.bits>4?e.n*i:e.n*Math.floor((i+1)/2);if(J.size(m)!==b)throw new Error("zeroPoints input size error.")}},tA=(n,e,r,t)=>{let i=n[0].dims,o=i.length,s=Math.floor((e.k+e.blockSize-1)/e.blockSize),a=i[o-2],u=e.k,d=e.n,m=i.slice(0,o-2),b=J.size(m),x=e.blockSize/8*e.bits/4,$=n[0].dataType,I=dt(a),A=dt(e.k),k=dt(x),P=Ln($),z=a*s*P,U=Math.floor(t/z),F=s<=r[0]&&U>0,Y=!F||U>=4?dt(d):U>=2&&dt(d)>=2?2:1,ie=m.concat([a,d]),ne=J.size(ie)/Y/I,le=F?[]:[{type:12,data:ne},{type:12,data:e.blockSize}],ge=[b,a,u/A],se=J.convertShape(n[1].dims).slice();se.splice(-1,1,x/k),le.push(...pe(ge)),le.push(...pe(se)),le.push(...pe(n[2].dims)),n.length===4&&le.push(...pe(J.convertShape(n[3].dims)));let re=[b,a,d/Y];le.push(...pe(re));let _e=Oe=>{let he=ge.length,$e=ee("a",n[0].dataType,he,A),je=ee("b",12,se.length,k),Ue=ee("scales",n[2].dataType,n[2].dims.length),Be=[$e,je,Ue],Ae=n.length===4?ee("zero_points",12,n[3].dims.length):void 0;Ae&&Be.push(Ae);let Le=re.length,Pe=de("output",n[0].dataType,Le,Y),Tt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],oe=ut(n[0].dataType),ve=(()=>{switch(A){case 1:return`array<${oe}, 8>`;case 2:return`mat4x2<${oe}>`;case 4:return`mat2x4<${oe}>`;default:throw new Error(`${A}-component is not supported.`)}})(),He=` + for (var word: u32 = 0; word < ${x}; word += ${k}) { + ${je.indicesSet("b_indices","2","word")}; + let b_data = ${je.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${k}; i++) { + let b_value: u32 = ${k===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 = ${ve}(${Array.from({length:4},(wt,bt)=>`${oe}(b_value_lower[${bt}]), ${oe}(b_value_upper[${bt}])`).join(", ")}); + let b_dequantized_values = ${(()=>A===1?`${ve}(${Array.from({length:8},(wt,bt)=>`(b_quantized_values[${bt}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ve}(${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 < ${F?a:I}u; m++) { + ${$e.indicesSet("a_indices",he-2,F?"m":`row * ${I} + m`)}; + ${$e.indicesSet("a_indices",he-1,"word_offset")}; + var input_offset = ${$e.indicesToOffset("a_indices")}; + var a_data: ${ve}; + for (var j: u32 = 0; j < ${8/A}; j++) { + a_data[j] = ${$e.getByOffset("input_offset")}; + input_offset++; + } + ${F?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${Y>1?"[c]":""} += ${Array.from({length:8/A},(wt,bt)=>`${A===1?`a_data[${bt}] * b_dequantized_values[${bt}]`:`dot(a_data[${bt}], b_dequantized_values[${bt}])`}`).join(" + ")}; + } + word_offset += ${8/A}; + } + }`,Et=Ae?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${Ae.getByOffset("zero_point_index")}; + }`:"";return F?` + var workgroup_shared: array<${Pe.type.value}, ${a*s}>; + ${Oe.declareVariables(...Be,Pe)} + ${Oe.mainStart([s,1,1])} + var a_indices: ${$e.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${$e.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${Y}; c++) { + let col_times_components_plus_c = col * ${Y} + c; + ${Ae?` + var zero_point_bytes_per_col: u32 = (${s} + 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 = ${Ae.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} + var b_indices: ${je.type.indices}; + ${je.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 * ${s} + block; + let scale = ${Ue.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${oe}(${Ae?"(zero_point_word) & 0xFu":8}); + ${je.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${e.blockSize/A}; + var workgroup_shared_offset: u32 = block * ${a}; + ${He} + } + workgroupBarrier(); + if (local_id.x == 0u) { + var output_indices: ${Pe.type.indices}; + ${Pe.indicesSet("output_indices","0","batch")}; + ${Pe.indicesSet("output_indices",Le-1,"col")}; + ${Pe.indicesSet("output_indices",Le-2,"0")}; + var output_offset = ${Pe.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < ${a}u; m++) { + var output_value: ${Pe.type.value} = ${Pe.type.value}(0); + var workgroup_shared_offset: u32 = m; + for (var b: u32 = 0u; b < ${s}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${a}; + } + ${Pe.setByOffset("output_offset","output_value")}; + output_offset += ${d/Y}; + } + } + }`:` + ${Oe.registerUniforms(Tt).declareVariables(...Be,Pe)} + ${Oe.mainStart()} + ${Oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${Pe.type.value}, ${I}>; + var output_indices = ${Pe.offsetToIndices("global_idx")}; + var col = ${Pe.indicesGet("output_indices",Le-1)}; + var row = ${Pe.indicesGet("output_indices",Le-2)}; + var a_indices: ${$e.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 + ${Ae?` + var zero_point_abs_offset = col * ${Y} * ((${s} + 1) / 2); + var zero_point_index: u32 = zero_point_abs_offset / 4; + var zero_point_word: u32 = ${Ae.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} + var scale_index = col * ${s*Y}; + var b_indices: ${je.type.indices}; + for (var c: u32 = 0; c < ${Y}; c++) { + ${je.indicesSet("b_indices","0",`col * ${Y} + c`)}; + var block_offset: u32 = 0; + for (var block: u32 = 0; block < ${s}; block++) { + // The scale and zero points are computed per block. + let scale = ${Ue.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${oe}(${Ae?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${je.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${He} + scale_index++; + ${Et} + block_offset += uniforms.block_size / ${A}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${Ae?`if (zero_point_offset % 8 > 0) { + ${Et} + }`:""} + } + for (var k: u32 = 0u; k < ${I}u; k++) { + ${Pe.indicesSet("output_indices",Le-2,`${I} * row + k`)}; + ${Pe.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:F?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${e.cacheKey};${a};${$};${n.length}`,inputDependencies:Array(n.length).fill("rank")},getRunData:()=>({outputs:[{dims:ie,dataType:$}],name:F?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:F?{x:1,y:Math.ceil(d/Y),z:b}:{x:Math.ceil(ne/64)},programUniforms:le}),getShaderSource:_e}},Vv=(n,e)=>{eA(n.inputs,e);let r=n.getMaxComputeWorkgroupSizes(),t=n.getMaxComputeWorkgroupStoragesize();n.compute(tA(n.inputs,e,r,t))},Gv=n=>Ve(n)});var er,rA,qv,Hv,nA,Ol,Kv,Yv=q(()=>{"use strict";Ne();Ke();kt();os();ml();We();Ci();er=(n,e)=>n.length>e&&n[e].dims.length>0&&J.size(n[e].dims)>0?n[e]:void 0,rA=(n,e)=>{let r=n[0],t=er(n,1),i=er(n,2),o=er(n,3),s=er(n,4),a=er(n,5),u=er(n,6),d=er(n,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=!1,b=r.dims[0],w=r.dims[1],x=r.dims.length===3?m?r.dims[2]/3:r.dims[2]:e.numHeads*r.dims[4],$=w,I=0,A=0,k=Math.floor(x/e.numHeads);if(u&&d){if(u.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(u.dims[0]!==b||u.dims[1]!==e.numHeads||u.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[0]!==b||d.dims[1]!==e.numHeads||d.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[2]!==d.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');I=u.dims[2],A=u.dims[2]}else if(u||d)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let P;if(t){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(t.dims.length<3||t.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==t.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(t.dims.length===3){if(t.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');P=2,$=t.dims[1]}else if(t.dims.length===5){if(t.dims[2]!==e.numHeads||t.dims[3]!==2||t.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');P=5,$=t.dims[1]}else{if(t.dims[1]!==e.numHeads||t.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');P=0,$=t.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');P=3}if(o){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let z=0;if(s){z=8;let ne=s.dims;throw ne.length===1?ne[0]===b?z=1:ne[0]===3*b+2&&(z=3):ne.length===2&&ne[0]===b&&ne[1]===$&&(z=5),z===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,F=x;if(i){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if($!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');F=i.dims[2]}else{if($!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');F=i.dims[1]*i.dims[3],U=!0}}let Y=I+$,ie=!1;if(s)throw new Error("Key padding mask is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(a.dims[0]!==b&&a.dims[0]!==1||a.dims[1]!==e.numHeads||a.dims[2]!==w||a.dims[3]!==Y)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:b,sequenceLength:w,pastSequenceLength:I,kvSequenceLength:$,totalSequenceLength:Y,maxSequenceLength:A,inputHiddenSize:0,hiddenSize:x,vHiddenSize:F,headSize:k,vHeadSize:Math.floor(F/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:z,scale:e.scale,broadcastResPosBias:ie,passPastInKv:U,qkvFormat:P}},qv=n=>Ve({...n}),Hv=Ve({perm:[0,2,1,3]}),nA=(n,e,r,t,i,o,s)=>{let a=[t,i,o],u=J.size(a),d=[{type:12,data:u},{type:12,data:s},{type:12,data:o}],m=b=>{let w=de("qkv_with_bias",e.dataType,a),x=ee("qkv",e.dataType,a),$=ee("bias",r.dataType,a),I=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${b.registerUniforms(I).declareVariables(x,$,w)} + ${b.mainStart()} + ${b.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 n.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:e.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:m},{inputs:[e,r],outputs:[-1]})[0]},Ol=(n,e,r,t,i,o,s,a)=>{let u=o;if(s){if(t===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return u=nA(n,o,s,e,t,r*i,a),u=u.reshape([e,t,r,i]),n.compute(vr(u,Hv.perm),{inputs:[u],outputs:[-1]})[0]}else return o.dims.length===3&&(u=o.reshape([e,t,r,i])),n.compute(vr(u,Hv.perm),{inputs:[u],outputs:[-1]})[0]},Kv=(n,e)=>{let r=rA(n.inputs,e),t=n.inputs[0],i=er(n.inputs,1),o=er(n.inputs,2),s=er(n.inputs,3),a=er(n.inputs,4),u=er(n.inputs,5),d=er(n.inputs,6),m=er(n.inputs,7);if(t.dims.length===5)throw new Error("Packed QKV is not implemented");if(i?.dims.length===5)throw new Error("Packed KV is not implemented");let b=i&&o&&i.dims.length===4&&o.dims.length===4,w=Ol(n,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,t,s,0);if(b)return ps(n,w,i,o,a,void 0,d,m,u,r,e);if(!i||!o)throw new Error("key and value must be provided");let x=Ol(n,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,s,r.hiddenSize),$=Ol(n,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,o,s,2*r.hiddenSize);ps(n,w,x,$,a,void 0,d,m,u,r,e)}});var iA,oA,aA,sA,uA,lA,dA,cA,Xv,Zv=q(()=>{"use strict";Ne();Ke();We();iA=n=>{if(!n||n.length<1)throw new Error("Too few inputs");if(n[0].dataType!==1&&n[0].dataType!==10)throw new Error("Input type must be float or float16.");if(n.length>=2){let e=n[0].dims.length*2===n[1].dims[0];if(n.length===4&&(e=n[3].dims[0]*2===n[1].dims[0]),!e)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},oA=(n,e,r)=>{let t="";for(let i=e-1;i>=0;--i)t+=` + k = i32(${n.indicesGet("indices",i)}) - ${ze("uniforms.pads",i,r)}; + if (k < 0) { + break; + } + if (k >= i32(${ze("uniforms.x_shape",i,e)})) { + break; + } + offset += k * i32(${ze("uniforms.x_strides",i,e)}); + `;return` + value = ${n.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${t} + value = x[offset]; + } + `},aA=(n,e,r)=>{let t="";for(let i=e-1;i>=0;--i)t+=` + k = i32(${n.indicesGet("indices",i)}) - ${ze("uniforms.pads",i,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${ze("uniforms.x_shape",i,e)}) - 1); + k = k % _2n_1; + if(k >= i32(${ze("uniforms.x_shape",i,e)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${ze("uniforms.x_strides",i,e)}); + `;return` + var offset = 0; + var k = 0; + ${t} + value = x[offset]; + `},sA=(n,e,r)=>{let t="";for(let i=e-1;i>=0;--i)t+=` + k = i32(${n.indicesGet("indices",i)}) - ${ze("uniforms.pads",i,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${ze("uniforms.x_shape",i,e)})) { + k = i32(${ze("uniforms.x_shape",i,e)}) - 1; + } + offset += k * i32(${ze("uniforms.x_strides",i,e)}); + `;return` + var offset = 0; + var k = 0; + ${t} + value = x[offset]; + `},uA=(n,e,r)=>{let t="";for(let i=e-1;i>=0;--i)t+=` + k = i32(${n.indicesGet("indices",i)}) - ${ze("uniforms.pads",i,r)}; + if (k < 0) { + k += i32(${ze("uniforms.x_shape",i,e)}]); + } + if (k >= i32(${ze("uniforms.x_shape",i,e)})) { + k -= i32(${ze("uniforms.x_shape",i,e)}); + } + offset += k * i32(${ze("uniforms.x_strides",i,e)}); + `;return` + var offset = 0; + var k = 0; + ${t} + value = x[offset]; + `},lA=(n,e,r)=>{switch(r.mode){case 0:return oA(n,e,r.pads.length);case 1:return aA(n,e,r.pads.length);case 2:return sA(n,e,r.pads.length);case 3:return uA(n,e,r.pads.length);default:throw new Error("Invalid mode")}},dA=(n,e)=>{let r=J.padShape(n[0].dims.slice(),e.pads),t=n[0].dims,i=J.size(r),o=[{type:12,data:i},{type:6,data:e.pads}];e.mode===0&&o.push({type:n[0].dataType,data:e.value}),o.push(...pe(n[0].dims,r));let s=["rank"],a=u=>{let d=de("output",n[0].dataType,r.length),m=ee("x",n[0].dataType,t.length),b=m.type.value,w=lA(d,t.length,e),x=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&x.push({name:"constant_value",type:b}),` + ${u.registerUniforms(x).declareVariables(m,d)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + + var value = ${b}(0); + ${w} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${e.mode}`,inputDependencies:s},getRunData:()=>({outputs:[{dims:r,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(J.size(r)/64)},programUniforms:o}),getShaderSource:a}},cA=(n,e)=>{if(n.length>1){let r=n[1].getBigInt64Array(),t=n.length>=3&&n[2].data?n[2].getFloat32Array()[0]:0,i=n[0].dims.length,o=new Int32Array(2*i).fill(0);if(n.length>=4){let a=n[3].getBigInt64Array();for(let u=0;uo[Number(u)]=Number(a));let s=[];return o.forEach(a=>s.push(a)),{mode:e.mode,value:t,pads:s}}else return e},Xv=(n,e)=>{iA(n.inputs);let r=cA(n.inputs,e);n.compute(dA(n.inputs,r),{inputs:[0]})}});var Ts,Jv,Qv,ew,tw,fA,pA,rw,nw,iw,ow,aw,sw,uw,lw,dw,cw,fw,pw,hw=q(()=>{"use strict";Lt();Ne();Ke();We();Ts=n=>{if(De.webgpu.validateInputContent&&(!n||n.length!==1))throw new Error("Pool ops requires 1 input.")},Jv=(n,e,r)=>{let t=e.format==="NHWC",i=n.dims.slice();t&&i.splice(1,0,i.pop());let o=Object.hasOwnProperty.call(e,"dilations"),s=e.kernelShape.slice(),a=e.strides.slice(),u=o?e.dilations.slice():[],d=e.pads.slice();jn.adjustPoolAttributes(r,i,s,a,u,d);let m=jn.computePoolOutputShape(r,i,a,u,s,d,e.autoPad),b=Object.assign({},e);o?Object.assign(b,{kernelShape:s,strides:a,pads:d,dilations:u,cacheKey:e.cacheKey}):Object.assign(b,{kernelShape:s,strides:a,pads:d,cacheKey:e.cacheKey});let w=m.slice();return w.push(w.splice(1,1)[0]),[b,t?w:m]},Qv=(n,e)=>{let r=e.format==="NHWC",t=J.size(n),i=J.size(e.kernelShape),o=[{type:12,data:t},{type:12,data:i}],s=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(e.kernelShape.length<=2){let a=e.kernelShape[e.kernelShape.length-1],u=e.strides[e.strides.length-1],d=e.pads[e.pads.length/2-1],m=e.pads[e.pads.length-1],b=!!(d+m);o.push({type:12,data:a},{type:12,data:u},{type:12,data:d},{type:12,data:m}),s.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let w=!1;if(e.kernelShape.length===2){let x=e.kernelShape[e.kernelShape.length-2],$=e.strides[e.strides.length-2],I=e.pads[e.pads.length/2-2],A=e.pads[e.pads.length-2];w=!!(I+A),o.push({type:12,data:x},{type:12,data:$},{type:12,data:I},{type:12,data:A}),s.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,s,!0,b,w]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=J.computeStrides(e.kernelShape);o.push({type:12,data:a},{type:12,data:e.pads},{type:12,data:e.strides}),s.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:e.pads.length},{name:"strides",type:"u32",length:e.strides.length});let u=e.pads.reduce((d,m)=>d+m);return[o,s,!!u,!1,!1]}},ew=(n,e,r,t,i,o,s,a,u,d,m,b)=>{let w=i.format==="NHWC",x=e.type.value,$=de("output",e.type.tensor,t);if(i.kernelShape.length<=2){let I="",A="",k="",P=r-(w?2:1);if(m?I=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${P}] = indices[${P}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${P}] < 0 || xIndices[${P}] + >= uniforms.x_shape[${P}]) { + pad++; + continue; + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + }`:I=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${P}] = indices[${P}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + }`,i.kernelShape.length===2){let U=r-(w?3:2);b?A=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${U}] = indices[${U}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${U}] < 0 || xIndices[${U}] >= uniforms.x_shape[${U}]) { + pad += i32(uniforms.kw); + continue; + } + `:A=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${U}] = indices[${U}] * uniforms.sh - uniforms.phStart + j; + `,k=` + } + `}return` + ${n.registerUniforms(u).declareVariables(e,$)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${$.offsetToIndices("global_idx")}; + var xIndices = ${$.offsetToIndices("global_idx")}; + + var value = ${x}(${a}); + var pad = 0; + ${A} + ${I} + ${k} + ${s} + + output[global_idx] = value; + }`}else{if(w)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let I=i.kernelShape.length,A=i.pads.length,k="";return d?k=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + }`:k=` + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + `,` + ${n.registerUniforms(u).declareVariables(e,$)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${$.offsetToIndices("global_idx")}; + var xIndices = ${$.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${x}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${I-1}u; j++) { + offsets[j] = offset / ${ze("uniforms.kernelStrides","j",I)}; + offset -= offsets[j] * ${ze("uniforms.kernelStrides","j",I)}; + } + offsets[${I-1}] = offset; + + isPad = false; + for (var j = ${r-I}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${ze("uniforms.strides",`j - ${r-I}u`,I)} + + offsets[j - ${r-I}u] - ${ze("uniforms.pads","j - 2u",A)}; + ${k} + } + ${s} + + output[global_idx] = value; + }`}},tw=n=>`${n.format};${n.ceilMode};${n.autoPad};${n.kernelShape.length}`,fA=n=>`${tw(n)};${n.countIncludePad}`,pA=n=>`${tw(n)};${n.storageOrder};${n.dilations}`,rw=n=>({format:n.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],ceilMode:n.ceil_mode,kernelShape:n.kernel_shape,strides:n.strides,pads:n.pads}),nw=(n,e,r,t)=>{let[i,o]=Jv(e,t,r),s=ee("x",e.dataType,e.dims.length),a=s.type.value,u="value += x_val;",d="";i.countIncludePad?d+=`value /= ${a}(uniforms.kernelSize);`:d+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[m,b,w,x,$]=Qv(o,i);m.push(...pe(e.dims,o));let I=["rank"];return{name:n,shaderCache:{hint:`${t.cacheKey};${w};${x};${$}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(J.size(o)/64)},programUniforms:m}),getShaderSource:A=>ew(A,s,e.dims.length,o.length,i,u,d,0,b,w,x,$)}},iw=n=>{let e=n.count_include_pad!==0,r=rw(n);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let t={countIncludePad:e,...r,cacheKey:""};return{...t,cacheKey:fA(t)}},ow=(n,e)=>{Ts(n.inputs),n.compute(nw("AveragePool",n.inputs[0],!1,e))},aw={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},sw=n=>{let e=n.format;return{format:e,...aw,cacheKey:e}},uw=(n,e)=>{Ts(n.inputs),n.compute(nw("GlobalAveragePool",n.inputs[0],!0,e))},lw=(n,e,r,t)=>{let[i,o]=Jv(e,t,r),s=` + value = max(x_val, value); + `,a="",u=ee("x",e.dataType,e.dims.length),d=["rank"],[m,b,w,x,$]=Qv(o,i);return m.push(...pe(e.dims,o)),{name:n,shaderCache:{hint:`${t.cacheKey};${w};${x};${$}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(J.size(o)/64)},programUniforms:m}),getShaderSource:I=>ew(I,u,e.dims.length,o.length,i,s,a,e.dataType===10?-65504:-1e5,b,w,x,$)}},dw=(n,e)=>{Ts(n.inputs),n.compute(lw("MaxPool",n.inputs[0],!1,e))},cw=n=>{let e=n.storage_order,r=n.dilations,t=rw(n);if(e!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:e,dilations:r,...t,cacheKey:""};return{...i,cacheKey:pA(i)}},fw=n=>{let e=n.format;return{format:e,...aw,cacheKey:e}},pw=(n,e)=>{Ts(n.inputs),n.compute(lw("GlobalMaxPool",n.inputs[0],!0,e))}});var mA,gA,mw,gw=q(()=>{"use strict";Lt();Ne();We();mA=(n,e,r)=>{let t=n===e,i=ne&&r>0;if(t||i||o)throw new Error("Range these inputs' contents are invalid.")},gA=(n,e,r,t)=>{let i=Math.abs(Math.ceil((e-n)/r)),o=[i],s=i,a=[{type:12,data:s},{type:t,data:n},{type:t,data:r},...pe(o)],u=d=>{let m=de("output",t,o.length),b=m.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:b},{name:"delta",type:b}];return` + ${d.registerUniforms(w).declareVariables(m)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${b}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${t}`},getShaderSource:u,getRunData:()=>({outputs:[{dims:o,dataType:t}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:a})}},mw=n=>{let e=0,r=0,t=0;n.inputs[0].dataType===6?(e=n.inputs[0].getInt32Array()[0],r=n.inputs[1].getInt32Array()[0],t=n.inputs[2].getInt32Array()[0]):n.inputs[0].dataType===1&&(e=n.inputs[0].getFloat32Array()[0],r=n.inputs[1].getFloat32Array()[0],t=n.inputs[2].getFloat32Array()[0]),De.webgpu.validateInputContent&&mA(e,r,t),n.compute(gA(e,r,t,n.inputs[0].dataType),{inputs:[]})}});var yA,bA,vA,wA,_A,xA,$A,TA,SA,IA,CA,yw,AA,EA,OA,PA,kA,bw,vw,ww=q(()=>{"use strict";Ne();Ke();kt();We();yA=(n,e)=>{if(n.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),n.length>0){if(e.mode==="linear"){if(!(n.length===2||n.length===3||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1||n.length===5&&n[0]===1&&n[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"&&!(n.length===2||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},bA=(n,e,r)=>{e.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let t=new Array(r).fill(1);return e.forEach((i,o)=>t[i]=n[o]),t},vA=(n,e,r,t,i,o)=>{let[s,a,u]=r>10?[1,2,3]:[-1,n.length>1?1:-1,-1],d=n[0].dims.length;if(s>0&&n.length>s&&n[s].dims.length>0)n[s].getFloat32Array().forEach(m=>o.push(m));else if(e.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&n.length>a&&n[a].dims.length>0){if(n[a].getFloat32Array().forEach(m=>t.push(m)),t.length!==0&&t.length!==d&&r>=18&&t.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");yA(t,e),e.axes.length>0&&bA(t,e.axes,d).forEach((m,b)=>t[b]=m)}if(u>0&&n.length>u&&(n[u].getBigInt64Array().forEach(m=>i.push(Number(m))),i.length!==d||r>=18&&i.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(t.length!==e.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.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 t<"u"&&typeof i<"u"&&t.length>0&&i.length>d)throw new Error("Resize requires only of scales or sizes to be specified")},wA=(n,e)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${e} { `+(()=>{switch(n){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 ${n} is not supported`)}})()+"}",_A=(n,e,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(n){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 ${n} is not supported`)}})()+"}",xA=(n,e,r)=>{let t=new Array(r).fill(0).concat(new Array(r).fill(1)),i=n.length===0?t:n.slice();return e.length>0?(e.forEach((o,s)=>{t[o]=i[s],t[s+r]=i[e.length+s]}),t):i},$A=(n,e,r,t)=>{let i=[];if(r.length>0)if(t.length>0){if(n.forEach(o=>i.push(o)),Math.max(...t)>n.length)throw new Error("axes is out of bound");t.forEach((o,s)=>i[o]=r[s])}else r.forEach(o=>i.push(o));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");i=n.map((o,s)=>Math.round(o*e[s]))}return i},TA=(n,e,r)=>{let t=(()=>{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 i=n.slice();return r.axes.length>0?(r.axes.forEach(o=>e[o]=t),r.axes.forEach(o=>i[o]=Math.round(n[o]*e[o]))):(e.fill(t,0,e.length),i.forEach((o,s)=>i[s]=Math.round(o*e[s]))),i},SA=(n,e,r,t,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${n.type.indices}) -> array<${n.type.value}, ${r.length}> { + var original_indices: array<${n.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${n.indicesGet("output_indices","i")}; + var scale = ${ze("uniforms.scales","i",t)}; + var roi_low = ${ze("uniforms.roi","i",i)}; + var roi_hi = ${ze("uniforms.roi",`i + ${e.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${n.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; + }`,IA=(n,e,r,t,i,o,s)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> ${n.type.indices} { + var input_indices: ${n.type.indices}; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${ze("uniforms.scales","i",i)}; + 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",t.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${s} || (original_idx >= 0 && original_idx < ${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); + } + } + ${n.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,CA=(n,e)=>` + fn checkInputIndices(input_indices: ${n.type.indices}) -> bool { + for (var i:u32 = 0; i < ${e.length}; i++) { + var input_index = ${n.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${ze("uniforms.input_shape","i",e.length)}) { + return false; + } + } + return true; + }`,yw=(n,e,r,t)=>n.rank>t?` + ${n.indicesSet("input_indices",e,"channel")}; + ${n.indicesSet("input_indices",r,"batch")}; +`:"",AA=(n,e,r,t,i)=>{let[s,a,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=n.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} { + var input_indices: ${n.type.indices}; + ${n.indicesSet("input_indices",a,`max(0, min(row, ${r[a]} - 1))`)}; + ${n.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; + ${yw(n,d,s,2)} + return ${n.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${e.type.indices}) -> ${m} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${m} = originalIndices[${a}]; + var col:${m} = originalIndices[${u}]; + ${t?`if (row < 0 || row > (${r[a]} - 1) || col < 0 || col > (${r[u]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${r[a]} - 1)); + col = max(0, min(col, ${r[u]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${r.length>2?`u32(originalIndices[${d}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${s}])`:"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); + }`},EA=(n,e,r,t,i,o,s,a,u,d)=>{let m=r.length===2,b=!0,[w,x]=m?[0,1]:b?[2,3]:[1,2],$=n.type.value,I=A=>{let k=A===w?"row":"col";return` + fn ${k}CubicInterpolation(input_indices: ${n.type.indices}, output_indices: ${e.type.indices}) -> ${$} { + var output_index = ${e.indicesGet("output_indices",A)}; + var originalIdx: ${$} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[A]}, + ${t[A]}, ${r[A]}, ${o[A]}, ${o[A]} + ${r.length}); + var fractOriginalIdx: ${$} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${r[A]} - 1))) { + return ${u}; + } + var data: array<${$}, 4> = array<${$}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${k}: ${$} = originalIdx + ${$}(i); + if (${k} < 0 || ${k} >= ${r[A]}) { + ${(()=>d?`coefs[i + 1] = 0.0; + continue;`:a?`return ${u};`:`${k} = max(0, min(${k}, ${r[A]} - 1));`)()}; + } + var input_indices_copy: ${n.type.indices} = input_indices; + ${n.indicesSet("input_indices_copy",A,`u32(${k})`)}; + data[i + 1] = ${A===w?n.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${I(w)}; + ${I(x)}; + 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] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s}; + coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1; + coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${$}, 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: ${n.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},OA=(n,e,r,t,i)=>{let[s,a,u,d,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],b=n.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${b} { + var input_indices: ${n.type.indices}; + ${n.indicesSet("input_indices",a,`max(0, min(depth, ${r[a]} - 1))`)}; + ${n.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; + ${n.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; + ${yw(n,m,s,3)} + return ${n.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${b} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${b} = originalIndices[${a}]; + var height:${b} = originalIndices[${u}]; + var width:${b} = originalIndices[${d}]; + ${t?`if (depth < 0 || depth > (${r[a]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${r[a]} - 1)); + height = max(0, min(height, ${r[u]} - 1)); + width = max(0, min(width, ${r[d]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${r.length>3?`u32(originalIndices[${m}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${s}])`:"0"}; + + var x111: ${b} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${b} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${b} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${b} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${b} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${b} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${b} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${b} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${b} = abs(depth - ${b}(depth1)); + var dx2: ${b} = abs(${b}(depth2) - depth); + var dy1: ${b} = abs(height - ${b}(height1)); + var dy2: ${b} = abs(${b}(height2) - height); + var dz1: ${b} = abs(width - ${b}(width1)); + var dz2: ${b} = abs(${b}(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); + }`},PA=(n,e,r,t,i,o)=>{let s=n.dims,a=xA(o,e.axes,s.length),u=$A(s,t,i,e.axes),d=t.slice();t.length===0&&(d=s.map((P,z)=>P===0?1:u[z]/P),e.keepAspectRatioPolicy!=="stretch"&&(u=TA(s,d,e)));let m=de("output",n.dataType,u.length),b=ee("input",n.dataType,s.length),w=J.size(u),x=s.length===u.length&&s.every((P,z)=>P===u[z]),$=e.coordinateTransformMode==="tf_crop_and_resize",I=e.extrapolationValue,A=b.type.value,k=P=>` + ${x?"":` + ${wA(e.coordinateTransformMode,A)}; + ${(()=>{switch(e.mode){case"nearest":return` + ${CA(b,s)}; + ${_A(e.nearestMode,r,A)}; + ${IA(b,m,s,u,d.length,a.length,$)}; + `;case"linear":return` + ${SA(m,s,u,d.length,a.length)}; + ${(()=>{if(s.length===2||s.length===4)return`${AA(b,m,s,$,I)}`;if(s.length===3||s.length===5)return`${OA(b,m,s,$,I)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(s.length===2||s.length===4)return`${EA(b,m,s,u,d,a,e.cubicCoeffA,$,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")}})()}; + `} + ${P.registerUniform("output_size","u32").registerUniform("scales","f32",d.length).registerUniform("roi","f32",a.length).declareVariables(b,m)} + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${x?"output[global_idx] = input[global_idx];":` + let output_indices = ${m.offsetToIndices("global_idx")}; + var input_indices: ${b.type.indices}; + ${(()=>{switch(e.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${b.getByIndices("input_indices")}; + } else { + output[global_idx] = ${e.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${s.length===2||s.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${e.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${e.cacheKey}|${r}|${d.length>0?d:""}|${i.length>0?i:""}|${a.length>0?a:""}|${x}|${s}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[{dims:u,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:d},{type:1,data:a},...pe(s,u)]})}},kA=n=>{let e=n.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},bw=(n,e)=>{let r=[],t=[],i=[],o=kA(n);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");vA(n.inputs,e,o,r,t,i),n.compute(PA(n.inputs[0],e,o,r,t,i),{inputs:[0]})},vw=n=>{let e=n.antialias,r=n.axes,t=n.coordinateTransformMode,i=n.cubicCoeffA,o=n.excludeOutside!==0,s=n.extrapolationValue,a=n.keepAspectRatioPolicy,u=n.mode,d=n.nearestMode===""?"simple":n.nearestMode;return Ve({antialias:e,axes:r,coordinateTransformMode:t,cubicCoeffA:i,excludeOutside:o,extrapolationValue:s,keepAspectRatioPolicy:a,mode:u,nearestMode:d})}});var DA,BA,_w,xw=q(()=>{"use strict";Ne();Ke();kt();We();DA=(n,e)=>{let[r,t,i,o]=n,{numHeads:s,rotaryEmbeddingDim:a}=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(!J.areEqual(t.dims,[])&&!J.areEqual(t.dims,[1])&&t.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${t.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!J.areEqual(i.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&s===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let u=r.dims[0],d=r.dims[r.dims.length-2],m=i.dims[0],b=J.sizeFromDimension(r.dims,1)/d,w=a===0?i.dims[1]*2:b/s;if(a>w)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(t.dims.length===2){if(u!==t.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${t.dims[0]}`);if(d!==t.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${t.dims[1]}`)}if(w/2!==i.dims[1]&&a/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(d>m)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},BA=(n,e)=>{let{interleaved:r,numHeads:t,rotaryEmbeddingDim:i,scale:o}=e,s=n[0].dims[0],a=J.sizeFromDimension(n[0].dims,1),u=n[0].dims[n[0].dims.length-2],d=a/u,m=n[2].dims[1],b=i===0?m*2:d/t,w=new Array(s,u,d/b,b-m),x=J.computeStrides(w),$=[{type:1,data:o},{type:12,data:w},{type:12,data:x},...n[0].dims.length===3?new Array({type:12,data:[a,d,b,1]}):[],...n[0].dims.length===4?new Array({type:12,data:[a,b,u*b,1]}):[],...pe(n[0].dims,n[1].dims,n[2].dims,n[3].dims,n[0].dims)],I=A=>{let k=ee("input",n[0].dataType,n[0].dims.length),P=ee("position_ids",n[1].dataType,n[1].dims.length),z=ee("cos_cache",n[2].dataType,n[2].dims.length),U=ee("sin_cache",n[3].dataType,n[3].dims.length),F=de("output",n[0].dataType,n[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:x.length},{name:"input_output_strides",type:"u32",length:x.length}]),` + ${A.declareVariables(k,P,z,U,F)} + + ${A.mainStart(Un)} + let half_rotary_emb_dim = uniforms.${z.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${A.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${P.broadcastedIndicesToOffset("bsnh.xy",de("",P.type.tensor,2))}; + let position_id = + u32(${P.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 = ${k.getByOffset("i")} * ${z.get("position_id","bsnh[3]")} - + ${k.getByOffset("j")} * ${U.get("position_id","bsnh[3]")}; + ${F.setByOffset("i","re")} + let im = ${k.getByOffset("i")} * ${U.get("position_id","bsnh[3]")} + + ${k.getByOffset("j")} * ${z.get("position_id","bsnh[3]")}; + ${F.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${F.setByOffset("k",k.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Ve({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(J.size(w)/Un)},programUniforms:$})}},_w=(n,e)=>{DA(n.inputs,e),n.compute(BA(n.inputs,e))}});var RA,zA,$w,Tw=q(()=>{"use strict";Ne();Ke();We();RA=n=>{if(!n||n.length<3)throw new Error("layerNorm requires at least 3 inputs.");let e=n[0],r=n[1],t=n[2];if(e.dataType!==r.dataType||e.dataType!==t.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 i=e.dims[e.dims.length-1],o=e.dims[e.dims.length-2];if(r.dims[r.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(t.dims.length!==1)throw new Error("Gamma must be 1D");if(t.dims[t.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(n.length>3){let s=n[3];if(s.dims.length!==1)throw new Error("Beta must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(n.length>4){let s=n[4];if(s.dims.length!==1)throw new Error("Bias must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},zA=(n,e,r,t)=>{let i=e.simplified,o=n[0].dims,s=J.size(o),a=o,u=s,d=o.slice(-1)[0],m=t?o.slice(0,-1).concat(1):[],b=!i&&n.length>3,w=n.length>4,x=t&&r>1,$=t&&r>2,I=r>3,A=dt(d),k=[{type:12,data:u},{type:12,data:A},{type:12,data:d},{type:1,data:e.epsilon}],P=U=>{let F=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Y=[ee("x",n[0].dataType,n[0].dims,A),ee("skip",n[1].dataType,n[1].dims,A),ee("gamma",n[2].dataType,n[2].dims,A)];b&&Y.push(ee("beta",n[3].dataType,n[3].dims,A)),w&&Y.push(ee("bias",n[4].dataType,n[4].dims,A)),Y.push(de("output",n[0].dataType,a,A)),x&&Y.push(de("mean_output",1,m)),$&&Y.push(de("inv_std_output",1,m)),I&&Y.push(de("input_skip_bias_sum",n[0].dataType,a,A));let ie=ut(n[0].dataType);return` + + ${U.registerUniforms(F).declareVariables(...Y)} + + ${U.mainStart()} + ${U.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 = ${Er("f32",A)}; + var squareSum = ${Er("f32",A)}; + for (var i: u32 = 0; i < hidden_size_vectorized; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${w?"bias[i]":ie+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${I?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Fn(ie,A,"value")}; + sum += f32_value; + squareSum += f32_value * f32_value; + } + let mean = ${Or("sum",A)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Or("squareSum",A)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${x?"mean_output[global_idx] = mean;":""} + ${$?"inv_std_output[global_idx] = inv_std_dev;":""} + for (var i: u32 = 0; i < hidden_size_vectorized; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${ie}(mean)`}) * ${ie}(inv_std_dev) * gamma[i] ${b?"+ beta[i]":""}; + } + }`},z=[{dims:a,dataType:n[0].dataType}];return r>1&&z.push({dims:m,dataType:1}),r>2&&z.push({dims:m,dataType:1}),r>3&&z.push({dims:o,dataType:n[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${A};${x};${$};${I}`,inputDependencies:n.map((U,F)=>"type")},getShaderSource:P,getRunData:()=>({outputs:z,dispatchGroup:{x:Math.ceil(u/d/64)},programUniforms:k})}},$w=(n,e)=>{RA(n.inputs);let t=[0];n.outputCount>1&&t.push(-3),n.outputCount>2&&t.push(-3),n.outputCount>3&&t.push(3),n.compute(zA(n.inputs,e,n.outputCount,!1),{outputs:t})}});var MA,Ss,NA,Sw,LA,jA,Iw,Cw,Aw=q(()=>{"use strict";Ne();Ke();kt();We();MA=(n,e)=>{if(!n||n.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");n.slice(1).forEach((r,t)=>{if(n[t+1].dataType!==6&&n[t+1].dataType!==7)throw new Error(`Input ${t} must be an array of int32 or int64`)})},Ss=(n,e)=>{let r=[];if(n.length>e)if(n[e].dataType===7)n[e].getBigInt64Array().forEach(t=>r.push(Number(t)));else if(n[e].dataType===6)n[e].getInt32Array().forEach(t=>r.push(Number(t)));else throw new Error(`Input ${e} must be an array of int32 or int64`);return r},NA=(n,e)=>{if(n.length>1){let r=Ss(n,1),t=Ss(n,2),i=Ss(n,3);return i.length===0&&(i=[...Array(n[0].dims.length).keys()]),Ve({starts:r,ends:t,axes:i})}else return e},Sw=(n,e,r,t,i)=>{let o=n;return n<0&&(o+=r[t[e]]),i[e]<0?Math.max(0,Math.min(o,r[t[e]]-1)):Math.max(0,Math.min(o,r[t[e]]))},LA=(n,e,r)=>`fn calculateInputIndices(output_indices: ${e.type.indices}) -> ${n.type.indices} { + var input_indices: ${n.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; + } + ${n.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,jA=(n,e)=>{let r=n[0].dims,t=J.size(r),i=e.axes.length>0?J.normalizeAxes(e.axes,r.length):[...Array(r.length).keys()],o=Ss(n,4);o.forEach(k=>k!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(i.length).fill(1));let s=e.starts.map((k,P)=>Sw(k,P,r,i,o)),a=e.ends.map((k,P)=>Sw(k,P,r,i,o));if(i.length!==s.length||i.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let k=0;kMath.sign(k));o.forEach((k,P,z)=>{if(k<0){let U=(a[P]-s[P])/k,F=s[P],Y=F+U*o[P];s[P]=Y,a[P]=F,z[P]=-k}});let d=r.slice(0);i.forEach((k,P)=>{d[k]=Math.ceil((a[k]-s[k])/o[k])});let m={dims:d,dataType:n[0].dataType},b=de("output",n[0].dataType,d.length),w=ee("input",n[0].dataType,n[0].dims.length),x=J.size(d),$=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:u.length},{name:"steps",type:"u32",length:o.length}],I=[{type:12,data:x},{type:12,data:s},{type:6,data:u},{type:12,data:o},...pe(n[0].dims,d)],A=k=>` + ${k.registerUniforms($).declareVariables(w,b)} + ${LA(w,b,r)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${b.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${b.setByOffset("global_idx",w.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${u.length}_${s.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:I})}},Iw=(n,e)=>{MA(n.inputs,e);let r=NA(n.inputs,e);n.compute(jA(n.inputs,r),{inputs:[0]})},Cw=n=>{let e=n.starts,r=n.ends,t=n.axes;return Ve({starts:e,ends:r,axes:t})}});var UA,FA,Ew,Ow,Pw=q(()=>{"use strict";Ne();Ke();kt();We();UA=n=>{if(!n||n.length!==1)throw new Error("Softmax op requires 1 input.")},FA=(n,e)=>{let r=n.dims,t=J.size(r),i=64,o=e.axis;if(o<0&&(o=r.length+o),ok===4?`max(max(${A}.x, ${A}.y), max(${A}.z, ${A}.w))`:k===2?`max(${A}.x, ${A}.y)`:k===3?`max(max(${A}.x, ${A}.y), ${A}.z)`:A,b=ee("x",n.dataType,n.dims,u),w=de("result",n.dataType,n.dims,u),x=b.type.value,$=ut(n.dataType)==="f32"?`var threadMax = ${x}(-3.402823e+38f);`:`var threadMax = ${x}(-65504.0h);`,I=A=>` + var rowMaxShared : ${x}; + var rowSumShared : ${x}; + var threadShared : array<${x}, ${i}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${x} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${x}) { + let index = row * row_stride + col; + result[index] = value; + } + ${A.registerUniform("packedCols","i32").declareVariables(b,w)} + ${A.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${i}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${$} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${x}(${m("threadShared[0]",u)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${x}(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 = ${x}(${Or("threadShared[0]",u)}); + } + 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:`${u}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:n.dataType}],dispatchGroup:{x:a},programUniforms:[{type:6,data:d}]}),getShaderSource:I}},Ew=(n,e)=>{UA(n.inputs),n.compute(FA(n.inputs[0],e))},Ow=n=>Ve({axis:n.axis})});var VA,GA,WA,HA,qA,kw,Dw,Bw=q(()=>{"use strict";Ne();Ke();kt();We();VA=n=>{if(!n||n.length<1)throw new Error("too few inputs")},GA=(n,e)=>{let r=[],t=e.numOutputs;return n[1].dims[0]>0&&(n[1].getBigInt64Array().forEach(i=>r.push(Number(i))),t=r.length),Ve({numOutputs:t,axis:e.axis,splitSizes:r})},WA=n=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${n}u; i += 1u ) { + if (index < ${ze("uniforms.size_in_split_axis","i",n)}) { + return i; + } + } + return ${n}u; +}`,HA=n=>{let e=n.length,r=[];for(let t=0;t{let r=n[0].dims,t=J.size(r),i=n[0].dataType,o=J.normalizeAxis(e.axis,r.length),s=new Array(e.numOutputs),a=ee("input",i,r.length),u=new Array(e.numOutputs),d=[],m=[],b=0,w=[{type:12,data:t}];for(let $=0;$` + ${$.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",u.length).declareVariables(a,...s)} + ${WA(u.length)} + ${HA(s)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",o)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${ze("uniforms.size_in_split_axis","output_number - 1u",u.length)}; + ${a.indicesSet("indices",o,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:e.cacheKey,inputDependencies:["rank"]},getShaderSource:x,getRunData:()=>({outputs:d,dispatchGroup:{x:Math.ceil(t/64)},programUniforms:w})}},kw=(n,e)=>{VA(n.inputs);let r=n.inputs.length===1?e:GA(n.inputs,e);n.compute(qA(n.inputs,r),{inputs:[0]})},Dw=n=>{let e=n.axis,r=n.splitSizes,t=n.numOutputs<0?r.length:n.numOutputs;if(t!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Ve({axis:e,numOutputs:t,splitSizes:r})}});var Rw,KA,YA,XA,zw,Mw=q(()=>{"use strict";Ne();Ke();We();Rw=n=>Array.from(n.getBigInt64Array(),Number),KA=n=>{if(!n||n.length!==2)throw new Error("Tile requires 2 inputs.");if(n[0].dataType!==1&&n[0].dataType!==6&&n[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(n[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(n[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Rw(n[1]).length!==n[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},YA=(n,e)=>{let r=[];for(let t=0;t{let e=n[0].dims,r=Rw(n[1]),t=YA(e,r),i=J.size(t),o=n[0].dataType,s=ee("input",o,e.length),a=de("output",o,t.length),u=d=>` + const inputShape = ${s.indices(...e)}; + ${d.registerUniform("output_size","u32").declareVariables(s,a)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${a.offsetToIndices("global_idx")}; + var input_indices: ${s.type.indices}; + for (var i = 0; i < ${e.length}; i++) { + let input_dim_i = ${s.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${a.indicesGet("output_indices","i")} % input_dim_i; + + ${s.indicesSet("input_indices","i","input_dim_value")} + } + ${a.setByOffset("global_idx",s.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...pe(n[0].dims,t)]}),getShaderSource:u}},zw=n=>{KA(n.inputs),n.compute(XA(n.inputs),{inputs:[0]})}});var ZA,JA,Nw,Lw=q(()=>{"use strict";Ne();Ke();We();ZA=(n,e,r,t,i)=>{let o=de("output_data",i,r.length,4),s=ee("a_data",e[1].dataType,e[1].dims.length,4),a=ee("b_data",e[2].dataType,e[2].dims.length,4),u=ee("c_data",e[0].dataType,e[0].dims.length,4),d,m=(b,w,x)=>`select(${w}, ${b}, ${x})`;if(!t)d=o.setByOffset("global_idx",m(s.getByOffset("global_idx"),a.getByOffset("global_idx"),u.getByOffset("global_idx")));else{let b=(w,x,$="")=>{let I=`a_data[index_a${x}][component_a${x}]`,A=`b_data[index_b${x}][component_b${x}]`,k=`bool(c_data[index_c${x}] & (0xffu << (component_c${x} * 8)))`;return` + let output_indices${x} = ${o.offsetToIndices(`global_idx * 4u + ${x}u`)}; + let offset_a${x} = ${s.broadcastedIndicesToOffset(`output_indices${x}`,o)}; + let offset_b${x} = ${a.broadcastedIndicesToOffset(`output_indices${x}`,o)}; + let offset_c${x} = ${u.broadcastedIndicesToOffset(`output_indices${x}`,o)}; + let index_a${x} = offset_a${x} / 4u; + let index_b${x} = offset_b${x} / 4u; + let index_c${x} = offset_c${x} / 4u; + let component_a${x} = offset_a${x} % 4u; + let component_b${x} = offset_b${x} % 4u; + let component_c${x} = offset_c${x} % 4u; + ${w}[${x}] = ${$}(${m(I,A,k)}); + `};i===9?d=` + var data = vec4(0); + ${b("data",0,"u32")} + ${b("data",1,"u32")} + ${b("data",2,"u32")} + ${b("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:d=` + ${b("output_data[global_idx]",0)} + ${b("output_data[global_idx]",1)} + ${b("output_data[global_idx]",2)} + ${b("output_data[global_idx]",3)} + `}return` + ${n.registerUniform("vec_size","u32").declareVariables(u,s,a,o)} + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${d} + }`},JA=n=>{let e=n[1].dims,r=n[2].dims,t=n[0].dims,i=n[1].dataType,o=!(J.areEqual(e,r)&&J.areEqual(r,t)),s=e,a=J.size(e);if(o){let d=Ur.calcShape(Ur.calcShape(e,r,!1),t,!1);if(!d)throw new Error("Can't perform where op on the given tensors");s=d,a=J.size(s)}let u=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>ZA(d,n,s,o,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:u},...pe(t,e,r,s)]})}},Nw=n=>{n.compute(JA(n.inputs))}});var jw,Uw=q(()=>{"use strict";Zb();ml();r0();i0();F0();Q0();hl();wl();pv();gv();vv();Tv();Cv();Ev();kv();Rv();Nv();jv();Fv();xl();Wv();Yv();Zv();hw();gw();ds();ww();xw();Tw();Aw();Pw();Bw();Mw();Ci();gs();Lw();jw=new Map([["Abs",[o0]],["Acos",[a0]],["Acosh",[s0]],["Add",[V0]],["ArgMax",[Xb,pl]],["ArgMin",[Yb,pl]],["Asin",[u0]],["Asinh",[l0]],["Atan",[d0]],["Atanh",[c0]],["Attention",[e0]],["AveragePool",[ow,iw]],["BatchNormalization",[t0]],["BiasAdd",[n0]],["BiasSplitGelu",[U0]],["Cast",[p0,f0]],["Ceil",[m0]],["Clip",[h0]],["Concat",[Jb,Qb]],["Conv",[Sl,Tl]],["ConvTranspose",[fv,cv]],["Cos",[g0]],["Cosh",[y0]],["CumSum",[hv,mv]],["DepthToSpace",[yv,bv]],["Div",[G0]],["Einsum",[xv,$v]],["Elu",[b0,hs]],["Equal",[W0]],["Erf",[v0]],["Exp",[w0]],["Expand",[Iv]],["FastGelu",[Av]],["Floor",[_0]],["FusedConv",[Sl,Tl]],["Gather",[Pv,Ov]],["GatherElements",[Bv,Dv]],["Gelu",[x0]],["Gemm",[Mv,zv]],["GlobalAveragePool",[uw,sw]],["GlobalMaxPool",[pw,fw]],["Greater",[Y0]],["GreaterOrEqual",[Z0]],["HardSigmoid",[O0,E0]],["InstanceNormalization",[Lv]],["LayerNormalization",[Uv]],["LeakyRelu",[$0,hs]],["Less",[X0]],["LessOrEqual",[J0]],["Log",[L0]],["MatMul",[ov]],["MatMulNBits",[Vv,Gv]],["MaxPool",[dw,cw]],["Mul",[H0]],["MultiHeadAttention",[Kv,qv]],["Neg",[S0]],["Not",[T0]],["Pad",[Xv]],["Pow",[q0]],["Range",[mw]],["Reciprocal",[I0]],["ReduceMin",[Vb]],["ReduceMean",[Nb]],["ReduceMax",[Fb]],["ReduceSum",[Wb]],["ReduceProd",[Gb]],["ReduceL1",[Lb]],["ReduceL2",[jb]],["ReduceLogSum",[qb]],["ReduceLogSumExp",[Ub]],["ReduceSumSquare",[Hb]],["Relu",[C0]],["Resize",[bw,vw]],["RotaryEmbedding",[_w]],["Sigmoid",[A0]],["Sin",[P0]],["Sinh",[k0]],["Slice",[Iw,Cw]],["SkipLayerNormalization",[$w]],["Split",[kw,Dw]],["Sqrt",[D0]],["Softmax",[Ew,Ow]],["Sub",[K0]],["Tan",[B0]],["Tanh",[z0]],["ThresholdedRelu",[N0,hs]],["Tile",[zw]],["Transpose",[Sb,Ib]],["Where",[Nw]]])});var Is,Fw=q(()=>{"use strict";Lt();cn();We();Is=class{constructor(e){this.backend=e;this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,i,o){sr(e.programInfo.name);let s=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let m of r)u.push({binding:u.length,resource:{buffer:m.buffer}});for(let m of t)u.push({binding:u.length,resource:{buffer:m.buffer}});o&&u.push({binding:u.length,resource:o});let d=s.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let m={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}a.setPipeline(e.computePipeline),a.setBindGroup(0,d),a.dispatchWorkgroups(...i),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Xt(e.programInfo.name)}dispose(){}build(e,r){sr(e.name);let t=this.backend.device,i=[];t.features.has("shader-f16")&&i.push("enable f16;");let o=$b(r,this.backend.device.limits),s=e.getShaderSource(o),a=`${i.join(` +`)} +${o.additionalImplementations} +${s}`,u=t.createShaderModule({code:a,label:e.name});ft("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let d=t.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Xt(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&i<=o)return[r,t,i];let s=r*t*i,a=Math.ceil(Math.sqrt(s));if(a>o){if(a=Math.ceil(Math.cbrt(s)),a>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}});var QA,eE,Pl,Cs,Vw=q(()=>{"use strict";Lt();Ne();cn();yb();xb();Uw();Fw();QA=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let r=[];for(let t=0;t{let t=n.name;return n.shaderCache?.hint&&(t+="["+n.shaderCache.hint+"]"),t+=":"+r+`:${QA(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,t},Pl=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Cs=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 e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t};r.features.has("chromium-experimental-timestamp-query-inside-passes")?t.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&t.push("timestamp-query"),r.features.has("shader-f16")&&t.push("shader-f16"),this.device=await r.requestDevice(i),this.adapterInfo=new Pl(await r.requestAdapterInfo()),this.gpuDataManager=_b(this),this.programManager=new Is(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,mb(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;sr(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=x);let I=Number(x-this.queryTimeBase),A=Number($-this.queryTimeBase);if(!Number.isSafeInteger(I)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:b.map(k=>({dims:k.dims,dataType:dn(k.dataType)})),outputsMetadata:w.map(k=>({dims:k.dims,dataType:dn(k.dataType)})),kernelId:s,kernelType:u,kernelName:d,programName:m,startTime:I,endTime:A});else{let k="";b.forEach((z,U)=>{k+=`input[${U}]: [${z.dims}] | ${dn(z.dataType)}, `});let P="";w.forEach((z,U)=>{P+=`output[${U}]: [${z.dims}] | ${dn(z.dataType)}, `}),console.log(`[profiling] kernel "${s}|${u}|${d}|${m}" ${k}${P}execution time: ${A-I} ns`)}sa("GPU",`${m}::${x}::${$}`)}e.unmap(),this.pendingQueries.delete(e)}),Xt()}run(e,r,t,i,o,s){sr(e.name);let a=[];for(let z=0;zU):t;if(b.length!==u.length)throw new Error(`Output size ${b.length} must be equal to ${u.length}.`);let w=[],x=[];for(let z=0;z=s)throw new Error(`Invalid output index: ${b[z]}`);if(b[z]===-3)continue;let U=b[z]===-1,F=b[z]===-2,Y=U||F?o(u[z].dataType,u[z].dims):i(b[z],u[z].dataType,u[z].dims);if(w.push(Y),Y.data===0)continue;let ie=this.gpuDataManager.get(Y.data);if(!ie)throw new Error(`no GPU data for output: ${Y.data}`);if(U&&this.temporaryData.push(ie),F){let ne=this.kernelPersistentData.get(this.currentKernelId);ne||(ne=[],this.kernelPersistentData.set(this.currentKernelId,ne)),ne.push(ie)}x.push(ie)}if(a.length!==r.length||x.length!==w.length){if(x.length===0)return Xt(e.name),w;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let $;if(m){let z=0,U=[];m.forEach(ne=>{let le=typeof ne.data=="number"?[ne.data]:ne.data;if(le.length===0)return;let ge=ne.type===10?2:4,se,re;ne.type===10?(re=le.length>4?16:le.length>2?8:le.length*ge,se=le.length>4?16:ge*le.length):(re=le.length<=2?le.length*ge:16,se=16),z=Math.ceil(z/re)*re,U.push(z);let _e=ne.type===10?8:4;z+=le.length>4?Math.ceil(le.length/_e)*se:le.length*ge});let F=16;z=Math.ceil(z/F)*F;let Y=new ArrayBuffer(z);m.forEach((ne,le)=>{let ge=U[le],se=typeof ne.data=="number"?[ne.data]:ne.data;if(ne.type===6)new Int32Array(Y,ge,se.length).set(se);else if(ne.type===12)new Uint32Array(Y,ge,se.length).set(se);else if(ne.type===10)new Uint16Array(Y,ge,se.length).set(se);else if(ne.type===1)new Float32Array(Y,ge,se.length).set(se);else throw new Error(`Unsupported uniform type: ${dn(ne.type)}`)});let ie=this.gpuDataManager.create(z,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(ie.buffer,0,Y,0,z),this.gpuDataManager.release(ie.id),$={offset:0,size:z,buffer:ie.buffer}}let I=this.programManager.normalizeDispatchGroupSize(d),A=I[1]===1&&I[2]===1,k=eE(e,r,A),P=this.programManager.getArtifact(k);if(P||(P=this.programManager.build(e,I),this.programManager.setArtifact(k,P),ft("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),m&&P.uniformVariablesInfo){if(m.length!==P.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${P.uniformVariablesInfo.length}, got ${m.length} in program "${P.programInfo.name}".`);for(let z=0;z`[ProgramManager] run "${e.name}" (key=${k}) with ${I[0]}x${I[1]}x${I[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let z={kernelId:this.currentKernelId,programName:P.programInfo.name,inputTensorViews:r,outputTensorViews:w};this.pendingKernels.push(z),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(z)}return this.programManager.run(P,a,x,I,$),Xt(e.name),w}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,i){let o=jw.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let s={kernelType:e,kernelName:i,kernelEntry:o[0],attributes:[o[1],t]};this.kernels.set(r,s)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let o=i.kernelType,s=i.kernelName,a=i.kernelEntry,u=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${s}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),ft("info",()=>`[WebGPU] Start to run kernel "[${o}] ${s}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),a(r,u[1]),0}catch(m){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${s}" failed. ${m}`)),1}finally{d&&t.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel "[${o}] ${s}": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,i){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let s=o.get(r),a=this.gpuDataManager.registerExternalBuffer(t,i,s?.[1]);return o.set(r,[a,t]),a}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[1])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let i=await al(this,e,r);return gb(i.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}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(){ft("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(){ft("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ft("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}});var Gw={};Tn(Gw,{init:()=>tE});var To,kl,tE,Ww=q(()=>{"use strict";Ne();Vw();cn();Ke();To=class n{constructor(e,r,t,i){this.module=e;this.dataType=r;this.data=t;this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=J.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=J.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=J.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(J.size(e)!==J.size(this.dims))throw new Error("Invalid new shape");return new n(this.module,this.dataType,this.data,e)}},kl=class{constructor(e,r,t){this.module=e;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let i=e.HEAPU32,o=t>>>2;this.opKernelContext=i[o++];let s=i[o++];this.outputCount=i[o++],this.customDataOffset=i[o++],this.customDataSize=i[o++];let a=[];for(let u=0;utypeof a=="number"?this.inputs[a]:a)??this.inputs,i=r?.outputs??[],o=(a,u,d)=>new To(this.module,u,this.output(a,d),d),s=(a,u)=>{let d=Ln(a);if(!d)throw new Error(`Unsupported data type: ${a}`);let m=d*J.size(u),b=m>0?this.backend.gpuDataManager.create(m).id:0;return new To(this.module,a,b,u)};return this.backend.run(e,t,i,o,s,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let i=this.module.stackAlloc((1+r.length)*4),o=i>>2;this.module.HEAPU32[o++]=r.length;for(let s=0;s{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let o=new Cs;await o.initialize(r,t),i("webgpu",[o,s=>o.alloc(s),s=>o.free(s),(s,a,u,d=!1)=>{if(d)ft("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${a}, size=${u}`),o.memcpy(s,a);else{ft("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${a}, size=${u}`);let m=e.HEAPU8.subarray(s>>>0,(s>>>0)+u);o.upload(a,m)}},async(s,a,u)=>{ft("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${a}, size=${u}`),await o.download(s,()=>e.HEAPU8.subarray(a>>>0,(a>>>0)+u))},(s,a,u)=>o.createKernel(s,a,u,e.UTF8ToString(e._JsepGetNodeName(a))),s=>o.releaseKernel(s),(s,a,u,d)=>{ft("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${s}, contextDataOffset=${a}`);let m=new kl(e,o,a);return o.computeKernel(s,m,d)},()=>o.captureBegin(),()=>o.captureEnd(),()=>o.replay()])}else i("webnn")}});var rE,qw,Kw,Vn,nE,Dl,Yw,Xw,Hw,Zw,Jw,Qw,e_=q(()=>{"use strict";db();fb();Ne();Si();rs();rl();rE=(n,e)=>{xt()._OrtInit(n,e)!==0&&ct("Can't initialize onnxruntime.")},qw=async n=>{rE(n.wasm.numThreads,vo(n.logLevel))},Kw=async(n,e)=>{{let r=(Ww(),Kr(Gw)).init;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let t=n.webgpu.adapter;if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=n.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let o=n.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}if(!n.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",xt(),n,t)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",xt(),n)}}},Vn=new Map,nE=n=>{let e=xt(),r=e.stackSave();try{let t=e.stackAlloc(8);return e._OrtGetInputOutputCount(n,t,t+4)!==0&&ct("Can't get session input/output count."),[e.HEAP32[t/4],e.HEAP32[t/4+1]]}finally{e.stackRestore(r)}},Dl=n=>{let e=xt(),r=e._malloc(n.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,r),[r,n.byteLength]},Yw=async(n,e)=>{let r,t,i=xt();Array.isArray(n)?[r,t]=n:n.buffer===i.HEAPU8.buffer?[r,t]=[n.byteOffset,n.byteLength]:[r,t]=Dl(n);let o=0,s=0,a=0,u=[],d=[],m=[];try{if([s,u]=cb(e),e?.externalData&&i.mountExternalData){let P=[];for(let z of e.externalData){let U=typeof z=="string"?z:z.path;P.push(wo(typeof z=="string"?z:z.data).then(F=>{i.mountExternalData(U,F)}))}await Promise.all(P)}o=await i._OrtCreateSession(r,t,s),o===0&&ct("Can't create a session.");let[b,w]=nE(o),x=!!e?.enableGraphCapture,$=[],I=[],A=[];for(let P=0;PP==="gpu-buffer")&&(a=i._OrtCreateBinding(o),a===0&&ct("Can't create IO binding."),k={handle:a,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(P=>tl(P))}),Vn.set(o,[o,d,m,k,x,!1]),[o,$,I]}catch(b){throw d.forEach(w=>i._OrtFree(w)),m.forEach(w=>i._OrtFree(w)),a!==0&&i._OrtReleaseBinding(a),o!==0&&i._OrtReleaseSession(o),b}finally{i._free(r),s!==0&&i._OrtReleaseSessionOptions(s),u.forEach(b=>i._free(b)),i.unmountExternalData?.()}},Xw=n=>{let e=xt(),r=Vn.get(n);if(!r)throw new Error(`cannot release session. invalid session id: ${n}`);let[t,i,o,s,a]=r;s&&(a&&e._OrtClearBoundOutputs(s.handle),e._OrtReleaseBinding(s.handle)),e.jsepOnReleaseSession?.(n),i.forEach(u=>e._OrtFree(u)),o.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(t),Vn.delete(n)},Hw=(n,e,r,t,i,o=!1)=>{if(!n){e.push(0);return}let s=xt(),a=n[0],u=n[1],d=n[3],m,b;if(a==="string"&&d==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(o&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let $=n[2].gpuBuffer,I=Ln(el(a));b=u.reduce((k,P)=>k*P,1)*I;let A=s.jsepRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=A(t,i,$,b)}else{let $=n[2];if(Array.isArray($)){b=4*$.length,m=s._malloc(b),r.push(m);let I=m/4;for(let A=0;A<$.length;A++){if(typeof $[A]!="string")throw new TypeError(`tensor data at index ${A} is not a string`);s.HEAPU32[I++]=$t($[A],r)}}else b=$.byteLength,m=s._malloc(b),r.push(m),s.HEAPU8.set(new Uint8Array($.buffer,$.byteOffset,b),m)}let w=s.stackSave(),x=s.stackAlloc(4*u.length);try{let $=x/4;u.forEach(A=>s.HEAP32[$++]=A);let I=s._OrtCreateTensor(el(a),m,b,x,u.length,tl(d));I===0&&ct(`Can't create tensor for input/output. session=${t}, index=${i}.`),e.push(I)}finally{s.stackRestore(w)}},Zw=async(n,e,r,t,i,o)=>{let s=xt(),a=Vn.get(n);if(!a)throw new Error(`cannot run inference. invalid session id: ${n}`);let u=a[0],d=a[1],m=a[2],b=a[3],w=a[4],x=a[5],$=e.length,I=t.length,A=0,k=[],P=[],z=[],U=[],F=s.stackSave(),Y=s.stackAlloc($*4),ie=s.stackAlloc($*4),ne=s.stackAlloc(I*4),le=s.stackAlloc(I*4);try{[A,k]=lb(o);for(let $e=0;$e<$;$e++)Hw(r[$e],P,U,n,e[$e],w);for(let $e=0;$e_t*Ot,1);Le=dn(ve);let Br=b?.outputPreferredLocations[t[$e]];if(Le==="string"){if(Br==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let _t=[],Ot=Pe/4;for(let Yt=0;Yt0){let _t=s.jsepGetBuffer;if(!_t)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ot=_t(Pe),Yt=Ln(ve);if(Yt===void 0||!is(Le))throw new Error(`Unsupported data type: ${Le}`);Ae=!0,he.push([Le,wt,{gpuBuffer:Ot,download:s.jsepCreateDownloader(Ot,bt*Yt,Le),dispose:()=>{s._OrtReleaseTensor(je)}},"gpu-buffer"])}else{let _t=ns(Le),Ot=new _t(bt);new Uint8Array(Ot.buffer,Ot.byteOffset,Ot.byteLength).set(s.HEAPU8.subarray(Pe,Pe+Ot.byteLength)),he.push([Le,wt,Ot,"cpu"])}}finally{s.stackRestore(Ue),Le==="string"&&Pe&&s._free(Pe),Ae||s._OrtReleaseTensor(je)}}return b&&!w&&(s._OrtClearBoundOutputs(b.handle),Vn.set(n,[u,d,m,b,w,!1])),he}finally{s.stackRestore(F),P.forEach(ge=>s._OrtReleaseTensor(ge)),z.forEach(ge=>s._OrtReleaseTensor(ge)),U.forEach(ge=>s._free(ge)),A!==0&&s._OrtReleaseRunOptions(A),k.forEach(ge=>s._free(ge))}},Jw=n=>{let e=xt(),r=Vn.get(n);if(!r)throw new Error("invalid session id");let t=r[0],i=e._OrtEndProfiling(t);i===0&&ct("Can't get an profile file name."),e._OrtFree(i)},Qw=n=>{let e=[];for(let r of n){let t=r[2];!Array.isArray(t)&&"buffer"in t&&e.push(t.buffer)}return e}});var t_=ht((SG,oE)=>{oE.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'});var Gn,wr,So,Es,Os,Bl,Rl,Ai,Ei,aE,As,r_,n_,i_,o_,a_,s_,u_,zl=q(()=>{"use strict";Lt();e_();Si();Gn=()=>!!De.wasm.proxy&&typeof document<"u",So=!1,Es=!1,Os=!1,Rl=new Map,Ai=(n,e)=>{let r=Rl.get(n);r?r.push(e):Rl.set(n,[e])},Ei=()=>{if(So||!Es||Os||!wr)throw new Error("worker not ready")},aE=n=>{switch(n.data.type){case"init-wasm":So=!1,n.data.err?(Os=!0,Bl[1](n.data.err)):(Es=!0,Bl[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Rl.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}default:}},As=typeof document<"u"?document?.currentScript?.src:void 0,r_=async()=>{if(!Es){if(So)throw new Error("multiple calls to 'initWasm()' detected.");if(Os)throw new Error("previous call to 'initWasm()' failed.");if(So=!0,Gn())return De.wasm.wasmPaths===void 0&&As&&As.indexOf("blob:")!==0&&(De.wasm.wasmPaths=As.substr(0,+As.lastIndexOf("/")+1)),new Promise((n,e)=>{wr?.terminate();let r=URL.createObjectURL(new Blob([t_()],{type:"text/javascript"}));wr=new Worker(r,{name:"ort-wasm-proxy-worker"}),wr.onerror=i=>e(i),wr.onmessage=aE,URL.revokeObjectURL(r),Bl=[n,e];let t={type:"init-wasm",in:De};wr.postMessage(t)});try{await ub(De.wasm),await qw(De),Es=!0}catch(n){throw Os=!0,n}finally{So=!1}}},n_=async n=>{if(Gn())return Ei(),new Promise((e,r)=>{Ai("init-ep",[e,r]);let t={type:"init-ep",in:{epName:n,env:De}};wr.postMessage(t)});await Kw(De,n)},i_=async n=>Gn()?(Ei(),new Promise((e,r)=>{Ai("copy-from",[e,r]);let t={type:"copy-from",in:{buffer:n}};wr.postMessage(t,[n.buffer])})):Dl(n),o_=async(n,e)=>{if(Gn()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ei(),new Promise((r,t)=>{Ai("create",[r,t]);let i={type:"create",in:{model:n,options:{...e}}},o=[];n instanceof Uint8Array&&o.push(n.buffer),wr.postMessage(i,o)})}else return Yw(n,e)},a_=async n=>{if(Gn())return Ei(),new Promise((e,r)=>{Ai("release",[e,r]);let t={type:"release",in:n};wr.postMessage(t)});Xw(n)},s_=async(n,e,r,t,i,o)=>{if(Gn()){if(r.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ei(),new Promise((s,a)=>{Ai("run",[s,a]);let u=r,d={type:"run",in:{sessionId:n,inputIndices:e,inputs:u,outputIndices:t,options:o}};wr.postMessage(d,Qw(u))})}else return Zw(n,e,r,t,i,o)},u_=async n=>{if(Gn())return Ei(),new Promise((e,r)=>{Ai("end-profiling",[e,r]);let t={type:"end-profiling",in:n};wr.postMessage(t)});Jw(n)}});var l_,sE,Ps,d_=q(()=>{"use strict";Lt();zl();Ne();rl();l_=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},sE=n=>{switch(n[3]){case"cpu":return new Dt(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!is(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:t,dispose:i}=n[2];return Dt.fromGpuBuffer(r,{dataType:e,dims:n[1],download:t,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},Ps=class{async fetchModelAndCopyToWasmMemory(e){return i_(await wo(e))}async loadModel(e,r){sr();let t;typeof e=="string"?typeof process<"u"&&process.versions&&process.versions.node?t=await wo(e):t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames]=await o_(t,r),Xt()}async dispose(){return a_(this.sessionId)}async run(e,r,t){sr();let i=[],o=[];Object.entries(e).forEach(w=>{let x=w[0],$=w[1],I=this.inputNames.indexOf(x);if(I===-1)throw new Error(`invalid input '${x}'`);i.push($),o.push(I)});let s=[],a=[];Object.entries(r).forEach(w=>{let x=w[0],$=w[1],I=this.outputNames.indexOf(x);if(I===-1)throw new Error(`invalid output '${x}'`);s.push($),a.push(I)});let u=i.map((w,x)=>l_(w,()=>`input "${this.inputNames[o[x]]}"`)),d=s.map((w,x)=>w?l_(w,()=>`output "${this.outputNames[a[x]]}"`):null),m=await s_(this.sessionId,o,u,a,d,t),b={};for(let w=0;w{"use strict";Lt();zl();d_();uE=()=>{if((typeof De.wasm.initTimeout!="number"||De.wasm.initTimeout<0)&&(De.wasm.initTimeout=0),typeof De.wasm.simd!="boolean"&&(De.wasm.simd=!0),typeof De.wasm.proxy!="boolean"&&(De.wasm.proxy=!1),typeof De.wasm.trace!="boolean"&&(De.wasm.trace=!1),typeof De.wasm.numThreads!="number"||!Number.isInteger(De.wasm.numThreads)||De.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(De.wasm.numThreads=1);let n=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;De.wasm.numThreads=Math.min(4,Math.ceil((n||1)/2))}},ks=class{async init(e){uE(),await r_(),await n_(e)}async createInferenceSessionHandler(e,r){let t=new Ps;return await t.loadModel(e,r),Promise.resolve(t)}}});var f_={};Tn(f_,{wasmBackend:()=>lE});var lE,p_=q(()=>{"use strict";c_();lE=new ks});Lt();Lt();Lt();var Vf="1.18.0";var qG=Fs;{let n=(qy(),Kr(Hy)).onnxjsBackend;rn("webgl",n,-10)}{let n=(p_(),Kr(f_)).wasmBackend;rn("webgpu",n,5),rn("webnn",n,5),rn("cpu",n,10),rn("wasm",n,10)}Object.defineProperty(De.versions,"web",{value:Vf,enumerable:!0});export{k1 as InferenceSession,sa as TRACE,sr as TRACE_FUNC_BEGIN,Xt as TRACE_FUNC_END,Dt as Tensor,B1 as TrainingSession,qG as default,De as env,rn as registerBackend}; +/** + * @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. + * ============================================================================= + */ +/*! Bundled license information: + +long/index.js: + (** + * @license + * Copyright 2009 The Closure Library Authors + * Copyright 2020 Daniel Wirtz / The long.js Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + *) +*/ +//# sourceMappingURL=ort.all.min.js.map