/*! * ONNX Runtime Web v1.18.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ var Zn=Object.defineProperty;var Og=Object.getOwnPropertyDescriptor;var Pg=Object.getOwnPropertyNames;var zg=Object.prototype.hasOwnProperty;var ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vr=(e,t)=>{for(var r in t)Zn(e,r,{get:t[r],enumerable:!0})},Rg=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Pg(t))!zg.call(e,o)&&o!==r&&Zn(e,o,{get:()=>t[o],enumerable:!(s=Og(t,o))||s.enumerable});return e};var Qt=e=>Rg(Zn({},"__esModule",{value:!0}),e);var nn,cr,pr,jg,an,on=ie(()=>{"use strict";nn=new Map,cr=[],pr=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=nn.get(e);if(s===void 0)nn.set(e,{backend:t,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=cr.indexOf(e);o!==-1&&cr.splice(o,1);for(let c=0;c{let t=nn.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(s){return r||(t.error=`${s}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},an=async e=>{let t=e.executionProviders||[],r=t.map(h=>typeof h=="string"?h:h.name),s=r.length===0?cr:r,o,c=[],p=new Set;for(let h of s){let y=await jg(h);typeof y=="string"?c.push({name:h,err:y}):(o||(o=y),o===y&&p.add(h))}if(!o)throw new Error(`no available backend found. ERR: ${c.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:y}of c)r.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${y}`);let l=t.filter(h=>p.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,y)=>y==="executionProviders"?l:Reflect.get(h,y)})]}});var Cu=ie(()=>{"use strict";on()});var xu,Su=ie(()=>{"use strict";xu="1.18.0"});var Iu,$t,Jn=ie(()=>{"use strict";Su();Iu="warning",$t={wasm:{},webgl:{},webgpu:{},versions:{common:xu},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}`);Iu=e}},get logLevel(){return Iu}};Object.defineProperty($t,"logLevel",{enumerable:!0})});var We,Tu=ie(()=>{"use strict";Jn();We=$t});var Au,Eu,ku=ie(()=>{"use strict";Au=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let s=r.getContext("2d");if(s!=null){let o,c;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],c=e.dims[3]):(o=e.dims[3],c=e.dims[2]);let p=t?.format!==void 0?t.format:"RGB",l=t?.norm,h,y;l===void 0||l.mean===void 0?h=[255,255,255,255]:typeof l.mean=="number"?h=[l.mean,l.mean,l.mean,l.mean]:(h=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(h[3]=l.mean[3])),l===void 0||l.bias===void 0?y=[0,0,0,0]:typeof l.bias=="number"?y=[l.bias,l.bias,l.bias,l.bias]:(y=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(y[3]=l.bias[3]));let $=c*o,_=0,C=$,T=$*2,S=-1;p==="RGBA"?(_=0,C=$,T=$*2,S=$*3):p==="RGB"?(_=0,C=$,T=$*2):p==="RBG"&&(_=0,T=$,C=$*2);for(let E=0;E{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let o,c,p;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],c=e.dims[1],p=e.dims[3]):(o=e.dims[3],c=e.dims[2],p=e.dims[1]);let l=t!==void 0&&t.format!==void 0?t.format:"RGB",h=t?.norm,y,$;h===void 0||h.mean===void 0?y=[255,255,255,255]:typeof h.mean=="number"?y=[h.mean,h.mean,h.mean,h.mean]:(y=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(y[3]=h.mean[3])),h===void 0||h.bias===void 0?$=[0,0,0,0]:typeof h.bias=="number"?$=[h.bias,h.bias,h.bias,h.bias]:($=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&($[3]=h.bias[3]));let _=c*o;if(t!==void 0&&(t.format!==void 0&&p===4&&t.format!=="RGBA"||p===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let C=4,T=0,S=1,E=2,O=3,R=0,z=_,M=_*2,U=-1;l==="RGBA"?(R=0,z=_,M=_*2,U=_*3):l==="RGB"?(R=0,z=_,M=_*2):l==="RBG"&&(R=0,M=_,z=_*2),s=r.createImageData(o,c);for(let L=0;L{"use strict";sn();ea=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=t,o=t.norm??{mean:255,bias:0},c,p;typeof o.mean=="number"?c=[o.mean,o.mean,o.mean,o.mean]:c=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?p=[o.bias,o.bias,o.bias,o.bias]:p=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let l=t.format!==void 0?t.format:"RGBA",h=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",y=r*s,$=h==="RGBA"?new Float32Array(y*4):new Float32Array(y*3),_=4,C=0,T=1,S=2,E=3,O=0,R=y,z=y*2,M=-1;l==="RGB"&&(_=3,C=0,T=1,S=2,E=-1),h==="RGBA"?M=y*3:h==="RBG"?(O=0,z=y,R=y*2):h==="BGR"&&(z=0,R=y,O=y*2);for(let L=0;L{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,c=typeof e=="string",p,l=t??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},y=$=>$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(r){let $=h();$.width=e.width,$.height=e.height;let _=y($);if(_!=null){let C=e.height,T=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(C=t.resizedHeight,T=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");l.tensorFormat="RGBA",l.height=C,l.width=T}else l.tensorFormat="RGBA",l.height=C,l.width=T;_.drawImage(e,0,0),p=_.getImageData(0,0,T,C).data}else throw new Error("Can not access image data")}else if(s){let $,_;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?($=t.resizedHeight,_=t.resizedWidth):($=e.height,_=e.width),t!==void 0&&(l=t),l.format="RGBA",l.height=$,l.width=_,t!==void 0){let C=h();C.width=_,C.height=$;let T=y(C);if(T!=null)T.putImageData(e,0,0),p=T.getImageData(0,0,_,$).data;else throw new Error("Can not access image data")}else p=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let $=h();$.width=e.width,$.height=e.height;let _=y($);if(_!=null){let C=e.height,T=e.width;return _.drawImage(e,0,0,T,C),p=_.getImageData(0,0,T,C).data,l.height=C,l.width=T,ea(p,l)}else throw new Error("Can not access image data")}else{if(c)return new Promise(($,_)=>{let C=h(),T=y(C);if(!e||!T)return _();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{C.width=S.width,C.height=S.height,T.drawImage(S,0,0,C.width,C.height);let E=T.getImageData(0,0,C.width,C.height);l.height=C.height,l.width=C.width,$(ea(E.data,l))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(p!==void 0)return ea(p,l);throw new Error("Input data provided is not supported - aborted tensor creation")},Pu=(e,t)=>{let{width:r,height:s,download:o,dispose:c}=t,p=[1,s,r,4];return new ft({location:"texture",type:"float32",texture:e,dims:p,download:o,dispose:c})},zu=(e,t)=>{let{dataType:r,dims:s,download:o,dispose:c}=t;return new ft({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:o,dispose:c})},Ru=(e,t,r)=>new ft({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})});var fr,bi,Bu,Du,Mu=ie(()=>{"use strict";fr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),bi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Bu=!1,Du=()=>{if(!Bu){Bu=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(fr.set("int64",BigInt64Array),bi.set(BigInt64Array,"int64")),t&&(fr.set("uint64",BigUint64Array),bi.set(BigUint64Array,"uint64")),r?(fr.set("float16",Float16Array),bi.set(Float16Array,"float16")):fr.set("float16",Uint16Array)}}});var Uu,Wu,Nu=ie(()=>{"use strict";sn();Uu=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new ft(e.type,e.data,t);case"cpu-pinned":return new ft({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new ft({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new ft({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var ft,sn=ie(()=>{"use strict";ku();ju();Mu();Nu();ft=class{constructor(t,r,s){Du();let o,c;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,o=t.type,c=t.dims,t.location){case"cpu-pinned":{let l=fr.get(o);if(!l)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(t.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=t.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,h;if(typeof t=="string")if(o=t,h=s,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");l=r}else{let y=fr.get(t);if(y===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&y===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");t==="uint64"||t==="int64"?l=y.from(r,BigInt):l=y.from(r)}else if(r instanceof y)l=r;else throw new TypeError(`A ${o} tensor's data must be type of ${y}`)}else if(h=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let y=typeof t[0];if(y==="string")o="string",l=t;else if(y==="boolean")o="bool",l=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${y}.`)}else{let y=bi.get(t.constructor);if(y===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=y,l=t}if(h===void 0)h=[l.length];else if(!Array.isArray(h))throw new TypeError("A tensor's dims must be a number array");c=h,this.cpuData=l,this.dataLocation="cpu"}let p=Uu(c);if(this.cpuData&&p!==this.cpuData.length)throw new Error(`Tensor's size(${p}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=c,this.size=p}static async fromImage(t,r){return Ou(t,r)}static fromTexture(t,r){return Pu(t,r)}static fromGpuBuffer(t,r){return zu(t,r)}static fromPinnedBuffer(t,r,s){return Ru(t,r,s)}toDataURL(t){return Au(this,t)}toImageData(t){return Eu(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&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(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Wu(this,t)}}});var st,un=ie(()=>{"use strict";sn();st=ft});var ln,Vu,Ct,ht,ta=ie(()=>{"use strict";Jn();ln=(e,t)=>{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||console.timeStamp(`${e}::ORT::${t}`)},Vu=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let o=0;o{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||Vu("BEGIN",e)},ht=e=>{(typeof $t.trace>"u"?!$t.wasm.trace:!$t.trace)||Vu("END",e)}});var dn,Gu=ie(()=>{"use strict";on();un();ta();dn=class e{constructor(t){this.handler=t}async run(t,r,s){Ct();let o={},c={};if(typeof t!="object"||t===null||t instanceof st||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let p=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof st)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.");p=!1;for(let y of r){if(typeof y!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(y)===-1)throw new RangeError(`'fetches' contains invalid output name: ${y}.`);o[y]=null}if(typeof s=="object"&&s!==null)c=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let y=!1,$=Object.getOwnPropertyNames(r);for(let _ of this.outputNames)if($.indexOf(_)!==-1){let C=r[_];(C===null||C instanceof st)&&(y=!0,p=!1,o[_]=C)}if(y){if(typeof s=="object"&&s!==null)c=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else c=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let y of this.inputNames)if(typeof t[y]>"u")throw new Error(`input '${y}' is missing in 'feeds'.`);if(p)for(let y of this.outputNames)o[y]=null;let l=await this.handler.run(t,o,c),h={};for(let y in l)if(Object.hasOwnProperty.call(l,y)){let $=l[y];$ instanceof st?h[y]=$:h[y]=new st($.type,$.data,$.dims)}return ht(),h}async release(){return this.handler.dispose()}static async create(t,r,s,o){Ct();let c,p={};if(typeof t=="string"){if(c=t,typeof r=="object"&&r!==null)p=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(c=t,typeof r=="object"&&r!==null)p=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let $=t,_=0,C=t.byteLength;if(typeof r=="object"&&r!==null)p=r;else if(typeof r=="number"){if(_=r,!Number.isSafeInteger(_))throw new RangeError("'byteOffset' must be an integer.");if(_<0||_>=$.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${$.byteLength}).`);if(C=t.byteLength-_,typeof s=="number"){if(C=s,!Number.isSafeInteger(C))throw new RangeError("'byteLength' must be an integer.");if(C<=0||_+C>$.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$.byteLength-_}].`);if(typeof o=="object"&&o!==null)p=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");c=new Uint8Array($,_,C)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[l,h]=await an(p),y=await l.createInferenceSessionHandler(c,h);return ht(),new e(y)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var Bg,Hu=ie(()=>{"use strict";Gu();Bg=dn});var Lu=ie(()=>{"use strict"});var Fu=ie(()=>{"use strict"});var qu=ie(()=>{"use strict"});var Ku=ie(()=>{"use strict"});var Dg,cn,Yu=ie(()=>{"use strict";on();un();Dg="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",cn=class e{constructor(t,r,s){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=s}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let s=t.evalModel||"",o=t.optimizerModel||"",c=r||{},[p,l]=await an(c);if(p.createTrainingSessionHandler){let h=await p.createTrainingSessionHandler(t.checkpointState,t.trainModel,s,o,l);return new e(h,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Dg)}typeNarrowingForRunStep(t,r,s,o,c){let p={},l={};if(typeof s!="object"||s===null||s instanceof st||Array.isArray(s))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let h=!0;if(typeof o=="object"){if(o===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(o instanceof st)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(o)){if(o.length===0)throw new TypeError("'fetches' cannot be an empty array.");h=!1;for(let y of o){if(typeof y!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(y)===-1)throw new RangeError(`'fetches' contains invalid output name: ${y}.`);p[y]=null}if(typeof c=="object"&&c!==null)l=c;else if(typeof c<"u")throw new TypeError("'options' must be an object.")}else{let y=!1,$=Object.getOwnPropertyNames(o);for(let _ of r)if($.indexOf(_)!==-1){let C=o[_];(C===null||C instanceof st)&&(y=!0,h=!1,p[_]=C)}if(y){if(typeof c=="object"&&c!==null)l=c;else if(typeof c<"u")throw new TypeError("'options' must be an object.")}else l=o}}else if(typeof o<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let y of t)if(typeof s[y]>"u")throw new Error(`input '${y}' is missing in 'feeds'.`);if(h)for(let y of r)p[y]=null;return[p,l]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let s in t)if(Object.hasOwnProperty.call(t,s)){let o=t[s];o instanceof st?r[s]=o:r[s]=new st(o.type,o.data,o.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,s){let[o,c]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,s),p=await this.handler.runTrainStep(t,o,c);return this.convertHandlerReturnTypeToMapOfTensors(p)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,s){if(this.hasEvalModel){let[o,c]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,s),p=await this.handler.runEvalStep(t,o,c);return this.convertHandlerReturnTypeToMapOfTensors(p)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let s=await this.getParametersSize(r);if(t.length!==4*s)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}});var Mg,Qu=ie(()=>{"use strict";Yu();Mg=cn});var ra={};Vr(ra,{InferenceSession:()=>Bg,TRACE:()=>ln,TRACE_FUNC_BEGIN:()=>Ct,TRACE_FUNC_END:()=>ht,Tensor:()=>st,TrainingSession:()=>Mg,env:()=>We,registerBackend:()=>pr});var Tt=ie(()=>{"use strict";Cu();Tu();Hu();un();Lu();Fu();ta();qu();Ku();Qu()});var pn={};Vr(pn,{createReadStream:()=>Zu,readFile:()=>Ug,readFileSync:()=>Wg});var Ug,Wg,Zu,fn=ie(()=>{Ug=void 0,Wg=void 0,Zu=void 0});var ia={};Vr(ia,{join:()=>Ng});var Ng,na=ie(()=>{Ng=void 0});var tl=Nr((el,aa)=>{"use strict";var Ju=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(t={}){var r=t,s,o,c=new Promise((i,n)=>{s=i,o=n});r.mountExternalData=(i,n)=>{(r.Ph||(r.Ph=new Map)).set(i,n)},r.unmountExternalData=()=>{delete r.Ph};let p=()=>{let i=(a,u,d)=>(...f)=>{let g=_t,v=u?.();f=a(...f);let b=u?.();return v!==b&&(a=b,d(v),u=d=null),_t!=g?Ni():f},n=a=>async(...u)=>{try{if(r.Oh)throw Error("Session already started");let d=r.Oh={gi:u[0],errors:[]},f=await a(...u);if(r.Oh!==d)throw Error("Session mismatch");r.Uh?.flush();let g=d.errors;if(0b),0r._OrtCreateSession,a=>r._OrtCreateSession=a),r._OrtRun=n(i(r._OrtRun,()=>r._OrtRun,a=>r._OrtRun=a)),r._OrtRunWithBinding=n(i(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,a=>r._OrtRunWithBinding=a)),r._OrtBindInput=i(r._OrtBindInput,()=>r._OrtBindInput,a=>r._OrtBindInput=a),p=void 0};r.jsepInit=(i,n)=>{if(p?.(),i==="webgpu"){[r.Uh,r.Zh,r.ci,r.Vh,r.bi,r.je,r.di,r.fi,r.$h,r.ai,r.ei]=n;let a=r.Uh;r.jsepRegisterBuffer=(u,d,f,g)=>a.registerBuffer(u,d,f,g),r.jsepGetBuffer=u=>a.getBuffer(u),r.jsepCreateDownloader=(u,d,f)=>a.createDownloader(u,d,f),r.jsepOnReleaseSession=u=>{a.onReleaseSession(u)},r.jsepOnRunStart=u=>a.onRunStart(u)}};var l=Object.assign({},r),h="./this.program",y=(i,n)=>{throw n},$=typeof window=="object",_=typeof importScripts=="function",C=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",T="",S,E,O;if(C){var R=(fn(),Qt(pn)),z=(na(),Qt(ia));T=_?z.dirname(T)+"/":__dirname+"/",S=(i,n)=>(i=rt(i)?new URL(i):z.normalize(i),R.readFileSync(i,n?void 0:"utf8")),O=i=>(i=S(i,!0),i.buffer||(i=new Uint8Array(i)),i),E=(i,n,a,u=!0)=>{i=rt(i)?new URL(i):z.normalize(i),R.readFile(i,u?void 0:"utf8",(d,f)=>{d?a(d):n(u?f.buffer:f)})},!r.thisProgram&&1{throw process.exitCode=i,n}}else($||_)&&(_?T=self.location.href:typeof document<"u"&&document.currentScript&&(T=document.currentScript.src),e&&(T=e),T.startsWith("blob:")?T="":T=T.substr(0,T.replace(/[?#].*/,"").lastIndexOf("/")+1),S=i=>{var n=new XMLHttpRequest;return n.open("GET",i,!1),n.send(null),n.responseText},_&&(O=i=>{var n=new XMLHttpRequest;return n.open("GET",i,!1),n.responseType="arraybuffer",n.send(null),new Uint8Array(n.response)}),E=(i,n,a)=>{var u=new XMLHttpRequest;u.open("GET",i,!0),u.responseType="arraybuffer",u.onload=()=>{u.status==200||u.status==0&&u.response?n(u.response):a()},u.onerror=a,u.send(null)});var M=console.log.bind(console),U=console.error.bind(console);Object.assign(r,l),l=null;var L,F=!1,te,J,oe,le,ge,Z,fe,we,ue,me,Ee;function ke(){var i=L.buffer;r.HEAP8=J=new Int8Array(i),r.HEAP16=le=new Int16Array(i),r.HEAPU8=oe=new Uint8Array(i),r.HEAPU16=ge=new Uint16Array(i),r.HEAP32=Z=new Int32Array(i),r.HEAPU32=fe=new Uint32Array(i),r.HEAPF32=we=new Float32Array(i),r.HEAPF64=Ee=new Float64Array(i),r.HEAP64=ue=new BigInt64Array(i),r.HEAPU64=me=new BigUint64Array(i)}var Ce=[],ve=[],Ae=[],_e=0,et=null,ee=null;function ce(i){throw i="Aborted("+i+")",U(i),F=!0,te=1,i=new WebAssembly.RuntimeError(i+". Build with -sASSERTIONS for more info."),o(i),i}var Re=i=>i.startsWith("data:application/octet-stream;base64,"),rt=i=>i.startsWith("file://"),Qe;if(Qe="ort-wasm-simd.wasm",!Re(Qe)){var Ye=Qe;Qe=r.locateFile?r.locateFile(Ye,T):T+Ye}function Dt(i){if(O)return O(i);throw"both async and sync fetching of the wasm failed"}function Xe(i){if($||_){if(typeof fetch=="function"&&!rt(i))return fetch(i,{credentials:"same-origin"}).then(n=>{if(!n.ok)throw`failed to load wasm binary file at '${i}'`;return n.arrayBuffer()}).catch(()=>Dt(i));if(E)return new Promise((n,a)=>{E(i,u=>n(new Uint8Array(u)),a)})}return Promise.resolve().then(()=>Dt(i))}function it(i,n,a){return Xe(i).then(u=>WebAssembly.instantiate(u,n)).then(a,u=>{U(`failed to asynchronously prepare wasm: ${u}`),ce(u)})}function mt(i,n){var a=Qe;return typeof WebAssembly.instantiateStreaming!="function"||Re(a)||rt(a)||C||typeof fetch!="function"?it(a,i,n):fetch(a,{credentials:"same-origin"}).then(u=>WebAssembly.instantiateStreaming(u,i).then(n,function(d){return U(`wasm streaming compile failed: ${d}`),U("falling back to ArrayBuffer instantiation"),it(a,i,n)}))}var Ft={1261504:(i,n,a,u)=>{if(typeof r>"u"||!r.Ph)return 1;if(i=Ke(i>>>0),i.startsWith("./")&&(i=i.substring(2)),i=r.Ph.get(i),!i)return 2;if(n>>>=0,a>>>=0,n+a>i.byteLength)return 3;try{return oe.set(i.subarray(n,n+a),u>>>0>>>0),0}catch{return 4}},1262005:(i,n,a)=>{a=Ke(a);let u=new Uint8Array(n);u.set(oe.subarray(i>>>0,i+n>>>0)),typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"?(fn(),Qt(pn)).writeFileSync(a,u):(i=new File([u],a,{type:"application/octet-stream"}),i=URL.createObjectURL(i),window.open(i,"_blank"))},1262513:()=>{r.$h()},1262544:()=>{r.ai()},1262573:()=>{r.ei()},1262598:i=>r.Zh(i),1262631:i=>r.ci(i),1262663:(i,n,a)=>{r.Vh(i,n,a,!0)},1262702:(i,n,a)=>{r.Vh(i,n,a)},1262735:i=>{r.je("Abs",i,void 0)},1262786:i=>{r.je("Neg",i,void 0)},1262837:i=>{r.je("Floor",i,void 0)},1262890:i=>{r.je("Ceil",i,void 0)},1262942:i=>{r.je("Reciprocal",i,void 0)},1263e3:i=>{r.je("Sqrt",i,void 0)},1263052:i=>{r.je("Exp",i,void 0)},1263103:i=>{r.je("Erf",i,void 0)},1263154:i=>{r.je("Sigmoid",i,void 0)},1263209:(i,n,a)=>{r.je("HardSigmoid",i,{alpha:n,beta:a})},1263288:i=>{r.je("Log",i,void 0)},1263339:i=>{r.je("Sin",i,void 0)},1263390:i=>{r.je("Cos",i,void 0)},1263441:i=>{r.je("Tan",i,void 0)},1263492:i=>{r.je("Asin",i,void 0)},1263544:i=>{r.je("Acos",i,void 0)},1263596:i=>{r.je("Atan",i,void 0)},1263648:i=>{r.je("Sinh",i,void 0)},1263700:i=>{r.je("Cosh",i,void 0)},1263752:i=>{r.je("Asinh",i,void 0)},1263805:i=>{r.je("Acosh",i,void 0)},1263858:i=>{r.je("Atanh",i,void 0)},1263911:i=>{r.je("Tanh",i,void 0)},1263963:i=>{r.je("Not",i,void 0)},1264014:(i,n,a)=>{r.je("Clip",i,{min:n,max:a})},1264083:i=>{r.je("Clip",i,void 0)},1264135:(i,n)=>{r.je("Elu",i,{alpha:n})},1264193:i=>{r.je("Relu",i,void 0)},1264245:(i,n)=>{r.je("LeakyRelu",i,{alpha:n})},1264309:(i,n)=>{r.je("ThresholdedRelu",i,{alpha:n})},1264379:(i,n)=>{r.je("Cast",i,{to:n})},1264437:i=>{r.je("Add",i,void 0)},1264488:i=>{r.je("Sub",i,void 0)},1264539:i=>{r.je("Mul",i,void 0)},1264590:i=>{r.je("Div",i,void 0)},1264641:i=>{r.je("Pow",i,void 0)},1264692:i=>{r.je("Equal",i,void 0)},1264745:i=>{r.je("Greater",i,void 0)},1264800:i=>{r.je("GreaterOrEqual",i,void 0)},1264862:i=>{r.je("Less",i,void 0)},1264914:i=>{r.je("LessOrEqual",i,void 0)},1264973:(i,n,a,u,d)=>{r.je("ReduceMean",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1265132:(i,n,a,u,d)=>{r.je("ReduceMax",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1265290:(i,n,a,u,d)=>{r.je("ReduceMin",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1265448:(i,n,a,u,d)=>{r.je("ReduceProd",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1265607:(i,n,a,u,d)=>{r.je("ReduceSum",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1265765:(i,n,a,u,d)=>{r.je("ReduceL1",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1265922:(i,n,a,u,d)=>{r.je("ReduceL2",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1266079:(i,n,a,u,d)=>{r.je("ReduceLogSum",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1266240:(i,n,a,u,d)=>{r.je("ReduceSumSquare",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1266404:(i,n,a,u,d)=>{r.je("ReduceLogSumExp",i,{keepDims:!!n,noopWithEmptyAxes:!!a,axes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1266568:i=>{r.je("Where",i,void 0)},1266621:(i,n,a)=>{r.je("Transpose",i,{perm:n?Array.from(Z.subarray(n>>>0,a>>>0)):[]})},1266729:(i,n,a,u)=>{r.je("DepthToSpace",i,{blocksize:n,mode:Ke(a),format:u?"NHWC":"NCHW"})},1266862:(i,n,a,u)=>{r.je("DepthToSpace",i,{blocksize:n,mode:Ke(a),format:u?"NHWC":"NCHW"})},1266995:(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)=>{r.je("ConvTranspose",i,{format:b?"NHWC":"NCHW",autoPad:n,dilations:[a],group:u,kernelShape:[d],pads:[f,g],strides:[v],wIsConst:()=>!!J[x>>>0],outputPadding:I?Array.from(Z.subarray(I>>>0,P>>>0)):[],outputShape:B?Array.from(Z.subarray(B>>>0,k>>>0)):[],activation:Ke(W)})},1267396:(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>{r.je("ConvTranspose",i,{format:v?"NHWC":"NCHW",autoPad:n,dilations:Array.from(Z.subarray(a>>>0,(a>>>0)+2>>>0)),group:u,kernelShape:Array.from(Z.subarray(d>>>0,(d>>>0)+2>>>0)),pads:Array.from(Z.subarray(f>>>0,(f>>>0)+4>>>0)),strides:Array.from(Z.subarray(g>>>0,(g>>>0)+2>>>0)),wIsConst:()=>!!J[b>>>0],outputPadding:x?Array.from(Z.subarray(x>>>0,I>>>0)):[],outputShape:P?Array.from(Z.subarray(P>>>0,B>>>0)):[],activation:Ke(k)})},1267961:(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)=>{r.je("ConvTranspose",i,{format:b?"NHWC":"NCHW",autoPad:n,dilations:[a],group:u,kernelShape:[d],pads:[f,g],strides:[v],wIsConst:()=>!!J[x>>>0],outputPadding:I?Array.from(Z.subarray(I>>>0,P>>>0)):[],outputShape:B?Array.from(Z.subarray(B>>>0,k>>>0)):[],activation:Ke(W)})},1268362:(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>{r.je("ConvTranspose",i,{format:v?"NHWC":"NCHW",autoPad:n,dilations:Array.from(Z.subarray(a>>>0,(a>>>0)+2>>>0)),group:u,kernelShape:Array.from(Z.subarray(d>>>0,(d>>>0)+2>>>0)),pads:Array.from(Z.subarray(f>>>0,(f>>>0)+4>>>0)),strides:Array.from(Z.subarray(g>>>0,(g>>>0)+2>>>0)),wIsConst:()=>!!J[b>>>0],outputPadding:x?Array.from(Z.subarray(x>>>0,I>>>0)):[],outputShape:P?Array.from(Z.subarray(P>>>0,B>>>0)):[],activation:Ke(k)})},1268927:(i,n)=>{r.je("GlobalAveragePool",i,{format:n?"NHWC":"NCHW"})},1269018:(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>{r.je("AveragePool",i,{format:Y?"NHWC":"NCHW",auto_pad:n,ceil_mode:a,count_include_pad:u,storage_order:d,dilations:[f,g],kernel_shape:[v,b],pads:[x,I,P,B],strides:[k,W]})},1269302:(i,n)=>{r.je("GlobalAveragePool",i,{format:n?"NHWC":"NCHW"})},1269393:(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>{r.je("AveragePool",i,{format:Y?"NHWC":"NCHW",auto_pad:n,ceil_mode:a,count_include_pad:u,storage_order:d,dilations:[f,g],kernel_shape:[v,b],pads:[x,I,P,B],strides:[k,W]})},1269677:(i,n)=>{r.je("GlobalMaxPool",i,{format:n?"NHWC":"NCHW"})},1269764:(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>{r.je("MaxPool",i,{format:Y?"NHWC":"NCHW",auto_pad:n,ceil_mode:a,count_include_pad:u,storage_order:d,dilations:[f,g],kernel_shape:[v,b],pads:[x,I,P,B],strides:[k,W]})},1270044:(i,n)=>{r.je("GlobalMaxPool",i,{format:n?"NHWC":"NCHW"})},1270131:(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>{r.je("MaxPool",i,{format:Y?"NHWC":"NCHW",auto_pad:n,ceil_mode:a,count_include_pad:u,storage_order:d,dilations:[f,g],kernel_shape:[v,b],pads:[x,I,P,B],strides:[k,W]})},1270411:(i,n,a,u,d)=>{r.je("Gemm",i,{alpha:n,beta:a,transA:u,transB:d})},1270515:i=>{r.je("MatMul",i,void 0)},1270569:(i,n,a,u)=>{r.je("ArgMax",i,{keepDims:!!n,selectLastIndex:!!a,axis:u})},1270677:(i,n,a,u)=>{r.je("ArgMin",i,{keepDims:!!n,selectLastIndex:!!a,axis:u})},1270785:(i,n)=>{r.je("Softmax",i,{axis:n})},1270848:(i,n)=>{r.je("Concat",i,{axis:n})},1270908:(i,n,a,u,d)=>{r.je("Split",i,{axis:n,numOutputs:a,splitSizes:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1271048:i=>{r.je("Expand",i,void 0)},1271102:(i,n)=>{r.je("Gather",i,{axis:Number(n)})},1271173:(i,n)=>{r.je("GatherElements",i,{axis:Number(n)})},1271252:(i,n,a,u,d,f,g,v,b,x,I)=>{r.je("Resize",i,{antialias:n,axes:a?Array.from(Z.subarray(a>>>0,u>>>0)):[],coordinateTransformMode:Ke(d),cubicCoeffA:f,excludeOutside:g,extrapolationValue:v,keepAspectRatioPolicy:Ke(b),mode:Ke(x),nearestMode:Ke(I)})},1271598:(i,n,a,u,d,f,g)=>{r.je("Slice",i,{starts:n?Array.from(Z.subarray(n>>>0,a>>>0)):[],ends:u?Array.from(Z.subarray(u>>>0,d>>>0)):[],axes:f?Array.from(Z.subarray(f>>>0,g>>>0)):[]})},1271814:i=>{r.je("Tile",i,void 0)},1271866:(i,n,a,u)=>{r.je("LayerNormalization",i,{axis:n,epsilon:a,simplified:!!u})},1271977:(i,n,a)=>{r.je("InstanceNormalization",i,{epsilon:n,format:a?"NHWC":"NCHW"})},1272091:(i,n,a)=>{r.je("InstanceNormalization",i,{epsilon:n,format:a?"NHWC":"NCHW"})},1272205:i=>{r.je("Range",i,void 0)},1272258:(i,n)=>{r.je("Einsum",i,{equation:Ke(n)})},1272339:(i,n,a,u,d)=>{r.je("Pad",i,{mode:n,value:a,pads:u?Array.from(Z.subarray(u>>>0,d>>>0)):[]})},1272466:(i,n,a,u,d,f)=>{r.je("BatchNormalization",i,{epsilon:n,momentum:a,spatial:!!d,trainingMode:!!u,format:f?"NHWC":"NCHW"})},1272635:(i,n,a,u,d,f)=>{r.je("BatchNormalization",i,{epsilon:n,momentum:a,spatial:!!d,trainingMode:!!u,format:f?"NHWC":"NCHW"})},1272804:(i,n,a)=>{r.je("CumSum",i,{exclusive:Number(n),reverse:Number(a)})},1272901:(i,n,a,u,d,f,g,v,b)=>{r.je("Attention",i,{numHeads:n,isUnidirectional:a,maskFilterValue:u,scale:d,doRotary:f,qkvHiddenSizes:g?Array.from(Z.subarray(Number(v)>>>0,Number(v)+g>>>0)):[],pastPresentShareBuffer:!!b})},1273173:i=>{r.je("BiasAdd",i,void 0)},1273228:i=>{r.je("BiasSplitGelu",i,void 0)},1273289:i=>{r.je("FastGelu",i,void 0)},1273345:(i,n,a,u,d,f,g,v,b,x,I,P,B)=>{r.je("Conv",i,{format:b?"NHWC":"NCHW",auto_pad:n,dilations:[a],group:u,kernel_shape:[d],pads:f?Array.from(Z.subarray(f>>>0,g>>>0)):[],strides:[v],w_is_const:()=>!!J[x>>>0],activation:Ke(I),activation_params:P?Array.from(we.subarray(P>>>0,B>>>0)):[]})},1273715:(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>{r.je("Conv",i,{format:P?"NHWC":"NCHW",auto_pad:n,dilations:[a,u],group:d,kernel_shape:[f,g],pads:v?Array.from(Z.subarray(v>>>0,b>>>0)):[],strides:[x,I],w_is_const:()=>!!J[B>>>0],activation:Ke(k),activation_params:W?Array.from(we.subarray(W>>>0,Y>>>0)):[]})},1274106:i=>{r.je("Gelu",i,void 0)},1274158:(i,n,a,u,d,f)=>{r.je("MatMulNBits",i,{k:n,n:a,accuracyLevel:u,bits:d,blockSize:f})},1274285:(i,n,a,u,d,f)=>{r.je("MultiHeadAttention",i,{numHeads:n,isUnidirectional:a,maskFilterValue:u,scale:d,doRotary:f})},1274444:(i,n,a,u,d)=>{r.je("RotaryEmbedding",i,{interleaved:!!n,numHeads:a,rotaryEmbeddingDim:u,scale:d})},1274583:(i,n,a)=>{r.je("SkipLayerNormalization",i,{epsilon:n,simplified:!!a})},1274685:(i,n,a)=>{r.je("SkipLayerNormalization",i,{epsilon:n,simplified:!!a})},1274787:(i,n,a,u)=>{r.je("LayerNormalization",i,{axis:n,epsilon:a,simplified:!!u})},1274898:i=>{r.di(i)},1274932:(i,n)=>r.fi(i,n,r.Oh.gi,r.Oh.errors)};function qt(i){this.name="ExitStatus",this.message=`Program terminated with exit(${i})`,this.status=i}var yt=[],er=0,dt=0;class wr{constructor(n){this.Nh=n,this.Ih=n-24}}var _r=i=>{var n=dt;if(!n)return sr(0),0;var a=new wr(n);fe[a.Ih+16>>>2>>>0]=n;var u=fe[a.Ih+4>>>2>>>0];if(!u)return sr(0),n;for(var d in i){var f=i[d];if(f===0||f===u)break;if(Ji(f,u,a.Ih+16))return sr(f),n}return sr(u),n},Kr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ai=(i,n,a)=>{n>>>=0;var u=n+a;for(a=n;i[a]&&!(a>=u);)++a;if(16d?u+=String.fromCharCode(d):(d-=65536,u+=String.fromCharCode(55296|d>>10,56320|d&1023))}}else u+=String.fromCharCode(d)}return u},Ke=(i,n)=>(i>>>=0)?Ai(oe,i,n):"",tr=i=>{for(var n=0,a=0;a=u?n++:2047>=u?n+=2:55296<=u&&57343>=u?(n+=4,++a):n+=3}return n},xt=(i,n,a,u)=>{if(a>>>=0,!(0=g){var v=i.charCodeAt(++f);g=65536+((g&1023)<<10)|v&1023}if(127>=g){if(a>=u)break;n[a++>>>0]=g}else{if(2047>=g){if(a+1>=u)break;n[a++>>>0]=192|g>>6}else{if(65535>=g){if(a+2>=u)break;n[a++>>>0]=224|g>>12}else{if(a+3>=u)break;n[a++>>>0]=240|g>>18,n[a++>>>0]=128|g>>12&63}n[a++>>>0]=128|g>>6&63}n[a++>>>0]=128|g&63}}return n[a>>>0]=0,a-d},$r,vt=i=>{for(var n="";oe[i>>>0];)n+=$r[oe[i++>>>0]];return n},Cr={},xr={},Ei={},at;function ki(i,n,a={}){var u=n.name;if(!i)throw new at(`type "${u}" must have a positive integer typeid pointer`);if(xr.hasOwnProperty(i)){if(a.Xh)return;throw new at(`Cannot register type '${u}' twice`)}xr[i]=n,delete Ei[i],Cr.hasOwnProperty(i)&&(n=Cr[i],delete Cr[i],n.forEach(d=>d()))}function bt(i,n,a={}){if(!("argPackAdvance"in n))throw new TypeError("registerType registeredInstance requires argPackAdvance");return ki(i,n,a)}var xe=(i,n,a)=>{switch(n){case 1:return a?u=>J[u>>>0]:u=>oe[u>>>0];case 2:return a?u=>le[u>>>1>>>0]:u=>ge[u>>>1>>>0];case 4:return a?u=>Z[u>>>2>>>0]:u=>fe[u>>>2>>>0];case 8:return a?u=>ue[u>>>3]:u=>me[u>>>3];default:throw new TypeError(`invalid integer width (${n}): ${i}`)}},Kt=[],St=[];function Yr(i){i>>>=0,9{if(!i)throw new at("Cannot use deleted val. handle = "+i);return St[i]},wt=i=>{switch(i){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let n=Kt.pop()||St.length;return St[n]=i,St[n+1]=1,n}};function Sr(i){return this.fromWireType(fe[i>>>2>>>0])}var Oi={name:"emscripten::val",fromWireType:i=>{var n=ot(i);return Yr(i),n},toWireType:(i,n)=>wt(n),argPackAdvance:8,readValueFromPointer:Sr,Mh:null},Pi=(i,n)=>{switch(n){case 4:return function(a){return this.fromWireType(we[a>>>2>>>0])};case 8:return function(a){return this.fromWireType(Ee[a>>>3>>>0])};default:throw new TypeError(`invalid float width (${n}): ${i}`)}},Qr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Xr=(i,n)=>{for(var a=i>>1,u=a+n/2;!(a>=u)&&ge[a>>>0];)++a;if(a<<=1,32>>0,a>>>0));for(a="",u=0;!(u>=n/2);++u){var d=le[i+2*u>>>1>>>0];if(d==0)break;a+=String.fromCharCode(d)}return a},zi=(i,n,a)=>{if(a??=2147483647,2>a)return 0;a-=2;var u=n;a=a<2*i.length?a/2:i.length;for(var d=0;d>>1>>>0]=i.charCodeAt(d),n+=2;return le[n>>>1>>>0]=0,n-u},Ri=i=>2*i.length,ji=(i,n)=>{for(var a=0,u="";!(a>=n/4);){var d=Z[i+4*a>>>2>>>0];if(d==0)break;++a,65536<=d?(d-=65536,u+=String.fromCharCode(55296|d>>10,56320|d&1023)):u+=String.fromCharCode(d)}return u},Bi=(i,n,a)=>{if(n>>>=0,a??=2147483647,4>a)return 0;var u=n;a=u+a-4;for(var d=0;d=f){var g=i.charCodeAt(++d);f=65536+((f&1023)<<10)|g&1023}if(Z[n>>>2>>>0]=f,n+=4,n+4>a)break}return Z[n>>>2>>>0]=0,n-u},Di=i=>{for(var n=0,a=0;a=u&&++a,n+=4}return n},Ir=(i,n)=>{var a=xr[i];if(a===void 0)throw i=ai(i),a=vt(i),It(i),new at(`${n} has unknown type ${a}`);return a},Zr=(i,n,a)=>{var u=[];return i=i.toWireType(u,a),u.length&&(fe[n>>>2>>>0]=wt(u)),i},rr=i=>{try{i()}catch(n){ce(n)}},Mi=i=>{if(!F)try{i();try{te=te=i=te,r.onExit?.(i),F=!0,y(i,new qt(i))}catch(n){n instanceof qt||n=="unwind"||y(1,n)}}catch(n){n instanceof qt||n=="unwind"||y(1,n)}};function Ui(){var i=D,n={};for(let[a,u]of Object.entries(i))n[a]=typeof u=="function"?(...d)=>{ir.push(a);try{return u(...d)}finally{F||(ir.pop(),_t&&kt===1&&ir.length===0&&(kt=0,rr(bu),typeof Fibers<"u"&&Fibers.mi()))}}:u;return n}var kt=0,_t=null,Jr=0,ir=[],Tr={},nr={},Yt=0,Ar=null,Wi=[];function Ni(){return new Promise((i,n)=>{Ar={resolve:i,reject:n}})}function Vi(){var i=or(65548),n=i+12;fe[i>>>2>>>0]=n,fe[i+4>>>2>>>0]=n+65536,n=ir[0];var a=Tr[n];return a===void 0&&(a=Yt++,Tr[n]=a,nr[a]=n),Z[i+8>>>2>>>0]=a,i}function Gi(i){if(!F){if(kt===0){var n=!1,a=!1;i((u=0)=>{if(!F&&(Jr=u,n=!0,a)){kt=2,rr(()=>wu(_t)),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.resume(),u=!1;try{var d=(0,D[nr[Z[_t+8>>>2>>>0]]])()}catch(v){d=v,u=!0}var f=!1;if(!_t){var g=Ar;g&&(Ar=null,(u?g.reject:g.resolve)(d),f=!0)}if(u&&!f)throw d}}),a=!0,n||(kt=1,_t=Vi(),typeof Browser<"u"&&Browser.Sh.Wh&&Browser.Sh.pause(),rr(()=>vu(_t)))}else kt===2?(kt=0,rr(_u),It(_t),_t=null,Wi.forEach(Mi)):ce(`invalid state: ${kt}`);return Jr}}function Er(i){return Gi(n=>{i().then(n)})}var ar=[],Fn={},He=i=>{var n=Fn[i];return n===void 0?vt(i):n},kr=()=>typeof globalThis=="object"?globalThis:Function("return this")(),ei=i=>{var n=ar.length;return ar.push(i),n},Hi=(i,n)=>{for(var a=Array(i),u=0;u>>2>>>0],"parameter "+u);return a},Or=(i,n)=>Object.defineProperty(n,"name",{value:i});function Li(i){var n=Function;if(!(n instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof n} which is not a function`);var a=Or(n.name||"unknownFunctionName",function(){});return a.prototype=n.prototype,a=new a,i=n.apply(a,i),i instanceof Object?i:a}var Lt=i=>i%4===0&&(i%100!==0||i%400===0),ti=[0,31,60,91,121,152,182,213,244,274,305,335],ri=[0,31,59,90,120,151,181,212,243,273,304,334],Pr=[],Fi=(i,n)=>{Pr.length=0;for(var a;a=oe[i++>>>0];){var u=a!=105;u&=a!=112,n+=u&&n%8?4:0,Pr.push(a==112?fe[n>>>2>>>0]:a==106?ue[n>>>3]:a==105?Z[n>>>2>>>0]:Ee[n>>>3>>>0]),n+=u?8:4}return Pr},zr={},ii=()=>{if(!Rr){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:h||"./this.program"},n;for(n in zr)zr[n]===void 0?delete i[n]:i[n]=zr[n];var a=[];for(n in i)a.push(`${n}=${i[n]}`);Rr=a}return Rr},Rr,qn=[null,[],[]],qi=[31,29,31,30,31,30,31,31,30,31,30,31],ni=[31,28,31,30,31,30,31,31,30,31,30,31];function jr(i){var n=Array(tr(i)+1);return xt(i,n,0,n.length),n}function Ki(i,n,a,u){function d(k,W,Y){for(k=typeof k=="number"?k.toString():k||"";k.lengthde?-1:0ae-k.getDate())W-=ae-k.getDate()+1,k.setDate(1),11>Y?k.setMonth(Y+1):(k.setMonth(0),k.setFullYear(k.getFullYear()+1));else{k.setDate(k.getDate()+W);break}}return Y=new Date(k.getFullYear()+1,0,4),W=v(new Date(k.getFullYear(),0,4)),Y=v(Y),0>=g(W,k)?0>=g(Y,k)?k.getFullYear()+1:k.getFullYear():k.getFullYear()-1}i>>>=0,n>>>=0,a>>>=0,u>>>=0;var x=fe[u+40>>>2>>>0];u={ji:Z[u>>>2>>>0],ii:Z[u+4>>>2>>>0],Qh:Z[u+8>>>2>>>0],Th:Z[u+12>>>2>>>0],Rh:Z[u+16>>>2>>>0],Lh:Z[u+20>>>2>>>0],Jh:Z[u+24>>>2>>>0],Kh:Z[u+28>>>2>>>0],li:Z[u+32>>>2>>>0],hi:Z[u+36>>>2>>>0],ki:x?Ke(x):""},a=Ke(a),x={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var I in x)a=a.replace(new RegExp(I,"g"),x[I]);var P="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),B="January February March April May June July August September October November December".split(" ");x={"%a":k=>P[k.Jh].substring(0,3),"%A":k=>P[k.Jh],"%b":k=>B[k.Rh].substring(0,3),"%B":k=>B[k.Rh],"%C":k=>f((k.Lh+1900)/100|0,2),"%d":k=>f(k.Th,2),"%e":k=>d(k.Th,2," "),"%g":k=>b(k).toString().substring(2),"%G":b,"%H":k=>f(k.Qh,2),"%I":k=>(k=k.Qh,k==0?k=12:12{for(var W=0,Y=0;Y<=k.Rh-1;W+=(Lt(k.Lh+1900)?qi:ni)[Y++]);return f(k.Th+W,3)},"%m":k=>f(k.Rh+1,2),"%M":k=>f(k.ii,2),"%n":()=>` `,"%p":k=>0<=k.Qh&&12>k.Qh?"AM":"PM","%S":k=>f(k.ji,2),"%t":()=>" ","%u":k=>k.Jh||7,"%U":k=>f(Math.floor((k.Kh+7-k.Jh)/7),2),"%V":k=>{var W=Math.floor((k.Kh+7-(k.Jh+6)%7)/7);if(2>=(k.Jh+371-k.Kh-2)%7&&W++,W)W==53&&(Y=(k.Jh+371-k.Kh)%7,Y==4||Y==3&&Lt(k.Lh)||(W=1));else{W=52;var Y=(k.Jh+7-k.Kh-1)%7;(Y==4||Y==5&&Lt(k.Lh%400-1))&&W++}return f(W,2)},"%w":k=>k.Jh,"%W":k=>f(Math.floor((k.Kh+7-(k.Jh+6)%7)/7),2),"%y":k=>(k.Lh+1900).toString().substring(2),"%Y":k=>k.Lh+1900,"%z":k=>{k=k.hi;var W=0<=k;return k=Math.abs(k)/60,(W?"+":"-")+("0000"+(k/60*100+k%60)).slice(-4)},"%Z":k=>k.ki,"%%":()=>"%"},a=a.replace(/%%/g,"\0\0");for(I in x)a.includes(I)&&(a=a.replace(new RegExp(I,"g"),x[I](u)));return a=a.replace(/\0\0/g,"%"),I=jr(a),I.length>n?0:(J.set(I,i>>>0),I.length-1)}for(var Ot=Array(256),ct=0;256>ct;++ct)Ot[ct]=String.fromCharCode(ct);$r=Ot,at=r.BindingError=class extends Error{constructor(i){super(i),this.name="BindingError"}},r.InternalError=class extends Error{constructor(i){super(i),this.name="InternalError"}},St.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>St.length/2-5-Kt.length;var Yi={bd:function(i,n,a){return Er(async()=>{await r.bi(i,n,a)})},v:function(i){if(i=new wr(i>>>0),J[i.Ih+12>>>0]==0&&(J[i.Ih+12>>>0]=1,er--),J[i.Ih+13>>>0]=0,yt.push(i),Zi(i.Nh),en(fe[i.Ih+4>>>2>>>0]))i=fe[i.Nh>>>2>>>0];else{var n=fe[i.Ih+16>>>2>>>0];i=n!==0?n:i.Nh}return i},N:()=>{N(0,0);var i=yt.pop();Xi(i.Nh),dt=0},a:function(){return _r([])},m:function(i){return _r([i>>>0])},x:function(i,n){return _r([i>>>0,n>>>0])},q:function(i,n,a){return _r([i>>>0,n>>>0,a>>>0])},Bb:()=>{var i=yt.pop();i||ce("no exception to throw");var n=i.Nh;throw J[i.Ih+13>>>0]==0&&(yt.push(i),J[i.Ih+13>>>0]=1,J[i.Ih+12>>>0]=0,er++),dt=n,dt},s:function(i,n,a){i>>>=0;var u=new wr(i);throw fe[u.Ih+16>>>2>>>0]=0,fe[u.Ih+4>>>2>>>0]=n>>>0,fe[u.Ih+8>>>2>>>0]=a>>>0,dt=i,er++,dt},fb:()=>er,g:function(i){throw dt||=i>>>0,dt},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(i,n,a){n=vt(n>>>0),bt(i>>>0,{name:n,fromWireType:u=>u,toWireType:function(u,d){if(typeof d!="bigint"&&typeof d!="number")throw d===null?d="null":(u=typeof d,d=u==="object"||u==="array"||u==="function"?d.toString():""+d),new TypeError(`Cannot convert "${d}" to ${this.name}`);return typeof d=="number"&&(d=BigInt(d)),d},argPackAdvance:8,readValueFromPointer:xe(n,a>>>0,n.indexOf("u")==-1),Mh:null})},Ec:function(i,n,a,u){n=vt(n>>>0),bt(i>>>0,{name:n,fromWireType:function(d){return!!d},toWireType:function(d,f){return f?a:u},argPackAdvance:8,readValueFromPointer:function(d){return this.fromWireType(oe[d>>>0])},Mh:null})},Cc:function(i){return bt(i>>>0,Oi)},Vb:function(i,n,a){n=vt(n>>>0),bt(i>>>0,{name:n,fromWireType:u=>u,toWireType:(u,d)=>d,argPackAdvance:8,readValueFromPointer:Pi(n,a>>>0),Mh:null})},Aa:function(i,n,a,u,d){if(i>>>=0,a>>>=0,n=vt(n>>>0),d===-1&&(d=4294967295),d=v=>v,u===0){var f=32-8*a;d=v=>v<>>f}var g=n.includes("unsigned")?function(v,b){return b>>>0}:function(v,b){return b};bt(i,{name:n,fromWireType:d,toWireType:g,argPackAdvance:8,readValueFromPointer:xe(n,a,u!==0),Mh:null})},_:function(i,n,a){function u(f){return new d(J.buffer,fe[f+4>>>2>>>0],fe[f>>>2>>>0])}var d=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][n];a=vt(a>>>0),bt(i>>>0,{name:a,fromWireType:u,argPackAdvance:8,readValueFromPointer:u},{Xh:!0})},Xb:function(i,n){n=vt(n>>>0);var a=n==="std::string";bt(i>>>0,{name:n,fromWireType:function(u){var d=fe[u>>>2>>>0],f=u+4;if(a)for(var g=f,v=0;v<=d;++v){var b=f+v;if(v==d||oe[b>>>0]==0){if(g=Ke(g,b-g),x===void 0)var x=g;else x+=String.fromCharCode(0),x+=g;g=b+1}}else{for(x=Array(d),v=0;v>>0]);x=x.join("")}return It(u),x},toWireType:function(u,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var f=typeof d=="string";if(!(f||d instanceof Uint8Array||d instanceof Uint8ClampedArray||d instanceof Int8Array))throw new at("Cannot pass non-string to std::string");var g=a&&f?tr(d):d.length,v=or(4+g+1),b=v+4;if(fe[v>>>2>>>0]=g,a&&f)xt(d,oe,b,g+1);else if(f)for(f=0;f>>0]=x}else for(f=0;f>>0]=d[f];return u!==null&&u.push(It,v),v},argPackAdvance:8,readValueFromPointer:Sr,Mh(u){It(u)}})},Ab:function(i,n,a){if(n>>>=0,a>>>=0,a=vt(a),n===2)var u=Xr,d=zi,f=Ri,g=v=>ge[v>>>1>>>0];else n===4&&(u=ji,d=Bi,f=Di,g=v=>fe[v>>>2>>>0]);bt(i>>>0,{name:a,fromWireType:v=>{for(var b=fe[v>>>2>>>0],x,I=v+4,P=0;P<=b;++P){var B=v+4+P*n;(P==b||g(B)==0)&&(I=u(I,B-I),x===void 0?x=I:(x+=String.fromCharCode(0),x+=I),I=B+n)}return It(v),x},toWireType:(v,b)=>{if(typeof b!="string")throw new at(`Cannot pass non-string to C++ string type ${a}`);var x=f(b),I=or(4+x+n);return fe[I>>>2>>>0]=x/n,d(b,I+4,x+n),v!==null&&v.push(It,I),I},argPackAdvance:8,readValueFromPointer:Sr,Mh(v){It(v)}})},Fc:function(i,n){n=vt(n>>>0),bt(i>>>0,{Yh:!0,name:n,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ad:()=>1,kd:function(i,n,a){return n>>>=0,a>>>=0,i=ot(i>>>0),n=Ir(n,"emval::as"),Zr(n,a,i)},Cd:function(i){return i>>>=0,Er(()=>(i=ot(i),i.then(wt)))},ud:function(i,n,a,u){return a>>>=0,u>>>=0,i=ar[i>>>0],n=ot(n>>>0),i(null,n,a,u)},ia:function(i,n,a,u,d){return a>>>=0,u>>>=0,d>>>=0,i=ar[i>>>0],n=ot(n>>>0),a=He(a),i(n,n[a],u,d)},Bc:Yr,qd:function(i,n){return n>>>=0,i=ot(i>>>0),n=ot(n),i==n},zd:function(i){return i>>>=0,i===0?wt(kr()):(i=He(i),wt(kr()[i]))},ha:function(i,n,a){n=Hi(i,n>>>0);var u=n.shift();i--;var d=`return function (obj, func, destructorsRef, args) { `,f=0,g=[];a===0&&g.push("obj");for(var v=["retType"],b=[u],x=0;xI.name).join(", ")}) => ${u.name}>`,ei(Or(a,i))},yd:function(i,n){return n>>>=0,i=ot(i>>>0),n=ot(n),wt(i[n])},ba:function(i){i>>>=0,9>>0);for(var n=Array(i.length),a=0;a>>0))},Xa:function(){return wt({})},vd:function(i){i>>>=0;for(var n=ot(i);n.length;){var a=n.pop();n.pop()(a)}Yr(i)},sd:function(i,n,a){n>>>=0,a>>>=0,i=ot(i>>>0),n=ot(n),a=ot(a),i[n]=a},zb:function(i,n){return n>>>=0,i=Ir(i>>>0,"_emval_take_value"),i=i.readValueFromPointer(n),wt(i)},Rc:function(i,n){i=-9007199254740992>i||9007199254740992>>=0,i=new Date(1e3*i),Z[n>>>2>>>0]=i.getUTCSeconds(),Z[n+4>>>2>>>0]=i.getUTCMinutes(),Z[n+8>>>2>>>0]=i.getUTCHours(),Z[n+12>>>2>>>0]=i.getUTCDate(),Z[n+16>>>2>>>0]=i.getUTCMonth(),Z[n+20>>>2>>>0]=i.getUTCFullYear()-1900,Z[n+24>>>2>>>0]=i.getUTCDay(),Z[n+28>>>2>>>0]=(i.getTime()-Date.UTC(i.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Sc:function(i,n){i=-9007199254740992>i||9007199254740992>>=0,i=new Date(1e3*i),Z[n>>>2>>>0]=i.getSeconds(),Z[n+4>>>2>>>0]=i.getMinutes(),Z[n+8>>>2>>>0]=i.getHours(),Z[n+12>>>2>>>0]=i.getDate(),Z[n+16>>>2>>>0]=i.getMonth(),Z[n+20>>>2>>>0]=i.getFullYear()-1900,Z[n+24>>>2>>>0]=i.getDay(),Z[n+28>>>2>>>0]=(Lt(i.getFullYear())?ti:ri)[i.getMonth()]+i.getDate()-1|0,Z[n+36>>>2>>>0]=-(60*i.getTimezoneOffset());var a=new Date(i.getFullYear(),6,1).getTimezoneOffset(),u=new Date(i.getFullYear(),0,1).getTimezoneOffset();Z[n+32>>>2>>>0]=(a!=u&&i.getTimezoneOffset()==Math.min(u,a))|0},Tc:function(i){i>>>=0;var n=new Date(Z[i+20>>>2>>>0]+1900,Z[i+16>>>2>>>0],Z[i+12>>>2>>>0],Z[i+8>>>2>>>0],Z[i+4>>>2>>>0],Z[i>>>2>>>0],0),a=Z[i+32>>>2>>>0],u=n.getTimezoneOffset(),d=new Date(n.getFullYear(),6,1).getTimezoneOffset(),f=new Date(n.getFullYear(),0,1).getTimezoneOffset(),g=Math.min(f,d);return 0>a?Z[i+32>>>2>>>0]=+(d!=f&&g==u):0>>2>>>0]=n.getDay(),Z[i+28>>>2>>>0]=(Lt(n.getFullYear())?ti:ri)[n.getMonth()]+n.getDate()-1|0,Z[i>>>2>>>0]=n.getSeconds(),Z[i+4>>>2>>>0]=n.getMinutes(),Z[i+8>>>2>>>0]=n.getHours(),Z[i+12>>>2>>>0]=n.getDate(),Z[i+16>>>2>>>0]=n.getMonth(),Z[i+20>>>2>>>0]=n.getYear(),i=n.getTime(),BigInt(isNaN(i)?-1:i/1e3)},Pc:function(){return-52},Qc:function(){},Ic:function(i,n,a,u){a>>>=0,u>>>=0;var d=new Date().getFullYear(),f=new Date(d,0,1),g=new Date(d,6,1);d=f.getTimezoneOffset();var v=g.getTimezoneOffset();fe[i>>>0>>>2>>>0]=60*Math.max(d,v),Z[n>>>0>>>2>>>0]=+(d!=v),i=b=>b.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],f=i(f),g=i(g),v{ce("")},A:function(i,n,a){return i>>>=0,n=Fi(n>>>0,a>>>0),Ft[i](...n)},bc:function(i,n,a){return i>>>=0,n=Fi(n>>>0,a>>>0),Ft[i](...n)},$b:()=>Date.now(),Jc:function(){return 4294901760},ga:()=>performance.now(),Hc:function(i){i>>>=0;var n=oe.length;if(4294901760=a;a*=2){var u=n*(1+.2/a);u=Math.min(u,i+100663296);var d=Math;u=Math.max(i,u);e:{d=(d.min.call(d,4294901760,u+(65536-u%65536)%65536)-L.buffer.byteLength+65535)/65536;try{L.grow(d),ke();var f=1;break e}catch{}f=void 0}if(f)return!0}return!1},Wc:function(i,n){i>>>=0,n>>>=0;var a=0;return ii().forEach((u,d)=>{var f=n+a;for(d=fe[i+4*d>>>2>>>0]=f,f=0;f>>0]=u.charCodeAt(f);J[d>>>0]=0,a+=u.length+1}),0},Xc:function(i,n){i>>>=0,n>>>=0;var a=ii();fe[i>>>2>>>0]=a.length;var u=0;return a.forEach(d=>u+=d.length+1),fe[n>>>2>>>0]=u,0},Db:()=>52,Zb:function(){return 52},Vc:function(){return 70},Yb:function(i,n,a,u){n>>>=0,a>>>=0,u>>>=0;for(var d=0,f=0;f>>2>>>0],v=fe[n+4>>>2>>>0];n+=8;for(var b=0;b>>0],I=qn[i];x===0||x===10?((i===1?M:U)(Ai(I,0)),I.length=0):I.push(x)}d+=v}return fe[u>>>2>>>0]=d,0},xb:rm,cd:Ag,ua:Ah,W:yg,$:vg,ra:ih,ta:em,dd:Tg,ob:Th,P:jm,z:Uf,b:$f,Ub:Rf,ya:jf,e:wf,kb:hg,h:bf,X:ig,i:Af,ed:Sg,j:Tf,t:If,r:Lf,o:Xf,Wa:om,Ca:Vh,ma:qf,Qb:Pm,db:Bm,Ib:Gh,mb:Ph,kc:ag,xc:lm,hc:lg,ic:sg,ac:xg,oa:uh,yb:Qf,Ba:rg,Eb:$g,ea:lh,jc:og,Ta:Mm,F:xf,G:_m,Gb:ng,jd:ug,qa:$h,O:Sm,V:$m,T:Wm,y:Bf,Fb:fg,gc:dg,D:Yh,Hb:Zh,id:cg,Ua:Rm,wa:hh,lc:Jh,cc:Cg,Nb:ah,aa:tm,I:Df,C:mm,_a:Qh,fc:pg,Q:xm,d:Sf,ab:Tm,n:Cf,Ya:mg,va:Ih,wb:dm,f:_f,yc:um,da:tg,gb:Em,Da:nh,lb:zh,hb:pm,c:Ef,vc:gm,od:Hh,k:kf,tc:Am,l:Of,wc:fm,sc:km,rd:jh,p:Pf,Ra:Lm,tb:Hm,Qa:Fm,Kb:Eh,B:Ff,K:Mf,S:Kf,$a:Lh,pc:_h,ub:Im,za:Um,ka:zf,xa:zm,Sb:Yf,La:Ch,jb:Ig,Ga:Mh,nc:Uh,Ha:Dh,Ia:Rh,fd:_g,xd:Om,Z:Jm,pa:Sh,pd:Nh,wd:Vm,Mb:oh,Ma:bh,Ka:xh,Tb:Vf,rc:dh,Ja:kh,Na:vh,pb:sh,la:gh,Ea:Nm,mc:Xh,qc:fh,Jb:Wh,Fa:qh,ja:bm,Ad:nm,nd:Fh,R:ph,eb:Hf,Za:eg,ec:bg,ib:cm,E:Jf,M:Nf,Va:sm,ld:Kh,ca:am,nb:Oh,na:mh,dc:wg,Ac:Gf,u:Wf,L:ym,td:wh,Pb:Xm,oc:Bh,Bd:im,Ob:Zm,Lb:ch,cb:Dm,zc:Zf,Rb:wm,Oa:yh,Y:eh,uc:vm,J:Cm,gd:gg,vb:hm,sa:rh,H:th,rb:Ym,Pa:Km,Sa:Gm,sb:qm,qb:Qm,w:function(i){return i>>>0},Dc:Ki,fa:function(i,n,a,u){return Ki(i>>>0,n>>>0,a>>>0,u>>>0)}},D=function(){function i(a){return D=a.exports,D=Ui(),D=Eg(),L=D.Dd,ke(),ve.unshift(D.Ed),_e--,_e==0&&(et!==null&&(clearInterval(et),et=null),ee&&(a=ee,ee=null,a())),D}var n={a:Yi};if(_e++,r.instantiateWasm)try{return r.instantiateWasm(n,i)}catch(a){U(`Module.instantiateWasm callback failed with error: ${a}`),o(a)}return mt(n,function(a){i(a.instance)}).catch(o),{}}(),ai=i=>(ai=D.Fd)(i);r._OrtInit=(i,n)=>(r._OrtInit=D.Gd)(i,n),r._OrtGetLastError=(i,n)=>(r._OrtGetLastError=D.Hd)(i,n),r._OrtCreateSessionOptions=(i,n,a,u,d,f,g,v,b,x)=>(r._OrtCreateSessionOptions=D.Id)(i,n,a,u,d,f,g,v,b,x),r._OrtAppendExecutionProvider=(i,n)=>(r._OrtAppendExecutionProvider=D.Jd)(i,n),r._OrtAddFreeDimensionOverride=(i,n,a)=>(r._OrtAddFreeDimensionOverride=D.Kd)(i,n,a),r._OrtAddSessionConfigEntry=(i,n,a)=>(r._OrtAddSessionConfigEntry=D.Ld)(i,n,a),r._OrtReleaseSessionOptions=i=>(r._OrtReleaseSessionOptions=D.Md)(i),r._OrtCreateSession=(i,n,a)=>(r._OrtCreateSession=D.Nd)(i,n,a),r._OrtReleaseSession=i=>(r._OrtReleaseSession=D.Od)(i),r._OrtGetInputOutputCount=(i,n,a)=>(r._OrtGetInputOutputCount=D.Pd)(i,n,a),r._OrtGetInputName=(i,n)=>(r._OrtGetInputName=D.Qd)(i,n),r._OrtGetOutputName=(i,n)=>(r._OrtGetOutputName=D.Rd)(i,n),r._OrtFree=i=>(r._OrtFree=D.Sd)(i),r._OrtCreateTensor=(i,n,a,u,d,f)=>(r._OrtCreateTensor=D.Td)(i,n,a,u,d,f),r._OrtGetTensorData=(i,n,a,u,d)=>(r._OrtGetTensorData=D.Ud)(i,n,a,u,d),r._OrtReleaseTensor=i=>(r._OrtReleaseTensor=D.Vd)(i),r._OrtCreateRunOptions=(i,n,a,u)=>(r._OrtCreateRunOptions=D.Wd)(i,n,a,u),r._OrtAddRunConfigEntry=(i,n,a)=>(r._OrtAddRunConfigEntry=D.Xd)(i,n,a),r._OrtReleaseRunOptions=i=>(r._OrtReleaseRunOptions=D.Yd)(i),r._OrtCreateBinding=i=>(r._OrtCreateBinding=D.Zd)(i),r._OrtBindInput=(i,n,a)=>(r._OrtBindInput=D._d)(i,n,a),r._OrtBindOutput=(i,n,a,u)=>(r._OrtBindOutput=D.$d)(i,n,a,u),r._OrtClearBoundOutputs=i=>(r._OrtClearBoundOutputs=D.ae)(i),r._OrtReleaseBinding=i=>(r._OrtReleaseBinding=D.be)(i),r._OrtRunWithBinding=(i,n,a,u,d)=>(r._OrtRunWithBinding=D.ce)(i,n,a,u,d),r._OrtRun=(i,n,a,u,d,f,g,v)=>(r._OrtRun=D.de)(i,n,a,u,d,f,g,v),r._OrtEndProfiling=i=>(r._OrtEndProfiling=D.ee)(i),r._JsepOutput=(i,n,a)=>(r._JsepOutput=D.fe)(i,n,a),r._JsepGetNodeName=i=>(r._JsepGetNodeName=D.ge)(i);var or=r._malloc=i=>(or=r._malloc=D.he)(i),It=r._free=i=>(It=r._free=D.ie)(i),N=(i,n)=>(N=D.ke)(i,n),sr=i=>(sr=D.le)(i),V=i=>(V=D.me)(i),Qi=i=>(Qi=D.ne)(i),G=()=>(G=D.oe)(),Xi=i=>(Xi=D.pe)(i),Zi=i=>(Zi=D.qe)(i),Ji=(i,n,a)=>(Ji=D.re)(i,n,a),en=i=>(en=D.se)(i),ur=r.dynCall_vii=(i,n,a)=>(ur=r.dynCall_vii=D.te)(i,n,a),Br=r.dynCall_iiii=(i,n,a,u)=>(Br=r.dynCall_iiii=D.ue)(i,n,a,u),oi=r.dynCall_iii=(i,n,a)=>(oi=r.dynCall_iii=D.ve)(i,n,a),si=r.dynCall_ii=(i,n)=>(si=r.dynCall_ii=D.we)(i,n),ui=r.dynCall_iiiiiii=(i,n,a,u,d,f,g)=>(ui=r.dynCall_iiiiiii=D.xe)(i,n,a,u,d,f,g),Dr=r.dynCall_vi=(i,n)=>(Dr=r.dynCall_vi=D.ye)(i,n),Mr=r.dynCall_v=i=>(Mr=r.dynCall_v=D.ze)(i),li=r.dynCall_iiiiii=(i,n,a,u,d,f)=>(li=r.dynCall_iiiiii=D.Ae)(i,n,a,u,d,f),di=r.dynCall_iiij=(i,n,a,u)=>(di=r.dynCall_iiij=D.Be)(i,n,a,u),ci=r.dynCall_iiiii=(i,n,a,u,d)=>(ci=r.dynCall_iiiii=D.Ce)(i,n,a,u,d),Ur=r.dynCall_viii=(i,n,a,u)=>(Ur=r.dynCall_viii=D.De)(i,n,a,u),lr=r.dynCall_viiiii=(i,n,a,u,d,f)=>(lr=r.dynCall_viiiii=D.Ee)(i,n,a,u,d,f),Wr=r.dynCall_viiii=(i,n,a,u,d)=>(Wr=r.dynCall_viiii=D.Fe)(i,n,a,u,d),pi=r.dynCall_viiiiii=(i,n,a,u,d,f,g)=>(pi=r.dynCall_viiiiii=D.Ge)(i,n,a,u,d,f,g),fi=r.dynCall_viiji=(i,n,a,u,d)=>(fi=r.dynCall_viiji=D.He)(i,n,a,u,d),mi=r.dynCall_viiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P)=>(mi=r.dynCall_viiiiiiiiiii=D.Ie)(i,n,a,u,d,f,g,v,b,x,I,P),hi=r.dynCall_viiijjjii=(i,n,a,u,d,f,g,v,b)=>(hi=r.dynCall_viiijjjii=D.Je)(i,n,a,u,d,f,g,v,b),gi=r.dynCall_iid=(i,n,a)=>(gi=r.dynCall_iid=D.Ke)(i,n,a),tn=r.dynCall_iif=(i,n,a)=>(tn=r.dynCall_iif=D.Le)(i,n,a),dr=r.dynCall_iij=(i,n,a)=>(dr=r.dynCall_iij=D.Me)(i,n,a),yi=r.dynCall_jii=(i,n,a)=>(yi=r.dynCall_jii=D.Ne)(i,n,a),m=r.dynCall_i=i=>(m=r.dynCall_i=D.Oe)(i),w=r.dynCall_viiiiiiii=(i,n,a,u,d,f,g,v,b)=>(w=r.dynCall_viiiiiiii=D.Pe)(i,n,a,u,d,f,g,v,b),A=r.dynCall_viiiiij=(i,n,a,u,d,f,g)=>(A=r.dynCall_viiiiij=D.Qe)(i,n,a,u,d,f,g),j=r.dynCall_ji=(i,n)=>(j=r.dynCall_ji=D.Re)(i,n),H=r.dynCall_viij=(i,n,a,u)=>(H=r.dynCall_viij=D.Se)(i,n,a,u),X=r.dynCall_iiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P)=>(X=r.dynCall_iiiiiiiiiiii=D.Te)(i,n,a,u,d,f,g,v,b,x,I,P),re=r.dynCall_viiiiiiiii=(i,n,a,u,d,f,g,v,b,x)=>(re=r.dynCall_viiiiiiiii=D.Ue)(i,n,a,u,d,f,g,v,b,x),ye=r.dynCall_ij=(i,n)=>(ye=r.dynCall_ij=D.Ve)(i,n),he=r.dynCall_iiiiij=(i,n,a,u,d,f)=>(he=r.dynCall_iiiiij=D.We)(i,n,a,u,d,f),pe=r.dynCall_j=i=>(pe=r.dynCall_j=D.Xe)(i),be=r.dynCall_vij=(i,n,a)=>(be=r.dynCall_vij=D.Ye)(i,n,a),De=r.dynCall_viijjjiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P)=>(De=r.dynCall_viijjjiiiiii=D.Ze)(i,n,a,u,d,f,g,v,b,x,I,P),Me=r.dynCall_viiijiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P)=>(Me=r.dynCall_viiijiiiiiii=D._e)(i,n,a,u,d,f,g,v,b,x,I,P),q=r.dynCall_iiiiiiii=(i,n,a,u,d,f,g,v)=>(q=r.dynCall_iiiiiiii=D.$e)(i,n,a,u,d,f,g,v),Ie=r.dynCall_viiiiiii=(i,n,a,u,d,f,g,v)=>(Ie=r.dynCall_viiiiiii=D.af)(i,n,a,u,d,f,g,v),Ue=r.dynCall_iiiiiiiij=(i,n,a,u,d,f,g,v,b)=>(Ue=r.dynCall_iiiiiiiij=D.bf)(i,n,a,u,d,f,g,v,b),Mt=r.dynCall_viiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>(Mt=r.dynCall_viiiiiiiiiiiii=D.cf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k),vi=r.dynCall_iiiiiiiii=(i,n,a,u,d,f,g,v,b)=>(vi=r.dynCall_iiiiiiiii=D.df)(i,n,a,u,d,f,g,v,b),Fa=r.dynCall_iiiiijiiiii=(i,n,a,u,d,f,g,v,b,x,I)=>(Fa=r.dynCall_iiiiijiiiii=D.ef)(i,n,a,u,d,f,g,v,b,x,I),qa=r.dynCall_vijjjiiij=(i,n,a,u,d,f,g,v,b)=>(qa=r.dynCall_vijjjiiij=D.ff)(i,n,a,u,d,f,g,v,b),Ka=r.dynCall_fi=(i,n)=>(Ka=r.dynCall_fi=D.gf)(i,n),Ya=r.dynCall_fii=(i,n,a)=>(Ya=r.dynCall_fii=D.hf)(i,n,a),Qa=r.dynCall_di=(i,n)=>(Qa=r.dynCall_di=D.jf)(i,n),Xa=r.dynCall_dii=(i,n,a)=>(Xa=r.dynCall_dii=D.kf)(i,n,a),Za=r.dynCall_vijj=(i,n,a,u)=>(Za=r.dynCall_vijj=D.lf)(i,n,a,u),Ja=r.dynCall_iiiiiiiiii=(i,n,a,u,d,f,g,v,b,x)=>(Ja=r.dynCall_iiiiiiiiii=D.mf)(i,n,a,u,d,f,g,v,b,x),eo=r.dynCall_viijiii=(i,n,a,u,d,f,g)=>(eo=r.dynCall_viijiii=D.nf)(i,n,a,u,d,f,g),to=r.dynCall_viid=(i,n,a,u)=>(to=r.dynCall_viid=D.of)(i,n,a,u),ro=r.dynCall_viffiii=(i,n,a,u,d,f,g)=>(ro=r.dynCall_viffiii=D.pf)(i,n,a,u,d,f,g),io=r.dynCall_viifiii=(i,n,a,u,d,f,g)=>(io=r.dynCall_viifiii=D.qf)(i,n,a,u,d,f,g),no=r.dynCall_viiiiidiidi=(i,n,a,u,d,f,g,v,b,x,I)=>(no=r.dynCall_viiiiidiidi=D.rf)(i,n,a,u,d,f,g,v,b,x,I),ao=r.dynCall_viiiiiiiiidi=(i,n,a,u,d,f,g,v,b,x,I,P)=>(ao=r.dynCall_viiiiiiiiidi=D.sf)(i,n,a,u,d,f,g,v,b,x,I,P),oo=r.dynCall_jiii=(i,n,a,u)=>(oo=r.dynCall_jiii=D.tf)(i,n,a,u),so=r.dynCall_vjiiiiii=(i,n,a,u,d,f,g,v)=>(so=r.dynCall_vjiiiiii=D.uf)(i,n,a,u,d,f,g,v),uo=r.dynCall_viiid=(i,n,a,u,d)=>(uo=r.dynCall_viiid=D.vf)(i,n,a,u,d),lo=r.dynCall_viiiiiiiiiji=(i,n,a,u,d,f,g,v,b,x,I,P)=>(lo=r.dynCall_viiiiiiiiiji=D.wf)(i,n,a,u,d,f,g,v,b,x,I,P),co=r.dynCall_viji=(i,n,a,u)=>(co=r.dynCall_viji=D.xf)(i,n,a,u),po=r.dynCall_vijjjjjjjjjjjjji=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>(po=r.dynCall_vijjjjjjjjjjjjji=D.yf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y),fo=r.dynCall_viiiji=(i,n,a,u,d,f)=>(fo=r.dynCall_viiiji=D.zf)(i,n,a,u,d,f),mo=r.dynCall_vijjjiiji=(i,n,a,u,d,f,g,v,b)=>(mo=r.dynCall_vijjjiiji=D.Af)(i,n,a,u,d,f,g,v,b),ho=r.dynCall_iiiji=(i,n,a,u,d)=>(ho=r.dynCall_iiiji=D.Bf)(i,n,a,u,d),go=r.dynCall_iiijiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>(go=r.dynCall_iiijiiiiiiiiii=D.Cf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k),yo=r.dynCall_vj=(i,n)=>(yo=r.dynCall_vj=D.Df)(i,n),vo=r.dynCall_jjj=(i,n,a)=>(vo=r.dynCall_jjj=D.Ef)(i,n,a),bo=r.dynCall_iiijiiiiii=(i,n,a,u,d,f,g,v,b,x)=>(bo=r.dynCall_iiijiiiiii=D.Ff)(i,n,a,u,d,f,g,v,b,x),wo=r.dynCall_vfiii=(i,n,a,u,d)=>(wo=r.dynCall_vfiii=D.Gf)(i,n,a,u,d),_o=r.dynCall_viiiiff=(i,n,a,u,d,f,g)=>(_o=r.dynCall_viiiiff=D.Hf)(i,n,a,u,d,f,g),$o=r.dynCall_viiiiiff=(i,n,a,u,d,f,g,v)=>($o=r.dynCall_viiiiiff=D.If)(i,n,a,u,d,f,g,v),Co=r.dynCall_viiff=(i,n,a,u,d)=>(Co=r.dynCall_viiff=D.Jf)(i,n,a,u,d),xo=r.dynCall_viiiiiiiiifiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>(xo=r.dynCall_viiiiiiiiifiii=D.Kf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k),So=r.dynCall_viiiiiiiijj=(i,n,a,u,d,f,g,v,b,x,I)=>(So=r.dynCall_viiiiiiiijj=D.Lf)(i,n,a,u,d,f,g,v,b,x,I),Io=r.dynCall_iiiiiiiiiiiiiifii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae)=>(Io=r.dynCall_iiiiiiiiiiiiiifii=D.Mf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae),To=r.dynCall_viiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(To=r.dynCall_viiiiiiiiiiii=D.Nf)(i,n,a,u,d,f,g,v,b,x,I,P,B),Ao=r.dynCall_iiiiiiiiiiiiiiiiifii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be)=>(Ao=r.dynCall_iiiiiiiiiiiiiiiiifii=D.Of)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be),Eo=r.dynCall_vijjiiiiii=(i,n,a,u,d,f,g,v,b,x)=>(Eo=r.dynCall_vijjiiiiii=D.Pf)(i,n,a,u,d,f,g,v,b,x),ko=r.dynCall_iiiijjj=(i,n,a,u,d,f,g)=>(ko=r.dynCall_iiiijjj=D.Qf)(i,n,a,u,d,f,g),Oo=r.dynCall_viiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I)=>(Oo=r.dynCall_viiiiiiiiii=D.Rf)(i,n,a,u,d,f,g,v,b,x,I),Po=r.dynCall_iiijjj=(i,n,a,u,d,f)=>(Po=r.dynCall_iiijjj=D.Sf)(i,n,a,u,d,f),zo=r.dynCall_fffffff=(i,n,a,u,d,f,g)=>(zo=r.dynCall_fffffff=D.Tf)(i,n,a,u,d,f,g),Ro=r.dynCall_viiiij=(i,n,a,u,d,f)=>(Ro=r.dynCall_viiiij=D.Uf)(i,n,a,u,d,f),jo=r.dynCall_viiiiiijiifiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>(jo=r.dynCall_viiiiiijiifiii=D.Vf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k),Bo=r.dynCall_vjjjjjjffjifiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de)=>(Bo=r.dynCall_vjjjjjjffjifiiiiii=D.Wf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de),Do=r.dynCall_viiiiiiffjifiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae)=>(Do=r.dynCall_viiiiiiffjifiiiii=D.Xf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae),Mo=r.dynCall_viiiiiiffjfiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>(Mo=r.dynCall_viiiiiiffjfiiiii=D.Yf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y),Uo=r.dynCall_viiiiiiffjiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)=>(Uo=r.dynCall_viiiiiiffjiiiii=D.Zf)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W),Wo=r.dynCall_vjjjjjjjjfffiiifiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve)=>(Wo=r.dynCall_vjjjjjjjjfffiiifiiiii=D._f)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve),No=r.dynCall_vjjjjjjfffifijiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e)=>(No=r.dynCall_vjjjjjjfffifijiiiii=D.$f)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e),Vo=r.dynCall_vjjjjjjfffifiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de)=>(Vo=r.dynCall_vjjjjjjfffifiiiiii=D.ag)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de),Go=r.dynCall_vjjjjjjjjfffjifiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve)=>(Go=r.dynCall_vjjjjjjjjfffjifiiiiii=D.bg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve),Ho=r.dynCall_vijiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(Ho=r.dynCall_vijiiiiiiiiii=D.cg)(i,n,a,u,d,f,g,v,b,x,I,P,B),Lo=r.dynCall_vijjfffiii=(i,n,a,u,d,f,g,v,b,x)=>(Lo=r.dynCall_vijjfffiii=D.dg)(i,n,a,u,d,f,g,v,b,x),Fo=r.dynCall_viiiiiiijiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(Fo=r.dynCall_viiiiiiijiiii=D.eg)(i,n,a,u,d,f,g,v,b,x,I,P,B),qo=r.dynCall_vijjjjjjifiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)=>(qo=r.dynCall_vijjjjjjifiiiii=D.fg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W),Ko=r.dynCall_viifi=(i,n,a,u,d)=>(Ko=r.dynCall_viifi=D.gg)(i,n,a,u,d),Yo=r.dynCall_vjjjjjiiii=(i,n,a,u,d,f,g,v,b,x)=>(Yo=r.dynCall_vjjjjjiiii=D.hg)(i,n,a,u,d,f,g,v,b,x),Qo=r.dynCall_vjjjjfiii=(i,n,a,u,d,f,g,v,b)=>(Qo=r.dynCall_vjjjjfiii=D.ig)(i,n,a,u,d,f,g,v,b),Xo=r.dynCall_viiiiiijiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>(Xo=r.dynCall_viiiiiijiiiiii=D.jg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k),Zo=r.dynCall_vijjii=(i,n,a,u,d,f)=>(Zo=r.dynCall_vijjii=D.kg)(i,n,a,u,d,f),Jo=r.dynCall_viiiiijjiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(Jo=r.dynCall_viiiiijjiiiii=D.lg)(i,n,a,u,d,f,g,v,b,x,I,P,B),es=r.dynCall_iiiiiji=(i,n,a,u,d,f,g)=>(es=r.dynCall_iiiiiji=D.mg)(i,n,a,u,d,f,g),ts=r.dynCall_iiiiji=(i,n,a,u,d,f)=>(ts=r.dynCall_iiiiji=D.ng)(i,n,a,u,d,f),rs=r.dynCall_viiiiijiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(rs=r.dynCall_viiiiijiiiiii=D.og)(i,n,a,u,d,f,g,v,b,x,I,P,B),is=r.dynCall_viiijiiiiii=(i,n,a,u,d,f,g,v,b,x,I)=>(is=r.dynCall_viiijiiiiii=D.pg)(i,n,a,u,d,f,g,v,b,x,I),ns=r.dynCall_viijj=(i,n,a,u,d)=>(ns=r.dynCall_viijj=D.qg)(i,n,a,u,d),as=r.dynCall_viiiijii=(i,n,a,u,d,f,g,v)=>(as=r.dynCall_viiiijii=D.rg)(i,n,a,u,d,f,g,v),os=r.dynCall_viijjiii=(i,n,a,u,d,f,g,v)=>(os=r.dynCall_viijjiii=D.sg)(i,n,a,u,d,f,g,v),ss=r.dynCall_ijii=(i,n,a,u)=>(ss=r.dynCall_ijii=D.tg)(i,n,a,u),us=r.dynCall_viiiiijjji=(i,n,a,u,d,f,g,v,b,x)=>(us=r.dynCall_viiiiijjji=D.ug)(i,n,a,u,d,f,g,v,b,x),ls=r.dynCall_vijjjjiij=(i,n,a,u,d,f,g,v,b)=>(ls=r.dynCall_vijjjjiij=D.vg)(i,n,a,u,d,f,g,v,b),ds=r.dynCall_viiiiijij=(i,n,a,u,d,f,g,v,b)=>(ds=r.dynCall_viiiiijij=D.wg)(i,n,a,u,d,f,g,v,b),cs=r.dynCall_viiiiiijij=(i,n,a,u,d,f,g,v,b,x)=>(cs=r.dynCall_viiiiiijij=D.xg)(i,n,a,u,d,f,g,v,b,x),ps=r.dynCall_vijiii=(i,n,a,u,d,f)=>(ps=r.dynCall_vijiii=D.yg)(i,n,a,u,d,f),fs=r.dynCall_viiiiiiiiifi=(i,n,a,u,d,f,g,v,b,x,I,P)=>(fs=r.dynCall_viiiiiiiiifi=D.zg)(i,n,a,u,d,f,g,v,b,x,I,P),ms=r.dynCall_iiijiiii=(i,n,a,u,d,f,g,v)=>(ms=r.dynCall_iiijiiii=D.Ag)(i,n,a,u,d,f,g,v),hs=r.dynCall_viiiiiijjiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>(hs=r.dynCall_viiiiiijjiiiii=D.Bg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k),gs=r.dynCall_viiiiiiijiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)=>(gs=r.dynCall_viiiiiiijiiiiii=D.Cg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W),ys=r.dynCall_vif=(i,n,a)=>(ys=r.dynCall_vif=D.Dg)(i,n,a),vs=r.dynCall_viif=(i,n,a,u)=>(vs=r.dynCall_viif=D.Eg)(i,n,a,u),bs=r.dynCall_fiii=(i,n,a,u)=>(bs=r.dynCall_fiii=D.Fg)(i,n,a,u),ws=r.dynCall_diii=(i,n,a,u)=>(ws=r.dynCall_diii=D.Gg)(i,n,a,u),_s=r.dynCall_viiiiiifii=(i,n,a,u,d,f,g,v,b,x)=>(_s=r.dynCall_viiiiiifii=D.Hg)(i,n,a,u,d,f,g,v,b,x),$s=r.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve,tt,pt,Kn,Yn,Qn)=>($s=r.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=D.Ig)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve,tt,pt,Kn,Yn,Qn),Cs=r.dynCall_viijji=(i,n,a,u,d,f)=>(Cs=r.dynCall_viijji=D.Jg)(i,n,a,u,d,f),xs=r.dynCall_iiiiiiiiiiiji=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(xs=r.dynCall_iiiiiiiiiiiji=D.Kg)(i,n,a,u,d,f,g,v,b,x,I,P,B),Ss=r.dynCall_viifiifijjjii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(Ss=r.dynCall_viifiifijjjii=D.Lg)(i,n,a,u,d,f,g,v,b,x,I,P,B),Is=r.dynCall_viiiiiiiiiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve)=>(Is=r.dynCall_viiiiiiiiiiiiiiiiiiii=D.Mg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve),Ts=r.dynCall_viiiiifiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(Ts=r.dynCall_viiiiifiiiiii=D.Ng)(i,n,a,u,d,f,g,v,b,x,I,P,B),As=r.dynCall_vijiiiiiiijjii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k)=>(As=r.dynCall_vijiiiiiiijjii=D.Og)(i,n,a,u,d,f,g,v,b,x,I,P,B,k),Es=r.dynCall_viiiiiiiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e)=>(Es=r.dynCall_viiiiiiiiiiiiiiiiii=D.Pg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e),ks=r.dynCall_viiiiiiiiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be)=>(ks=r.dynCall_viiiiiiiiiiiiiiiiiii=D.Qg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be),Os=r.dynCall_viiiiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)=>(Os=r.dynCall_viiiiiiiiiiiiiii=D.Rg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y),Ps=r.dynCall_viiiiiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae)=>(Ps=r.dynCall_viiiiiiiiiiiiiiii=D.Sg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae),zs=r.dynCall_viiiijjj=(i,n,a,u,d,f,g,v)=>(zs=r.dynCall_viiiijjj=D.Tg)(i,n,a,u,d,f,g,v),Rs=r.dynCall_iiiiid=(i,n,a,u,d,f)=>(Rs=r.dynCall_iiiiid=D.Ug)(i,n,a,u,d,f),js=r.dynCall_viiiiiiijjj=(i,n,a,u,d,f,g,v,b,x,I)=>(js=r.dynCall_viiiiiiijjj=D.Vg)(i,n,a,u,d,f,g,v,b,x,I),Bs=r.dynCall_iiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I)=>(Bs=r.dynCall_iiiiiiiiiii=D.Wg)(i,n,a,u,d,f,g,v,b,x,I),Ds=r.dynCall_iiiiiiiiiiiiiiiiiifi=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be)=>(Ds=r.dynCall_iiiiiiiiiiiiiiiiiifi=D.Xg)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be),Ms=r.dynCall_viiif=(i,n,a,u,d)=>(Ms=r.dynCall_viiif=D.Yg)(i,n,a,u,d),Us=r.dynCall_viiijiiiii=(i,n,a,u,d,f,g,v,b,x)=>(Us=r.dynCall_viiijiiiii=D.Zg)(i,n,a,u,d,f,g,v,b,x),Ws=r.dynCall_viiij=(i,n,a,u,d)=>(Ws=r.dynCall_viiij=D._g)(i,n,a,u,d),Ns=r.dynCall_iijjj=(i,n,a,u,d)=>(Ns=r.dynCall_iijjj=D.$g)(i,n,a,u,d),Vs=r.dynCall_viiiiji=(i,n,a,u,d,f,g)=>(Vs=r.dynCall_viiiiji=D.ah)(i,n,a,u,d,f,g),Gs=r.dynCall_iijjji=(i,n,a,u,d,f)=>(Gs=r.dynCall_iijjji=D.bh)(i,n,a,u,d,f),Hs=r.dynCall_ijijji=(i,n,a,u,d,f)=>(Hs=r.dynCall_ijijji=D.ch)(i,n,a,u,d,f),Ls=r.dynCall_viiijjiii=(i,n,a,u,d,f,g,v,b)=>(Ls=r.dynCall_viiijjiii=D.dh)(i,n,a,u,d,f,g,v,b),Fs=r.dynCall_iiiiijji=(i,n,a,u,d,f,g,v)=>(Fs=r.dynCall_iiiiijji=D.eh)(i,n,a,u,d,f,g,v),qs=r.dynCall_iiiifi=(i,n,a,u,d,f)=>(qs=r.dynCall_iiiifi=D.fh)(i,n,a,u,d,f),Ks=r.dynCall_iiijii=(i,n,a,u,d,f)=>(Ks=r.dynCall_iiijii=D.gh)(i,n,a,u,d,f),Ys=r.dynCall_iiiiiiiiijii=(i,n,a,u,d,f,g,v,b,x,I,P)=>(Ys=r.dynCall_iiiiiiiiijii=D.hh)(i,n,a,u,d,f,g,v,b,x,I,P),Qs=r.dynCall_iiiijjii=(i,n,a,u,d,f,g,v)=>(Qs=r.dynCall_iiiijjii=D.ih)(i,n,a,u,d,f,g,v),Xs=r.dynCall_iiiiiijjjii=(i,n,a,u,d,f,g,v,b,x,I)=>(Xs=r.dynCall_iiiiiijjjii=D.jh)(i,n,a,u,d,f,g,v,b,x,I),Zs=r.dynCall_iiijiii=(i,n,a,u,d,f,g)=>(Zs=r.dynCall_iiijiii=D.kh)(i,n,a,u,d,f,g),Js=r.dynCall_iiiiiiiijjjfi=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(Js=r.dynCall_iiiiiiiijjjfi=D.lh)(i,n,a,u,d,f,g,v,b,x,I,P,B),eu=r.dynCall_iijiiii=(i,n,a,u,d,f,g)=>(eu=r.dynCall_iijiiii=D.mh)(i,n,a,u,d,f,g),tu=r.dynCall_iijjjii=(i,n,a,u,d,f,g)=>(tu=r.dynCall_iijjjii=D.nh)(i,n,a,u,d,f,g),ru=r.dynCall_jij=(i,n,a)=>(ru=r.dynCall_jij=D.oh)(i,n,a),iu=r.dynCall_iiji=(i,n,a,u)=>(iu=r.dynCall_iiji=D.ph)(i,n,a,u),nu=r.dynCall_iiif=(i,n,a,u)=>(nu=r.dynCall_iiif=D.qh)(i,n,a,u),au=r.dynCall_vidi=(i,n,a,u)=>(au=r.dynCall_vidi=D.rh)(i,n,a,u),ou=r.dynCall_vjiii=(i,n,a,u,d)=>(ou=r.dynCall_vjiii=D.sh)(i,n,a,u,d),su=r.dynCall_diiii=(i,n,a,u,d)=>(su=r.dynCall_diiii=D.th)(i,n,a,u,d),uu=r.dynCall_diiiii=(i,n,a,u,d,f)=>(uu=r.dynCall_diiiii=D.uh)(i,n,a,u,d,f),lu=r.dynCall_viiijjiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P)=>(lu=r.dynCall_viiijjiiiiii=D.vh)(i,n,a,u,d,f,g,v,b,x,I,P),du=r.dynCall_viijjijjjjiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(du=r.dynCall_viijjijjjjiii=D.wh)(i,n,a,u,d,f,g,v,b,x,I,P,B),cu=r.dynCall_iiiij=(i,n,a,u,d)=>(cu=r.dynCall_iiiij=D.xh)(i,n,a,u,d),pu=r.dynCall_viiijii=(i,n,a,u,d,f,g)=>(pu=r.dynCall_viiijii=D.yh)(i,n,a,u,d,f,g),fu=r.dynCall_viijiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B)=>(fu=r.dynCall_viijiiiiiiiii=D.zh)(i,n,a,u,d,f,g,v,b,x,I,P,B),mu=r.dynCall_fiiii=(i,n,a,u,d)=>(mu=r.dynCall_fiiii=D.Ah)(i,n,a,u,d),hu=r.dynCall_jfi=(i,n,a)=>(hu=r.dynCall_jfi=D.Bh)(i,n,a),gu=r.dynCall_viiiiiiiiiiiiii=(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)=>(gu=r.dynCall_viiiiiiiiiiiiii=D.Ch)(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W),yu=r.dynCall_jiij=(i,n,a,u)=>(yu=r.dynCall_jiij=D.Dh)(i,n,a,u),vu=i=>(vu=D.Eh)(i),bu=()=>(bu=D.Fh)(),wu=i=>(wu=D.Gh)(i),_u=()=>(_u=D.Hh)();r.___start_em_js=1275044,r.___stop_em_js=1275205;function bf(i,n,a,u){var d=G();try{return Br(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function wf(i,n,a){var u=G();try{return oi(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function _f(i,n,a){var u=G();try{ur(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function $f(i,n){var a=G();try{return si(i,n)}catch(u){if(V(a),u!==u+0)throw u;N(1,0)}}function Cf(i,n){var a=G();try{Dr(i,n)}catch(u){if(V(a),u!==u+0)throw u;N(1,0)}}function xf(i,n,a,u){var d=G();try{return di(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function Sf(i){var n=G();try{Mr(i)}catch(a){if(V(n),a!==a+0)throw a;N(1,0)}}function If(i,n,a,u,d,f,g){var v=G();try{return ui(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function Tf(i,n,a,u,d,f){var g=G();try{return li(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Af(i,n,a,u,d){var f=G();try{return ci(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Ef(i,n,a,u){var d=G();try{Ur(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function kf(i,n,a,u,d){var f=G();try{Wr(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Of(i,n,a,u,d,f){var g=G();try{lr(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Pf(i,n,a,u,d,f,g){var v=G();try{pi(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function zf(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{mi(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function Rf(i,n,a){var u=G();try{return gi(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function jf(i,n,a){var u=G();try{return tn(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function Bf(i,n,a){var u=G();try{return dr(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function Df(i,n,a){var u=G();try{return yi(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;return N(1,0),0n}}function Mf(i,n,a,u,d,f,g,v,b){var x=G();try{w(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function Uf(i){var n=G();try{return m(i)}catch(a){if(V(n),a!==a+0)throw a;N(1,0)}}function Wf(i,n,a){var u=G();try{be(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function Nf(i,n,a,u,d){var f=G();try{fi(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Vf(i,n,a,u,d,f,g){var v=G();try{A(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function Gf(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{De(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function Hf(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{Me(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function Lf(i,n,a,u,d,f,g,v){var b=G();try{return q(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function Ff(i,n,a,u,d,f,g,v){var b=G();try{Ie(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function qf(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{return X(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function Kf(i,n,a,u,d,f,g,v,b,x){var I=G();try{re(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function Yf(i,n,a,u,d,f,g,v,b,x,I,P,B,k){var W=G();try{Mt(i,n,a,u,d,f,g,v,b,x,I,P,B,k)}catch(Y){if(V(W),Y!==Y+0)throw Y;N(1,0)}}function Qf(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{return Fa(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function Xf(i,n,a,u,d,f,g,v,b){var x=G();try{return vi(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function Zf(i,n,a,u,d,f,g,v,b){var x=G();try{qa(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function Jf(i,n,a,u){var d=G();try{H(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function em(i,n){var a=G();try{return Ka(i,n)}catch(u){if(V(a),u!==u+0)throw u;N(1,0)}}function tm(i,n){var a=G();try{return j(i,n)}catch(u){if(V(a),u!==u+0)throw u;return N(1,0),0n}}function rm(i,n){var a=G();try{return Qa(i,n)}catch(u){if(V(a),u!==u+0)throw u;N(1,0)}}function im(i,n,a,u){var d=G();try{Za(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function nm(i,n,a,u,d,f,g){var v=G();try{pu(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function am(i,n,a,u,d){var f=G();try{ns(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function om(i,n,a,u,d,f,g,v,b,x){var I=G();try{return Ja(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function sm(i,n,a,u,d,f,g){var v=G();try{eo(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function um(i,n,a,u){var d=G();try{to(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function lm(i,n,a,u,d,f,g,v,b){var x=G();try{return Ue(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function dm(i,n,a,u,d,f,g){var v=G();try{ro(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function cm(i,n,a,u,d,f,g,v,b){var x=G();try{hi(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function pm(i,n,a,u,d,f,g){var v=G();try{io(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function fm(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{no(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function mm(i,n,a,u){var d=G();try{return oo(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;return N(1,0),0n}}function hm(i,n,a,u,d,f,g,v){var b=G();try{so(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function gm(i,n,a,u,d){var f=G();try{uo(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function ym(i,n,a,u){var d=G();try{co(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function vm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y){var ae=G();try{po(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)}catch(de){if(V(ae),de!==de+0)throw de;N(1,0)}}function bm(i,n,a,u,d,f){var g=G();try{fo(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function wm(i,n,a,u,d,f,g,v,b){var x=G();try{mo(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function _m(i,n,a,u,d){var f=G();try{return ho(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function $m(i,n,a,u,d,f,g,v,b,x,I,P,B,k){var W=G();try{return go(i,n,a,u,d,f,g,v,b,x,I,P,B,k)}catch(Y){if(V(W),Y!==Y+0)throw Y;N(1,0)}}function Cm(i,n){var a=G();try{yo(i,n)}catch(u){if(V(a),u!==u+0)throw u;N(1,0)}}function xm(i,n,a){var u=G();try{return vo(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;return N(1,0),0n}}function Sm(i,n,a,u,d,f,g,v,b,x){var I=G();try{return bo(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function Im(i,n,a,u,d,f,g,v,b,x,I,P,B,k){var W=G();try{xo(i,n,a,u,d,f,g,v,b,x,I,P,B,k)}catch(Y){if(V(W),Y!==Y+0)throw Y;N(1,0)}}function Tm(i,n,a,u,d){var f=G();try{wo(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Am(i,n,a,u,d,f,g){var v=G();try{_o(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function Em(i,n,a,u,d){var f=G();try{Co(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function km(i,n,a,u,d,f,g,v){var b=G();try{$o(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function Om(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{So(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function Pm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae){var de=G();try{return Io(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae)}catch($e){if(V(de),$e!==$e+0)throw $e;N(1,0)}}function zm(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{To(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function Rm(i,n){var a=G();try{return ye(i,n)}catch(u){if(V(a),u!==u+0)throw u;N(1,0)}}function jm(i,n,a,u,d){var f=G();try{return mu(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Bm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be){var Ve=G();try{return Ao(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be)}catch(tt){if(V(Ve),tt!==tt+0)throw tt;N(1,0)}}function Dm(i,n,a,u,d,f,g,v,b,x){var I=G();try{Eo(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function Mm(i,n,a,u,d,f,g){var v=G();try{return ko(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function Um(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{Oo(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function Wm(i,n,a,u,d,f){var g=G();try{return Po(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Nm(i,n,a,u,d,f){var g=G();try{Ro(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Vm(i,n,a,u,d,f,g,v,b,x,I,P,B,k){var W=G();try{jo(i,n,a,u,d,f,g,v,b,x,I,P,B,k)}catch(Y){if(V(W),Y!==Y+0)throw Y;N(1,0)}}function Gm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de){var $e=G();try{Bo(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de)}catch(Be){if(V($e),Be!==Be+0)throw Be;N(1,0)}}function Hm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae){var de=G();try{Do(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae)}catch($e){if(V(de),$e!==$e+0)throw $e;N(1,0)}}function Lm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y){var ae=G();try{Mo(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)}catch(de){if(V(ae),de!==de+0)throw de;N(1,0)}}function Fm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W){var Y=G();try{Uo(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)}catch(ae){if(V(Y),ae!==ae+0)throw ae;N(1,0)}}function qm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve){var tt=G();try{Wo(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve)}catch(pt){if(V(tt),pt!==pt+0)throw pt;N(1,0)}}function Km(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e){var Be=G();try{No(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e)}catch(Ve){if(V(Be),Ve!==Ve+0)throw Ve;N(1,0)}}function Ym(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de){var $e=G();try{Vo(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de)}catch(Be){if(V($e),Be!==Be+0)throw Be;N(1,0)}}function Qm(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve){var tt=G();try{Go(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve)}catch(pt){if(V(tt),pt!==pt+0)throw pt;N(1,0)}}function Xm(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{Ho(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function Zm(i,n,a,u,d,f,g,v,b,x){var I=G();try{Lo(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function Jm(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{Fo(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function eh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W){var Y=G();try{qo(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)}catch(ae){if(V(Y),ae!==ae+0)throw ae;N(1,0)}}function th(i,n,a,u,d,f,g,v,b,x){var I=G();try{Yo(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function rh(i,n,a,u,d,f,g,v,b){var x=G();try{Qo(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function ih(i,n,a,u,d,f,g){var v=G();try{return zo(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function nh(i,n,a,u,d){var f=G();try{Ko(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function ah(i,n,a){var u=G();try{return hu(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;return N(1,0),0n}}function oh(i,n,a,u,d,f,g,v,b,x,I,P,B,k){var W=G();try{Xo(i,n,a,u,d,f,g,v,b,x,I,P,B,k)}catch(Y){if(V(W),Y!==Y+0)throw Y;N(1,0)}}function sh(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{Jo(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function uh(i,n,a,u,d,f,g){var v=G();try{return es(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function lh(i,n,a,u,d,f){var g=G();try{return ts(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function dh(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{rs(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function ch(i,n,a,u,d,f){var g=G();try{Zo(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function ph(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{is(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function fh(i,n,a,u,d,f,g,v){var b=G();try{as(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function mh(i,n,a,u,d,f,g,v){var b=G();try{os(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function hh(i,n,a,u){var d=G();try{return ss(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function gh(i,n,a,u,d,f,g,v,b,x){var I=G();try{us(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function yh(i,n,a,u,d,f,g,v,b){var x=G();try{ls(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function vh(i,n,a,u,d,f,g,v,b){var x=G();try{ds(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function bh(i,n,a,u,d,f,g,v,b,x){var I=G();try{cs(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function wh(i,n,a,u,d,f){var g=G();try{ps(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function _h(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{fs(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function $h(i,n,a,u,d,f,g,v){var b=G();try{return ms(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function Ch(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W){var Y=G();try{gu(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)}catch(ae){if(V(Y),ae!==ae+0)throw ae;N(1,0)}}function xh(i,n,a,u,d,f,g,v,b,x,I,P,B,k){var W=G();try{hs(i,n,a,u,d,f,g,v,b,x,I,P,B,k)}catch(Y){if(V(W),Y!==Y+0)throw Y;N(1,0)}}function Sh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W){var Y=G();try{gs(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W)}catch(ae){if(V(Y),ae!==ae+0)throw ae;N(1,0)}}function Ih(i,n,a){var u=G();try{ys(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function Th(i,n,a,u){var d=G();try{return bs(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function Ah(i,n,a,u){var d=G();try{return ws(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function Eh(i,n,a,u,d,f,g,v,b,x){var I=G();try{_s(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function kh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve,tt,pt,Kn,Yn,Qn){var kg=G();try{$s(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve,tt,pt,Kn,Yn,Qn)}catch(Xn){if(V(kg),Xn!==Xn+0)throw Xn;N(1,0)}}function Oh(i,n,a,u,d,f){var g=G();try{Cs(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Ph(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{return xs(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function zh(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{Ss(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function Rh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve){var tt=G();try{Is(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be,Ve)}catch(pt){if(V(tt),pt!==pt+0)throw pt;N(1,0)}}function jh(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{Ts(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function Bh(i,n,a,u,d,f,g,v,b,x,I,P,B,k){var W=G();try{As(i,n,a,u,d,f,g,v,b,x,I,P,B,k)}catch(Y){if(V(W),Y!==Y+0)throw Y;N(1,0)}}function Dh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be){var Ve=G();try{ks(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be)}catch(tt){if(V(Ve),tt!==tt+0)throw tt;N(1,0)}}function Mh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae){var de=G();try{Ps(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae)}catch($e){if(V(de),$e!==$e+0)throw $e;N(1,0)}}function Uh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e){var Be=G();try{Es(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e)}catch(Ve){if(V(Be),Ve!==Ve+0)throw Ve;N(1,0)}}function Wh(i,n,a,u,d,f,g,v){var b=G();try{zs(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function Nh(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{js(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function Vh(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{return Bs(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function Gh(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be){var Ve=G();try{return Ds(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y,ae,de,$e,Be)}catch(tt){if(V(Ve),tt!==tt+0)throw tt;N(1,0)}}function Hh(i,n,a,u,d){var f=G();try{Ms(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Lh(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{ao(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function Fh(i,n,a,u,d,f,g,v,b,x){var I=G();try{Us(i,n,a,u,d,f,g,v,b,x)}catch(P){if(V(I),P!==P+0)throw P;N(1,0)}}function qh(i,n,a,u,d){var f=G();try{Ws(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Kh(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{fu(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function Yh(i,n,a,u,d){var f=G();try{return Ns(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Qh(i,n,a,u){var d=G();try{return yu(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;return N(1,0),0n}}function Xh(i,n,a,u,d,f,g){var v=G();try{Vs(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function Zh(i,n,a,u,d,f){var g=G();try{return Gs(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Jh(i,n,a,u,d,f){var g=G();try{return Hs(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function eg(i,n,a,u,d,f,g,v,b){var x=G();try{Ls(i,n,a,u,d,f,g,v,b)}catch(I){if(V(x),I!==I+0)throw I;N(1,0)}}function tg(i,n,a,u){var d=G();try{vs(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function rg(i,n,a,u,d,f,g,v){var b=G();try{return Fs(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function ig(i,n,a,u,d,f){var g=G();try{return qs(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function ng(i,n,a,u,d,f){var g=G();try{return Ks(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function ag(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{return Ys(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function og(i,n,a,u,d,f,g,v){var b=G();try{return Qs(i,n,a,u,d,f,g,v)}catch(x){if(V(b),x!==x+0)throw x;N(1,0)}}function sg(i,n,a,u,d,f,g,v,b,x,I){var P=G();try{return Xs(i,n,a,u,d,f,g,v,b,x,I)}catch(B){if(V(P),B!==B+0)throw B;N(1,0)}}function ug(i,n,a,u,d,f,g){var v=G();try{return Zs(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function lg(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{return Js(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function dg(i,n,a,u,d,f,g){var v=G();try{return eu(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function cg(i,n,a,u,d,f,g){var v=G();try{return tu(i,n,a,u,d,f,g)}catch(b){if(V(v),b!==b+0)throw b;N(1,0)}}function pg(i,n,a){var u=G();try{return ru(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;return N(1,0),0n}}function fg(i,n,a,u){var d=G();try{return iu(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function mg(i,n,a,u){var d=G();try{au(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function hg(i,n,a,u){var d=G();try{return nu(i,n,a,u)}catch(f){if(V(d),f!==f+0)throw f;N(1,0)}}function gg(i,n,a,u,d){var f=G();try{ou(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function yg(i,n,a,u,d){var f=G();try{return su(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function vg(i,n,a,u,d,f){var g=G();try{return uu(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function bg(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{lu(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function wg(i,n,a,u,d,f,g,v,b,x,I,P,B){var k=G();try{du(i,n,a,u,d,f,g,v,b,x,I,P,B)}catch(W){if(V(k),W!==W+0)throw W;N(1,0)}}function _g(i,n,a,u,d,f,g,v,b,x,I,P){var B=G();try{lo(i,n,a,u,d,f,g,v,b,x,I,P)}catch(k){if(V(B),k!==k+0)throw k;N(1,0)}}function $g(i,n,a,u,d){var f=G();try{return cu(i,n,a,u,d)}catch(g){if(V(f),g!==g+0)throw g;N(1,0)}}function Cg(i){var n=G();try{return pe(i)}catch(a){if(V(n),a!==a+0)throw a;return N(1,0),0n}}function xg(i,n,a,u,d,f){var g=G();try{return he(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Sg(i,n,a,u,d,f){var g=G();try{return Rs(i,n,a,u,d,f)}catch(v){if(V(g),v!==v+0)throw v;N(1,0)}}function Ig(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y){var ae=G();try{Os(i,n,a,u,d,f,g,v,b,x,I,P,B,k,W,Y)}catch(de){if(V(ae),de!==de+0)throw de;N(1,0)}}function Tg(i,n,a){var u=G();try{return Ya(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function Ag(i,n,a){var u=G();try{return Xa(i,n,a)}catch(d){if(V(u),d!==d+0)throw d;N(1,0)}}function Eg(){var i=D;i=Object.assign({},i);var n=a=>u=>a(u)>>>0;return i.Fd=n(i.Fd),i.he=n(i.he),i.ne=n(i.ne),i.oe=(a=>()=>a()>>>0)(i.oe),i}r.stackSave=()=>G(),r.stackRestore=i=>V(i),r.stackAlloc=i=>Qi(i),r.UTF8ToString=Ke,r.stringToUTF8=(i,n,a)=>xt(i,oe,n,a),r.lengthBytesUTF8=tr;var rn;ee=function i(){rn||$u(),rn||(ee=i)};function $u(){if(!(0<_e)){if(r.preRun)for(typeof r.preRun=="function"&&(r.preRun=[r.preRun]);r.preRun.length;){var i=r.preRun.shift();Ce.unshift(i)}for(;0Ju)});var rl=Nr(()=>{});var il=Nr(()=>{});var nl={};Vr(nl,{cpus:()=>Vg});var Vg,al=ie(()=>{Vg=void 0});var ul=Nr((sl,oa)=>{"use strict";var ol=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){function r(){return we.buffer!=Ce.buffer&&ee(),Ce}function s(){return we.buffer!=Ce.buffer&&ee(),ve}function o(){return we.buffer!=Ce.buffer&&ee(),Ae}function c(){return we.buffer!=Ce.buffer&&ee(),_e}function p(){return we.buffer!=Ce.buffer&&ee(),et}var l=t,h,y;l.ready=new Promise((m,w)=>{h=m,y=w}),l.jsepInit=(m,w,A,j,H,X,re,ye)=>{l.Qb=m,l.wb=w,l.yb=A,l.jb=j,l.xb=H,l.Ea=X,l.zb=re,l.Ab=ye,w=(he,pe,be)=>(...De)=>{let Me=ct,q=pe?.();De=he(...De);let Ie=pe?.();return q!==Ie&&(he=Ie,be(q),pe=be=null),ct!=Me?V():De},A=he=>async(...pe)=>{try{if(l.bb)throw Error("Session already started");let be=l.bb={Fb:pe[0],errors:[]},De=await he(...pe);if(l.bb!==be)throw Error("Session mismatch");m.flush();let Me=be.errors;if(0Ie),0l._OrtRun,he=>l._OrtRun=he)),l._OrtRunWithBinding=A(w(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,he=>l._OrtRunWithBinding=he)),l._OrtBindInput=w(l._OrtBindInput,()=>l._OrtBindInput,he=>l._OrtBindInput=he),l.jsepRegisterBuffer=(he,pe,be,De)=>m.registerBuffer(he,pe,be,De),l.jsepUnregisterBuffers=he=>{m.unregisterBuffers(he)},l.jsepGetBuffer=he=>m.getBuffer(he),l.jsepCreateDownloader=(he,pe,be)=>m.createDownloader(he,pe,be)};var $=Object.assign({},l),_="./this.program",C=(m,w)=>{throw w},T=typeof window=="object",S=typeof importScripts=="function",E=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",O=l.ENVIRONMENT_IS_PTHREAD||!1,R="";function z(m){return l.locateFile?l.locateFile(m,R):R+m}var M,U,L;if(E){var F=(fn(),Qt(pn)),te=(na(),Qt(ia));R=S?te.dirname(R)+"/":__dirname+"/",M=(w,A)=>(w=w.startsWith("file://")?new URL(w):te.normalize(w),F.readFileSync(w,A?void 0:"utf8")),L=w=>(w=M(w,!0),w.buffer||(w=new Uint8Array(w)),w),U=(w,A,j,H=!0)=>{w=w.startsWith("file://")?new URL(w):te.normalize(w),F.readFile(w,H?void 0:"utf8",(X,re)=>{X?j(X):A(H?re.buffer:re)})},!l.thisProgram&&1{throw process.exitCode=w,A},l.inspect=()=>"[Emscripten Module object]";let m;try{m=rl()}catch(w){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),w}global.Worker=m.Worker}else(T||S)&&(S?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),typeof e<"u"&&e&&(R=e),R.indexOf("blob:")!==0?R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):R="",E||(M=m=>{var w=new XMLHttpRequest;return w.open("GET",m,!1),w.send(null),w.responseText},S&&(L=m=>{var w=new XMLHttpRequest;return w.open("GET",m,!1),w.responseType="arraybuffer",w.send(null),new Uint8Array(w.response)}),U=(m,w,A)=>{var j=new XMLHttpRequest;j.open("GET",m,!0),j.responseType="arraybuffer",j.onload=()=>{j.status==200||j.status==0&&j.response?w(j.response):A()},j.onerror=A,j.send(null)}));E&&typeof performance>"u"&&(global.performance=il().performance);var J=console.log.bind(console),oe=console.error.bind(console);E&&(J=(...m)=>F.writeSync(1,m.join(" ")+` `),oe=(...m)=>F.writeSync(2,m.join(" ")+` `));var le=l.print||J,ge=l.printErr||oe;Object.assign(l,$),$=null,l.thisProgram&&(_=l.thisProgram),l.quit&&(C=l.quit);var Z;l.wasmBinary&&(Z=l.wasmBinary);var fe=l.noExitRuntime||!0;typeof WebAssembly!="object"&&yt("no native wasm support detected");var we,ue,me,Ee=!1,ke,Ce,ve,Ae,_e,et;function ee(){var m=we.buffer;l.HEAP8=Ce=new Int8Array(m),l.HEAP16=new Int16Array(m),l.HEAP32=Ae=new Int32Array(m),l.HEAPU8=ve=new Uint8Array(m),l.HEAPU16=new Uint16Array(m),l.HEAPU32=_e=new Uint32Array(m),l.HEAPF32=new Float32Array(m),l.HEAPF64=et=new Float64Array(m)}var ce=l.INITIAL_MEMORY||16777216;if(5242880<=ce||yt("INITIAL_MEMORY should be larger than STACK_SIZE, was "+ce+"! (STACK_SIZE=5242880)"),O)we=l.wasmMemory;else if(l.wasmMemory)we=l.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 Re=[],rt=[],Qe=[],Ye=0;function Dt(){return fe||0{if(!w.ok)throw"failed to load wasm binary file at '"+m+"'";return w.arrayBuffer()}).catch(()=>wr(m));if(U)return new Promise((w,A)=>{U(m,j=>w(new Uint8Array(j)),A)})}return Promise.resolve().then(()=>wr(m))}function Kr(m,w,A){return _r(m).then(j=>WebAssembly.instantiate(j,w)).then(j=>j).then(A,j=>{ge("failed to asynchronously prepare wasm: "+j),yt(j)})}function Ai(m,w){var A=dt;return Z||typeof WebAssembly.instantiateStreaming!="function"||er(A)||A.startsWith("file://")||E||typeof fetch!="function"?Kr(A,m,w):fetch(A,{credentials:"same-origin"}).then(j=>WebAssembly.instantiateStreaming(j,m).then(w,function(H){return ge("wasm streaming compile failed: "+H),ge("falling back to ArrayBuffer instantiation"),Kr(A,m,w)}))}var Ke,tr={906828:m=>{l.Ea("Abs",m,void 0)},906879:m=>{l.Ea("Neg",m,void 0)},906930:m=>{l.Ea("Floor",m,void 0)},906983:m=>{l.Ea("Ceil",m,void 0)},907035:m=>{l.Ea("Reciprocal",m,void 0)},907093:m=>{l.Ea("Sqrt",m,void 0)},907145:m=>{l.Ea("Exp",m,void 0)},907196:m=>{l.Ea("Erf",m,void 0)},907247:m=>{l.Ea("Sigmoid",m,void 0)},907302:m=>{l.Ea("Log",m,void 0)},907353:m=>{l.Ea("Sin",m,void 0)},907404:m=>{l.Ea("Cos",m,void 0)},907455:m=>{l.Ea("Tan",m,void 0)},907506:m=>{l.Ea("Asin",m,void 0)},907558:m=>{l.Ea("Acos",m,void 0)},907610:m=>{l.Ea("Atan",m,void 0)},907662:m=>{l.Ea("Sinh",m,void 0)},907714:m=>{l.Ea("Cosh",m,void 0)},907766:m=>{l.Ea("Asinh",m,void 0)},907819:m=>{l.Ea("Acosh",m,void 0)},907872:m=>{l.Ea("Atanh",m,void 0)},907925:m=>{l.Ea("Tanh",m,void 0)},907977:m=>{l.Ea("Not",m,void 0)},908028:(m,w,A)=>{l.Ea("ClipV10",m,{min:w,max:A})},908100:m=>{l.Ea("Clip",m,void 0)},908152:(m,w)=>{l.Ea("Elu",m,{alpha:w})},908210:m=>{l.Ea("Relu",m,void 0)},908262:(m,w)=>{l.Ea("LeakyRelu",m,{alpha:w})},908326:(m,w)=>{l.Ea("ThresholdedRelu",m,{alpha:w})},908396:(m,w)=>{l.Ea("Cast",m,{to:w})},908454:m=>{l.Ea("Add",m,void 0)},908505:m=>{l.Ea("Sub",m,void 0)},908556:m=>{l.Ea("Mul",m,void 0)},908607:m=>{l.Ea("Div",m,void 0)},908658:m=>{l.Ea("Pow",m,void 0)},908709:m=>{l.Ea("Equal",m,void 0)},908762:m=>{l.Ea("Greater",m,void 0)},908817:m=>{l.Ea("GreaterOrEqual",m,void 0)},908879:m=>{l.Ea("Less",m,void 0)},908931:m=>{l.Ea("LessOrEqual",m,void 0)},908990:(m,w,A,j,H)=>{l.Ea("ReduceMean",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},909154:(m,w,A,j,H)=>{l.Ea("ReduceMax",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},909317:(m,w,A,j,H)=>{l.Ea("ReduceMin",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},909480:(m,w,A,j,H)=>{l.Ea("ReduceProd",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},909644:(m,w,A,j,H)=>{l.Ea("ReduceSum",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},909807:(m,w,A,j,H)=>{l.Ea("ReduceL1",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},909969:(m,w,A,j,H)=>{l.Ea("ReduceL2",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},910131:(m,w,A,j,H)=>{l.Ea("ReduceLogSum",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},910297:(m,w,A,j,H)=>{l.Ea("ReduceSumSquare",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},910466:(m,w,A,j,H)=>{l.Ea("ReduceLogSumExp",m,{keepDims:!!w,noopWithEmptyAxes:!!A,axes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},910635:m=>{l.Ea("Where",m,void 0)},910688:(m,w,A)=>{l.Ea("Transpose",m,{perm:w?Array.from(o().subarray(A>>>0,A+w>>>0)):[]})},910801:(m,w,A,j,H,X,re,ye,he,pe)=>{l.Ea("Conv",m,{format:he?"NHWC":"NCHW",auto_pad:w,dilations:[A],group:j,kernel_shape:[H],pads:[X,re],strides:[ye],w_is_const:()=>!!r()[pe>>>0]})},911029:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q,Ie)=>{l.Ea("Conv",m,{format:q?"NHWC":"NCHW",auto_pad:w,dilations:[A,j],group:H,kernel_shape:[X,re],pads:[ye,he,pe,be],strides:[De,Me],w_is_const:()=>!!r()[Ie>>>0]})},911288:(m,w,A,j,H,X,re,ye,he,pe)=>{l.Ea("Conv",m,{format:he?"NHWC":"NCHW",auto_pad:w,dilations:[A],group:j,kernel_shape:[H],pads:[X,re],strides:[ye],w_is_const:()=>!!r()[pe>>>0]})},911516:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q,Ie)=>{l.Ea("Conv",m,{format:q?"NHWC":"NCHW",auto_pad:w,dilations:[A,j],group:H,kernel_shape:[X,re],pads:[ye,he,pe,be],strides:[De,Me],w_is_const:()=>!!r()[Ie>>>0]})},911775:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q)=>{l.Ea("ConvTranspose",m,{format:he?"NHWC":"NCHW",autoPad:w,dilations:[A],group:j,kernel_shape:[H],pads:[X,re],strides:[ye],wIsConst:()=>!!r()[pe>>>0],outputPadding:be?Array.from(o().subarray(De>>>0,De+be>>>0)):[],outputShape:Me?Array.from(o().subarray(q>>>0,q+Me>>>0)):[]})},912155:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me)=>{l.Ea("ConvTranspose",m,{format:ye?"NHWC":"NCHW",autoPad:w,dilations:Array.from(o().subarray(A>>>0,A+2>>>0)),group:j,kernelShape:Array.from(o().subarray(H>>>0,H+2>>>0)),pads:Array.from(o().subarray(X>>>0,X+4>>>0)),strides:Array.from(o().subarray(re>>>0,re+2>>>0)),wIsConst:()=>!!r()[he>>>0],outputPadding:0>>0,be+pe>>>0)):[],outputShape:0>>0,Me+De>>>0)):[]})},912678:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q)=>{l.Ea("ConvTranspose",m,{format:he?"NHWC":"NCHW",autoPad:w,dilations:[A],group:j,kernel_shape:[H],pads:[X,re],strides:[ye],wIsConst:()=>!!r()[pe>>>0],outputPadding:be?Array.from(o().subarray(De>>>0,De+be>>>0)):[],outputShape:Me?Array.from(o().subarray(q>>>0,q+Me>>>0)):[]})},913058:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me)=>{l.Ea("ConvTranspose",m,{format:ye?"NHWC":"NCHW",autoPad:w,dilations:Array.from(o().subarray(A>>>0,A+2>>>0)),group:j,kernelShape:Array.from(o().subarray(H>>>0,H+2>>>0)),pads:Array.from(o().subarray(X>>>0,X+4>>>0)),strides:Array.from(o().subarray(re>>>0,re+2>>>0)),wIsConst:()=>!!r()[he>>>0],outputPadding:0>>0,be+pe>>>0)):[],outputShape:0>>0,Me+De>>>0)):[]})},913581:(m,w)=>{l.Ea("GlobalAveragePool",m,{format:w?"NHWC":"NCHW"})},913672:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q,Ie,Ue)=>{l.Ea("AveragePool",m,{format:Ue?"NHWC":"NCHW",auto_pad:w,ceil_mode:A,count_include_pad:j,storage_order:H,dilations:[X,re],kernel_shape:[ye,he],pads:[pe,be,De,Me],strides:[q,Ie]})},913956:(m,w)=>{l.Ea("GlobalAveragePool",m,{format:w?"NHWC":"NCHW"})},914047:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q,Ie,Ue)=>{l.Ea("AveragePool",m,{format:Ue?"NHWC":"NCHW",auto_pad:w,ceil_mode:A,count_include_pad:j,storage_order:H,dilations:[X,re],kernel_shape:[ye,he],pads:[pe,be,De,Me],strides:[q,Ie]})},914331:(m,w)=>{l.Ea("GlobalMaxPool",m,{format:w?"NHWC":"NCHW"})},914418:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q,Ie,Ue)=>{l.Ea("MaxPool",m,{format:Ue?"NHWC":"NCHW",auto_pad:w,ceil_mode:A,count_include_pad:j,storage_order:H,dilations:[X,re],kernel_shape:[ye,he],pads:[pe,be,De,Me],strides:[q,Ie]})},914698:(m,w)=>{l.Ea("GlobalMaxPool",m,{format:w?"NHWC":"NCHW"})},914785:(m,w,A,j,H,X,re,ye,he,pe,be,De,Me,q,Ie,Ue)=>{l.Ea("MaxPool",m,{format:Ue?"NHWC":"NCHW",auto_pad:w,ceil_mode:A,count_include_pad:j,storage_order:H,dilations:[X,re],kernel_shape:[ye,he],pads:[pe,be,De,Me],strides:[q,Ie]})},915065:(m,w,A,j,H)=>{l.Ea("Gemm",m,{alpha:w,beta:A,transA:j,transB:H})},915169:m=>{l.Ea("MatMul",m,void 0)},915223:(m,w,A,j)=>{l.Ea("ArgMax",m,{keepDims:!!w,selectLastIndex:!!A,axis:j})},915331:(m,w,A,j)=>{l.Ea("ArgMin",m,{keepDims:!!w,selectLastIndex:!!A,axis:j})},915439:(m,w)=>{l.Ea("Softmax",m,{axis:w})},915502:(m,w)=>{l.Ea("Concat",m,{axis:w})},915562:(m,w,A,j,H)=>{l.Ea("Split",m,{axis:w,numOutputs:A,splitSizes:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},915707:m=>{l.Ea("Expand",m,void 0)},915761:(m,w)=>{l.Ea("Gather",m,{axis:Number(w)})},915832:(m,w)=>{l.Ea("GatherElements",m,{axis:Number(w)})},915911:(m,w,A,j,H,X,re,ye,he,pe,be)=>{l.Ea("Resize",m,{antialias:w,axes:A?Array.from(o().subarray(j>>>0,j+A>>>0)):[],coordinateTransformMode:at(H),cubicCoeffA:X,excludeOutside:re,extrapolationValue:ye,keepAspectRatioPolicy:at(he),mode:at(pe),nearestMode:at(be)})},916262:(m,w,A,j,H,X,re)=>{l.Ea("Slice",m,{starts:w?Array.from(o().subarray(A>>>0,A+w>>>0)):[],ends:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[],axes:X?Array.from(o().subarray(re>>>0,re+X>>>0)):[]})},916493:m=>{l.Ea("Tile",m,void 0)},916545:(m,w,A)=>{l.Ea("LayerNormalization",m,{axis:Number(w),epsilon:Number(A)})},916652:(m,w,A)=>{l.Ea("InstanceNormalization",m,{epsilon:w,format:A?"NHWC":"NCHW"})},916766:(m,w,A)=>{l.Ea("InstanceNormalization",m,{epsilon:w,format:A?"NHWC":"NCHW"})},916880:m=>{l.Ea("Range",m,void 0)},916933:(m,w)=>{l.Ea("Einsum",m,{equation:at(w)})},917014:(m,w,A,j,H)=>{l.Ea("Pad",m,{mode:w,value:A,pads:j?Array.from(o().subarray(H>>>0,H+j>>>0)):[]})},917146:m=>{l.Ea("Gelu",m,void 0)},917198:m=>{l.Ea("BiasAdd",m,void 0)},917253:m=>{l.Ea("BiasSplitGelu",m,void 0)},917314:(m,w)=>{l.Ea("SkipLayerNormalization",m,{epsilon:w})},917395:m=>{l.zb(m)},917429:(m,w)=>l.Ab(m,w,l.bb.Fb,l.bb.errors),917541:m=>l.wb(m),917574:m=>l.yb(m),917606:(m,w,A)=>{l.jb(m,w,A,!0)},917645:(m,w,A)=>{l.jb(m,w,A)}};function xt(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}function $r(m){m.terminate(),m.onmessage=()=>{}}function vt(m){(m=xe.Qa[m])||yt(),xe.Eb(m)}function Cr(m){var w=xe.tb();if(!w)return 6;xe.Ya.push(w),xe.Qa[m.Xa]=w,w.Xa=m.Xa;var A={cmd:"run",start_routine:m.Gb,arg:m.rb,pthread_ptr:m.Xa};return E&&w.unref(),w.postMessage(A,m.Mb),0}var xr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ei=(m,w,A)=>{w>>>=0;var j=w+A;for(A=w;m[A]&&!(A>=j);)++A;if(16H?j+=String.fromCharCode(H):(H-=65536,j+=String.fromCharCode(55296|H>>10,56320|H&1023))}}else j+=String.fromCharCode(H)}return j},at=(m,w)=>(m>>>=0)?Ei(s(),m,w):"";function ki(m){if(O)return He(1,1,m);ke=m,Dt()||(xe.Hb(),l.onExit&&l.onExit(m),Ee=!0),C(m,new xt(m))}var bt=m=>{if(ke=m,O)throw St(m),"unwind";ki(m)},xe={ab:[],Ya:[],mb:[],Qa:{},gb:function(){O?xe.vb():xe.ub()},ub:function(){Re.unshift(()=>{Ft(),xe.Bb(()=>qt())})},vb:function(){xe.receiveObjectTransfer=xe.Db,xe.threadInitTLS=xe.lb,xe.setExitStatus=xe.kb,fe=!1},kb:function(m){ke=m},Sb:["$terminateWorker"],Hb:function(){for(var m of xe.Ya)$r(m);for(m of xe.ab)$r(m);xe.ab=[],xe.Ya=[],xe.Qa=[]},Eb:function(m){var w=m.Xa;delete xe.Qa[w],xe.ab.push(m),xe.Ya.splice(xe.Ya.indexOf(m),1),m.Xa=0,Dr(w)},Db:function(){},lb:function(){xe.mb.forEach(m=>m())},Cb:m=>new Promise(w=>{m.onmessage=X=>{X=X.data;var re=X.cmd;if(X.targetThread&&X.targetThread!=ur()){var ye=xe.Qa[X.Rb];ye?ye.postMessage(X,X.transferList):ge('Internal error! Worker sent a message "'+re+'" to target pthread '+X.targetThread+", but that thread no longer exists!")}else re==="checkMailbox"?nr():re==="spawnThread"?Cr(X):re==="cleanupThread"?vt(X.thread):re==="killThread"?(X=X.thread,re=xe.Qa[X],delete xe.Qa[X],$r(re),Dr(X),xe.Ya.splice(xe.Ya.indexOf(re),1),re.Xa=0):re==="cancelThread"?xe.Qa[X.thread].postMessage({cmd:"cancel"}):re==="loaded"?(m.loaded=!0,w(m)):re==="alert"?alert("Thread "+X.threadId+": "+X.text):X.target==="setimmediate"?m.postMessage(X):re==="callHandler"?l[X.handler](...X.args):re&&ge("worker sent an unknown command "+re)},m.onerror=X=>{throw ge("worker sent an error! "+X.filename+":"+X.lineno+": "+X.message),X},E&&(m.on("message",function(X){m.onmessage({data:X})}),m.on("error",function(X){m.onerror(X)}));var A=[],j=["onExit","onAbort","print","printErr"],H;for(H of j)l.hasOwnProperty(H)&&A.push(H);m.postMessage({cmd:"load",handlers:A,urlOrBlob:l.mainScriptUrlOrBlob||e,wasmMemory:we,wasmModule:me})}),Bb:function(m){m()},qb:function(){var m=z("ort-wasm-simd-threaded.worker.js");m=new Worker(m),xe.ab.push(m)},tb:function(){return xe.ab.length==0&&(xe.qb(),xe.Cb(xe.ab[0])),xe.ab.pop()}};l.PThread=xe;var Kt=m=>{for(;0>2>>>0];m=o()[m+56>>2>>>0],ci(w,w-m),lr(w)};function St(m){if(O)return He(2,0,m);bt(m)}l.invokeEntryPoint=function(m,w){m=pi.apply(null,[m,w]),Dt()?xe.kb(m):Mr(m)};function Yr(m){this.fb=m-24,this.pb=function(w){c()[this.fb+4>>2>>>0]=w},this.ob=function(w){c()[this.fb+8>>2>>>0]=w},this.gb=function(w,A){this.nb(),this.pb(w),this.ob(A)},this.nb=function(){c()[this.fb+16>>2>>>0]=0}}var ot=0,wt=0;function Sr(m,w,A,j){return O?He(3,1,m,w,A,j):Oi(m,w,A,j)}function Oi(m,w,A,j){if(m>>>=0,w>>>=0,A>>>=0,j>>>=0,typeof SharedArrayBuffer>"u")return ge("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var H=[];return O&&H.length===0?Sr(m,w,A,j):(m={Gb:A,Xa:m,rb:j,Mb:H},O?(m.Ob="spawnThread",postMessage(m,H),0):Cr(m))}function Pi(m,w,A){return O?He(4,1,m,w,A):0}function Qr(m,w){if(O)return He(5,1,m,w)}var Xr=m=>{for(var w=0,A=0;A=j?w++:2047>=j?w+=2:55296<=j&&57343>=j?(w+=4,++A):w+=3}return w},zi=(m,w,A,j)=>{if(A>>>=0,!(0=re){var ye=m.charCodeAt(++X);re=65536+((re&1023)<<10)|ye&1023}if(127>=re){if(A>=j)break;w[A++>>>0]=re}else{if(2047>=re){if(A+1>=j)break;w[A++>>>0]=192|re>>6}else{if(65535>=re){if(A+2>=j)break;w[A++>>>0]=224|re>>12}else{if(A+3>=j)break;w[A++>>>0]=240|re>>18,w[A++>>>0]=128|re>>12&63}w[A++>>>0]=128|re>>6&63}w[A++>>>0]=128|re&63}}return w[A>>>0]=0,A-H},Ri=(m,w,A)=>zi(m,s(),w,A);function ji(m,w){if(O)return He(6,1,m,w)}function Bi(m,w,A){if(O)return He(7,1,m,w,A)}function Di(m,w,A){return O?He(8,1,m,w,A):0}function Ir(m,w){if(O)return He(9,1,m,w)}function Zr(m,w,A){if(O)return He(10,1,m,w,A)}function rr(m,w,A,j){if(O)return He(11,1,m,w,A,j)}function Mi(m,w,A,j){if(O)return He(12,1,m,w,A,j)}function Ui(m,w,A,j){if(O)return He(13,1,m,w,A,j)}function kt(m){if(O)return He(14,1,m)}function _t(m,w){if(O)return He(15,1,m,w)}function Jr(m,w,A){if(O)return He(16,1,m,w,A)}var ir=m=>{if(!Ee)try{if(m(),!Dt())try{O?Mr(ke):bt(ke)}catch(w){w instanceof xt||w=="unwind"||C(1,w)}}catch(w){w instanceof xt||w=="unwind"||C(1,w)}};function Tr(m){m>>>=0,typeof Atomics.Nb=="function"&&(Atomics.Nb(o(),m>>2,m).value.then(nr),m+=128,Atomics.store(o(),m>>2,1))}l.__emscripten_thread_mailbox_await=Tr;function nr(){var m=ur();m&&(Tr(m),ir(()=>li()))}l.checkMailbox=nr;var Yt=m=>m%4===0&&(m%100!==0||m%400===0),Ar=[0,31,60,91,121,152,182,213,244,274,305,335],Wi=[0,31,59,90,120,151,181,212,243,273,304,334];function Ni(m,w,A,j,H,X,re,ye){return O?He(17,1,m,w,A,j,H,X,re,ye):-52}function Vi(m,w,A,j,H,X,re){if(O)return He(18,1,m,w,A,j,H,X,re)}var Gi=m=>{var w=Xr(m)+1,A=Br(w);return A&&Ri(m,A,w),A},Er=[],ar=(m,w)=>{Er.length=0;var A;for(w>>=2;A=s()[m++>>>0];)w+=A!=105&w,Er.push(A==105?o()[w>>>0]:p()[w++>>>1]),++w;return Er},Fn=m=>{var w=Ur();return m=m(),lr(w),m};function He(m,w){var A=arguments.length-2,j=arguments;return Fn(()=>{for(var H=Wr(8*A),X=H>>3,re=0;re>>0]=ye}return ui(m,A,H,w)})}var kr=[],ei={},Hi=()=>{if(!Or){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"},w;for(w in ei)ei[w]===void 0?delete m[w]:m[w]=ei[w];var A=[];for(w in m)A.push(`${w}=${m[w]}`);Or=A}return Or},Or;function Li(m,w){if(O)return He(19,1,m,w);m>>>=0,w>>>=0;var A=0;return Hi().forEach(function(j,H){var X=w+A;for(H=c()[m+4*H>>2>>>0]=X,X=0;X>0>>>0]=j.charCodeAt(X);r()[H>>0>>>0]=0,A+=j.length+1}),0}function Lt(m,w){if(O)return He(20,1,m,w);m>>>=0,w>>>=0;var A=Hi();c()[m>>2>>>0]=A.length;var j=0;return A.forEach(function(H){j+=H.length+1}),c()[w>>2>>>0]=j,0}function ti(m){return O?He(21,1,m):52}function ri(m,w,A,j){return O?He(22,1,m,w,A,j):52}function Pr(m,w,A,j,H){return O?He(23,1,m,w,A,j,H):70}var Fi=[null,[],[]];function zr(m,w,A,j){if(O)return He(24,1,m,w,A,j);w>>>=0,A>>>=0,j>>>=0;for(var H=0,X=0;X>2>>>0],ye=c()[w+4>>2>>>0];w+=8;for(var he=0;he>>0],be=Fi[m];pe===0||pe===10?((m===1?le:ge)(Ei(be,0)),be.length=0):be.push(pe)}H+=ye}return c()[j>>2>>>0]=H,0}var ii=[31,29,31,30,31,30,31,31,30,31,30,31],Rr=[31,28,31,30,31,30,31,31,30,31,30,31];function qn(m){var w=Array(Xr(m)+1);return zi(m,w,0,w.length),w}var qi=(m,w)=>{r().set(m,w>>>0)};function ni(m,w,A,j){function H(q,Ie,Ue){for(q=typeof q=="number"?q.toString():q||"";q.lengthvi?-1:0Mt-q.getDate())Ie-=Mt-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,w>>>=0,A>>>=0,j>>>=0;var pe=o()[j+40>>2>>>0];j={Kb:o()[j>>2>>>0],Jb:o()[j+4>>2>>>0],cb:o()[j+8>>2>>>0],ib:o()[j+12>>2>>>0],eb:o()[j+16>>2>>>0],$a:o()[j+20>>2>>>0],Wa:o()[j+24>>2>>>0],Za:o()[j+28>>2>>>0],Tb:o()[j+32>>2>>>0],Ib:o()[j+36>>2>>>0],Lb:pe?at(pe):""},A=at(A),pe={"%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 be in pe)A=A.replace(new RegExp(be,"g"),pe[be]);var De="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Me="January February March April May June July August September October November December".split(" ");pe={"%a":q=>De[q.Wa].substring(0,3),"%A":q=>De[q.Wa],"%b":q=>Me[q.eb].substring(0,3),"%B":q=>Me[q.eb],"%C":q=>X((q.$a+1900)/100|0,2),"%d":q=>X(q.ib,2),"%e":q=>H(q.ib,2," "),"%g":q=>he(q).toString().substring(2),"%G":q=>he(q),"%H":q=>X(q.cb,2),"%I":q=>(q=q.cb,q==0?q=12:12{for(var Ie=0,Ue=0;Ue<=q.eb-1;Ie+=(Yt(q.$a+1900)?ii:Rr)[Ue++]);return X(q.ib+Ie,3)},"%m":q=>X(q.eb+1,2),"%M":q=>X(q.Jb,2),"%n":()=>` `,"%p":q=>0<=q.cb&&12>q.cb?"AM":"PM","%S":q=>X(q.Kb,2),"%t":()=>" ","%u":q=>q.Wa||7,"%U":q=>X(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&&Yt(q.$a)||(Ie=1));else{Ie=52;var Ue=(q.Wa+7-q.Za-1)%7;(Ue==4||Ue==5&&Yt(q.$a%400-1))&&Ie++}return X(Ie,2)},"%w":q=>q.Wa,"%W":q=>X(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,"%%":()=>"%"},A=A.replace(/%%/g,"\0\0");for(be in pe)A.includes(be)&&(A=A.replace(new RegExp(be,"g"),pe[be](j)));return A=A.replace(/\0\0/g,"%"),be=qn(A),be.length>w?0:(qi(be,m),be.length-1)}function jr(m){try{m()}catch(w){yt(w)}}function Ki(m){var w={},A;for(A in m)(function(j){var H=m[j];w[j]=typeof H=="function"?function(){D.push(j);try{return H.apply(null,arguments)}finally{Ee||(D.pop()===j||yt(),ct&&Ot===1&&D.length===0&&(Ot=0,Ye+=1,jr(mi),typeof Fibers<"u"&&Fibers.Ub()))}}:H})(A);return w}var Ot=0,ct=null,Yi=0,D=[],ai={},or={},It=0,N=null,sr=[];function V(){return new Promise((m,w)=>{N={resolve:m,reject:w}})}function Qi(){var m=Br(65548),w=m+12;c()[m>>2>>>0]=w,c()[m+4>>2>>>0]=w+65536,w=D[0];var A=ai[w];return A===void 0&&(A=It++,ai[w]=A,or[A]=w),w=A,o()[m+8>>2>>>0]=w,m}function G(){var m=o()[ct+8>>2>>>0];return m=ue[or[m]],--Ye,m()}function Xi(m){if(!Ee){if(Ot===0){var w=!1,A=!1;m((j=0)=>{if(!Ee&&(Yi=j,w=!0,A)){Ot=2,jr(()=>hi(ct)),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.resume(),j=!1;try{var H=G()}catch(ye){H=ye,j=!0}var X=!1;if(!ct){var re=N;re&&(N=null,(j?re.reject:re.resolve)(H),X=!0)}if(j&&!X)throw H}}),A=!0,w||(Ot=1,ct=Qi(),typeof Browser<"u"&&Browser.hb.sb&&Browser.hb.pause(),jr(()=>fi(ct)))}else Ot===2?(Ot=0,jr(gi),oi(ct),ct=null,sr.forEach(j=>ir(j))):yt(`invalid state: ${Ot}`);return Yi}}function Zi(m){return Xi(w=>{m().then(w)})}xe.gb();var Ji=[null,ki,St,Sr,Pi,Qr,ji,Bi,Di,Ir,Zr,rr,Mi,Ui,kt,_t,Jr,Ni,Vi,Li,Lt,ti,ri,Pr,zr],en={r:function(m,w,A){return Zi(async()=>{await l.xb(m,w,A)})},b:function(m,w,A){throw m>>>=0,new Yr(m).gb(w>>>0,A>>>0),ot=m,wt++,ot},O:function(m){si(m>>>0,!S,1,!T,131072,!1),xe.lb()},l:function(m){m>>>=0,O?postMessage({cmd:"cleanupThread",thread:m}):vt(m)},I:Oi,i:Pi,U:Qr,E:ji,G:Bi,V:Di,S:Ir,K:Zr,R:rr,p:Mi,F:Ui,C:kt,T:_t,D:Jr,q:()=>!0,A:function(m,w){m>>>=0,m==w>>>0?setTimeout(()=>nr()):O?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=xe.Qa[m])&&m.postMessage({cmd:"checkMailbox"})},M:function(){return-1},N:Tr,X:function(m){E&&xe.Qa[m>>>0].ref()},u:function(m,w,A){m=w+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*w:NaN,A>>>=0,m=new Date(1e3*m),o()[A>>2>>>0]=m.getUTCSeconds(),o()[A+4>>2>>>0]=m.getUTCMinutes(),o()[A+8>>2>>>0]=m.getUTCHours(),o()[A+12>>2>>>0]=m.getUTCDate(),o()[A+16>>2>>>0]=m.getUTCMonth(),o()[A+20>>2>>>0]=m.getUTCFullYear()-1900,o()[A+24>>2>>>0]=m.getUTCDay(),m=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[A+28>>2>>>0]=m},v:function(m,w,A){m=w+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*w:NaN,A>>>=0,m=new Date(1e3*m),o()[A>>2>>>0]=m.getSeconds(),o()[A+4>>2>>>0]=m.getMinutes(),o()[A+8>>2>>>0]=m.getHours(),o()[A+12>>2>>>0]=m.getDate(),o()[A+16>>2>>>0]=m.getMonth(),o()[A+20>>2>>>0]=m.getFullYear()-1900,o()[A+24>>2>>>0]=m.getDay(),w=(Yt(m.getFullYear())?Ar:Wi)[m.getMonth()]+m.getDate()-1|0,o()[A+28>>2>>>0]=w,o()[A+36>>2>>>0]=-(60*m.getTimezoneOffset()),w=new Date(m.getFullYear(),6,1).getTimezoneOffset();var j=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=(w!=j&&m.getTimezoneOffset()==Math.min(j,w))|0,o()[A+32>>2>>>0]=m},w:function(m){m>>>=0;var w=new Date(o()[m+20>>2>>>0]+1900,o()[m+16>>2>>>0],o()[m+12>>2>>>0],o()[m+8>>2>>>0],o()[m+4>>2>>>0],o()[m>>2>>>0],0),A=o()[m+32>>2>>>0],j=w.getTimezoneOffset(),H=new Date(w.getFullYear(),6,1).getTimezoneOffset(),X=new Date(w.getFullYear(),0,1).getTimezoneOffset(),re=Math.min(X,H);return 0>A?o()[m+32>>2>>>0]=+(H!=X&&re==j):0>2>>>0]=w.getDay(),A=(Yt(w.getFullYear())?Ar:Wi)[w.getMonth()]+w.getDate()-1|0,o()[m+28>>2>>>0]=A,o()[m>>2>>>0]=w.getSeconds(),o()[m+4>>2>>>0]=w.getMinutes(),o()[m+8>>2>>>0]=w.getHours(),o()[m+12>>2>>>0]=w.getDate(),o()[m+16>>2>>>0]=w.getMonth(),o()[m+20>>2>>>0]=w.getYear(),m=w.getTime()/1e3,di((Ke=m,1<=+Math.abs(Ke)?0>>0:~~+Math.ceil((Ke-+(~~Ke>>>0))/4294967296)>>>0:0)),m>>>0},s:Ni,t:Vi,z:function(m,w,A){function j(pe){return(pe=pe.toTimeString().match(/\(([A-Za-z ]+)\)$/))?pe[1]:"GMT"}m>>>=0,w>>>=0,A>>>=0;var H=new Date().getFullYear(),X=new Date(H,0,1),re=new Date(H,6,1);H=X.getTimezoneOffset();var ye=re.getTimezoneOffset(),he=Math.max(H,ye);c()[m>>2>>>0]=60*he,o()[w>>2>>>0]=+(H!=ye),m=j(X),w=j(re),m=Gi(m),w=Gi(w),ye>2>>>0]=m,c()[A+4>>2>>>0]=w):(c()[A>>2>>>0]=w,c()[A+4>>2>>>0]=m)},d:()=>{yt("")},c:function(m,w,A){return m>>>=0,w=ar(w>>>0,A>>>0),tr[m].apply(null,w)},k:function(m,w,A){return m>>>=0,w=ar(w>>>0,A>>>0),tr[m].apply(null,w)},m:function(){},j:function(){return Date.now()},W:()=>{throw Ye+=1,"unwind"},B:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:function(){return E?(al(),Qt(nl)).cpus().length:navigator.hardwareConcurrency},L:function(m,w,A,j){for(xe.Pb=w>>>0,kr.length=A,w=j>>>0>>3,j=0;j>>0];return(0>m?tr[-m-1]:Ji[m]).apply(null,kr)},y:function(m){m>>>=0;var w=s().length;if(m<=w||4294901760=A;A*=2){var j=w*(1+.2/A);j=Math.min(j,m+100663296);var H=Math;j=Math.max(m,j);e:{H=H.min.call(H,4294901760,j+(65536-j%65536)%65536)-we.buffer.byteLength+65535>>>16;try{we.grow(H),ee();var X=1;break e}catch{}X=void 0}if(X)return!0}return!1},P:Li,Q:Lt,H:bt,h:ti,o:ri,x:Pr,n:zr,a:we||l.wasmMemory,J:ni,e:function(m,w,A,j){return ni(m>>>0,w>>>0,A>>>0,j>>>0)}};(function(){function m(A,j){return A=A.exports,A=Ki(A),ue=A=tn(A),xe.mb.push(ue.Da),rt.unshift(ue.Y),me=j,qt(),A}var w={a:en};if(Ft(),l.instantiateWasm)try{return l.instantiateWasm(w,m)}catch(A){ge("Module.instantiateWasm callback failed with error: "+A),y(A)}return Ai(w,function(A){m(A.instance,A.module)}).catch(y),{}})(),l._OrtInit=(m,w)=>(l._OrtInit=ue.Z)(m,w),l._OrtGetLastError=(m,w)=>(l._OrtGetLastError=ue._)(m,w),l._OrtCreateSessionOptions=(m,w,A,j,H,X,re,ye,he,pe)=>(l._OrtCreateSessionOptions=ue.$)(m,w,A,j,H,X,re,ye,he,pe),l._OrtAppendExecutionProvider=(m,w)=>(l._OrtAppendExecutionProvider=ue.aa)(m,w),l._OrtAddFreeDimensionOverride=(m,w,A)=>(l._OrtAddFreeDimensionOverride=ue.ba)(m,w,A),l._OrtAddSessionConfigEntry=(m,w,A)=>(l._OrtAddSessionConfigEntry=ue.ca)(m,w,A),l._OrtReleaseSessionOptions=m=>(l._OrtReleaseSessionOptions=ue.da)(m),l._OrtCreateSession=(m,w,A)=>(l._OrtCreateSession=ue.ea)(m,w,A),l._OrtReleaseSession=m=>(l._OrtReleaseSession=ue.fa)(m),l._OrtGetInputOutputCount=(m,w,A)=>(l._OrtGetInputOutputCount=ue.ga)(m,w,A),l._OrtGetInputName=(m,w)=>(l._OrtGetInputName=ue.ha)(m,w),l._OrtGetOutputName=(m,w)=>(l._OrtGetOutputName=ue.ia)(m,w),l._OrtFree=m=>(l._OrtFree=ue.ja)(m),l._OrtCreateTensor=(m,w,A,j,H,X)=>(l._OrtCreateTensor=ue.ka)(m,w,A,j,H,X),l._OrtGetTensorData=(m,w,A,j,H)=>(l._OrtGetTensorData=ue.la)(m,w,A,j,H),l._OrtReleaseTensor=m=>(l._OrtReleaseTensor=ue.ma)(m),l._OrtCreateRunOptions=(m,w,A,j)=>(l._OrtCreateRunOptions=ue.na)(m,w,A,j),l._OrtAddRunConfigEntry=(m,w,A)=>(l._OrtAddRunConfigEntry=ue.oa)(m,w,A),l._OrtReleaseRunOptions=m=>(l._OrtReleaseRunOptions=ue.pa)(m),l._OrtCreateBinding=m=>(l._OrtCreateBinding=ue.qa)(m),l._OrtBindInput=(m,w,A)=>(l._OrtBindInput=ue.ra)(m,w,A),l._OrtBindOutput=(m,w,A,j)=>(l._OrtBindOutput=ue.sa)(m,w,A,j),l._OrtClearBoundOutputs=m=>(l._OrtClearBoundOutputs=ue.ta)(m),l._OrtReleaseBinding=m=>(l._OrtReleaseBinding=ue.ua)(m),l._OrtRunWithBinding=(m,w,A,j,H)=>(l._OrtRunWithBinding=ue.va)(m,w,A,j,H),l._OrtRun=(m,w,A,j,H,X,re,ye)=>(l._OrtRun=ue.wa)(m,w,A,j,H,X,re,ye),l._OrtEndProfiling=m=>(l._OrtEndProfiling=ue.xa)(m),l._JsepOutput=(m,w,A)=>(l._JsepOutput=ue.ya)(m,w,A),l._JsepGetNodeName=m=>(l._JsepGetNodeName=ue.za)(m);var ur=l._pthread_self=()=>(ur=l._pthread_self=ue.Aa)(),Br=l._malloc=m=>(Br=l._malloc=ue.Ba)(m),oi=l._free=m=>(oi=l._free=ue.Ca)(m);l.__emscripten_tls_init=()=>(l.__emscripten_tls_init=ue.Da)();var si=l.__emscripten_thread_init=(m,w,A,j,H,X)=>(si=l.__emscripten_thread_init=ue.Fa)(m,w,A,j,H,X);l.__emscripten_thread_crashed=()=>(l.__emscripten_thread_crashed=ue.Ga)();var ui=(m,w,A,j)=>(ui=ue.Ha)(m,w,A,j),Dr=m=>(Dr=ue.Ia)(m),Mr=l.__emscripten_thread_exit=m=>(Mr=l.__emscripten_thread_exit=ue.Ja)(m),li=l.__emscripten_check_mailbox=()=>(li=l.__emscripten_check_mailbox=ue.Ka)(),di=m=>(di=ue.La)(m),ci=(m,w)=>(ci=ue.Ma)(m,w),Ur=()=>(Ur=ue.Na)(),lr=m=>(lr=ue.Oa)(m),Wr=m=>(Wr=ue.Pa)(m),pi=l.dynCall_ii=(m,w)=>(pi=l.dynCall_ii=ue.Ra)(m,w),fi=m=>(fi=ue.Sa)(m),mi=()=>(mi=ue.Ta)(),hi=m=>(hi=ue.Ua)(m),gi=()=>(gi=ue.Va)();l.___start_em_js=917678,l.___stop_em_js=917839;function tn(m){m=Object.assign({},m);var w=j=>()=>j()>>>0,A=j=>H=>j(H)>>>0;return m.__errno_location=w(m.__errno_location),m.pthread_self=w(m.pthread_self),m.malloc=A(m.malloc),m.stackSave=w(m.stackSave),m.stackAlloc=A(m.stackAlloc),m}l.keepRuntimeAlive=Dt,l.wasmMemory=we,l.stackAlloc=Wr,l.stackSave=Ur,l.stackRestore=lr,l.UTF8ToString=at,l.stringToUTF8=Ri,l.lengthBytesUTF8=Xr,l.ExitStatus=xt,l.PThread=xe;var dr;mt=function m(){dr||yi(),dr||(mt=m)};function yi(){function m(){if(!dr&&(dr=!0,l.calledRun=!0,!Ee)&&(O||Kt(rt),h(l),l.onRuntimeInitialized&&l.onRuntimeInitialized(),!O)){if(l.postRun)for(typeof l.postRun=="function"&&(l.postRun=[l.postRun]);l.postRun.length;){var w=l.postRun.shift();Qe.unshift(w)}Kt(Qe)}}if(!(0ol)});var ll=Nr((Nb,Gg)=>{Gg.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 cl,Hg,sa,ua,mn,dl,Lg,Fg,qg,pl,Ze,Gr=ie(()=>{"use strict";cl=tl();Hg=ul(),ua=!1,mn=!1,dl=!1,Lg=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}},Fg=()=>{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}},qg=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",pl=async e=>{if(ua)return Promise.resolve();if(mn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(dl)throw new Error("previous call to 'initializeWebAssembly()' failed.");mn=!0;let t=e.initTimeout,r=e.numThreads,s=e.simd,o=Lg(r),c=s&&Fg(),p=e.wasmPaths,l=typeof p=="string"?p:void 0,h=qg(c,o),y=typeof p=="object"?p[h]:void 0,$=!1,_=[];if(t>0&&_.push(new Promise(C=>{setTimeout(()=>{$=!0,C()},t)})),_.push(new Promise((C,T)=>{let S=o?Hg:cl,E={locateFile:(O,R)=>{if(o&&O.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([ll()],{type:"text/javascript"}));if(O.endsWith(".wasm")){if(y)return y;let z=l??R;return h==="ort-wasm-simd.wasm"?z+"ort-wasm-simd.jsep.wasm":h==="ort-wasm-simd-threaded.wasm"?z+"ort-wasm-simd-threaded.jsep.wasm":z+h}return R+O}};if(o)if(E.numThreads=r,typeof Blob>"u")E.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let O=`var ortWasmThreaded=${S.toString()};`;E.mainScriptUrlOrBlob=new Blob([O],{type:"text/javascript"})}S(E).then(O=>{mn=!1,ua=!0,sa=O,C()},O=>{mn=!1,dl=!0,T(O)})})),await Promise.race(_),$)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ze=()=>{if(ua&&sa)return sa;throw new Error("WebAssembly is not initialized yet.")}});var Je,wi,Fe,hn=ie(()=>{"use strict";Gr();Je=(e,t)=>{let r=Ze(),s=r.lengthBytesUTF8(e)+1,o=r._malloc(s);return r.stringToUTF8(e,o,s),t.push(o),o},wi=(e,t,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([o,c])=>{let p=t?t+o:o;if(typeof c=="object")wi(c,p+".",r,s);else if(typeof c=="string"||typeof c=="number")s(p,c.toString());else if(typeof c=="boolean")s(p,c?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof c}`)})},Fe=e=>{let t=Ze(),r=t.stackSave();try{let s=t.stackAlloc(8);t._OrtGetLastError(s,s+4);let o=t.HEAP32[s/4],c=t.HEAPU32[s/4+1],p=c?t.UTF8ToString(c):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${p}`)}finally{t.stackRestore(r)}}});var fl,ml=ie(()=>{"use strict";Gr();hn();fl=e=>{let t=Ze(),r=0,s=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.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)o.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&&(o.terminate=!1);let c=0;return e?.tag!==void 0&&(c=Je(e.tag,s)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,c),r===0&&Fe("Can't create run options."),e?.extra!==void 0&&wi(e.extra,"",new WeakSet,(p,l)=>{let h=Je(p,s),y=Je(l,s);t._OrtAddRunConfigEntry(r,h,y)!==0&&Fe(`Can't set a run config entry: ${p} - ${l}.`)}),[r,s]}catch(c){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(p=>t._free(p)),c}}});var Kg,Yg,Qg,Xg,hl,gl=ie(()=>{"use strict";Gr();hn();Kg=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}`)}},Yg=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Qg=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Xg=(e,t,r)=>{for(let s of t){let o=typeof s=="string"?s:s.name;switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s;if(p?.deviceType){let l=Je("deviceType",r),h=Je(p.deviceType,r);Ze()._OrtAddSessionConfigEntry(e,l,h)!==0&&Fe(`Can't set a session config entry: 'deviceType' - ${p.deviceType}.`)}if(p?.numThreads){let l=p.numThreads;(typeof l!="number"||!Number.isInteger(l)||l<0)&&(l=0);let h=Je("numThreads",r),y=Je(l.toString(),r);Ze()._OrtAddSessionConfigEntry(e,h,y)!==0&&Fe(`Can't set a session config entry: 'numThreads' - ${p.numThreads}.`)}if(p?.powerPreference){let l=Je("powerPreference",r),h=Je(p.powerPreference,r);Ze()._OrtAddSessionConfigEntry(e,l,h)!==0&&Fe(`Can't set a session config entry: 'powerPreference' - ${p.powerPreference}.`)}}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p?.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);let l=Je("preferredLayout",r),h=Je(p.preferredLayout,r);Ze()._OrtAddSessionConfigEntry(e,l,h)!==0&&Fe(`Can't set a session config entry: 'preferredLayout' - ${p.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let c=Je(o,r);Ze()._OrtAppendExecutionProvider(e,c)!==0&&Fe(`Can't append execution provider: ${o}.`)}},hl=e=>{let t=Ze(),r=0,s=[],o=e||{};Qg(o);try{let c=Kg(o.graphOptimizationLevel??"all"),p=Yg(o.executionMode??"sequential"),l=typeof o.logId=="string"?Je(o.logId,s):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log serverity level is not valid: ${h}`);let y=o.logVerbosityLevel??0;if(!Number.isInteger(y)||y<0||y>4)throw new Error(`log verbosity level is not valid: ${y}`);let $=typeof o.optimizedModelFilePath=="string"?Je(o.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(c,!!o.enableCpuMemArena,!!o.enableMemPattern,p,!!o.enableProfiling,0,l,h,y,$),r===0&&Fe("Can't create session options."),o.executionProviders&&Xg(r,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let _=Je("enableGraphCapture",s),C=Je(o.enableGraphCapture.toString(),s);t._OrtAddSessionConfigEntry(r,_,C)!==0&&Fe(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[_,C]of Object.entries(o.freeDimensionOverrides)){if(typeof _!="string")throw new Error(`free dimension override name must be a string: ${_}`);if(typeof C!="number"||!Number.isInteger(C)||C<0)throw new Error(`free dimension override value must be a non-negative integer: ${C}`);let T=Je(_,s);t._OrtAddFreeDimensionOverride(r,T,C)!==0&&Fe(`Can't set a free dimension override: ${_} - ${C}.`)}return o.extra!==void 0&&wi(o.extra,"",new WeakSet,(_,C)=>{let T=Je(_,s),S=Je(C,s);t._OrtAddSessionConfigEntry(r,T,S)!==0&&Fe(`Can't set a session config entry: ${_} - ${C}.`)}),[r,s]}catch(c){throw r!==0&&t._OrtReleaseSessionOptions(r),s.forEach(p=>t._free(p)),c}}});var la,Xt,mr,gn,_i,yn,da,Te=ie(()=>{"use strict";la=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}`)}},Xt=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}`)}},mr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],gn=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}`)}},_i=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}`)}},yn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",da=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 $i,ca=ie(()=>{"use strict";$i=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(e),s=[];for await(let o of r)s.push(o);return new Uint8Array(Buffer.concat(s))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),c;try{c=new ArrayBuffer(s)}catch(l){if(l instanceof RangeError){let h=Math.ceil(s/65536);c=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw l}let p=0;for(;;){let{done:l,value:h}=await o.read();if(l)break;let y=h.byteLength;new Uint8Array(c,p,y).set(h),p+=y}return new Uint8Array(c,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var Zg,Jg,yl,vl,bl,ey,qe,Zt=ie(()=>{"use strict";Te();Zg=["V","I","W","E","F"],Jg=(e,t)=>{console.log(`[${Zg[e]},${new Date().toISOString()}]${t}`)},bl=(e,t)=>{yl=e,vl=t},ey=(e,t)=>{let r=_i(e),s=_i(yl);r>=s&&Jg(r,typeof t=="function"?t():t)},qe=(...e)=>{vl&&ey(...e)}});var wl,_l=ie(()=>{"use strict";Te();wl=(e,t)=>new(gn(t))(e)});var vn=ie(()=>{"use strict"});var $l,pa,fa,ty,ry,Cl,ha,ma,Sl,Il=ie(()=>{"use strict";Zt();vn();$l=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]]),pa=[],fa=e=>Math.ceil(e/16)*16,ty=e=>{for(let t=0;try++,ha=async(e,t,r,s)=>{let o=fa(r),c=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let p=e.getCommandEncoder();e.endComputePass(),p.copyBufferToBuffer(t,0,c,0,o),e.flush(),await c.mapAsync(GPUMapMode.READ);let l=c.getMappedRange();if(s){let h=s();return h.set(new Uint8Array(l,0,r)),h}else return new Uint8Array(l.slice(0,r))}finally{c.destroy()}},ma=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[r]of $l)pa.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[])}upload(t,r){let s=r.buffer,o=r.byteOffset,c=r.byteLength,p=fa(c),l=this.storageCache.get(t);if(!l)throw new Error("gpu data for uploading does not exist");if(l.originalSize!==c)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${c}`);let h=this.backend.device.createBuffer({mappedAtCreation:!0,size:p,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),y=h.getMappedRange();new Uint8Array(y).set(new Uint8Array(s,o,c)),h.unmap();let $=this.backend.getCommandEncoder();this.backend.endComputePass(),$.copyBufferToBuffer(h,0,l.gpuData.buffer,0,p),qe("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(h)}memcpy(t,r){let s=this.storageCache.get(t);if(!s)throw new Error("source gpu data for memcpy does not exist");let o=this.storageCache.get(r);if(!o)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==o.originalSize)throw new Error("inconsistent source and destination gpu data size");let c=fa(s.originalSize),p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(s.gpuData.buffer,0,o.gpuData.buffer,0,c)}registerExternalBuffer(t,r,s){let o;if(s){if(o=this.externalBuffers.get(s),o===void 0)throw new Error("previous buffer is not registered");if(t===s)return qe("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;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(s)}else o=Cl();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,o),qe("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),qe("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=ty(t),o,c=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,p=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(c||p){let y=(c?this.freeBuffers:this.freeUniformBuffers).get(s);y?y.length>0?o=y.pop():o=this.backend.device.createBuffer({size:s,usage:r}):o=this.backend.device.createBuffer({size:s,usage:r})}else o=this.backend.device.createBuffer({size:s,usage:r});let l={id:Cl(),type:0,buffer:o};return this.storageCache.set(l.id,{gpuData:l,originalSize:t}),qe("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=this.storageCache.get(t);if(!r)throw new Error("releasing data does not exist");return qe("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(t,r){let s=this.storageCache.get(t);if(!s)throw new Error("data does not exist");await ha(this.backend,s.gpuData.buffer,s.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let r=$l.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(t.size)||[];r===void 0||s.length>=r?t.destroy():s.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(t.size)||[];r===void 0||s.length>=r?t.destroy():s.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(t))}},Sl=(...e)=>new ma(...e)});var ga,Oe,nt=ie(()=>{"use strict";ga=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},Oe=e=>new ga(e)});var ya,Ut,K,hr,bn,wn,_n,je=ie(()=>{"use strict";ya=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},Ut=class{static calcShape(t,r,s=!1){let o=t.length,c=r.length;if(o===0)return r;if(c===0)return t;let p=Math.max(t.length,r.length),l=new Array(p);if(s){if(o<2||c<2)return;let h=ya.calcMatMulShape([t[o-2],t[o-1]],[r[c-2],r[c-1]]);if(h===void 0)return;[l[p-2],l[p-1]]=h}for(let h=s?3:1;h<=p;h++){let y=o-h<0?1:t[o-h],$=c-h<0?1:r[c-h];if(y!==$&&y>1&&$>1)return;let _=Math.max(y,$);if(y&&$)l[p-h]=Math.max(y,$);else{if(_>1)return;l[p-h]=0}}return l}static isValidBroadcast(t,r){let s=t.length,o=r.length;if(s>o)return!1;for(let c=1;c<=s;c++)if(t[s-c]!==1&&t[s-c]!==r[o-c])return!1;return!0}},K=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let s=t.length;if(s===0)return[];let o=new Array(s),c=s-1;for(;c>=0;){if(t[c]%r===0){o[c]=t[c]/r;break}if(r%t[c]!==0)throw new Error("cannot convert shape");o[c]=1,r/=t[c],c--}for(c--;c>=0;c--)o[c]=t[c];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,s){let o=1;for(let c=r;c=0;--o)s[o]=s[o+1]*t[o+1];return s}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(s=>this.normalizeAxis(s,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(s=>t[s]):t.slice().reverse()}static padShape(t,r){let s=t.length;return t.map((o,c)=>o+r[c]+r[c+s])}static areEqual(t,r){return t.length!==r.length?!1:t.every((s,o)=>s===r[o])}},hr=class e{static adjustPoolAttributes(t,r,s,o,c,p){if(!t&&s.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let l=0;l=s.length?s.push(r[l+2]):s[l]=r[l+2];for(let l=0;l=s[l]||p[l+s.length]>=s[l])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,s,o,c,p,l){if(l){if(c.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let h=0;h{"use strict";Te();je();gr=64,ba=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},Ge=(e,t=1)=>{let r=ba(e,t);return typeof r=="string"?r:r[0]},ut=(e,t=1)=>{let r=ba(e,t);return typeof r=="string"?r:r[1]},se=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:K.computeStrides(r)})}),t},Le=e=>e%4===0?4:e%2===0?2:1,Pt=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,yr=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,zt=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Se=(e,t,r,s)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?s==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:s==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,wa=(e,t,r,s,o)=>{let c=typeof r=="number",p=c?r:r.length,l=[...new Array(p).keys()],h=p<2?"u32":p<=4?`vec${p}`:`array`,y=ba(t,o),$=typeof y=="string"?y:y[1],_=typeof y=="string"?y:y[0],C={indices:h,value:$,storage:_,tensor:t},T=ee=>typeof ee=="string"?ee:`${ee}u`,S={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=c?"uniforms.":"",O=`${E}${e}_shape`,R=`${E}${e}_strides`,z="";for(let ee=0;ee ${C.indices} { var indices: ${C.indices}; var current = offset; ${z} return indices; }`,U=ee=>(S.offsetToIndices=!0,p<2?ee:`o2i_${e}(${ee})`),L=[];if(p>=2)for(let ee=p-1;ee>=0;ee--)L.push(`${Se(R,ee,p)} * (indices[${ee}])`);let F=p<2?"":` fn i2o_${e}(indices: ${C.indices}) -> u32 { return ${L.join("+")}; }`,te=ee=>(S.indicesToOffset=!0,p<2?ee:`i2o_${e}(${ee})`),J=(...ee)=>p===0?"0u":`${C.indices}(${ee.map(T).join(",")})`,oe=(ee,ce)=>p<2?`${ee}`:`${Se(ee,ce,p)}`,le=(ee,ce,Re)=>p<2?`${ee}=${Re};`:`${Se(ee,ce,p)}=${Re};`,ge={},Z=(ee,ce)=>{S.broadcastedIndicesToOffset=!0;let Re=`${ce.name}broadcastedIndicesTo${e}Offset`;if(Re in ge)return`${Re}(${ee})`;let rt=[];for(let Qe=p-1;Qe>=0;Qe--){let Ye=ce.indicesGet("outputIndices",Qe+ce.rank-p);rt.push(`${oe(R,Qe)} * (${Ye} % ${oe(O,Qe)})`)}return ge[Re]=`fn ${Re}(outputIndices: ${ce.type.indices}) -> u32 { return ${rt.length>0?rt.join("+"):"0u"}; }`,`${Re}(${ee})`},fe=(ee,ce)=>(()=>{if(C.storage===C.value)return`${e}[${ee}]=${ce};`;if(C.storage==="vec2"&&C.value==="i32")return`${e}[${ee}]=vec2(u32(${ce}), select(0u, 0xFFFFFFFFu, ${ce} < 0));`;if(C.storage==="vec2"&&C.value==="u32")return`${e}[${ee}]=vec2(u32(${ce}), 0u);`;if(C.storage==="u32"&&C.value==="vec4")return`${e}[${ee}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ce}));`;throw new Error(`not supported combination of storage type ${C.storage} and value type ${C.value} yet`)})(),we=ee=>(()=>{if(C.storage===C.value)return`${e}[${ee}]`;if(C.storage==="vec2"&&C.value==="i32")return`i32(${e}[${ee}].x)`;if(C.storage==="vec2"&&C.value==="u32")return`u32(${e}[${ee}].x)`;if(C.storage==="u32"&&C.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 ${C.storage} and value type ${C.value} yet`)})(),ue=p<2?"":` fn get_${e}ByIndices(indices: ${C.indices}) -> ${$} { return ${we(`i2o_${e}(indices)`)}; }`,me=p<2?"":(()=>{let ee=l.map(Re=>`d${Re}: u32`).join(", "),ce=l.map(Re=>`d${Re}`).join(", ");return` fn get_${e}(${ee}) -> ${$} { return get_${e}ByIndices(${J(ce)}); }`})(),Ee=(...ee)=>{if(ee.length!==p)throw new Error(`indices length must be ${p}`);let ce=ee.map(T).join(",");return p===0?we("0u"):p===1?we(ce[0]):(S.get=!0,S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}(${ce})`)},ke=ee=>p<2?we(ee):(S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}ByIndices(${ee})`),Ce=p<2?"":` fn set_${e}ByIndices(indices: ${C.indices}, value: ${$}) { ${fe(`i2o_${e}(indices)`,"value")} }`,ve=p<2?"":(()=>{let ee=l.map(Re=>`d${Re}: u32`).join(", "),ce=l.map(Re=>`d${Re}`).join(", ");return` fn set_${e}(${ee}, value: ${$}) { set_${e}ByIndices(${J(ce)}, value); }`})();return{impl:()=>{let ee=[],ce=!1;return S.offsetToIndices&&(ee.push(M),ce=!0),S.indicesToOffset&&(ee.push(F),ce=!0),S.broadcastedIndicesToOffset&&(Object.values(ge).forEach(Re=>ee.push(Re)),ce=!0),S.set&&(ee.push(ve),ce=!0),S.setByIndices&&(ee.push(Ce),ce=!0),S.get&&(ee.push(me),ce=!0),S.getByIndices&&(ee.push(ue),ce=!0),!c&&ce&&ee.unshift(`const ${O} = ${C.indices}(${r.join(",")});`,`const ${R} = ${C.indices}(${K.computeStrides(r).join(",")});`),ee.join(` `)},type:C,offsetToIndices:U,indicesToOffset:te,broadcastedIndicesToOffset:Z,indices:J,indicesGet:oe,indicesSet:le,set:(...ee)=>{if(ee.length!==p+1)throw new Error(`indices length must be ${p}`);let ce=ee[p];if(typeof ce!="string")throw new Error("value must be string");let Re=ee.slice(0,p).map(T).join(",");return p===0?fe("0u",ce):p===1?fe(Re[0],ce):(S.set=!0,S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}(${Re}, ${ce})`)},setByOffset:fe,setByIndices:(ee,ce)=>p<2?fe(ee,ce):(S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}ByIndices(${ee}, ${ce});`),get:Ee,getByOffset:we,getByIndices:ke,usage:s,name:e,strides:R,shape:O,rank:p}},Q=(e,t,r,s=1)=>wa(e,t,r,"input",s),ne=(e,t,r,s=1)=>wa(e,t,r,"output",s),$n=(e,t,r,s=1)=>wa(e,t,r,"internal",s),va=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=gr){let r=typeof t=="number"?t:t[0],s=typeof t=="number"?1:t[1],o=typeof t=="number"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${s}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*s*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${s}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let c=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,p=c?`@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`,l=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] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r*s*o}u + local_idx;`;return`@compute @workgroup_size(${r}, ${s}, ${o}) fn main(${p}) { ${l} `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let s=t.usage==="input"?"read":"read_write",o=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(` `)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,s=1){return this.uniforms.push({name:t,type:r,length:s}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:s,length:o}of this.uniforms)if(o&&o>4)s==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(o/8)}>`):t.push(`${r}:array, ${Math.ceil(o/4)}>`);else{let c=o==null||o===1?s:`vec${o}<${s}>`;t.push(`${r}:${c}`)}return` struct Uniforms { ${t.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(` `)+this.internalVariables.map(t=>t.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},Tl=(e,t)=>new va(e,t),Hr=(e,t)=>{let r=e.length,s=[];for(let o=0;o1&&p===1&&s.unshift(c)}return s}});var iy,Al,ny,ay,At,El,kl,Lr=ie(()=>{"use strict";Te();je();nt();ze();iy=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Al=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,ny=(e,t)=>K.sortBasedOnPerm(e,Al(e.length,t)),ay=(e,t,r,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let c=0;c{let r=e.dataType,s=e.dims.length,o=Al(s,t),c=ny(e.dims,o),p=ne("output",r,c.length),l=Q("a",r,s),h=y=>` ${y.registerUniform("output_size","u32").declareVariables(l,p)} ${ay(o,s,l,p)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${p.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${p.setByOffset("global_idx",l.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:y=>{let $=K.size(c);return{outputs:[{dims:c,dataType:y[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...se(y[0].dims,c)]}},getShaderSource:h}},El=(e,t)=>{iy(e.inputs),e.compute(At(e.inputs[0],t.perm))},kl=e=>Oe({perm:e.perm})});var oy,sy,uy,ly,dy,cy,py,fy,my,hy,Wt,Ol,Pl,zl,Rl,jl,Bl,Dl,Ml,Ul,Wl,Nl=ie(()=>{"use strict";Te();je();ze();Cn();Lr();oy={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"},sy={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"},uy={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},ly={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},dy=(e,t)=>{let r=[];for(let s=t-e;s{let r=[],s=e.length;for(let c=0;ce[c]);return[r,o]},py=(e,t)=>{let r=e.length+t.length,s=[],o=0;for(let c=0;c{for(let r=0;r{let r=[];if(!fy(e,t)){for(let s=0;sr.push(s))}return r},hy=(e,t,r,s,o,c,p)=>{let l=r[0].dims,h=K.size(c),y=K.size(p),$=Q("_A",r[0].dataType,l),_=ne("output",o,c),C=32,T=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:E=>` ${E.registerUniform("reduceSize","u32").declareVariables($,_)} ${T} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${E.mainStart(C)} let outputIndex = global_idx / ${C}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${uy[s]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${C}) { let candidate = f32(${$.getByOffset("offset + k")}); bestValue = ${oy[s]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${C}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 = ${sy[s]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${_.setByOffset("outputIndex",`${s==="mean"?`${_.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${_.type.storage}(${ly[s]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:c,dataType:o}],dispatchGroup:{x:h},programUniforms:[{type:12,data:y}]})}},Wt=(e,t,r,s)=>{let o=e.inputs.length===1?r:_a(e.inputs,r),c=o.axes;c.length===0&&!o.noopWithEmptyAxes&&(c=e.inputs[0].dims.map((T,S)=>S));let p=K.normalizeAxes(c,e.inputs[0].dims.length),l=p,h=e.inputs[0],y=my(l,e.inputs[0].dims.length);y.length>0&&(h=e.compute(At(e.inputs[0],y),{inputs:[0],outputs:[-1]})[0],l=dy(l.length,h.dims.length));let[$,_]=cy(h.dims,l),C=$;o.keepDims&&(C=py($,p)),e.compute(hy(t,{hint:o.cacheKey,inputDependencies:["type"]},[h],s,e.inputs[0].dataType,C,_),{inputs:[h]})},Ol=(e,t)=>{Wt(e,"ReduceMeanShared",t,"mean")},Pl=(e,t)=>{Wt(e,"ReduceL1Shared",t,"l1")},zl=(e,t)=>{Wt(e,"ReduceL2Shared",t,"l2")},Rl=(e,t)=>{Wt(e,"ReduceLogSumExpShared",t,"logSumExp")},jl=(e,t)=>{Wt(e,"ReduceMaxShared",t,"max")},Bl=(e,t)=>{Wt(e,"ReduceMinShared",t,"min")},Dl=(e,t)=>{Wt(e,"ReduceProdShared",t,"prod")},Ml=(e,t)=>{Wt(e,"ReduceSumShared",t,"sum")},Ul=(e,t)=>{Wt(e,"ReduceSumSquareShared",t,"sumSquare")},Wl=(e,t)=>{Wt(e,"ReduceLogSumShared",t,"logSum")}});var Nt,gy,xn,_a,Vt,yy,vy,by,wy,_y,$y,Cy,xy,Sy,Iy,Gt,Vl,Gl,Hl,Ll,Fl,ql,Kl,Yl,Ql,Xl,Cn=ie(()=>{"use strict";Te();je();nt();ze();Nl();Nt=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.")},gy=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],xn=(e,t,r,s,o,c,p=!1,l=!1)=>{let h=[],y=r[0].dims,$=y.length,_=K.normalizeAxes(o,$),C=!l&&_.length===0;y.forEach((O,R)=>{C||_.indexOf(R)>=0?p&&h.push(1):h.push(O)});let T=h.length,S=K.size(h);return{name:e,shaderCache:t,getShaderSource:O=>{let R=[],z=Q("_A",r[0].dataType,$),M=ne("output",c,T),U=s(z,M,_),L=U[2];for(let F=0,te=0;F<$;F++)C||_.indexOf(F)>=0?(p&&te++,L=`for(var j${F}: u32 = 0; j${F} < ${y[F]}; j${F}++) { ${U[2].includes("last_index")?`let last_index = j${F};`:""} ${z.indicesSet("input_indices",F,`j${F}`)} ${L} }`):(R.push(`${z.indicesSet("input_indices",F,M.indicesGet("output_indices",te))};`),te++);return` ${O.registerUniform("output_size","u32").declareVariables(z,M)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${z.type.indices}; let output_indices = ${M.offsetToIndices("global_idx")}; ${R.join(` `)} ${U[0]} // init ops for reduce max/min ${U[1]} ${L} ${U[3]} ${U.length===4?M.setByOffset("global_idx","value"):U.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:h,dataType:c}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...se(y,h)]})}},_a=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),Oe({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Vt=(e,t,r,s)=>{let o=e.inputs,c=o.length===1?r:_a(o,r);e.compute(xn(t,{hint:c.cacheKey,inputDependencies:["rank"]},[o[0]],c.noopWithEmptyAxes&&c.axes.length===0?gy:s,c.axes,o[0].dataType,c.keepDims,c.noopWithEmptyAxes),{inputs:[0]})},yy=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceLogSum",t,(s,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},vy=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceL1",t,(s,o)=>[`var value = ${o.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},by=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceL2",t,(s,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},wy=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceLogSumExp",t,(s,o)=>[`var value = ${o.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},_y=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceMax",t,(s,o,c)=>{let p=[];for(let l=0;l=0||c.length===0)&&p.push(s.indicesSet("input_indices",l,0));return[`${p.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},$y=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceMean",t,(s,o,c)=>{let p=1;for(let l=0;l=0||c.length===0)&&(p*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${o.type.value}(sum / ${p});`]})},Cy=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceMin",t,(s,o,c)=>{let p=[];for(let l=0;l=0||c.length===0)&&p.push(`input_indices[${l}] = 0;`);return[`${p.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},xy=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceProd",t,(s,o)=>[`var value = ${o.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Sy=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceSum",t,(s,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Iy=(e,t)=>{Nt(e.inputs),Vt(e,"ReduceSumSquare",t,(s,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},Gt=(e,t,r)=>{if(t.length===0)return r;let s=1,o=1;for(let c=0;c1024},Vl=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$y(e,t):Ol(e,t)},Gl=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vy(e,t):Pl(e,t)},Hl=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?by(e,t):zl(e,t)},Ll=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wy(e,t):Rl(e,t)},Fl=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_y(e,t):jl(e,t)},ql=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Cy(e,t):Bl(e,t)},Kl=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xy(e,t):Dl(e,t)},Yl=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sy(e,t):Ml(e,t)},Ql=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Iy(e,t):Ul(e,t)},Xl=(e,t)=>{Gt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?yy(e,t):Wl(e,t)}});var Zl,Jl,ed,$a,td=ie(()=>{"use strict";Te();nt();Cn();Zl=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.")},Jl=(e,t)=>{Zl(e.inputs);let r=(s,o,c)=>{let p=[];for(let l=0;l=0||c.length===0)&&p.push(`input_indices[${l}] = 0;`);return[`${p.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",o.setByOffset("global_idx","best_index")]};e.compute(xn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ed=(e,t)=>{Zl(e.inputs);let r=(s,o,c)=>{let p=[];for(let l=0;l=0||c.length===0)&&p.push(`input_indices[${l}] = 0;`);return[`${p.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",o.setByOffset("global_idx","best_index")]};e.compute(xn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},$a=e=>Oe(e)});var Ty,Ay,Ey,Sn,rd,id,Ca=ie(()=>{"use strict";Te();je();nt();ze();Ty=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,s=e[r],o=s.dataType,c=s.dims.length;e.forEach((p,l)=>{if(l!==r){if(p.dataType!==o)throw new Error("input tensors should be one type");if(p.dims.length!==c)throw new Error("input tensors should have the same shape");p.dims.forEach((h,y)=>{if(y!==t&&h!==s.dims[y])throw new Error("non concat dimensions must match")})}})},Ay=(e,t)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${t}); for (var i: u32 = 0u; i < ${e}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${e}u; }`,Ey=(e,t)=>{let r=e.length,s=[];for(let o=0;o{let o=K.size(r),c=new Array(e.length),p=new Array(e.length),l=0,h=[],y=[],$=[{type:12,data:o}];for(let E=0;E`uniforms.sizeInConcatAxis${E}`).join(","),S=E=>` ${(()=>{E.registerUniform("outputSize","u32");for(let O=0;O(${T}); ${C} -= sizeInConcatAxis[inputIndex - 1u]; } ${Ey(p,_)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:r,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:$}),getShaderSource:S}},rd=(e,t)=>{let r=e.inputs,s=r[0].dims,o=K.normalizeAxis(t.axis,s.length);Ty(r,o);let c=s.slice();c[o]=r.reduce((l,h)=>l+(h.dims.length>o?h.dims[o]:0),0);let p=r.filter(l=>K.size(l.dims)>0);e.compute(Sn(p,o,c,r[0].dataType),{inputs:p})},id=e=>Oe({axis:e.axis})});var ky,Oy,Py,zy,In,Ry,nd,xa=ie(()=>{"use strict";Te();vn();ze();Ca();ky=(e,t)=>{let r=e[0],s=e[1],o=e[2],c=e[3],p=e[4],l=e[5];if(p&&l)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let h=r.dims[0],y=r.dims[1],$=r.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==$)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let _=o.dims[0]/3,C=_,T=C;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let M of t.qkvHiddenSizes)if(M%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");_=t.qkvHiddenSizes[0],C=t.qkvHiddenSizes[1],T=t.qkvHiddenSizes[2]}let S=y;if(_!==C)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==_+C+T)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let E=0;if(p){if(C!==T)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(p.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(p.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(p.dims[1]!==h)throw new Error('Input "past" second dimension must be batch_size');if(p.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(p.dims[4]!==C/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(E=p.dims[3])}let O=S+E,R=-1,z=0;if(c)throw new Error("Mask not supported");if(p)throw new Error("past is not supported");return{batchSize:h,sequenceLength:y,pastSequenceLength:E,kvSequenceLength:S,totalSequenceLength:O,maxSequenceLength:R,inputHiddenSize:$,hiddenSize:_,vHiddenSize:T,headSize:Math.floor(_/t.numHeads),vHeadSize:Math.floor(T/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:z,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Oy=(e,t,r,s)=>{let o=Le(s),c=64,p=s/o;p{let T=ne("x",t.dataType,t.dims,o),E=[{name:"d_inv",type:ut(t.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${C.registerUniforms(E).declareVariables(T)} ${C.mainStart([c,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 = ${$}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${$}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(o){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: ${o}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${c}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${$}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${$}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(o){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: ${o}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${c}; 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] = ${T.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 = ${$}(x[offset + i]); x[offset + i] = ${T.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${y};${o}`},getShaderSource:_,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:h})}},Py=(e,t,r,s,o,c,p)=>{let l=p+o.kvSequenceLength,h=[o.batchSize,o.numHeads,o.sequenceLength,l],y=c.scale===0?1/Math.sqrt(o.headSize):c.scale,$=Le(o.headSize),_=o.headSize/$,C=12,T={x:Math.ceil(l/C),y:Math.ceil(o.sequenceLength/C),z:o.batchSize*o.numHeads},S=[{type:12,data:o.sequenceLength},{type:12,data:_},{type:12,data:l},{type:12,data:o.numHeads},{type:1,data:y}],E=["type","type"];s&&(E.push("rank"),S.push(...se(s.dims)));let O=R=>{let z=Q("q",t.dataType,t.dims,$),M=Q("key",r.dataType,r.dims,$),U=[z,M],L=s?Q("relative_position_bias",s.dataType,s.dims.length):void 0;L&&U.push(L);let F=ne("output",t.dataType,h),te=ut(1,$),J=[{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 = ${C}u; var tileQ: array<${z.type.storage}, ${C*C}>; var tileK: array<${z.type.storage}, ${C*C}>; ${R.registerUniforms(J).declareVariables(...U,F)} ${R.mainStart([C,C,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 = ${te}(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 += ${te}(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($){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: ${$}`)}})()}; ${(()=>L?` let batch = workgroup_id.z / uniforms.num_heads; let head = workgroup_id.z % uniforms.num_heads; var indices = ${L.type.indices}(batch, head, global_id.y, global_id.x); output[outputIdx] = ${F.type.value}(sum * uniforms.alpha) + ${L.getByIndices("indices")};`:`output[outputIdx] = ${F.type.value} (sum * uniforms.alpha);`)()} } }`};return{name:"AttentionProbs",shaderCache:{hint:`${$}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:h,dataType:t.dataType,gpuDataType:0}],dispatchGroup:T,programUniforms:S}),getShaderSource:O}},zy=(e,t,r,s,o)=>{let c=o+s.kvSequenceLength,p=[s.batchSize,s.sequenceLength,s.vHiddenSize],l=12,h={x:Math.ceil(s.vHeadSize/l),y:Math.ceil(s.sequenceLength/l),z:s.batchSize*s.numHeads},y=[{type:12,data:s.sequenceLength},{type:12,data:c},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:s.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:p,dataType:t.dataType,gpuDataType:0}],dispatchGroup:h,programUniforms:y}),getShaderSource:C=>{let T=Q("probs",t.dataType,t.dims),S=Q("v",r.dataType,r.dims),E=ne("output",t.dataType,p),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` const TILE_SIZE = ${l}u; var tileQ: array<${T.type.value}, ${l*l}>; var tileK: array<${T.type.value}, ${l*l}>; ${C.registerUniforms(O).declareVariables(T,S,E)} ${C.mainStart([l,l,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 = ${T.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; } }`}}},In=(e,t,r,s,o,c,p,l,h,y,$)=>{let _=e.outputCount>1,C=e.outputCount>2,T=_&&C?y.pastSequenceLength:0,S=T+y.kvSequenceLength,E=[y.batchSize,y.numHeads,S,y.headSize],O=p?[p,r]:[r],R=_?e.compute(Sn(O,2,E,r.dataType),{inputs:O,outputs:[1]})[0]:r,z=[y.batchSize,y.numHeads,S,y.headSize],M=l?[l,s]:[s],U=C?e.compute(Sn(M,2,z,s.dataType),{inputs:M,outputs:[2]})[0]:s,L=[t,R];h&&L.push(h);let F=e.compute(Py(e,t,R,h,y,$,T),{inputs:L,outputs:[-1]})[0];e.compute(Oy(e,F,y.batchSize*y.numHeads*y.sequenceLength,S),{inputs:[F],outputs:[]});let te=[F,U];e.compute(zy(e,F,U,y,T),{inputs:te,outputs:[0]})},Ry=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],s=t.sequenceLength,o=t.inputHiddenSize,c=t.headSize,p=12,l={x:Math.ceil(t.headSize/p),y:Math.ceil(t.sequenceLength/p),z:t.batchSize*t.numHeads},h=[e.inputs[0],e.inputs[1],e.inputs[2]],y=[{type:12,data:s},{type:12,data:o},{type:12,data:c},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],$=_=>{let C=ne("output_q",h[0].dataType,r),T=ne("output_k",h[0].dataType,r),S=ne("output_v",h[0].dataType,r),E=Q("input",h[0].dataType,h[0].dims),O=Q("weight",h[1].dataType,h[1].dims),R=Q("bias",h[2].dataType,h[2].dims),z=E.type.storage,M=[{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 = ${p}u; var tileInput: array<${z}, ${p*p}>; var tileWeightQ: array<${z}, ${p*p}>; var tileWeightK: array<${z}, ${p*p}>; var tileWeightV: array<${z}, ${p*p}>; ${_.registerUniforms(M).declareVariables(E,O,R,C,T,S)} ${_.mainStart([p,p,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 = ${z}(0); var valueK = ${z}(0); var valueV = ${z}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:y}),getShaderSource:$},{inputs:h,outputs:[-1,-1,-1]})},nd=(e,t)=>{let r=ky(e.inputs,t),[s,o,c]=Ry(e,r);return In(e,s,o,c,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var jy,By,Dy,ad,od=ie(()=>{"use strict";Tt();Te();je();nt();ze();jy=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(s,o,c)=>{let p=o.length;if(p!==s.length)throw new Error(`${c}: num dimensions != ${p}`);o.forEach((l,h)=>{if(l!==s[h])throw new Error(`${c}: dim[${h}] do not match`)})};if(e[0].dims.length>1){let s=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,s,"Invalid input scale"),r(e[2].dims,s,"Invalid input B"),r(e[3].dims,s,"Invalid input mean"),r(e[4].dims,s,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},By=(e,t)=>{let{epsilon:r,spatial:s,format:o}=t,c=e[0].dims,p=s?Le(c[c.length-1]):1,l=o==="NHWC"&&c.length>1?p:1,h=K.size(c)/p,y=s,$=y?c.length:c,_=Q("x",e[0].dataType,e[0].dims,p),C=Q("scale",e[1].dataType,e[1].dims,l),T=Q("bias",e[2].dataType,e[2].dims,l),S=Q("inputMean",e[3].dataType,e[3].dims,l),E=Q("inputVar",e[4].dataType,e[4].dims,l),O=ne("y",e[0].dataType,$,p),R=()=>{let M="";if(s)M=`let cOffset = ${c.length===1?"0u":o==="NHWC"?`outputIndices[${c.length-1}] / ${p}`:"outputIndices[1]"};`;else if(o==="NCHW")M=` ${O.indicesSet("outputIndices","0","0")} let cOffset = ${O.indicesToOffset("outputIndices")};`;else{M=`var cIndices = ${C.type.indices}(0); cIndices[0] = outputIndices[${c.length-1}];`;for(let U=1;U` const epsilon = ${r}; ${M.registerUniform("outputSize","u32").declareVariables(_,C,T,S,E,O)} ${M.mainStart()} ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${O.offsetToIndices(`global_idx * ${p}`)}; ${R()} let scale = ${C.getByOffset("cOffset")}; let bias = ${T.getByOffset("cOffset")}; let inputMean = ${S.getByOffset("cOffset")}; let inputVar = ${E.getByOffset("cOffset")}; let x = ${_.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${O.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${s}_${p}`,inputDependencies:y?["rank","type","type","type","type"]:void 0},getShaderSource:z,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:y?[{type:12,data:h},...se(c)]:[{type:12,data:h}]})}},Dy=e=>Oe(e),ad=(e,t)=>{let{inputs:r,outputCount:s}=e,o=Dy({...t,outputCount:s});if(We.webgpu.validateInputContent&&jy(r,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(By(r,o))}});var My,Uy,sd,ud=ie(()=>{"use strict";je();ze();My=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")},Uy=e=>{let t=e[0].dims,r=e[0].dims[2],s=K.size(t)/4,o=e[0].dataType,c=Q("input",o,t,4),p=Q("bias",o,[r],4),l=Q("residual",o,t,4),h=ne("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:$=>` const channels = ${r}u / 4; ${$.declareVariables(c,p,l,h)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes(s)} let value = ${c.getByOffset("global_idx")} + ${p.getByOffset("global_idx % channels")} + ${l.getByOffset("global_idx")}; ${h.setByOffset("global_idx","value")} }`}},sd=e=>{My(e.inputs),e.compute(Uy(e.inputs))}});var Wy,Ne,ld,dd,cd,pd,fd,md,hd,gd,yd,Ny,vd,bd,wd,_d,Tn,$d,An,Cd,xd,Sd,Id,Td,Ad,Ed,kd,Od,Pd,zd,Rd,jd,Bd,Dd,Md,Ud,Wd,Sa,Ia,Nd,Vd,Gd,En=ie(()=>{"use strict";Te();je();nt();ze();Wy=(e,t,r,s,o,c)=>{let p=Math.ceil(t/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let h=Q("inputData",r,[p],4),y=ne("outputData",s,[p],4);return` ${e.registerUniform("vec_size","u32").declareVariables(h,y)} ${c??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${y.setByOffset("global_idx",l)} }`},Ne=(e,t,r,s,o,c=e.dataType)=>({name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:p=>Wy(p,K.size(e.dims),e.dataType,c,r,s),getRunData:p=>({outputs:[{dims:e.dims,dataType:c}],dispatchGroup:{x:Math.ceil(K.size(p[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(K.size(e.dims)/4)}]})}),ld=e=>{e.compute(Ne(e.inputs[0],"Abs","abs"))},dd=e=>{e.compute(Ne(e.inputs[0],"Acos","acos"))},cd=e=>{e.compute(Ne(e.inputs[0],"Acosh","acosh"))},pd=e=>{e.compute(Ne(e.inputs[0],"Asin","asin"))},fd=e=>{e.compute(Ne(e.inputs[0],"Asinh","asinh"))},md=e=>{e.compute(Ne(e.inputs[0],"Atan","atan"))},hd=e=>{e.compute(Ne(e.inputs[0],"Atanh","atanh"))},gd=e=>Oe(e),yd=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(Ne(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Ny=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:wn,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:_n;return Oe({min:t,max:r})},vd=(e,t)=>{let r=e.inputs.length===1?t:Ny(e.inputs),s=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"Clip",o=>`clamp(${o}, clip_min_, clip_max_)`,` const clip_min_: vec4<${s}> = vec4(${s}(${r.min})); const clip_max_: vec4<${s}> = vec4(${s}(${r.max})); `,r.cacheKey),{inputs:[0]})},bd=e=>{e.compute(Ne(e.inputs[0],"Ceil","ceil"))},wd=e=>{e.compute(Ne(e.inputs[0],"Cos","cos"))},_d=e=>{e.compute(Ne(e.inputs[0],"Cosh","cosh"))},Tn=e=>Oe(e),$d=(e,t)=>{let r=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` const elu_alpha_ = ${r}(${t.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},An=(e="f32")=>` const r0: ${e} = 0.3275911; const r1: ${e} = 0.254829592; const r2: ${e} = -0.284496736; const r3: ${e} = 1.421413741; const r4: ${e} = -1.453152027; const r5: ${e} = 1.061405429; fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,Cd=e=>{let t=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,An(t)))},xd=e=>{e.compute(Ne(e.inputs[0],"Exp","exp"))},Sd=e=>{e.compute(Ne(e.inputs[0],"Floor","floor"))},Id=e=>{let t=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,An(t)))},Td=(e,t)=>{let r=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Ad=e=>{e.compute(Ne(e.inputs[0],"Not",t=>`!${t}`))},Ed=e=>{e.compute(Ne(e.inputs[0],"Neg",t=>`-${t}`))},kd=e=>{e.compute(Ne(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Od=e=>{let t=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Pd=e=>{e.compute(Ne(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},zd=e=>Oe(e),Rd=(e,t)=>{let r=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"HardSigmoid",s=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${s} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},jd=e=>{e.compute(Ne(e.inputs[0],"Sin","sin"))},Bd=e=>{e.compute(Ne(e.inputs[0],"Sinh","sinh"))},Dd=e=>{e.compute(Ne(e.inputs[0],"Sqrt","sqrt"))},Md=e=>{e.compute(Ne(e.inputs[0],"Tan","tan"))},Ud=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Wd=e=>{e.compute(Ne(e.inputs[0],"Tanh",Ud))},Sa=(e="f32")=>` const fast_gelu_a: ${e} = 0.5; const fast_gelu_b: ${e} = 0.7978845608028654; const fast_gelu_c: ${e} = 0.035677408136300125; fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { return ${Ud("v")}; } `,Ia=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Nd=e=>{let t=ut(e.inputs[0].dataType);e.compute(Ne(e.inputs[0],"FastGelu",Ia,Sa(t),void 0,e.inputs[0].dataType))},Vd=(e,t)=>{let r=ut(e.inputs[0].dataType);return e.compute(Ne(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${r}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},Gd=e=>{e.compute(Ne(e.inputs[0],"Log","log"))}});var Vy,Gy,Ld,Fd=ie(()=>{"use strict";je();ze();En();Vy=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")},Gy=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Q("input",e[0].dataType,e[0].dims,4),s=Q("bias",e[0].dataType,[e[0].dims[2]],4),o=ne("output",e[0].dataType,t,4),c=K.size(t)/4,p=Ge(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)}}),getShaderSource:h=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${h.declareVariables(r,s,o)} ${An(p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(c)} 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); ${o.setByOffset("global_idx","valueLeft * geluRight")} }`}},Ld=e=>{Vy(e.inputs),e.compute(Gy(e.inputs))}});var Hy,Ly,Ht,qd,Kd,Yd,Qd,Xd,Zd,Jd,ec,tc,rc,ic=ie(()=>{"use strict";Te();je();ze();Hy=(e,t,r,s,o,c,p,l,h,y,$,_)=>{let C,T;typeof l=="string"?C=T=(z,M)=>`${l}((${z}),(${M}))`:typeof l=="function"?C=T=l:(C=l.scalar,T=l.vector);let S=ne("outputData",$,s.length,4),E=Q("aData",h,t.length,4),O=Q("bData",y,r.length,4),R;if(o)if(c){let z=K.size(t)===1,M=K.size(r)===1,U=t.length>0&&t[t.length-1]%4===0,L=r.length>0&&r[r.length-1]%4===0;z||M?R=S.setByOffset("global_idx",T(z?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),M?`${O.type.value}(${O.getByOffset("0")}.x)`:O.getByOffset("global_idx"))):R=` let outputIndices = ${S.offsetToIndices("global_idx * 4u")}; let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",S)}; let offsetB = ${O.broadcastedIndicesToOffset("outputIndices",S)}; ${S.setByOffset("global_idx",T(p||U?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,p||L?O.getByOffset("offsetB / 4u"):`${O.type.value}(${O.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else R=S.setByOffset("global_idx",T(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 z=(M,U,L="")=>{let F=`aData[indexA${U}][componentA${U}]`,te=`bData[indexB${U}][componentB${U}]`;return` let outputIndices${U} = ${S.offsetToIndices(`global_idx * 4u + ${U}u`)}; let offsetA${U} = ${E.broadcastedIndicesToOffset(`outputIndices${U}`,S)}; let offsetB${U} = ${O.broadcastedIndicesToOffset(`outputIndices${U}`,S)}; let indexA${U} = offsetA${U} / 4u; let indexB${U} = offsetB${U} / 4u; let componentA${U} = offsetA${U} % 4u; let componentB${U} = offsetB${U} % 4u; ${M}[${U}] = ${L}(${C(F,te)}); `};$===9?R=` var data = vec4(0); ${z("data",0,"u32")} ${z("data",1,"u32")} ${z("data",2,"u32")} ${z("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:R=` ${z("outputData[global_idx]",0)} ${z("outputData[global_idx]",1)} ${z("outputData[global_idx]",2)} ${z("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(E,O,S)} ${_??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${R} }`},Ly=(e,t,r,s,o,c,p=r.dataType)=>{let l=!K.areEqual(r.dims,s.dims),h=r.dims,y=K.size(r.dims),$=!1,_=!1,C=[l];if(l){let T=Ut.calcShape(r.dims,s.dims,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");h=T,y=K.size(h);let S=K.size(r.dims)===1,E=K.size(s.dims)===1,O=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,R=s.dims.length>0&&s.dims[s.dims.length-1]%4===0;C.push(S),C.push(E),C.push(O),C.push(R);let z=1;for(let M=1;MT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>Hy(T,r.dims,s.dims,h,$,l,_,o,r.dataType,s.dataType,p,c),getRunData:()=>({outputs:[{dims:h,dataType:p}],dispatchGroup:{x:Math.ceil(y/64/4)},programUniforms:[{type:12,data:Math.ceil(K.size(h)/4)},...se(r.dims,s.dims,h)]})}},Ht=(e,t,r,s,o,c)=>{e.compute(Ly(t,o??"",e.inputs[0],e.inputs[1],r,s,c))},qd=e=>{Ht(e,"Add",(t,r)=>`${t}+${r}`)},Kd=e=>{Ht(e,"Div",(t,r)=>`${t}/${r}`)},Yd=e=>{Ht(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Qd=e=>{Ht(e,"Mul",(t,r)=>`${t}*${r}`)},Xd=e=>{let t=Q("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ht(e,"Pow",{scalar:(s,o)=>`pow_custom(${s},${o})`,vector:(s,o)=>`pow_vector_custom(${s},${o})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},Zd=e=>{Ht(e,"Sub",(t,r)=>`${t}-${r}`)},Jd=e=>{Ht(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},ec=e=>{Ht(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},tc=e=>{Ht(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},rc=e=>{Ht(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var Rt,jt,Bt,kn,Jt=ie(()=>{"use strict";Te();je();Rt=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},jt=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},Bt=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},kn=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,s]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:s}}else if(t==="Clip"){let[r,s]=e?.activation_params||[wn,_n];return{activation:t,clipMax:s,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var lt,On,Pn=ie(()=>{"use strict";lt=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},On=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `});var zn,Ta=ie(()=>{"use strict";zn=e=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } `});var qy,Ky,Ci,nc,Yy,xi,Qy,Rn,Si=ie(()=>{"use strict";Te();je();ze();Jt();Pn();qy=(e,t)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${t?", batchIndices":""}); `,Ky=(e,t)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,Ci=(e,t,r="f32",s,o=!1,c=32,p=!1,l=32)=>{let h=t[1]*e[1],y=t[0]*e[0],$=o?h:c,_=o?c:h,C=$/t[0],T=c/t[1];if(!((o&&C===4&&e[1]===4||!o&&(C===3||C===4))&&$%t[0]===0&&c%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${C} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${C} must be 3 or 4. tileAWidth ${$} must be divisible by workgroupSize[0]${t[0]}. tileInner ${c} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${$/C}>, ${_}>; var mm_Bsub: array, ${y/e[0]}>, ${c}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${C}; const tileInner = ${c}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${p?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${h}; let num_tiles = ${p?`${Math.ceil(l/c)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${p?`i32(globalId.z) * ${l}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${T}; 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; ${qy(o,s)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${T}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", 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]; ${C===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Ky(o,C)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},nc=(e,t)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${t?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${t?", batchIndices":""}); `,Yy=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",xi=(e,t,r="f32",s,o=!1,c=32,p=!1,l=32,h=!1)=>{let y=e[1]*t[1],$=e[0]*t[0],_=o?y:c,C=o?c:y;if(!(C%t[1]===0&&_%t[0]===0&&c%t[1]===0))throw new Error(`tileAHight ${C} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${_} must be divisible by workgroupSize[0]${t[0]}, tileInner ${c} must be divisible by workgroupSize[1]${t[1]}`);let T=C/t[1],S=_/t[0],E=c/t[1],O=h?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${y}; let globalColStart = i32(workgroupId.x) * ${$}; // 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 < ${C}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${_}; inputCol = inputCol + ${t[0]}) { ${nc(o,s)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${$}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${s?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${y}; let tileRowA = i32(localId.y) * ${T}; let tileColA = i32(localId.x) * ${S}; let tileRowB = i32(localId.y) * ${E}; // 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 < ${T}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${S}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${nc(o,s)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${E}; 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${s?", 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) { ${Yy(o)} 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, ${C}>; var mm_Bsub : array, ${c}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${c}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${p?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${p?`${Math.ceil(l/c)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${p?`i32(globalId.z) * ${l}`:"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; } } ${O} } `},Qy=(e,t,r,s,o,c=!1)=>{let[p,l,h]=o,[y,$,_,C]=s,T=Hr(p,h),S=Hr(l,h),E=Ge(s[0].type.tensor),O=()=>{let M=$.rank,U=y.rank,L=`var aIndices: ${$.type.indices};`;for(let F=M-2-1,te=U-1;F>=0;F--,te--)L+=` aIndices[${F}] = ${U>1?`batchIndices[${te}]`:"batchIndices"};`;return T.forEach(F=>{L+=` aIndices[${F}] = 0;`}),L+=` aIndices[${M-2}] = u32(row); aIndices[${M-1}] = u32(colIn);`,L},R=()=>{let M=_.rank,U=y.rank,L=`var bIndices: ${_.type.indices};`;for(let F=M-2-1,te=U-1;F>=0;F--,te--)L+=` bIndices[${F}] = ${U>1?`batchIndices[${te}]`:"batchIndices"};`;return S.forEach(F=>{L+=` bIndices[${F}] = 0;`}),L+=` bIndices[${M-2}] = u32(row); bIndices[${M-1}] = u32(colIn);`,L};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${y.type.indices}) -> ${lt(e,E)} { var value = ${lt(e,E)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${O()} value = ${$.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${y.type.indices}) -> ${lt(e,E)} { var value = ${lt(e,E)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${R()} value = ${_.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${lt(e,E)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${c?"bias[colIn]":`${lt(e,E)}(bias[row])`};`:""} ${r} ${C.setByIndices("vec3(coords)","value")} } } `},Rn=(e,t,r,s,o=!1)=>{let c=e[0].dims,p=e[1].dims,l=c.slice(0,-2),h=p.slice(0,-2),y=s?s.slice(0,-2):r.slice(0,-2),$=K.size(y),_=c[c.length-2],C=c[c.length-1],T=p[p.length-1],S=C%4===0&&T%4===0,E=_<=8?[4,1,1]:[4,4,1],O=[8,8,1],R=[Math.ceil(T/O[0]/E[0]),Math.ceil(_/O[1]/E[1]),Math.ceil($/O[2]/E[2])],z=S?4:1,M=[...l,_,C/z],U=M.length,L=[...h,C,T/z],F=L.length,te=[$,_,T/z],J=[{type:6,data:_},{type:6,data:T},{type:6,data:C}];jt(t,J),J.push(...se(y,M,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=Z=>{let fe=y.length,we=$n("batchDims",e[0].dataType,fe,1),ue=Ge(e[0].dataType),me=Q("a",e[0].dataType,U,z),Ee=Q("b",e[1].dataType,F,z),ke=ne("result",e[0].dataType,te.length,z),Ce=[me,Ee];if(le){let ee=o?z:1;Ce.push(Q("bias",e[2].dataType,e[2].dims.length,ee))}let ve=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Bt(t,ve);let Ae=Ge(ke.type.tensor),_e=Rt(t,ke.type.value,Ae),et=Qy(z,le,_e,[we,me,Ee,ke],[l,h,y],o);return` ${Z.registerUniforms(ve).registerInternalVariables(we).declareVariables(...Ce,ke)} ${et} ${S?Ci(E,O,ue,we):xi(E,O,ue,we)} `};return{name:"MatMul",shaderCache:{hint:`${E};${t.activation};${S};${o}`,inputDependencies:oe},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:R[0],y:R[1],z:R[2]},programUniforms:J}),getShaderSource:ge}}});var Xy,ac,oc=ie(()=>{"use strict";Te();Zt();ze();Jt();Pn();Ta();Si();Xy=(e,t,r,s,o=!1,c,p=4,l=4,h=4,y="f32")=>{let $=le=>{switch(le){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${y}>(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.`)}},C=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,T=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,S=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",R=e?"col":"row",z=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${O} / outWidth; let outCol = ${O} % outWidth; let WRow = ${R} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${R} / 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 = ${R} % inChannels; var resData = ${lt(p,y)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${S} && xCol >= 0 && xCol < ${E}) { ${C} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${$(p)} } return resData;`,M=e?t&&s?` let col = colIn * ${p}; ${z}`:` let col = colIn * ${p}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${z} } return ${lt(p,y)}(0.0);`:s&&r?` let col = colIn * ${p}; ${z}`:` let col = colIn * ${p}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${z} } return ${lt(p,y)}(0.0);`,U=`${_(l)}`,L=lt(h,y),F=e?lt(p,y):lt(l,y),te=e?lt(l,y):lt(p,y),J=Rt(c,L,y);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${F} { ${e?M:U} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${te} { ${e?U:M} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${L}) { let col = colIn * ${h}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${T} ${On(o)} ${J} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},ac=(e,t,r,s,o,c,p,l)=>{let h=t.format==="NHWC",y=h?e[0].dims[3]:e[0].dims[1],$=r[0],_=h?r[2]:r[3],C=h?r[1]:r[2],T=h?r[3]:r[1],S=h&&(y%4===0||y%3===0)&&T%4===0,E=h?T:_*C,O=h?_*C:T,R=[8,8,1],z=s<=8?[4,1,1]:[4,4,1],M=[Math.ceil(E/R[0]/z[0]),Math.ceil(O/R[1]/z[1]),Math.ceil($/R[2]/z[2])];qe("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${M}`);let U=S?h&&y%4!==0?3:4:1,L=R[1]*z[1],F=R[0]*z[0],te=Math.max(R[0]*U,R[1]),J=s%L===0,oe=o%F===0,le=c%te===0,ge=S?[U,4,4]:[1,1,1],Z=[{type:6,data:s},{type:6,data:o},{type:6,data:c},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];jt(t,Z),Z.push(...se(e[0].dims,e[1].dims));let fe=["rank","rank"];p&&(Z.push(...se(e[2].dims)),fe.push("rank")),Z.push(...se(r));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}];Bt(t,me);let Ee=S?4:1,ke=Ge(e[0].dataType),Ce=` fn setOutputAtIndex(flatIndex : i32, value : ${S?`vec4<${ke}>`:ke}) { result[flatIndex] = ${S?`vec4<${ke}>`:ke}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${S?`vec4<${ke}>`:ke}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${S?"/ 4":""}, value); }`,ve=Q("x",e[0].dataType,e[0].dims.length,U===3?1:U),Ae=Q("w",e[1].dataType,e[1].dims.length,Ee),_e=[ve,Ae],et=ne("result",e[0].dataType,r.length,Ee);if(p){let ee=Q("bias",e[2].dataType,e[2].dims.length,Ee);_e.push(ee),Ce+=` fn getBiasByOutputCoords(coords : vec4) -> ${S?`vec4<${ke}>`:ke} { return bias[coords.${h?"w":"y"}${S?"/ 4":""}]; }`}return` ${zn("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 }; ${ue.registerUniforms(me).declareVariables(..._e,et)} ${Ce} ${Xy(h,J,oe,le,p,t,ge[0],ge[1],ge[2],ke)} ${S?Ci(z,R,ke,void 0,!h,te):xi(z,R,ke,void 0,!h,te,!1,void 0,l)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${U};${S};${J};${oe};${le};${L};${F};${te}`,inputDependencies:fe},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:M[0],y:M[1],z:M[2]},programUniforms:Z}),getShaderSource:we}}});var Aa,sc,uc=ie(()=>{"use strict";Te();je();ze();Ea();Jt();Aa=(e,t,r)=>{let s=e.length>2,o=s?"value += b[output_channel];":"",c=e[0].dims,p=e[1].dims,l=p[0]/t.group,h=t.format==="NHWC",y=jn(c,p,t.dilations,t.pads,t.strides,h),$=K.size(y),_=[{type:12,data:$},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:l}];jt(t,_),_.push(...se(c,p));let C=["rank","rank"];s&&(_.push(...se(e[2].dims)),C.push("rank")),_.push(...se(y));let T=S=>{let E=ne("output",e[0].dataType,y.length),O=Ge(E.type.tensor),R=Rt(t,E.type.value,O),z=Q("x",e[0].dataType,c.length),M=Q("w",e[1].dataType,p.length),U=[z,M];s&&U.push(Q("b",e[2].dataType,e[2].dims.length));let L=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Bt(t,L),` ${S.registerUniforms(L).declareVariables(...U,E)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${E.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${h?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${h?1:2}], outputIndices[${h?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${E.type.value} = ${E.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = group_id * uniforms.w_shape[1] + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[${h?1:2}]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[${h?2:3}]) { continue; } let xVal = ${h?z.get("batch","xHeight","xWidth","input_channel"):z.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${M.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${o} ${R} ${E.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:C},getRunData:()=>({outputs:[{dims:r?r(y):y,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:_}),getShaderSource:T}},sc=(e,t,r)=>{let s=e.length>2,o=Le(r[3]),c=Le(r[2]),p=K.size(r)/o/c,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],y=[r[0],r[1],r[2],r[3]/o],$=[{type:12,data:p},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];jt(t,$),$.push(...se(l,h,y));let _=(c-1)*t.strides[1]+h[1],C=T=>{let S=ne("output",e[0].dataType,y.length,o),E=Ge(S.type.tensor),O=Rt(t,S.type.value,E),R=Q("x",e[0].dataType,l.length,o),z=Q("w",e[1].dataType,h.length,o),M=[R,z];s&&M.push(Q("b",e[2].dataType,e[2].dims,o));let U=s?"value += b[output_channel];":"",L=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Bt(t,L),` ${T.registerUniforms(L).declareVariables(...M,S)} ${T.mainStart()} ${T.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] / ${c}u; let col = (index1 % width1) * ${c}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<${R.type.value}, ${_}>; var values: array<${S.type.value}, ${c}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${_}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${R.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${R.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${z.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${c}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${c}u; i++) { var value = values[i]; ${U} ${O} ${S.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${o};${c};${_};${h[0]};${h[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:$}),getShaderSource:C}}});var ka,Zy,lc,Oa=ie(()=>{"use strict";Te();je();Si();ze();Jt();ka=(e,t,r,s,o=!1)=>{let c=e[0].dims,p=e[1].dims,l=c[c.length-2],h=p[p.length-1],y=c[c.length-1],$=Le(h),_=Le(y),C=Le(l),T=K.size(r)/$/C,S=e.length>2,E=s?s.slice(0,-2):r.slice(0,-2),R=[K.size(E),l,h],z=[{type:12,data:T},{type:12,data:l},{type:12,data:h},{type:12,data:y}];jt(t,z),z.push(...se(E,c,p)),S&&z.push(...se(e[2].dims)),z.push(...se(R));let M=U=>{let L=$n("batch_dims",e[0].dataType,E.length),F=Q("a",e[0].dataType,c.length,_),te=Q("b",e[1].dataType,p.length,$),J=ne("output",e[0].dataType,R.length,$),oe=Ge(J.type.tensor),le=Rt(t,J.type.value,oe),ge=[F,te],Z="";if(S){let ve=o?$:1;ge.push(Q("bias",e[2].dataType,e[2].dims.length,ve)),Z=`${o?`value += bias[col / ${ve}];`:`value += ${J.type.value}(bias[row + i]);`}`}let fe=c.slice(0,-2),we=p.slice(0,-2),ue=Hr(fe,E),me=Hr(we,E),Ee=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Bt(t,Ee);let ke=(ve,Ae)=>{let _e=ve.rank,et=ve.name;if(_e===2)return`var ${et}_indices = ${ve.type.indices}(0u, 0u);`;let ee=L.rank,ce=`var ${et}_indices: ${ve.type.indices};`;for(let Re=_e-2-1,rt=ee-1;Re>=0;Re--,rt--)ce+=` ${et}_indices[${Re}] = ${ee>1?`batch_indices[${rt}]`:"batch_indices"};`;return Ae.forEach(Re=>{ce+=` ${et}_indices[${Re}] = 0;`}),ce+=`${et}_indices[${_e-2}] = 0u; ${et}_indices[${_e-1}] = 0u;`,ce},Ce=()=>{let ve=`var a_data: ${F.type.value};`;for(let Ae=0;Ae<_;Ae++)ve+=` let b_data${Ae} = b[(b_offset + (k + ${Ae}) * uniforms.N + col) / ${$}];`;for(let Ae=0;Ae; for (var k: u32 = 0u; k < uniforms.K; k = k + ${_}) { ${Ce()} } for (var i = 0u; i < ${C}u; i++) { var value = values[i]; ${Z} ${le} let cur_indices = ${J.type.indices}(batch, row + i, col); let offset = ${J.indicesToOffset("cur_indices")}; ${J.setByOffset(`offset / ${$}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${$};${_};${C};${o}`,inputDependencies:S?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:z}),getShaderSource:M}},Zy=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.")},lc=e=>{Zy(e.inputs);let t=Ut.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&s<8?e.compute(ka(e.inputs,{activation:""},t)):e.compute(Rn(e.inputs,{activation:""},t))}});var jn,Pa,Jy,dc,za,e0,t0,Ra,Ea=ie(()=>{"use strict";je();oc();Si();uc();Jt();Oa();Lr();jn=(e,t,r,s,o,c)=>{let p=e[0],l=e.slice(c?1:2,c?3:4),h=l.length,y=t[0],_=t.slice(2).map((S,E)=>S+(S-1)*(r[E]-1)),T=l.map((S,E)=>S+s[E]+s[E+h]).map((S,E)=>Math.floor((S-_[E]+o[E])/o[E]));return T.splice(0,0,p),T.splice(c?3:1,0,y),T},Pa=[2,3,1,0],Jy=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*t.group;if(r!==s)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 o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},dc=(e,t)=>{let r=e.kernelShape.slice();for(let c=2;c{let t=kn(e),r=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,c=e.group,p=e.kernel_shape,l=e.pads,h=e.strides,y=e.w_is_const();return{autoPad:s,format:r,dilations:o,group:c,kernelShape:p,pads:l,strides:h,wIsConst:y,...t,cacheKey:`${e.format};${t.activation};`}},e0=(e,t,r)=>{let s=dc(r,t),o=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let te=jn(t[0].dims,t[1].dims,r.dilations,s.pads,r.strides,o),J=e.kernelCustomData.wT??e.compute(At(t[1],Pa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=J);let oe=[t[0],J];t.length===3&&oe.push(t[2]),e.compute(sc(oe,s,te),{inputs:oe})}else e.compute(Aa(t,s));return}let c=t.length===3,p=t[0].dims[o?1:2],l=t[0].dims[o?2:3],h=t[0].dims[o?3:1],y=t[1].dims[2],$=t[1].dims[3],_=jn(t[0].dims,t[1].dims,r.dilations,s.pads,r.strides,o),C=_[o?1:2],T=_[o?2:3],S=_[o?3:1],E=o&&y===p&&$===l&&r.pads[0]===0&&r.pads[1]===0;if(E||y===1&&$===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 F=_[0],te,J,oe,le=[];if(o){let fe=e.kernelCustomData.wT??e.compute(At(t[1],Pa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=fe),E){let we=p*l*h;te=t[0].reshape([1,F,we]),J=fe.reshape([1,we,S]),oe=[1,F,S]}else te=t[0].reshape([F,p*l,h]),J=fe.reshape([1,h,S]),oe=[F,C*T,S];le.push(te),le.push(J)}else te=t[0].reshape([F,h,p*l]),J=t[1].reshape([1,S,h]),oe=[F,S,C*T],le.push(J),le.push(te);c&&le.push(t[2]);let ge=oe[2],Z=le[0].dims[le[0].dims.length-1];ge<8&&Z<8?e.compute(ka(le,s,_,oe,o),{inputs:le}):e.compute(Rn(le,s,_,oe,o),{inputs:le});return}let O=!0,R=e.kernelCustomData.wT??e.compute(At(t[1],Pa),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=R);let z=[t[0],R];c&&z.push(t[2]);let M=o?C*T:S,U=o?S:C*T,L=y*$*h;e.compute(ac(z,s,_,M,U,L,c,O),{inputs:z})},t0=(e,t)=>{let r=t.format==="NHWC",s=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],c=[1].concat(t.strides),p=[1].concat(t.dilations),l=[1].concat(t.kernelShape),h=dc({...t,pads:o,strides:c,dilations:p,kernelShape:l},s);e.compute(Aa(s,h,y=>r?[y[0],y[2],y[3]]:[]))},Ra=(e,t)=>{Jy(e.inputs,t),e.inputs[0].dims.length===3?t0(e,t):e0(e,e.inputs,t)}});var r0,cc,pc=ie(()=>{"use strict";Te();Zt();ze();Jt();Pn();Ta();Si();r0=(e,t=!1,r,s,o=4)=>{let c=R=>{switch(R){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 ${s}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${R} is not supported.`)}},p=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,l=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,h=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",y=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",$=e?"row":"col",_=e?"col":"row",C=` let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${$} / outWidth; let outCol = ${$} % outWidth; let WRow = ${_} / (uniforms.filter_dims[1] * inChannels); let WCol = ${_} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${h}) || fract(xR) > 0.0) { return ${s}(0.0); } if (xC < 0.0 || xC >= f32(${y}) || fract(xC) > 0.0) { return ${s}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${_} % inChannels; ${p} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`,T=e?` let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${C} } return ${s}(0.0);`:` let col = colIn * ${o}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${C} } return ${s}(0.0);`,S=` let col = colIn * ${o}; let inChannels = ${e?"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 (${e?"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); ${c(o)} } return ${s}(0.0); `,E=Rt(r,s);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${s} { ${e?T:S} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${s} { ${e?S:T} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${s}) { let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${l} ${On(t)} ${E} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value; } }`},cc=(e,t,r,s,o,c,p,l)=>{let h=t.format==="NHWC",y=h?e[0].dims[3]:e[0].dims[1],$=r[0],_=h?r[2]:r[3],C=h?r[1]:r[2],T=h?r[3]:r[1],S=h&&y%4===0&&y%3&&T%4===0,E=h?T:_*C,O=h?_*C:T,R=[8,8,1],z=s<=8?[4,1,1]:[4,4,1],M=[Math.ceil(E/R[0]/z[0]),Math.ceil(O/R[1]/z[1]),Math.ceil($/R[2]/z[2])];qe("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${M}`);let U=S?4:1,L=Math.max(R[0]*U,R[1]),F=S?4:1,te=[t.kernelShape[h?1:2],t.kernelShape[h?2:3]],J=[te[0]+(t.dilations[0]<=1?0:(te[0]-1)*(t.dilations[0]-1)),te[1]+(t.dilations[1]<=1?0:(te[1]-1)*(t.dilations[1]-1))],oe=[J[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),J[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],le=[{type:6,data:s},{type:6,data:o},{type:6,data:c},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:te},{type:6,data:oe}];jt(t,le),le.push(...se(e[0].dims,e[1].dims));let ge=["rank","rank"];p&&(le.push(...se(e[2].dims)),ge.push("rank")),le.push(...se(r));let Z=fe=>{let we=Q("x",e[0].dataType,e[0].dims.length,F),ue=Q("w",e[1].dataType,e[1].dims.length,1),me=ne("result",e[0].dataType,r.length,F),Ee=[we,ue],ke="";if(p){let Ae=Q("bias",e[2].dataType,e[2].dims.length,F);Ee.push(Ae),ke+=` fn getBiasByOutputCoords(coords : vec4) -> ${Ae.type.value} { return bias[coords.${h?"w":"y"}${S?"/ 4":""}]; }`}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}];Bt(t,Ce);let ve=Ge(e[0].dataType,1);if(ve!=="f16"&&ve!=="f32")throw new Error(`elemType ${ve} is not supported.`);return` ${zn("uniforms.result_strides")} ${fe.registerUniforms(Ce).declareVariables(...Ee,me)}; ${ke} ${r0(h,p,t,we.type.value,U)} ${S?Ci(z,R,ve,void 0,!h,L):xi(z,R,ve,void 0,!h,L,!1,void 0,l)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${z};${R};${S}`,inputDependencies:ge},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:M[0],y:M[1],z:M[2]},programUniforms:le}),getShaderSource:Z}}});var i0,ja,fc=ie(()=>{"use strict";Te();Zt();je();ze();i0=(e,t,r,s,o,c=!1,p,l,h=!1)=>{let y=h?1:2,$=h?2:3,_=h?3:1,C=c?2:1,T=` fn setOutputAtIndex(flatIndex : u32, value : ${c?`vec4<${p}>`:p}) { result[flatIndex] = ${c?`vec4<${p}>`:p}(value); }`;s&&(T+=` fn getBiasByOutputCoords(coords : vec4) -> ${c?`vec4<${p}>`:p} { return bias[coords.${h?"w":"y"}${c?"/ 4":""}]; }`);let S=c?4:1,E=Q("W",t[1].dataType,t[1].dims.length,S),O=Q("Dy",t[0].dataType,t[0].dims.length,S),R=[O,E];s&&R.push(Q("bias",t[2].dataType,[r[_]].length,S));let z=ne("result",t[0].dataType,r.length,S),M=`{ let batch: u32 = ${o?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${o?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${o?"global_id.y":"workgroup_id.y"} * ${C}; let d1: u32 = ${o?"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, ${C}>; for (var i = 0; i < ${C}; i++) { dotProd[i] = vec4<${p}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${p}(dyCorner.x) + ${p}(wR)) / ${p}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${p}(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 = (${p}(dyCorner.y) + ${p}(wC)) / ${p}(uniforms.strides.y); let dyC2 = (${p}(dyCorner.y) + 1.0 + ${p}(wC)) / ${p}(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 >= ${p}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${p}(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 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${O.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${p}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${O.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${p}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${_}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${O.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${p}>(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 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${O.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${p}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${C}; i = i + 1) { let value = dotProd[i] + ${s?"bias[c+i]":`vec4<${p}>(0.0)`}; ${z.set("batch","r","c + i","d1","value")}; } }`,U=` let outputIndices = ${z.offsetToIndices("global_idx")}; let batch = ${z.indicesGet("outputIndices",0)}; let d1 = ${z.indicesGet("outputIndices",_)}; let r = ${z.indicesGet("outputIndices",y)}; let c = ${z.indicesGet("outputIndices",$)}; 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 = ${p}(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 = (${p}(dyRCorner) + ${p}(wR)) / ${p}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${p}(uniforms.Dy_shape[${y}]) || 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 = (${p}(dyCCorner) + ${p}(wC)) / ${p}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${p}(uniforms.Dy_shape[${$}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${h?O.get("batch","idyR","idyC","inputChannel"):O.get("batch","inputChannel","idyR","idyC")}; let wValue = ${E.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${s?"bias[d1]":`${p}(0.0)`}; ${z.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(l).declareVariables(...R,z)} ${T} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${c?M:U}}`},ja=(e,t,r)=>{let s=e.length>2,o=t.outputShape,c=K.size(o),p=[Math.ceil(c/64),1,1];qe("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${p}`);let l=t.format==="NHWC",h=["rank","rank"],y=[t.strides[0],t.strides[1]],$=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],_=[t.dilations[0],t.dilations[1]],C=[$[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),$[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],T=[C[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),C[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],S=!1,E=t.group,O=e[1].dims,R=O[0]/E,z=O[1],M=[{type:12,data:c},{type:12,data:y},{type:12,data:$},{type:12,data:_},{type:12,data:C},{type:6,data:T},{type:12,data:R},{type:12,data:z},...se(e[0].dims,e[1].dims)];s&&(M.push(...se(e[2].dims)),h.push("rank")),M.push(...se(o));let U=p[1]===1&&p[2]===1,L=F=>{let te=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:y.length},{name:"filter_dims",type:"u32",length:$.length},{name:"dilations",type:"u32",length:$.length},{name:"effective_filter_dims",type:"u32",length:C.length},{name:"pads",type:"i32",length:T.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],J=Ge(e[0].dataType);return`${i0(F,e,o,s,U,S,J,te,l)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:h},getRunData:()=>({dispatchGroup:{x:p[0],y:p[1],z:p[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:M}),getShaderSource:L}}});var n0,a0,o0,mc,hc,s0,u0,l0,d0,gc,yc=ie(()=>{"use strict";pc();fc();Jt();Lr();n0=(e,t,r,s,o,c)=>(e-1)*t+r+(s-1)*o+1-c,a0=(e,t,r,s,o)=>{let c=Math.floor(e/2);t==="SAME_UPPER"?(r[s]=c,r[o]=e-c):t==="SAME_LOWER"&&(r[s]=e-c,r[o]=c)},o0=(e,t,r,s,o,c,p,l,h,y)=>{let $=e.length-2,_=y.length===0;if(h.length===0)for(let S=0;S<$;++S)h.push(0);let C=e[0],T=t[l?3:1]*o;for(let S=0,E=e.length-$-(l?1:0);S<$;++S,++E){let O=e[E],R=_?O*p[S]:y[S],z=n0(O,p[S],c[S],t[E],r[S],R);a0(z,s,c,S,S+$),_&&y.push(p[S]*(O-1)+h[S]+(t[E]-1)*r[S]+1-c[S]-c[S+$])}y.splice(0,0,C),y.splice(l?3:1,0,T)},mc=(e,t)=>{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((_,C)=>_*C,1)===0){r.length=0;for(let _=2;__+C,0)===0){let _=t[0].dims.length-2;h=new Array(_).fill(1)}let y=e.strides.slice();if(y.reduce((_,C)=>_+C,0)===0){let _=t[0].dims.length-2;y=new Array(_).fill(1)}o0(l,r,h,e.autoPad,e.group,o,y,s,p,c);let $=Object.assign({},e);return Object.assign($,{kernelShape:r,pads:o,outputPadding:p,outputShape:c,dilations:h,strides:y}),$},hc=e=>{let t=kn(e),r=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,c=e.group,p=e.kernelShape,l=e.pads,h=e.strides,y=e.wIsConst(),$=e.outputPadding,_=e.outputShape;return{autoPad:s,format:r,dilations:o,group:c,kernelShape:p,outputPadding:$,outputShape:_,pads:l,strides:h,wIsConst:y,...t,cacheKey:`${e.format};${t.activation};`}},s0=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(r!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let c=e[0].dims.length-2;if(t.dilations.reduce(($,_)=>$+_,0)>0&&t.dilations.length!==c)throw new Error(`dilations should be ${c}D`);if(t.strides.reduce(($,_)=>$+_,0)>0&&t.strides.length!==c)throw new Error(`strides should be ${c}D`);if(t.pads.reduce(($,_)=>$+_,0)>0&&t.pads.length!==c*2)throw new Error(`pads should be ${c*2}D`);if(t.outputPadding.length!==c&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${c}D`);if(t.kernelShape.reduce(($,_)=>$+_,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},u0=[2,3,1,0],l0=(e,t,r)=>{let s=mc(r,t),o=r.format==="NHWC",c=s.outputShape,p=c[o?3:1],l=t[0].dims[o?3:1];if(s.group!==1||p===1&&l===1){e.compute(ja(t,s));return}let h=c[o?1:2],y=c[o?2:3],$=t[1].dims[2],_=t[1].dims[3],C=o?h*y:p,T=o?p:h*y,S=$*_*l,E=!0,O=e.kernelCustomData.wT??e.compute(At(t[1],u0),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O);let R=[t[0],O],z=t.length===3;z&&(!o&&t[2].dims.length===1?R.push(t[2].reshape([t[2].dims[0],1,1])):R.push(t[2])),e.compute(cc(R,s,c,C,T,S,z,E),{inputs:R})},d0=(e,t)=>{let r=t.format==="NHWC",s=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let c=t.dilations;(c.length===0||c[0]===0)&&(c=[1]);let p=t.strides;(p.length===0||p[0]===0)&&(p=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],p=[1].concat(p),c=[1].concat(c),o=[1].concat(o);let h=mc({...t,pads:l,strides:p,dilations:c,kernelShape:o},s);e.compute(ja(s,h,y=>r?[y[0],y[2],y[3]]:[y[0],y[1],y[3]]))},gc=(e,t)=>{s0(e.inputs,t),e.inputs[0].dims.length===3?d0(e,t):l0(e,e.inputs,t)}});var c0,vc,bc,wc=ie(()=>{"use strict";Te();je();nt();ze();c0=(e,t,r,s)=>{let o=K.size(t),c=t.length,p=Q("input",e,c),l=ne("output",e,c),h=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),y=K.normalizeAxis(h,c),$=_=>{let C=` i32(${p.indicesGet("inputIndices","uniforms.axis")}) `,T=Se("uniforms.input_shape","uniforms.axis",c),S=s.reverse?C+(s.exclusive?" + 1":""):"0",E=s.reverse?T:C+(s.exclusive?"":" + 1");return` ${_.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(p,l)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${l.offsetToIndices("global_idx")}; var sum = ${l.type.value}(0); let first : i32 = ${S}; let last : i32 = ${E}; for (var i : i32 = first; i < last; i++) { ${p.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${p.getByIndices("inputIndices")}; } ${l.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:y},...se(t,t)]}),getShaderSource:$}},vc=(e,t)=>{let r=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(c0(s,r,o,t),{inputs:[0]})},bc=e=>{let t=e.exclusive===1,r=e.reverse===1;return Oe({exclusive:t,reverse:r})}});var p0,f0,m0,_c,$c,Cc=ie(()=>{"use strict";Te();je();nt();ze();p0=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.")},f0=(e,t,r,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let c=0;c{let r,s,o,c,p,l,h=t.format==="NHWC",y=t.blocksize,$=t.mode==="DCR";h?([r,s,o,c]=e.dims,p=$?[r,s,o,y,y,c/y**2]:[r,s,o,c/y**2,y,y],l=$?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,s,o,c]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],p=$?[r,y,y,c/y**2,s,o]:[r,c/y**2,y,y,s,o],l=$?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let _=e.reshape(p),C=_.dims.length,T=e.dataType,S=Q("a",T,C),E=ne("output",T,C),O=R=>` ${R.registerUniform("output_size","u32").declareVariables(S,E)} ${f0(l,C,S,E)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${E.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${E.setByOffset("global_idx",S.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:R=>{let z=h?[r,s*y,o*y,c/y**2]:[r,c/y**2,s*y,o*y],M=K.size(z),U=_.dims,L=K.sortBasedOnPerm(U,l);return{outputs:[{dims:z,dataType:R[0].dataType}],dispatchGroup:{x:Math.ceil(M/64)},programUniforms:[{type:12,data:M},...se(U,L)]}},getShaderSource:O}},_c=(e,t)=>{p0(e.inputs),e.compute(m0(e.inputs[0],t))},$c=e=>Oe({blocksize:e.blocksize,mode:e.mode,format:e.format})});var Ba,Bn,xc,h0,g0,Da,Ma,Sc,y0,Ic,Tc,Ac=ie(()=>{"use strict";Te();je();nt();ze();Ba="[a-zA-Z]|\\.\\.\\.",Bn="("+Ba+")+",xc="^"+Bn+"$",h0="("+Bn+",)*"+Bn,g0="^"+h0+"$",Da=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let s=this.symbolToIndices.get(t);s===void 0?s=[r]:s.push(r),this.symbolToIndices.set(t,s)}},Ma=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,o]=r.includes("->")?r.split("->",2):[r,""];if(!s.match(RegExp(g0)))throw new Error("Invalid LHS term");if(s.split(",").forEach((l,h)=>{let y=t[h].dims.slice();if(!l.match(RegExp(xc)))throw new Error("Invalid LHS term");let $=this.processTerm(l,!0,y,h);this.lhs.push($)}),o==="")o+=[...this.symbolToInfo.entries()].filter(([l,h])=>h.count===1||l==="...").map(([l])=>l).join("");else if(!o.match(RegExp(Bn)))throw new Error("Invalid RHS");o.match(RegExp(Ba,"g"))?.forEach(l=>{if(l==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let h=this.symbolToInfo.get(l);if(h===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(h.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,s){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error("Dimension mismatch");o.count++,o.inputIndices.push(s)}else o={count:1,dimValue:r,inputIndices:[s]};this.symbolToInfo.set(t,o)}processTerm(t,r,s,o=-1){let c=s.length,p=!1,l=[],h=0;if(!t.match(RegExp(xc))&&!r&&t!=="")throw new Error("Invalid LHS term");let y=t.match(RegExp(Ba,"g")),$=new Da(o);return y?.forEach((_,C)=>{if(_==="..."){if(p)throw new Error("Only one ellipsis is allowed per input term");p=!0;let T=c-y.length+1;if(T<0)throw new Error("Ellipsis out of bounds");if(l=s.slice(h,h+T),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let S=0;Se+"_max",y0=(e,t,r,s)=>{let c=e.map($=>$.length).map(($,_)=>Q(`input${_}`,t,$)),p=K.size(s),l=ne("output",t,s.length),h=[...r.symbolToInfo.keys()].filter($=>!r.rhs.symbolToIndices.has($)),y=$=>{let _=[],C="var prod = 1.0;",T="var sum = 0.0;",S="sum += prod;",E=[],O=[],R=[],z=[],M=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((L,F)=>{if(r.rhs.symbolToIndices.has(F)){let te=r.rhs.symbolToIndices.get(F)?.[0];te!==void 0&&r.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,l.indicesGet("outputIndices",te))}`)})}})}else r.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}`)}`)}),z.push(`prod *= ${c[J].getByIndices(`input${J}Indices`)};`)}}),O.push(`for(var ${F}: u32 = 0; ${F} < uniforms.${Sc(F)}; ${F}++) {`),R.push("}")});let U=M?[..._,`let sum = ${c.map((L,F)=>L.getByIndices(`input${F}Indices`)).join(" * ")};`]:[..._,T,...O,...E,C,...z,S,...R];return` ${$.registerUniforms(h.map(L=>({name:`${Sc(L)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...c,l)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${l.offsetToIndices("global_idx")}; ${c.map((L,F)=>`var input${F}Indices: ${c[F].type.indices};`).join(` `)} ${U.join(` `)}; ${l.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let $=h.filter(C=>r.symbolToInfo.has(C)).map(C=>({type:12,data:r.symbolToInfo.get(C)?.dimValue||0}));$.push({type:12,data:p});let _=e.map((C,T)=>[...se(C)]).reduce((C,T)=>C.concat(T),$);return _.push(...se(s)),{outputs:[{dims:s,dataType:t}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}},getShaderSource:y}},Ic=(e,t)=>{let r=new Ma(e.inputs,t.equation),s=r.outputDims,o=e.inputs.map((c,p)=>c.dims);e.compute(y0(o,e.inputs[0].dataType,r,s))},Tc=e=>{let t=e.equation.replace(/\s+/g,"");return Oe({equation:t})}});var v0,Ec,b0,w0,kc,Oc=ie(()=>{"use strict";Te();je();ze();v0=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),s=r.length{let r=e.length-t.length,s=[];for(let o=0;oe.length>t.length?Ec(e,t):Ec(t,e),w0=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),s=b0(t,r),o=e[0].dataType,c=o===9?4:1,p=Math.ceil(K.size(s)/c),l=y=>{let $=Q("input",o,t.length,c),_=ne("output",o,s.length,c),C;if(o===9){let T=(S,E,O="")=>` let outputIndices${E} = ${_.offsetToIndices(`outputOffset + ${E}u`)}; let offset${E} = ${$.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; let index${E} = offset${E} / 4u; let component${E} = offset${E} % 4u; ${S}[${E}] = ${O}(${$.getByOffset(`index${E}`)}[component${E}]); `;C=` let outputOffset = global_idx * ${c}; var data = vec4(0); ${T("data",0,"u32")} ${T("data",1,"u32")} ${T("data",2,"u32")} ${T("data",3,"u32")} ${_.setByOffset("global_idx","data")} }`}else C=` let outputIndices = ${_.offsetToIndices("global_idx")}; let inputOffset = ${$.broadcastedIndicesToOffset("outputIndices",_)}; ${_.setByOffset("global_idx",$.getByOffset("inputOffset"))} }`;return` ${y.registerUniform("vec_size","u32").declareVariables($,_)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${C}`},h=[{type:12,data:p},...se(t,s)];return{name:"Expand",shaderCache:{hint:`${s.length}`,inputDependencies:["rank"]},getShaderSource:l,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h})}},kc=e=>{v0(e.inputs),e.compute(w0(e.inputs),{inputs:[0]})}});var _0,Pc,zc=ie(()=>{"use strict";Te();je();ze();En();_0=e=>{let t=e[0].dataType,r=K.size(e[0].dims),s=K.size(e[1].dims),o=s%4===0,c=p=>{let l=Q("x",t,[1],4),h=Q("bias",t,[1],4),y=ne("y",t,[1],4),$=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],_=T=>` let bias${T}_offset: u32 = (global_idx * 4 + ${T}) % uniforms.bias_size; let bias${T} = ${h.getByOffset(`bias${T}_offset / 4`)}[bias${T}_offset % 4];`,C=o?` let bias = ${h.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${_(0)}${_(1)}${_(2)}${_(3)} let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${p.registerUniforms($).declareVariables(l,h,y)} ${Sa(ut(t))} ${p.mainStart(gr)} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${l.getByOffset("global_idx")}; ${C} let x_in = x + bias; ${y.setByOffset("global_idx",Ia("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:c,getRunData:p=>({outputs:[{dims:p[0].dims,dataType:p[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(r/gr/4)}})}},Pc=e=>{e.inputs.length<2||K.size(e.inputs[1].dims)===0?Nd(e):e.compute(_0(e.inputs))}});var $0,C0,Rc,jc,Bc=ie(()=>{"use strict";Te();je();nt();ze();$0=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},C0=(e,t)=>{let r=e[0].dims,s=e[1].dims,o=r.length,c=K.normalizeAxis(t.axis,o),p=r.slice(0);p.splice(c,1,...s);let l=r[c],h=e[0].dataType===9?4:1,y=Math.ceil(K.size(p)/h),$=[{type:12,data:y},{type:6,data:l},{type:12,data:c},...se(e[0].dims,e[1].dims,p)],_=C=>{let T=Q("data",e[0].dataType,e[0].dims.length,h),S=Q("inputIndices",e[1].dataType,e[1].dims.length),E=ne("output",e[0].dataType,p.length,h),O=z=>{let M=s.length,U=`var indicesIndices${z} = ${S.type.indices}(0);`;for(let L=0;L1?`indicesIndices${z}[${L}]`:`indicesIndices${z}`} = ${p.length>1?`outputIndices${z}[uniforms.axis + ${L}]`:`outputIndices${z}`};`;U+=` var idx${z} = ${S.getByIndices(`indicesIndices${z}`)}; if (idx${z} < 0) { idx${z} = idx${z} + uniforms.axisDimLimit; } var dataIndices${z} : ${T.type.indices}; `;for(let L=0,F=0;L1?`dataIndices${z}[${L}]`:`dataIndices${z}`} = u32(idx${z});`,F+=M):(U+=`${o>1?`dataIndices${z}[${L}]`:`dataIndices${z}`} = ${p.length>1?`outputIndices${z}[${F}]`:`outputIndices${z}`};`,F++);return U},R;if(e[0].dataType===9){let z=(M,U,L="")=>` let outputIndices${U} = ${E.offsetToIndices(`outputOffset + ${U}u`)}; ${O(U)}; let offset${U} = ${T.indicesToOffset(`dataIndices${U}`)}; let index${U} = offset${U} / 4u; let component${U} = offset${U} % 4u; ${M}[${U}] = ${L}(${T.getByOffset(`index${U}`)}[component${U}]); `;R=` let outputOffset = global_idx * ${h}; var value = vec4(0); ${z("value",0,"u32")} ${z("value",1,"u32")} ${z("value",2,"u32")} ${z("value",3,"u32")} ${E.setByOffset("global_idx","value")} `}else R=` let outputIndices = ${E.offsetToIndices("global_idx")}; ${O("")}; let value = ${T.getByIndices("dataIndices")}; ${E.setByOffset("global_idx","value")}; `;return` ${C.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(T,S,E)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${R} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:$}),getShaderSource:_}},Rc=e=>Oe({axis:e.axis}),jc=(e,t)=>{let r=e.inputs;$0(r),e.compute(C0(e.inputs,t))}});var x0,S0,Dc,Mc,Uc=ie(()=>{"use strict";Te();je();nt();ze();x0=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},S0=(e,t)=>{let r=e[0].dims,s=e[0].dataType,o=r.length,c=e[1].dims,p=e[1].dataType,l=K.normalizeAxis(t.axis,o),h=r[l],y=c.slice(0),$=K.size(y),_=Q("input",s,o),C=Q("indicesInput",p,c.length),T=ne("output",s,y.length),S=[{type:12,data:$},{type:6,data:h},{type:12,data:l}];return S.push(...se(r,c,y)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:y,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:S}),getShaderSource:R=>` ${R.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,C,T)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${T.offsetToIndices("global_idx")}; var idx = ${C.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${_.type.indices}(outputIndices); ${_.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${_.getByIndices("inputIndices")}; ${T.setByOffset("global_idx","value")}; }`}},Dc=e=>Oe({axis:e.axis}),Mc=(e,t)=>{let r=e.inputs;x0(r),e.compute(S0(e.inputs,t))}});var I0,T0,Wc,Nc,Vc=ie(()=>{"use strict";Te();je();ze();I0=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")},T0=(e,t)=>{let r=e[0].dims.slice(),s=e[1].dims.slice(),[o,c,p]=bn.getShapeOfGemmResult(r,t.transA,s,t.transB,e.length===3?e[2].dims:void 0),l=[o,c];if(!l)throw new Error("Can't use gemm on the given tensors");let h=K.size(l),y=[{type:12,data:h},{type:12,data:o},{type:12,data:c},{type:12,data:p},{type:1,data:t.alpha},{type:1,data:t.beta}],$=["type","type"];e.length===3&&(y.push(...se(e[2].dims)),$.push("rank")),y.push(...se(l));let _=C=>{let T="";t.transA&&t.transB?T="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?T="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?T="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(T="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=t.alpha===1?"":"value *= uniforms.alpha;",E=Q("a",e[0].dataType,e[0].dims),O=Q("b",e[1].dataType,e[1].dims),R=E.type.value,z=null,M=[E,O];e.length===3&&(z=Q("c",e[2].dataType,e[2].dims.length),M.push(z));let U=ne("output",e[0].dataType,l.length);M.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` ${C.registerUniforms(L).declareVariables(...M)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${R}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${T} } ${S} ${(()=>z!=null?`let cOffset = ${z.broadcastedIndicesToOffset("vec2(m, n)",U)}; value += ${R}(uniforms.beta) * ${z.getByOffset("cOffset")};`:"")()} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:y}),getShaderSource:_}},Wc=e=>{let t=e.transA,r=e.transB,s=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Nc=(e,t)=>{I0(e.inputs),e.compute(T0(e.inputs,t))}});var A0,E0,k0,Gc,Hc=ie(()=>{"use strict";Te();je();ze();A0=(e,t)=>{let r=e[0].dims,s=r,o=2,c=K.sizeToDimension(r,o),p=K.sizeFromDimension(r,o),l=Le(p),h=p/l,y=[r[0],r[1],h],$=["rank","type","type"],_=[{type:12,data:p},{type:12,data:h}];_.push(...se(y,y));let C=T=>{let S=Q("x",e[0].dataType,y.length,l),E=Q("scale",e[1].dataType,e[1].dims),O=Q("bias",e[2].dataType,e[2].dims),R=ne("output",e[0].dataType,y.length,l),z=[S,E,O,R],M=S.type.value,U=l===1?"f32":`vec${l}`,L=64,F=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${U}, ${L}>; const workgroupSize = ${L}u; ${T.registerUniforms(F).declareVariables(...z)} ${T.mainStart(L)} let norm = global_idx / workgroupSize; let batch = norm / uniforms.x_shape[1]; let channel = norm % uniforms.x_shape[1]; let localIndex = local_id.x; // initialize workgroup memory var initial = ${U}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${U}(${S.get("batch","channel","h")}); } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the mean of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { meanShared = ${zt("workgroupShared[0]",l)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${U}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${U}(${S.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 = ${zt("workgroupShared[0]",l)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); let channelScale = invStdDev * f32(${E.getByOffset("channel")}); let channelShift = f32(${O.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${S.get("batch","channel","h")} * ${M}(${U}(channelScale)) + ${M}(${U}(channelShift)); ${R.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${l}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:c},programUniforms:_}),getShaderSource:C}},E0=(e,t,r,s,o,c,p,l)=>{let h=Le(p),y=64,$=h===1?"vec2f":`mat2x${h}f`,_=h===1?"f32":`vec${h}f`,C=(F,te)=>`${$}(${F}, ${te})`,T=o*p/h,S=Math.ceil(c/y),E=["type"],O=[{type:12,data:S},{type:12,data:c},{type:12,data:Math.floor(p/h)},{type:12,data:Math.floor(c*p/h)}],R=F=>{let te=Q("input",t.dataType,t.dims,h);return` ${F.declareVariables(te)} @group(0) @binding(1) var output : array<${$}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${F.mainStart(y)} let currentImageNumber = global_idx / ${y} / uniforms.C; let currentChannelNumber = (global_idx / ${y}) % 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 = ${Pt("f32",h)}; var squaredSum = ${Pt("f32",h)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${_}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${C("sum","squaredSum")}; }`},z=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${h}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:[o,p,y,2],dataType:1}],dispatchGroup:{x:o*p/h},programUniforms:O}),getShaderSource:R},{inputs:[t],outputs:[-1]})[0],M=[{type:12,data:T},{type:12,data:c},{type:12,data:Math.floor(p/h)},{type:12,data:Math.floor(y*p/h)}],U=["type","type","type"],L=F=>{let te=Q("scale",r.dataType,r.dims,h),J=Q("bias",s.dataType,s.dims,h);return` @group(0) @binding(0) var input : array<${$}>; @group(0) @binding(1) var scale : array<${te.type.storage}>; @group(0) @binding(2) var bias : array<${J.type.storage}>; @group(0) @binding(3) var output : array<${$}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${F.mainStart()} ${F.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 = ${Pt("f32",h)}; var squaredSum = ${Pt("f32",h)}; for (var i: u32 = 0; i < min(${y}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${y}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${l})); let channelScale = invStdDev * ${_}(scale[currentChannelNumber]); let channelShift = ${_}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${C("channelScale","channelShift")}; }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${h};${l}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:[o,p,2],dataType:1}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:M}),getShaderSource:L},{inputs:[z,r,s],outputs:[-1]})[0]},k0=(e,t,r)=>{let s=t[0].dims,o=s,c=s[0],p=s[s.length-1],l=K.sizeFromDimension(s,1)/p,h=Le(p),y=K.size(o)/h,$=[{type:12,data:l},{type:12,data:Math.floor(p/h)}],_=["type","type"],C=E0(e,t[0],t[1],t[2],c,l,p,r.epsilon),T=S=>{let E=Ge(t[0].dataType),O=h===1?"vec2f":`mat2x${h}f`,R=h===1?E:`vec${h}<${E}>`,z=Q("input",t[0].dataType,t[0].dims,h),M=ne("output",t[0].dataType,o,h);return` @group(0) @binding(0) var input : array<${z.type.storage}>; @group(0) @binding(1) var scaleInput : array<${O}>; @group(0) @binding(2) var output : array<${M.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${S.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], ${R}(scale[0]), ${R}(scale[1])); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${h}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:$}),getShaderSource:T},{inputs:[t[0],C]})},Gc=(e,t)=>{t.format==="NHWC"?k0(e,e.inputs,t):e.compute(A0(e.inputs,t))}});var O0,P0,Lc,Fc=ie(()=>{"use strict";Te();je();ze();O0=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},P0=(e,t,r)=>{let s=t.simplified,o=e[0].dims,c=e[1],p=!s&&e[2],l=o,h=K.normalizeAxis(t.axis,o.length),y=K.sizeToDimension(o,h),$=K.sizeFromDimension(o,h),_=K.size(c.dims),C=p?K.size(p.dims):0;if(_!==$||p&&C!==$)throw new Error(`Size of X.shape()[axis:] == ${$}. Size of scale and bias (if provided) must match this. Got scale size of ${_} and bias size of ${C}`);let T=[];for(let L=0;L1,z=r>2,M=L=>{let F=Ge(e[0].dataType),te=[Q("x",e[0].dataType,e[0].dims,S),Q("scale",c.dataType,c.dims,S)];p&&te.push(Q("bias",p.dataType,p.dims,S)),te.push(ne("output",e[0].dataType,l,S)),R&&te.push(ne("mean_data_output",1,T)),z&&te.push(ne("inv_std_output",1,T));let J=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${L.registerUniforms(J).declareVariables(...te)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Pt("f32",S)}; var mean_square_vector = ${Pt("f32",S)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${yr(F,S,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${zt("mean_vector",S)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${zt("mean_square_vector",S)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${yr(F,S,"x[j + offset]")}; let f32scale = ${yr(F,S,"scale[j]")}; output[j + offset] = ${te[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale ${p?`+ ${yr(F,S,"bias[j]")}`:""} ); } ${R?"mean_data_output[global_idx] = mean":""}; ${z?"inv_std_output[global_idx] = inv_std_dev":""}; }`},U=[{dims:l,dataType:e[0].dataType}];return R&&U.push({dims:T,dataType:1}),z&&U.push({dims:T,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${S};${r};${s}`,inputDependencies:E},getRunData:()=>({outputs:U,dispatchGroup:{x:Math.ceil(y/64)},programUniforms:O}),getShaderSource:M}},Lc=(e,t)=>{O0(e.inputs),e.compute(P0(e.inputs,t,e.outputCount))}});var z0,R0,qc,Kc,Yc=ie(()=>{"use strict";Te();je();nt();ze();z0=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],s=r.dims.length;if(r.dims[s-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),c=t.blockSize/8*t.bits,p=e[1];if(!K.areEqual(p.dims,[t.n,o,c]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let h=e[2].dims;if(K.size(h)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let $=e[3].dims,_=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(K.size($)!==_)throw new Error("zeroPoints input size error.")}},R0=(e,t,r,s)=>{let o=e[0].dims,c=o.length,p=Math.floor((t.k+t.blockSize-1)/t.blockSize),l=o[c-2],h=t.k,y=t.n,$=o.slice(0,c-2),_=K.size($),T=t.blockSize/8*t.bits/4,S=e[0].dataType,E=Le(l),O=Le(t.k),R=Le(T),z=mr(S),M=l*p*z,U=Math.floor(s/M),L=p<=r[0]&&U>0,F=!L||U>=4?Le(y):U>=2&&Le(y)>=2?2:1,te=$.concat([l,y]),J=K.size(te)/F/E,oe=L?[]:[{type:12,data:J},{type:12,data:t.blockSize}],le=[_,l,h/O],ge=K.convertShape(e[1].dims).slice();ge.splice(-1,1,T/R),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 Z=[_,l,y/F];oe.push(...se(Z));let fe=we=>{let ue=le.length,me=Q("a",e[0].dataType,ue,O),Ee=Q("b",12,ge.length,R),ke=Q("scales",e[2].dataType,e[2].dims.length),Ce=[me,Ee,ke],ve=e.length===4?Q("zero_points",12,e[3].dims.length):void 0;ve&&Ce.push(ve);let Ae=Z.length,_e=ne("output",e[0].dataType,Ae,F),et=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],ee=Ge(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.`)}})(),Re=` for (var word: u32 = 0; word < ${T}; word += ${R}) { ${Ee.indicesSet("b_indices","2","word")}; let b_data = ${Ee.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${R}; i++) { let b_value: u32 = ${R===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 = ${ce}(${Array.from({length:4},(Qe,Ye)=>`${ee}(b_value_lower[${Ye}]), ${ee}(b_value_upper[${Ye}])`).join(", ")}); let b_dequantized_values = ${(()=>O===1?`${ce}(${Array.from({length:8},(Qe,Ye)=>`(b_quantized_values[${Ye}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ce}(${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 < ${L?l:E}u; m++) { ${me.indicesSet("a_indices",ue-2,L?"m":`row * ${E} + m`)}; ${me.indicesSet("a_indices",ue-1,"word_offset")}; var input_offset = ${me.indicesToOffset("a_indices")}; var a_data: ${ce}; for (var j: u32 = 0; j < ${8/O}; j++) { a_data[j] = ${me.getByOffset("input_offset")}; input_offset++; } ${L?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${F>1?"[c]":""} += ${Array.from({length:8/O},(Qe,Ye)=>`${O===1?`a_data[${Ye}] * b_dequantized_values[${Ye}]`:`dot(a_data[${Ye}], b_dequantized_values[${Ye}])`}`).join(" + ")}; } word_offset += ${8/O}; } }`,rt=ve?` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${ve.getByOffset("zero_point_index")}; }`:"";return L?` var workgroup_shared: array<${_e.type.value}, ${l*p}>; ${we.declareVariables(...Ce,_e)} ${we.mainStart([p,1,1])} var a_indices: ${me.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${me.indicesSet("a_indices","0","batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${F}; c++) { let col_times_components_plus_c = col * ${F} + c; ${ve?` var zero_point_bytes_per_col: u32 = (${p} + 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 = ${ve.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} var b_indices: ${Ee.type.indices}; ${Ee.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 * ${p} + block; let scale = ${ke.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${ee}(${ve?"(zero_point_word) & 0xFu":8}); ${Ee.indicesSet("b_indices","1","block")}; var word_offset: u32 = block * ${t.blockSize/O}; var workgroup_shared_offset: u32 = block * ${l}; ${Re} } workgroupBarrier(); if (local_id.x == 0u) { var output_indices: ${_e.type.indices}; ${_e.indicesSet("output_indices","0","batch")}; ${_e.indicesSet("output_indices",Ae-1,"col")}; ${_e.indicesSet("output_indices",Ae-2,"0")}; var output_offset = ${_e.indicesToOffset("output_indices")}; for (var m: u32 = 0u; m < ${l}u; m++) { var output_value: ${_e.type.value} = ${_e.type.value}(0); var workgroup_shared_offset: u32 = m; for (var b: u32 = 0u; b < ${p}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${l}; } ${_e.setByOffset("output_offset","output_value")}; output_offset += ${y/F}; } } }`:` ${we.registerUniforms(et).declareVariables(...Ce,_e)} ${we.mainStart()} ${we.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${_e.type.value}, ${E}>; var output_indices = ${_e.offsetToIndices("global_idx")}; var col = ${_e.indicesGet("output_indices",Ae-1)}; var row = ${_e.indicesGet("output_indices",Ae-2)}; var a_indices: ${me.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 ${ve?` var zero_point_abs_offset = col * ${F} * ((${p} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${ve.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} var scale_index = col * ${p*F}; var b_indices: ${Ee.type.indices}; for (var c: u32 = 0; c < ${F}; c++) { ${Ee.indicesSet("b_indices","0",`col * ${F} + c`)}; var block_offset: u32 = 0; for (var block: u32 = 0; block < ${p}; block++) { // The scale and zero points are computed per block. let scale = ${ke.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${ee}(${ve?"extractBits(zero_point_word, zero_point_offset, 4)":8}); ${Ee.indicesSet("b_indices","1","block")}; var word_offset: u32 = block_offset; ${Re} scale_index++; ${rt} block_offset += uniforms.block_size / ${O}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${ve?`if (zero_point_offset % 8 > 0) { ${rt} }`:""} } for (var k: u32 = 0u; k < ${E}u; k++) { ${_e.indicesSet("output_indices",Ae-2,`${E} * row + k`)}; ${_e.setByIndices("output_indices","output_values[k]")} } }`};return{name:L?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${l};${S};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:te,dataType:S}],name:L?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:L?{x:1,y:Math.ceil(y/F),z:_}:{x:Math.ceil(J/64)},programUniforms:oe}),getShaderSource:fe}},qc=(e,t)=>{z0(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),s=e.getMaxComputeWorkgroupStoragesize();e.compute(R0(e.inputs,t,r,s))},Kc=e=>Oe(e)});var gt,j0,Xc,Qc,B0,Ua,Zc,Jc=ie(()=>{"use strict";Te();je();nt();vn();xa();ze();Lr();gt=(e,t)=>e.length>t&&e[t].dims.length>0&&K.size(e[t].dims)>0?e[t]:void 0,j0=(e,t)=>{let r=e[0],s=gt(e,1),o=gt(e,2),c=gt(e,3),p=gt(e,4),l=gt(e,5),h=gt(e,6),y=gt(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let $=!1,_=r.dims[0],C=r.dims[1],T=r.dims.length===3?$?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],S=C,E=0,O=0,R=Math.floor(T/t.numHeads);if(h&&y){if(h.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(h.dims[0]!==_||h.dims[1]!==t.numHeads||h.dims[3]!==R)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(y.dims[0]!==_||y.dims[1]!==t.numHeads||y.dims[3]!==R)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[2]!==y.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(y.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');E=h.dims[2],O=h.dims[2]}else if(h||y)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let z;if(s){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');z=2,S=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==t.numHeads||s.dims[3]!==2||s.dims[4]!==R)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');z=5,S=s.dims[1]}else{if(s.dims[1]!==t.numHeads||s.dims[3]!==R)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');z=0,S=s.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');z=3}if(c){if(c.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(o&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let M=0;if(p){M=8;let J=p.dims;throw J.length===1?J[0]===_?M=1:J[0]===3*_+2&&(M=3):J.length===2&&J[0]===_&&J[1]===S&&(M=5),M===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=T;if(o){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(S!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');L=o.dims[2]}else{if(S!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');L=o.dims[1]*o.dims[3],U=!0}}let F=E+S,te=!1;if(p)throw new Error("Key padding mask is not supported");if(l){if(l.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(l.dims[0]!==_&&l.dims[0]!==1||l.dims[1]!==t.numHeads||l.dims[2]!==C||l.dims[3]!==F)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:_,sequenceLength:C,pastSequenceLength:E,kvSequenceLength:S,totalSequenceLength:F,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:T,vHiddenSize:L,headSize:R,vHeadSize:Math.floor(L/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:M,scale:t.scale,broadcastResPosBias:te,passPastInKv:U,qkvFormat:z}},Xc=e=>Oe({...e}),Qc=Oe({perm:[0,2,1,3]}),B0=(e,t,r,s,o,c,p)=>{let l=[s,o,c],h=K.size(l),y=[{type:12,data:h},{type:12,data:p},{type:12,data:c}],$=_=>{let C=ne("qkv_with_bias",t.dataType,l),T=Q("qkv",t.dataType,l),S=Q("bias",r.dataType,l),E=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${_.registerUniforms(E).declareVariables(T,S,C)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:y}),getShaderSource:$},{inputs:[t,r],outputs:[-1]})[0]},Ua=(e,t,r,s,o,c,p,l)=>{let h=c;if(p){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return h=B0(e,c,p,t,s,r*o,l),h=h.reshape([t,s,r,o]),e.compute(At(h,Qc.perm),{inputs:[h],outputs:[-1]})[0]}else return c.dims.length===3&&(h=c.reshape([t,s,r,o])),e.compute(At(h,Qc.perm),{inputs:[h],outputs:[-1]})[0]},Zc=(e,t)=>{let r=j0(e.inputs,t),s=e.inputs[0],o=gt(e.inputs,1),c=gt(e.inputs,2),p=gt(e.inputs,3),l=gt(e.inputs,4),h=gt(e.inputs,5),y=gt(e.inputs,6),$=gt(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let _=o&&c&&o.dims.length===4&&c.dims.length===4,C=Ua(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,s,p,0);if(_)return In(e,C,o,c,l,void 0,y,$,h,r,t);if(!o||!c)throw new Error("key and value must be provided");let T=Ua(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,p,r.hiddenSize),S=Ua(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,c,p,2*r.hiddenSize);In(e,C,T,S,l,void 0,y,$,h,r,t)}});var D0,M0,U0,W0,N0,V0,G0,H0,ep,tp=ie(()=>{"use strict";Te();je();ze();D0=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},M0=(e,t,r)=>{let s="";for(let o=t-1;o>=0;--o)s+=` k = i32(${e.indicesGet("indices",o)}) - ${Se("uniforms.pads",o,r)}; if (k < 0) { break; } if (k >= i32(${Se("uniforms.x_shape",o,t)})) { break; } offset += k * i32(${Se("uniforms.x_strides",o,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${s} value = x[offset]; } `},U0=(e,t,r)=>{let s="";for(let o=t-1;o>=0;--o)s+=` k = i32(${e.indicesGet("indices",o)}) - ${Se("uniforms.pads",o,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Se("uniforms.x_shape",o,t)}) - 1); k = k % _2n_1; if(k >= i32(${Se("uniforms.x_shape",o,t)})) { k = _2n_1 - k; } } offset += k * i32(${Se("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},W0=(e,t,r)=>{let s="";for(let o=t-1;o>=0;--o)s+=` k = i32(${e.indicesGet("indices",o)}) - ${Se("uniforms.pads",o,r)}; if (k < 0) { k = 0; } if (k >= i32(${Se("uniforms.x_shape",o,t)})) { k = i32(${Se("uniforms.x_shape",o,t)}) - 1; } offset += k * i32(${Se("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},N0=(e,t,r)=>{let s="";for(let o=t-1;o>=0;--o)s+=` k = i32(${e.indicesGet("indices",o)}) - ${Se("uniforms.pads",o,r)}; if (k < 0) { k += i32(${Se("uniforms.x_shape",o,t)}]); } if (k >= i32(${Se("uniforms.x_shape",o,t)})) { k -= i32(${Se("uniforms.x_shape",o,t)}); } offset += k * i32(${Se("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},V0=(e,t,r)=>{switch(r.mode){case 0:return M0(e,t,r.pads.length);case 1:return U0(e,t,r.pads.length);case 2:return W0(e,t,r.pads.length);case 3:return N0(e,t,r.pads.length);default:throw new Error("Invalid mode")}},G0=(e,t)=>{let r=K.padShape(e[0].dims.slice(),t.pads),s=e[0].dims,o=K.size(r),c=[{type:12,data:o},{type:6,data:t.pads}];t.mode===0&&c.push({type:e[0].dataType,data:t.value}),c.push(...se(e[0].dims,r));let p=["rank"],l=h=>{let y=ne("output",e[0].dataType,r.length),$=Q("x",e[0].dataType,s.length),_=$.type.value,C=V0(y,s.length,t),T=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&T.push({name:"constant_value",type:_}),` ${h.registerUniforms(T).declareVariables($,y)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${y.offsetToIndices("global_idx")}; var value = ${_}(0); ${C} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(K.size(r)/64)},programUniforms:c}),getShaderSource:l}},H0=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,o=e[0].dims.length,c=new Int32Array(2*o).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let h=0;hc[Number(h)]=Number(l));let p=[];return c.forEach(l=>p.push(l)),{mode:t.mode,value:s,pads:p}}else return t},ep=(e,t)=>{D0(e.inputs);let r=H0(e.inputs,t);e.compute(G0(e.inputs,r),{inputs:[0]})}});var Dn,rp,ip,np,ap,L0,F0,op,sp,up,lp,dp,cp,pp,fp,mp,hp,gp,yp,vp=ie(()=>{"use strict";Tt();Te();je();ze();Dn=e=>{if(We.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},rp=(e,t,r)=>{let s=t.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let c=Object.hasOwnProperty.call(t,"dilations"),p=t.kernelShape.slice(),l=t.strides.slice(),h=c?t.dilations.slice():[],y=t.pads.slice();hr.adjustPoolAttributes(r,o,p,l,h,y);let $=hr.computePoolOutputShape(r,o,l,h,p,y,t.autoPad),_=Object.assign({},t);c?Object.assign(_,{kernelShape:p,strides:l,pads:y,dilations:h,cacheKey:t.cacheKey}):Object.assign(_,{kernelShape:p,strides:l,pads:y,cacheKey:t.cacheKey});let C=$.slice();return C.push(C.splice(1,1)[0]),[_,s?C:$]},ip=(e,t)=>{let r=t.format==="NHWC",s=K.size(e),o=K.size(t.kernelShape),c=[{type:12,data:s},{type:12,data:o}],p=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],h=t.strides[t.strides.length-1],y=t.pads[t.pads.length/2-1],$=t.pads[t.pads.length-1],_=!!(y+$);c.push({type:12,data:l},{type:12,data:h},{type:12,data:y},{type:12,data:$}),p.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let C=!1;if(t.kernelShape.length===2){let T=t.kernelShape[t.kernelShape.length-2],S=t.strides[t.strides.length-2],E=t.pads[t.pads.length/2-2],O=t.pads[t.pads.length-2];C=!!(E+O),c.push({type:12,data:T},{type:12,data:S},{type:12,data:E},{type:12,data:O}),p.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[c,p,!0,_,C]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=K.computeStrides(t.kernelShape);c.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),p.push({name:"kernelStrides",type:"u32",length:l.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let h=t.pads.reduce((y,$)=>y+$);return[c,p,!!h,!1,!1]}},np=(e,t,r,s,o,c,p,l,h,y,$,_)=>{let C=o.format==="NHWC",T=t.type.value,S=ne("output",t.type.tensor,s);if(o.kernelShape.length<=2){let E="",O="",R="",z=r-(C?2:1);if($?E=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${z}] = indices[${z}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${z}] < 0 || xIndices[${z}] >= uniforms.x_shape[${z}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${c} }`:E=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${z}] = indices[${z}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${c} }`,o.kernelShape.length===2){let U=r-(C?3:2);_?O=` 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; } `:O=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${U}] = indices[${U}] * uniforms.sh - uniforms.phStart + j; `,R=` } `}return` ${e.registerUniforms(h).declareVariables(t,S)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${S.offsetToIndices("global_idx")}; var xIndices = ${S.offsetToIndices("global_idx")}; var value = ${T}(${l}); var pad = 0; ${O} ${E} ${R} ${p} output[global_idx] = value; }`}else{if(C)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=o.kernelShape.length,O=o.pads.length,R="";return y?R=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${c} }`:R=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${c} `,` ${e.registerUniforms(h).declareVariables(t,S)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${S.offsetToIndices("global_idx")}; var xIndices = ${S.offsetToIndices("global_idx")}; var offsets: array; var value = ${T}(${l}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${E-1}u; j++) { offsets[j] = offset / ${Se("uniforms.kernelStrides","j",E)}; offset -= offsets[j] * ${Se("uniforms.kernelStrides","j",E)}; } offsets[${E-1}] = offset; isPad = false; for (var j = ${r-E}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${Se("uniforms.strides",`j - ${r-E}u`,E)} + offsets[j - ${r-E}u] - ${Se("uniforms.pads","j - 2u",O)}; ${R} } ${p} output[global_idx] = value; }`}},ap=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,L0=e=>`${ap(e)};${e.countIncludePad}`,F0=e=>`${ap(e)};${e.storageOrder};${e.dilations}`,op=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}),sp=(e,t,r,s)=>{let[o,c]=rp(t,s,r),p=Q("x",t.dataType,t.dims.length),l=p.type.value,h="value += x_val;",y="";o.countIncludePad?y+=`value /= ${l}(uniforms.kernelSize);`:y+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[$,_,C,T,S]=ip(c,o);$.push(...se(t.dims,c));let E=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${C};${T};${S}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(K.size(c)/64)},programUniforms:$}),getShaderSource:O=>np(O,p,t.dims.length,c.length,o,h,y,0,_,C,T,S)}},up=e=>{let t=e.count_include_pad!==0,r=op(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:t,...r,cacheKey:""};return{...s,cacheKey:L0(s)}},lp=(e,t)=>{Dn(e.inputs),e.compute(sp("AveragePool",e.inputs[0],!1,t))},dp={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},cp=e=>{let t=e.format;return{format:t,...dp,cacheKey:t}},pp=(e,t)=>{Dn(e.inputs),e.compute(sp("GlobalAveragePool",e.inputs[0],!0,t))},fp=(e,t,r,s)=>{let[o,c]=rp(t,s,r),p=` value = max(x_val, value); `,l="",h=Q("x",t.dataType,t.dims.length),y=["rank"],[$,_,C,T,S]=ip(c,o);return $.push(...se(t.dims,c)),{name:e,shaderCache:{hint:`${s.cacheKey};${C};${T};${S}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(K.size(c)/64)},programUniforms:$}),getShaderSource:E=>np(E,h,t.dims.length,c.length,o,p,l,t.dataType===10?-65504:-1e5,_,C,T,S)}},mp=(e,t)=>{Dn(e.inputs),e.compute(fp("MaxPool",e.inputs[0],!1,t))},hp=e=>{let t=e.storage_order,r=e.dilations,s=op(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:r,...s,cacheKey:""};return{...o,cacheKey:F0(o)}},gp=e=>{let t=e.format;return{format:t,...dp,cacheKey:t}},yp=(e,t)=>{Dn(e.inputs),e.compute(fp("GlobalMaxPool",e.inputs[0],!0,t))}});var K0,Y0,bp,wp=ie(()=>{"use strict";Tt();Te();ze();K0=(e,t,r)=>{let s=e===t,o=et&&r>0;if(s||o||c)throw new Error("Range these inputs' contents are invalid.")},Y0=(e,t,r,s)=>{let o=Math.abs(Math.ceil((t-e)/r)),c=[o],p=o,l=[{type:12,data:p},{type:s,data:e},{type:s,data:r},...se(c)],h=y=>{let $=ne("output",s,c.length),_=$.type.value,C=[{name:"outputSize",type:"u32"},{name:"start",type:_},{name:"delta",type:_}];return` ${y.registerUniforms(C).declareVariables($)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${_}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:h,getRunData:()=>({outputs:[{dims:c,dataType:s}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:l})}},bp=e=>{let t=0,r=0,s=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),We.webgpu.validateInputContent&&K0(t,r,s),e.compute(Y0(t,r,s,e.inputs[0].dataType),{inputs:[]})}});var Q0,X0,Z0,J0,ev,tv,rv,iv,nv,av,ov,_p,sv,uv,lv,dv,cv,$p,Cp,xp=ie(()=>{"use strict";Te();je();nt();ze();Q0=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},X0=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(r).fill(1);return t.forEach((o,c)=>s[o]=e[c]),s},Z0=(e,t,r,s,o,c)=>{let[p,l,h]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],y=e[0].dims.length;if(p>0&&e.length>p&&e[p].dims.length>0)e[p].getFloat32Array().forEach($=>c.push($));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(l>0&&e.length>l&&e[l].dims.length>0){if(e[l].getFloat32Array().forEach($=>s.push($)),s.length!==0&&s.length!==y&&r>=18&&s.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Q0(s,t),t.axes.length>0&&X0(s,t.axes,y).forEach(($,_)=>s[_]=$)}if(h>0&&e.length>h&&(e[h].getBigInt64Array().forEach($=>o.push(Number($))),o.length!==y||r>=18&&o.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(s.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof o<"u"&&s.length>0&&o.length>y)throw new Error("Resize requires only of scales or sizes to be specified")},J0=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / ${t}(lengthResized - 1); } else { return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",ev=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",tv=(e,t,r)=>{let s=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?s:e.slice();return t.length>0?(t.forEach((c,p)=>{s[c]=o[p],s[p+r]=o[t.length+p]}),s):o},rv=(e,t,r,s)=>{let o=[];if(r.length>0)if(s.length>0){if(e.forEach(c=>o.push(c)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((c,p)=>o[c]=r[p])}else r.forEach(c=>o.push(c));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((c,p)=>Math.round(c*t[p]))}return o},iv=(e,t,r)=>{let s=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(c=>t[c]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(c=>t[c]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(c=>t[c]=s),r.axes.forEach(c=>o[c]=Math.round(e[c]*t[c]))):(t.fill(s,0,t.length),o.forEach((c,p)=>o[p]=Math.round(c*t[p]))),o},nv=(e,t,r,s,o)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Se("uniforms.scales","i",s)}; var roi_low = ${Se("uniforms.roi","i",o)}; var roi_hi = ${Se("uniforms.roi",`i + ${t.length}`,o)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Se("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Se("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; }`,av=(e,t,r,s,o,c,p)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Se("uniforms.scales","i",o)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Se("uniforms.roi","i",c)}; var roi_hi = ${Se("uniforms.roi",`i + ${r.length}`,c)}; var input_shape_i = ${Se("uniforms.input_shape","i",r.length)}; var output_shape_i = ${Se("uniforms.output_shape","i",s.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${p} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,ov=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${Se("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,_p=(e,t,r,s)=>e.rank>s?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",sv=(e,t,r,s,o)=>{let[p,l,h,y]=r.length===2?[-1,0,1,-1]:[0,2,3,1],$=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${$} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",l,`max(0, min(row, ${r[l]} - 1))`)}; ${e.indicesSet("input_indices",h,`max(0, min(col, ${r[h]} - 1))`)}; ${_p(e,y,p,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${$} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${$} = originalIndices[${l}]; var col:${$} = originalIndices[${h}]; ${s?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[h]} - 1)) { return ${o}; }`:""}; row = max(0, min(row, ${r[l]} - 1)); col = max(0, min(col, ${r[h]} - 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[${y}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"}; var x11: ${$} = getInputValue(batch, channel, row1, col1); var x12: ${$} = getInputValue(batch, channel, row1, col2); var x21: ${$} = getInputValue(batch, channel, row2, col1); var x22: ${$} = getInputValue(batch, channel, row2, col2); var dx1: ${$} = abs(row - ${$}(row1)); var dx2: ${$} = abs(${$}(row2) - row); var dy1: ${$} = abs(col - ${$}(col1)); var dy2: ${$} = abs(${$}(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); }`},uv=(e,t,r,s,o,c,p,l,h,y)=>{let $=r.length===2,_=!0,[C,T]=$?[0,1]:_?[2,3]:[1,2],S=e.type.value,E=O=>{let R=O===C?"row":"col";return` fn ${R}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${S} { var output_index = ${t.indicesGet("output_indices",O)}; var originalIdx: ${S} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[O]}, ${s[O]}, ${r[O]}, ${c[O]}, ${c[O]} + ${r.length}); var fractOriginalIdx: ${S} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${l} && (originalIdx < 0 || originalIdx > (${r[O]} - 1))) { return ${h}; } var data: array<${S}, 4> = array<${S}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${R}: ${S} = originalIdx + ${S}(i); if (${R} < 0 || ${R} >= ${r[O]}) { ${(()=>y?`coefs[i + 1] = 0.0; continue;`:l?`return ${h};`:`${R} = max(0, min(${R}, ${r[O]} - 1));`)()}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",O,`u32(${R})`)}; data[i + 1] = ${O===C?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${E(C)}; ${E(T)}; fn getCubicInterpolationCoefs(s: ${S}) -> array<${S}, 4> { var absS = abs(s); var coeffs: array<${S}, 4> = array<${S}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${S} = 1.0 - absS; var twoMinusAbsS: ${S} = 2.0 - absS; var onePlusAbsS: ${S} = 1.0 + absS; coeffs[0] = ((${p} * onePlusAbsS - 5 * ${p}) * onePlusAbsS + 8 * ${p}) * onePlusAbsS - 4 * ${p}; coeffs[1] = ((${p} + 2) * absS - (${p} + 3)) * absS * absS + 1; coeffs[2] = ((${p} + 2) * oneMinusAbsS - (${p} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${p} * twoMinusAbsS - 5 * ${p}) * twoMinusAbsS + 8 * ${p}) * twoMinusAbsS - 4 * ${p}; return coeffs; } fn cubicInterpolation1D(x: array<${S}, 4>, coefs: array<${S}, 4>) -> ${S} { var coefsSum: ${S} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${S} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},lv=(e,t,r,s,o)=>{let[p,l,h,y,$]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],_=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${_} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",l,`max(0, min(depth, ${r[l]} - 1))`)}; ${e.indicesSet("input_indices",h,`max(0, min(height, ${r[h]} - 1))`)}; ${e.indicesSet("input_indices",y,`max(0, min(width, ${r[y]} - 1))`)}; ${_p(e,$,p,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${_} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${_} = originalIndices[${l}]; var height:${_} = originalIndices[${h}]; var width:${_} = originalIndices[${y}]; ${s?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[h]} - 1) || width < 0 || (width > ${r[y]} - 1)) { return ${o}; }`:""}; depth = max(0, min(depth, ${r[l]} - 1)); height = max(0, min(height, ${r[h]} - 1)); width = max(0, min(width, ${r[y]} - 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[${$}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${p}])`:"0"}; var x111: ${_} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${_} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${_} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${_} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${_} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${_} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${_} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${_} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${_} = abs(depth - ${_}(depth1)); var dx2: ${_} = abs(${_}(depth2) - depth); var dy1: ${_} = abs(height - ${_}(height1)); var dy2: ${_} = abs(${_}(height2) - height); var dz1: ${_} = abs(width - ${_}(width1)); var dz2: ${_} = abs(${_}(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); }`},dv=(e,t,r,s,o,c)=>{let p=e.dims,l=tv(c,t.axes,p.length),h=rv(p,s,o,t.axes),y=s.slice();s.length===0&&(y=p.map((z,M)=>z===0?1:h[M]/z),t.keepAspectRatioPolicy!=="stretch"&&(h=iv(p,y,t)));let $=ne("output",e.dataType,h.length),_=Q("input",e.dataType,p.length),C=K.size(h),T=p.length===h.length&&p.every((z,M)=>z===h[M]),S=t.coordinateTransformMode==="tf_crop_and_resize",E=t.extrapolationValue,O=_.type.value,R=z=>` ${T?"":` ${J0(t.coordinateTransformMode,O)}; ${(()=>{switch(t.mode){case"nearest":return` ${ov(_,p)}; ${ev(t.nearestMode,r,O)}; ${av(_,$,p,h,y.length,l.length,S)}; `;case"linear":return` ${nv($,p,h,y.length,l.length)}; ${(()=>{if(p.length===2||p.length===4)return`${sv(_,$,p,S,E)}`;if(p.length===3||p.length===5)return`${lv(_,$,p,S,E)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(p.length===2||p.length===4)return`${uv(_,$,p,h,y,l,t.cubicCoeffA,S,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${z.registerUniform("output_size","u32").registerUniform("scales","f32",y.length).registerUniform("roi","f32",l.length).declareVariables(_,$)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${T?"output[global_idx] = input[global_idx];":` let output_indices = ${$.offsetToIndices("global_idx")}; var input_indices: ${_.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${_.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${p.length===2||p.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${y.length>0?y:""}|${o.length>0?o:""}|${l.length>0?l:""}|${T}|${p}`,inputDependencies:["rank"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:h,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},{type:1,data:y},{type:1,data:l},...se(p,h)]})}},cv=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},$p=(e,t)=>{let r=[],s=[],o=[],c=cv(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Z0(e.inputs,t,c,r,s,o),e.compute(dv(e.inputs[0],t,c,r,s,o),{inputs:[0]})},Cp=e=>{let t=e.antialias,r=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,c=e.excludeOutside!==0,p=e.extrapolationValue,l=e.keepAspectRatioPolicy,h=e.mode,y=e.nearestMode===""?"simple":e.nearestMode;return Oe({antialias:t,axes:r,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:c,extrapolationValue:p,keepAspectRatioPolicy:l,mode:h,nearestMode:y})}});var pv,fv,Sp,Ip=ie(()=>{"use strict";Te();je();nt();ze();pv=(e,t)=>{let[r,s,o,c]=e,{numHeads:p,rotaryEmbeddingDim:l}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!K.areEqual(s.dims,[])&&!K.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.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(o.dims,c.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(l>0&&p===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let h=r.dims[0],y=r.dims[r.dims.length-2],$=o.dims[0],_=K.sizeFromDimension(r.dims,1)/y,C=l===0?o.dims[1]*2:_/p;if(l>C)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(h!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(y!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(C/2!==o.dims[1]&&l/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(y>$)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},fv=(e,t)=>{let{interleaved:r,numHeads:s,rotaryEmbeddingDim:o,scale:c}=t,p=e[0].dims[0],l=K.sizeFromDimension(e[0].dims,1),h=e[0].dims[e[0].dims.length-2],y=l/h,$=e[2].dims[1],_=o===0?$*2:y/s,C=new Array(p,h,y/_,_-$),T=K.computeStrides(C),S=[{type:1,data:c},{type:12,data:C},{type:12,data:T},...e[0].dims.length===3?new Array({type:12,data:[l,y,_,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[l,_,h*_,1]}):[],...se(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],E=O=>{let R=Q("input",e[0].dataType,e[0].dims.length),z=Q("position_ids",e[1].dataType,e[1].dims.length),M=Q("cos_cache",e[2].dataType,e[2].dims.length),U=Q("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:C.length},{name:"global_strides",type:"u32",length:T.length},{name:"input_output_strides",type:"u32",length:T.length}]),` ${O.declareVariables(R,z,M,U,L)} ${O.mainStart(gr)} let half_rotary_emb_dim = uniforms.${M.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${O.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${z.broadcastedIndicesToOffset("bsnh.xy",ne("",z.type.tensor,2))}; let position_id = u32(${z.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 = ${R.getByOffset("i")} * ${M.get("position_id","bsnh[3]")} - ${R.getByOffset("j")} * ${U.get("position_id","bsnh[3]")}; ${L.setByOffset("i","re")} let im = ${R.getByOffset("i")} * ${U.get("position_id","bsnh[3]")} + ${R.getByOffset("j")} * ${M.get("position_id","bsnh[3]")}; ${L.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${L.setByOffset("k",R.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:Oe({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(K.size(C)/gr)},programUniforms:S})}},Sp=(e,t)=>{pv(e.inputs,t),e.compute(fv(e.inputs,t))}});var mv,hv,Tp,Ap=ie(()=>{"use strict";Te();je();ze();mv=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],s=e[2];if(t.dataType!==r.dataType||t.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],c=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==c)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let p=e[3];if(p.dims.length!==1)throw new Error("Beta must be 1D");if(p.dims[p.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let p=e[4];if(p.dims.length!==1)throw new Error("Bias must be 1D");if(p.dims[p.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},hv=(e,t,r,s)=>{let o=t.simplified,c=e[0].dims,p=K.size(c),l=c,h=p,y=c.slice(-1)[0],$=s?c.slice(0,-1).concat(1):[],_=!o&&e.length>3,C=e.length>4,T=s&&r>1,S=s&&r>2,E=r>3,O=Le(y),R=[{type:12,data:h},{type:12,data:O},{type:12,data:y},{type:1,data:t.epsilon}],z=U=>{let L=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],F=[Q("x",e[0].dataType,e[0].dims,O),Q("skip",e[1].dataType,e[1].dims,O),Q("gamma",e[2].dataType,e[2].dims,O)];_&&F.push(Q("beta",e[3].dataType,e[3].dims,O)),C&&F.push(Q("bias",e[4].dataType,e[4].dims,O)),F.push(ne("output",e[0].dataType,l,O)),T&&F.push(ne("mean_output",1,$)),S&&F.push(ne("inv_std_output",1,$)),E&&F.push(ne("input_skip_bias_sum",e[0].dataType,l,O));let te=Ge(e[0].dataType);return` ${U.registerUniforms(L).declareVariables(...F)} ${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 = ${Pt("f32",O)}; var squareSum = ${Pt("f32",O)}; for (var i: u32 = 0; i < hidden_size_vectorized; i++) { let skip_value = skip[offset + i]; let bias_value = ${C?"bias[i]":te+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${E?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${yr(te,O,"value")}; sum += f32_value; squareSum += f32_value * f32_value; } let mean = ${zt("sum",O)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${zt("squareSum",O)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); ${T?"mean_output[global_idx] = mean;":""} ${S?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < hidden_size_vectorized; i++) { output[offset + i] = (output[offset + i] ${o?"":`- ${te}(mean)`}) * ${te}(inv_std_dev) * gamma[i] ${_?"+ beta[i]":""}; } }`},M=[{dims:l,dataType:e[0].dataType}];return r>1&&M.push({dims:$,dataType:1}),r>2&&M.push({dims:$,dataType:1}),r>3&&M.push({dims:c,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${O};${T};${S};${E}`,inputDependencies:e.map((U,L)=>"type")},getShaderSource:z,getRunData:()=>({outputs:M,dispatchGroup:{x:Math.ceil(h/y/64)},programUniforms:R})}},Tp=(e,t)=>{mv(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(hv(e.inputs,t,e.outputCount,!1),{outputs:s})}});var gv,Mn,yv,Ep,vv,bv,kp,Op,Pp=ie(()=>{"use strict";Te();je();nt();ze();gv=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Mn=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(s=>r.push(Number(s)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(s=>r.push(Number(s)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},yv=(e,t)=>{if(e.length>1){let r=Mn(e,1),s=Mn(e,2),o=Mn(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),Oe({starts:r,ends:s,axes:o})}else return t},Ep=(e,t,r,s,o)=>{let c=e;return e<0&&(c+=r[s[t]]),o[t]<0?Math.max(0,Math.min(c,r[s[t]]-1)):Math.max(0,Math.min(c,r[s[t]]))},vv=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${Se("uniforms.input_shape","i",r.length)}; let steps_i = ${Se("uniforms.steps","i",r.length)}; let signs_i = ${Se("uniforms.signs","i",r.length)}; let starts_i = ${Se("uniforms.starts","i",r.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,bv=(e,t)=>{let r=e[0].dims,s=K.size(r),o=t.axes.length>0?K.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],c=Mn(e,4);c.forEach(R=>R!==0||(()=>{throw new Error("step cannot be 0")})),c.length===0&&(c=Array(o.length).fill(1));let p=t.starts.map((R,z)=>Ep(R,z,r,o,c)),l=t.ends.map((R,z)=>Ep(R,z,r,o,c));if(o.length!==p.length||o.length!==l.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==r.length)for(let R=0;RMath.sign(R));c.forEach((R,z,M)=>{if(R<0){let U=(l[z]-p[z])/R,L=p[z],F=L+U*c[z];p[z]=F,l[z]=L,M[z]=-R}});let y=r.slice(0);o.forEach((R,z)=>{y[R]=Math.ceil((l[R]-p[R])/c[R])});let $={dims:y,dataType:e[0].dataType},_=ne("output",e[0].dataType,y.length),C=Q("input",e[0].dataType,e[0].dims.length),T=K.size(y),S=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:p.length},{name:"signs",type:"i32",length:h.length},{name:"steps",type:"u32",length:c.length}],E=[{type:12,data:T},{type:12,data:p},{type:6,data:h},{type:12,data:c},...se(e[0].dims,y)],O=R=>` ${R.registerUniforms(S).declareVariables(C,_)} ${vv(C,_,r)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${_.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${_.setByOffset("global_idx",C.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${h.length}_${p.length}_${c.length}`,inputDependencies:["rank"]},getShaderSource:O,getRunData:()=>({outputs:[$],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:E})}},kp=(e,t)=>{gv(e.inputs,t);let r=yv(e.inputs,t);e.compute(bv(e.inputs,r),{inputs:[0]})},Op=e=>{let t=e.starts,r=e.ends,s=e.axes;return Oe({starts:t,ends:r,axes:s})}});var wv,_v,zp,Rp,jp=ie(()=>{"use strict";Te();je();nt();ze();wv=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},_v=(e,t)=>{let r=e.dims,s=K.size(r),o=64,c=t.axis;if(c<0&&(c=r.length+c),cR===4?`max(max(${O}.x, ${O}.y), max(${O}.z, ${O}.w))`:R===2?`max(${O}.x, ${O}.y)`:R===3?`max(max(${O}.x, ${O}.y), ${O}.z)`:O,_=Q("x",e.dataType,e.dims,h),C=ne("result",e.dataType,e.dims,h),T=_.type.value,S=Ge(e.dataType)==="f32"?`var threadMax = ${T}(-3.402823e+38f);`:`var threadMax = ${T}(-65504.0h);`,E=O=>` var rowMaxShared : ${T}; var rowSumShared : ${T}; var threadShared : array<${T}, ${o}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${T} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${T}) { let index = row * row_stride + col; result[index] = value; } ${O.registerUniform("packedCols","i32").declareVariables(_,C)} ${O.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${o}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${S} 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 = ${T}(${$("threadShared[0]",h)}); } workgroupBarrier(); // find the rows sum var threadSum = ${T}(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 = ${T}(${zt("threadShared[0]",h)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`;return{name:"Softmax",shaderCache:{hint:`${h}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:l},programUniforms:[{type:6,data:y}]}),getShaderSource:E}},zp=(e,t)=>{wv(e.inputs),e.compute(_v(e.inputs[0],t))},Rp=e=>Oe({axis:e.axis})});var $v,Cv,xv,Sv,Iv,Bp,Dp,Mp=ie(()=>{"use strict";Te();je();nt();ze();$v=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Cv=(e,t)=>{let r=[],s=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),s=r.length),Oe({numOutputs:s,axis:t.axis,splitSizes:r})},xv=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Se("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Sv=e=>{let t=e.length,r=[];for(let s=0;s{let r=e[0].dims,s=K.size(r),o=e[0].dataType,c=K.normalizeAxis(t.axis,r.length),p=new Array(t.numOutputs),l=Q("input",o,r.length),h=new Array(t.numOutputs),y=[],$=[],_=0,C=[{type:12,data:s}];for(let S=0;S` ${S.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",h.length).declareVariables(l,...p)} ${xv(h.length)} ${Sv(p)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${l.offsetToIndices("global_idx")}; var index = ${l.indicesGet("indices",c)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Se("uniforms.size_in_split_axis","output_number - 1u",h.length)}; ${l.indicesSet("indices",c,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:T,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:C})}},Bp=(e,t)=>{$v(e.inputs);let r=e.inputs.length===1?t:Cv(e.inputs,t);e.compute(Iv(e.inputs,r),{inputs:[0]})},Dp=e=>{let t=e.axis,r=e.splitSizes,s=e.numOutputs<0?r.length:e.numOutputs;if(s!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Oe({axis:t,numOutputs:s,splitSizes:r})}});var Up,Tv,Av,Ev,Wp,Np=ie(()=>{"use strict";Te();je();ze();Up=e=>Array.from(e.getBigInt64Array(),Number),Tv=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(Up(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")},Av=(e,t)=>{let r=[];for(let s=0;s{let t=e[0].dims,r=Up(e[1]),s=Av(t,r),o=K.size(s),c=e[0].dataType,p=Q("input",c,t.length),l=ne("output",c,s.length),h=y=>` const inputShape = ${p.indices(...t)}; ${y.registerUniform("output_size","u32").declareVariables(p,l)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${l.offsetToIndices("global_idx")}; var input_indices: ${p.type.indices}; for (var i = 0; i < ${t.length}; i++) { let input_dim_i = ${p.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; ${p.indicesSet("input_indices","i","input_dim_value")} } ${l.setByOffset("global_idx",p.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...se(e[0].dims,s)]}),getShaderSource:h}},Wp=e=>{Tv(e.inputs),e.compute(Ev(e.inputs),{inputs:[0]})}});var kv,Ov,Vp,Gp=ie(()=>{"use strict";Te();je();ze();kv=(e,t,r,s,o)=>{let c=ne("output_data",o,r.length,4),p=Q("a_data",t[1].dataType,t[1].dims.length,4),l=Q("b_data",t[2].dataType,t[2].dims.length,4),h=Q("c_data",t[0].dataType,t[0].dims.length,4),y,$=(_,C,T)=>`select(${C}, ${_}, ${T})`;if(!s)y=c.setByOffset("global_idx",$(p.getByOffset("global_idx"),l.getByOffset("global_idx"),h.getByOffset("global_idx")));else{let _=(C,T,S="")=>{let E=`a_data[index_a${T}][component_a${T}]`,O=`b_data[index_b${T}][component_b${T}]`,R=`bool(c_data[index_c${T}] & (0xffu << (component_c${T} * 8)))`;return` let output_indices${T} = ${c.offsetToIndices(`global_idx * 4u + ${T}u`)}; let offset_a${T} = ${p.broadcastedIndicesToOffset(`output_indices${T}`,c)}; let offset_b${T} = ${l.broadcastedIndicesToOffset(`output_indices${T}`,c)}; let offset_c${T} = ${h.broadcastedIndicesToOffset(`output_indices${T}`,c)}; let index_a${T} = offset_a${T} / 4u; let index_b${T} = offset_b${T} / 4u; let index_c${T} = offset_c${T} / 4u; let component_a${T} = offset_a${T} % 4u; let component_b${T} = offset_b${T} % 4u; let component_c${T} = offset_c${T} % 4u; ${C}[${T}] = ${S}(${$(E,O,R)}); `};o===9?y=` var data = vec4(0); ${_("data",0,"u32")} ${_("data",1,"u32")} ${_("data",2,"u32")} ${_("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:y=` ${_("output_data[global_idx]",0)} ${_("output_data[global_idx]",1)} ${_("output_data[global_idx]",2)} ${_("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(h,p,l,c)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${y} }`},Ov=e=>{let t=e[1].dims,r=e[2].dims,s=e[0].dims,o=e[1].dataType,c=!(K.areEqual(t,r)&&K.areEqual(r,s)),p=t,l=K.size(t);if(c){let y=Ut.calcShape(Ut.calcShape(t,r,!1),s,!1);if(!y)throw new Error("Can't perform where op on the given tensors");p=y,l=K.size(p)}let h=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:y=>kv(y,e,p,c,o),getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:h},...se(s,t,r,p)]})}},Vp=e=>{e.compute(Ov(e.inputs))}});var Hp,Lp=ie(()=>{"use strict";td();xa();od();ud();Fd();ic();Ca();Ea();yc();wc();Cc();Ac();Oc();zc();Bc();Uc();Vc();Hc();Fc();Oa();Yc();Jc();tp();vp();wp();Cn();xp();Ip();Ap();Pp();jp();Mp();Np();Lr();En();Gp();Hp=new Map([["Abs",[ld]],["Acos",[dd]],["Acosh",[cd]],["Add",[qd]],["ArgMax",[ed,$a]],["ArgMin",[Jl,$a]],["Asin",[pd]],["Asinh",[fd]],["Atan",[md]],["Atanh",[hd]],["Attention",[nd]],["AveragePool",[lp,up]],["BatchNormalization",[ad]],["BiasAdd",[sd]],["BiasSplitGelu",[Ld]],["Cast",[yd,gd]],["Ceil",[bd]],["Clip",[vd]],["Concat",[rd,id]],["Conv",[Ra,za]],["ConvTranspose",[gc,hc]],["Cos",[wd]],["Cosh",[_d]],["CumSum",[vc,bc]],["DepthToSpace",[_c,$c]],["Div",[Kd]],["Einsum",[Ic,Tc]],["Elu",[$d,Tn]],["Equal",[Yd]],["Erf",[Cd]],["Exp",[xd]],["Expand",[kc]],["FastGelu",[Pc]],["Floor",[Sd]],["FusedConv",[Ra,za]],["Gather",[jc,Rc]],["GatherElements",[Mc,Dc]],["Gelu",[Id]],["Gemm",[Nc,Wc]],["GlobalAveragePool",[pp,cp]],["GlobalMaxPool",[yp,gp]],["Greater",[Jd]],["GreaterOrEqual",[tc]],["HardSigmoid",[Rd,zd]],["InstanceNormalization",[Gc]],["LayerNormalization",[Lc]],["LeakyRelu",[Td,Tn]],["Less",[ec]],["LessOrEqual",[rc]],["Log",[Gd]],["MatMul",[lc]],["MatMulNBits",[qc,Kc]],["MaxPool",[mp,hp]],["Mul",[Qd]],["MultiHeadAttention",[Zc,Xc]],["Neg",[Ed]],["Not",[Ad]],["Pad",[ep]],["Pow",[Xd]],["Range",[bp]],["Reciprocal",[kd]],["ReduceMin",[ql]],["ReduceMean",[Vl]],["ReduceMax",[Fl]],["ReduceSum",[Yl]],["ReduceProd",[Kl]],["ReduceL1",[Gl]],["ReduceL2",[Hl]],["ReduceLogSum",[Xl]],["ReduceLogSumExp",[Ll]],["ReduceSumSquare",[Ql]],["Relu",[Od]],["Resize",[$p,Cp]],["RotaryEmbedding",[Sp]],["Sigmoid",[Pd]],["Sin",[jd]],["Sinh",[Bd]],["Slice",[kp,Op]],["SkipLayerNormalization",[Tp]],["Split",[Bp,Dp]],["Sqrt",[Dd]],["Softmax",[zp,Rp]],["Sub",[Zd]],["Tan",[Md]],["Tanh",[Wd]],["ThresholdedRelu",[Vd,Tn]],["Tile",[Wp]],["Transpose",[El,kl]],["Where",[Vp]]])});var Un,Fp=ie(()=>{"use strict";Tt();Zt();ze();Un=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,s,o,c){Ct(t.programInfo.name);let p=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let h=[];for(let $ of r)h.push({binding:h.length,resource:{buffer:$.buffer}});for(let $ of s)h.push({binding:h.length,resource:{buffer:$.buffer}});c&&h.push({binding:h.length,resource:c});let y=p.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:h,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let $={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:y,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push($)}l.setPipeline(t.computePipeline),l.setBindGroup(0,y),l.dispatchWorkgroups(...o),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),ht(t.programInfo.name)}dispose(){}build(t,r){Ct(t.name);let s=this.backend.device,o=[];s.features.has("shader-f16")&&o.push("enable f16;");let c=Tl(r,this.backend.device.limits),p=t.getShaderSource(c),l=`${o.join(` `)} ${c.additionalImplementations} ${p}`,h=s.createShaderModule({code:l,label:t.name});qe("verbose",()=>`[WebGPU] ${t.name} shader code: ${l}`);let y=s.createComputePipeline({compute:{module:h,entryPoint:"main"},layout:"auto",label:t.name});return ht(t.name),{programInfo:t,computePipeline:y,uniformVariablesInfo:c.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,s=typeof t=="number"?1:t.y||1,o=typeof t=="number"?1:t.z||1,c=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=c&&s<=c&&o<=c)return[r,s,o];let p=r*s*o,l=Math.ceil(Math.sqrt(p));if(l>c){if(l=Math.ceil(Math.cbrt(p)),l>c)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}});var Pv,zv,Wa,Wn,qp=ie(()=>{"use strict";Tt();Te();Zt();_l();Il();Lp();Fp();Pv=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let s=0;s{let s=e.name;return e.shaderCache?.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+r+`:${Pv(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,s},Wa=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Wn=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let s=[],o={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:s};r.features.has("chromium-experimental-timestamp-query-inside-passes")?s.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&s.push("timestamp-query"),r.features.has("shader-f16")&&s.push("shader-f16"),this.device=await r.requestDevice(o),this.adapterInfo=new Wa(await r.requestAdapterInfo()),this.gpuDataManager=Sl(this),this.programManager=new Un(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,bl(t.logLevel,!!t.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:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ct(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),s=this.pendingQueries.get(t);for(let o=0;o"u"&&(this.queryTimeBase=T);let E=Number(T-this.queryTimeBase),O=Number(S-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(R=>({dims:R.dims,dataType:Xt(R.dataType)})),outputsMetadata:C.map(R=>({dims:R.dims,dataType:Xt(R.dataType)})),kernelId:p,kernelType:h,kernelName:y,programName:$,startTime:E,endTime:O});else{let R="";_.forEach((M,U)=>{R+=`input[${U}]: [${M.dims}] | ${Xt(M.dataType)}, `});let z="";C.forEach((M,U)=>{z+=`output[${U}]: [${M.dims}] | ${Xt(M.dataType)}, `}),console.log(`[profiling] kernel "${p}|${h}|${y}|${$}" ${R}${z}execution time: ${O-E} ns`)}ln("GPU",`${$}::${T}::${S}`)}t.unmap(),this.pendingQueries.delete(t)}),ht()}run(t,r,s,o,c,p){Ct(t.name);let l=[];for(let M=0;MU):s;if(_.length!==h.length)throw new Error(`Output size ${_.length} must be equal to ${h.length}.`);let C=[],T=[];for(let M=0;M=p)throw new Error(`Invalid output index: ${_[M]}`);if(_[M]===-3)continue;let U=_[M]===-1,L=_[M]===-2,F=U||L?c(h[M].dataType,h[M].dims):o(_[M],h[M].dataType,h[M].dims);if(C.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)}T.push(te)}if(l.length!==r.length||T.length!==C.length){if(T.length===0)return ht(t.name),C;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let S;if($){let M=0,U=[];$.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,Z;J.type===10?(Z=oe.length>4?16:oe.length>2?8:oe.length*le,ge=oe.length>4?16:le*oe.length):(Z=oe.length<=2?oe.length*le:16,ge=16),M=Math.ceil(M/Z)*Z,U.push(M);let fe=J.type===10?8:4;M+=oe.length>4?Math.ceil(oe.length/fe)*ge:oe.length*le});let L=16;M=Math.ceil(M/L)*L;let F=new ArrayBuffer(M);$.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: ${Xt(J.type)}`)});let te=this.gpuDataManager.create(M,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(te.buffer,0,F,0,M),this.gpuDataManager.release(te.id),S={offset:0,size:M,buffer:te.buffer}}let E=this.programManager.normalizeDispatchGroupSize(y),O=E[1]===1&&E[2]===1,R=zv(t,r,O),z=this.programManager.getArtifact(R);if(z||(z=this.programManager.build(t,E),this.programManager.setArtifact(R,z),qe("info",()=>`[artifact] key: ${R}, programName: ${t.name}`)),$&&z.uniformVariablesInfo){if($.length!==z.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${z.uniformVariablesInfo.length}, got ${$.length} in program "${z.programInfo.name}".`);for(let M=0;M<$.length;M++){let U=$[M],L=U.type,F=typeof U.data=="number"?1:U.data.length,[te,J]=z.uniformVariablesInfo[M];if(L!==te||F!==J)throw new Error(`Uniform variable ${M} mismatch: expect type ${te} with size ${J}, got type ${L} with size ${F} in program "${z.programInfo.name}".`)}}if(qe("info",()=>`[ProgramManager] run "${t.name}" (key=${R}) with ${E[0]}x${E[1]}x${E[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let M={kernelId:this.currentKernelId,programName:z.programInfo.name,inputTensorViews:r,outputTensorViews:C};this.pendingKernels.push(M),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(M)}return this.programManager.run(z,l,T,E,S),ht(t.name),C}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,s,o){let c=Hp.get(t);if(!c)throw new Error(`kernel not implemented: ${t}`);let p={kernelType:t,kernelName:o,kernelEntry:c[0],attributes:[c[1],s]};this.kernels.set(r,p)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let s of r)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,s){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let c=o.kernelType,p=o.kernelName,l=o.kernelEntry,h=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${c}] ${p}" is not allowed to be called recursively`);this.currentKernelId=t,h[0]&&(h[1]=h[0](h[1]),h[0]=void 0),qe("info",()=>`[WebGPU] Start to run kernel "[${c}] ${p}"...`);let y=this.env.debug;this.temporaryData=[];try{return y&&this.device.pushErrorScope("validation"),l(r,h[1]),0}catch($){return s.push(Promise.resolve(`[WebGPU] Kernel "[${c}] ${p}" failed. ${$}`)),1}finally{y&&s.push(this.device.popErrorScope().then($=>$?`GPU validation error for kernel "[${c}] ${p}": ${$.message}`:null));for(let $ of this.temporaryData)this.gpuDataManager.release($.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,s,o){let c=this.sessionExternalDataMapping.get(t);c||(c=new Map,this.sessionExternalDataMapping.set(t,c));let p=c.get(r),l=this.gpuDataManager.registerExternalBuffer(s,o,p?.[1]);return c.set(r,[l,s]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,s){return async()=>{let o=await ha(this,t,r);return wl(o.buffer,s)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){qe("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(){qe("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){qe("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),s=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var Kp={};Vr(Kp,{init:()=>Rv});var Ii,Na,Rv,Yp=ie(()=>{"use strict";Te();qp();Zt();je();Ii=class e{constructor(t,r,s,o){this.module=t;this.dataType=r;this.data=s;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=K.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=K.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=K.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(K.size(t)!==K.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Na=class{constructor(t,r,s){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let o=t.HEAPU32,c=s>>>2;this.opKernelContext=o[c++];let p=o[c++];this.outputCount=o[c++],this.customDataOffset=o[c++],this.customDataSize=o[c++];let l=[];for(let h=0;htypeof l=="number"?this.inputs[l]:l)??this.inputs,o=r?.outputs??[],c=(l,h,y)=>new Ii(this.module,h,this.output(l,y),y),p=(l,h)=>{let y=mr(l);if(!y)throw new Error(`Unsupported data type: ${l}`);let $=y*K.size(h),_=$>0?this.backend.gpuDataManager.create($).id:0;return new Ii(this.module,l,_,h)};return this.backend.run(t,s,o,c,p,this.outputCount)}output(t,r){let s=this.module.stackSave();try{let o=this.module.stackAlloc((1+r.length)*4),c=o>>2;this.module.HEAPU32[c++]=r.length;for(let p=0;p{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let c=new Wn;await c.initialize(r,s),o("webgpu",[c,p=>c.alloc(p),p=>c.free(p),(p,l,h,y=!1)=>{if(y)qe("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${p}, dst=${l}, size=${h}`),c.memcpy(p,l);else{qe("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${p}, gpuDataId=${l}, size=${h}`);let $=t.HEAPU8.subarray(p>>>0,(p>>>0)+h);c.upload(l,$)}},async(p,l,h)=>{qe("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${p}, dataOffset=${l}, size=${h}`),await c.download(p,()=>t.HEAPU8.subarray(l>>>0,(l>>>0)+h))},(p,l,h)=>c.createKernel(p,l,h,t.UTF8ToString(t._JsepGetNodeName(l))),p=>c.releaseKernel(p),(p,l,h,y)=>{qe("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${h}, kernel=${p}, contextDataOffset=${l}`);let $=new Na(t,c,l);return c.computeKernel(p,$,y)},()=>c.captureBegin(),()=>c.captureEnd(),()=>c.replay()])}else o("webnn")}});var jv,Xp,Zp,vr,Bv,Va,Jp,ef,Qp,tf,rf,nf,af=ie(()=>{"use strict";ml();gl();Te();Gr();hn();ca();jv=(e,t)=>{Ze()._OrtInit(e,t)!==0&&Fe("Can't initialize onnxruntime.")},Xp=async e=>{jv(e.wasm.numThreads,_i(e.logLevel))},Zp=async(e,t)=>{{let r=(Yp(),Qt(Kp)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let c=e.webgpu.forceFallbackAdapter;if(c!==void 0&&typeof c!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${c}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:c}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");await r("webgpu",Ze(),e,s)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Ze(),e)}}},vr=new Map,Bv=e=>{let t=Ze(),r=t.stackSave();try{let s=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,s,s+4)!==0&&Fe("Can't get session input/output count."),[t.HEAP32[s/4],t.HEAP32[s/4+1]]}finally{t.stackRestore(r)}},Va=e=>{let t=Ze(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Jp=async(e,t)=>{let r,s,o=Ze();Array.isArray(e)?[r,s]=e:e.buffer===o.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=Va(e);let c=0,p=0,l=0,h=[],y=[],$=[];try{if([p,h]=hl(t),t?.externalData&&o.mountExternalData){let z=[];for(let M of t.externalData){let U=typeof M=="string"?M:M.path;z.push($i(typeof M=="string"?M:M.data).then(L=>{o.mountExternalData(U,L)}))}await Promise.all(z)}c=await o._OrtCreateSession(r,s,p),c===0&&Fe("Can't create a session.");let[_,C]=Bv(c),T=!!t?.enableGraphCapture,S=[],E=[],O=[];for(let z=0;z<_;z++){let M=o._OrtGetInputName(c,z);M===0&&Fe("Can't get an input name."),y.push(M),S.push(o.UTF8ToString(M))}for(let z=0;zz==="gpu-buffer")&&(l=o._OrtCreateBinding(c),l===0&&Fe("Can't create IO binding."),R={handle:l,outputPreferredLocations:O,outputPreferredLocationsEncoded:O.map(z=>da(z))}),vr.set(c,[c,y,$,R,T,!1]),[c,S,E]}catch(_){throw y.forEach(C=>o._OrtFree(C)),$.forEach(C=>o._OrtFree(C)),l!==0&&o._OrtReleaseBinding(l),c!==0&&o._OrtReleaseSession(c),_}finally{o._free(r),p!==0&&o._OrtReleaseSessionOptions(p),h.forEach(_=>o._free(_)),o.unmountExternalData?.()}},ef=e=>{let t=Ze(),r=vr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,c,p,l]=r;p&&(l&&t._OrtClearBoundOutputs(p.handle),t._OrtReleaseBinding(p.handle)),t.jsepOnReleaseSession?.(e),o.forEach(h=>t._OrtFree(h)),c.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(s),vr.delete(e)},Qp=(e,t,r,s,o,c=!1)=>{if(!e){t.push(0);return}let p=Ze(),l=e[0],h=e[1],y=e[3],$,_;if(l==="string"&&y==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(c&&y!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(y==="gpu-buffer"){let S=e[2].gpuBuffer,E=mr(la(l));_=h.reduce((R,z)=>R*z,1)*E;let O=p.jsepRegisterBuffer;if(!O)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$=O(s,o,S,_)}else{let S=e[2];if(Array.isArray(S)){_=4*S.length,$=p._malloc(_),r.push($);let E=$/4;for(let O=0;Op.HEAP32[S++]=O);let E=p._OrtCreateTensor(la(l),$,_,T,h.length,da(y));E===0&&Fe(`Can't create tensor for input/output. session=${s}, index=${o}.`),t.push(E)}finally{p.stackRestore(C)}},tf=async(e,t,r,s,o,c)=>{let p=Ze(),l=vr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=l[0],y=l[1],$=l[2],_=l[3],C=l[4],T=l[5],S=t.length,E=s.length,O=0,R=[],z=[],M=[],U=[],L=p.stackSave(),F=p.stackAlloc(S*4),te=p.stackAlloc(S*4),J=p.stackAlloc(E*4),oe=p.stackAlloc(E*4);try{[O,R]=fl(c);for(let me=0;meXe*it,1);Ae=Xt(ce);let Dt=_?.outputPreferredLocations[s[me]];if(Ae==="string"){if(Dt==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Xe=[],it=_e/4;for(let mt=0;mt0){let Xe=p.jsepGetBuffer;if(!Xe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let it=Xe(_e),mt=mr(ce);if(mt===void 0||!yn(Ae))throw new Error(`Unsupported data type: ${Ae}`);ve=!0,ue.push([Ae,Qe,{gpuBuffer:it,download:p.jsepCreateDownloader(it,Ye*mt,Ae),dispose:()=>{p._OrtReleaseTensor(Ee)}},"gpu-buffer"])}else{let Xe=gn(Ae),it=new Xe(Ye);new Uint8Array(it.buffer,it.byteOffset,it.byteLength).set(p.HEAPU8.subarray(_e,_e+it.byteLength)),ue.push([Ae,Qe,it,"cpu"])}}finally{p.stackRestore(ke),Ae==="string"&&_e&&p._free(_e),ve||p._OrtReleaseTensor(Ee)}}return _&&!C&&(p._OrtClearBoundOutputs(_.handle),vr.set(e,[h,y,$,_,C,!1])),ue}finally{p.stackRestore(L),z.forEach(le=>p._OrtReleaseTensor(le)),M.forEach(le=>p._OrtReleaseTensor(le)),U.forEach(le=>p._free(le)),O!==0&&p._OrtReleaseRunOptions(O),R.forEach(le=>p._free(le))}},rf=e=>{let t=Ze(),r=vr.get(e);if(!r)throw new Error("invalid session id");let s=r[0],o=t._OrtEndProfiling(s);o===0&&Fe("Can't get an profile file name."),t._OrtFree(o)},nf=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer)}return t}});var of=Nr((vS,Mv)=>{Mv.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 br,Et,Ti,Vn,Gn,Ga,Ha,Fr,qr,Uv,Nn,sf,uf,lf,df,cf,pf,ff,La=ie(()=>{"use strict";Tt();af();Gr();br=()=>!!We.wasm.proxy&&typeof document<"u",Ti=!1,Vn=!1,Gn=!1,Ha=new Map,Fr=(e,t)=>{let r=Ha.get(e);r?r.push(t):Ha.set(e,[t])},qr=()=>{if(Ti||!Vn||Gn||!Et)throw new Error("worker not ready")},Uv=e=>{switch(e.data.type){case"init-wasm":Ti=!1,e.data.err?(Gn=!0,Ga[1](e.data.err)):(Vn=!0,Ga[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ha.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},Nn=typeof document<"u"?document?.currentScript?.src:void 0,sf=async()=>{if(!Vn){if(Ti)throw new Error("multiple calls to 'initWasm()' detected.");if(Gn)throw new Error("previous call to 'initWasm()' failed.");if(Ti=!0,br())return We.wasm.wasmPaths===void 0&&Nn&&Nn.indexOf("blob:")!==0&&(We.wasm.wasmPaths=Nn.substr(0,+Nn.lastIndexOf("/")+1)),new Promise((e,t)=>{Et?.terminate();let r=URL.createObjectURL(new Blob([of()],{type:"text/javascript"}));Et=new Worker(r,{name:"ort-wasm-proxy-worker"}),Et.onerror=o=>t(o),Et.onmessage=Uv,URL.revokeObjectURL(r),Ga=[e,t];let s={type:"init-wasm",in:We};Et.postMessage(s)});try{await pl(We.wasm),await Xp(We),Vn=!0}catch(e){throw Gn=!0,e}finally{Ti=!1}}},uf=async e=>{if(br())return qr(),new Promise((t,r)=>{Fr("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:We}};Et.postMessage(s)});await Zp(We,e)},lf=async e=>br()?(qr(),new Promise((t,r)=>{Fr("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};Et.postMessage(s,[e.buffer])})):Va(e),df=async(e,t)=>{if(br()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return qr(),new Promise((r,s)=>{Fr("create",[r,s]);let o={type:"create",in:{model:e,options:{...t}}},c=[];e instanceof Uint8Array&&c.push(e.buffer),Et.postMessage(o,c)})}else return Jp(e,t)},cf=async e=>{if(br())return qr(),new Promise((t,r)=>{Fr("release",[t,r]);let s={type:"release",in:e};Et.postMessage(s)});ef(e)},pf=async(e,t,r,s,o,c)=>{if(br()){if(r.some(p=>p[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(p=>p))throw new Error("pre-allocated output tensor is not supported for proxy.");return qr(),new Promise((p,l)=>{Fr("run",[p,l]);let h=r,y={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:s,options:c}};Et.postMessage(y,nf(h))})}else return tf(e,t,r,s,o,c)},ff=async e=>{if(br())return qr(),new Promise((t,r)=>{Fr("end-profiling",[t,r]);let s={type:"end-profiling",in:e};Et.postMessage(s)});rf(e)}});var mf,Wv,Hn,hf=ie(()=>{"use strict";Tt();La();Te();ca();mf=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Wv=e=>{switch(e[3]){case"cpu":return new st(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!yn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:o}=e[2];return st.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Hn=class{async fetchModelAndCopyToWasmMemory(t){return lf(await $i(t))}async loadModel(t,r){Ct();let s;typeof t=="string"?typeof process<"u"&&process.versions&&process.versions.node?s=await $i(t):s=await this.fetchModelAndCopyToWasmMemory(t):s=t,[this.sessionId,this.inputNames,this.outputNames]=await df(s,r),ht()}async dispose(){return cf(this.sessionId)}async run(t,r,s){Ct();let o=[],c=[];Object.entries(t).forEach(C=>{let T=C[0],S=C[1],E=this.inputNames.indexOf(T);if(E===-1)throw new Error(`invalid input '${T}'`);o.push(S),c.push(E)});let p=[],l=[];Object.entries(r).forEach(C=>{let T=C[0],S=C[1],E=this.outputNames.indexOf(T);if(E===-1)throw new Error(`invalid output '${T}'`);p.push(S),l.push(E)});let h=o.map((C,T)=>mf(C,()=>`input "${this.inputNames[c[T]]}"`)),y=p.map((C,T)=>C?mf(C,()=>`output "${this.outputNames[l[T]]}"`):null),$=await pf(this.sessionId,c,h,l,y,s),_={};for(let C=0;C<$.length;C++)_[this.outputNames[l[C]]]=p[C]??Wv($[C]);return ht(),_}startProfiling(){}endProfiling(){ff(this.sessionId)}}});var Nv,Ln,gf=ie(()=>{"use strict";Tt();La();hf();Nv=()=>{if((typeof We.wasm.initTimeout!="number"||We.wasm.initTimeout<0)&&(We.wasm.initTimeout=0),typeof We.wasm.simd!="boolean"&&(We.wasm.simd=!0),typeof We.wasm.proxy!="boolean"&&(We.wasm.proxy=!1),typeof We.wasm.trace!="boolean"&&(We.wasm.trace=!1),typeof We.wasm.numThreads!="number"||!Number.isInteger(We.wasm.numThreads)||We.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(We.wasm.numThreads=1);let e=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;We.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Ln=class{async init(t){Nv(),await sf(),await uf(t)}async createInferenceSessionHandler(t,r){let s=new Hn;return await s.loadModel(t,r),Promise.resolve(s)}}});var yf={};Vr(yf,{wasmBackend:()=>Vv});var Vv,vf=ie(()=>{"use strict";gf();Vv=new Ln});Tt();Tt();Tt();var Xu="1.18.0";var WS=ra;{let e=(vf(),Qt(yf)).wasmBackend;pr("webgpu",e,5),pr("webnn",e,5),pr("cpu",e,10),pr("wasm",e,10)}Object.defineProperty(We.versions,"web",{value:Xu,enumerable:!0});export{Bg as InferenceSession,ln as TRACE,Ct as TRACE_FUNC_BEGIN,ht as TRACE_FUNC_END,st as Tensor,Mg as TrainingSession,WS as default,We as env,pr 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. * ============================================================================= */ //# sourceMappingURL=ort.webgpu.min.js.map